Files
rosetta/src/Formats/codecs/video/Mpeg2/Decoder.luau
T

1530 lines
44 KiB
Luau

--!strict
--!native
-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws).
-- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame
-- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion
-- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11;
-- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser
-- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported:
-- 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
--
-- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js
-- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion
-- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int),
-- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid
-- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2
-- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are
-- clamped (ffmpeg skips the prediction): both only matter for corrupt data.
--
-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture.
-- Every read position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock),
-- motion vectors are clamped to the reference picture, and bad data ends the slice instead of raising.
local V = require("@formats/codecs/video/Mpeg2/Vlc")
local T = require("@formats/codecs/video/Mpeg2/Tables")
local Dsp = require("@formats/codecs/video/Dsp")
local readu8 = buffer.readu8
local writeu8 = buffer.writeu8
local readu32 = buffer.readu32
local writeu32 = buffer.writeu32
local readi32 = buffer.readi32
local writei32 = buffer.writei32
local band = bit32.band
local bor = bit32.bor
local bxor = bit32.bxor
local lshift = bit32.lshift
local rshift = bit32.rshift
local bswap = bit32.byteswap
local idct = Dsp.idct
local fillBlock = Dsp.fill
local mc = Dsp.mc
local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2 KB, the pos check runs per macroblock
local D = {}
D.PICTURE_I = 1
D.PICTURE_P = 2
D.PICTURE_B = 3
-- scan index -> natural position (zigzag, alternate); default matrices in natural order
local ZZ = buffer.create(64)
local ALT = buffer.create(64)
local DEF_INTRA = buffer.create(64)
local DEF_NON_INTRA = buffer.create(64)
for i = 0, 63 do
buffer.writeu8(ZZ, i, T.ZIG_ZAG[i])
buffer.writeu8(ALT, i, T.ALTERNATE_SCAN[i])
buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[i])
buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[i])
end
local NON_LINEAR = buffer.create(32)
for i = 0, 31 do
buffer.writeu8(NON_LINEAR, i, T.NON_LINEAR_QSCALE[i])
end
local COFF = 40000
local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS
local CBP, CBP_BITS = V.CBP, V.CBP_BITS
local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS
local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS
local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS
local DCT_FIRST, DCT_NEXT, DCT_B15 = V.DCT_FIRST, V.DCT_NEXT, V.DCT_B15
local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB
local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B }
local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS }
-- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr -
-- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256)
-- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest.
-- the constant terms, plus COFF * 256 so the sums stay positive for rshift
local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128
local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160
local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72
-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path
local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer)
-- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four
local chw = cw // 2
local w2 = w // 2 -- whole pixel pairs per row
local stride = w * 4
for y = 0, h - 1, 2 do
local yo = y * cw
local co = (y // 2) * chw
local o = y * stride
local two = y + 1 < h
for _ = 1, w2 do
local cb, cr = readu8(Cb, co), readu8(Cr, co)
co += 1
local rr = cr * 409 + RBIAS
local gg = GBIAS - cb * 100 - cr * 208
local bb = cb * 516 + BBIAS
local yv = readu8(Y, yo) * 298
writeu32(out, o, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000)
yv = readu8(Y, yo + 1) * 298
writeu32(out, o + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000)
if two then
yv = readu8(Y, yo + cw) * 298
writeu32(out, o + stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000)
yv = readu8(Y, yo + cw + 1) * 298
writeu32(out, o + stride + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000)
end
yo += 2
o += 8
end
if w % 2 == 1 then
-- the last column of an odd width
local cb, cr = readu8(Cb, co), readu8(Cr, co)
local rr = cr * 409 + RBIAS
local gg = GBIAS - cb * 100 - cr * 208
local bb = cb * 516 + BBIAS
for k = 0, if two then 1 else 0 do
local yv = readu8(Y, yo + k * cw) * 298
writeu32(out, o + k * stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000)
end
end
end
end
D.toRgba = toRgba
-- YCbCr 4:2:2 planes -> RGBA8: chroma row y for luma row y, chroma column x // 2
local function toRgba422(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer)
local chw = cw // 2
for y = 0, h - 1 do
local o = y * w * 4
for x = 0, w - 1 do
local c = y * chw + x // 2
local cb, cr = readu8(Cb, c), readu8(Cr, c)
local yv = readu8(Y, y * cw + x) * 298
local r = math.clamp(rshift(yv + cr * 409 + RBIAS, 8) - COFF, 0, 255)
local g = math.clamp(rshift(yv + GBIAS - cb * 100 - cr * 208, 8) - COFF, 0, 255)
local b = math.clamp(rshift(yv + cb * 516 + BBIAS, 8) - COFF, 0, 255)
writeu32(out, o + x * 4, r + g * 256 + b * 65536 + 0xFF000000)
end
end
end
D.toRgba422 = toRgba422
export type Store = {
y: buffer,
cb: buffer,
cr: buffer,
w: number,
h: number,
cw: number, -- luma stride (coded width); chroma stride cw / 2
chroma: number, -- 1 = 4:2:0, 2 = 4:2:2
tref: number,
ptype: number,
tag: any,
mpeg2: boolean,
progressive: boolean, -- progressive_frame (MPEG-1: true)
fields: boolean, -- coded as two field pictures
tff: boolean, -- top_field_first
rff: boolean, -- repeat_first_field
clamped: number, -- predictions from outside the reference (edge-emulated) in the last picture decoded into it
concealed: { [number]: boolean }, -- macroblock rows (of the frame) with macroblocks no slice covered (concealed)
}
export type Core = {
-- data
write: (src: buffer, off: number, n: number) -> (),
-- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when
-- no picture is complete or it could not be decoded), and whether more data is needed. A frame coded as two field
-- pictures comes back once, after its second field.
nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean),
toRgba: (s: Store, out: buffer) -> (),
reset: () -> (),
state: {
width: number,
height: number,
codedWidth: number,
codedHeight: number,
frameRate: number,
aspect: number,
bitRate: number,
mpeg2: boolean,
chroma: number,
progressive: boolean, -- progressive_sequence
profileLevel: number,
sizeChanged: boolean,
pictures: number,
errors: number,
skipped: number,
clamped: number, -- motion vectors pointing outside the reference (clamped)
maxPixels: number,
refOld: Store?,
refNew: Store?,
},
}
function D.new(maxPixels: number?): Core
local state = {
width = 0,
height = 0,
codedWidth = 0,
codedHeight = 0,
frameRate = 0,
aspect = 0,
bitRate = 0,
mpeg2 = false,
chroma = 1,
progressive = true,
profileLevel = 0,
sizeChanged = false,
pictures = 0,
errors = 0,
skipped = 0,
clamped = 0,
maxPixels = maxPixels or 4096 * 2304,
refOld = nil :: Store?,
refNew = nil :: Store?,
}
-- bitstream
local data = buffer.create(64 * 1024 + PAD)
local dataLen = 0
local readByte = 0 -- next byte to look at for a start code
local scanPos = 0 -- resume point of the picture-end scan
local pos = 0 -- bit position inside data
local err = false
-- sequence
local hasSeq = false
local mpeg2 = false
local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2
local progSeq = true
local mbW, mbH = 0, 0 -- frame size in macroblocks
local cw, chw = 0, 0 -- luma / chroma strides (coded widths)
local lumaH, chromaH = 0, 0 -- plane heights (coded)
local intraQ = buffer.create(64) -- natural order
local nonIntraQ = buffer.create(64)
local chromaIntraQ = buffer.create(64)
local chromaNonIntraQ = buffer.create(64)
buffer.copy(intraQ, 0, DEF_INTRA, 0, 64)
buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64)
buffer.copy(chromaIntraQ, 0, DEF_INTRA, 0, 64)
buffer.copy(chromaNonIntraQ, 0, DEF_NON_INTRA, 0, 64)
local stores: { Store } = {}
local bStore: Store? = nil
-- the sequence header's values, applied (and the stores allocated) once its extension has been seen
local seqW, seqH = 0, 0
-- picture
local ptype = 0
local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t]
local fullPelFw, fullPelBw = false, false
local dcPrec = 0
local picStruct = 3 -- 1 top field, 2 bottom field, 3 frame
local fpfd = true -- frame_pred_frame_dct
local concealMv = false
local qScaleType = 0
local intraVlc = false
local scan = ZZ
local tff, rff, progFrame = true, false, true
local fieldPic = false
local secondField = false
local parity = 0 -- the current field (0 top, 1 bottom)
local mbRows, mbSize = 0, 0 -- of the current picture (field pictures: half the frame's rows)
local lstride, lbase, cstride, cbase = 0, 0, 0, 0 -- plane addressing of the current picture
local cur: Store? = nil
local curY, curCb, curCr = data, data, data
local fwS: Store? = nil
local bwS: Store? = nil
local pending: Store? = nil -- a first field waiting for its second
local pendingStruct = 0
local pendingFw: Store? = nil
local pendingBw: Store? = nil
-- slice / macroblock
local qscale = 2
local mbAddr, mbRow, mbCol = 0, 0, 0
local dcY, dcCb, dcCr = 128, 128, 128
local mbIntra = false
local motFw, motBw = false, false
local motionType = 1 -- 1 frame (field pictures: field 16x16), 2 field (frame pictures), 3 16x8, 4 dual prime
local dctType = 0
-- vectors: MV[(d * 4 + k) * 2 + c + 1] (direction d, vector k: 0 / 1 the two fields or halves, 2 / 3 dual-prime
-- opposite-parity vectors; component c); PMV[(d * 2 + r) * 2 + c + 1]; FSEL[d * 2 + r + 1]
local MV = table.create(16, 0)
local PMV = table.create(8, 0)
local FSEL = table.create(4, 0)
local blk = buffer.create(256)
local function peek32(): number
local bp = rshift(pos, 3)
local w = bswap(readu32(data, bp))
local s = band(pos, 7)
if s ~= 0 then
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
end
return w
end
local function read(n: number): number
local v = rshift(peek32(), 32 - n)
pos += n
return v
end
local function vlc(lut: buffer, k: number): number
local e = readu32(lut, rshift(peek32(), 32 - k) * 4)
local l = rshift(e, 16)
if l == 0 then
err = true
return 0
end
pos += l
return band(e, 0xFFFF) - 32768
end
-- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1
local function findStart(from: number, to: number): number
local i = from
while i + 3 < to do
local c = readu8(data, i + 2)
if c > 1 then
i += 3
elseif c == 1 then
if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then
return i
end
i += 3
else
i += 1
end
end
return -1
end
local function newStore(): Store
local y = buffer.create(cw * lumaH)
local cb = buffer.create(chw * chromaH)
local cr = buffer.create(chw * chromaH)
buffer.fill(y, 0, 16) -- black until a picture is decoded into it
buffer.fill(cb, 0, 128)
buffer.fill(cr, 0, 128)
return {
y = y,
cb = cb,
cr = cr,
w = state.width,
h = state.height,
cw = cw,
chroma = chroma,
tref = 0,
ptype = 0,
tag = nil,
mpeg2 = mpeg2,
progressive = true,
fields = false,
tff = true,
rff = false,
clamped = 0,
concealed = {},
}
end
local function loadMatrix(q: buffer)
for i = 0, 63 do
local v = read(8)
writeu8(q, readu8(ZZ, i), if v == 0 then 1 else v)
end
end
-- the sequence (header + extension) takes effect: sizes and stores
local function applySequence(): boolean
local w, h = seqW, seqH
if w == 0 or h == 0 or w * h > state.maxPixels then
return false
end
local mh = if mpeg2 and not progSeq then 2 * ((h + 31) // 32) else (h + 15) // 16
if w ~= state.width or h ~= state.height or mh ~= mbH or chroma ~= state.chroma or mpeg2 ~= state.mpeg2 then
state.width = w
state.height = h
state.chroma = chroma
state.mpeg2 = mpeg2
mbW = (w + 15) // 16
mbH = mh
cw = mbW * 16
chw = mbW * 8
lumaH = mbH * 16
chromaH = if chroma == 2 then lumaH else lumaH // 2
state.codedWidth = cw
state.codedHeight = lumaH
stores = { newStore(), newStore() }
bStore = newStore()
state.refOld = nil
state.refNew = nil
pending = nil
state.sizeChanged = true
end
state.progressive = progSeq
hasSeq = true
return true
end
-- sequence header at byte p (after the start code); false when invalid
local function sequenceHeader(p: number): boolean
pos = p * 8
local w = read(12)
local h = read(12)
local aspect = read(4)
local rate = read(4)
local bitRate = read(18)
pos += 1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag
if read(1) == 1 then
loadMatrix(intraQ)
else
buffer.copy(intraQ, 0, DEF_INTRA, 0, 64)
end
if read(1) == 1 then
loadMatrix(nonIntraQ)
else
buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64)
end
buffer.copy(chromaIntraQ, 0, intraQ, 0, 64)
buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64)
state.frameRate = T.PICTURE_RATE[rate] or 0
state.aspect = aspect
state.bitRate = bitRate * 400
seqW, seqH = w, h
mpeg2 = false -- until a sequence extension follows
chroma = 1
progSeq = true
return w > 0 and h > 0
end
local function sequenceExtension()
state.profileLevel = read(8)
progSeq = read(1) == 1
local cf = read(2)
seqW += lshift(read(2), 12)
seqH += lshift(read(2), 12)
state.bitRate += lshift(read(12), 18) * 400
pos += 1 + 8 + 1 -- marker, vbv_buffer_size_extension, low_delay
local n = read(2)
local d = read(5)
state.frameRate = state.frameRate * (n + 1) / (d + 1)
mpeg2 = true
chroma = if cf == 2 then 2 else 1 -- 4:4:4 (3) is not supported: decoded as 4:2:0 (wrong but safe)
if cf == 3 then
state.errors += 1
end
end
local function quantMatrixExtension()
if read(1) == 1 then
loadMatrix(intraQ)
buffer.copy(chromaIntraQ, 0, intraQ, 0, 64)
end
if read(1) == 1 then
loadMatrix(nonIntraQ)
buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64)
end
if read(1) == 1 then
loadMatrix(chromaIntraQ)
end
if read(1) == 1 then
loadMatrix(chromaNonIntraQ)
end
end
local function fcode(v: number): number
return if v < 1 or v > 9 then 1 else v
end
local function pictureCodingExtension()
fc00, fc01, fc10, fc11 = fcode(read(4)), fcode(read(4)), fcode(read(4)), fcode(read(4))
dcPrec = read(2)
picStruct = read(2)
tff = read(1) == 1
fpfd = read(1) == 1
concealMv = read(1) == 1
qScaleType = read(1)
intraVlc = read(1) == 1
scan = if read(1) == 1 then ALT else ZZ
rff = read(1) == 1
pos += 1 -- chroma_420_type
progFrame = read(1) == 1
if picStruct == 0 then
picStruct = 3
err = true
end
end
-- an extension (00 00 01 B5) at byte p
local function extension(p: number)
pos = p * 8
local id = read(4)
if id == 1 then
sequenceExtension()
elseif id == 3 then
quantMatrixExtension()
elseif id == 8 then
pictureCodingExtension()
end
end
local function decodeMotion(f: number, pred: number): number
local code = vlc(MOTION, MOTION_BITS)
local d = code
local rsize = f - 1
if code ~= 0 and rsize > 0 then
local r = read(rsize)
d = lshift(math.abs(code) - 1, rsize) + r + 1
if code < 0 then
d = -d
end
end
local range = lshift(16, rsize)
return (pred + d + range) % (2 * range) - range
end
-- ------------------------------------------------------------------------------------------------ prediction
-- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0:
-- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the
-- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the
-- first prediction.
local EDGE = buffer.create(Dsp.EDGE_SIZE)
local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean)
local stride, sb, db, ph = cw, 0, 0, lumaH
local cs, csb, cdb = chw, 0, 0
if sp >= 0 then
stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2
cs, csb, cdb = 2 * chw, sp * chw, dp * chw
end
-- luma
local hx, hy = band(mvx, 1), band(mvy, 1)
local sx = mbCol * 16 + (mvx - hx) // 2
local sy = rowY + (mvy - hy) // 2
local dOff = db + rowY * stride + mbCol * 16
if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + h + hy > ph then
-- outside the reference (invalid in MPEG; ffmpeg's encoder writes such half-sample vectors at the right /
-- bottom edge): predicted from repeated edge samples, as the encoder meant (ffmpeg's decoder skips it)
Dsp.edge(rY, stride, sb, sx, sy, 16, h, cw, ph, EDGE)
mc(EDGE, 32, 0, curY, stride, dOff, 16, h, hx, hy, avg)
state.clamped += 1;
(cur :: Store).clamped += 1
else
mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg)
end
-- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0
local mx = mvx // 2
if mvx < 0 then
mx = -((-mvx) // 2)
end
local cx, cy, chh, cph, chx, chy
chx = band(mx, 1)
cx = mbCol * 8 + (mx - chx) // 2
if chroma == 1 then
local my = mvy // 2
if mvy < 0 then
my = -((-mvy) // 2)
end
chy = band(my, 1)
cy = rowY // 2 + (my - chy) // 2
chh, cph = h // 2, ph // 2
else
chy = band(mvy, 1)
cy = rowY + (mvy - chy) // 2
chh, cph = h, ph
end
local crow = rowY
if chroma == 1 then
crow = rowY // 2
end
local cdOff = cdb + crow * cs + mbCol * 8
if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then
Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE)
mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg)
Dsp.edge(rCr, cs, csb, cx, cy, 8, chh, chw, cph, EDGE)
mc(EDGE, 32, 0, curCr, cs, cdOff, 8, chh, chx, chy, avg)
else
local so = csb + cy * cs + cx
mc(rCb, cs, so, curCb, cs, cdOff, 8, chh, chx, chy, avg)
mc(rCr, cs, so, curCr, cs, cdOff, 8, chh, chx, chy, avg)
end
end
-- the reference frame for field fs of direction d in a field picture: the second field of a P frame takes the
-- opposite parity from its own first field
local function fieldRef(d: number, fs: number): Store
if d == 0 then
if secondField and ptype == 2 and fs ~= parity then
return cur :: Store
end
return (fwS or cur) :: Store
end
return (bwS or cur) :: Store
end
-- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock
local function predictDir(d: number, avg: boolean)
local o = d * 8
if not fieldPic then
local r = bwS
if d == 0 then
r = fwS
end
if r == nil then
r = cur
end
local ref = r :: Store
local ry, rcb, rcr = ref.y, ref.cb, ref.cr
if motionType == 1 then
mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg)
elseif motionType == 2 then
mcPart(ry, rcb, rcr, FSEL[d * 2 + 1], 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg)
mcPart(ry, rcb, rcr, FSEL[d * 2 + 2], 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg)
else -- dual prime: each field from the same parity (MV 0 / 1), averaged with the opposite parity (MV 2 / 3)
mcPart(ry, rcb, rcr, 0, 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg)
mcPart(ry, rcb, rcr, 1, 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg)
mcPart(ry, rcb, rcr, 1, 0, mbRow * 8, 8, MV[o + 5], MV[o + 6], true)
mcPart(ry, rcb, rcr, 0, 1, mbRow * 8, 8, MV[o + 7], MV[o + 8], true)
end
return
end
if motionType == 1 then
local fs = FSEL[d * 2 + 1]
local r = fieldRef(d, fs)
mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg)
elseif motionType == 3 then
for k = 0, 1 do
local fs = FSEL[d * 2 + k + 1]
local r = fieldRef(d, fs)
mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16 + k * 8, 8, MV[o + k * 2 + 1], MV[o + k * 2 + 2], avg)
end
else -- dual prime: same parity, then the opposite one (the first field of this frame for a second field)
local r = (fwS or cur) :: Store
mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg)
local q = if secondField then cur :: Store else r
mcPart(q.y, q.cb, q.cr, 1 - parity, parity, mbRow * 16, 16, MV[o + 5], MV[o + 6], true)
end
end
-- the prediction of a non-intra macroblock from the current motion state
local function predictMb()
if ptype == 2 then
predictDir(0, false)
elseif motFw then
predictDir(0, false)
if motBw then
predictDir(1, true)
end
elseif motBw then
predictDir(1, false)
end
end
local function resetPmv()
for i = 1, 8 do
PMV[i] = 0
end
end
-- a skipped macroblock's motion (13818-2 7.6.6): P a zero vector (field pictures: from the same parity); B the
-- previous macroblock's directions with its first vectors as frame (or same-parity field) prediction
local function skipMotion()
motionType = 1
FSEL[1], FSEL[3] = parity, parity
if ptype == 2 then
resetPmv()
MV[1], MV[2] = 0, 0
else
MV[1], MV[2] = PMV[1], PMV[2]
MV[9], MV[10] = PMV[5], PMV[6]
end
end
-- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1
-- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do
-- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock
-- before the gap.
local covered = 0
local gapFw, gapBw = false, false
local GAP = table.create(16, 0)
local gapType = 1
local hasRef = false
local SAVE = table.create(16, 0)
local function conceal(from: number, to: number)
if from > to or not hasRef then
return
end
local sFw, sBw, sType = motFw, motBw, motionType
table.move(MV, 1, 16, 1, SAVE)
local f1, f2, f3, f4 = FSEL[1], FSEL[2], FSEL[3], FSEL[4]
if ptype == 3 and mpeg2 then
-- both references, zero vectors (ffmpeg's error concealment of B macroblocks, without its deblocking)
motFw, motBw, motionType = true, true, 1
MV[1], MV[2], MV[9], MV[10] = 0, 0, 0, 0
elseif ptype == 3 then
motFw, motBw, motionType = gapFw, gapBw, gapType
table.move(GAP, 1, 16, 1, MV)
if not motFw and not motBw then
motFw = true
motionType = 1
MV[1], MV[2] = 0, 0
end
else
motionType = 1
if not (ptype == 2 and gapFw) then
MV[1], MV[2] = 0, 0
else
MV[1], MV[2] = GAP[1], GAP[2]
end
end
FSEL[1], FSEL[2], FSEL[3], FSEL[4] = parity, parity, parity, parity
local pt = ptype
if pt == 1 then
ptype = 2 -- a damaged I picture: copy the previous reference
end
local c = (cur :: Store).concealed
for a = from, to do
mbRow = a // mbW
mbCol = a % mbW
predictMb()
if fieldPic then
c[mbRow * 2] = true
c[mbRow * 2 + 1] = true
else
c[mbRow] = true
end
end
ptype = pt
motFw, motBw, motionType = sFw, sBw, sType
table.move(SAVE, 1, 16, 1, MV)
FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4
end
-- ------------------------------------------------------------------------------------------------ blocks
-- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture.
-- False on a bitstream error.
local function decodeBlock(b: number): boolean
local n = 0
local q: buffer
local onlyDc = true
local luma = b < 4
local parityOdd = 1 -- MPEG-2 mismatch control: 1 while the coefficient sum is even
if mbIntra then
local dc
local size
if luma then
size = vlc(DC_LUMA, DC_LUMA_BITS)
dc = dcY
else
size = vlc(DC_CHROMA, DC_CHROMA_BITS)
dc = dcCr
if b % 2 == 0 then
dc = dcCb
end
end
if size > 0 then
local diff = read(size)
if band(diff, lshift(1, size - 1)) == 0 then
diff = diff + 1 - lshift(1, size)
end
dc += diff
end
if err then
return false
end
local top = lshift(256, dcPrec) - 1
if dc < 0 or dc > top then
dc = if dc < 0 then 0 else top -- corrupt data: clamped, which also bounds the IDCT input
end
if luma then
dcY = dc
elseif b % 2 == 0 then
dcCb = dc
else
dcCr = dc
end
local v = lshift(dc, 3 - dcPrec)
writei32(blk, 0, v)
parityOdd = bxor(1, band(v, 1))
q = chromaIntraQ
if luma then
q = intraQ
end
n = 1
else
q = chromaNonIntraQ
if luma then
q = nonIntraQ
end
end
local lut, nextLut = DCT_NEXT, DCT_NEXT
if mbIntra and intraVlc then
lut, nextLut = DCT_B15, DCT_B15
elseif n == 0 then
lut = DCT_FIRST
end
local intra = mbIntra
local qs = qscale
local m2 = mpeg2
while true do
-- inline peek
local bp = rshift(pos, 3)
local w = bswap(readu32(data, bp))
local s = band(pos, 7)
if s ~= 0 then
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
end
local e = readu32(lut, rshift(w, 24) * 4)
if e >= SUB then
e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4)
end
local l = rshift(e, 16)
if l == 0 then
err = true
return false
end
local v = band(e, 0xFFFF)
lut = nextLut
if v == EOB then
pos += l
break
end
local run, level, neg
if v == ESC then
pos += l
run = read(6)
if m2 then
-- a 12-bit signed level
level = read(12)
if level >= 2048 then
level -= 4096
end
else
-- an 8-bit level or 0x00 / 0x80 and 8 more bits
level = read(8)
if level == 0 then
level = read(8)
elseif level == 128 then
level = read(8) - 256
elseif level > 128 then
level -= 256
end
end
neg = level < 0
if neg then
level = -level
end
if level == 0 then
err = true
return false
end
else
run = rshift(v, 8)
level = band(v, 255)
neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code
pos += l + 1
end
n += run
if n > 63 then
err = true
return false
end
local zz = readu8(scan, n)
-- dequantise the magnitude (ffmpeg's arithmetic); MPEG-1 makes it odd toward zero
local m
if intra then
m = (level * qs * readu8(q, zz)) // 16
else
m = ((level * 2 + 1) * qs * readu8(q, zz)) // 32
end
if not m2 then
if m == 0 then
m = -1
elseif band(m, 1) == 0 then
m -= 1
end
end
if neg then
m = -m
end
if m2 then
parityOdd = bxor(parityOdd, band(m, 1))
end
-- saturate
if m > 2047 then
m = 2047
elseif m < -2048 then
m = -2048
end
if zz ~= 0 then
onlyDc = false
end
writei32(blk, zz * 4, m)
n += 1
end
if m2 and parityOdd == 1 then
-- mismatch control: toggle the last coefficient's lowest bit
local v = readi32(blk, 252)
writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1)
onlyDc = false
end
-- reconstruction
local dst, off, stride
if luma then
dst = curY
if fieldPic then
stride = lstride
off = lbase + (mbRow * 16 + (if b >= 2 then 8 else 0)) * stride + mbCol * 16 + (if b % 2 == 1 then 8 else 0)
elseif dctType == 1 then
stride = 2 * cw
off = (mbRow * 16 + (if b >= 2 then 1 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0)
else
stride = cw
off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0)
end
else
dst = curCr
if b % 2 == 0 then
dst = curCb
end
local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock
if chroma == 1 then
stride = cstride
off = cbase + mbRow * 8 * stride + mbCol * 8
elseif fieldPic then
stride = cstride
off = cbase + (mbRow * 16 + k * 8) * stride + mbCol * 8
elseif dctType == 1 then
stride = 2 * chw
off = (mbRow * 16 + k) * chw + mbCol * 8
else
stride = chw
off = (mbRow * 16 + k * 8) * chw + mbCol * 8
end
end
if onlyDc then
fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra)
writei32(blk, 0, 0)
else
idct(blk, dst, off, stride, not intra)
buffer.fill(blk, 0, 0, 256)
end
return true
end
-- ------------------------------------------------------------------------------------------------ macroblocks
local function getQscale(code: number): number
if qScaleType == 1 then
return readu8(NON_LINEAR, code)
end
return code * 2
end
-- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled)
local function motionVectors(d: number)
local fh, fv = fc10, fc11
if d == 0 then
fh, fv = fc00, fc01
end
local o, p, f = d * 8, d * 4, d * 2
if motionType == 1 and not fieldPic then
local x = decodeMotion(fh, PMV[p + 1])
local y = decodeMotion(fv, PMV[p + 2])
PMV[p + 1], PMV[p + 3] = x, x
PMV[p + 2], PMV[p + 4] = y, y
if (d == 0 and fullPelFw) or (d == 1 and fullPelBw) then
x *= 2
y *= 2
end
MV[o + 1], MV[o + 2] = x, y
elseif motionType == 2 then
-- field prediction in a frame picture: vertical predictors in frame units
for r = 0, 1 do
FSEL[f + r + 1] = read(1)
local x = decodeMotion(fh, PMV[p + r * 2 + 1])
local y = decodeMotion(fv, PMV[p + r * 2 + 2] // 2)
PMV[p + r * 2 + 1] = x
PMV[p + r * 2 + 2] = y * 2
MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y
end
elseif motionType == 1 then
-- field picture, 16x16
FSEL[f + 1] = read(1)
local x = decodeMotion(fh, PMV[p + 1])
local y = decodeMotion(fv, PMV[p + 2])
PMV[p + 1], PMV[p + 3] = x, x
PMV[p + 2], PMV[p + 4] = y, y
MV[o + 1], MV[o + 2] = x, y
elseif motionType == 3 then
-- 16x8 (field pictures)
for r = 0, 1 do
FSEL[f + r + 1] = read(1)
local x = decodeMotion(fh, PMV[p + r * 2 + 1])
local y = decodeMotion(fv, PMV[p + r * 2 + 2])
PMV[p + r * 2 + 1], PMV[p + r * 2 + 2] = x, y
MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y
end
else
-- dual prime
local shift = if fieldPic then 0 else 1
local x = decodeMotion(fh, PMV[p + 1])
local dmx = if read(1) == 1 then 1 - 2 * read(1) else 0
local y = decodeMotion(fv, if shift == 1 then PMV[p + 2] // 2 else PMV[p + 2])
local dmy = if read(1) == 1 then 1 - 2 * read(1) else 0
PMV[p + 1], PMV[p + 3] = x, x
PMV[p + 2], PMV[p + 4] = y * (shift + 1), y * (shift + 1)
MV[o + 1], MV[o + 2], MV[o + 3], MV[o + 4] = x, y, x, y
-- the opposite-parity vectors: scaled by the field distance, rounded away from zero
local xp, yp = if x > 0 then 1 else 0, if y > 0 then 1 else 0
if not fieldPic then
local m = if tff then 1 else 3
MV[o + 5] = (x * m + xp) // 2 + dmx
MV[o + 6] = (y * m + yp) // 2 + dmy - 1
m = 4 - m
MV[o + 7] = (x * m + xp) // 2 + dmx
MV[o + 8] = (y * m + yp) // 2 + dmy + 1
else
MV[o + 5] = (x + xp) // 2 + dmx
MV[o + 6] = (y + yp) // 2 + dmy + (if parity == 0 then -1 else 1)
end
end
end
-- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data.
local function decodeMacroblock(first: boolean, endBits: number): boolean
local inc = 0
local t = vlc(MBAI, MBAI_BITS)
while t == 34 and not err and pos < endBits do -- stuffing
t = vlc(MBAI, MBAI_BITS)
end
while t == 35 and not err and pos < endBits do -- escape
inc += 33
t = vlc(MBAI, MBAI_BITS)
end
if err or t < 1 or t > 33 then
err = true
return false
end
inc += t
if first then
mbAddr += inc
if mbAddr > covered and mbAddr <= mbSize then
conceal(covered, mbAddr - 1)
end
else
if mbAddr + inc >= mbSize then
err = true
return false
end
if inc > 1 then
if ptype == 1 then
err = true -- no skipped macroblocks in I pictures
return false
end
dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec)
skipMotion()
for _ = 2, inc do
mbAddr += 1
mbRow = mbAddr // mbW
mbCol = mbAddr % mbW
predictMb()
end
end
mbAddr += 1
end
if mbAddr < 0 or mbAddr >= mbSize then
err = true
return false
end
mbRow = mbAddr // mbW
mbCol = mbAddr % mbW
covered = mbAddr + 1
local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype])
if err then
return false
end
mbIntra = band(mt, 1) ~= 0
local pattern = band(mt, 2) ~= 0
local fw = band(mt, 8) ~= 0
local bw = band(mt, 4) ~= 0
dctType = 0
if mpeg2 then
if mbIntra or not (fw or bw) then
motionType = 1
if not fieldPic and not fpfd and (mbIntra or pattern) then
dctType = read(1)
end
else
if not fieldPic and fpfd then
motionType = 1
else
local mtc = read(2)
if fieldPic then
motionType = if mtc == 1 then 1 elseif mtc == 2 then 3 else 4
else
motionType = if mtc == 1 then 2 elseif mtc == 2 then 1 else 4
end
if mtc == 0 then
err = true
return false
end
if not fieldPic and pattern then
dctType = read(1)
end
end
end
else
motionType = 1
end
if band(mt, 0x10) ~= 0 then
local code = read(5)
if code == 0 then
err = true
return false
end
qscale = getQscale(code)
end
if mbIntra then
if concealMv then
-- concealment vectors: parsed, kept as predictors
if fieldPic then
pos += 1
end
local x = decodeMotion(fc00, PMV[1])
local y = decodeMotion(fc01, PMV[2])
PMV[1], PMV[3] = x, x
PMV[2], PMV[4] = y, y
pos += 1 -- marker
else
resetPmv()
end
else
dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec)
motFw = fw
motBw = bw
if fw then
motionVectors(0)
elseif ptype == 2 then
-- P without motion: a zero vector (field pictures: from the same parity)
resetPmv()
motFw = true
motionType = 1
MV[1], MV[2] = 0, 0
FSEL[1] = parity
end
if bw then
motionVectors(1)
end
if err then
return false
end
predictMb()
end
local nb = if chroma == 2 then 8 else 6
local cbp
if pattern then
cbp = vlc(CBP, CBP_BITS)
if nb == 8 then
cbp = cbp * 4 + read(2)
end
if err then
return false
end
else
cbp = if mbIntra then lshift(1, nb) - 1 else 0
end
if cbp ~= 0 then
for b = 0, nb - 1 do
if band(cbp, lshift(1, nb - 1 - b)) ~= 0 then
if not decodeBlock(b) then
return false
end
end
end
end
return pos <= endBits
end
local function decodeSlice(row: number, endByte: number)
if mpeg2 and lumaH > 2800 then
row += lshift(read(3), 7)
end
if row > mbRows then
return
end
mbAddr = (row - 1) * mbW - 1
resetPmv()
dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec)
motFw, motBw = false, false
local code = read(5)
local endBits = endByte * 8
while read(1) == 1 and pos < endBits do
pos += 8
end
if code == 0 then
return
end
qscale = getQscale(code)
local first = true
while true do
if not decodeMacroblock(first, endBits) then
state.errors += 1
buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded
break
end
first = false
-- the slice ends at a start code (byte aligned) or at the end of the picture data
local i = rshift(pos + 7, 3)
if i >= endByte then
break
end
if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then
break
end
end
-- the motion state a gap after this slice repeats (B pictures)
if mbIntra then
gapFw, gapBw = false, false
else
gapFw, gapBw, gapType = motFw, motBw, motionType
table.move(MV, 1, 16, 1, GAP)
end
end
-- ------------------------------------------------------------------------------------------------ pictures
-- the frame a picture completes becomes the newest reference (I / P)
local function finishFrame(s: Store)
if s.ptype ~= 3 then
state.refOld = state.refNew
state.refNew = s
end
end
-- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice
-- start code (-1: none) and the temporal reference, or nil when the picture is skipped
local function pictureHeader(p: number, stop: number): (number?, number)
pos = p * 8
local tref = read(10)
ptype = read(3)
pos += 16 -- vbv_delay
if ptype < 1 or ptype > 3 then
state.skipped += 1 -- D pictures and invalid types
return nil, 0
end
fullPelFw, fullPelBw = false, false
if ptype >= 2 then
fullPelFw = read(1) == 1
local c = read(3)
if c == 0 then
state.skipped += 1
return nil, 0
end
fc00, fc01 = c, c
end
if ptype == 3 then
fullPelBw = read(1) == 1
local c = read(3)
if c == 0 then
state.skipped += 1
return nil, 0
end
fc10, fc11 = c, c
end
-- MPEG-1 semantics unless a picture coding extension follows
dcPrec, picStruct, fpfd, concealMv, qScaleType, intraVlc, scan = 0, 3, true, false, 0, false, ZZ
tff, rff, progFrame = true, false, true
err = false
local at = findStart(rshift(pos + 7, 3), stop)
while at >= 0 do
local code = readu8(data, at + 3)
if code == 0xB5 then
extension(at + 4)
elseif code ~= 0xB2 then
break
end
at = findStart(at + 4, stop)
end
if mpeg2 then
fullPelFw, fullPelBw = false, false
end
if err then
state.errors += 1
err = false
end
return at, tref
end
-- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped
local function selectTarget(tref: number, tag: any): boolean
fieldPic = picStruct ~= 3
parity = if picStruct == 2 then 1 else 0
secondField = false
local target: Store
if fieldPic and pending and pendingStruct ~= picStruct then
secondField = true
target = pending :: Store
fwS, bwS = pendingFw, pendingBw
if ptype == 3 and (fwS == nil or bwS == nil) then
state.skipped += 1
return false
end
else
if pending then
-- an unpaired field: its frame is done as it is
finishFrame(pending :: Store)
pending = nil
end
local refOld, refNew = state.refOld, state.refNew
if ptype == 1 then
target = if stores[1] == refNew then stores[2] else stores[1]
fwS, bwS = refNew, nil
elseif ptype == 2 then
if refNew == nil and not fieldPic then
state.skipped += 1
return false
end
target = if stores[1] == refNew then stores[2] else stores[1]
fwS, bwS = refNew, nil
else
if refOld == nil or refNew == nil or bStore == nil then
state.skipped += 1
return false
end
target = bStore :: Store
fwS, bwS = refOld, refNew
end
target.ptype = ptype
target.tref = tref
target.tag = tag
target.mpeg2 = mpeg2
target.progressive = progFrame
target.fields = fieldPic
target.tff = if fieldPic then picStruct == 1 else tff
target.rff = rff
target.clamped = 0
target.concealed = {}
end
cur = target
return true
end
-- plane addressing of the current picture
local function setAddressing()
local target = cur :: Store
curY, curCb, curCr = target.y, target.cb, target.cr
if fieldPic then
mbRows = mbH // 2
lstride, lbase = 2 * cw, parity * cw
cstride, cbase = 2 * chw, parity * chw
else
mbRows = mbH
lstride, lbase = cw, 0
cstride, cbase = chw, 0
end
mbSize = mbW * mbRows
covered = 0
hasRef = fwS ~= nil
gapFw, gapBw = false, false
mbIntra = false
end
-- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil
-- (skipped, or the first field of a frame).
local function decodePicture(p: number, stop: number, tag: any): Store?
local first, tref = pictureHeader(p, stop)
if first == nil or not selectTarget(tref, tag) then
return nil
end
setAddressing()
-- slices
local at = first :: number
while at >= 0 do
local code = readu8(data, at + 3)
if code >= 0x01 and code <= 0xAF then
pos = (at + 4) * 8
err = false
decodeSlice(code, stop)
local nb = rshift(pos + 7, 3)
if nb >= stop then
break
end
at = findStart(nb, stop)
elseif code == 0xB2 or code == 0xB5 then
at = findStart(at + 4, stop)
else
break
end
end
conceal(covered, mbSize - 1)
state.pictures += 1
local target = cur :: Store
if fieldPic and not secondField then
pending = target
pendingStruct = picStruct
pendingFw, pendingBw = fwS, bwS
return nil
end
pending = nil
finishFrame(target)
return target
end
local core = {} :: Core
core.state = state
function core.write(src: buffer, off: number, n: number)
if n <= 0 then
return
end
-- drop consumed bytes, keeping the scan state relative
if readByte > 0 then
local keep = dataLen - readByte
if keep > 0 then
buffer.copy(data, 0, data, readByte, keep)
end
scanPos = math.max(0, scanPos - readByte)
dataLen = keep
readByte = 0
end
local need = dataLen + n + PAD
if need > buffer.len(data) then
local cap = buffer.len(data)
while cap < need do
cap *= 2
end
local nb = buffer.create(cap)
buffer.copy(nb, 0, data, 0, dataLen)
data = nb
end
buffer.copy(data, dataLen, src, off, n)
dataLen += n
buffer.fill(data, dataLen, 0, PAD)
end
-- the sequence header unit at byte at (up to stop): the header, then its extensions
local function sequenceUnit(at: number, stop: number)
local ok = sequenceHeader(at + 4)
local s = findStart(at + 4, stop)
while s >= 0 do
if readu8(data, s + 3) == 0xB5 then
extension(s + 4)
end
s = findStart(s + 4, stop)
end
if not ok or not applySequence() then
state.errors += 1
end
end
function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean)
while true do
local at = findStart(readByte, dataLen)
if at < 0 then
-- keep the last 3 bytes: a start code may straddle the next write
readByte = math.max(readByte, dataLen - 3)
if atEnd then
readByte = dataLen
end
return nil, true
end
local code = readu8(data, at + 3)
if code == 0xB3 or code == 0x00 then
-- a unit is complete when the next unit start (or the end of the data) follows it
local stop = dataLen
do
local s = findStart(math.max(at + 4, scanPos), dataLen)
while s >= 0 do
local c = readu8(data, s + 3)
if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then
break
end
s = findStart(s + 4, dataLen)
end
if s < 0 then
if not atEnd then
scanPos = math.max(at + 4, dataLen - 3)
readByte = at
return nil, true
end
else
stop = s
end
end
scanPos = 0
readByte = stop
if code == 0xB3 then
sequenceUnit(at, stop)
elseif hasSeq then
local s = decodePicture(at + 4, stop, tag)
if s then
return s, false
end
else
state.skipped += 1
end
else
readByte = at + 4 -- GOP header, sequence end, user data, stray slices
end
end
end
function core.toRgba(s: Store, out: buffer)
if s.chroma == 2 then
toRgba422(s.y, s.cb, s.cr, s.cw, s.w, s.h, out)
else
toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out)
end
end
function core.reset()
dataLen = 0
readByte = 0
scanPos = 0
state.refOld = nil
state.refNew = nil
pending = nil
end
return core
end
return D