diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d612dc3..18cd04e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -133,6 +133,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - 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: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. + - codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. - 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: 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). diff --git a/src/Formats/codecs/video/Dsp.luau b/src/Formats/codecs/video/Dsp.luau index 02b875d..f632ed7 100644 --- a/src/Formats/codecs/video/Dsp.luau +++ b/src/Formats/codecs/video/Dsp.luau @@ -17,6 +17,7 @@ -- 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, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block +-- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+) -- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE) local Dsp = {} @@ -692,6 +693,34 @@ function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride end end +-- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1: +-- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst. +function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number) + if hx == 0 and hy == 0 then + Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) + return + end + local dx = if hx == 0 then sStride else 1 -- the second sample of a two-tap average + for _ = 1, h do + for i = 0, w - 4, 4 do + local p + if hx == 0 or hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + dx) + p = band(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 + sStride), readu32(src, sOff + i + sStride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x01010101 + 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 + writeu32(dst, dOff + i, p) + end + 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). diff --git a/src/Formats/codecs/video/H263/Decoder.luau b/src/Formats/codecs/video/H263/Decoder.luau new file mode 100644 index 0000000..b5b33f0 --- /dev/null +++ b/src/Formats/codecs/video/H263/Decoder.luau @@ -0,0 +1,827 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T +-- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark). +-- +-- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats, +-- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers +-- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion +-- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the +-- PLUSPTYPE form with its reversible MVD codes and unlimited range) and the extended escape of Annex T. Sorenson Spark +-- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit +-- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message): +-- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures, +-- advanced intra coding, the deblocking filter, slice structure, reference picture selection / resampling, reduced +-- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape). +-- +-- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL| +-- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read +-- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int` +-- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors). +-- +-- local core = D.new(flv, maxPixels) +-- local hdr, msg = D.header(buf, off, len, flv, core.opp) -- the picture header (no decoding) +-- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned) +-- core.reset() -- forget the reference (after a seek) +local Tb = require("@formats/codecs/video/H263/Tables") +local Dsp = require("@formats/codecs/video/Dsp") + +local readu8 = buffer.readu8 +local readu32 = buffer.readu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local bfill = buffer.fill +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 mcNoRound = Dsp.mcNoRound +local edge = Dsp.edge + +local MCBPC_I = Tb.MCBPC_I +local MCBPC_P = Tb.MCBPC_P +local CBPY = Tb.CBPY +local MVD = Tb.MVD +local TCOEF = Tb.TCOEF +local ZIGZAG = Tb.ZIGZAG +local DQUANT = Tb.DQUANT +local STUFFING = Tb.STUFFING +local ESCAPE = Tb.ESCAPE + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2.5 KB, the end check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 + +-- the PLUSPTYPE options that persist while UFEP = 0 +export type Opp = { + format: number, + customPcf: boolean, + umv: boolean, + options: string?, -- the unsupported options set, or nil + width: number, + height: number, +} + +export type Header = { + flv: boolean, + version: number, -- Sorenson Spark: 0 (H.263 escapes) or 1 (7 / 11-bit escapes) + tr: number, -- temporal reference + width: number, + height: number, + ptype: number, -- 1 I, 2 P + disposable: boolean, -- Sorenson: a P picture nothing predicts from + quant: number, + umv: boolean, -- unrestricted vectors, baseline form (long vectors) + umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form + rounding: number, -- RTYPE (0: half-sample averages round up) + plus: boolean, -- PLUSPTYPE + cpm: boolean, + deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg) + aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen) + aspectNum: number?, + aspectDen: number?, + opp: Opp?, -- the PLUSPTYPE options in force + bitPos: number, -- absolute bit position of the first macroblock +} + +export type Store = { + y: buffer, + cb: buffer, + cr: buffer, + ls: number, -- luma stride (16 * macroblock columns); chroma stride ls / 2 + w: number, + h: number, + ptype: number, + tr: number, + disposable: boolean, +} + +-- ------------------------------------------------------------------------------------------------ header +-- n (<= 24) bits at bit position p of buf, zeros past endByte +local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number + local v = 0 + for k = p, p + n - 1 do + local byte = rshift(k, 3) + local b = if byte < endByte then readu8(buf, byte) else 0 + v = v * 2 + band(rshift(b, 7 - band(k, 7)), 1) + end + return v +end + +-- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson: +-- 17 bits 0..01 and version 0 / 1), or -1 +local function findStart(buf: buffer, off: number, len: number, flv: boolean): number + local mask = if flv then 0xF8 else 0xFC + for i = off, off + len - 3 do + if readu8(buf, i) == 0 and readu8(buf, i + 1) == 0 and band(readu8(buf, i + 2), mask) == 0x80 then + return i + end + end + return -1 +end + +-- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in +-- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them) +function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?) + if off < 0 or len < 0 or off + len > buffer.len(buf) then + return nil, "bad range" + end + local s = findStart(buf, off, len, flv) + if s < 0 then + return nil, "no picture start code" + end + local e = off + len + local p = s * 8 + local function bits(n: number): number + local v = bitsAt(buf, e, p, n) + p += n + return v + end + local h: Header = { + flv = flv, + version = 0, + tr = 0, + width = 0, + height = 0, + ptype = 1, + disposable = false, + quant = 1, + umv = false, + umvPlus = false, + rounding = 0, + plus = false, + cpm = false, + deblock = false, + bitPos = 0, + } + if flv then + bits(17) + h.version = bits(5) + h.tr = bits(8) + local size = bits(3) + if size == 0 then + h.width, h.height = bits(8), bits(8) + elseif size == 1 then + h.width, h.height = bits(16), bits(16) + elseif size <= 6 then + local d = Tb.FLV_SIZES[size] + h.width, h.height = d[1], d[2] + else + return nil, "reserved picture size" + end + local t = bits(2) + if t == 3 then + return nil, "reserved picture type" + end + h.ptype = if t == 0 then 1 else 2 + h.disposable = t == 2 + h.deblock = bits(1) == 1 + h.quant = bits(5) + else + bits(22) + h.tr = bits(8) + if bits(1) ~= 1 or bits(1) ~= 0 then + return nil, "bad PTYPE" + end + bits(3) -- split screen, document camera, freeze picture release + local format = bits(3) + if format >= 1 and format <= 5 then + local d = Tb.FORMATS[format] + h.width, h.height = d[1], d[2] + h.ptype = bits(1) + 1 + h.umv = bits(1) == 1 + local sac, ap, pb = bits(1), bits(1), bits(1) + if sac == 1 then + return nil, "unsupported: syntax-based arithmetic coding" + elseif ap == 1 then + return nil, "unsupported: advanced prediction mode" + elseif pb == 1 then + return nil, "unsupported: PB-frames" + end + h.quant = bits(5) + h.cpm = bits(1) == 1 + if h.cpm then + bits(2) + end + elseif format == 7 then + h.plus = true + local ufep = bits(3) + local o: Opp + if ufep == 1 then + local f = bits(3) + local pcf, umv = bits(1) == 1, bits(1) == 1 + local names: { string } = { "syntax-based arithmetic coding", "advanced prediction", "advanced intra coding", + "deblocking filter", "slice structure", "reference picture selection", "independent segment decoding", + "alternative inter VLC", "modified quantisation" } + local unsup: string? = nil + for i = 1, 9 do + if bits(1) == 1 and not unsup then + unsup = names[i] + end + end + bits(4) -- 1 000 + o = { format = f, customPcf = pcf, umv = umv, options = unsup, width = 0, height = 0 } + elseif ufep == 0 and opp then + o = opp + else + return nil, if ufep == 0 then "PLUSPTYPE without the options (UFEP 0 first)" else "bad UFEP" + end + local t = bits(3) + if t ~= 0 and t ~= 1 then + return nil, "unsupported: " .. ({ "", "improved PB-frames", "B-pictures", "EI-pictures", "EP-pictures", "reserved", "reserved" })[t] .. " picture type" + end + h.ptype = t + 1 + local rpr, rru = bits(1), bits(1) + h.rounding = bits(1) + bits(3) -- 0 0 1 + if rpr == 1 then + return nil, "unsupported: reference picture resampling" + elseif rru == 1 then + return nil, "unsupported: reduced-resolution update" + end + local unsupported = o.options + if unsupported ~= nil then + return nil, "unsupported: " .. unsupported + end + h.cpm = bits(1) == 1 + if h.cpm then + bits(2) + end + if ufep == 1 then + if o.format == 6 then + local par = bits(4) + o.width = (bits(9) + 1) * 4 + bits(1) + o.height = bits(9) * 4 + h.aspect = par + if par == 15 then + h.aspectNum, h.aspectDen = bits(8), bits(8) + end + elseif o.format >= 1 and o.format <= 5 then + local d = Tb.FORMATS[o.format] + o.width, o.height = d[1], d[2] + else + return nil, "bad source format " .. o.format + end + if o.customPcf then + bits(8) -- clock conversion code, clock divisor + end + end + if o.customPcf then + bits(2) -- ETR + end + if ufep == 1 and o.umv then + if bits(1) == 0 then + bits(1) + end + end + h.width, h.height = o.width, o.height + h.umvPlus = o.umv + h.opp = o + else + return nil, "bad source format " .. format + end + h.quant = if h.plus then bits(5) else h.quant + end + -- PEI / PSPARE + local guard = 0 + while bits(1) == 1 do + bits(8) + guard += 1 + if guard > 256 then + return nil, "PSPARE without end" + end + end + if h.quant == 0 then + return nil, "QUANT 0" + end + if h.width < 1 or h.height < 1 then + return nil, "empty picture size" + end + if p > e * 8 then + return nil, "truncated picture header" + end + h.bitPos = p + return h, nil +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Core = { + decode: (buf: buffer, off: number, len: number) -> (Store?, string?), + reset: () -> (), + state: { + width: number, + height: number, + pictures: number, + errors: number, + header: Header?, + opp: Opp?, + maxPixels: number, + }, +} + +function D.new(flv: boolean, maxPixels: number?): Core + local state = { + width = 0, + height = 0, + pictures = 0, + errors = 0, + header = nil :: Header?, + opp = nil :: Opp?, + maxPixels = maxPixels or 4096 * 2304, + } + -- bitstream + local data = buffer.create(64 * 1024 + PAD) + local endBits = 0 + local pos = 0 + local err = false + -- picture + local W, H = 0, 0 + local mbW, mbH = 0, 0 + local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights + local stores: { Store } = {} + local ref: Store? = nil + local curY, curCb, curCr = data, data, data + local refY, refCb, refCr = data, data, data + local quant = 1 + local escFlv = false -- Sorenson version 1 escapes + local longMv = false + local umvPlus = false + local mcf = mc + local mvX, mvY = {} :: { number }, {} :: { number } -- the current row's vectors (half samples) + local upX, upY = {} :: { number }, {} :: { number } -- the row above + local blk = buffer.create(256) + local EDGE = buffer.create(Dsp.EDGE_SIZE) + + local function read(n: number): 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 + pos += n + return rshift(w, 32 - n) + end + + 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 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) + end + + local function alloc(w: number, h: number) + W, H = w, h + mbW, mbH = (w + 15) // 16, (h + 15) // 16 + ls, cs, lh, chh = mbW * 16, mbW * 8, mbH * 16, mbH * 8 + stores = {} + for i = 1, 2 do + local y = buffer.create(ls * lh) + local cb = buffer.create(cs * chh) + local cr = buffer.create(cs * chh) + bfill(cb, 0, 128) + bfill(cr, 0, 128) + stores[i] = { y = y, cb = cb, cr = cr, ls = ls, w = w, h = h, ptype = 0, tr = 0, disposable = false } + end + mvX, mvY, upX, upY = table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0) + ref = nil + state.width, state.height = w, h + end + + -- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's + -- coefficients added to the prediction already in dst + local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean + local i = 0 + local dcOnly = true + if intra then + local v = read(8) + if v == 255 then + v = 128 + end + writei32(blk, 0, v * 8) + i = 1 + end + if coded then + local q2 = quant * 2 + local qadd = if quant % 2 == 1 then quant else quant - 1 + while true do + 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(TCOEF, rshift(w, 20) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + local last, run, level + if v == ESCAPE then + -- the escape and the 25 (H.263) / 22 or 26 (Sorenson v1) bits after it, all inside w's next bits + if escFlv then + local is11 = band(rshift(w, 24), 1) + last = band(rshift(w, 23), 1) + run = band(rshift(w, 17), 63) + if is11 == 1 then + level = band(rshift(w, 6), 2047) + if level >= 1024 then + level -= 2048 + end + pos += 7 + 1 + 7 + 11 + else + level = band(rshift(w, 10), 127) + if level >= 64 then + level -= 128 + end + pos += 7 + 1 + 7 + 7 + end + else + last = band(rshift(w, 24), 1) + run = band(rshift(w, 18), 63) + level = band(rshift(w, 10), 255) + pos += 7 + 1 + 6 + 8 + if level == 128 then + -- the extended escape (Annex T): 5 low bits, then 6 signed high bits + local x = read(11) + level = band(x, 31) + (rshift(x, 5) - (if x >= 1024 then 64 else 0)) * 32 + elseif level > 128 then + level -= 256 + end + end + if level == 0 then + err = true + return false + end + else + last = rshift(v, 10) + run = band(rshift(v, 4), 63) + level = band(v, 15) + if band(w, lshift(1, 31 - l)) ~= 0 then + level = -level + end + pos += l + 1 + end + i += run + if i > 63 then + err = true + return false + end + local rec = if level > 0 then level * q2 + qadd else level * q2 - qadd + -- not the -2048..2047 saturation of H.263 6.2.1: ffmpeg does not saturate, and encoders write values + -- slightly past it (2055 = 68 * 30 + 15). +-2400 bounds the IDCT output to Dsp's clamp table. + if rec > 2400 then + rec = 2400 + elseif rec < -2400 then + rec = -2400 + end + local z = readu8(ZIGZAG, i) + if z ~= 0 then + dcOnly = false + end + writei32(blk, z * 4, rec) + i += 1 + if last ~= 0 then + break + end + end + elseif not intra then + return true + end + if dcOnly then + local dc = readi32(blk, 0) + writei32(blk, 0, 0) + fillBlock(dst, off, stride, (dc + 4) // 8, not intra) + else + idct(blk, dst, off, stride, not intra) + bfill(blk, 0, 0, 256) + end + return true + end + + -- one motion vector component from its prediction (half samples) + local function motion(pred: number): number + if umvPlus then + -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign + if read(1) == 1 then + return pred + end + local code = 2 + read(1) + local guard = 0 + while read(1) == 1 do + code = code * 2 + read(1) + guard += 1 + if guard > 14 then + err = true + return pred + end + end + local mag = code // 2 + return if code % 2 == 1 then pred - mag else pred + mag + end + local d = vlc(MVD, 12) + if d == 0 then + return pred + end + if read(1) == 1 then + d = -d + end + local v = pred + d + if longMv then + -- Annex D (baseline header): vectors up to +-31.5; the other value of a code pair only past +-16 + if pred < -31 and v < -63 then + v += 64 + elseif pred > 32 and v > 63 then + v -= 64 + end + return v + end + return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 + end + + -- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples + local function predict(col: number, row: number, mx: number, my: number) + local hx, hy = mx % 2, my % 2 + local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2 + local dOff = row * 16 * ls + col * 16 + if sx < 0 or sy < 0 or sx + 16 + hx > ls or sy + 16 + hy > lh then + edge(refY, ls, 0, sx, sy, 16, 16, ls, lh, EDGE) + mcf(EDGE, 32, 0, curY, ls, dOff, 16, 16, hx, hy, false) + else + mcf(refY, ls, sy * ls + sx, curY, ls, dOff, 16, 16, hx, hy, false) + end + -- chroma: the luma position halved, half-sample flags from the quarter positions rounded to halves + local cx, cy = sx // 2, sy // 2 + local chx = if hx == 1 or (mx // 2) % 2 == 1 then 1 else 0 + local chy = if hy == 1 or (my // 2) % 2 == 1 then 1 else 0 + local cOff = row * 8 * cs + col * 8 + if cx < 0 or cy < 0 or cx + 8 + chx > cs or cy + 8 + chy > chh then + edge(refCb, cs, 0, cx, cy, 8, 8, cs, chh, EDGE) + mcf(EDGE, 32, 0, curCb, cs, cOff, 8, 8, chx, chy, false) + edge(refCr, cs, 0, cx, cy, 8, 8, cs, chh, EDGE) + mcf(EDGE, 32, 0, curCr, cs, cOff, 8, 8, chx, chy, false) + else + local so = cy * cs + cx + mcf(refCb, cs, so, curCb, cs, cOff, 8, 8, chx, chy, false) + mcf(refCr, cs, so, curCr, cs, cOff, 8, 8, chx, chy, false) + end + end + + -- a macroblock copied from the reference (not coded, or concealed); mid-grey without one + local function copyMb(col: number, row: number) + local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 + if ref then + mc(refY, ls, yo, curY, ls, yo, 16, 16, 0, 0, false) + mc(refCb, cs, co, curCb, cs, co, 8, 8, 0, 0, false) + mc(refCr, cs, co, curCr, cs, co, 8, 8, 0, 0, false) + else + fillBlock(curY, yo, ls, 128, false) + fillBlock(curY, yo + 8, ls, 128, false) + fillBlock(curY, yo + 8 * ls, ls, 128, false) + fillBlock(curY, yo + 8 * ls + 8, ls, 128, false) + fillBlock(curCb, co, cs, 128, false) + fillBlock(curCr, co, cs, 128, false) + end + end + + -- macroblock (col, row) of a picture (P: an inter picture; top: the first row of the picture or of a GOB with a + -- header, whose vector predictions do not look up). false on bad data. + local function macroblock(col: number, row: number, P: boolean, top: boolean): boolean + if pos > endBits then + return false + end + if P and read(1) == 1 then + copyMb(col, row) + mvX[col + 1], mvY[col + 1] = 0, 0 + return true + end + local lut = if P then MCBPC_P else MCBPC_I + local m = vlc(lut, 9) + while m == STUFFING and not err do + if P and read(1) == 1 then -- stuffing is followed by a new COD in P-pictures + copyMb(col, row) + mvX[col + 1], mvY[col + 1] = 0, 0 + return pos <= endBits + end + if pos > endBits then + return false + end + m = vlc(lut, 9) + end + if err then + return false + end + local mtype, cbpc = m // 4, m % 4 + if mtype == 2 then + err = true -- INTER4V needs advanced prediction (Annex F), which the header refused + return false + end + local intra = mtype >= 3 + local cbpy = vlc(CBPY, 6) + if err then + return false + end + if mtype == 1 or mtype == 4 then + quant = math.clamp(quant + DQUANT[read(2)], 1, 31) + end + local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 + if intra then + mvX[col + 1], mvY[col + 1] = 0, 0 + if not block(true, cbpy >= 8, curY, yo, ls) or not block(true, cbpy % 8 >= 4, curY, yo + 8, ls) + or not block(true, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(true, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls) + or not block(true, cbpc >= 2, curCb, co, cs) or not block(true, cbpc % 2 == 1, curCr, co, cs) then + return false + end + return pos <= endBits + end + cbpy = 15 - cbpy + -- the vector prediction: the median of left, above and above right (outside or past the right edge: 0; the + -- first row of a picture / GOB: the left vector) + local ax = if col > 0 then mvX[col] else 0 + local ay = if col > 0 then mvY[col] else 0 + local px, py = ax, ay + if not top then + local bx, by = upX[col + 1], upY[col + 1] + local cx = if col + 1 < mbW then upX[col + 2] else 0 + local cy = if col + 1 < mbW then upY[col + 2] else 0 + px = math.max(math.min(ax, bx), math.min(math.max(ax, bx), cx)) + py = math.max(math.min(ay, by), math.min(math.max(ay, by), cy)) + end + local mx = motion(px) + local my = motion(py) + if umvPlus and mx - px == 1 and my - py == 1 then + pos += 1 -- start code emulation prevention bit + end + if err then + return false + end + mvX[col + 1], mvY[col + 1] = mx, my + predict(col, row, mx, my) + if not block(false, cbpy >= 8, curY, yo, ls) or not block(false, cbpy % 8 >= 4, curY, yo + 8, ls) + or not block(false, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(false, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls) + or not block(false, cbpc >= 2, curCb, co, cs) or not block(false, cbpc % 2 == 1, curCr, co, cs) then + return false + end + return pos <= endBits + end + + -- an optional GOB header at a GOB boundary (GBSC, after zero stuffing to a byte boundary or not): its GN and + -- GQUANT, or nil + local function gobHeader(cpm: boolean): (number?, number?) + local start = pos + local w = peek32() + if rshift(w, 15) ~= 1 then + local s = (8 - pos % 8) % 8 + if s == 0 or rshift(w, 32 - s) ~= 0 then + return nil, nil + end + pos += s + if rshift(peek32(), 15) ~= 1 then + pos = start + return nil, nil + end + end + pos += 17 + local gn = read(5) + if cpm then + read(2) + end + read(2) -- GFID + return gn, read(5) + end + + local function picture(hdr: Header): (Store?, string?) + if hdr.width ~= W or hdr.height ~= H then + if hdr.width * hdr.height > state.maxPixels then + return nil, "limit: picture size " .. hdr.width .. "x" .. hdr.height + end + alloc(hdr.width, hdr.height) + end + local P = hdr.ptype == 2 + local r = ref + if P and not r then + return nil, "a P picture without a reference picture" + end + local cur = if stores[1] == r then stores[2] else stores[1] + curY, curCb, curCr = cur.y, cur.cb, cur.cr + if r then + refY, refCb, refCr = r.y, r.cb, r.cr + end + quant = hdr.quant + escFlv = hdr.flv and hdr.version == 1 + longMv = hdr.umv + umvPlus = hdr.umvPlus + mcf = if hdr.rounding == 1 then mcNoRound :: any else mc + pos = hdr.bitPos + err = false + local gobRows = if hdr.flv then 0 elseif H <= 400 then 1 elseif H <= 800 then 2 else 4 + local top = 0 -- the first row of the current GOB with a header + local row = 0 + local failAt = -1 + while row < mbH do + if gobRows > 0 and row > 0 and row % gobRows == 0 then + local gn, gq = gobHeader(hdr.cpm) + if gn and gq then + local at = gn * gobRows + if gn == 0 or at >= mbH or at < row or gq == 0 then + failAt = row * mbW + break + end + for k = row * mbW, at * mbW - 1 do -- GOBs missing in between: copied + copyMb(k % mbW, k // mbW) + end + row, top, quant = at, at, gq + end + end + mvX, upX = upX, mvX + mvY, upY = upY, mvY + for col = 0, mbW - 1 do + if not macroblock(col, row, P, row == top) then + failAt = row * mbW + col + break + end + end + if failAt >= 0 then + break + end + row += 1 + end + local msg: string? = nil + if failAt >= 0 then + state.errors += 1 + msg = "bad macroblock data at macroblock " .. failAt + for k = failAt, mbW * mbH - 1 do + copyMb(k % mbW, k // mbW) + end + end + cur.ptype = hdr.ptype + cur.tr = hdr.tr + cur.disposable = hdr.disposable + if not hdr.disposable then + ref = cur + end + state.pictures += 1 + return cur, msg + end + + local core = {} :: Core + core.state = state + + function core.decode(buf: buffer, off: number, len: number): (Store?, string?) + local hdr, herr = D.header(buf, off, len, flv, state.opp) + if not hdr then + state.errors += 1 + return nil, herr + end + state.header = hdr + if hdr.opp then + state.opp = hdr.opp + end + -- the data from the header on, with zero padding + local need = len + PAD + if buffer.len(data) < need then + data = buffer.create(need) + else + bfill(data, len, 0, PAD) + end + buffer.copy(data, 0, buf, off, len) + endBits = len * 8 + hdr.bitPos -= off * 8 + local s, msg = picture(hdr) + hdr.bitPos += off * 8 + return s, msg + end + + function core.reset() + ref = nil + end + + return core +end + +return D diff --git a/src/Formats/codecs/video/H263/Tables.luau b/src/Formats/codecs/video/H263/Tables.luau new file mode 100644 index 0000000..0f427db --- /dev/null +++ b/src/Formats/codecs/video/H263/Tables.luau @@ -0,0 +1,206 @@ +--!strict +-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures, +-- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of +-- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time. +-- +-- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code). +-- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, +-- 4 INTRA+Q), STUFFING for the stuffing code +-- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value) +-- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0) +-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code +local T = {} + +T.STUFFING = 255 +T.ESCAPE = 0xFFFF + +-- builds a K-bit flat table from { bits, value } pairs +local function flat(codes: { { any } }, k: number): buffer + local lut = buffer.create(4 * 2 ^ k) + for _, c in codes do + local bits: string = c[1] + local len = #bits + local code = tonumber(bits, 2) :: number + local shift = k - len + local first = code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, len * 65536 + c[2]) + end + end + return lut +end + +-- table 7: MCBPC for I-pictures (type 3 INTRA, 4 INTRA+Q; CBPC = Cb Cr) +T.MCBPC_I = flat({ + { "1", 3 * 4 + 0 }, + { "001", 3 * 4 + 1 }, + { "010", 3 * 4 + 2 }, + { "011", 3 * 4 + 3 }, + { "0001", 4 * 4 + 0 }, + { "000001", 4 * 4 + 1 }, + { "000010", 4 * 4 + 2 }, + { "000011", 4 * 4 + 3 }, + { "000000001", T.STUFFING }, +}, 9) + +-- table 8: MCBPC for P-pictures +T.MCBPC_P = flat({ + { "1", 0 * 4 + 0 }, + { "0011", 0 * 4 + 1 }, + { "0010", 0 * 4 + 2 }, + { "000101", 0 * 4 + 3 }, + { "011", 1 * 4 + 0 }, + { "0000111", 1 * 4 + 1 }, + { "0000110", 1 * 4 + 2 }, + { "000000101", 1 * 4 + 3 }, + { "010", 2 * 4 + 0 }, + { "0000101", 2 * 4 + 1 }, + { "0000100", 2 * 4 + 2 }, + { "00000101", 2 * 4 + 3 }, + { "00011", 3 * 4 + 0 }, + { "00000100", 3 * 4 + 1 }, + { "00000011", 3 * 4 + 2 }, + { "0000011", 3 * 4 + 3 }, + { "000100", 4 * 4 + 0 }, + { "000000100", 4 * 4 + 1 }, + { "000000011", 4 * 4 + 2 }, + { "000000010", 4 * 4 + 3 }, + { "000000001", T.STUFFING }, +}, 9) + +-- table 13: CBPY (intra values 0..15) +do + local codes = { "0011", "00101", "00100", "1001", "00011", "0111", "000010", "1011", "00010", "000011", "0101", + "1010", "0100", "1000", "0110", "11" } + local list = {} + for i, c in codes do + list[i] = { c, i - 1 } + end + T.CBPY = flat(list, 6) +end + +-- table 14: MVD magnitudes 0, 0.5, 1, ... 16 (in half samples 0..32); the sign bit is not part of these +do + local codes = { "1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", + "000001001", "0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100", "0000001011", + "0000001010", "0000001001", "0000001000", "0000000111", "0000000110", "0000000101", "0000000100", "00000000111", + "00000000110", "00000000101", "00000000100", "00000000011", "00000000010", "000000000011", "000000000010" } + local list = {} + for i, c in codes do + list[i] = { c, i - 1 } + end + T.MVD = flat(list, 12) +end + +-- table 16: TCOEF, per LAST and RUN the codes of levels 1, 2, ... (without the sign bit) +local TCOEF_LAST0: { [number]: { string } } = { + [0] = { "10", "1111", "010101", "0010111", "00011111", "000100101", "000100100", "0000100001", "0000100000", + "00000000111", "00000000110", "00000100000" }, + [1] = { "110", "010100", "00011110", "0000001111", "00000100001", "000001010000" }, + [2] = { "1110", "00011101", "0000001110", "000001010001" }, + [3] = { "01101", "000100011", "0000001101" }, + [4] = { "01100", "000100010", "000001010010" }, + [5] = { "01011", "0000001100", "000001010011" }, + [6] = { "010011", "0000001011", "000001010100" }, + [7] = { "010010", "0000001010" }, + [8] = { "010001", "0000001001" }, + [9] = { "010000", "0000001000" }, + [10] = { "0010110", "000001010101" }, + [11] = { "0010101" }, + [12] = { "0010100" }, + [13] = { "00011100" }, + [14] = { "00011011" }, + [15] = { "000100001" }, + [16] = { "000100000" }, + [17] = { "000011111" }, + [18] = { "000011110" }, + [19] = { "000011101" }, + [20] = { "000011100" }, + [21] = { "000011011" }, + [22] = { "000011010" }, + [23] = { "00000100010" }, + [24] = { "00000100011" }, + [25] = { "000001010110" }, + [26] = { "000001010111" }, +} +local TCOEF_LAST1: { [number]: { string } } = { + [0] = { "0111", "000011001", "00000000101" }, + [1] = { "001111", "00000000100" }, + [2] = { "001110" }, + [3] = { "001101" }, + [4] = { "001100" }, + [5] = { "0010011" }, + [6] = { "0010010" }, + [7] = { "0010001" }, + [8] = { "0010000" }, + [9] = { "00011010" }, + [10] = { "00011001" }, + [11] = { "00011000" }, + [12] = { "00010111" }, + [13] = { "00010110" }, + [14] = { "00010101" }, + [15] = { "00010100" }, + [16] = { "00010011" }, + [17] = { "000011000" }, + [18] = { "000010111" }, + [19] = { "000010110" }, + [20] = { "000010101" }, + [21] = { "000010100" }, + [22] = { "000010011" }, + [23] = { "000010010" }, + [24] = { "000010001" }, + [25] = { "0000000111" }, + [26] = { "0000000110" }, + [27] = { "0000000101" }, + [28] = { "0000000100" }, + [29] = { "00000100100" }, + [30] = { "00000100101" }, + [31] = { "00000100110" }, + [32] = { "00000100111" }, + [33] = { "000001011000" }, + [34] = { "000001011001" }, + [35] = { "000001011010" }, + [36] = { "000001011011" }, + [37] = { "000001011100" }, + [38] = { "000001011101" }, + [39] = { "000001011110" }, + [40] = { "000001011111" }, +} +do + local list = { { "0000011", T.ESCAPE } } + for last = 0, 1 do + local byRun = if last == 0 then TCOEF_LAST0 else TCOEF_LAST1 + for run = 0, 40 do + local levels = byRun[run] + if levels then + for level, c in levels do + table.insert(list, { c, last * 1024 + run * 16 + level }) + end + end + end + end + T.TCOEF = flat(list, 12) + T.TCOEF_COUNT = #list - 1 +end + +-- figure 14: the zigzag scan (scan index -> natural position) +T.ZIGZAG = buffer.create(64) +do + local zz = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, + 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, + 60, 61, 54, 47, 55, 62, 63 } + for i, v in zz do + buffer.writeu8(T.ZIGZAG, i - 1, v) + end +end + +-- table 12: DQUANT (2 bits) -> the change of QUANT +T.DQUANT = { [0] = -1, -2, 1, 2 } + +-- source formats 1..5 (sub-QCIF, QCIF, CIF, 4CIF, 16CIF): width, height +T.FORMATS = { { 128, 96 }, { 176, 144 }, { 352, 288 }, { 704, 576 }, { 1408, 1152 } } + +-- Sorenson Spark picture sizes 2..6 +T.FLV_SIZES = { [2] = { 352, 288 }, [3] = { 176, 144 }, [4] = { 128, 96 }, [5] = { 320, 240 }, [6] = { 160, 120 } } + +return T diff --git a/src/Formats/codecs/video/H263/init.luau b/src/Formats/codecs/video/H263/init.luau new file mode 100644 index 0000000..be23e40 --- /dev/null +++ b/src/Formats/codecs/video/H263/init.luau @@ -0,0 +1,176 @@ +--!strict +-- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. +-- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is +-- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal +-- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures, +-- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter +-- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP +-- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...). +-- +-- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1) +-- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned) +-- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601) +-- local img, err = dec:image(packetData) -- both at once +-- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ... +-- dec:reset() -- after a seek: wait for the next I picture +-- +-- Nothing here throws: bad arguments and bad data come back as nil, Err. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local D = require("@formats/codecs/video/H263/Decoder") + +local H263 = {} + +H263.PICTURE_I = 1 +H263.PICTURE_P = 2 + +export type Header = D.Header + +export type Frame = { + width: number, + height: number, + -- decoder-owned planes, valid until the next decode: luma stride `stride`, chroma stride stride / 2 + y: buffer, + cb: buffer, + cr: buffer, + stride: number, + pictureType: number, -- 1 I, 2 P + keyframe: boolean, + disposable: boolean, -- a Sorenson disposable inter picture (not used as a reference) + temporalReference: number, + index: number, -- pictures returned so far + flv: boolean, +} + +export type Options = { + flv: boolean?, -- Sorenson Spark (FLV1) bitstreams (default false: H.263) + maxPixels: number?, -- larger pictures are refused (LIMIT; default 4096 * 2304) +} + +local Decoder = {} +Decoder.__index = Decoder + +export type Decoder = typeof(setmetatable({} :: { _core: D.Core, _flv: boolean, _count: number, stats: { pictures: number, errors: number } }, Decoder)) + +function H263.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local flv = o.flv == true + local maxPixels = if type(o.maxPixels) == "number" and o.maxPixels > 0 then o.maxPixels else nil + return setmetatable({ _core = D.new(flv, maxPixels), _flv = flv, _count = 0, stats = { pictures = 0, errors = 0 } }, Decoder) +end + +local function span(data: any, off: number?, len: number?): (buffer?, number, number) + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return nil, 0, 0 + end + local total = buffer.len(b) + local o = math.floor(tonumber(off) or 0) + if o < 0 or o > total then + return nil, 0, 0 + end + local n = math.floor(tonumber(len) or (total - o)) + if n < 0 or o + n > total then + return nil, 0, 0 + end + return b, o, n +end + +-- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged +-- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them). +function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?) + local b, o, n = span(data, off, len) + if not b then + return nil, Err.new(Err.ARG, "decode: expected a buffer or string and a valid range") + end + local core = self._core + local s, msg = core.decode(b, o, n) + self.stats.pictures = core.state.pictures + self.stats.errors = core.state.errors + if not s then + return nil, Err.from(msg or "bad picture") + end + self._count += 1 + return { + width = s.w, + height = s.h, + y = s.y, + cb = s.cb, + cr = s.cr, + stride = s.ls, + pictureType = s.ptype, + keyframe = s.ptype == 1, + disposable = s.disposable, + temporalReference = s.tr, + index = self._count, + flv = self._flv, + }, nil +end + +-- decode + frameImage +function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?) + local f, err = self:decode(data, off, len) + if not f then + return nil, err + end + return H263.frameImage(f), nil +end + +-- Forgets the reference picture (after a seek: P pictures fail until the next I picture). +function Decoder.reset(self: Decoder) + self._core.reset() +end + +-- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x +-- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame +function H263.frameImage(frame: Frame): 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, ls = frame.width, frame.height, frame.stride + if type(w) ~= "number" or type(h) ~= "number" or type(ls) ~= "number" or w < 1 or h < 1 or ls < w then + return nil + end + local cw, ch, cs = (w + 1) // 2, (h + 1) // 2, ls // 2 + if buffer.len(frame.y) < ls * h or buffer.len(frame.cb) < cs * ch or buffer.len(frame.cr) < cs * ch then + return nil + end + local 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 * ls, w) + end + local o = w * h + for y = 0, ch - 1 do + buffer.copy(px, o + y * cw, frame.cb, y * cs, cw) + buffer.copy(px, o + cw * ch + y * cw, frame.cr, y * cs, cw) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { + format = if frame.flv then "flv1" else "h263", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + disposable = frame.disposable, + } + return img +end + +-- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err: +-- the first picture header in the data, without decoding (containers use it for the track size) +function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?) + local b, o, n = span(data, off, len) + if not b then + return nil, Err.new(Err.ARG, "header: expected a buffer or string and a valid range") + end + local h, msg = D.header(b, o, n, flv == true, nil) + if not h then + return nil, Err.from(msg or "bad picture header") + end + return h, nil +end + +return H263 diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 6410afb..5ec9500 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -253,6 +253,17 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec return H264.newVideoDecoder(track, opts) end +-- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering +local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local H263 = require("@formats/codecs/video/H263") + local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + return dec:image(data) + end, function() + dec:reset() + end), nil +end + -- ------------------------------------------------------------------------------------------------ registry -- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. local BUILTIN: { Entry } = { @@ -267,6 +278,8 @@ local BUILTIN: { Entry } = { { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, + { id = "h263", name = "H.263", fourcc = { "H263", "h263", "s263", "U263" }, new = h263Decoder }, + { id = "flv1", name = "Sorenson Spark (FLV1)", fourcc = { "FLV1" }, new = h263Decoder }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, } diff --git a/tests/codecs/h263.luau b/tests/codecs/h263.luau new file mode 100644 index 0000000..2e3765a --- /dev/null +++ b/tests/codecs/h263.luau @@ -0,0 +1,244 @@ +-- codecs/video/H263 tests. Against `ffmpeg -idct int` (tools/fixtures/h263.py): H.263 streams (sub-QCIF .. 4CIF, GOB +-- headers, DQUANT, q 1 .. high quantisers), H.263+ PLUSPTYPE streams (custom sizes, sizes that are not a multiple of +-- 16, the rounding type, unrestricted vectors with reversible codes) and Sorenson Spark streams (standard, 8-bit and +-- 16-bit custom sizes, 11-bit escapes, high motion, disposable inter pictures) decode one picture at a time to exactly +-- ffmpeg's planes, every frame; header info; frameImage; the registry's decoders (h263, flv1); unsupported options are +-- UNSUPPORTED; truncated and corrupted pictures never throw; the fuzz no-throw pass. +local T = require("@tests/T") +local H263 = require("@formats/codecs/video/H263") +local Video = require("@formats/codecs/video/Video") +local Err = require("@formats/core/Err") +local Base64 = require("@formats/core/Base64") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/compress/Deflate") + +local STREAMS = { + require("@tests/gen/h263_qcif"), + require("@tests/gen/h263_cif_mandel"), + require("@tests/gen/h263_sqcif_scroll"), + require("@tests/gen/h263_qcif_q1"), + require("@tests/gen/h263_qcif_aq"), + require("@tests/gen/h263_cif_gob"), + require("@tests/gen/h263_4cif_gob"), + require("@tests/gen/h263_plus_custom"), + require("@tests/gen/h263_plus_odd"), + require("@tests/gen/h263_plus_umv"), + require("@tests/gen/h263_flv_320"), + require("@tests/gen/h263_flv_odd"), + require("@tests/gen/h263_flv_wide"), + require("@tests/gen/h263_flv_q1"), + require("@tests/gen/h263_flv_scroll"), + require("@tests/gen/h263_flv_disposable"), +} +local BAD = require("@tests/gen/h263_bad") + +local t = T.suite("codecs/h263") +local rand = T.rng(263) + +local function b64(s: string): buffer + return Base64.decode(s) :: buffer +end + +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 + +local function crcs(f: any): (number, number, number) + local w, h = f.width, f.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + return planeCrc(f.y, f.stride, w, h), planeCrc(f.cb, f.stride // 2, cw, ch), planeCrc(f.cr, f.stride // 2, cw, ch) +end + +-- differing luma samples against a reference frame (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.stride + 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 + +-- 1. every stream against ffmpeg, bit-exact +local total = 0 +local disposables = 0 +for _, fx in STREAMS do + local name = fx.name + local file = b64(fx.file) + local dec = H263.new({ flv = fx.flv }) + local t0 = os.clock() + local bad, n, msg = 0, 0, "" + for k, u in fx.units do + local f, err = dec:decode(file, u[1], u[2]) + if not f then + bad += 1 + if bad == 1 then + msg = string.format(" (first: picture %d: %s)", k, tostring(err)) + end + else + n += 1 + if f.disposable then + disposables += 1 + end + local y, cb, cr = crcs(f) + local ref = fx.crcs[k] + if not ref or y ~= ref[1] or cb ~= ref[2] or cr ~= ref[3] then + bad += 1 + if bad == 1 then + local detail = "" + if k == 1 then + local nd, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer) + detail = string.format(", %d luma samples differ, first at %d,%d", nd, first % 65536, first // 65536) + end + msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType, + tostring(ref and y == ref[1]), tostring(ref and cb == ref[2]), tostring(ref and cr == ref[3]), detail) + end + end + end + end + local dt = os.clock() - t0 + t:eq(n, fx.frames, name .. ": frame count") + t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg) + t:eq(dec.stats.errors, 0, name .. ": no damaged pictures") + total += n + t:note(" %-16s %4dx%-4d %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height, n, n / dt) +end +t:check(disposables > 0, "disposable Sorenson pictures decoded (" .. disposables .. ")") + +-- 2. header info +do + local fx = STREAMS[8] -- plus_custom + local file = b64(fx.file) + local h = assert(H263.header(file, fx.units[1][1], fx.units[1][2])) + t:check(h.plus and h.width == 320 and h.height == 240 and h.ptype == 1, "plus_custom: PLUSPTYPE custom size, I picture") + local h2 = assert(H263.header(file, fx.units[2][1], fx.units[2][2])) + t:check(h2.ptype == 2, "plus_custom: second picture P") + fx = STREAMS[12] -- flv_odd + file = b64(fx.file) + h = assert(H263.header(file, fx.units[1][1], fx.units[1][2], true)) + t:check(h.flv and h.width == 100 and h.height == 75 and h.version == 1, "flv_odd: Sorenson 8-bit custom size, version 1") + fx = STREAMS[1] + h = assert(H263.header(b64(fx.file), 0, fx.units[1][2])) + t:check(not h.plus and h.width == 176 and h.height == 144, "qcif: PTYPE QCIF") + local _, e = H263.header(buffer.create(16)) + t:check(e ~= nil and e.code == Err.CORRUPT, "no start code: CORRUPT") +end + +-- 3. unsupported H.263+ options +for name, data in BAD do + local dec = H263.new() + local f, e = dec:decode(b64(data)) + t:check(f == nil and e ~= nil and e.code == Err.UNSUPPORTED, name .. ": UNSUPPORTED (" .. tostring(e) .. ")") +end + +-- 4. frameImage +do + local fx = STREAMS[12] + local dec = H263.new({ flv = true }) + local file = b64(fx.file) + local f = assert(dec:decode(file, fx.units[1][1], fx.units[1][2])) + local img = assert(H263.frameImage(f)) + t:check(img.format == "yuv420p" and img.width == 100 and img.height == 75, "frameImage: yuv420p 100x75") + t:eq(buffer.len(img.pixels), 100 * 75 + 2 * 50 * 38, "frameImage: plane sizes") + t:eq(Crc32.of(img.pixels, 0, 100 * 75), fx.crcs[1][1], "frameImage: luma equals ffmpeg's") + t:eq(img.meta.yuv.range, "limited", "frameImage: limited range") + t:eq(img.meta.source.format, "flv1", "frameImage: meta.source.format") + t:check(H263.frameImage({} :: any) == nil, "frameImage of a non-frame is nil") + t:check(dec:decode(42 :: any) == nil, "decode of a non-buffer is nil") +end + +-- 5. the registry's decoders +do + t:check(Video.fromFourcc("H263") == "h263" and Video.fromFourcc("s263") == "h263" and Video.fromFourcc("FLV1") == "flv1", "registry names") + t:check(Video.canDecode("h263") and Video.canDecode("flv1"), "registry decoders") + for _, idx in { 2, 13 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + local dec = assert(Video.decoder({ id = 1, kind = "video", codec = if fx.flv then "flv1" else "h263", timescale = 25, width = fx.width, height = fx.height } :: any)) + local frames, same = 0, true + for i, u in fx.units do + local d = buffer.create(u[2]) + buffer.copy(d, 0, file, u[1], u[2]) + local e = dec:decode({ track = 1, pts = i, keyframe = i == 1, data = d } :: any) + t:check(e == nil, fx.name .. ": registry decode " .. tostring(e)) + while true do + local img, pts = dec:receive() + if not img then + break + end + frames += 1 + same = same and pts == i and img.meta.yuv ~= nil and Crc32.of(img.pixels, 0, fx.width * fx.height) == fx.crcs[frames][1] + end + end + t:eq(frames, fx.frames, fx.name .. ": registry frame count") + t:check(same, fx.name .. ": registry frames equal ffmpeg's") + dec:reset() + local p = buffer.create(fx.units[2][2]) + buffer.copy(p, 0, file, fx.units[2][1], fx.units[2][2]) + t:check(dec:decode({ track = 1, pts = 2, keyframe = false, data = p } :: any) ~= nil, fx.name .. ": a P picture after reset is an error") + end +end + +-- 6. robustness: truncated and corrupted pictures, garbage (never throws), the fuzz pass +do + local samples = {} + for _, idx in { 1, 6, 8, 10, 11, 14 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + for k = 1, 2 do + local u = fx.units[k] + local b = buffer.create(u[2]) + buffer.copy(b, 0, file, u[1], u[2]) + table.insert(samples, { b, fx.flv }) + end + end + local threw, damaged = 0, 0 + for round = 1, 40 do + local s = samples[1 + round % #samples] + local src = s[1] + local n = if round % 3 == 0 then rand(buffer.len(src)) else buffer.len(src) + local b = buffer.create(n) + buffer.copy(b, 0, src, 0, n) + for _ = 1, 1 + round % 7 do + local i = 4 + rand(math.max(1, n - 4)) - 1 + if i < n then + buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8) - 1))) + end + end + local ok = pcall(function() + local dec = H263.new({ flv = s[2] }) + dec:decode(src) + dec:decode(b) + dec:decode(b) + damaged += dec.stats.errors + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "corrupted pictures never throw") + t:check(damaged > 0, "corrupted pictures are counted (" .. damaged .. ")") + local fuzz = {} + for _, s in samples do + table.insert(fuzz, s[1]) + end + t:fuzz("decode", function(b: buffer) + local dec = H263.new({ flv = buffer.len(b) > 2 and bit32.band(buffer.readu8(b, 2), 0x04) ~= 0 }) + local f = dec:decode(b) + dec:decode(b) + return f + end, fuzz, { mutations = 40, garbage = 20 }) +end + +t:note(" %d frames bit-exact with ffmpeg -idct int", total) +t:done() diff --git a/tools/fixtures/h263.py b/tools/fixtures/h263.py new file mode 100644 index 0000000..55cb428 --- /dev/null +++ b/tools/fixtures/h263.py @@ -0,0 +1,187 @@ +# H.263 / Sorenson Spark fixtures for codecs/video/H263 (tools/fixtures.py): streams from ffmpeg's encoders (h263: +# sub-QCIF .. 4CIF, GOB headers, adaptive quantisation (DQUANT), low and high bitrates; h263p: PLUSPTYPE with custom +# sizes, the rounding type, unrestricted vectors; flv: Sorenson Spark with its standard, 8-bit and 16-bit custom +# sizes, 11-bit escapes, disposable inter pictures patched in), high and low motion (testsrc2, mandelbrot, scroll), +# each with `ffmpeg -flags +bitexact -idct int` decoding as the reference (the integer IDCT codecs/video/Dsp +# reproduces; bitexact: ffmpeg's x86 half-sample averages without rounding are approximations otherwise). +# tests/gen/h263_.luau { name, flv, width, height, frames, file (base64), units = { { offset, length } } (one +# picture each), crcs = { { y, u, v } } (CRC-32 of each frame's planes), first (the first +# yuv frame, base64 zlib) } +# tests/gen/h263_bad.luau { aic, obmc: one picture each with an unsupported H.263+ option (base64) } +# tests/gen/h263_bench.luau { { name, flv, width, height, file, units } }: CIF H.263 and Sorenson Spark +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"] + + +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)] + + +H263 = ["-c:v", "h263", "-f", "h263"] +H263P = ["-threads", "1", "-c:v", "h263p", "-f", "rawvideo"] +FLV = ["-c:v", "flv", "-f", "flv"] + +# name: (ffmpeg input + encoder args, flv) +CASES = { + "qcif": (src("testsrc2", 176, 144, 1.0) + ["-b:v", "200k", "-g", "12"] + H263, False), + "cif_mandel": (src("mandelbrot", 352, 288, 0.6) + ["-b:v", "800k", "-g", "8"] + H263, False), + "sqcif_scroll": (src("testsrc2", 128, 96, 1.0, vf="scroll=h=0.05:v=0.03") + ["-q:v", "4", "-g", "30"] + H263, False), + "qcif_q1": (src("mandelbrot", 176, 144, 0.4) + ["-qmin", "1", "-q:v", "1", "-g", "5"] + H263, False), + "qcif_aq": (src("testsrc2", 176, 144, 0.8, vf="scroll=h=0.01") + ["-b:v", "60k", "-lumi_mask", "0.3", "-dark_mask", "0.3", + "-p_mask", "0.2", "-g", "20"] + H263, False), + "cif_gob": (src("testsrc2", 352, 288, 0.6, vf="scroll=v=0.02") + ["-b:v", "500k", "-ps", "300", "-g", "10"] + H263, False), + "4cif_gob": (src("mandelbrot", 704, 576, 0.16) + ["-b:v", "2M", "-ps", "1200", "-g", "4"] + H263, False), + "plus_custom": (src("testsrc2", 320, 240, 0.8, vf="scroll=h=0.02:v=0.01") + ["-b:v", "300k", "-g", "15"] + H263P, False), + "plus_odd": (src("mandelbrot", 196, 148, 0.6) + ["-b:v", "250k", "-g", "8"] + H263P, False), + "plus_umv": (src("testsrc2", 200, 152, 0.8, vf="scroll=h=0.06:v=0.04") + ["-umv", "1", "-q:v", "5", "-g", "25"] + H263P, False), + "flv_320": (src("testsrc2", 320, 240, 1.0) + ["-b:v", "300k", "-g", "12"] + FLV, True), + "flv_odd": (src("mandelbrot", 100, 75, 0.6) + ["-b:v", "150k", "-g", "8"] + FLV, True), + "flv_wide": (src("testsrc2", 400, 224, 0.4, vf="scroll=h=0.03") + ["-b:v", "400k", "-g", "6"] + FLV, True), + "flv_q1": (src("mandelbrot", 160, 120, 0.4) + ["-qmin", "1", "-q:v", "1", "-g", "4"] + FLV, True), + "flv_scroll": (src("testsrc2", 176, 144, 1.0, vf="scroll=h=0.05:v=-0.04") + ["-q:v", "6", "-g", "50"] + FLV, True), +} + + +def h263_units(es): + starts = [] + i = 0 + while True: + i = es.find(b"\x00\x00", i) + if i < 0 or i + 2 >= len(es): + break + if es[i + 2] & 0xFC == 0x80: + starts.append(i) + i += 3 + else: + i += 1 + return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)] + + +def flv_tags(data): + """the video tags of an FLV file: [(offset of the tag header, payload offset, payload length)]""" + p = int.from_bytes(data[5:9], "big") + 4 + out = [] + while p + 11 <= len(data): + kind = data[p] & 0x1F + size = int.from_bytes(data[p + 1:p + 4], "big") + if kind == 9 and size > 1: + out.append((p, p + 12, size - 1)) + p += 11 + size + 4 + return out + + +def flv_disposable(data): + """every third inter picture of a Sorenson FLV marked disposable (tag frame type 3, picture type 2)""" + b = bytearray(data) + inter = 0 + for tag, off, n in flv_tags(data): + if b[tag + 11] >> 4 != 2: + continue + inter += 1 + if inter % 3 != 0: + continue + b[tag + 11] = (3 << 4) | (b[tag + 11] & 15) + # picture size field: bits 30..32 after the start of the picture + bits = int.from_bytes(b[off:off + 8], "big") + fmt = (bits >> (64 - 33)) & 7 + p = 33 + (16 if fmt == 0 else 32 if fmt == 1 else 0) # the picture type's first bit + byte, bit = p // 8, p % 8 + word = int.from_bytes(b[off + byte:off + byte + 2], "big") + shift = 16 - bit - 2 + word = (word & ~(3 << shift)) | (2 << shift) + b[off + byte:off + byte + 2] = word.to_bytes(2, "big") + return bytes(b) + + +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): + out = path + ".yuv" + ff(["-flags", "+bitexact", "-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", out]) + return open(out, "rb").read() + + def emit(name, path, flv): + data = open(path, "rb").read() + if flv: + tags = flv_tags(data) + file = b"".join(data[o:o + n] for _, o, n in tags) + units, o = [], 0 + for _, _, n in tags: + units.append([o, n]) + o += n + else: + file, units = data, h263_units(data) + w, h = size(path) + yuv = reference(path) + cw, ch = (w + 1) // 2, (h + 1) // 2 + fs = w * h + 2 * cw * ch + n = len(yuv) // fs + crcs = [] + 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:])]) + assert n == len(units), "h263 %s: %d frames for %d pictures" % (name, n, len(units)) + ctx.emit("h263_" + name, {"name": name, "flv": flv, "width": w, "height": h, "frames": n, "file": b64(file), + "units": units, "crcs": crcs, "first": z64(yuv[:fs])}) + return file, units + + with tempfile.TemporaryDirectory(prefix="formats-h263-") as tmp: + for name, (args, flv) in CASES.items(): + path = os.path.join(tmp, name + (".flv" if flv else ".h263")) + ff(args + [path]) + emit(name, path, flv) + # Sorenson disposable inter pictures (ffmpeg's encoder writes none): patched into a stream; ffmpeg's decoder + # does not keep them as references either + path = os.path.join(tmp, "disp.flv") + ff(src("testsrc2", 160, 120, 1.0, vf="scroll=h=0.02") + ["-b:v", "200k", "-g", "20"] + FLV + [path]) + patched = os.path.join(tmp, "disposable.flv") + open(patched, "wb").write(flv_disposable(open(path, "rb").read())) + emit("flv_disposable", patched, True) + + # unsupported H.263+ options: one picture each + bad = {} + for name, extra in (("aic", ["-flags", "+aic"]), ("obmc", ["-obmc", "1"])): + path = os.path.join(tmp, name + ".h263") + ff(src("testsrc2", 176, 144, 0.04) + extra + H263P + [path]) + bad[name] = b64(open(path, "rb").read()) + ctx.emit("h263_bad", bad) + + bench = [] + for name, args, flv in (("h263", H263, False), ("flv1", FLV, True)): + path = os.path.join(tmp, "bench_" + name + (".flv" if flv else ".h263")) + ff(src("mandelbrot", 352, 288, 1.2) + ["-b:v", "1M", "-g", "12"] + args + [path]) + data = open(path, "rb").read() + if flv: + tags = flv_tags(data) + file = b"".join(data[o:o + n] for _, o, n in tags) + units, o = [], 0 + for _, _, n in tags: + units.append([o, n]) + o += n + else: + file, units = data, h263_units(data) + bench.append({"name": name, "flv": flv, "width": 352, "height": 288, "file": b64(file), "units": units}) + ctx.emit("h263_bench", bench)