Files
rosetta/src/Formats/codecs/video/Mpeg1/Decoder.luau
T
4DBug 51b08575c4 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
2026-10-31 12:25:03 -05:00

1137 lines
33 KiB
Luau

--!strict
--!native
-- codecs/video/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures,
-- half-pel motion compensation, custom quantiser matrices, sequence headers anywhere in the stream. Absorbed from
-- mpeg1-luau e2e2898 (same author; src/Mpeg1/Decoder.luau, unchanged but for this header and the requires), a port
-- of jsmpeg's decoder (src/mpeg1.js by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt) with these changes for
-- speed and accuracy in Luau:
-- * table-driven VLC decoding (Vlc.luau) on a 32-bit peek instead of a bit-by-bit tree walk;
-- * an accurate integer IDCT (the LL&M / "islow" factorisation, 13-bit constants) instead of jsmpeg's AAN
-- approximation, so P-picture drift stays close to ffmpeg's decode; dequantisation follows the standard
-- (magnitude, truncation toward zero, oddification);
-- * B pictures (forward, backward and interpolated prediction, skipped macroblocks), which jsmpeg skips;
-- * motion compensation four bytes at a time (SWAR rounding averages);
-- * BT.601 limited-range YCbCr -> RGBA8 (jsmpeg's canvas path treats Y as full range).
--
-- The IDCT is not codecs/image/Dct's: it computes the same islow transform (its put mode is bit-identical to
-- Dct.idctBlock with a unit quantiser and no level shift, checked on 20000 random blocks), but MPEG-1 adds the
-- residual of P / B blocks to the prediction before clamping, dequantises into i32 coefficients itself (MPEG
-- rounding and oddification, not JPEG's q multiply) and writes u8 samples four per writeu32, where Dct clamps to
-- 0..maxv, dequantises JPEG-style and writes u16 planes.
--
-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture.
-- Native code must never throw (an error unwinding through native code crashes Roblox Studio): 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/Mpeg1/Vlc")
local T = require("@formats/codecs/video/Mpeg1/Tables")
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 PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~1.5 KB, the pos check runs per macroblock
local D = {}
D.PICTURE_I = 1
D.PICTURE_P = 2
D.PICTURE_B = 3
local ZZ = buffer.create(64)
local DEF_INTRA = buffer.create(64) -- scan order (Q[n] = matrix[ZZ[n]])
local DEF_NON_INTRA = buffer.create(64)
for i = 0, 63 do
buffer.writeu8(ZZ, i, T.ZIG_ZAG[i])
buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]])
buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]])
end
-- clamp to 0..255 by lookup: CLAMP[v + COFF] for any v in [-COFF, COFF]. IDCT outputs are bounded by
-- 64 * 2048 / 4 = 32768 for any coefficients, plus a prediction of up to 255.
local COFF = 40000
local CLAMP = buffer.create(2 * COFF + 256)
for i = 0, 2 * COFF + 255 do
buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255))
end
-- 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
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 = V.DCT_FIRST, V.DCT_NEXT
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 }
-- Integer IDCT (LL&M factorisation as in the IJG "islow" IDCT: CONST_BITS 13, PASS1_BITS 2) of the 64 i32
-- coefficients in blk (natural order), written to dst (put) or added to it (add), clamped to 0..255.
local function idct(blk: buffer, ws: buffer, dst: buffer, off: number, stride: number, add: boolean)
-- pass 1: columns, into ws scaled by 4
for c = 0, 28, 4 do
local d0 = readi32(blk, c)
local d1 = readi32(blk, c + 32)
local d2 = readi32(blk, c + 64)
local d3 = readi32(blk, c + 96)
local d4 = readi32(blk, c + 128)
local d5 = readi32(blk, c + 160)
local d6 = readi32(blk, c + 192)
local d7 = readi32(blk, c + 224)
if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then
local dc = d0 * 4
writei32(ws, c, dc)
writei32(ws, c + 32, dc)
writei32(ws, c + 64, dc)
writei32(ws, c + 96, dc)
writei32(ws, c + 128, dc)
writei32(ws, c + 160, dc)
writei32(ws, c + 192, dc)
writei32(ws, c + 224, dc)
else
-- even part
local z1 = (d2 + d6) * 4433
local t2 = z1 - d6 * 15137
local t3 = z1 + d2 * 6270
local t0 = (d0 + d4) * 8192
local t1 = (d0 - d4) * 8192
local t10 = t0 + t3
local t13 = t0 - t3
local t11 = t1 + t2
local t12 = t1 - t2
-- odd part
local o0, o1, o2, o3 = d7, d5, d3, d1
local y1 = o0 + o3
local y2 = o1 + o2
local y3 = o0 + o2
local y4 = o1 + o3
local z5 = (y3 + y4) * 9633
o0 *= 2446
o1 *= 16819
o2 *= 25172
o3 *= 12299
y1 *= -7373
y2 *= -20995
y3 = y3 * -16069 + z5
y4 = y4 * -3196 + z5
o0 += y1 + y3
o1 += y2 + y4
o2 += y2 + y3
o3 += y1 + y4
writei32(ws, c, (t10 + o3 + 1024) // 2048)
writei32(ws, c + 224, (t10 - o3 + 1024) // 2048)
writei32(ws, c + 32, (t11 + o2 + 1024) // 2048)
writei32(ws, c + 192, (t11 - o2 + 1024) // 2048)
writei32(ws, c + 64, (t12 + o1 + 1024) // 2048)
writei32(ws, c + 160, (t12 - o1 + 1024) // 2048)
writei32(ws, c + 96, (t13 + o0 + 1024) // 2048)
writei32(ws, c + 128, (t13 - o0 + 1024) // 2048)
end
end
-- pass 2: rows, descaled by 2^18 (13 + 2 + 3), into the picture
for r = 0, 224, 32 do
local d0 = readi32(ws, r)
local d1 = readi32(ws, r + 4)
local d2 = readi32(ws, r + 8)
local d3 = readi32(ws, r + 12)
local d4 = readi32(ws, r + 16)
local d5 = readi32(ws, r + 20)
local d6 = readi32(ws, r + 24)
local d7 = readi32(ws, r + 28)
local p0, p1, p2, p3, p4, p5, p6, p7
if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then
local v = (d0 + 16) // 32
p0, p1, p2, p3, p4, p5, p6, p7 = v, v, v, v, v, v, v, v
else
local z1 = (d2 + d6) * 4433
local t2 = z1 - d6 * 15137
local t3 = z1 + d2 * 6270
local t0 = (d0 + d4) * 8192
local t1 = (d0 - d4) * 8192
local t10 = t0 + t3 + 131072
local t13 = t0 - t3 + 131072
local t11 = t1 + t2 + 131072
local t12 = t1 - t2 + 131072
local o0, o1, o2, o3 = d7, d5, d3, d1
local y1 = o0 + o3
local y2 = o1 + o2
local y3 = o0 + o2
local y4 = o1 + o3
local z5 = (y3 + y4) * 9633
o0 *= 2446
o1 *= 16819
o2 *= 25172
o3 *= 12299
y1 *= -7373
y2 *= -20995
y3 = y3 * -16069 + z5
y4 = y4 * -3196 + z5
o0 += y1 + y3
o1 += y2 + y4
o2 += y2 + y3
o3 += y1 + y4
p0 = (t10 + o3) // 262144
p7 = (t10 - o3) // 262144
p1 = (t11 + o2) // 262144
p6 = (t11 - o2) // 262144
p2 = (t12 + o1) // 262144
p5 = (t12 - o1) // 262144
p3 = (t13 + o0) // 262144
p4 = (t13 - o0) // 262144
end
if add then
p0 += readu8(dst, off)
p1 += readu8(dst, off + 1)
p2 += readu8(dst, off + 2)
p3 += readu8(dst, off + 3)
p4 += readu8(dst, off + 4)
p5 += readu8(dst, off + 5)
p6 += readu8(dst, off + 6)
p7 += readu8(dst, off + 7)
end
writeu32(
dst,
off,
readu8(CLAMP, p0 + COFF)
+ readu8(CLAMP, p1 + COFF) * 256
+ readu8(CLAMP, p2 + COFF) * 65536
+ readu8(CLAMP, p3 + COFF) * 16777216
)
writeu32(
dst,
off + 4,
readu8(CLAMP, p4 + COFF)
+ readu8(CLAMP, p5 + COFF) * 256
+ readu8(CLAMP, p6 + COFF) * 65536
+ readu8(CLAMP, p7 + COFF) * 16777216
)
off += stride
end
end
D.idct = idct
-- a constant 8x8 block (DC only): put or add v
local function fillBlock(dst: buffer, off: number, stride: number, v: number, add: boolean)
if not add then
local c = readu8(CLAMP, v + COFF) * 0x01010101
for _ = 1, 8 do
writeu32(dst, off, c)
writeu32(dst, off + 4, c)
off += stride
end
else
for _ = 1, 8 do
for i = off, off + 7 do
writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF))
end
off += stride
end
end
end
-- Motion-compensated prediction of a size x size block (16 luma, 8 chroma) from src at sOff to dst at dOff with
-- half-pel flags hx / hy; avg averages into what dst holds (the second prediction of a B macroblock). Four bytes at
-- a time: avg(a, b) rounding up = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its
-- low 2 bits and high 6 bits so no lane overflows.
local function mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: number, size: number, hx: number, hy: number, avg: boolean)
for _ = 1, size do
for i = 0, size - 4, 4 do
local p
if hx == 0 then
if hy == 0 then
p = readu32(src, sOff + i)
else
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride)
p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
end
elseif hy == 0 then
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
else
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1)
local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202
local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2)
p = h + band(rshift(l, 2), 0x0F0F0F0F)
end
if avg then
local q = readu32(dst, dOff + i)
p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1)
end
writeu32(dst, dOff + i, p)
end
sOff += stride
dOff += stride
end
end
D.mc = mc
-- 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
export type Store = { y: buffer, cb: buffer, cr: buffer, w: number, h: number, cw: number, tref: number, ptype: number, tag: any }
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.
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,
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,
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 mbW, mbH, mbSize = 0, 0, 0
local cw, chw = 0, 0 -- luma / chroma strides (coded widths)
local intraQ = buffer.create(64)
local nonIntraQ = buffer.create(64)
buffer.copy(intraQ, 0, DEF_INTRA, 0, 64)
buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64)
local stores: { Store } = {}
local bStore: Store? = nil
-- picture / slice / macroblock state
local ptype = 0
local fullPelFw, fwRSize, fwF = false, 0, 1
local fullPelBw, bwRSize, bwF = false, 0, 1
local curY, curCb, curCr = data, data, data
local fwY, fwCb, fwCr = data, data, data
local bwY, bwCb, bwCr = data, data, data
local qs = 1
local mbAddr, mbRow, mbCol = 0, 0, 0
local dcY, dcCb, dcCr = 128, 128, 128
local pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0
local mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0
local mbIntra = false
local motFw, motBw = false, false
local blk = buffer.create(256)
local ws = 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 sz = cw * mbH * 16
local y = buffer.create(sz)
local cb = buffer.create(sz // 4)
local cr = buffer.create(sz // 4)
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, tref = 0, ptype = 0, tag = nil }
end
-- sequence header at byte p (after the start code); returns 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 w == 0 or h == 0 or w * h > state.maxPixels then
return false
end
if read(1) == 1 then
for i = 0, 63 do
local v = read(8)
writeu8(intraQ, i, if v == 0 then 1 else v)
end
else
buffer.copy(intraQ, 0, DEF_INTRA, 0, 64)
end
if read(1) == 1 then
for i = 0, 63 do
local v = read(8)
writeu8(nonIntraQ, i, if v == 0 then 1 else v)
end
else
buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64)
end
state.frameRate = T.PICTURE_RATE[rate] or 0
state.aspect = aspect
state.bitRate = bitRate * 400
if w ~= state.width or h ~= state.height then
state.width = w
state.height = h
mbW = (w + 15) // 16
mbH = (h + 15) // 16
mbSize = mbW * mbH
cw = mbW * 16
chw = mbW * 8
state.codedWidth = cw
state.codedHeight = mbH * 16
stores = { newStore(), newStore() }
bStore = newStore()
state.refOld = nil
state.refNew = nil
state.sizeChanged = true
end
hasSeq = true
return true
end
local function decodeMotion(rsize: number, f: number, pmv: number): number
local code = vlc(MOTION, MOTION_BITS)
local d = code
if code ~= 0 and f ~= 1 then
local r = read(rsize)
d = (math.abs(code) - 1) * f + r + 1
if code < 0 then
d = -d
end
end
local v = pmv + d
if v > f * 16 - 1 then
v -= f * 32
elseif v < -f * 16 then
v += f * 32
end
return v
end
-- prediction of the current macroblock from one reference (avg: average into the first prediction)
local function predict(rY: buffer, rCb: buffer, rCr: buffer, mvH: number, mvV: number, avg: boolean)
local ch = mbH * 16
-- luma
local hx, hy = band(mvH, 1), band(mvV, 1)
local sx = mbCol * 16 + mvH // 2
local sy = mbRow * 16 + mvV // 2
if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + 16 + hy > ch then
-- outside the picture: a corrupt vector, clamped (full-pel)
hx, hy = 0, 0
sx = if sx < 0 then 0 elseif sx > cw - 16 then cw - 16 else sx
sy = if sy < 0 then 0 elseif sy > ch - 16 then ch - 16 else sy
state.clamped += 1
end
mc(rY, curY, cw, sy * cw + sx, mbRow * 16 * cw + mbCol * 16, 16, hx, hy, avg)
-- chroma: vector / 2 truncated toward zero
local cH = if mvH < 0 then -((-mvH) // 2) else mvH // 2
local cV = if mvV < 0 then -((-mvV) // 2) else mvV // 2
hx, hy = band(cH, 1), band(cV, 1)
sx = mbCol * 8 + cH // 2
sy = mbRow * 8 + cV // 2
local chh = mbH * 8
if sx < 0 or sy < 0 or sx + 8 + hx > chw or sy + 8 + hy > chh then
hx, hy = 0, 0
sx = if sx < 0 then 0 elseif sx > chw - 8 then chw - 8 else sx
sy = if sy < 0 then 0 elseif sy > chh - 8 then chh - 8 else sy
end
local so = sy * chw + sx
local dof = mbRow * 8 * chw + mbCol * 8
mc(rCb, curCb, chw, so, dof, 8, hx, hy, avg)
mc(rCr, curCr, chw, so, dof, 8, hx, hy, avg)
end
-- prediction of a non-intra macroblock from the current motion state
local function predictMb()
if ptype == 2 then
predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false)
elseif motFw then
predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false)
if motBw then
predict(bwY, bwCb, bwCr, mvBwH, mvBwV, true)
end
elseif motBw then
predict(bwY, bwCb, bwCr, mvBwH, mvBwV, false)
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 gapFwH, gapFwV, gapBwH, gapBwV = 0, 0, 0, 0
local hasRef = false
local function conceal(from: number, to: number)
if from > to or not hasRef then
return
end
local sFw, sBw, sFwH, sFwV, sBwH, sBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV
if ptype == 3 then
motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = gapFw, gapBw, gapFwH, gapFwV, gapBwH, gapBwV
if not motFw and not motBw then
motFw = true
mvFwH, mvFwV = 0, 0
end
elseif ptype == 2 and gapFw then
mvFwH, mvFwV = gapFwH, gapFwV
else
mvFwH, mvFwV = 0, 0
end
local pt = ptype
if pt == 1 then
ptype = 2 -- a damaged I picture: copy the previous reference
end
for a = from, to do
mbRow = a // mbW
mbCol = a % mbW
predictMb()
end
ptype = pt
motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = sFw, sBw, sFwH, sFwV, sBwH, sBwV
end
-- one 8x8 block: 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
if mbIntra then
local dc
if b < 4 then
local size = vlc(DC_LUMA, DC_LUMA_BITS)
dc = dcY
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
dcY = dc
else
local size = vlc(DC_CHROMA, DC_CHROMA_BITS)
dc = if b == 4 then dcCb else dcCr
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 b == 4 then
dcCb = dc
else
dcCr = dc
end
end
if err then
return false
end
if dc < 0 or dc > 255 then
-- out of range (corrupt data): clamp, which also bounds the IDCT input
dc = if dc < 0 then 0 else 255
if b < 4 then
dcY = dc
elseif b == 4 then
dcCb = dc
else
dcCr = dc
end
end
writei32(blk, 0, dc * 8)
q = intraQ
n = 1
else
q = nonIntraQ
end
local lut = if n == 0 then DCT_FIRST else DCT_NEXT
local intra = mbIntra
local qscale = qs
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 = DCT_NEXT
if v == EOB then
pos += l
break
end
local run, level, neg
if v == ESC then
-- 6-bit run, then an 8-bit level or 0x00 / 0x80 and 8 more bits
pos += l
run = read(6)
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
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
-- dequantise the magnitude (truncating), make it odd toward zero, clamp
local m
if intra then
m = (level * 2 * qscale * readu8(q, n)) // 16
else
m = ((level * 2 + 1) * qscale * readu8(q, n)) // 16
end
if band(m, 1) == 0 and m ~= 0 then
m -= 1
end
if neg then
if m > 2048 then
m = 2048
end
m = -m
elseif m > 2047 then
m = 2047
end
local zz = readu8(ZZ, n)
if zz ~= 0 then
onlyDc = false
end
writei32(blk, zz * 4, m)
n += 1
end
-- reconstruction
local dst, off, stride
if b < 4 then
dst = curY
stride = cw
off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0)
else
dst = if b == 4 then curCb else curCr
stride = chw
off = mbRow * 8 * chw + mbCol * 8
end
if onlyDc then
fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra)
writei32(blk, 0, 0)
else
idct(blk, ws, dst, off, stride, not intra)
buffer.fill(blk, 0, 0, 256)
end
return true
end
local function resetMv()
pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0
mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0
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
dcY, dcCb, dcCr = 128, 128, 128
if ptype == 2 then
resetMv()
end
-- skipped macroblocks: P copies the reference (zero vector), B repeats the previous prediction
for _ = 2, inc do
mbAddr += 1
mbRow = mbAddr // mbW
mbCol = mbAddr % mbW
if ptype == 1 then
err = true -- no skipped macroblocks in I pictures
return false
end
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
if band(mt, 0x10) ~= 0 then
qs = read(5)
if qs == 0 then
err = true
return false
end
end
if mbIntra then
resetMv()
else
dcY, dcCb, dcCr = 128, 128, 128
motFw = band(mt, 8) ~= 0
motBw = band(mt, 4) ~= 0
if motFw then
pmvFwH = decodeMotion(fwRSize, fwF, pmvFwH)
pmvFwV = decodeMotion(fwRSize, fwF, pmvFwV)
mvFwH = if fullPelFw then pmvFwH * 2 else pmvFwH
mvFwV = if fullPelFw then pmvFwV * 2 else pmvFwV
elseif ptype == 2 then
resetMv()
end
if motBw then
pmvBwH = decodeMotion(bwRSize, bwF, pmvBwH)
pmvBwV = decodeMotion(bwRSize, bwF, pmvBwV)
mvBwH = if fullPelBw then pmvBwH * 2 else pmvBwH
mvBwV = if fullPelBw then pmvBwV * 2 else pmvBwV
end
if err then
return false
end
predictMb()
end
local cbp
if band(mt, 2) ~= 0 then
cbp = vlc(CBP, CBP_BITS)
if err then
return false
end
else
cbp = if mbIntra then 63 else 0
end
if cbp ~= 0 then
for b = 0, 5 do
if band(cbp, rshift(32, 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 row > mbH then
return
end
mbAddr = (row - 1) * mbW - 1
resetMv()
dcY, dcCb, dcCr = 128, 128, 128
motFw, motBw = false, false
qs = read(5)
local endBits = endByte * 8
while read(1) == 1 and pos < endBits do
pos += 8
end
if qs == 0 then
return
end
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, gapFwH, gapFwV, gapBwH, gapBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV
end
end
-- the picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop
local function decodePicture(p: number, stop: number, tag: any): Store?
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
end
if ptype >= 2 then
fullPelFw = read(1) == 1
local fcode = read(3)
if fcode == 0 then
state.skipped += 1
return nil
end
fwRSize = fcode - 1
fwF = lshift(1, fwRSize)
end
if ptype == 3 then
fullPelBw = read(1) == 1
local bcode = read(3)
if bcode == 0 then
state.skipped += 1
return nil
end
bwRSize = bcode - 1
bwF = lshift(1, bwRSize)
end
-- references: P from the newest, B between the two newest
local target: Store
local refOld, refNew = state.refOld, state.refNew
if ptype == 1 then
target = if stores[1] == refNew then stores[2] else stores[1]
if refNew then
fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr
end
elseif ptype == 2 then
if refNew == nil then
state.skipped += 1
return nil
end
target = if stores[1] == refNew then stores[2] else stores[1]
fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr
else
if refOld == nil or refNew == nil or bStore == nil then
state.skipped += 1
return nil
end
target = bStore :: Store
local ro, rn = refOld :: Store, refNew :: Store
fwY, fwCb, fwCr = ro.y, ro.cb, ro.cr
bwY, bwCb, bwCr = rn.y, rn.cb, rn.cr
end
curY, curCb, curCr = target.y, target.cb, target.cr
err = false
covered = 0
hasRef = refNew ~= nil
gapFw, gapBw = false, false
mbIntra = false
-- slices
local at = findStart(rshift(pos + 7, 3), stop)
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
target.tref = tref
target.ptype = ptype
target.tag = tag
if ptype ~= 3 then
-- the new picture becomes the newest reference
state.refOld = refNew
state.refNew = target
end
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
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
if not sequenceHeader(at + 4) then
state.errors += 1
end
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)
toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out)
end
function core.reset()
dataLen = 0
readByte = 0
scanPos = 0
state.refOld = nil
state.refNew = nil
end
return core
end
return D