From c33ffa7343ddc5f6cf26f407e5608cd7129e4ee7 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:25:51 -0500 Subject: [PATCH] ws-video2: codecs/video/Mpeg2 (MPEG-1/2 core, Main profile, 4:2:2, field pictures, dual prime), bit-exact with ffmpeg -idct int Mpeg1 is now the Mpeg2 module under its old name (core, tables and VLCs moved to Mpeg2/). Dsp.mc takes separate source / destination strides; Dsp.edge emulates edges. containers/MpegEs: field-picture pairs are one access unit (pictureStructure). Registry: mpeg1 and mpeg2 decode through Mpeg2.newVideoDecoder; more MPEG-2 FourCCs. Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 5 +- src/Formats/codecs/video/Dsp.luau | 50 +- src/Formats/codecs/video/Mpeg1/Decoder.luau | 942 ----------- src/Formats/codecs/video/Mpeg1/init.luau | 267 +-- src/Formats/codecs/video/Mpeg2/Decoder.luau | 1490 +++++++++++++++++ .../codecs/video/{Mpeg1 => Mpeg2}/Tables.luau | 45 +- .../codecs/video/{Mpeg1 => Mpeg2}/Vlc.luau | 46 +- src/Formats/codecs/video/Mpeg2/init.luau | 364 ++++ src/Formats/codecs/video/Video/init.luau | 53 +- src/Formats/containers/MpegEs.luau | 34 +- tests/codecs/mpeg2.luau | 302 ++++ tools/fixtures/mpeg2.py | 178 ++ 12 files changed, 2487 insertions(+), 1289 deletions(-) delete mode 100644 src/Formats/codecs/video/Mpeg1/Decoder.luau create mode 100644 src/Formats/codecs/video/Mpeg2/Decoder.luau rename src/Formats/codecs/video/{Mpeg1 => Mpeg2}/Tables.luau (73%) rename src/Formats/codecs/video/{Mpeg1 => Mpeg2}/Vlc.luau (68%) create mode 100644 src/Formats/codecs/video/Mpeg2/init.luau create mode 100644 tests/codecs/mpeg2.luau create mode 100644 tools/fixtures/mpeg2.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f36b9a6..acfcdbf 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -132,7 +132,8 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - **video** - - codecs/video/Dsp: block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the + - codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the - - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from + - codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder + - codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/src/Formats/codecs/video/Dsp.luau b/src/Formats/codecs/video/Dsp.luau index 6bdc215..02b875d 100644 --- a/src/Formats/codecs/video/Dsp.luau +++ b/src/Formats/codecs/video/Dsp.luau @@ -16,7 +16,8 @@ -- -- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it -- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3) --- Dsp.mc(src, dst, stride, sOff, dOff, size, hx, hy, avg) -- half-pel prediction, size 8 / 16 (multiple of 4) +-- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block +-- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE) local Dsp = {} local readu8 = buffer.readu8 @@ -654,20 +655,20 @@ function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: bool end -- ------------------------------------------------------------------------------------------------ motion --- Motion-compensated prediction of a size x size block (size 8 or 16; 4 for H.263 chroma is fine too: any multiple --- of 4) from src at sOff to dst at dOff, both with stride (twice the plane width for field prediction), half-pel --- flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what dst holds (the second --- prediction of a bidirectional block, rounding up). Four bytes at a time: avg(a, b) = (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. -function Dsp.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 +-- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst +-- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what +-- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for +-- field prediction. Four bytes at a time: avg(a, b) = (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. +function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) + for _ = 1, h do + for i = 0, w - 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) + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + sStride) p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) end elseif hy == 0 then @@ -675,10 +676,10 @@ function Dsp.mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: nu 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 c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 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) + local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = hi + band(rshift(l, 2), 0x0F0F0F0F) end if avg then local q = readu32(dst, dOff + i) @@ -686,8 +687,27 @@ function Dsp.mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: nu end writeu32(dst, dOff + i, p) end - sOff += stride - dOff += stride + sOff += sStride + dOff += dStride + end +end + +-- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to +-- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture +-- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes). +Dsp.EDGE_STRIDE = 32 +Dsp.EDGE_SIZE = 32 * 34 + 4 +function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) + for j = 0, h do + local sy = y + j + sy = if sy < 0 then 0 elseif sy >= ph then ph - 1 else sy + local row = base + sy * stride + local o = j * 32 + for i = 0, w do + local sx = x + i + sx = if sx < 0 then 0 elseif sx >= pw then pw - 1 else sx + writeu8(out, o + i, readu8(src, row + sx)) + end end end diff --git a/src/Formats/codecs/video/Mpeg1/Decoder.luau b/src/Formats/codecs/video/Mpeg1/Decoder.luau deleted file mode 100644 index 0431576..0000000 --- a/src/Formats/codecs/video/Mpeg1/Decoder.luau +++ /dev/null @@ -1,942 +0,0 @@ ---!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 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 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 } - -local idct = Dsp.idct -local fillBlock = Dsp.fill -local mc = Dsp.mc -D.idct = idct -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, 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 diff --git a/src/Formats/codecs/video/Mpeg1/init.luau b/src/Formats/codecs/video/Mpeg1/init.luau index 25c7d10..54f1aa4 100644 --- a/src/Formats/codecs/video/Mpeg1/init.luau +++ b/src/Formats/codecs/video/Mpeg1/init.luau @@ -1,262 +1,11 @@ --!strict --- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from --- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder --- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures, --- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage. --- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom --- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display --- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau). --- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding. --- --- local dec = Mpeg1.new({ reorder = true, rgba = false }) --- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts --- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) --- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces --- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek --- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... } --- --- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). -local Types = require("@formats/Types") -local D = require("@formats/codecs/video/Mpeg1/Decoder") +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder +-- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / +-- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2. +local Mpeg2 = require("@formats/codecs/video/Mpeg2") -local Mpeg1 = {} +export type Frame = Mpeg2.Frame +export type Options = Mpeg2.Options +export type Decoder = Mpeg2.Decoder -Mpeg1.PICTURE_I = 1 -Mpeg1.PICTURE_P = 2 -Mpeg1.PICTURE_B = 3 - -export type Frame = { - width: number, - height: number, - pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } - pictureType: number, -- 1 I, 2 P, 3 B - temporalReference: number, -- the picture's 10-bit display index within its GOP - index: number, -- frames returned so far (1-based) - tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) - -- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth, - -- chroma stride codedWidth / 2 - y: buffer, - cb: buffer, - cr: buffer, - codedWidth: number, -} - -export type Options = { - reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the - -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is - -- display order for streams without B-frames. - rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) - maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) -} - -local Decoder = {} -Decoder.__index = Decoder - -export type Decoder = typeof(setmetatable( - {} :: { - _core: D.Core, - _reorder: boolean, - _rgba: boolean, - _held: D.Store?, - _pixels: buffer?, - _count: number, - width: number, - height: number, - frameRate: number, - bitRate: number, - stats: { pictures: number, errors: number, skipped: number }, - }, - Decoder -)) - -function Mpeg1.new(opts: Options?): Decoder - local o: Options = if type(opts) == "table" then opts else {} - local core = D.new(o.maxPixels) - return setmetatable({ - _core = core, - _reorder = o.reorder == true, - _rgba = o.rgba ~= false, - _held = nil, - _pixels = nil, - _count = 0, - width = 0, - height = 0, - frameRate = 0, - bitRate = 0, - stats = { pictures = 0, errors = 0, skipped = 0 }, - }, Decoder) -end - -local function emit(self: Decoder, s: D.Store): Frame - local core = self._core - local pixels: buffer? = nil - if self._rgba then - local need = s.w * s.h * 4 - local px = self._pixels - if px == nil or buffer.len(px) ~= need then - px = buffer.create(need) - self._pixels = px - end - core.toRgba(s, px :: buffer) - pixels = px - end - self._count += 1 - return { - width = s.w, - height = s.h, - pixels = pixels, - pictureType = s.ptype, - temporalReference = s.tref, - index = self._count, - tag = s.tag, - y = s.y, - cb = s.cb, - cr = s.cr, - codedWidth = s.cw, - } -end - -local function sync(self: Decoder) - local st = self._core.state - self.width = st.width - self.height = st.height - self.frameRate = st.frameRate - self.bitRate = st.bitRate - self.stats.pictures = st.pictures - self.stats.errors = st.errors - self.stats.skipped = st.skipped -end - --- a decoded picture -> the frame to return now (nil while reordering holds it) -local function handle(self: Decoder, s: D.Store): Frame? - if not self._reorder or s.ptype == D.PICTURE_B then - return emit(self, s) - end - local prev = self._held - self._held = s - if prev then - return emit(self, prev) - end - return nil -end - -local function run(self: Decoder, atEnd: boolean, tag: any): Frame? - local core = self._core - while true do - local s, needData = core.nextPicture(atEnd, tag) - sync(self) - if s then - local f = handle(self, s) - if f then - return f - end - elseif needData then - return nil - end - end -end - -local function append(self: Decoder, data: any, offset: number?, len: number?): boolean - local src: buffer - if type(data) == "string" then - src = buffer.fromstring(data) - elseif type(data) == "buffer" then - src = data - else - return false - end - local total = buffer.len(src) - local off = math.floor(tonumber(offset) or 0) - if off < 0 or off > total then - return false - end - local n = math.floor(tonumber(len) or (total - off)) - if n < 0 or off + n > total then - return false - end - self._core.write(src, off, n) - return true -end - --- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. -function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean - return append(self, data, offset, len) -end - --- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is --- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). -function Decoder.decodeFrame(self: Decoder): Frame? - return run(self, false, nil) -end - --- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). --- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. -function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? - if not append(self, data, offset, len) then - return nil - end - return run(self, true, tag) -end - --- At the end of the stream: decodes what is left of the written data, then returns the reference picture held --- for reordering. Call until it returns nil. -function Decoder.flush(self: Decoder): Frame? - local f = run(self, true, nil) - if f then - return f - end - local held = self._held - if held then - self._held = nil - return emit(self, held) - end - return nil -end - --- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). -function Decoder.reset(self: Decoder) - self._core.reset() - self._held = nil -end - --- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to --- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8 --- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame. -function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image? - if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then - return nil - end - local w, h, cw = frame.width, frame.height, frame.codedWidth - if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then - return nil - end - local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 - if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then - return nil - end - local img - if rgba then - img = Types.Image.new(w, h) - D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) - else - img = Types.Image.new(w, h, "yuv420p") - local px = img.pixels - for y = 0, h - 1 do - buffer.copy(px, y * w, frame.y, y * cw, w) - end - local o = w * h - for y = 0, oh - 1 do - buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) - buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) - end - end - img.meta.source = { - format = "mpeg1", - pictureType = frame.pictureType, - temporalReference = frame.temporalReference, - range = if rgba then nil else "limited", - } - return img -end - -return Mpeg1 +return Mpeg2 diff --git a/src/Formats/codecs/video/Mpeg2/Decoder.luau b/src/Formats/codecs/video/Mpeg2/Decoder.luau new file mode 100644 index 0000000..4cd982c --- /dev/null +++ b/src/Formats/codecs/video/Mpeg2/Decoder.luau @@ -0,0 +1,1490 @@ +--!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 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 = if mvx < 0 then -((-mvx) // 2) else mvx // 2 + local cx, cy, chh, cph, chx, chy + chx = band(mx, 1) + cx = mbCol * 8 + (mx - chx) // 2 + if chroma == 1 then + local my = if mvy < 0 then -((-mvy) // 2) else mvy // 2 + 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 cdOff = cdb + (if chroma == 1 then rowY // 2 else rowY) * 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 = (if d == 0 then fwS else bwS) or cur :: Store + local ry, rcb, rcr = r.y, r.cb, r.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 = if b % 2 == 0 then dcCb else dcCr + 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 = bit32.bxor(1, band(v, 1)) + q = if luma then intraQ else chromaIntraQ + n = 1 + else + q = if luma then nonIntraQ else chromaNonIntraQ + end + local lut = if mbIntra and intraVlc then DCT_B15 elseif n == 0 then DCT_FIRST else DCT_NEXT + local nextLut = if mbIntra and intraVlc then DCT_B15 else DCT_NEXT + 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 + parityOdd = bit32.bxor(parityOdd, band(m, 1)) + -- 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 = if b % 2 == 0 then curCb else curCr + 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 = if d == 0 then fc00 else fc10, if d == 0 then fc01 else fc11 + 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 diff --git a/src/Formats/codecs/video/Mpeg1/Tables.luau b/src/Formats/codecs/video/Mpeg2/Tables.luau similarity index 73% rename from src/Formats/codecs/video/Mpeg1/Tables.luau rename to src/Formats/codecs/video/Mpeg2/Tables.luau index 1cad194..86960c9 100644 --- a/src/Formats/codecs/video/Mpeg1/Tables.luau +++ b/src/Formats/codecs/video/Mpeg2/Tables.luau @@ -1,7 +1,8 @@ --!strict --- codecs/video/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, -- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from --- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays. +-- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the +-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7. local T = {} T.PICTURE_RATE = { [0] = 0.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, @@ -74,16 +75,6 @@ T.MOTION = { [0] = 3, 0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0, 0, -15, 0, 0, -11, 0, 0, -13, } -T.DCT_DC_SIZE_LUMINANCE = { [0] = 6, - 3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36, - 33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0, - 0, 7, 0, 0, 8, -} -T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6, - 3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0, - 0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0, - 0, 7, 0, 0, 8, -} T.DCT_COEFF = { [0] = 3, 6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0, 0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81, @@ -114,4 +105,34 @@ T.DCT_COEFF = { [0] = 3, 0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0, 0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842, } +-- dct_dc_size_luminance / chrominance (Tables B-12 / B-13, sizes 0..11): { code, length } per size +T.DC_SIZE_LUMA = { { 4, 3 }, { 0, 2 }, { 1, 2 }, { 5, 3 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 511, 9 } } +T.DC_SIZE_CHROMA = { { 0, 2 }, { 1, 2 }, { 2, 2 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 1022, 10 }, { 1023, 10 } } +-- Table B-15 (intra_vlc_format = 1), ISO/IEC 13818-2: { code, length, run * 256 + level } (the sign bit follows) +T.DCT_COEFF_B15 = { + 2,2,1, 6,3,2, 7,4,3, 28,5,4, 29,5,5, 5,6,6, 4,6,7, 123,7,8, + 124,7,9, 35,8,10, 34,8,11, 250,8,12, 251,8,13, 254,8,14, 255,8,15, 31,14,16, + 30,14,17, 29,14,18, 28,14,19, 27,14,20, 26,14,21, 25,14,22, 24,14,23, 23,14,24, + 22,14,25, 21,14,26, 20,14,27, 19,14,28, 18,14,29, 17,14,30, 16,14,31, 24,15,32, + 23,15,33, 22,15,34, 21,15,35, 20,15,36, 19,15,37, 18,15,38, 17,15,39, 16,15,40, + 2,3,257, 6,5,258, 121,7,259, 39,8,260, 32,8,261, 22,13,262, 21,13,263, 31,15,264, + 30,15,265, 29,15,266, 28,15,267, 27,15,268, 26,15,269, 25,15,270, 19,16,271, 18,16,272, + 17,16,273, 16,16,274, 5,5,513, 7,7,514, 252,8,515, 12,10,516, 20,13,517, 7,5,769, + 38,8,770, 28,12,771, 19,13,772, 6,6,1025, 253,8,1026, 18,12,1027, 7,6,1281, 4,9,1282, + 18,13,1283, 6,7,1537, 30,12,1538, 20,16,1539, 4,7,1793, 21,12,1794, 5,7,2049, 17,12,2050, + 120,7,2305, 17,13,2306, 122,7,2561, 16,13,2562, 33,8,2817, 26,16,2818, 37,8,3073, 25,16,3074, + 36,8,3329, 24,16,3330, 5,9,3585, 23,16,3586, 7,9,3841, 22,16,3842, 13,10,4097, 21,16,4098, + 31,12,4353, 26,12,4609, 25,12,4865, 23,12,5121, 22,12,5377, 31,13,5633, 30,13,5889, 29,13,6145, + 28,13,6401, 27,13,6657, 31,16,6913, 30,16,7169, 29,16,7425, 28,16,7681, 27,16,7937, +} +-- quantiser_scale for q_scale_type = 1 (Table 7-6), indexed by quantiser_scale_code +T.NON_LINEAR_QSCALE = { [0] = 0, + 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 104, 112, +} +-- the alternate scan (Figure 7-3): scan index -> natural position +T.ALTERNATE_SCAN = { [0] = 0, + 8, 16, 24, 1, 9, 2, 10, 17, 25, 32, 40, 48, 56, 57, 49, 41, 33, 26, 18, 3, 11, 4, 12, 19, 27, 34, 42, 50, 58, + 35, 43, 51, 59, 20, 28, 5, 13, 6, 14, 21, 29, 36, 44, 52, 60, 37, 45, 53, 61, 22, 30, 7, 15, 23, 31, 38, 46, + 54, 62, 39, 47, 55, 63, +} return T diff --git a/src/Formats/codecs/video/Mpeg1/Vlc.luau b/src/Formats/codecs/video/Mpeg2/Vlc.luau similarity index 68% rename from src/Formats/codecs/video/Mpeg1/Vlc.luau rename to src/Formats/codecs/video/Mpeg2/Vlc.luau index b4799aa..7ab0504 100644 --- a/src/Formats/codecs/video/Mpeg1/Vlc.luau +++ b/src/Formats/codecs/video/Mpeg2/Vlc.luau @@ -1,14 +1,15 @@ --!strict --- codecs/video/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). +-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). -- -- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds -- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level -- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, -- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the -- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one --- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but --- for this header and the require. -local T = require("@formats/codecs/video/Mpeg1/Tables") +-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA / +-- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees); +-- the MPEG-2 tables are built from code lists. +local T = require("@formats/codecs/video/Mpeg2/Tables") local V = {} @@ -32,8 +33,7 @@ local function leaves(tree: { [number]: number }): { Leaf } return out end -local function flat(tree: { [number]: number }): (buffer, number) - local ls = leaves(tree) +local function flatLeaves(ls: { Leaf }): (buffer, number) local k = 0 for _, l in ls do k = math.max(k, l.len) @@ -49,6 +49,19 @@ local function flat(tree: { [number]: number }): (buffer, number) return lut, k end +local function flat(tree: { [number]: number }): (buffer, number) + return flatLeaves(leaves(tree)) +end + +-- { { code, length } } indexed from 1 -> leaves with value = index - 1 +local function codeLeaves(codes: { { number } }): { Leaf } + local out: { Leaf } = {} + for i, c in codes do + table.insert(out, { code = c[1], len = c[2], value = i - 1 }) + end + return out +end + V.SUB = 0x1000000 V.ESC = 0xFFFF V.EOB = 0xFFFE @@ -93,10 +106,16 @@ V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA) V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE) V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B) -V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN) +do + -- MPEG-2 adds "0000 0000 1" = 0 (Table B-9: a 4:2:2 macroblock whose coded blocks are all in the extra chroma + -- pattern bits) + local ls = leaves(T.CODE_BLOCK_PATTERN) + table.insert(ls, { code = 1, len = 9, value = 0 }) + V.CBP, V.CBP_BITS = flatLeaves(ls) +end V.MOTION, V.MOTION_BITS = flat(T.MOTION) -V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE) -V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE) +V.DC_LUMA, V.DC_LUMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_LUMA)) +V.DC_CHROMA, V.DC_CHROMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_CHROMA)) do local ls = leaves(T.DCT_COEFF) @@ -113,4 +132,13 @@ do V.DCT_NEXT = twoLevel(nextLs) end +do + local ls: { Leaf } = { { code = 1, len = 6, value = V.ESC }, { code = 6, len = 4, value = V.EOB } } + local b = T.DCT_COEFF_B15 + for i = 1, #b, 3 do + table.insert(ls, { code = b[i], len = b[i + 1], value = b[i + 2] }) + end + V.DCT_B15 = twoLevel(ls) +end + return V diff --git a/src/Formats/codecs/video/Mpeg2/init.luau b/src/Formats/codecs/video/Mpeg2/init.luau new file mode 100644 index 0000000..846cbf7 --- /dev/null +++ b/src/Formats/codecs/video/Mpeg2/init.luau @@ -0,0 +1,364 @@ +--!strict +-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). +-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I / +-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes +-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from +-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this +-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines); +-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded. +-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +-- +-- local dec = Mpeg2.new({ reorder = true, rgba = false }) +-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts +-- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) +-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces +-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek +-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... } +-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2) +-- +-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local D = require("@formats/codecs/video/Mpeg2/Decoder") + +local Mpeg2 = {} + +Mpeg2.PICTURE_I = 1 +Mpeg2.PICTURE_P = 2 +Mpeg2.PICTURE_B = 3 + +export type Frame = { + width: number, + height: number, + pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } + pictureType: number, -- 1 I, 2 P, 3 B + temporalReference: number, -- the picture's 10-bit display index within its GOP + index: number, -- frames returned so far (1-based) + tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) + -- the decoded YCbCr planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride + -- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2) + y: buffer, + cb: buffer, + cr: buffer, + codedWidth: number, + chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 + mpeg2: boolean, + progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true) + fields: boolean, -- coded as two field pictures + topFieldFirst: boolean, + repeatFirstField: boolean, + clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated) + concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed) +} + +export type Options = { + reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the + -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is + -- display order for streams without B-frames. + rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) + maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) +} + +local Decoder = {} +Decoder.__index = Decoder + +export type Decoder = typeof(setmetatable( + {} :: { + _core: D.Core, + _reorder: boolean, + _rgba: boolean, + _held: D.Store?, + _pixels: buffer?, + _count: number, + width: number, + height: number, + frameRate: number, + bitRate: number, + stats: { pictures: number, errors: number, skipped: number }, + }, + Decoder +)) + +function Mpeg2.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local core = D.new(o.maxPixels) + return setmetatable({ + _core = core, + _reorder = o.reorder == true, + _rgba = o.rgba ~= false, + _held = nil, + _pixels = nil, + _count = 0, + width = 0, + height = 0, + frameRate = 0, + bitRate = 0, + stats = { pictures = 0, errors = 0, skipped = 0 }, + }, Decoder) +end + +local function emit(self: Decoder, s: D.Store): Frame + local core = self._core + local pixels: buffer? = nil + if self._rgba then + local need = s.w * s.h * 4 + local px = self._pixels + if px == nil or buffer.len(px) ~= need then + px = buffer.create(need) + self._pixels = px + end + core.toRgba(s, px :: buffer) + pixels = px + end + self._count += 1 + return { + width = s.w, + height = s.h, + pixels = pixels, + pictureType = s.ptype, + temporalReference = s.tref, + index = self._count, + tag = s.tag, + y = s.y, + cb = s.cb, + cr = s.cr, + codedWidth = s.cw, + chroma = s.chroma, + mpeg2 = s.mpeg2, + progressive = s.progressive, + fields = s.fields, + topFieldFirst = s.tff, + repeatFirstField = s.rff, + clamped = s.clamped, + concealed = s.concealed, + } +end + +local function sync(self: Decoder) + local st = self._core.state + self.width = st.width + self.height = st.height + self.frameRate = st.frameRate + self.bitRate = st.bitRate + self.stats.pictures = st.pictures + self.stats.errors = st.errors + self.stats.skipped = st.skipped +end + +-- a decoded picture -> the frame to return now (nil while reordering holds it) +local function handle(self: Decoder, s: D.Store): Frame? + if not self._reorder or s.ptype == D.PICTURE_B then + return emit(self, s) + end + local prev = self._held + self._held = s + if prev then + return emit(self, prev) + end + return nil +end + +local function run(self: Decoder, atEnd: boolean, tag: any): Frame? + local core = self._core + while true do + local s, needData = core.nextPicture(atEnd, tag) + sync(self) + if s then + local f = handle(self, s) + if f then + return f + end + elseif needData then + return nil + end + end +end + +local function append(self: Decoder, data: any, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local total = buffer.len(src) + local off = math.floor(tonumber(offset) or 0) + if off < 0 or off > total then + return false + end + local n = math.floor(tonumber(len) or (total - off)) + if n < 0 or off + n > total then + return false + end + self._core.write(src, off, n) + return true +end + +-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. +function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean + return append(self, data, offset, len) +end + +-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is +-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). +function Decoder.decodeFrame(self: Decoder): Frame? + return run(self, false, nil) +end + +-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). +-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. +function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? + if not append(self, data, offset, len) then + return nil + end + return run(self, true, tag) +end + +-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held +-- for reordering. Call until it returns nil. +function Decoder.flush(self: Decoder): Frame? + local f = run(self, true, nil) + if f then + return f + end + local held = self._held + if held then + self._held = nil + return emit(self, held) + end + return nil +end + +-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). +function Decoder.reset(self: Decoder) + self._core.reset() + self._held = nil +end + +-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to +-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma +-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for +-- a value that is not a Frame. +function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image? + if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, cw = frame.width, frame.height, frame.codedWidth + if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then + return nil + end + local c422 = frame.chroma == 2 + local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 + local crows = if c422 then h else oh + if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then + return nil + end + local img + if rgba then + img = Types.Image.new(w, h) + if c422 then + D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + else + D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + end + else + img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * cw, w) + end + local o = w * h + if not c422 then + for y = 0, oh - 1 do + buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) + buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) + end + else + -- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field + -- (4k + j and 4k + j + 2), so the fields do not mix + local inter = not frame.progressive + for y = 0, oh - 1 do + local a, b + if inter then + local base = (y // 2) * 4 + y % 2 + a, b = base, base + 2 + else + a, b = 2 * y, 2 * y + 1 + end + if b >= h then + b = a + end + for x = 0, ow - 1 do + buffer.writeu8(px, o + y * ow + x, (buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) // 2) + buffer.writeu8(px, o + ow * oh + y * ow + x, (buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) // 2) + end + end + end + end + img.meta.source = { + format = if frame.mpeg2 then "mpeg2" else "mpeg1", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + chroma = if c422 then "422" else "420", + interlaced = not frame.progressive, + topFieldFirst = frame.topFieldFirst, + range = if rgba then nil else "limited", + } + return img +end + +-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder +-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in +-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of +-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream). +function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) + local queue: { any } = {} + local function push(f: Frame) + local img = Mpeg2.frameImage(f) + if img then + img.meta.yuv = { range = "limited", matrix = "bt601" } + local tag = f.tag + table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) + end + end + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local tag = { packet.pts } + local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) + end + while f do -- more pictures in the packet + push(f) + f = dec:decode(packet.data, 0, 0, tag) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) + for _ = 1, 8 do + local f = dec:flush() + if not f then + break + end + push(f) + end + end + function self.reset(_: any) + dec:reset() + table.clear(queue) + end + return self :: any, nil +end + +return Mpeg2 diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..01f8218 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -240,51 +240,10 @@ local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) end --- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture) -local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Mpeg1 = require("@formats/codecs/video/Mpeg1") - local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) - local queue: { any } = {} - local function push(f: any) - local img = Mpeg1.frameImage(f) - if img then - img.meta.yuv = { range = "limited", matrix = "bt601" } - local tag = f.tag - table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) - end - end - local self = {} - function self.decode(_: any, packet: Types.Packet): Err.Err? - local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts }) - if not ok then - return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) - end - if f then - push(f) - end - return nil - end - function self.receive(_: any): (Types.Image?, number?, boolean?) - local q = table.remove(queue, 1) - if q then - return q[1], q[2], q[3] - end - return nil, nil, nil - end - function self.flush(_: any) - for _ = 1, 4 do - local f = dec:flush() - if not f then - break - end - push(f) - end - end - function self.reset(_: any) - dec:reset() - table.clear(queue) - end - return self :: any, nil +-- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display +local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Mpeg2 = require("@formats/codecs/video/Mpeg2") + return Mpeg2.newVideoDecoder(track, opts) end -- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); @@ -299,9 +258,9 @@ end local BUILTIN: { Entry } = { { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, - { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder }, + { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg2Decoder }, { id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder }, - { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } }, + { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v", "hdv1", "hdv2", "hdv3", "hdv5", "hdv6", "hdv7", "hdv8", "hdv9", "hdva", "xdv1", "xdv2", "xdv3", "xdv4", "xdv5", "xdv6", "xdv7", "xdv8", "xdv9", "xdva", "xdvb", "xdvc", "xdvd", "xdve", "xdvf", "xd54", "xd55", "xd59", "xd5a", "xd5b", "xd5c", "xd5d", "xd5e", "xd5f", "xdhd", "xdh2", "AVmp", "mx3n", "mx3p", "mx4n", "mx4p", "mx5n", "mx5p", "mmes", "MMES", "M701", "M702", "M703", "M704", "M705", "mpgv", "m2v1", "M2V1" }, matroska = { "V_MPEG2" }, new = mpeg2Decoder }, { id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } }, { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder }, { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, diff --git a/src/Formats/containers/MpegEs.luau b/src/Formats/containers/MpegEs.luau index f84a0bf..704db06 100644 --- a/src/Formats/containers/MpegEs.luau +++ b/src/Formats/containers/MpegEs.luau @@ -35,6 +35,8 @@ export type Picture = { temporal: number, -- temporal_reference gop: boolean, -- a GOP header precedes the picture sequence: boolean, -- a sequence header precedes the picture + structure: number, -- MPEG-2 picture_structure: 1 top field, 2 bottom field, 3 frame (MPEG-1: 3) + fields: number?, -- 2: a frame coded as two field pictures (both in this unit) } export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean } @@ -77,8 +79,30 @@ function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, num return 0, 0 end +-- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture +-- coding extension (3 = frame when there is none: MPEG-1) +function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number + local q = MpegEs.findStart(b, p + 4, limit) + local count = 0 + while q and count < 8 do + count += 1 + local code = if q + 6 < limit then readu8(b, q + 3) else -1 + if code == 0xB5 then + if readu8(b, q + 4) // 16 == 8 then + local st = readu8(b, q + 6) % 4 + return if st == 0 then 3 else st + end + elseif code ~= 0xB2 then + break + end + q = MpegEs.findStart(b, q + 4, limit) + end + return 3 +end + -- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its --- sequence / GOP header when one precedes it and runs to the next unit's start +-- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures +-- is one unit (fields = 2) function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local out: { Picture } = {} local unitStart: number? = nil @@ -87,7 +111,11 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local p = MpegEs.findStart(b, off, limit) while p do local code = if p + 3 < limit then readu8(b, p + 3) else -1 - if code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then + local st = if code == 0x00 then MpegEs.pictureStructure(b, p, limit) else 3 + if code == 0x00 and cur and cur.structure ~= 3 and cur.fields == nil and st ~= 3 and st ~= cur.structure then + -- the second field of the current frame: same unit + cur.fields = 2 + elseif code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then -- a sequence / GOP header or a picture after a picture closes it if cur and (code ~= 0xB7) then cur.size = p - cur.offset @@ -106,7 +134,7 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) t, tr = (x // 8) % 8, x // 64 end - cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq } + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } unitStart, seq, gop = nil, false, false elseif code == 0xB7 and cur then cur.size = p + 4 - cur.offset diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau new file mode 100644 index 0000000..fb3da3f --- /dev/null +++ b/tests/codecs/mpeg2.luau @@ -0,0 +1,302 @@ +-- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and +-- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan, +-- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd +-- size, B-frames, dual prime) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display +-- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive, +-- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted +-- streams never throw; the fuzz no-throw pass. +local T = require("@tests/T") +local Mpeg2 = require("@formats/codecs/video/Mpeg2") +local Video = require("@formats/codecs/video/Video") +local Base64 = require("@formats/core/Base64") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/compress/Deflate") + +local STREAMS = { + require("@tests/gen/mpeg2_prog"), + require("@tests/gen/mpeg2_tff"), + require("@tests/gen/mpeg2_bff_alt"), + require("@tests/gen/mpeg2_tools"), + require("@tests/gen/mpeg2_dc9_matrix"), + require("@tests/gen/mpeg2_dc11_q1"), + require("@tests/gen/mpeg2_motion"), + require("@tests/gen/mpeg2_odd_ilace"), + require("@tests/gen/mpeg2_c422"), + require("@tests/gen/mpeg2_c422_ilace"), + require("@tests/gen/mpeg2_dualprime"), +} + +local t = T.suite("codecs/mpeg2") +local rand = T.rng(11) + +local function b64(s: string): buffer + return Base64.decode(s) :: buffer +end + +-- CRC-32 of a plane cropped to w x h from a buffer with stride +local function planeCrc(b: buffer, stride: number, w: number, h: number): number + local row = buffer.create(w * h) + for y = 0, h - 1 do + buffer.copy(row, y * w, b, y * stride, w) + end + return Crc32.of(row) +end + +-- the cropped planes of a frame, as ffmpeg writes them (w x h luma, ceil(w / 2) x (h or ceil(h / 2)) chroma) +local function crcs(f: any): (number, number, number) + local w, h = f.width, f.height + local cw = (w + 1) // 2 + local ch = if f.chroma == 2 then h else (h + 1) // 2 + local chw = f.codedWidth // 2 + return planeCrc(f.y, f.codedWidth, w, h), planeCrc(f.cb, chw, cw, ch), planeCrc(f.cr, chw, cw, ch) +end + +-- differing samples between a frame's luma and a reference yuv frame (debug detail on a mismatch) +local function lumaDiff(f: any, ref: buffer): (number, number) + local n, first = 0, -1 + for y = 0, f.height - 1 do + for x = 0, f.width - 1 do + if buffer.readu8(f.y, y * f.codedWidth + x) ~= buffer.readu8(ref, y * f.width + x) then + n += 1 + if first < 0 then + first = y * 65536 + x + end + end + end + end + return n, first +end + +local function decodeUnits(fx: any, file: buffer): { any } + local dec = Mpeg2.new({ reorder = true, rgba = false }) + local out = {} + local function take(f: any) + local y, u, v = crcs(f) + -- the 16-line luma bands now: the planes belong to the decoder + local bands = {} + for b = 0, (f.height + 15) // 16 - 1 do + local rows = math.min(16, f.height - b * 16) + local buf = buffer.create(f.width * rows) + for r = 0, rows - 1 do + buffer.copy(buf, r * f.width, f.y, (b * 16 + r) * f.codedWidth, f.width) + end + bands[b] = Crc32.of(buf) + end + table.insert(out, { y, u, v, f, bands }) + end + for i, u in fx.units do + local f = dec:decode(file, u[1], u[2], i) + while f do + take(f) + f = dec:decode(file, 0, 0, i) + end + end + while true do + local f = dec:flush() + if not f then + break + end + take(f) + end + return out +end + +-- 1. every stream against ffmpeg, bit-exact. ffmpeg's encoder sometimes ends a B-picture slice before the row's last +-- macroblock (invalid MPEG-2); both decoders conceal the gap, ffmpeg with its error-resilience guesses and deblocking. +-- Frames with concealed macroblocks compare every 16-line luma band but those and their neighbours. +local total, concealedFrames = 0, 0 +for _, fx in STREAMS do + local name = fx.name + local file = b64(fx.file) + local t0 = os.clock() + local got = decodeUnits(fx, file) + local dt = os.clock() - t0 + t:eq(#got, fx.frames, name .. ": frame count") + local bad, msg = 0, "" + for k, ref in fx.crcs do + local g = got[k] + if g and (g[1] ~= ref[1] or g[2] ~= ref[2] or g[3] ~= ref[3]) then + local f = g[4] + local ok = next(f.concealed) ~= nil + if ok then + concealedFrames += 1 + for band, crc in fx.bands[k] do + local b = band - 1 + if not (f.concealed[b] or f.concealed[b - 1] or f.concealed[b + 1]) then + ok = ok and g[5][b] == crc + end + end + end + if not ok then + bad += 1 + if bad == 1 then + local detail = "" + if k == 1 and #got == 1 then + local n, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer) + detail = string.format(" (%d luma samples differ, first at %d,%d)", n, first % 65536, first // 65536) + end + msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType, + tostring(g[1] == ref[1]), tostring(g[2] == ref[2]), tostring(g[3] == ref[3]), detail) + end + end + end + end + t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg) + local f1 = got[1] and got[1][4] + if f1 then + t:check(f1.mpeg2 == true, name .. ": mpeg2 flag") + t:eq(f1.chroma, fx.chroma, name .. ": chroma format") + end + total += #got + t:note(" %-12s %4dx%-4d %s %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height, + if fx.chroma == 2 then "4:2:2" else "4:2:0", #got, #got / dt) +end + +-- 2. interlace flags +do + local got = decodeUnits(STREAMS[2], b64(STREAMS[2].file)) + t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == true, "tff: interlaced, top field first") + got = decodeUnits(STREAMS[3], b64(STREAMS[3].file)) + t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == false, "bff_alt: bottom field first") + got = decodeUnits(STREAMS[1], b64(STREAMS[1].file)) + t:check(got[1][4].progressive == true, "prog: progressive") +end + +-- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit +for _, idx in { 2, 9 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + local want = decodeUnits(fx, file) + local dec = Mpeg2.new({ reorder = true, rgba = false }) + local p, k, ok = 0, 0, true + local n = buffer.len(file) + local function check(f: any) + k += 1 + local y, u, v = crcs(f) + local ref = want[k] + ok = ok and ref ~= nil and y == ref[1] and u == ref[2] and v == ref[3] + end + while p < n do + local len = math.min(n - p, 1 + rand(5000)) + dec:write(file, p, len) + p += len + while true do + local f = dec:decodeFrame() + if not f then + break + end + check(f) + end + end + while true do + local f = dec:flush() + if not f then + break + end + check(f) + end + t:check(ok and k == fx.frames, string.format("%s: random pieces give the same %d frames (%d)", fx.name, fx.frames, k)) +end + +-- 4. frameImage: yuv420p (4:2:2 converted), rgba8 +do + local fx = STREAMS[9] + local dec = Mpeg2.new({ reorder = false, rgba = true }) + local file = b64(fx.file) + local f = dec:decode(file, fx.units[1][1], fx.units[1][2]) + t:check(f ~= nil and f.pixels ~= nil, "c422: rgba frame") + if f then + local img = Mpeg2.frameImage(f) + t:check(img ~= nil and img.format == "yuv420p" and img.width == fx.width, "c422: frameImage yuv420p") + if img then + local cw, ch = (fx.width + 1) // 2, (fx.height + 1) // 2 + t:eq(buffer.len(img.pixels), fx.width * fx.height + 2 * cw * ch, "c422: yuv420p size") + t:eq(img.meta.source.format, "mpeg2", "c422: meta.source.format") + t:eq(img.meta.source.chroma, "422", "c422: meta.source.chroma") + end + local rgba = Mpeg2.frameImage(f, true) + t:check(rgba ~= nil and rgba.format == "rgba8", "c422: frameImage rgba8") + end + t:check(Mpeg2.frameImage({} :: any) == nil, "frameImage of a non-frame is nil") +end + +-- 5. the registry's decoder (packets = access units), display order with pts +do + t:check(Video.fromFourcc("mpg2") == "mpeg2" and Video.fromMatroska("V_MPEG2") == "mpeg2", "registry names") + t:check(Video.canDecode("mpeg2") and Video.canDecode("mpeg1"), "registry decoders") + local fx = STREAMS[1] + local file = b64(fx.file) + local want = decodeUnits(fx, file) + local dec = assert(Video.decoder({ id = 1, kind = "video", codec = "mpeg2", timescale = 25 } :: any)) + local frames, order = 0, true + local last = -1 + for i, u in fx.units do + local d = buffer.create(u[2]) + buffer.copy(d, 0, file, u[1], u[2]) + dec:decode({ track = 1, pts = i, keyframe = false, data = d } :: any) + while true do + local img, pts = dec:receive() + if not img then + break + end + frames += 1 + local ref = want[frames] + local w, h = fx.width, fx.height + order = order and ref ~= nil and Crc32.of(img.pixels, 0, w * h) == ref[1] and img.meta.yuv ~= nil + last = pts or last + end + end + dec:flush() + while dec:receive() do + frames += 1 + end + t:eq(frames, fx.frames, "registry decoder: frame count") + t:check(order, "registry decoder: frames in display order, equal to the codec's") +end + +-- 6. robustness: truncated units, bit flips, garbage (never throws), and the fuzz pass +do + local samples = {} + for _, idx in { 1, 2, 9, 11 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + local n = math.min(buffer.len(file), 60000) + local b = buffer.create(n) + buffer.copy(b, 0, file, 0, n) + table.insert(samples, b) + end + local threw = 0 + for round = 1, 12 do + local src = samples[1 + round % #samples] + local b = buffer.create(buffer.len(src)) + buffer.copy(b, 0, src) + for _ = 1, 20 do + local i = rand(buffer.len(b)) + buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8)))) + end + local ok = pcall(function() + local dec = Mpeg2.new({ reorder = true }) + dec:write(b) + while dec:decodeFrame() do + end + while dec:flush() do + end + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "corrupted streams never throw") + t:fuzz("decode", function(b: buffer) + local dec = Mpeg2.new({ reorder = true }) + dec:write(b) + local f = dec:decodeFrame() + while f do + f = dec:decodeFrame() + end + return dec:flush() + end, samples, { mutations = 60, garbage = 10 }) +end + +t:note(" %d frames bit-exact with ffmpeg -idct int (%d with concealed macroblocks: compared outside them)", total, concealedFrames) +t:done() diff --git a/tools/fixtures/mpeg2.py b/tools/fixtures/mpeg2.py new file mode 100644 index 0000000..b9e1f00 --- /dev/null +++ b/tools/fixtures/mpeg2.py @@ -0,0 +1,178 @@ +# MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder +# (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the +# alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and +# chroma matrices, large motion (f_code > 1), odd sizes, B-frames) and from mjpegtools' mpeg2enc (dual-prime +# prediction in interlaced frame pictures), each with `ffmpeg -idct int` decoding as the reference: the IJG integer +# IDCT that codecs/video/Dsp reproduces, so the planes must match exactly. +# tests/gen/mpeg2_.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64), +# units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of +# every frame's cropped planes, display order), bands = { { crc } } (per frame, of +# each 16-line luma band), first / last = the yuv frame (base64 zlib) } +# tests/gen/mpeg2_containers.luau the prog stream in MPEG-TS (stream type 0x02, and patched to 0x80), MPEG-PS, +# Matroska and AVI, base64, with the stream's crcs +# tests/gen/mpeg2_bench.luau { { width, height, file, units } }: 720x576 interlaced (DVD-like) for tools/bench.luau +import base64, os, shutil, subprocess, tempfile, zlib + + +def b64(b): + return base64.b64encode(b).decode() + + +def z64(b): + return base64.b64encode(zlib.compress(b, 9)).decode() + + +FF = ["-hide_banner", "-loglevel", "error", "-y"] +ENC = ["-c:v", "mpeg2video", "-f", "mpeg2video"] +ILACE = ["-flags", "+ilme+ildct"] +CHROMA_INTRA = ",".join(str(8 + (i // 8) * 2 + (i % 8)) for i in range(64)) +INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64)) +INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64)) + + +def src(kind, w, h, t, rate=25, vf=None): + s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate) + if vf: + s += "," + vf + return ["-f", "lavfi", "-i", s, "-t", str(t)] + + +# name: (ffmpeg input + encoder args, chroma) +CASES = { + "prog": (src("testsrc2", 352, 288, 0.8) + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1), + "tff": (src("mandelbrot", 352, 288, 0.8, vf="setfield=tff") + ILACE + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1), + "bff_alt": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.01:v=0.02,setfield=bff") + ILACE + ["-alternate_scan", "1", + "-b:v", "1500k", "-bf", "1", "-g", "9"], 1), + "tools": (src("mandelbrot", 320, 240, 0.6) + ["-intra_vlc", "1", "-non_linear_quant", "1", "-qmax", "28", "-dc", "10", "-b:v", "1500k", + "-bf", "2", "-g", "8"], 1), + "dc9_matrix": (src("testsrc2", 176, 144, 0.6) + ["-dc", "9", "-intra_matrix", INTRA, "-inter_matrix", INTER, + "-b:v", "800k", "-bf", "1", "-g", "6"], 1), + "dc11_q1": (src("mandelbrot", 176, 144, 0.32) + ["-dc", "11", "-q:v", "1", "-qmin", "1", "-bf", "0", "-g", "4"], 1), + "motion": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.04:v=0.03") + ["-b:v", "3M", "-bf", "3", "-g", "15"], 1), + "odd_ilace": (src("testsrc2", 346, 258, 0.48) + ILACE + ["-b:v", "1500k", "-bf", "2", "-g", "6"], 1), + "c422": (src("mandelbrot", 352, 288, 0.48) + ["-pix_fmt", "yuv422p", "-b:v", "3M", "-bf", "2", "-g", "6", + "-chroma_intra_matrix", CHROMA_INTRA], 2), + "c422_ilace": (src("testsrc2", 320, 240, 0.48, vf="scroll=h=0.02,setfield=tff") + ["-pix_fmt", "yuv422p"] + ILACE + + ["-alternate_scan", "1", "-b:v", "3M", "-bf", "1", "-g", "6"], 2), +} + + +def access_units(es): + # one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start + starts = [] + i = 0 + pending = None + while True: + i = es.find(b"\x00\x00\x01", i) + if i < 0 or i + 3 >= len(es): + break + code = es[i + 3] + if code in (0xB3, 0xB8) and pending is None: + pending = i + elif code == 0x00: + starts.append(pending if pending is not None else i) + pending = None + i += 3 + return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)] + + +def generate(ctx): + ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip() + ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe") + + def ff(args): + subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True) + + def size(path): + r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", + "-of", "csv=p=0", path], check=True, capture_output=True) + return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2]) + + def reference(path, chroma): + out = path + ".yuv" + ff(["-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo", + "-pix_fmt", "yuv422p" if chroma == 2 else "yuv420p", out]) + return open(out, "rb").read() + + def emit(name, es, path, chroma): + w, h = size(path) + yuv = reference(path, chroma) + cw, ch = (w + 1) // 2, (h if chroma == 2 else (h + 1) // 2) + fs = w * h + 2 * cw * ch + n = len(yuv) // fs + crcs, bands = [], [] + for k in range(n): + f = yuv[k * fs:(k + 1) * fs] + crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])]) + bands.append([zlib.crc32(f[y * w:min(h, y + 16) * w]) for y in range(0, h, 16)]) + ctx.emit("mpeg2_" + name, { + "name": name, "width": w, "height": h, "chroma": chroma, "frames": n, "file": b64(es), + "units": access_units(es), "crcs": crcs, "bands": bands, "first": z64(yuv[:fs]), "last": z64(yuv[(n - 1) * fs:n * fs]), + }) + return crcs + + with tempfile.TemporaryDirectory(prefix="formats-mpeg2-") as tmp: + crcs = {} + for name, (args, chroma) in CASES.items(): + path = os.path.join(tmp, name + ".m2v") + ff(args + ENC + [path]) + crcs[name] = emit(name, open(path, "rb").read(), path, chroma) + + # mjpegtools' mpeg2enc: interlaced frame pictures with dual-prime prediction (P only, as dual prime requires) + y4m = os.path.join(tmp, "src.y4m") + ff(src("mandelbrot", 352, 288, 0.6) + ["-vf", "setfield=tff", "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", y4m]) + dp = os.path.join(tmp, "dualprime.m2v") + ctx.nix("mjpegtools", ["sh", "-c", "mpeg2enc -v 0 -f 3 -I 1 --dualprime-mpeg2 -R 0 -b 2500 -g 9 -G 9 -o '%s' < '%s'" + % (dp, y4m)]) + emit("dualprime", open(dp, "rb").read(), dp, 1) + + # the prog stream in the containers (stream copy) + prog = os.path.join(tmp, "prog.m2v") + cont = {"crcs": crcs["prog"]} + for fmt, ext in (("mpegts", "ts"), ("vob", "mpg"), ("matroska", "mkv"), ("avi", "avi")): + out = os.path.join(tmp, "prog." + ext) + ff(["-fflags", "+genpts", "-r", "25", "-i", prog, "-c", "copy", "-f", fmt, out]) + cont[ext] = b64(open(out, "rb").read()) + # stream type 0x80 (private / DigiCipher II video): the PMT's 0x02 entry patched, its CRC redone + ts = bytearray(base64.b64decode(cont["ts"])) + patched = False + for p in range(0, len(ts), 188): + pkt = ts[p:p + 188] + if pkt[0] != 0x47 or not (pkt[1] & 0x40): + continue + pid = ((pkt[1] & 0x1F) << 8) | pkt[2] + if pid == 0 or pid == 0x11 or pkt[3] & 0x20: + continue + o = p + 5 + pkt[4] + if ts[o] != 0x02: # table_id of a PMT + continue + slen = ((ts[o + 1] & 0x0F) << 8) | ts[o + 2] + pinfo = ((ts[o + 10] & 0x0F) << 8) | ts[o + 11] + e = o + 12 + pinfo + while e < o + 3 + slen - 4: + if ts[e] == 0x02: + ts[e] = 0x80 + patched = True + e += 5 + (((ts[e + 3] & 0x0F) << 8) | ts[e + 4]) + crc = zlib_crc32_mpeg(bytes(ts[o:o + 3 + slen - 4])) + ts[o + 3 + slen - 4:o + 3 + slen] = crc.to_bytes(4, "big") + assert patched, "mpeg2: no PMT entry patched" + cont["ts80"] = b64(bytes(ts)) + ctx.emit("mpeg2_containers", cont) + + bench = [] + path = os.path.join(tmp, "bench.m2v") + ff(src("mandelbrot", 720, 576, 1.0) + ILACE + ["-b:v", "6M", "-bf", "2", "-g", "12"] + ENC + [path]) + es = open(path, "rb").read() + bench.append({"width": 720, "height": 576, "file": b64(es), "units": access_units(es)}) + ctx.emit("mpeg2_bench", bench) + + +def zlib_crc32_mpeg(data): + # CRC-32/MPEG-2: poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor + crc = 0xFFFFFFFF + for b in data: + crc ^= b << 24 + for _ in range(8): + crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF + return crc