just follow spec

This commit is contained in:
Ryan Oldenburg 2022-05-25 23:18:22 -05:00
parent 0c075e6774
commit 43b776bb94

View file

@ -544,19 +544,16 @@ proc readBits(state: var DecoderState, n: int): int =
state.bitBuffer = k and (not bitMasks[n]) state.bitBuffer = k and (not bitMasks[n])
state.bitsBuffered -= n state.bitsBuffered -= n
proc getBitsAsSignedInt(state: var DecoderState, n: int): int = proc receiveExtend(state: var DecoderState, n: int): int =
## Get n number of bits as a signed integer. ## Get n number of bits as a signed integer. See Jpeg spec pages 109 and 114
# TODO: Investigate why 15 not 16? ## for EXTEND and RECEIVE.
if n notin 0 .. 15: var
failInvalid() v = state.readBits(n)
if state.bitsBuffered < n: vt = (1 shl (n - 1))
state.fillBitBuffer() if v < vt:
let vt = (-1 shl n) + 1
sign = cast[int32](state.bitBuffer) shr 31 # Sign is always in MSB v = v + vt
k = lrot(state.bitBuffer, n) return v
result = (k and bitMasks[n]).int + (biases[n] and (not sign))
state.bitBuffer = k and (not bitMasks[n])
state.bitsBuffered -= n
proc decodeRegularBlock( proc decodeRegularBlock(
state: var DecoderState, component: int, data: var array[64, int16] state: var DecoderState, component: int, data: var array[64, int16]
@ -570,7 +567,7 @@ proc decodeRegularBlock(
if t == 0: if t == 0:
0 0
else: else:
state.getBitsAsSignedInt(t) state.receiveExtend(t)
dc = state.components[component].dcPred + diff dc = state.components[component].dcPred + diff
state.components[component].dcPred = dc state.components[component].dcPred = dc
data[0] = cast[int16](dc) data[0] = cast[int16](dc)
@ -590,7 +587,7 @@ proc decodeRegularBlock(
if i >= 64: if i >= 64:
failInvalid() failInvalid()
let zig = deZigZag[i] let zig = deZigZag[i]
data[zig] = cast[int16](state.getBitsAsSignedInt(s.int)) data[zig] = cast[int16](state.receiveExtend(s.int))
inc i inc i
proc decodeProgressiveBlock( proc decodeProgressiveBlock(
@ -607,7 +604,7 @@ proc decodeProgressiveBlock(
let let
diff = diff =
if t > 0: if t > 0:
state.getBitsAsSignedInt(t) state.receiveExtend(t)
else: else:
0 0
dc = state.components[component].dcPred + diff dc = state.components[component].dcPred + diff
@ -653,7 +650,7 @@ proc decodeProgressiveContinuationBlock(
inc k inc k
if s >= 15: if s >= 15:
failInvalid() failInvalid()
data[zig] = cast[int16](state.getBitsAsSignedInt(s.int) * (1 shl shift)) data[zig] = cast[int16](state.receiveExtend(s.int) * (1 shl shift))
else: else:
var bit = 1 shl state.successiveApproxLow var bit = 1 shl state.successiveApproxLow