From 840f0b12bb3040bd53fa8d2cc3808d47058a6ad6 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:56:27 -0500 Subject: [PATCH 01/19] ws-video2: codecs/video/Dsp (jrevdct IDCT bit-exact with ffmpeg -idct int, shared MC); Mpeg1 uses it MPEG-1 decode is now bit-exact with ffmpeg -idct int (was ~0.6 MAE). ~5% slower on luau (1695 vs 1790 fps at 320x240). The IJG jrevdct.c is IJG-licensed (ffmpeg LICENSE.md), credited in licenses/NOTICE.md. --- licenses/NOTICE.md | 1 + src/Formats/codecs/video/Dsp.luau | 693 ++++++++++++++++++++ src/Formats/codecs/video/Mpeg1/Decoder.luau | 204 +----- 3 files changed, 699 insertions(+), 199 deletions(-) create mode 100644 src/Formats/codecs/video/Dsp.luau diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..76a1a69 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -37,6 +37,7 @@ | `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | +| `src/Formats/codecs/video/Dsp.luau` (the 8x8 IDCT: jrevdct.c translated to Luau, branch tree and constants unchanged) | IJG jrevdct.c as shipped in ffmpeg (libavcodec/jrevdct.c; IJG-licensed, not LGPL: ffmpeg's LICENSE.md) | IJG: [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/codecs/video/Dsp.luau b/src/Formats/codecs/video/Dsp.luau new file mode 100644 index 0000000..f449f53 --- /dev/null +++ b/src/Formats/codecs/video/Dsp.luau @@ -0,0 +1,693 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. +-- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added +-- into 8-bit planes, constant (DC-only) blocks, -- half-pel motion compensation four samples at a time. Native, never throws (the caller keeps offsets in range). +-- +-- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg +-- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then +-- columns, with every sparse-input special case of the original kept, because several of them use merged constants +-- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that +-- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order +-- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for +-- coefficients in the MPEG range), and the put / add clamping fused into the last pass. +-- +-- 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) +local 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 rshift = bit32.rshift + +-- clamp to 0..255 by lookup: CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the IDCT output of MPEG-range +-- coefficients is bounded by 64 * 2048 / 8 * sqrt(2)^2 < COFF, 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 +Dsp.CLAMP = CLAMP +Dsp.COFF = COFF + +-- ------------------------------------------------------------------------------------------------ IDCT +function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) + local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 + local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 + local z1, z2, z3, z4, z5 = 0, 0, 0, 0, 0 + -- pass 1: rows, scaled up by 2^PASS1_BITS + for r = 0, 224, 32 do + local d0 = readi32(blk, r) + local d1 = readi32(blk, r + 4) + local d2 = readi32(blk, r + 8) + local d3 = readi32(blk, r + 12) + local d4 = readi32(blk, r + 16) + local d5 = readi32(blk, r + 20) + local d6 = readi32(blk, r + 24) + local d7 = readi32(blk, r + 28) + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + if d0 ~= 0 then + local v = d0 * 4 + writei32(blk, r, v) + writei32(blk, r + 4, v) + writei32(blk, r + 8, v) + writei32(blk, r + 12, v) + writei32(blk, r + 16, v) + writei32(blk, r + 20, v) + writei32(blk, r + 24, v) + writei32(blk, r + 28, v) + end + else + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z4 = d5 + d1 + z5 = (d7 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 = z2 + z3 + tmp3 += z1 + z4 + else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 += z5 + z4 += z5 + tmp0 += z3 + tmp1 += z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 = z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 += z3 + tmp1 = z2 + z5 + tmp2 += z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 += z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 += z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 = z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 += z2 + tmp2 += z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 += z4 + tmp2 = z2 + z5 + tmp3 += z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 += z5 + tmp3 += z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, r, (tmp10 + tmp3 + 1024) // 2048) + writei32(blk, r + 28, (tmp10 - tmp3 + 1024) // 2048) + writei32(blk, r + 4, (tmp11 + tmp2 + 1024) // 2048) + writei32(blk, r + 24, (tmp11 - tmp2 + 1024) // 2048) + writei32(blk, r + 8, (tmp12 + tmp1 + 1024) // 2048) + writei32(blk, r + 20, (tmp12 - tmp1 + 1024) // 2048) + writei32(blk, r + 12, (tmp13 + tmp0 + 1024) // 2048) + writei32(blk, r + 16, (tmp13 - tmp0 + 1024) // 2048) + end + end + -- pass 2: columns, descaled by 2^(CONST_BITS + PASS1_BITS + 3) + for c = 0, 28, 4 do + local d0 = readi32(blk, c) + local d1 = readi32(blk, c + 32) + local d2 = readi32(blk, c + 64) + local d3 = readi32(blk, c + 96) + local d4 = readi32(blk, c + 128) + local d5 = readi32(blk, c + 160) + local d6 = readi32(blk, c + 192) + local d7 = readi32(blk, c + 224) + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 = z2 + z3 + tmp3 += z1 + z4 + else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 += z5 + z4 += z5 + tmp0 += z3 + tmp1 += z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 = z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 += z3 + tmp1 = z2 + z5 + tmp2 += z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 += z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 += z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 = z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 += z2 + tmp2 += z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 += z4 + tmp2 = z2 + z5 + tmp3 += z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 += z5 + tmp3 += z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, c, (tmp10 + tmp3 + 131072) // 262144) + writei32(blk, c + 224, (tmp10 - tmp3 + 131072) // 262144) + writei32(blk, c + 32, (tmp11 + tmp2 + 131072) // 262144) + writei32(blk, c + 192, (tmp11 - tmp2 + 131072) // 262144) + writei32(blk, c + 64, (tmp12 + tmp1 + 131072) // 262144) + writei32(blk, c + 160, (tmp12 - tmp1 + 131072) // 262144) + writei32(blk, c + 96, (tmp13 + tmp0 + 131072) // 262144) + writei32(blk, c + 128, (tmp13 - tmp0 + 131072) // 262144) + end + -- put / add, clamped + for r = 0, 224, 32 do + local p0 = readi32(blk, r) + COFF + local p1 = readi32(blk, r + 4) + COFF + local p2 = readi32(blk, r + 8) + COFF + local p3 = readi32(blk, r + 12) + COFF + local p4 = readi32(blk, r + 16) + COFF + local p5 = readi32(blk, r + 20) + COFF + local p6 = readi32(blk, r + 24) + COFF + local p7 = readi32(blk, r + 28) + COFF + if add then + p0 += readu8(dst, off) + p1 += readu8(dst, off + 1) + p2 += readu8(dst, off + 2) + p3 += readu8(dst, off + 3) + p4 += readu8(dst, off + 4) + p5 += readu8(dst, off + 5) + p6 += readu8(dst, off + 6) + p7 += readu8(dst, off + 7) + end + writeu32(dst, off, readu8(CLAMP, p0) + readu8(CLAMP, p1) * 256 + readu8(CLAMP, p2) * 65536 + readu8(CLAMP, p3) * 16777216) + writeu32(dst, off + 4, readu8(CLAMP, p4) + readu8(CLAMP, p5) * 256 + readu8(CLAMP, p6) * 65536 + readu8(CLAMP, p7) * 16777216) + off += stride + end +end + +-- ------------------------------------------------------------------------------------------------ blocks +-- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT +-- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere) +function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) + if not add then + local c = readu8(CLAMP, v + COFF) * 0x01010101 + for _ = 1, 8 do + writeu32(dst, off, c) + writeu32(dst, off + 4, c) + off += stride + end + else + for _ = 1, 8 do + for i = off, off + 7 do + writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) + end + off += stride + end + end +end + +-- ------------------------------------------------------------------------------------------------ motion +-- 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 + local p + if hx == 0 then + if hy == 0 then + p = readu32(src, sOff + i) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + end + elseif hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 + local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = h + band(rshift(l, 2), 0x0F0F0F0F) + end + if avg then + local q = readu32(dst, dOff + i) + p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) + end + writeu32(dst, dOff + i, p) + end + sOff += stride + dOff += stride + end +end + +return Dsp diff --git a/src/Formats/codecs/video/Mpeg1/Decoder.luau b/src/Formats/codecs/video/Mpeg1/Decoder.luau index 5fcdb1f..0431576 100644 --- a/src/Formats/codecs/video/Mpeg1/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg1/Decoder.luau @@ -25,6 +25,7 @@ -- 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 @@ -82,205 +83,10 @@ local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } --- Integer IDCT (LL&M factorisation as in the IJG "islow" IDCT: CONST_BITS 13, PASS1_BITS 2) of the 64 i32 --- coefficients in blk (natural order), written to dst (put) or added to it (add), clamped to 0..255. -local function idct(blk: buffer, ws: buffer, dst: buffer, off: number, stride: number, add: boolean) - -- pass 1: columns, into ws scaled by 4 - for c = 0, 28, 4 do - local d0 = readi32(blk, c) - local d1 = readi32(blk, c + 32) - local d2 = readi32(blk, c + 64) - local d3 = readi32(blk, c + 96) - local d4 = readi32(blk, c + 128) - local d5 = readi32(blk, c + 160) - local d6 = readi32(blk, c + 192) - local d7 = readi32(blk, c + 224) - if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then - local dc = d0 * 4 - writei32(ws, c, dc) - writei32(ws, c + 32, dc) - writei32(ws, c + 64, dc) - writei32(ws, c + 96, dc) - writei32(ws, c + 128, dc) - writei32(ws, c + 160, dc) - writei32(ws, c + 192, dc) - writei32(ws, c + 224, dc) - else - -- even part - local z1 = (d2 + d6) * 4433 - local t2 = z1 - d6 * 15137 - local t3 = z1 + d2 * 6270 - local t0 = (d0 + d4) * 8192 - local t1 = (d0 - d4) * 8192 - local t10 = t0 + t3 - local t13 = t0 - t3 - local t11 = t1 + t2 - local t12 = t1 - t2 - -- odd part - local o0, o1, o2, o3 = d7, d5, d3, d1 - local y1 = o0 + o3 - local y2 = o1 + o2 - local y3 = o0 + o2 - local y4 = o1 + o3 - local z5 = (y3 + y4) * 9633 - o0 *= 2446 - o1 *= 16819 - o2 *= 25172 - o3 *= 12299 - y1 *= -7373 - y2 *= -20995 - y3 = y3 * -16069 + z5 - y4 = y4 * -3196 + z5 - o0 += y1 + y3 - o1 += y2 + y4 - o2 += y2 + y3 - o3 += y1 + y4 - writei32(ws, c, (t10 + o3 + 1024) // 2048) - writei32(ws, c + 224, (t10 - o3 + 1024) // 2048) - writei32(ws, c + 32, (t11 + o2 + 1024) // 2048) - writei32(ws, c + 192, (t11 - o2 + 1024) // 2048) - writei32(ws, c + 64, (t12 + o1 + 1024) // 2048) - writei32(ws, c + 160, (t12 - o1 + 1024) // 2048) - writei32(ws, c + 96, (t13 + o0 + 1024) // 2048) - writei32(ws, c + 128, (t13 - o0 + 1024) // 2048) - end - end - -- pass 2: rows, descaled by 2^18 (13 + 2 + 3), into the picture - for r = 0, 224, 32 do - local d0 = readi32(ws, r) - local d1 = readi32(ws, r + 4) - local d2 = readi32(ws, r + 8) - local d3 = readi32(ws, r + 12) - local d4 = readi32(ws, r + 16) - local d5 = readi32(ws, r + 20) - local d6 = readi32(ws, r + 24) - local d7 = readi32(ws, r + 28) - local p0, p1, p2, p3, p4, p5, p6, p7 - if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then - local v = (d0 + 16) // 32 - p0, p1, p2, p3, p4, p5, p6, p7 = v, v, v, v, v, v, v, v - else - local z1 = (d2 + d6) * 4433 - local t2 = z1 - d6 * 15137 - local t3 = z1 + d2 * 6270 - local t0 = (d0 + d4) * 8192 - local t1 = (d0 - d4) * 8192 - local t10 = t0 + t3 + 131072 - local t13 = t0 - t3 + 131072 - local t11 = t1 + t2 + 131072 - local t12 = t1 - t2 + 131072 - local o0, o1, o2, o3 = d7, d5, d3, d1 - local y1 = o0 + o3 - local y2 = o1 + o2 - local y3 = o0 + o2 - local y4 = o1 + o3 - local z5 = (y3 + y4) * 9633 - o0 *= 2446 - o1 *= 16819 - o2 *= 25172 - o3 *= 12299 - y1 *= -7373 - y2 *= -20995 - y3 = y3 * -16069 + z5 - y4 = y4 * -3196 + z5 - o0 += y1 + y3 - o1 += y2 + y4 - o2 += y2 + y3 - o3 += y1 + y4 - p0 = (t10 + o3) // 262144 - p7 = (t10 - o3) // 262144 - p1 = (t11 + o2) // 262144 - p6 = (t11 - o2) // 262144 - p2 = (t12 + o1) // 262144 - p5 = (t12 - o1) // 262144 - p3 = (t13 + o0) // 262144 - p4 = (t13 - o0) // 262144 - end - if add then - p0 += readu8(dst, off) - p1 += readu8(dst, off + 1) - p2 += readu8(dst, off + 2) - p3 += readu8(dst, off + 3) - p4 += readu8(dst, off + 4) - p5 += readu8(dst, off + 5) - p6 += readu8(dst, off + 6) - p7 += readu8(dst, off + 7) - end - writeu32( - dst, - off, - readu8(CLAMP, p0 + COFF) - + readu8(CLAMP, p1 + COFF) * 256 - + readu8(CLAMP, p2 + COFF) * 65536 - + readu8(CLAMP, p3 + COFF) * 16777216 - ) - writeu32( - dst, - off + 4, - readu8(CLAMP, p4 + COFF) - + readu8(CLAMP, p5 + COFF) * 256 - + readu8(CLAMP, p6 + COFF) * 65536 - + readu8(CLAMP, p7 + COFF) * 16777216 - ) - off += stride - end -end +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc D.idct = idct - --- a constant 8x8 block (DC only): put or add v -local function fillBlock(dst: buffer, off: number, stride: number, v: number, add: boolean) - if not add then - local c = readu8(CLAMP, v + COFF) * 0x01010101 - for _ = 1, 8 do - writeu32(dst, off, c) - writeu32(dst, off + 4, c) - off += stride - end - else - for _ = 1, 8 do - for i = off, off + 7 do - writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) - end - off += stride - end - end -end - --- Motion-compensated prediction of a size x size block (16 luma, 8 chroma) from src at sOff to dst at dOff with --- half-pel flags hx / hy; avg averages into what dst holds (the second prediction of a B macroblock). Four bytes at --- a time: avg(a, b) rounding up = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its --- low 2 bits and high 6 bits so no lane overflows. -local function mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: number, size: number, hx: number, hy: number, avg: boolean) - for _ = 1, size do - for i = 0, size - 4, 4 do - local p - if hx == 0 then - if hy == 0 then - p = readu32(src, sOff + i) - else - local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride) - p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) - end - elseif hy == 0 then - local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) - p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) - else - local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) - local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1) - local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 - local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) - p = h + band(rshift(l, 2), 0x0F0F0F0F) - end - if avg then - local q = readu32(dst, dOff + i) - p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) - end - writeu32(dst, dOff + i, p) - end - sOff += stride - dOff += stride - end -end D.mc = mc -- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path @@ -775,7 +581,7 @@ function D.new(maxPixels: number?): Core fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) writei32(blk, 0, 0) else - idct(blk, ws, dst, off, stride, not intra) + idct(blk, dst, off, stride, not intra) buffer.fill(blk, 0, 0, 256) end return true From cf737746d4d50a58b484b5aec9cfdecede9b443b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:56:33 -0500 Subject: [PATCH 02/19] ws-video2: Dsp header --- docs/FORMATS.md | 1 + src/Formats/codecs/video/Dsp.luau | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..f36b9a6 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -132,6 +132,7 @@ 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/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/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 f449f53..6bdc215 100644 --- a/src/Formats/codecs/video/Dsp.luau +++ b/src/Formats/codecs/video/Dsp.luau @@ -3,7 +3,8 @@ --!optimize 2 -- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. -- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added --- into 8-bit planes, constant (DC-only) blocks, -- half-pel motion compensation four samples at a time. Native, never throws (the caller keeps offsets in range). +-- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never +-- throws (the caller keeps offsets in range). -- -- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg -- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then From 7b4bf1ee4345365560598c0c67df86cb4595a383 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:02:01 -0500 Subject: [PATCH 03/19] containers: video track palettes and depths for the legacy codecs Small backward-compatible additions so palettised codecs find their colour table on the Track: - containers/Avi: Avi.bitmapInfo(strf) (BITMAPINFOHEADER facts + palette as 256 RGBA u32); video/avi sets track.palette for 1..8-bit streams. - containers/IsoBmff/QtPalette (new): QuickTime sample description depth + colour table (stsd table, Mac default tables, grey ramps); IsoBmff Demux sets track.bitsPerPixel / track.palette, video/mp4 copies them. - video/mkv: V_MS/VFW/FOURCC (BITMAPINFOHEADER) and V_QUICKTIME (sample description) CodecPrivate map to the FourCC's codec with depth / palette. --- src/Formats/Registry.luau | 2 +- src/Formats/containers/Avi/init.luau | 47 ++++++++ src/Formats/containers/IsoBmff/Demux.luau | 14 +++ src/Formats/containers/IsoBmff/QtPalette.luau | 113 ++++++++++++++++++ src/Formats/video/avi/init.luau | 4 + src/Formats/video/mkv/Parse.luau | 38 ++++++ src/Formats/video/mkv/init.luau | 2 +- src/Formats/video/mp4/init.luau | 2 + 8 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 src/Formats/containers/IsoBmff/QtPalette.luau diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..288846f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -308,7 +308,7 @@ local list: { Entry } = { path = "video/mkv", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") diff --git a/src/Formats/containers/Avi/init.luau b/src/Formats/containers/Avi/init.luau index 081e9b9..9d89f18 100644 --- a/src/Formats/containers/Avi/init.luau +++ b/src/Formats/containers/Avi/init.luau @@ -9,6 +9,7 @@ -- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf -- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute -- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() +-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW) -- -- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). local Err = require("@formats/core/Err") @@ -520,4 +521,50 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer return w:finish() end +-- ------------------------------------------------------------------------------------------------ BITMAPINFO +export type BitmapInfo = { + width: number, + height: number, -- signed: > 0 = bottom-up rows + bits: number, -- biBitCount + compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB) + palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0 + extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none +} + +-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) | +-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries; +-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it. +function Avi.bitmapInfo(f: buffer): BitmapInfo? + local n = buffer.len(f) + if n < 40 then + return nil + end + local bits = readu16(f, 14) + local info: BitmapInfo = { + width = buffer.readi32(f, 4), + height = buffer.readi32(f, 8), + bits = bits, + compression = readstring(f, 16, 4), + } + if n > 40 then + local e = buffer.create(n - 40) + buffer.copy(e, 0, f, 40) + info.extra = e + if bits >= 1 and bits <= 8 then + local count = math.min(2 ^ bits, (n - 40) // 4) + local at = n - count * 4 + if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then + at -= 9 + end + local pal = buffer.create(1024) + for i = 0, count - 1 do + local o = at + i * 4 + buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000) + end + info.palette = pal + end + end + return info +end + return Avi diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau index 7f8689d..d44c566 100644 --- a/src/Formats/containers/IsoBmff/Demux.luau +++ b/src/Formats/containers/IsoBmff/Demux.luau @@ -8,9 +8,14 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Box = require("@formats/containers/IsoBmff/Box") +local QtPalette = require("@formats/containers/IsoBmff/QtPalette") local readstring = buffer.readstring +local function readu16be(b: buffer, o: number): number + return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) +end + local Demux = {} export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) @@ -33,6 +38,8 @@ export type Track = { channels: number?, bitsPerSample: number?, config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...) + bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...) + palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF) objectType: number?, -- esds objectTypeIndication pcm: { bits: number, float: boolean, little: boolean }?, entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...) @@ -194,6 +201,13 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) t.height = r:u16be() r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) childStart = r.pos + -- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...) + local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ) + t.bitsPerPixel = depth + t.palette = pal + if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then + childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8) + end else childStart = r.pos end diff --git a/src/Formats/containers/IsoBmff/QtPalette.luau b/src/Formats/containers/IsoBmff/QtPalette.luau new file mode 100644 index 0000000..2034dc3 --- /dev/null +++ b/src/Formats/containers/IsoBmff/QtPalette.luau @@ -0,0 +1,113 @@ +--!strict +-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime +-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0). +-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1, +-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey +-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the +-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). +-- +-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec) +-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil +-- +-- Never throws. +local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 + +local QtPalette = {} + +local function rgb(r: number, g: number, b: number): number + return r + g * 256 + b * 65536 + 0xFF000000 +end + +-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette) +local SMALL: { [number]: { number } } = { + [1] = { 0xFFFFFF, 0x000000 }, + [2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 }, + [4] = { + 0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA, + 0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000, + }, +} + +local function defaultTable(bits: number): buffer + local pal = buffer.create(1024) + local small = SMALL[bits] + if small then + for i, c in small do + writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256)) + end + return pal + end + local i = 0 + for r = 5, 0, -1 do + for g = 5, 0, -1 do + for b = 5, 0, -1 do + if i < 215 then + writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51)) + end + i += 1 + end + end + end + -- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black + local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + i = 215 + for ch = 0, 3 do + for _, v in RAMP do + local r = if ch == 0 or ch == 3 then v else 0 + local g = if ch == 1 or ch == 3 then v else 0 + local b = if ch == 2 or ch == 3 then v else 0 + writeu32(pal, i * 4, rgb(r, g, b)) + i += 1 + end + end + writeu32(pal, 255 * 4, rgb(0, 0, 0)) + return pal +end + +-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size +-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it. +function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?) + if start + 86 > stop or stop > buffer.len(b) then + return nil, nil + end + local raw = readu16(b, start + 82) + local id = readu16(b, start + 84) + local bits = raw % 32 + local grey = raw >= 32 and (raw // 32) % 2 == 1 + if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then + return raw, nil + end + if grey and codec == "cinepak" then + return raw, nil + end + if grey and bits > 1 and id ~= 0 then + local pal = buffer.create(1024) + local count = 2 ^ bits + local step = 256 // (count - 1) + local v = 255 + for i = 0, count - 1 do + writeu32(pal, i * 4, rgb(v, v, v)) + v = math.max(0, v - step) + end + return bits, pal + elseif id ~= 0 then + return bits, defaultTable(bits) + end + local pal = buffer.create(1024) + if start + 94 <= stop then + local first = readu32(b, start + 86) + local last = readu16(b, start + 92) + if first <= 255 and last <= 255 then + for i = first, last do + local o = start + 94 + (i - first) * 8 + if o + 8 > stop then + break + end + writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6))) + end + end + end + return bits, pal +end + +return QtPalette diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index fc46a32..3c5d919 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -110,6 +110,10 @@ local function videoTrack(s: Avi.Stream, id: number): Types.Track t.pixelFormat = "yuv420p" end end + local bi = Avi.bitmapInfo(f) + if bi and bi.palette then + t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...) + end local size = buffer.readu32(f, 0) if size > 40 and buffer.len(f) > 40 then local c = buffer.create(buffer.len(f) - 40) diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index fd07900..252a004 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -9,6 +9,8 @@ local Types = require("@formats/Types") local Ebml = require("@formats/containers/Ebml") local Demux = require("@formats/containers/Demux") local Video = require("@formats/codecs/video/Video") +local Avi = require("@formats/containers/Avi") +local QtPalette = require("@formats/containers/IsoBmff/QtPalette") local Deflate = require("@formats/codecs/compress/Deflate") local Parse = {} @@ -152,6 +154,39 @@ local function codecFor(id: string, kind: string, bits: number?): string end Parse.codecFor = codecFor +-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample +-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata +local function vfwOrQuickTime(t: any, codecId: string, priv: buffer) + local n = buffer.len(priv) + if codecId == "V_MS/VFW/FOURCC" then + local bi = Avi.bitmapInfo(priv) + if bi then + t.codec = Video.fromFourcc(bi.compression) or t.codec + t.codecTag = bi.compression + t.bitsPerPixel = bi.bits + t.palette = bi.palette + t.config = bi.extra + end + elseif codecId == "V_QUICKTIME" and n >= 21 then + local desc = priv + if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then + desc = buffer.create(n + 4) + local size = n + 4 + buffer.writeu8(desc, 0, size // 16777216 % 256) + buffer.writeu8(desc, 1, size // 65536 % 256) + buffer.writeu8(desc, 2, size // 256 % 256) + buffer.writeu8(desc, 3, size % 256) + buffer.copy(desc, 4, priv, 0, n) + end + local fcc = buffer.readstring(desc, 4, 4) + t.codec = Video.fromFourcc(fcc) or t.codec + t.codecTag = fcc + local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec) + t.bitsPerPixel = depth + t.palette = pal + end +end + type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? } local function parseVideo(buf: buffer, off: number, len: number, t: any) @@ -278,6 +313,9 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" t.codecTag = codecId t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + if t.kind == "video" and t.config then + vfwOrQuickTime(t, codecId, t.config) + end if t.kind == "audio" then t.sampleRate = t.sampleRate or 8000 t.channels = t.channels or 1 diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 1a94272..b8a22a5 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -27,7 +27,7 @@ local Mkv = { category = "video", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, } diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 0dcf3e8..f4d8217 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -133,6 +133,8 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) bitsPerSample = it.bitsPerSample, config = it.config, default = true, + bitsPerPixel = it.bitsPerPixel, + palette = it.palette, } if it.kind == "video" then if not Video.entry(t.codec) then From 8183f4d2d7bb50d66d72fa8ab89667b127d3a2b9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:16:35 -0500 Subject: [PATCH 04/19] ws-video2-theora: codecs/video/Theora, a Theora decoder (port of libtheora 1.2.0, BSD) Headers (identification, comment via VorbisComment, setup: loop-filter limits, quant ranges -> dequant tables, the 80 Huffman trees as collapsed lookup tables), intra / inter frames, coded SB / block flags, MB modes (8 alphabets), MVs (VLC / CLC, last / prior, 4MV with per-format chroma averages, half / quarter-pel), block qi, DCT tokens with EOB runs, DC prediction, the spec IDCT, loop filter, golden / previous refs, 4:2:0 / 4:2:2 / 4:4:4, picture-region crop, empty-packet dupes. Bit-exact with ffmpeg on every frame of 12 fixtures (tests/codecs/theora). Outside the folder: codecs/video/Video BUILTIN entry theora gets a decoder (track.config = Xiph-laced headers, as Matroska's CodecPrivate); licenses/libtheora-BSD.txt + NOTICE row. --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/libtheora-BSD.txt | 28 + src/Formats/codecs/video/Theora/Decoder.luau | 1254 ++++++++++++++++++ src/Formats/codecs/video/Theora/Header.luau | 370 ++++++ src/Formats/codecs/video/Theora/init.luau | 270 ++++ src/Formats/codecs/video/Video/init.luau | 9 +- tests/codecs/theora.luau | 285 ++++ tools/fixtures/theora.py | 195 +++ 9 files changed, 2412 insertions(+), 1 deletion(-) create mode 100644 licenses/libtheora-BSD.txt create mode 100644 src/Formats/codecs/video/Theora/Decoder.luau create mode 100644 src/Formats/codecs/video/Theora/Header.luau create mode 100644 src/Formats/codecs/video/Theora/init.luau create mode 100644 tests/codecs/theora.luau create mode 100644 tools/fixtures/theora.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..5f34e95 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -134,4 +134,5 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **video** - 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/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..ef688ee 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,7 @@ | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/libtheora-BSD.txt b/licenses/libtheora-BSD.txt new file mode 100644 index 0000000..c8ccce4 --- /dev/null +++ b/licenses/libtheora-BSD.txt @@ -0,0 +1,28 @@ +Copyright (C) 2002-2009 Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau new file mode 100644 index 0000000..d29b8cf --- /dev/null +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -0,0 +1,1254 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A +-- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, +-- idct.c, fragment.c) with the bit-exact reconstruction of the specification: +-- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode +-- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel +-- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; +-- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), +-- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for +-- unrestricted motion vectors, golden / previous reference frames; +-- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. +-- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, +-- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), +-- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- +-- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled +-- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +local Header = require("@formats/codecs/video/Theora/Header") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu16 = buffer.readu16 +local readi16 = buffer.readi16 +local writei16 = buffer.writei16 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local readu32 = buffer.readu32 +local bcopy = buffer.copy +local bfill = buffer.fill +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local D = {} + +-- macro block modes (libtheora's numbering) +local NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV = 0, 1, 2, 3, 4, 5, 6, 7 +-- reference frames of a fragment (refi) +local GOLD, PREV, SELF, NONE = 0, 1, 2, 3 +local FRAME_FOR_MODE = { [0] = PREV, SELF, PREV, PREV, PREV, GOLD, GOLD, PREV } + +-- the mode alphabets of schemes 1..7 (scheme 0 sends its own) +local ALPHABETS = { + { MV_LAST, MV_LAST2, INTER_MV, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, MV_LAST2, NOMV, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, MV_LAST2, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, NOMV, MV_LAST2, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, GOLD_NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_MV, FOURMV }, + { NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV }, +} + +-- the macro block mode VLC (0, 10, 110, ..., 1111110, 1111111): by the next 7 bits, index * 8 + length +local MODE_VLC = table.create(128, 0) +for w = 0, 127 do + local n = 0 + while n < 7 and bit32.extract(w, 6 - n, 1) == 1 do + n += 1 + end + MODE_VLC[w + 1] = n * 8 + (if n < 7 then n + 1 else 7) +end + +-- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length +local MV_VLC = table.create(256, 0) +do + local function put(code: number, len: number, v: number) + local sh = 8 - len + for i = 0, 2 ^ sh - 1 do + MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len + end + end + put(0, 3, 0) + put(1, 3, 1) + put(2, 3, -1) + put(6, 4, 2) + put(7, 4, -2) + put(8, 4, 3) + put(9, 4, -3) + for m = 4, 7 do + put(0x28 + (m - 4) * 2, 6, m) + put(0x29 + (m - 4) * 2, 6, -m) + end + for m = 8, 15 do + put(0x60 + (m - 8) * 2, 7, m) + put(0x61 + (m - 8) * 2, 7, -m) + end + for m = 16, 31 do + put(0xE0 + (m - 16) * 2, 8, m) + put(0xE1 + (m - 16) * 2, 8, -m) + end +end + +-- DCT tokens: extra bits per token +local TOKEN_EXTRA = { + [0] = 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +} + +-- natural index of zig-zag position (1-based by position + 1) +local ZIGZAG = Header.ZIGZAG + +-- clamp to 0..255 by lookup: CLAMP[v + COFF], v in [-COFF, COFF + 255] +local COFF = 70000 +local CLAMP = buffer.create(2 * COFF + 512) +for i = 0, 2 * COFF + 511 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 + +export type State = { + pf: number, + hdec: number, + vdec: number, + fw: number, + fh: number, + pw: { number }, -- plane sizes in pixels, [pli + 1] + ph: { number }, + nhf: { number }, -- plane sizes in fragments + nvf: { number }, + foff: { number }, -- first fragment id - 1 of each plane + stride: { number }, + padx: { number }, + pady: { number }, + origin: { number }, -- byte offset of pixel (0, 0) + planeSize: { number }, + nfrags: number, + nsbs: number, + sbPlane: { number }, -- [pli + 1]: the first super block (0-based) of each plane, and [4] = nsbs + sbFr: { number }, -- [sbi * 16 + quad * 4 + bi + 1]: fragment id (1-based) or 0 + sbQuadValid: { boolean }, -- [sbi * 4 + quad + 1] + nmbs: number, + mbMode: { number }, -- [mbi + 1]: -1 outside the frame + mbFr: { number }, -- [mbi * 12 + pli * 4 + bi + 1]: fragment id or 0 + mapIdx: { number }, -- the valid (pli * 4 + bi) slots of a macro block for this pixel format + -- per fragment [fi] + coded: { number }, + refi: { number }, + fmode: { number }, + mvx: { number }, + mvy: { number }, + qii: { number }, + dcv: { number }, + tis: { number }, + last: { number }, + fpos: { number }, -- byte offset of the fragment's first pixel in its plane + fpl: { number }, -- plane (0..2) + coef: buffer, -- i16 [(fi - 1) * 64 + zzi] + clist: { { number } }, -- coded fragments per plane, coded order + ncl: { number }, + act: { { number } }, + refs: { { buffer } }, -- [r][pli + 1] + gold: number, + prev: number, + shown: number, -- the reference holding the last decoded picture + dequant: buffer, + lflim: { number }, + huff: { number }, + roots: { number }, + blk: buffer, -- i32 x 64 work blocks + tmp: buffer, + res: buffer, + bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] + keyframes: number, +} + +-- new(info, setup) -> State +function D.new(info: Header.Info, setup: Header.Setup): State + local pf = info.pixelFormat + local hdec = if pf % 2 == 0 then 1 else 0 + local vdec = if pf < 2 then 1 else 0 + local fw, fh = info.frameWidth, info.frameHeight + local st: any = { + pf = pf, + hdec = hdec, + vdec = vdec, + fw = fw, + fh = fh, + pw = {}, + ph = {}, + nhf = {}, + nvf = {}, + foff = {}, + stride = {}, + padx = {}, + pady = {}, + origin = {}, + planeSize = {}, + dequant = setup.dequant, + lflim = setup.lflim, + huff = setup.huff, + roots = setup.roots, + blk = buffer.create(256), + tmp = buffer.create(256), + res = buffer.create(256), + bv = table.create(257, 0), + keyframes = 0, + } + local nfr = 0 + for pli = 0, 2 do + local hd, vd = if pli > 0 then hdec else 0, if pli > 0 then vdec else 0 + local w, h = fw // 2 ^ hd, fh // 2 ^ vd + local px, py = 16 // 2 ^ hd, 16 // 2 ^ vd + st.pw[pli + 1], st.ph[pli + 1] = w, h + st.nhf[pli + 1], st.nvf[pli + 1] = w // 8, h // 8 + st.foff[pli + 1] = nfr + nfr += (w // 8) * (h // 8) + st.padx[pli + 1], st.pady[pli + 1] = px, py + local stride = w + 2 * px + st.stride[pli + 1] = stride + st.origin[pli + 1] = py * stride + px + st.planeSize[pli + 1] = stride * (h + 2 * py) + end + st.nfrags = nfr + st.coded = table.create(nfr, 0) + st.refi = table.create(nfr, NONE) + st.fmode = table.create(nfr, 0) + st.mvx = table.create(nfr, 0) + st.mvy = table.create(nfr, 0) + st.qii = table.create(nfr, 0) + st.dcv = table.create(nfr, 0) + st.tis = table.create(nfr, 0) + st.last = table.create(nfr, 0) + st.fpos = table.create(nfr, 0) + st.fpl = table.create(nfr, 0) + st.coef = buffer.create(nfr * 128) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride, origin = st.stride[pli + 1], st.origin[pli + 1] + for fy = 0, nv - 1 do + for fx = 0, nh - 1 do + local fi = st.foff[pli + 1] + fy * nh + fx + 1 + st.fpos[fi] = origin + fy * 8 * stride + fx * 8 + st.fpl[fi] = pli + end + end + end + -- super blocks: 4x4 fragments in Hilbert order (oc_sb_create_plane_mapping) + local SB_MAP = { + { { 0, 0 }, { 0, 1 }, { 3, 2 }, { 3, 3 } }, + { { 0, 3 }, { 0, 2 }, { 3, 1 }, { 3, 0 } }, + { { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, + { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } }, + } + local sbFr: { number } = {} + local sbQuadValid: { boolean } = {} + local sbPlane: { number } = {} + local sbi = 0 + for pli = 0, 2 do + sbPlane[pli + 1] = sbi + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + for y = 0, nv - 1, 4 do + for x = 0, nh - 1, 4 do + for k = 1, 16 do + sbFr[sbi * 16 + k] = 0 + end + for i = 0, math.min(4, nv - y) - 1 do + for j = 0, math.min(4, nh - x) - 1 do + local m = SB_MAP[i + 1][j + 1] + sbFr[sbi * 16 + m[1] * 4 + m[2] + 1] = st.foff[pli + 1] + (y + i) * nh + x + j + 1 + end + end + for q = 0, 3 do + -- the upper left block of each quadrant: index 0, but 2 in quadrant 3 + local tl = if q == 3 then 2 else 0 + sbQuadValid[sbi * 4 + q + 1] = sbFr[sbi * 16 + q * 4 + tl + 1] ~= 0 + end + sbi += 1 + end + end + end + sbPlane[4] = sbi + st.nsbs = sbi + st.sbFr, st.sbQuadValid, st.sbPlane = sbFr, sbQuadValid, sbPlane + -- macro blocks: 4 per luma super block (oc_mb_create_mapping) + local nsbl = sbPlane[2] + local nmbs = nsbl * 4 + local mbMode = table.create(nmbs, 0) + local mbFr = table.create(nmbs * 12, 0) + local MB_MAP = { { 0, 3 }, { 1, 2 } } + local nhl, nvl = st.nhf[1], st.nvf[1] + local nhc = st.nhf[2] + sbi = 0 + for y = 0, nvl - 1, 4 do + for x = 0, nhl - 1, 4 do + for ymb = 0, 1 do + for xmb = 0, 1 do + local mbi = sbi * 4 + MB_MAP[ymb + 1][xmb + 1] + local mbx, mby = x + xmb * 2, y + ymb * 2 + if mbx >= nhl or mby >= nvl then + mbMode[mbi + 1] = -1 + else + local o = mbi * 12 + for i = 0, 1 do + for j = 0, 1 do + mbFr[o + i * 2 + j + 1] = (mby + i) * nhl + mbx + j + 1 + end + end + for pli = 1, 2 do + local base = st.foff[pli + 1] + 1 + if pf == 0 then + mbFr[o + pli * 4 + 1] = base + (mby // 2) * nhc + mbx // 2 + elseif pf == 2 then + for i = 0, 1 do + mbFr[o + pli * 4 + i * 2 + 1] = base + (mby + i) * nhc + mbx // 2 + end + else + for k = 0, 3 do + mbFr[o + pli * 4 + k + 1] = mbFr[o + k + 1] + st.foff[pli + 1] + end + end + end + end + end + end + sbi += 1 + end + end + st.nmbs, st.mbMode, st.mbFr = nmbs, mbMode, mbFr + st.mapIdx = if pf == 0 then { 0, 1, 2, 3, 4, 8 } elseif pf == 2 then { 0, 1, 2, 3, 4, 6, 8, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } + st.clist = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.act = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.ncl = { 0, 0, 0 } + -- three reference frames, grey until the first keyframe + st.refs = {} + for r = 1, 3 do + local planes = {} + for pli = 1, 3 do + local b = buffer.create(st.planeSize[pli]) + bfill(b, 0, 128) + planes[pli] = b + end + st.refs[r] = planes + end + st.gold, st.prev, st.shown = 1, 1, 1 + return st :: State +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs +local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) + local t0 = (C4 * (x0 + x4)) // 65536 + local t1 = (C4 * (x0 - x4)) // 65536 + local t2 = (C6 * x2) // 65536 - (C2 * x6) // 65536 + local t3 = (C2 * x2) // 65536 + (C6 * x6) // 65536 + local t4 = (C7 * x1) // 65536 - (C1 * x7) // 65536 + local t5 = (C3 * x5) // 65536 - (C5 * x3) // 65536 + local t6 = (C5 * x5) // 65536 + (C3 * x3) // 65536 + local t7 = (C1 * x1) // 65536 + (C7 * x7) // 65536 + local r = t4 + t5 + t5 = (C4 * (t4 - t5)) // 65536 + t4 = r + r = t7 + t6 + t6 = (C4 * (t7 - t6)) // 65536 + t7 = r + r = t0 + t3 + t3 = t0 - t3 + t0 = r + r = t1 + t2 + t2 = t1 - t2 + t1 = r + r = t6 + t5 + t5 = t6 - t5 + t6 = r + return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 +end + +-- 2-D IDCT of blk (i16, natural order) into res (i32 residuals). Like libtheora, the dequantised coefficients and +-- the first pass's outputs are 16-bit (the i16 buffers wrap them), which also bounds every residual to +-24000. +local function idct(blk: buffer, tmp: buffer, res: buffer) + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) + local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) + local c = i * 2 + if x0 == 0 and x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + writei16(tmp, c, 0) + writei16(tmp, c + 16, 0) + writei16(tmp, c + 32, 0) + writei16(tmp, c + 48, 0) + writei16(tmp, c + 64, 0) + writei16(tmp, c + 80, 0) + writei16(tmp, c + 96, 0) + writei16(tmp, c + 112, 0) + else + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + writei16(tmp, c, y0) + writei16(tmp, c + 16, y1) + writei16(tmp, c + 32, y2) + writei16(tmp, c + 48, y3) + writei16(tmp, c + 64, y4) + writei16(tmp, c + 80, y5) + writei16(tmp, c + 96, y6) + writei16(tmp, c + 112, y7) + end + end + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6) + local x4, x5, x6, x7 = readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14) + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + local c = i * 4 + writei32(res, c, (y0 + 8) // 16) + writei32(res, c + 32, (y1 + 8) // 16) + writei32(res, c + 64, (y2 + 8) // 16) + writei32(res, c + 96, (y3 + 8) // 16) + writei32(res, c + 128, (y4 + 8) // 16) + writei32(res, c + 160, (y5 + 8) // 16) + writei32(res, c + 192, (y6 + 8) // 16) + writei32(res, c + 224, (y7 + 8) // 16) + end +end + +local function wrap16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +-- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away +-- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel +local function mvSplit(d: number, q: boolean): (number, number) + local div = if q then 4 else 2 + local a = if d < 0 then -((-d) // div) else d // div + local frac = d - a * div + local b = if frac > 0 then 1 elseif frac < 0 then -1 else 0 + return a, b +end + +-- reconstruct one coded fragment into dst (the SELF reference planes) +local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) + local pli = st.fpl[fi] + local mode = st.fmode[fi] + local qti = if mode == INTRA then 0 else 1 + local dq = st.dequant + local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) + local dc = st.dcv[fi] + local last = st.last[fi] + local res = st.res + local flat = false + local fv = 0 + if last == 0 then + flat = true + fv = wrap16((dc * dcq + 15) // 32) + else + local blk = st.blk + bfill(blk, 0, 0, 128) + writei16(blk, 0, wrap16(dc * dcq)) + local coef = st.coef + local co = (fi - 1) * 128 + local ao = (((qis[st.qii[fi] + 1] * 3 + pli) * 2 + qti) * 64) * 2 + for z = 1, last do + local c = readi16(coef, co + z * 2) + if c ~= 0 then + writei16(coef, co + z * 2, 0) + writei16(blk, ZIGZAG[z + 1] * 2, wrap16(c * readu16(dq, ao + z * 2))) + end + end + st.last[fi] = 0 + idct(blk, st.tmp, res) + end + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] + if ri == SELF then + if flat then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + else + for y = 0, 7 do + local d, s = pos + y * stride, y * 32 + for x = 0, 7 do + writeu8(dst, d + x, readu8(CLAMP, readi32(res, s + x * 4) + 128 + COFF)) + end + end + end + return + end + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local qx = pli > 0 and st.hdec == 1 + local qy = pli > 0 and st.vdec == 1 + local mx, mx2 = mvSplit(st.mvx[fi], qx) + local my, my2 = mvSplit(st.mvy[fi], qy) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + local s2 = s1 + my2 * stride + mx2 + for y = 0, 7 do + local d, a, b, r = pos + y * stride, s1 + y * stride, s2 + y * stride, y * 32 + for x = 0, 7 do + local p = (readu8(ref, a + x) + readu8(ref, b + x)) // 2 + local v = if flat then fv else readi32(res, r + x * 4) + writeu8(dst, d + x, readu8(CLAMP, p + v + COFF)) + end + end + else + for y = 0, 7 do + local d, a, r = pos + y * stride, s1 + y * stride, y * 32 + for x = 0, 7 do + local v = if flat then fv else readi32(res, r + x * 4) + writeu8(dst, d + x, readu8(CLAMP, readu8(ref, a + x) + v + COFF)) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ loop filter +local function filterH(b: buffer, p: number, stride: number, bv: { number }) + p -= 2 + for _ = 0, 7 do + local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, p + 1, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + 2, readu8(CLAMP, p2 - f + COFF)) + p += stride + end +end + +local function filterV(b: buffer, p: number, stride: number, bv: { number }) + local q0, q1, q2 = p - 2 * stride, p - stride, p + stride + for x = 0, 7 do + local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, q1 + x, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + x, readu8(CLAMP, p2 - f + COFF)) + end +end + +local function loopFilter(st: State, planes: { buffer }, flimit: number) + local bv = st.bv + for i = -128, 128 do + local a = math.abs(i) + local v = 0 + if a < flimit then + v = i + elseif a < 2 * flimit then + v = if i > 0 then 2 * flimit - a else a - 2 * flimit + end + -- libtheora's table stops at index -127 (127 - i - flimit >= 0) + if i < -127 then + v = 0 + end + bv[i + 129] = v + end + local coded = st.coded + for pli = 0, 2 do + local b = planes[pli + 1] + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride = st.stride[pli + 1] + local base = st.foff[pli + 1] + local fpos = st.fpos + for fy = 0, nv - 1 do + local row = base + fy * nh + for fx = 0, nh - 1 do + local fi = row + fx + 1 + if coded[fi] ~= 0 then + local p = fpos[fi] + if fx > 0 then + filterH(b, p, stride, bv) + end + if fy > 0 then + filterV(b, p, stride, bv) + end + if fx + 1 < nh and coded[fi + 1] == 0 then + filterH(b, p + 8, stride, bv) + end + if fy + 1 < nv and coded[fi + nh] == 0 then + filterV(b, p + 8 * stride, stride, bv) + end + end + end + end + end +end + +-- extend each plane's edge pixels into its padding (for unrestricted motion vectors) +local function borders(st: State, planes: { buffer }) + for pli = 1, 3 do + local b = planes[pli] + local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] + local w, h = st.pw[pli], st.ph[pli] + for y = 0, h - 1 do + local o = (y + py) * stride + bfill(b, o, readu8(b, o + px), px) + bfill(b, o + px + w, readu8(b, o + px + w - 1), px) + end + local top, bot = py * stride, (py + h - 1) * stride + for k = 1, py do + bcopy(b, top - k * stride, b, top, stride) + bcopy(b, bot + k * stride, b, bot, stride) + end + end +end + +-- ------------------------------------------------------------------------------------------------ frame decode +-- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in +-- st.refs[st.shown]. +function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) + if len <= 0 then + return "dup", nil + end + -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first + local bb = buffer.create(len + 24) + bcopy(bb, 0, data, off, len) + local maxp = len * 8 + local pos = 0 + local function bits(n: number): number + if pos > maxp then + pos = maxp + end + local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + pos += n + return w + end + local huff = st.huff + local function token(root: number): number + if pos > maxp then + pos = maxp + end + local o = root + while true do + local n = huff[o] + local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + local e = huff[o + 1 + w] + if e >= 0 then + pos += e // 64 + return e % 64 + end + pos += n + o = -e + if pos > maxp then + pos = maxp + end + end + end + local function sbRun(): number + if bits(1) == 0 then + return 1 + elseif bits(1) == 0 then + return 2 + bits(1) + elseif bits(1) == 0 then + return 4 + bits(1) + elseif bits(1) == 0 then + return 6 + bits(2) + elseif bits(1) == 0 then + return 10 + bits(3) + elseif bits(1) == 0 then + return 18 + bits(4) + end + return 34 + bits(12) + end + local function blockRun(): number + if bits(1) == 0 then + return 1 + bits(1) + elseif bits(1) == 0 then + return 3 + bits(1) + elseif bits(1) == 0 then + return 5 + bits(1) + elseif bits(1) == 0 then + return 7 + bits(2) + elseif bits(1) == 0 then + return 11 + bits(2) + end + return 15 + bits(4) + end + + -- frame header + if bits(1) ~= 0 then + return nil, "not a data packet" + end + local intra = bits(1) == 0 + local qis = { bits(6) } + if bits(1) == 1 then + table.insert(qis, bits(6)) + if bits(1) == 1 then + table.insert(qis, bits(6)) + end + end + if intra then + if bits(3) ~= 0 then + return nil, "unsupported: reserved keyframe bits set" + end + end + local coded, refi, fmode, dcv, tis, qii = st.coded, st.refi, st.fmode, st.dcv, st.tis, st.qii + local mvx, mvy = st.mvx, st.mvy + local sbFr, sbQuadValid, sbPlane = st.sbFr, st.sbQuadValid, st.sbPlane + local clist, ncl = st.clist, st.ncl + local mbMode = st.mbMode + local nsbs = st.nsbs + local total = 0 + if intra then + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for sbi = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + for q = 0, 3 do + if sbQuadValid[sbi * 4 + q + 1] then + for bi = 0, 3 do + local fi = sbFr[sbi * 16 + q * 4 + bi + 1] + if fi ~= 0 then + coded[fi] = 1 + refi[fi] = SELF + fmode[fi] = INTRA + n += 1 + list[n] = fi + end + end + end + end + end + ncl[pli + 1] = n + total += n + end + else + -- partially coded super blocks, then fully coded ones among the rest + local partial, full = table.create(nsbs, false), table.create(nsbs, false) + local npartial = 0 + local flag = bits(1) + local sbi = 0 + while sbi < nsbs do + local run = sbRun() + local fullRun = run >= 4129 + repeat + partial[sbi + 1] = flag == 1 + npartial += flag + sbi += 1 + run -= 1 + until run <= 0 or sbi >= nsbs + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + end + if npartial < nsbs then + sbi = 0 + while partial[sbi + 1] do + sbi += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while sbi < nsbs do + if not partial[sbi + 1] then + if run <= 0 then + break + end + run -= 1 + full[sbi + 1] = flag == 1 + end + sbi += 1 + end + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + until sbi >= nsbs + end + -- block flags + local bflag = 0 + if npartial > 0 then + bflag = 1 - bits(1) + end + local run = 0 + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for s = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + local isFull, isPartial = full[s + 1], partial[s + 1] + for q = 0, 3 do + if sbQuadValid[s * 4 + q + 1] then + local quadCoded = 0 + for bi = 0, 3 do + local fi = sbFr[s * 16 + q * 4 + bi + 1] + if fi ~= 0 then + local c = 0 + if isFull then + c = 1 + elseif isPartial then + if run <= 0 then + run = blockRun() + bflag = 1 - bflag + end + run -= 1 + c = bflag + end + coded[fi] = c + refi[fi] = NONE + if c == 1 then + n += 1 + list[n] = fi + quadCoded = 1 + end + end + end + if pli == 0 then + mbMode[s * 4 + q + 1] = quadCoded + end + end + end + end + ncl[pli + 1] = n + total += n + end + if total == 0 then + return "dup", nil + end + -- macro block modes + local scheme = bits(3) + local alphabet: { number } + if scheme == 0 then + alphabet = table.create(8, NOMV) + for mi = 1, 8 do + alphabet[bits(3) + 1] = ALPHABETS[7][mi] + end + else + alphabet = ALPHABETS[scheme] + end + for mbi = 1, st.nmbs do + if mbMode[mbi] > 0 then + local idx: number + if scheme == 7 then + idx = bits(3) + else + local e = MODE_VLC[bits(7) + 1] + pos -= 7 - e % 8 + idx = e // 8 + end + mbMode[mbi] = alphabet[idx + 1] + end + end + -- motion vectors + local clc = bits(1) == 1 + local function mv(): number + if clc then + local v = bits(6) + return if v % 2 == 1 then -(v // 2) else v // 2 + end + local e = MV_VLC[bits(8) + 1] + pos -= 8 - e % 16 + return e // 16 - 32 + end + local mbFr, mapIdx = st.mbFr, st.mapIdx + local nmap = #mapIdx + local lastX, lastY, priorX, priorY = 0, 0, 0, 0 + local lx, ly = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local cx, cy = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local pf = st.pf + for mbi = 0, st.nmbs - 1 do + local mode = mbMode[mbi + 1] + if mode >= 0 then + local o = mbi * 12 + if mode == FOURMV then + priorX, priorY = lastX, lastY + for bi = 1, 4 do + local fi = mbFr[o + bi] + if coded[fi] ~= 0 then + refi[fi] = PREV + fmode[fi] = FOURMV + local x = mv() + local y = mv() + lx[bi], ly[bi] = x, y + lastX, lastY = x, y + mvx[fi], mvy[fi] = x, y + else + lx[bi], ly[bi] = 0, 0 + end + end + if pf == 0 then + local sx, sy = lx[1] + lx[2] + lx[3] + lx[4], ly[1] + ly[2] + ly[3] + ly[4] + cx[1] = (sx + 2 - (if sx < 0 then 1 else 0)) // 4 + cy[1] = (sy + 2 - (if sy < 0 then 1 else 0)) // 4 + elseif pf == 2 then + local sx, sy = lx[1] + lx[2], ly[1] + ly[2] + cx[1] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[1] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + sx, sy = lx[3] + lx[4], ly[3] + ly[4] + cx[3] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[3] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + else + for k = 1, 4 do + cx[k], cy[k] = lx[k], ly[k] + end + end + for m = 5, nmap do + local mi = mapIdx[m] + local fi = mbFr[o + mi + 1] + if coded[fi] ~= 0 then + local bi = mi % 4 + 1 + refi[fi] = PREV + fmode[fi] = FOURMV + mvx[fi], mvy[fi] = cx[bi], cy[bi] + end + end + else + local x, y = 0, 0 + if mode == INTER_MV then + priorX, priorY = lastX, lastY + x = mv() + y = mv() + lastX, lastY = x, y + elseif mode == MV_LAST then + x, y = lastX, lastY + elseif mode == MV_LAST2 then + x, y = priorX, priorY + priorX, priorY = lastX, lastY + lastX, lastY = x, y + elseif mode == GOLD_MV then + x = mv() + y = mv() + end + local r = FRAME_FOR_MODE[mode] + for m = 1, nmap do + local fi = mbFr[o + mapIdx[m] + 1] + if coded[fi] ~= 0 then + refi[fi] = r + fmode[fi] = mode + mvx[fi], mvy[fi] = x, y + end + end + end + end + end + end + + -- block qi indices (over every coded fragment, planes in order) + local nqis = #qis + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + local fi = list[k] + qii[fi] = 0 + dcv[fi] = 0 + tis[fi] = 0 + end + end + if nqis > 1 then + local all = table.create(total, 0) + local n = 0 + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + n += 1 + all[n] = list[k] + end + end + local flag = bits(1) + local nqi1 = 0 + local k = 1 + while k <= total do + local run = sbRun() + local fullRun = run >= 4129 + repeat + qii[all[k]] = flag + nqi1 += flag + k += 1 + run -= 1 + until run <= 0 or k > total + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + end + if nqis == 3 and nqi1 > 0 then + k = 1 + while qii[all[k]] == 0 do + k += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while k <= total do + local fi = all[k] + if qii[fi] ~= 0 then + if run <= 0 then + break + end + run -= 1 + qii[fi] += flag + end + k += 1 + end + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + until k > total + end + end + + -- DCT tokens: coefficient by coefficient, plane by plane, block by block in coded order; an EOB run ends the + -- next blocks that still wait for a token at their position + local coef, last = st.coef, st.last + local act = st.act + local nact = { 0, 0, 0 } + for pli = 1, 3 do + local src, dstl = clist[pli], act[pli] + for k = 1, ncl[pli] do + dstl[k] = src[k] + end + nact[pli] = ncl[pli] + end + local roots = st.roots + local hy: number = bits(4) + local hc: number = bits(4) + local eobs = 0 + for zzi = 0, 63 do + if zzi == 1 then + hy = bits(4) + hc = bits(4) + end + local grp: number = if zzi == 0 then 0 elseif zzi < 6 then 16 elseif zzi < 15 then 32 elseif zzi < 28 then 48 else 64 + for pli = 1, 3 do + local sel: number = if pli == 1 then hy else hc + local root = roots[sel + grp + 1] + local list = act[pli] + local n = nact[pli] + local w = 0 + for k = 1, n do + local fi = list[k] + local t = tis[fi] + if t == zzi then + if eobs > 0 then + eobs -= 1 + t = 64 + else + local tok = token(root) + local ex = TOKEN_EXTRA[tok] + local eb = if ex > 0 then bits(ex) else 0 + if tok < 7 then + local run: number + if tok < 3 then + run = tok + 1 + elseif tok == 3 then + run = 4 + eb + elseif tok == 4 then + run = 8 + eb + elseif tok == 5 then + run = 16 + eb + else + run = if eb == 0 then 2 ^ 31 else eb + end + eobs = run - 1 + t = 64 + elseif tok < 9 then + t = zzi + eb + 1 + else + local v, r = 0, 0 + if tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + local p = zzi + r + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p + end + t = p + 1 + end + end + tis[fi] = t + end + if t < 64 then + w += 1 + list[w] = fi + end + end + nact[pli] = w + end + end + + -- DC prediction (raster order per plane) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end + + -- reconstruction into a free reference buffer + local self = 1 + while self == st.gold or self == st.prev do + self += 1 + end + local dst = st.refs[self] + if not intra then + local src = st.refs[st.prev] + for pli = 1, 3 do + bcopy(dst[pli], 0, src[pli], 0, st.planeSize[pli]) + end + end + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + reconFrag(st, list[k], qis, dst) + end + end + local flimit = st.lflim[qis[1] + 1] + if flimit ~= 0 then + loopFilter(st, dst, flimit) + end + borders(st, dst) + if intra then + st.gold, st.prev = self, self + st.keyframes += 1 + else + st.prev = self + end + st.shown = self + return if intra then "key" else "inter", nil +end + +-- ------------------------------------------------------------------------------------------------ output +-- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose +-- top-left corner is (x0, y0) counted from the top of the plane +function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer + local src = st.refs[st.shown][pli + 1] + local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] + local out = buffer.create(w * h) + for y = 0, h - 1 do + local row = ph - 1 - (y0 + y) -- Theora rows count from the bottom + bcopy(out, y * w, src, origin + row * stride + x0, w) + end + return out +end + +-- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 +-- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) + for r = 0, oh - 1 do + local r0 = math.min(2 * r, ch - 1) + local r1 = math.min(2 * r + 1, ch - 1) + local a, b = r0 * cw, r1 * cw + local o = off + r * ow + if hdec == 1 then + for c = 0, math.min(ow, cw) - 1 do + writeu8(dst, o + c, (readu8(src, a + c) + readu8(src, b + c) + 1) // 2) + end + else + for c = 0, ow - 1 do + local c0 = math.min(2 * c, cw - 1) + local c1 = math.min(2 * c + 1, cw - 1) + writeu8(dst, o + c, (readu8(src, a + c0) + readu8(src, a + c1) + readu8(src, b + c0) + readu8(src, b + c1) + 2) // 4) + end + end + end +end + +return D diff --git a/src/Formats/codecs/video/Theora/Header.luau b/src/Formats/codecs/video/Theora/Header.luau new file mode 100644 index 0000000..2d88abd --- /dev/null +++ b/src/Formats/codecs/video/Theora/Header.luau @@ -0,0 +1,370 @@ +--!strict +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / +-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis +-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the +-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman +-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; +-- the table layout here is simpler). Never throws: bad headers return nil, message. +local Bits = require("@formats/core/Bits") + +local H = {} + +export type Info = { + versionMajor: number, + versionMinor: number, + versionSub: number, + frameWidth: number, -- coded frame size (multiples of 16) + frameHeight: number, + picWidth: number, -- the picture region (the displayed part) + picHeight: number, + picX: number, -- from the left + picY: number, -- from the bottom, as stored + fpsNum: number, + fpsDen: number, + aspectNum: number, + aspectDen: number, + colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG + bitrate: number, + quality: number, + granuleShift: number, + pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved) +} + +export type Setup = { + lflim: { number }, -- [qi + 1]: loop filter limit + dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora + huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable) + roots: { number }, -- [table + 1]: the root node offset in huff +} + +-- the zig-zag scan: natural index of the coefficient at scan position zzi +H.ZIGZAG = { + 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, +} + +local function ilog(v: number): number + local n = 0 + while v > 0 do + n += 1 + v = v // 2 + end + return n +end + +-- ------------------------------------------------------------------------------------------------ identification +-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +function H.info(b: buffer, off: number, len: number): (Info?, string?) + if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora identification header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + local info: Info = { + versionMajor = br:read(8), + versionMinor = br:read(8), + versionSub = br:read(8), + frameWidth = br:read(16) * 16, + frameHeight = br:read(16) * 16, + picWidth = br:read(24), + picHeight = br:read(24), + picX = br:read(8), + picY = br:read(8), + fpsNum = br:read(32), + fpsDen = br:read(32), + aspectNum = br:read(24), + aspectDen = br:read(24), + colorspace = br:read(8), + bitrate = br:read(24), + quality = br:read(6), + granuleShift = br:read(5), + pixelFormat = br:read(2), + } + local reserved = br:read(3) + if br.err then + return nil, "truncated identification header" + end + if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then + return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor + end + if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then + return nil, "bad frame / picture size" + end + if info.fpsNum == 0 or info.fpsDen == 0 then + return nil, "bad frame rate" + end + if info.pixelFormat == 1 or reserved ~= 0 then + return nil, "reserved pixel format" + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ comment +-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, nil, "not a Theora comment header" + end + local p, e = off + 7, off + len + local function str(): string? + if p + 4 > e then + return nil + end + local n = buffer.readu32(b, p) + p += 4 + if n > e - p then + return nil + end + local s = buffer.readstring(b, p, n) + p += n + return s + end + local vendor = str() + if not vendor or p + 4 > e then + return nil, nil, "truncated comment header" + end + local count = buffer.readu32(b, p) + p += 4 + if count * 4 > e - p then + return nil, nil, "bad comment count" + end + local list: { string } = {} + for _ = 1, count do + local s = str() + if not s then + return nil, nil, "truncated comment header" + end + table.insert(list, s) + end + return vendor, list, nil +end + +-- ------------------------------------------------------------------------------------------------ Huffman trees +-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in +-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf +-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). +local MAXBITS = 8 + +local function readTree(br: any): ({ number }?, { number }?, { number }?) + -- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root) + local kid0, kid1, tok = { 0 }, { 0 }, { -1 } + -- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length + local code, len, nleaves = 0, 0, 0 + while true do + local bit = br:read(1) + if br.err then + return nil, nil, nil + end + if bit == 0 then + len += 1 + if len > 32 then + return nil, nil, nil + end + else + nleaves += 1 + if nleaves > 32 then + return nil, nil, nil + end + local t = br:read(5) + -- insert the leaf + local n = 1 + for d = 1, len do + local k = (code // 2 ^ (32 - d)) % 2 + local kids = if k == 0 then kid0 else kid1 + local nx = kids[n] + if nx == 0 then + nx = #tok + 1 + kid0[nx], kid1[nx], tok[nx] = 0, 0, -1 + kids[n] = nx + end + n = nx + end + tok[n] = t + if len <= 0 then + break + end + -- the next codeword: clear the trailing 1 bits, then set the last 0 bit + local cb = 2 ^ (32 - len) + while len > 0 and (code // cb) % 2 == 1 do + code -= cb + cb *= 2 + len -= 1 + end + if len <= 0 then + break + end + code += cb + end + end + return kid0, kid1, tok +end + +local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number + local heights: { [number]: number } = {} + local function height(n: number): number + local h = heights[n] + if h then + return h + end + h = 0 + if tok[n] < 0 then + local a = if kid0[n] ~= 0 then height(kid0[n]) else 0 + local c = if kid1[n] ~= 0 then height(kid1[n]) else 0 + h = 1 + math.max(a, c) + end + heights[n] = h + return h + end + local function node(n: number): number + local nb = math.clamp(height(n), 1, MAXBITS) + local off = #out + 1 + out[off] = nb + local size = 2 ^ nb + for i = 1, size do + out[off + i] = 0 + end + for i = 0, size - 1 do + local cur, d = n, 0 + while d < nb and tok[cur] < 0 do + local bit = (i // 2 ^ (nb - 1 - d)) % 2 + local nx = if bit == 0 then kid0[cur] else kid1[cur] + d += 1 + cur = nx + if nx == 0 then + break + end + end + if cur == 0 then + out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0 + elseif tok[cur] >= 0 then + out[off + 1 + i] = d * 64 + tok[cur] + else + out[off + 1 + i] = -node(cur) + end + end + return off + end + return node(1) +end + +-- ------------------------------------------------------------------------------------------------ setup +local DC_MIN = { 16, 32 } +local AC_MIN = { 8, 16 } + +-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +function H.setup(b: buffer, off: number, len: number): (Setup?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora setup header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + -- loop filter limits, AC / DC scales + local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0) + local nb = br:read(3) + for qi = 1, 64 do + lflim[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + acScale[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + dcScale[qi] = br:read(nb) + end + local nbms = br:read(9) + 1 + local bms: { { number } } = {} + for m = 1, nbms do + local mat = table.create(64, 0) + for ci = 1, 64 do + mat[ci] = br:read(8) + end + bms[m] = mat + end + if br.err then + return nil, "truncated setup header" + end + -- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based) + local ranges: { { sizes: { number }, idx: { number } } } = {} + local mb = ilog(nbms - 1) + for i = 0, 5 do + local qti, pli = i // 3, i % 3 + local copy = false + if i > 0 and br:read(1) == 0 then + copy = true + local from = i - 1 + if qti > 0 and br:read(1) == 1 then + from = pli -- the same plane of the intra set + end + ranges[i + 1] = ranges[from + 1] + end + if not copy then + local sizes, idx = {}, { br:read(mb) } + local qi = 0 + while qi < 63 do + local s = br:read(ilog(62 - qi)) + 1 + table.insert(sizes, s) + qi += s + table.insert(idx, br:read(mb)) + end + if qi > 63 then + return nil, "bad quant ranges" + end + for _, m in idx do + if m >= nbms then + return nil, "bad base matrix index" + end + end + ranges[i + 1] = { sizes = sizes, idx = idx } + end + end + if br.err then + return nil, "truncated setup header" + end + -- the dequantisation tables (oc_dequant_tables_init) + local dequant = buffer.create(64 * 6 * 64 * 2) + local base = table.create(64, 0) + for qti = 0, 1 do + for pli = 0, 2 do + local r = ranges[qti * 3 + pli + 1] + local qi = 0 + for qri = 0, #r.sizes do + local m0 = bms[r.idx[qri + 1] + 1] + table.move(m0, 1, 64, 1, base) + local qiStart = qi + local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1] + while true do + local o = ((qi * 3 + pli) * 2 + qti) * 64 + local q = (dcScale[qi + 1] * base[1] // 100) * 4 + buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096)) + for zzi = 1, 63 do + q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4 + buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096)) + end + qi += 1 + if qi >= qiEnd then + break + end + -- interpolate the next base matrix + local m1 = bms[r.idx[qri + 2] + 1] + local sz = r.sizes[qri + 1] + for ci = 1, 64 do + base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz) + end + end + end + end + end + -- the 80 Huffman trees + local huff: { number } = {} + local roots: { number } = {} + for t = 1, 80 do + local k0, k1, tk = readTree(br) + if not k0 or not k1 or not tk then + return nil, "bad Huffman tree " .. (t - 1) + end + roots[t] = buildTable(huff, k0, k1, tk) + end + return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil +end + +return H diff --git a/src/Formats/codecs/video/Theora/init.luau b/src/Formats/codecs/video/Theora/init.luau new file mode 100644 index 0000000..dd99346 --- /dev/null +++ b/src/Formats/codecs/video/Theora/init.luau @@ -0,0 +1,270 @@ +--!strict +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska +-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau +-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). +-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV +-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, +-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); +-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). +-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). +-- +-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate +-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err +-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region +-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down +-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position +-- +-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") +local Header = require("@formats/codecs/video/Theora/Header") +local Decoder = require("@formats/codecs/video/Theora/Decoder") + +local Theora = {} + +export type Options = { + maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) +} + +local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } + +-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil +function Theora.isHeader(b: buffer, off: number?, len: number?): number? + local o = off or 0 + local n = len or (buffer.len(b) - o) + if n < 7 then + return nil + end + local t = buffer.readu8(b, o) + if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then + return t - 0x7F + end + return nil +end + +-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) +function Theora.splitConfig(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 or buffer.readu8(c, 0) ~= 2 then + return nil + end + local p, lens = 1, {} + for k = 1, 2 do + local size = 0 + repeat + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + size += b + p += 1 + until b < 255 + lens[k] = size + end + lens[3] = n - p - lens[1] - lens[2] + if lens[3] < 0 then + return nil + end + local out = {} + for k = 1, 3 do + out[k] = buffer.create(lens[k]) + buffer.copy(out[k], 0, c, p, lens[k]) + p += lens[k] + end + return out +end + +-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) +function Theora.granuleFrame(info: Header.Info, g: number): number + if g < 0 then + return -1 + end + local shift = 2 ^ info.granuleShift + local key = g // shift + local f = key + g % shift + -- since bitstream 3.2.1 the first frame is granule 1 + local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub + if v >= 0x030201 then + f -= 1 + end + return f +end + +-- ------------------------------------------------------------------------------------------------ decoder +local Dec = {} +Dec.__index = Dec + +export type TheoraDecoder = typeof(setmetatable( + {} :: { + info: Header.Info, + vendor: string, + comments: { string }, + tags: { [string]: string }, + width: number, -- the picture region + height: number, + frameRate: number, + pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" + aspect: number, -- pixel aspect ratio (1 when unknown) + frames: number, -- packets decoded (dupes included) + _st: Decoder.State, + _any: boolean, -- a frame was decoded + }, + Dec +)) + +-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config +function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) + local list: { buffer }? = nil + if type(headers) == "buffer" then + list = Theora.splitConfig(headers) + elseif type(headers) == "table" then + list = headers + end + if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then + return nil, Err.new(Err.CORRUPT, "missing Theora headers") + end + local ok, info, ierr = pcall(Header.info, list[1], 0, buffer.len(list[1])) + if not ok or not info then + return nil, Err.from(if ok then ierr else tostring(info)) + end + local maxPixels = opts and opts.maxPixels or 4096 * 2304 + if info.frameWidth * info.frameHeight > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") + end + local ok2, vendor, comments, cerr = pcall(Header.comment, list[2], 0, buffer.len(list[2])) + if not ok2 or not vendor or not comments then + return nil, Err.from(if ok2 then cerr else tostring(vendor)) + end + local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) + if not ok3 or not setup then + return nil, Err.from(if ok3 then serr else tostring(setup)) + end + local st = Decoder.new(info, setup) + local tags = VorbisComment.tags(comments) + return setmetatable({ + info = info, + vendor = vendor, + comments = comments, + tags = tags, + width = info.picWidth, + height = info.picHeight, + frameRate = info.fpsNum / info.fpsDen, + pixelFormat = PIXEL_FORMATS[info.pixelFormat], + aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1, + frames = 0, + _st = st, + _any = false, + }, Dec), nil +end + +-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). +function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) + local o = off or 0 + local n = len or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "decode: range outside the buffer") + end + if n > 0 and buffer.readu8(data, o) >= 0x80 then + return nil, nil + end + local kind, msg = Decoder.decode(self._st, data, o, n) + if not kind then + return nil, Err.from(msg) + end + self.frames += 1 + if kind ~= "dup" then + self._any = true + end + return kind, nil +end + +-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) +function Dec.reset(self: TheoraDecoder) + local st = self._st + st.shown = st.prev +end + +local function window(self: TheoraDecoder): (number, number, number, number) + local info = self.info + -- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom) + return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight +end + +-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, +-- chroma height +function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) + local st = self._st + local x0, y0, w, h = window(self) + local hd, vd = st.hdec, st.vdec + local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd + local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd + cw = math.min(cw, st.pw[2] - cx0) + ch = math.min(ch, st.ph[2] - cy0) + return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch +end + +-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) +function Dec.image(self: TheoraDecoder): Types.Image + local y, u, v, cw, ch = self:planes() + local w, h = self.width, self.height + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local ow, oh = (w + 1) // 2, (h + 1) // 2 + buffer.copy(px, 0, y, 0, w * h) + local st = self._st + if st.hdec == 1 and st.vdec == 1 then + for r = 0, oh - 1 do + local sr = math.min(r, ch - 1) + buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw)) + buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw)) + end + else + Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh) + Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace } + return img +end + +-- ------------------------------------------------------------------------------------------------ registry +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config +-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat +function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + if not track.config then + return nil, Err.new(Err.CORRUPT, "Theora track without its headers") + end + local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local d = dec :: TheoraDecoder + local pending: { any } = {} + local self: any = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local kind, e = d:decode(packet.data) + if not kind then + return e + end + if d._any then + table.insert(pending, { d:image(), packet.pts, kind == "key" }) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local p = table.remove(pending, 1) + if not p then + return nil, nil, nil + end + return p[1], p[2], p[3] + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(pending) + d:reset() + end + return self, nil +end + +return Theora diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..d986129 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -294,6 +294,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec return H264.newVideoDecoder(track, opts) end +-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv +-- builds the same); one picture per packet, empty packets repeat the previous one +local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Theora = require("@formats/codecs/video/Theora") + return Theora.newVideoDecoder(track, opts) +end + -- ------------------------------------------------------------------------------------------------ registry -- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. local BUILTIN: { Entry } = { @@ -307,7 +314,7 @@ local BUILTIN: { Entry } = { { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, { 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 = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, } diff --git a/tests/codecs/theora.luau b/tests/codecs/theora.luau new file mode 100644 index 0000000..f6dbbf9 --- /dev/null +++ b/tests/codecs/theora.luau @@ -0,0 +1,285 @@ +-- codecs/video/Theora tests. Against ffmpeg (tools/fixtures/theora.py, its vp3 decoder = libtheora's output): every +-- frame of every stream, bit-exact (Adler-32 of the native planes of the picture region, as ffmpeg's framecrc): 4:2:0 / +-- 4:2:2 / 4:4:4, qualities 0..10, a 300 kbit/s high-motion stream (4MV, golden frames, multiple qi), picture regions +-- smaller than the coded frame (even sizes from the encoder, odd sizes at offsets patched into the header), frames +-- the encoder dropped (empty packets: ffmpeg outputs nothing, we repeat the previous picture) and one spliced in; +-- image() as yuv420p (4:2:2 / 4:4:4 chroma averaged); Theora in Matroska through the codecs/video/Video registry. +-- Errors: missing / bad headers, maxPixels, header packets in the data, garbage packets; the fuzz no-throw passes +-- (headers, key and inter frames). +local T = require("@tests/T") +local Theora = require("@formats/codecs/video/Theora") +local Video = require("@formats/codecs/video/Video") +local Ogg = require("@formats/containers/Ogg") +local Mkv = require("@formats/video/mkv") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Adler32 = require("@formats/core/Adler32") +local Err = require("@formats/core/Err") + +local t = T.suite("theora") + +local CASES = { "q6", "q0", "q10", "motion", "odd", "static", "yuv422", "yuv444", "odd444", "crop", "crop422" } +local FIXTURES: { [string]: any } = { + q6 = require("@tests/gen/theora_q6"), + q0 = require("@tests/gen/theora_q0"), + q10 = require("@tests/gen/theora_q10"), + motion = require("@tests/gen/theora_motion"), + odd = require("@tests/gen/theora_odd"), + static = require("@tests/gen/theora_static"), + yuv422 = require("@tests/gen/theora_yuv422"), + yuv444 = require("@tests/gen/theora_yuv444"), + odd444 = require("@tests/gen/theora_odd444"), + crop = require("@tests/gen/theora_crop"), + crop422 = require("@tests/gen/theora_crop422"), +} + +-- the Theora packets of an Ogg file: headers, data packets +local function packets(file: buffer): ({ buffer }, { buffer }) + local d = Ogg.open(file) + local serial = d:find("theora") + local hdrs, data = {}, {} + for p in d:packets(serial) do + if #hdrs < 3 then + table.insert(hdrs, Ogg.copy(p)) + else + table.insert(data, Ogg.copy(p)) + end + end + return hdrs, data +end + +-- ffmpeg's framecrc: Adler-32 started at 0 over the packed planes +local function crc(y: buffer, u: buffer, v: buffer): number + local a = Adler32.of(y, nil, nil, 0) + a = Adler32.of(u, nil, nil, a) + return Adler32.of(v, nil, nil, a) +end + +local samples: { buffer } = {} +local headerSets: { { buffer } } = {} + +-- 1. every fixture, every frame +for _, name in CASES do + local fx = FIXTURES[name] + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + table.insert(headerSets, hdrs) + local dec, err = Theora.new(hdrs) + t:check(dec ~= nil, name .. ": headers: " .. tostring(err)) + if dec then + t:eq(dec.width, fx.width, name .. ": width") + t:eq(dec.height, fx.height, name .. ": height") + t:eq(dec.pixelFormat, fx.pixfmt, name .. ": pixel format") + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + local bad, dupes, prev = 0, 0, nil :: number? + for k, p in data do + local kind, e = dec:decode(p) + if not kind then + bad += 1 + t:check(false, name .. ": frame " .. (k - 1) .. ": " .. tostring(e)) + continue + end + local y, u, v = dec:planes() + local c = crc(y, u, v) + local w = want[k - 1] + if kind == "dup" then + dupes += 1 + t:check(w == nil, name .. ": ffmpeg shows no frame for empty packet " .. (k - 1)) + if c ~= prev then + bad += 1 + end + elseif w ~= c then + bad += 1 + end + prev = c + end + t:eq(bad, 0, name .. ": frames different from ffmpeg's (of " .. #data .. ", " .. dupes .. " repeated)") + t:eq(#data - dupes, #fx.frames, name .. ": as many shown frames as ffmpeg") + table.insert(samples, data[1]) + if data[2] then + table.insert(samples, data[2]) + end + end +end + +-- 2. an empty packet spliced in after the 5th frame repeats it; the rest follows +do + local fx = require("@tests/gen/theora_dupe") :: any + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + local bad, prev = 0, nil :: number? + for k, p in data do + local kind = dec:decode(p) + local y, u, v = dec:planes() + local c = crc(y, u, v) + if k == 6 then + t:eq(kind, "dup", "dupe: the empty packet") + t:eq(buffer.len(p), 0, "dupe: it is empty") + t:eq(c, prev, "dupe: repeats the previous picture") + elseif c ~= fx.frames[if k > 6 then k - 1 else k][2] then + bad += 1 + end + prev = c + end + t:eq(bad, 0, "dupe: the other frames") +end + +-- 3. image(): yuv420p, the planes as they are (4:2:0) or averaged (4:2:2 / 4:4:4) +for _, name in { "q6", "crop", "yuv422", "crop422", "odd444" } do + local fx = FIXTURES[name] + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + dec:decode(data[1]) + dec:decode(data[2]) + local img = dec:image() + local y, u, v, cw, ch = dec:planes() + local w, h = dec.width, dec.height + local ow, oh = (w + 1) // 2, (h + 1) // 2 + t:eq(img.format, "yuv420p", name .. ": image format") + t:eq(img.width * 1000 + img.height, w * 1000 + h, name .. ": image size") + t:eq(buffer.len(img.pixels), w * h + 2 * ow * oh, name .. ": image bytes") + t:eq(Adler32.of(img.pixels, 0, w * h), Adler32.of(y), name .. ": luma") + local bad = 0 + for r = 0, oh - 1 do + for c = 0, ow - 1 do + local want + if fx.pixfmt == "yuv420p" then + want = buffer.readu8(u, math.min(r, ch - 1) * cw + c) + elseif fx.pixfmt == "yuv422p" then + want = (buffer.readu8(u, math.min(2 * r, ch - 1) * cw + c) + buffer.readu8(u, math.min(2 * r + 1, ch - 1) * cw + c) + 1) // 2 + else + local r0, r1 = math.min(2 * r, ch - 1), math.min(2 * r + 1, ch - 1) + local c0, c1 = math.min(2 * c, cw - 1), math.min(2 * c + 1, cw - 1) + want = (buffer.readu8(u, r0 * cw + c0) + buffer.readu8(u, r0 * cw + c1) + buffer.readu8(u, r1 * cw + c0) + buffer.readu8(u, r1 * cw + c1) + 2) // 4 + end + if buffer.readu8(img.pixels, w * h + r * ow + c) ~= want then + bad += 1 + end + end + end + t:eq(bad, 0, name .. ": U downsampled") + local _ = v + t:eq(img.meta.yuv and img.meta.yuv.matrix, "bt601", name .. ": colour matrix") +end + +-- 4. Theora in Matroska: the registry entry (V_THEORA, Xiph-laced CodecPrivate) through video/mkv +do + t:eq(Video.fromMatroska("V_THEORA"), "theora", "registry: V_THEORA") + t:check(Video.canDecode("theora"), "registry: theora decodes") + local fx = require("@tests/gen/theora_mkv") :: any + local v, err = Mkv.open(Bytes.reader(Base64.decode(fx.file) :: buffer)) + t:check(v ~= nil, "mkv: open: " .. tostring(err)) + if v then + t:eq(v.codec, "theora", "mkv: codec") + local n, bad, shown = 0, 0, 0 + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + while true do + local f, e = v:nextFrame() + if not f then + t:check(e == nil, "mkv: frames: " .. tostring(e)) + break + end + local img = f.image + local w = want[math.floor(f.pts * 25 + 0.5)] + if w then + shown += 1 + if Adler32.of(img.pixels, nil, nil, 0) ~= w then + bad += 1 + end + end + n += 1 + end + t:eq(bad, 0, "mkv: frames as ffmpeg's") + t:eq(shown, #fx.frames, "mkv: every frame ffmpeg shows") + end +end + +-- 5. API details and errors +do + local fx = FIXTURES.q6 + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + t:eq(dec.frameRate, 25, "frame rate") + t:check(dec.vendor ~= "" and dec.tags.encoder ~= nil, "comment header: vendor and ENCODER tag") + t:eq(Theora.isHeader(hdrs[1]), 1, "isHeader: identification") + t:eq(Theora.isHeader(hdrs[3]), 3, "isHeader: setup") + t:eq(Theora.isHeader(data[1]), nil, "isHeader: data") + local kind, e = dec:decode(hdrs[2]) + t:check(kind == nil and e == nil, "a header packet in the data is skipped") + t:eq(Theora.granuleFrame(dec.info, 0), -1, "granule 0 (3.2.1 numbering)") + t:eq(Theora.granuleFrame(dec.info, 2 ^ dec.info.granuleShift * 12 + 3), 14, "granule: keyframe 12 + 3") + -- the Xiph-laced config Matroska uses + local lens = { buffer.len(hdrs[1]), buffer.len(hdrs[2]) } + local w = Bytes.writer(64) + w:u8(2) + for _, l in lens do + local x = l + while x >= 255 do + w:u8(255) + x -= 255 + end + w:u8(x) + end + for _, h in hdrs do + w:bytes(h) + end + local cfg = w:finish() + local parts = Theora.splitConfig(cfg) + t:check(parts ~= nil and #parts == 3 and buffer.len(parts[3]) == buffer.len(hdrs[3]), "splitConfig") + t:check(Theora.new(cfg) ~= nil, "new(config)") + local d2, e2 = Theora.new({ hdrs[1], hdrs[2] }) + t:check(d2 == nil and e2 ~= nil and e2.code == Err.CORRUPT, "missing setup header: CORRUPT") + local _, e3 = Theora.new({ hdrs[2], hdrs[1], hdrs[3] }) + t:check(e3 ~= nil and e3.code == Err.CORRUPT, "headers out of order: CORRUPT") + local cut = buffer.create(100) + buffer.copy(cut, 0, hdrs[3], 0, 100) + local _, e4 = Theora.new({ hdrs[1], hdrs[2], cut }) + t:check(e4 ~= nil, "truncated setup header: " .. tostring(e4)) + local _, e5 = Theora.new(hdrs, { maxPixels = 1000 }) + t:check(e5 ~= nil and e5.code == Err.LIMIT, "maxPixels: LIMIT") + local _, e6 = dec:decode(data[1], 5, buffer.len(data[1])) + t:check(e6 ~= nil and e6.code == Err.ARG, "decode: range outside the buffer") + -- an inter frame before any keyframe decodes over grey + local fresh = Theora.new(hdrs) :: Theora.TheoraDecoder + t:check(fresh:decode(data[2]) == "inter", "an inter frame first") + local track: any = { id = 1, kind = "video", codec = "theora", timescale = 25, config = cfg } + local vd = Theora.newVideoDecoder(track) + t:check(vd ~= nil, "newVideoDecoder") + if vd then + vd:decode({ track = 1, pts = 0, keyframe = true, data = data[1] }) + local img, pts, key = vd:receive() + t:check(img ~= nil and pts == 0 and key == true, "newVideoDecoder: a keyframe picture") + vd:reset() + t:check(vd:receive() == nil, "newVideoDecoder: reset drops pending pictures") + end + local nv, nerr = Theora.newVideoDecoder({ id = 1, kind = "video", codec = "theora", timescale = 25 } :: any) + t:check(nv == nil and nerr ~= nil, "newVideoDecoder without config") +end + +-- 6. fuzz: headers, keyframes and inter frames (a decoder primed with a keyframe, fed mutated packets) +do + local hdrs = headerSets[1] + t:fuzz("headers", function(b: buffer) + return Theora.new({ hdrs[1], hdrs[2], b }) + end, { hdrs[3] }, { mutations = 24, garbage = 50 }) + t:fuzz("identification", function(b: buffer) + return Theora.new({ b, hdrs[2], hdrs[3] }) + end, { hdrs[1] }, { mutations = 24, garbage = 20 }) + for i, h in headerSets do + local dec = Theora.new(h) :: Theora.TheoraDecoder + local s = { samples[2 * i - 1], samples[2 * i] } + dec:decode(s[1]) + t:fuzz("frames " .. CASES[i], function(b: buffer) + local kind = dec:decode(b) + dec:planes() + return kind + end, s, { mutations = 12, garbage = 20, seed = i }) + end +end + +t:done() diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py new file mode 100644 index 0000000..4395444 --- /dev/null +++ b/tools/fixtures/theora.py @@ -0,0 +1,195 @@ +# Theora fixtures for codecs/video/Theora and video/ogv (tools/fixtures.py): Ogg Theora files made by ffmpeg's +# libtheora encoder (testsrc2 / mandelbrot / static bars, several qualities and bit rates, odd sizes = picture regions +# smaller than the coded frame (the encoder keeps even sizes; two cases patch odd ones at offsets), 4:2:2 and 4:4:4, short and long keyframe intervals), one with an empty packet (a +# repeated frame) spliced in, an Ogg with Vorbis audio, and Theora in Matroska. The reference is ffmpeg's own decode +# (its vp3 decoder, bit-exact with libtheora): `-f framecrc` in the stream's native pixel format, one Adler-32 per +# frame over the packed planes of the picture region, with the frame's pts. +# tests/gen/theora_.luau { name, width, height, pixfmt, file (base64 .ogv), frames = { { pts, adler } } } +# tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original) +# tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64), +# rate, channels } +# tests/gen/theora_mkv.luau { file (base64 .mkv), frames } +# tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } for tools/bench.luau +import base64, os, shutil, struct, subprocess, tempfile, zlib + +FF = ["-hide_banner", "-loglevel", "error", "-y"] + + +def b64(b): + return base64.b64encode(b).decode() + + +def src(kind, w, h, rate, t): + return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)] + + +# name: (input args, encoder args, pixel format) +CASES = { + "q6": (src("testsrc2", 320, 240, 25, 1.2), ["-q:v", "6", "-g", "12"], "yuv420p"), + "q0": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "0", "-g", "30"], "yuv420p"), + "q10": (src("mandelbrot", 176, 144, 25, 0.6), ["-q:v", "10", "-g", "8"], "yuv420p"), + "motion": (src("mandelbrot", 240, 160, 30, 1.5), ["-b:v", "300k", "-g", "64"], "yuv420p"), + "odd": (src("testsrc2", 174, 98, 25, 1), ["-q:v", "5", "-g", "10"], "yuv420p"), + "static": (src("smptebars", 160, 120, 25, 1.2), ["-q:v", "4", "-g", "100"], "yuv420p"), + "yuv422": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "6", "-g", "12"], "yuv422p"), + "yuv444": (src("mandelbrot", 144, 112, 25, 1), ["-q:v", "6", "-g", "12"], "yuv444p"), + "odd444": (src("testsrc2", 98, 62, 25, 0.6), ["-q:v", "7", "-g", "6"], "yuv444p"), +} +# ffmpeg's encoder writes even picture sizes at offset 0: these cases patch the identification header to an odd +# picture region at an offset (width, height, x, y from the bottom); the reference is ffmpeg's decode of the patched +# file (-flags unaligned: the exact crop) +PATCH = { + "crop": (src("testsrc2", 176, 112, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv420p", (171, 97, 3, 5)), + "crop422": (src("mandelbrot", 128, 96, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv422p", (117, 81, 5, 2)), +} + + +def crc32(b): + return zlib.crc32(b) & 0xFFFFFFFF + + +def ogg_pages(data): + """yield (header fields, segment table, body) of each Ogg page""" + i = 0 + while i + 27 <= len(data): + assert data[i:i + 4] == b"OggS" + flags, granule, serial, seq = data[i + 5], struct.unpack_from("> 24) ^ x) & 0xFF]) & 0xFFFFFFFF + return c + + +def page(flags, granule, serial, seq, packets_segs, body): + head = b"OggS" + bytes([0, flags]) + struct.pack("> 5 + out = [] + seq = 0 + frames = [] + data_packets = packets[3:] + data_packets = data_packets[:after] + [b""] + data_packets[after:] + key = 0 + for k, p in enumerate(packets[:3]): + segs = [255] * (len(p) // 255) + [len(p) % 255] + out.append(page(2 if k == 0 else 0, 0, sid, seq, segs, p)) + seq += 1 + for k, p in enumerate(data_packets): + n = k + 1 + if len(p) > 0 and not (p[0] & 0x40): + key = n + segs = [255] * (len(p) // 255) + [len(p) % 255] + g = (key << shift) | (n - key) + out.append(page(4 if k == len(data_packets) - 1 else 0, g, sid, seq, segs, p)) + seq += 1 + return b"".join(out) + + +def patch_picture(data, w, h, x, y): + """rewrite the first page (the identification header) with another picture region""" + out = bytearray(data) + n = out[26] + o = 27 + n # the packet starts here + assert out[o:o + 7] == b"\x80theora" + out[o + 14:o + 17] = w.to_bytes(3, "big") + out[o + 17:o + 20] = h.to_bytes(3, "big") + out[o + 20] = x + out[o + 21] = y + plen = 27 + n + sum(out[27:27 + n]) + out[22:26] = b"\0\0\0\0" + struct.pack_into(" Date: Sat, 31 Oct 2026 14:20:17 -0500 Subject: [PATCH 05/19] codecs/video/Legacy: Cinepak, Microsoft Video 1, QuickTime RLE / SMC and FLIC decoders Registry decoders (codecs/video/Video BUILTIN: cvid, CRAM / MSVC / WHAM, 'rle ', 'smc ', AFLC), rgba8 pictures painted over the previous picture, palettes from track.palette (or packet.palette). Bit-exact with ffmpeg on 28 AVI / MOV / MKV fixtures (tools/fixtures/legacy.py: ffmpeg's encoders plus encoders in _legacy_mux.py for QuickTime RLE 1/2/4/8-bit, 8-bit MS Video 1 and Cinepak). Also fixes QtPalette's big-endian reads. --- docs/FORMATS.md | 1 + src/Formats/codecs/video/Legacy/Cinepak.luau | 303 ++++++++++++++ src/Formats/codecs/video/Legacy/Flic.luau | 372 +++++++++++++++++ src/Formats/codecs/video/Legacy/Msvideo1.luau | 121 ++++++ src/Formats/codecs/video/Legacy/Picture.luau | 115 ++++++ src/Formats/codecs/video/Legacy/QtRle.luau | 276 +++++++++++++ src/Formats/codecs/video/Legacy/Smc.luau | 183 +++++++++ src/Formats/codecs/video/Legacy/init.luau | 187 +++++++++ src/Formats/codecs/video/Video/init.luau | 14 + src/Formats/containers/IsoBmff/QtPalette.luau | 9 +- src/Formats/video/mkv/Parse.luau | 5 +- tests/codecs/legacy.luau | 113 ++++++ tools/fixtures/_legacy_mux.py | 375 ++++++++++++++++++ tools/fixtures/legacy.py | 100 +++++ 14 files changed, 2171 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/video/Legacy/Cinepak.luau create mode 100644 src/Formats/codecs/video/Legacy/Flic.luau create mode 100644 src/Formats/codecs/video/Legacy/Msvideo1.luau create mode 100644 src/Formats/codecs/video/Legacy/Picture.luau create mode 100644 src/Formats/codecs/video/Legacy/QtRle.luau create mode 100644 src/Formats/codecs/video/Legacy/Smc.luau create mode 100644 src/Formats/codecs/video/Legacy/init.luau create mode 100644 tests/codecs/legacy.luau create mode 100644 tools/fixtures/_legacy_mux.py create mode 100644 tools/fixtures/legacy.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..b7c26a7 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -133,5 +133,6 @@ 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/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/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/src/Formats/codecs/video/Legacy/Cinepak.luau b/src/Formats/codecs/video/Legacy/Cinepak.luau new file mode 100644 index 0000000..a7ed8d9 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Cinepak.luau @@ -0,0 +1,303 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 +-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description +-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 +-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame +-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are +-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra +-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak +-- decoder. Never throws: every read is range-checked against its chunk. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band = bit32.band + +local Cinepak = {} + +local MAX_STRIPS = 32 +-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index) +local ENTRY = 16 +local BOOK = 256 * ENTRY + +export type State = { + books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip) + filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet) +} + +function Cinepak.state(): State + return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 } +end + +local function be16(d: buffer, o: number): number + return readu8(d, o) * 256 + readu8(d, o + 1) +end +local function be24(d: buffer, o: number): number + return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2) +end +local function be32(d: buffer, o: number): number + return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3) +end + +local function clip(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set +local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number) + local six = band(id, 4) == 0 + local partial = band(id, 1) ~= 0 + local size = if six then 6 else 4 + local flag, mask = 0, 0 + for i = 0, 255 do + if partial then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + end + if not partial or band(flag, mask) ~= 0 then + if p + size > stop then + return + end + local e = book + i * ENTRY + local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3) + if six then + local u, v = readu8(d, p + 4), readu8(d, p + 5) + if u >= 128 then + u -= 256 + end + if v >= 128 then + v -= 256 + end + local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero) + local dr, dg, db = 2 * v, -uh - v, 2 * u + writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000) + writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000) + writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000) + writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000) + else + writeu32(books, e, y0 * 0x10101 + 0xFF000000) + writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000) + writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000) + writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000) + end + p += size + end + end +end + +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, + stop: number, x1: number, y1: number, x2: number, y2: number): boolean + local stride = pic.stride + local pal = pic.idx + local px = (pal or pic.rgba) :: buffer + local flag, mask = 0, 0 + local inter = band(id, 1) ~= 0 + local v1only = band(id, 2) ~= 0 + for y = y1, y2 - 1, 4 do + for x = x1, x2 - 1, 4 do + local paint = true + if inter then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + paint = band(flag, mask) ~= 0 + end + if paint then + local useV1 = v1only + if not v1only then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + useV1 = band(flag, mask) == 0 + end + local o = y * stride + x + if useV1 then + if p >= stop then + return false + end + local e = v1 + readu8(d, p) * ENTRY + p += 1 + -- each of the 4 entries fills a 2x2 square + local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12) + if pal then + a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256 + writeu32(px, o, a * 0x0101 + b * 0x01010000) + writeu32(px, o + stride, a * 0x0101 + b * 0x01010000) + writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000) + writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000) + else + for r = 0, 3 do + local q = (o + r * stride) * 4 + local l, rr = if r < 2 then a else c, if r < 2 then b else e4 + writeu32(px, q, l) + writeu32(px, q + 4, l) + writeu32(px, q + 8, rr) + writeu32(px, q + 12, rr) + end + end + else + if p + 4 > stop then + return false + end + local e0 = v4 + readu8(d, p) * ENTRY + local e1 = v4 + readu8(d, p + 1) * ENTRY + local e2 = v4 + readu8(d, p + 2) * ENTRY + local e3 = v4 + readu8(d, p + 3) * ENTRY + p += 4 + -- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right) + if pal then + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = o + r * stride + writeu8(px, q, readu8(books, l + off)) + writeu8(px, q + 1, readu8(books, l + off + 4)) + writeu8(px, q + 2, readu8(books, rr + off)) + writeu8(px, q + 3, readu8(books, rr + off + 4)) + end + else + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = (o + r * stride) * 4 + writeu32(px, q, readu32(books, l + off)) + writeu32(px, q + 4, readu32(books, l + off + 4)) + writeu32(px, q + 8, readu32(books, rr + off)) + writeu32(px, q + 12, readu32(books, rr + off + 4)) + end + end + end + end + end + end + return true +end + +-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this +-- packet (an empty frame); false + message = an error +function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) + local n = buffer.len(d) + if n < 10 then + return false, "frame too short" + end + local strips = be16(d, 8) + if strips == 0 and not (pic.idx and newPalette) then + return false, nil + end + local size = be24(d, 1) + if n < size * 5 // 100 then + return false, "frame shorter than its header says" + end + if st.filmSkip < 0 then + if size == 0 then + return false, "unsupported: a zero frame size" + end + if size ~= n and n % size ~= 0 then + if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6 + and readu8(d, 14) == 0 and readu8(d, 15) == 0 then + st.filmSkip = 6 + else + st.filmSkip = 2 + end + else + st.filmSkip = 0 + end + end + local skip = st.filmSkip + if n < 10 + skip + strips * 12 then + return false, "truncated strip headers" + end + if strips > 0 then + local ss = be24(d, 10 + skip + 1) + if ss < 12 or ss > size then + return false, "bad strip size" + end + end + local flags = readu8(d, 0) + local p = 10 + skip + strips = math.min(strips, MAX_STRIPS) + local books = st.books + -- the coded area: the size rounded up to whole blocks (the picture's plane) + local cw, ch = pic.stride, pic.rows + local y0 = 0 + for i = 0, strips - 1 do + if p + 12 > n then + return true, nil + end + local sy1 = be16(d, p + 4) + local sx1 = be16(d, p + 6) + local sy2, sx2 = be16(d, p + 8), be16(d, p + 10) + if sy1 == 0 then + sy1 = y0 + sy2 = y0 + sy2 + end + local ssize = be24(d, p + 1) - 12 + if ssize < 0 then + return true, nil + end + p += 12 + local stop = math.min(n, p + ssize) + local v4 = i * 2 * BOOK + local v1 = v4 + BOOK + if i > 0 and band(flags, 1) == 0 then + buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) + end + -- the strip's chunks: codebooks, then one vector chunk + -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) + if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then + return true, nil + end + local q = p + local done = false + while q + 4 <= stop do + local id = readu8(d, q) + local csize = be24(d, q + 1) - 4 + if csize < 0 then + return true, nil + end + q += 4 + local cstop = math.min(stop, q + csize) + if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then + codebook(books, v4, id, d, q, cstop) + elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then + codebook(books, v1, id, d, q, cstop) + elseif id == 0x30 or id == 0x31 or id == 0x32 then + if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then + return true, nil + end + done = true + break + end + q = cstop + end + if not done then + return true, nil + end + p = stop + y0 = sy2 + end + return true, nil +end + +return Cinepak diff --git a/src/Formats/codecs/video/Legacy/Flic.luau b/src/Formats/codecs/video/Legacy/Flic.luau new file mode 100644 index 0000000..99c72f7 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Flic.luau @@ -0,0 +1,372 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is +-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's +-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit +-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK +-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX +-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); +-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet +-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. +-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +local Types = require("@formats/Types") +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local Flic = {} + +-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette +export type State = { + pic: Picture.Picture, + depth: number, -- 8, 15, 16, 24 + bpp: number, -- bytes per pixel +} + +-- state(w, h, depth) -> State | nil, message +function Flic.state(w: number, h: number, depth: number): (State?, string?) + local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 + if bpp == 0 then + return nil, "unsupported: " .. depth .. "-bit FLIC" + end + local pic = Picture.new(w * bpp, h, true) + pic.w = w + return { pic = pic, depth = depth, bpp = bpp }, nil +end + +local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- decode(st, data) -> true | false, message +function Flic.decode(st: State, d: buffer): (boolean, string?) + local pic = st.pic + local px = pic.idx :: buffer + local pal = pic.pal + local w, h = pic.w, pic.h + local bpp = st.bpp + local deep = bpp > 1 + local stride = pic.stride + local limit = stride * h + local n = buffer.len(d) + if n < 16 then + return false, "frame too short" + end + local p = 0 + local function u8(): number + local v = if p < n then readu8(d, p) else 0 + p += 1 + return v + end + local function u16(): number + local a = u8() + return a + u8() * 256 + end + local frameSize = math.min(readu32(d, 0), n) + local chunks = readu8(d, 6) + readu8(d, 7) * 256 + if frameSize < 16 then + return false, "bad frame size" + end + frameSize -= 16 + p = 16 + while frameSize >= 6 and chunks > 0 and n - p >= 4 do + local size = readu32(d, p) + if size > frameSize then + size = frameSize + end + local after = p + size + p += 4 + local typ = u16() + if typ == 4 or typ == 11 then + if not deep then + -- palette packets: skip count, change count (0 = 256), r g b + local shift = typ == 11 + local packets = u16() + local at = 0 + for _ = 1, packets do + at += u8() + local count = u8() + if count == 0 then + count = 256 + end + if p + count * 3 > after then + break + end + for _ = 1, count do + if at >= 256 then + at = 0 + end + local r, g, b = u8(), u8(), u8() + if shift then + -- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below + r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256 + r, g, b = r + r // 64, g + g // 64, b + b // 64 + end + writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000) + at += 1 + end + end + end + elseif typ == 7 or (deep and typ == 27) then + -- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode) + local y = 0 + local lines = u16() + while lines > 0 do + if p + 2 > after then + break + end + if y > limit then + return false, "delta past the picture" + end + local lp = u16() + if lp >= 0x8000 then + lp -= 0x10000 + end + if deep then + if lp < 0 then + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + end + elseif lp < 0 and lp >= -0x4000 then + -- 0xC000 .. 0xFFFF: skip lines + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + elseif lp < 0 then + -- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its + -- padded row instead: the same pixel when rows are not padded) + local q = y + w - 1 + if q < 0 or q >= limit then + return false, "delta past the picture" + end + writeu8(px, q, lp % 256) + continue + elseif lp >= 0x4000 then + continue -- undefined opcode + end + lines -= 1 + local q = y + for _ = 1, lp do + if p + 2 > after then + break + end + q += u8() * bpp + local run = s8(u8()) + if deep then + local cnt = if run < 0 then -run else run + if q + cnt * bpp > limit then + return false, "delta past the picture" + end + if run < 0 then + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + else + if p + cnt * bpp > after then + break + end + buffer.copy(px, q, d, p, cnt * bpp) + p += cnt * bpp + q += cnt * bpp + end + elseif run < 0 then + local cnt = -run + local a, b = u8(), u8() + if q + cnt * 2 > limit then + return false, "delta past the picture" + end + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + q += 2 + end + else + if q + run * 2 > limit then + return false, "delta past the picture" + end + if p + run * 2 > after then + break + end + buffer.copy(px, q, d, p, run * 2) + p += run * 2 + q += run * 2 + end + end + y += stride + end + elseif typ == 12 and not deep then + -- byte-oriented delta (LC): first line, line count, per line packets of (skip, run) + local first = u16() + if first >= h then + return false, "bad first line" + end + local y = first * stride + local lines = u16() + while lines > 0 do + local q = y + if q > limit then + return false, "delta past the picture" + end + if p + 1 > after then + break + end + local packets = u8() + for _ = 1, packets do + if p + 1 > after then + break + end + q += u8() + local run = s8(u8()) + if run > 0 then + if q + run > limit then + return false, "delta past the picture" + end + if p + run > after then + break + end + buffer.copy(px, q, d, p, run) + p += run + q += run + elseif run < 0 then + local v = u8() + if q - run > limit then + return false, "delta past the picture" + end + bfill(px, q, v, -run) + q -= run + end + end + y += stride + lines -= 1 + end + elseif typ == 13 then + bfill(px, 0, 0, limit) + elseif typ == 15 or (deep and typ == 25) then + -- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals + local unit = if typ == 25 then bpp else 1 + local y = 0 + for _ = 1, h do + local q = y + p += 1 -- the packet count (unused) + local left = if typ == 25 then w else w * bpp + while left > 0 do + if p + 1 > after then + break + end + local run = s8(u8()) + if run == 0 and not deep then + return false, "zero byte run" + end + if run > 0 then + if q + run * unit > limit then + return false, "run past the picture" + end + if unit == 1 then + bfill(px, q, u8(), run) + q += run + else + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, run do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + end + left -= run + else + local cnt = -run + if q + cnt * unit > limit then + return false, "run past the picture" + end + if p + cnt * unit > after then + break + end + buffer.copy(px, q, d, p, cnt * unit) + p += cnt * unit + q += cnt * unit + left -= cnt + end + end + y += stride + end + elseif typ == 16 or (deep and typ == 26) then + -- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more) + local row = w * bpp + local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4 + local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h + if ok then + if deep and n - p < row * h then + return false, "truncated copy chunk" + end + for y = 0, h - 1 do + local s = p + y * padded + local cnt = math.max(0, math.min(row, n - s)) + if cnt > 0 then + buffer.copy(px, y * stride, d, s, cnt) + end + end + p += padded * h + end + end + -- typ 18 (PSTAMP) and unknown chunks are skipped + if after - p >= 0 then + p = after + else + break + end + frameSize -= size + chunks -= 1 + end + return true, nil +end + +-- image(st) -> a fresh rgba8 Image +function Flic.image(st: State): Types.Image + local pic = st.pic + if st.bpp == 1 then + return Picture.image(pic) + end + local w, h = pic.w, pic.h + local img = Types.Image.new(w, h, "rgba8") + local out = img.pixels + local px = pic.idx :: buffer + local stride = pic.stride + if st.bpp == 3 then + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 3 + writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000) + end + end + else + local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565() + local mask = if st.depth == 15 then 32768 else 65536 + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 2 + writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4)) + end + end + end + return img +end + +return Flic diff --git a/src/Formats/codecs/video/Legacy/Msvideo1.luau b/src/Formats/codecs/video/Legacy/Msvideo1.luau new file mode 100644 index 0000000..417ad45 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Msvideo1.luau @@ -0,0 +1,121 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit +-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows +-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour +-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour +-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. +-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band = bit32.band + +local Msvideo1 = {} + +-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 +-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +local function quadrant(x: number, y: number): number + return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) +end + +-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) +function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) + local n = buffer.len(d) + local bw, bh = pic.w // 4, pic.h // 4 + if n < bw * bh // 512 then + return false, "frame too small" + end + local stride = pic.stride + local total = bw * bh + local skip = 0 + local p = 0 + local wide = bits ~= 8 + local px = (if wide then pic.rgba else pic.idx) :: buffer + local lut = if wide then Picture.rgb555() else nil + local c = table.create(8, 0) + for by = bh - 1, 0, -1 do + for bx = 0, bw - 1 do + if skip ~= 0 then + skip -= 1 + total -= 1 + continue + end + if p + 2 > n then + return true, nil + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + if a == 0 and b == 0 and total == 0 then + return true, nil + end + -- the block's bottom-left pixel; its rows go up + local o = (by * 4 + 3) * stride + bx * 4 + if band(b, 0xFC) == 0x84 then + skip = (b - 0x84) * 256 + a - 1 + elseif b < 0x80 or (not wide and b >= 0x90) then + local flags = b * 256 + a + local eight + if wide then + if p + 4 > n then + return true, nil + end + c[1], c[2] = readu16(d, p), readu16(d, p + 2) + p += 4 + eight = c[1] >= 0x8000 + if eight then + if p + 12 > n then + return true, nil + end + for k = 3, 8 do + c[k] = readu16(d, p) + p += 2 + end + end + else + eight = b >= 0x90 + local cnt = if eight then 8 else 2 + if p + cnt > n then + return true, nil + end + for k = 1, cnt do + c[k] = readu8(d, p) + p += 1 + end + end + for y = 0, 3 do + local row = o - y * stride + for x = 0, 3 do + local k = (if band(flags, 1) == 1 then 1 else 2) + if eight then + k += quadrant(x, y) + end + flags = flags // 2 + if lut then + writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4)) + else + writeu8(px, row + x, c[k]) + end + end + end + else + local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a + for y = 0, 3 do + local row = o - y * stride + if lut then + for x = 0, 3 do + writeu32(px, (row + x) * 4, v) + end + else + writeu32(px, row, v * 0x01010101) + end + end + end + total -= 1 + end + end + return true, nil +end + +return Msvideo1 diff --git a/src/Formats/codecs/video/Legacy/Picture.luau b/src/Formats/codecs/video/Legacy/Picture.luau new file mode 100644 index 0000000..e4080c6 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Picture.luau @@ -0,0 +1,115 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame +-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, +-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past +-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication +-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in formats-luau. +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local Picture = {} + +export type Picture = { + w: number, + h: number, + stride: number, -- index plane: bytes per row; rgba plane: pixels per row + rows: number, + idx: buffer?, -- u8 index plane, stride * rows bytes (palettised) + rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour) + pal: buffer, -- 256 u32 entries, bytes R, G, B, A +} + +-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) +function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture + local pw, ph = padW or 1, padH or 1 + local stride = ((w + pw - 1) // pw) * pw + local rows = ((h + ph - 1) // ph) * ph + local pal = buffer.create(1024) + if palette and buffer.len(palette) >= 1024 then + buffer.copy(pal, 0, palette, 0, 1024) + end + local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal } + if palettised then + p.idx = buffer.create(stride * rows) + else + p.rgba = buffer.create(stride * rows * 4) + end + return p +end + +-- image(p) -> a fresh rgba8 Image of the visible w x h +function Picture.image(p: Picture): Types.Image + local w, h = p.w, p.h + local img = Types.Image.new(w, h, "rgba8") + local idx, rgba = p.idx, p.rgba + if idx then + Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal) + elseif rgba then + if p.stride == w then + buffer.copy(img.pixels, 0, rgba, 0, w * h * 4) + else + for y = 0, h - 1 do + buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4) + end + end + end + return img +end + +-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track +function Picture.setPalette(p: Picture, src: buffer) + if buffer.len(src) >= 1024 then + buffer.copy(p.pal, 0, src, 0, 1024) + end +end + +local lut555: buffer? = nil +local lut565: buffer? = nil + +-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries +function Picture.rgb555(): buffer + local t = lut555 + if t then + return t + end + local b = buffer.create(32768 * 4) + for v = 0, 32767 do + local r, g, bl = v // 1024, (v // 32) % 32, v % 32 + r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut555 = b + return b +end + +-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries +function Picture.rgb565(): buffer + local t = lut565 + if t then + return t + end + local b = buffer.create(65536 * 4) + for v = 0, 65535 do + local r, g, bl = v // 2048, (v // 32) % 64, v % 32 + r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut565 = b + return b +end + +-- copy of a picture's plane (for decoders that read the previous picture while writing the next) +function Picture.clonePlane(p: Picture): buffer + local src = (p.idx or p.rgba) :: buffer + local c = buffer.create(buffer.len(src)) + buffer.copy(c, 0, src, 0) + return c +end + +local _ = readu32 + +return Picture diff --git a/src/Formats/codecs/video/Legacy/QtRle.luau b/src/Formats/codecs/video/Legacy/QtRle.luau new file mode 100644 index 0000000..2c687e8 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/QtRle.luau @@ -0,0 +1,276 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File +-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per +-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). +-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its +-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames +-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read +-- and write is range-checked (a damaged frame stops where the damage is). +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local QtRle = {} + +local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line) +local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number) + row -= stride + local q = row + lines += 1 + while lines > 0 do + if p + 2 > n then + return + end + local skip = readu8(d, p) + local code = s8(readu8(d, p + 1)) + p += 2 + if code == 0 then + return + end + if skip >= 128 then + lines -= 1 + row += stride + q = row + 16 * (skip - 128) + else + q += 16 * skip + end + if q < 0 or q > limit then + return + end + if code ~= -1 then + if code < 0 then + local cnt = -code + if p + 2 > n or q + cnt * 16 > limit then + return + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + for _ = 1, cnt do + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(b, k), 1)) + q += 1 + end + end + else + local cnt = code * 2 + if p + cnt > n or q + cnt * 8 > limit then + return + end + for _ = 1, cnt do + local a = readu8(d, p) + p += 1 + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + end + end + end + end +end + +-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups +local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) + local group = 32 // bpp -- pixels per 4 bytes + local per = 8 // bpp -- pixels per byte + local mask = 2 ^ bpp - 1 + for _ = 1, lines do + if p >= n then + return + end + local q = row + group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + elseif code < 0 then + local cnt = -code + if p + 4 > n or q + cnt * group > limit then + return + end + if bpp == 8 then + local v = readu32(d, p) + for _ = 1, cnt do + writeu32(px, q, v) + q += 4 + end + else + local v0 = q + for b = 0, 3 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + for _ = 2, cnt do + buffer.copy(px, q, px, v0, group) + q += group + end + end + p += 4 + else + local bytes = code * 4 + if p + bytes > n or q + bytes * per > limit then + return + end + if bpp == 8 then + buffer.copy(px, q, d, p, bytes) + q += bytes + else + for b = 0, bytes - 1 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + end + p += bytes + end + end + row += stride + end +end + +-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels) +local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number) + local bpp = depth // 8 + local lut = if depth == 16 then Picture.rgb555() else nil + for _ = 1, lines do + if p >= n then + return + end + local q = row + (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += readu8(d, p) - 1 + p += 1 + if q < 0 or q > limit then + return + end + else + local cnt = if code < 0 then -code else code + local need = if code < 0 then bpp else bpp * cnt + if p + need > n or q + cnt > limit then + return + end + for _ = 1, cnt do + local v + if lut then + v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4) + elseif bpp == 3 then + v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000 + else + v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216 + end + writeu32(px, q * 4, v) + q += 1 + if code > 0 then + p += bpp + end + end + if code < 0 then + p += bpp + end + end + end + row += stride + end +end + +-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message +function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) + local n = buffer.len(d) + if n < 8 then + return true, nil -- no change + end + local p = 4 + local header = readu8(d, p) * 256 + readu8(d, p + 1) + p += 2 + local h = pic.h + local start, lines = 0, h + if band(header, 8) ~= 0 then + if n < 14 then + return true, nil + end + start = readu8(d, p) * 256 + readu8(d, p + 1) + lines = readu8(d, p + 4) * 256 + readu8(d, p + 5) + p += 8 + if lines > h - start then + return true, nil + end + end + local stride = pic.stride + local bits = if depth > 32 then depth - 32 else depth + local idx, rgba = pic.idx, pic.rgba + if idx and bits <= 8 then + local limit = stride * h + if bits == 1 then + decode1(idx, stride, limit, d, p, n, start * stride, lines) + else + decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits) + end + elseif rgba and (bits == 16 or bits == 24 or bits == 32) then + decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits) + else + return false, "unsupported: depth " .. depth + end + return true, nil +end + +-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs +function QtRle.palettised(depth: number): boolean + return depth <= 8 or depth > 32 +end +function QtRle.pad(depth: number): number + local bits = if depth > 32 then depth - 32 else depth + return if bits <= 8 then 32 // math.max(1, bits) else 1 +end + +return QtRle diff --git a/src/Formats/codecs/video/Legacy/Smc.luau b/src/Formats/codecs/video/Legacy/Smc.luau new file mode 100644 index 0000000..6ff9a60 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Smc.luau @@ -0,0 +1,183 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description +-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble +-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour +-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: +-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc +-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row +-- above). Never throws: reads past the data give zeros, the block count bounds every write. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smc = {} + +-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) +function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) + local px = pic.idx :: buffer + local n = buffer.len(d) + local stride = pic.stride -- a multiple of 4: the plane holds whole blocks + local bh = pic.rows // 4 + local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4) + if total // 1024 > n then + return false, "frame too small" + end + local blocksWide = (pic.w + 3) // 4 + local p = 4 -- flags byte + 24-bit chunk size + -- block position: bx, by (blocks) + local bx, by = 0, 0 + local pairI, quadI, octI = 0, 0, 0 + -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) + local function u8(): number + if p < n then + local v = readu8(d, p) + p += 1 + return v + end + return 0 + end + local function advance() + bx += 1 + if bx >= blocksWide then + bx = 0 + by += 1 + end + total -= 1 + end + while total > 0 do + if p >= n then + return false, "truncated" + end + local op = readu8(d, p) + p += 1 + local kind = rshift(op, 4) + local count: number + if kind < 8 then + count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15) + else + count = band(op, 15) + 1 + end + if kind <= 1 then + for _ = 1, count do + if total <= 0 then + break + end + advance() + end + elseif kind <= 5 then + -- repeat the last block (2, 3) or the last pair of blocks (4, 5) + local pair = kind >= 4 + local back = if pair then 2 else 1 + local pos = by * blocksWide + bx + if pos < back then + return false, "repeat before any block" + end + local reps = if pair then count * 2 else count + local srcA = pos - back + local srcB = pos - 1 + for k = 0, reps - 1 do + if total <= 0 or by >= bh then + break + end + local s = if pair and k % 2 == 1 then srcB else srcA + local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4 + local o, so = by * 4 * stride + bx * 4, sy * stride + sx + for r = 0, 3 do + writeu32(px, o + r * stride, readu32(px, so + r * stride)) + end + advance() + end + elseif kind <= 7 then + local c = u8() + local v = c * 0x01010101 + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for r = 0, 3 do + writeu32(px, o + r * stride, v) + end + advance() + end + elseif kind <= 13 then + -- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds) + local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8 + local base = if size == 2 then 0 elseif size == 4 then 512 else 1536 + local entry: number + if kind % 2 == 0 then + local i = if size == 2 then pairI elseif size == 4 then quadI else octI + for k = 0, size - 1 do + writeu8(tables, base + i * size + k, u8()) + end + entry = i + i = (i + 1) % 256 + if size == 2 then + pairI = i + elseif size == 4 then + quadI = i + else + octI = i + end + else + entry = u8() + end + local t = base + entry * size + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + if size == 2 then + local f = u8() * 256 + u8() + for k = 0, 15 do + local bit = band(rshift(f, 15 - k), 1) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit)) + end + elseif size == 4 then + local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8() + for k = 0, 15 do + local i = band(rshift(f, 30 - 2 * k), 3) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + else + -- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel) + local v1 = u8() * 256 + u8() + local v2 = u8() * 256 + u8() + local v3 = u8() * 256 + u8() + local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4) + local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15) + for k = 0, 15 do + local f = if k < 8 then fa else fb + local i = band(rshift(f, 21 - 3 * (k % 8)), 7) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + end + advance() + end + else + -- 16-colour blocks + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for k = 0, 15 do + writeu8(px, o + (k // 4) * stride + k % 4, u8()) + end + advance() + end + end + end + return true, nil +end + +-- tables() -> the colour group scratch (pairs, quads, octets) +function Smc.tables(): buffer + return buffer.create(512 + 1024 + 2048) +end + +return Smc diff --git a/src/Formats/codecs/video/Legacy/init.luau b/src/Formats/codecs/video/Legacy/init.luau new file mode 100644 index 0000000..51729a4 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/init.luau @@ -0,0 +1,187 @@ +--!strict +-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. +-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk +-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", +-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey) and QuickTime Graphics ("smc", 'smc '). +-- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's +-- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns +-- a fresh copy. +-- +-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the +-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that +-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). +-- +-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +-- +-- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Picture = require("@formats/codecs/video/Legacy/Picture") +local Flic = require("@formats/codecs/video/Legacy/Flic") +local Cinepak = require("@formats/codecs/video/Legacy/Cinepak") +local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1") +local QtRle = require("@formats/codecs/video/Legacy/QtRle") +local Smc = require("@formats/codecs/video/Legacy/Smc") + +local Legacy = {} + +Legacy.Picture = Picture +Legacy.Flic = Flic +Legacy.Cinepak = Cinepak +Legacy.Msvideo1 = Msvideo1 +Legacy.QtRle = QtRle +Legacy.Smc = Smc +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" } + +export type Options = { + maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) + [string]: any, +} + +-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? +type Codec = { + make: (track: Types.Track) -> (any, string?), + step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), +} + +local function fail(msg: string?): Err.Err + return Err.from(msg or "corrupt frame") +end + +local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean + local pal = (packet :: any).palette + if type(pal) == "buffer" then + Picture.setPalette(pic, pal) + return true + end + return false +end + +local CODECS: { [string]: Codec } = { + qtrle = { + make = function(t) + local depth = t.bitsPerPixel or 24 + local bits = if depth > 32 then depth - 32 else depth + if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then + return nil, "unsupported: depth " .. depth + end + return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = QtRle.decode(st.pic, data, st.depth) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + smc = { + make = function(t) + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = Smc.decode(st.pic, data, st.tables) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + msvideo1 = { + make = function(t) + if (t.width :: number) < 4 or (t.height :: number) < 4 then + return nil, "smaller than one block" + end + local bits = if t.bitsPerPixel == 8 then 8 else 16 + return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil + end, + step = function(st, data, packet) + if st.bits == 8 then + packetPalette(st.pic, packet) + end + local ok, msg = Msvideo1.decode(st.pic, data, st.bits) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + cinepak = { + make = function(t) + local pal = t.bitsPerPixel == 8 + return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil + end, + step = function(st, data, packet) + local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet) + local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal) + if not ok then + return nil, if msg then fail(msg) else nil + end + return Picture.image(st.pic), nil + end, + }, + flic = { + make = function(t) + return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) + end, + step = function(st, data, _packet) + local ok, msg = Flic.decode(st, data) + if not ok then + return nil, fail(msg) + end + return Flic.image(st), nil + end, + }, +} + +-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err +function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) + local codec = CODECS[id] + if not codec then + return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id)) + end + local w, h = track.width or 0, track.height or 0 + if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then + return nil, Err.new(Err.CORRUPT, "video track without a valid size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max or w > 32768 or h > 32768 then + return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit") + end + local st, msg = codec.make(track) + if not st then + return nil, fail(msg) + end + -- Video.simpleDecoder, without requiring the registry (which requires this module) + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(codec.step, st, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder failed: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + 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) end + function self.reset(_: any) + table.clear(queue) + st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + end + return self :: any, nil +end + +return Legacy diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..1b7cde8 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -294,6 +294,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec return H264.newVideoDecoder(track, opts) end +-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) +local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) + return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + return require("@formats/codecs/video/Legacy").newDecoder(id, track, opts) + end +end + -- ------------------------------------------------------------------------------------------------ registry -- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. local BUILTIN: { Entry } = { @@ -309,6 +316,13 @@ local BUILTIN: { Entry } = { { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, + -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) + { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, + { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, + { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, + { id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") }, + { id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") }, + { id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") }, } local byId: { [string]: Entry } = {} diff --git a/src/Formats/containers/IsoBmff/QtPalette.luau b/src/Formats/containers/IsoBmff/QtPalette.luau index 2034dc3..91b4524 100644 --- a/src/Formats/containers/IsoBmff/QtPalette.luau +++ b/src/Formats/containers/IsoBmff/QtPalette.luau @@ -10,7 +10,14 @@ -- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil -- -- Never throws. -local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 +local readu8, writeu32 = buffer.readu8, buffer.writeu32 + +local function readu16(b: buffer, o: number): number -- big-endian + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function readu32(b: buffer, o: number): number + return readu16(b, o) * 65536 + readu16(b, o + 2) +end local QtPalette = {} diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index 252a004..b4766d4 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -313,8 +313,9 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" t.codecTag = codecId t.codec = codecFor(codecId, t.kind, t.bitsPerSample) - if t.kind == "video" and t.config then - vfwOrQuickTime(t, codecId, t.config) + local cfg: buffer? = t.config + if t.kind == "video" and cfg then + vfwOrQuickTime(t, codecId, cfg) end if t.kind == "audio" then t.sampleRate = t.sampleRate or 8000 diff --git a/tests/codecs/legacy.luau b/tests/codecs/legacy.luau new file mode 100644 index 0000000..236f7d2 --- /dev/null +++ b/tests/codecs/legacy.luau @@ -0,0 +1,113 @@ +-- codecs/video/Legacy tests: Cinepak (24-bit, grey, 8-bit palettised, several strips, a 92x68 size), Microsoft Video 1 +-- (16-bit, 8-bit with an AVI palette), QuickTime RLE (depths 1 / 2 / 4 / 8 with colour tables, default Macintosh +-- tables and grey ramps; 16 / 24 / 32-bit and grey from ffmpeg) and QuickTime SMC, in AVI, MOV and MKV: every frame +-- equals ffmpeg's decode (CRC-32 of rgba); seeking; the registry entries; the fuzz pass on each codec's packet decoder. +-- Fixtures: tools/fixtures/legacy.py. +local T = require("@tests/T") +local F = require("@formats") +local Crc32 = require("@formats/core/Crc32") +local Video = require("@formats/codecs/video/Video") +local Legacy = require("@formats/codecs/video/Legacy") +local Fx = require("@tests/gen/legacy_cases") + +local t = T.suite("legacy") + +-- the registry +t:eq(Video.fromFourcc("cvid"), "cinepak", "cvid") +t:eq(Video.fromFourcc("CRAM"), "msvideo1", "CRAM") +t:eq(Video.fromFourcc("msvc"), "msvideo1", "msvc") +t:eq(Video.fromFourcc("rle "), "qtrle", "rle ") +t:eq(Video.fromFourcc("smc "), "smc", "smc ") +for _, id in Legacy.CODECS do + t:check(Video.canDecode(id), id .. ": decodable") +end + +local samples: { [string]: { any } } = {} + +for _, c in Fx do + local label = c.name + local v, err = F.video.open(c.data) + t:check(v ~= nil, label .. ": open: " .. tostring(err)) + if v then + t:eq(v.codec, c.codec, label .. ": codec") + t:eq(v.width, c.width, label .. ": width") + local n, bad, first = 0, 0, nil + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": decode error " .. tostring(ferr)) + break + end + n += 1 + local img = f.image + if img.format ~= "rgba8" or img.width ~= c.width or Crc32.of(img.pixels) ~= c.frames[n] then + bad += 1 + first = first or n + end + end + t:check(n == #c.frames and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ, first %s)", label, n - bad, #c.frames, bad, tostring(first))) + -- seeking: back to the start, the first frame again + v:seek(0) + local f = v:nextFrame() + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[1], label .. ": seek(0)") + -- packets for the fuzz pass + local dmx = v.demuxer + local tr = dmx:track("video") + if not samples[c.codec] then + local list = {} + for k = 1, math.min(3, dmx:count(tr.id)) do + table.insert(list, dmx:get(tr.id, k).data) + end + samples[c.codec] = { track = tr, packets = list } + end + end +end + +-- the fuzz pass on the native packet decoders (no pcall in between) +local P = Legacy.Picture +local raw: { [string]: (tr: any) -> (buffer) -> any } = { + cinepak = function(tr) + return function(b) + local pic = P.new(tr.width, tr.height, tr.bitsPerPixel == 8, 4, 4, tr.palette) + return Legacy.Cinepak.decode(pic, b, Legacy.Cinepak.state(), false) + end + end, + msvideo1 = function(tr) + return function(b) + local bits = if tr.bitsPerPixel == 8 then 8 else 16 + return Legacy.Msvideo1.decode(P.new(tr.width, tr.height, bits == 8, 4, 4), b, bits) + end + end, + qtrle = function(tr) + return function(b) + local d = tr.bitsPerPixel or 24 + for _, depth in { d, 1, 2, 4, 8, 16, 32 } do + Legacy.QtRle.decode(P.new(tr.width, tr.height, Legacy.QtRle.palettised(depth), Legacy.QtRle.pad(depth), 1), b, depth) + end + return true + end + end, + smc = function(tr) + return function(b) + return Legacy.Smc.decode(P.new(tr.width, tr.height, true, 4, 4), b, Legacy.Smc.tables()) + end + end, +} +for id, s in samples do + local fn = raw[id] + if fn then + t:fuzz(id .. " packets", fn(s.track), s.packets, { mutations = 24, garbage = 60 }) + end +end +t:fuzz("open", function(b: buffer) + local v = F.video.open(b) + if v then + for _ = 1, 3 do + if not v:nextFrame() then + break + end + end + end + return v +end, { Fx[1].data, Fx[#Fx].data }, { mutations = 8, garbage = 20 }) +t:done() diff --git a/tools/fixtures/_legacy_mux.py b/tools/fixtures/_legacy_mux.py new file mode 100644 index 0000000..c00c674 --- /dev/null +++ b/tools/fixtures/_legacy_mux.py @@ -0,0 +1,375 @@ +# Shared helpers for the legacy video fixture generators (legacy.py), loaded by path: tiny AVI and QuickTime MOV +# writers (one video track, constant frame rate) for streams encoded here, and small encoders for what ffmpeg cannot +# encode: QuickTime RLE at depths 1 / 2 / 4 / 8, Microsoft Video 1 at 8 bits, Cinepak at 8 bits (palettised). +import struct + + +def le16(v): + return struct.pack("H", v & 0xFFFF) + + +def be32(v): + return struct.pack(">I", v & 0xFFFFFFFF) + + +# ---------------------------------------------------------------------------------------------------- AVI +def _ck(cid, body): + return cid + le32(len(body)) + body + (b"\0" if len(body) & 1 else b"") + + +def _lst(kind, body): + return b"LIST" + le32(len(body) + 4) + kind + body + + +def bitmapinfo(w, h, bits, fourcc, palette=None): + """BITMAPINFOHEADER (+ palette: a list of (r, g, b) stored as B, G, R, 0)""" + n = len(palette) if palette else 0 + out = le32(40) + le32(w) + le32(h) + le16(1) + le16(bits) + fourcc + le32(w * h * max(1, bits // 8)) + \ + le32(0) + le32(0) + le32(n) + le32(0) + for r, g, b in palette or []: + out += bytes([b, g, r, 0]) + return out + + +def avi(w, h, fourcc, strf, frames, keys, fps=10): + """an AVI file: one video stream, frames = [bytes], keys = [bool]""" + n = len(frames) + avih = le32(1000000 // fps) + le32(0) + le32(0) + le32(0x10) + le32(n) + le32(0) + le32(1) + \ + le32(max(len(f) for f in frames)) + le32(w) + le32(h) + bytes(16) + strh = b"vids" + fourcc + le32(0) + le16(0) + le16(0) + le32(0) + le32(1) + le32(fps) + le32(0) + le32(n) + \ + le32(max(len(f) for f in frames)) + struct.pack("= len(g): + if first: + body += bytes([0x80 | skip, 0xFF]) + first = False + break + j = i + while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126: + j += 1 + sb = (0x80 if first else 0) | skip + first = False + if j > i: + body += bytes([sb, 256 - (j - i + 1)]) + _pack(g[i], 1) + i = j + 1 + else: + k = i + while k < len(g) and k - i < 63 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]): + k += 1 + k = max(k, i + 1) + body += bytes([sb, k - i]) + b"".join(_pack(x, 1) for x in g[i:k]) + i = k + if first: + body += bytes([0x80, 0xFF]) + continue + line = bytearray([1]) + i = 0 + while i < len(g): + skip = 0 + while pg and i < len(g) and g[i] == pg[i] and skip < 250: + skip += 1 + i += 1 + if i >= len(g): + break + if skip: + line += bytes([0, skip + 1]) + j = i + while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126: + j += 1 + if j > i: + line += bytes([256 - (j - i + 1)]) + _pack(g[i], bits) + i = j + 1 + else: + k = i + while k < len(g) and k - i < 127 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]): + k += 1 + k = max(k, i + 1) + line += bytes([k - i]) + b"".join(_pack(x, bits) for x in g[i:k]) + i = k + line += b"\xff" + body += line + if bits == 1: + body += b"\x00\x00" + else: + body += b"\x00" + head = be16(8) + be16(y0) + be16(0) + be16(y1 - y0) + be16(0) + return be32(4 + len(head) + len(body)) + head + bytes(body) + + +# ---------------------------------------------------------------------------------------------------- MS Video 1 +def _block(img, bx, by): + """the 16 pixels of a block, MS Video 1 order: bottom row first, left to right""" + return [img[by * 4 + 3 - y][bx * 4 + x] for y in range(4) for x in range(4)] + + +def msvc8_frame(img, prev): + """one 8-bit CRAM frame: skips for unchanged blocks, 1-colour, 2-colour or 8-colour blocks""" + h, w = len(img), len(img[0]) + bw, bh = w // 4, h // 4 + out = bytearray() + skip = 0 + + def flush(): + nonlocal skip + while skip: + k = min(skip, 1023) + out.extend([k & 0xFF, 0x84 + (k >> 8)]) + skip -= k + + for by in range(bh - 1, -1, -1): + for bx in range(bw): + px = _block(img, bx, by) + if prev and px == _block(prev, bx, by): + skip += 1 + continue + flush() + cols = sorted(set(px), key=lambda c: (-px.count(c), c)) + if len(cols) == 1: + out.extend([px[0], 0x80]) + elif len(cols) == 2: + c0 = px[15] # pixel 15's flag bit is 0: it takes colours[1] + c1 = cols[0] if cols[0] != c0 else cols[1] + flags = sum(1 << i for i in range(16) if px[i] == c1) + out.extend([flags & 0xFF, flags >> 8, c1, c0]) + else: + # 8-colour: a pair per quadrant; pixel 12 and 15 take the first colour of their quadrant (flags >= 0x9000) + colours = [0] * 8 + flags = 0 + for q, (qx, qy) in enumerate([(0, 0), (2, 0), (0, 2), (2, 2)]): + ids = [(qy + y) * 4 + qx + x for y in range(2) for x in range(2)] + vals = [px[i] for i in ids] + key = {2: 12, 3: 15}.get(q) + a = px[key] if key is not None else sorted(set(vals), key=lambda c: (-vals.count(c), c))[0] + rest = [v for v in vals if v != a] + b = rest[0] if rest else a + base = ((qy & 2) << 1) + (qx & 2) + colours[base], colours[base + 1] = a, b + for i in ids: + if px[i] == a: + flags |= 1 << i + else: + px[i] = b + out.extend([flags & 0xFF, flags >> 8] + colours) + flush() + return bytes(out) + + +# ---------------------------------------------------------------------------------------------------- Cinepak (8-bit) +def cvid8_frame(img, prev, first): + """one palettised Cinepak frame: one strip, a V1 codebook of 4-index entries (each a 2x2 square of one colour per + entry quarter) and a V4 codebook; blocks are V1 when their four 2x2 squares are uniform, else V4 (from the + codebook of 2x2 squares); inter frames skip unchanged blocks""" + h, w = len(img), len(img[0]) + blocks = [(x, y) for y in range(0, h, 4) for x in range(0, w, 4)] + v1, v4 = {}, {} + + def sq(x, y): + return (img[y][x], img[y][x + 1], img[y + 1][x], img[y + 1][x + 1]) + + plan = [] + for (x, y) in blocks: + if prev is not None and all(img[y + j][x + i] == prev[y + j][x + i] for j in range(4) for i in range(4)): + plan.append(None) + continue + q = [sq(x, y), sq(x + 2, y), sq(x, y + 2), sq(x + 2, y + 2)] + if all(len(set(s)) == 1 for s in q) and len(v1) < 256: + e = (q[0][0], q[1][0], q[2][0], q[3][0]) + v1.setdefault(e, len(v1)) + plan.append(("v1", v1[e])) + else: + ids = [] + for s in q: + if s not in v4 and len(v4) < 256: + v4[s] = len(v4) + ids.append(v4.get(s, 0)) + plan.append(("v4", ids)) + + def book(cid, entries): + data = b"".join(bytes(e) for e, _ in sorted(entries.items(), key=lambda kv: kv[1])) + return bytes([cid]) + (4 + len(data)).to_bytes(3, "big") + data + + chunks = b"" + if v4: + chunks += book(0x24, v4) + if v1: + chunks += book(0x26, v1) + bits, data = [], bytearray() + inter = prev is not None + # flags (MSB first, 32 per word) are interleaved with the indexes in decode order + words = bytearray() + flagbuf = [] + + def flag(b): + flagbuf.append(b) + if len(flagbuf) == 1: + words.extend(b"FLAG") # placeholder, patched below + pos_stack.append(len(words) - 4) + if len(flagbuf) == 32: + patch() + + pos_stack = [] + + def patch(): + v = 0 + for i, b in enumerate(flagbuf): + v |= b << (31 - i) + p = pos_stack.pop() + words[p:p + 4] = v.to_bytes(4, "big") + flagbuf.clear() + + for item in plan: + if inter: + flag(0 if item is None else 1) + if item is None: + continue + flag(1 if item[0] == "v4" else 0) + if item[0] == "v1": + words.append(item[1]) + else: + words.extend(item[1]) + if flagbuf: + patch() + vid = (0x31 if inter else 0x30) + chunks += bytes([vid]) + (4 + len(words)).to_bytes(3, "big") + bytes(words) + strip = bytes([0x10 if first else 0x11]) + (12 + len(chunks)).to_bytes(3, "big") + be16(0) + be16(0) + be16(h) + \ + be16(w) + chunks + size = 10 + len(strip) + return bytes([0]) + size.to_bytes(3, "big") + be16(w) + be16(h) + be16(1) + strip diff --git a/tools/fixtures/legacy.py b/tools/fixtures/legacy.py new file mode 100644 index 0000000..863b866 --- /dev/null +++ b/tools/fixtures/legacy.py @@ -0,0 +1,100 @@ +# Legacy video codec fixtures (tools/fixtures.py): Cinepak, Microsoft Video 1, QuickTime RLE and QuickTime SMC +# streams in AVI, MOV and MKV. ffmpeg encodes what it can (cinepak rgb24 / gray, msvideo1 rgb555, qtrle rgb24 / +# rgb555 / argb / gray, smc pal8); tools/fixtures/_legacy_mux.py encodes the rest (QuickTime RLE at 1 / 2 / 4 / 8 bits +# with colour tables and the default Macintosh palettes, 8-bit Microsoft Video 1 and Cinepak with AVI palettes). The +# reference is ffmpeg's decode of every file: the CRC-32 of each frame as rgba. +# tests/gen/legacy_cases.luau { { name, data, codec, width, height, frames = { crc } } } +import importlib.util, os, tempfile, zlib + +_here = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_here, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +V = _load("_video") +M = _load("_legacy_mux") + +INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_legacy_mux.py"] + +W, H = 128, 96 +SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H), "-t", "1"] + + +def rgba_crcs(path, w, h): + raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"]) + n = w * h * 4 + return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)] + + +def case(tmp, name, codec, w=W, h=H): + path = os.path.join(tmp, name) + return {"name": name, "data": open(path, "rb").read(), "codec": codec, "width": w, "height": h, + "frames": rgba_crcs(path, w, h)} + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="legacyfx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + cases = [] + # ffmpeg's encoders + for ext in ("avi", "mov", "mkv"): + ff(*SRC, "-c:v", "cinepak", "cinepak." + ext) + cases.append(case(tmp, "cinepak." + ext, "cinepak")) + ff(*SRC, "-c:v", "cinepak", "-pix_fmt", "gray", "cinepak_gray.avi") + cases.append(case(tmp, "cinepak_gray.avi", "cinepak")) + ff("-f", "lavfi", "-i", "testsrc2=size=92x68:rate=10", "-t", "0.5", "-c:v", "cinepak", "cinepak_odd.mov") + cases.append(case(tmp, "cinepak_odd.mov", "cinepak", 92, 68)) + ff(*SRC, "-c:v", "cinepak", "-min_strips", "3", "-max_strips", "3", "-skip_empty_cb", "1", "cinepak_strips.avi") + cases.append(case(tmp, "cinepak_strips.avi", "cinepak")) + for ext in ("avi", "mov", "mkv"): + ff(*SRC, "-c:v", "msvideo1", "msvideo1." + ext) + cases.append(case(tmp, "msvideo1." + ext, "msvideo1")) + for pf in ("rgb24", "rgb555be", "argb", "gray"): + ff(*SRC, "-c:v", "qtrle", "-pix_fmt", pf, "qtrle_%s.mov" % pf) + cases.append(case(tmp, "qtrle_%s.mov" % pf, "qtrle")) + ff("-f", "lavfi", "-i", "testsrc2=size=100x60:rate=10", "-t", "0.5", "-c:v", "qtrle", "-pix_fmt", "argb", "qtrle_odd.mov") + cases.append(case(tmp, "qtrle_odd.mov", "qtrle", 100, 60)) + for ext in ("mov", "mkv"): # (ffmpeg's AVI muxer has no tag for smc: it writes raw pal8) + ff(*SRC, "-c:v", "smc", "smc." + ext) + cases.append(case(tmp, "smc." + ext, "smc")) + # streams encoded here + w, h, n = 64, 48, 8 + for bits in (1, 2, 4, 8): + imgs = M.index_frames(w, h, n, 1 << bits, seed=bits) + frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)] + keys = [i == 0 for i in range(n)] + # a colour table in the sample description, and the Macintosh default table + pal = M.palette(1 << bits, seed=bits) + name = "qtrle_%d_ctab.mov" % bits + open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits, colors=pal), frames, keys)) + cases.append(case(tmp, name, "qtrle", w, h)) + name = "qtrle_%d_default.mov" % bits + open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits), frames, keys)) + cases.append(case(tmp, name, "qtrle", w, h)) + # grey depths (0x20 + bits) with the default table id: grey ramps + for bits in (2, 4): + imgs = M.index_frames(w, h, 4, 1 << bits, seed=10 + bits) + frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)] + name = "qtrle_%d_grey.mov" % bits + open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, 32 + bits), frames, [True] + [False] * 3)) + cases.append(case(tmp, name, "qtrle", w, h)) + # 8-bit Microsoft Video 1 and Cinepak with an AVI palette + pal = M.palette(256, seed=3) + imgs = M.index_frames(w, h, n, 256, seed=5) + frames = [M.msvc8_frame(img, imgs[i - 1] if i else None) for i, img in enumerate(imgs)] + open(os.path.join(tmp, "msvideo1_8.avi"), "wb").write( + M.avi(w, h, b"CRAM", M.bitmapinfo(w, h, 8, b"CRAM", pal), frames, [i == 0 for i in range(n)])) + cases.append(case(tmp, "msvideo1_8.avi", "msvideo1", w, h)) + imgs = M.index_frames(w, h, n, 200, seed=6) + frames = [M.cvid8_frame(img, imgs[i - 1] if i else None, i == 0) for i, img in enumerate(imgs)] + open(os.path.join(tmp, "cinepak_8.avi"), "wb").write( + M.avi(w, h, b"cvid", M.bitmapinfo(w, h, 8, b"cvid", pal), frames, [i == 0 for i in range(n)])) + cases.append(case(tmp, "cinepak_8.avi", "cinepak", w, h)) + for c in cases: + assert c["frames"], c["name"] + ": ffmpeg decoded no frame" + ctx.emit("legacy_cases", cases) From 4dcb0051807c30ec6feb8894a8a6ff6600662a6e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:22:39 -0500 Subject: [PATCH 06/19] ws-video2-theora: video/ogv, Ogg video (Theora + Vorbis / Opus / FLAC) Demuxes every logical stream of the first Ogg group into containers/Demux: Theora (frame times from granules, Xiph-laced headers as track.config, comment tags in meta.tags), Vorbis / Opus / FLAC audio (headers in track.config) for the api's openAudio hook; open = Video.open. Sniff claims only Ogg files with a Theora BOS page. encode remuxes Theora (+ Vorbis / Opus pages from AudioWrap, interleaved by time). codecs/video/Theora gains info / comment helpers. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Theora/init.luau | 33 +- src/Formats/video/ogv/init.luau | 407 ++++++++++++++++++++++ tests/video/ogv.luau | 211 +++++++++++ tools/fixtures/theora.py | 10 + 6 files changed, 667 insertions(+), 7 deletions(-) create mode 100644 src/Formats/video/ogv/init.luau create mode 100644 tests/video/ogv.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5f34e95..d1c5a0e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -33,6 +33,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | ogv | .ogv .ogg | yes | yes | streaming: true, remux: true, video: "theora", audio: true | `tests/video/ogv.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..206913c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -350,6 +350,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "ogv", + category = "video", + path = "video/ogv", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, + load = function() + return require("@formats/video/ogv") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Theora/init.luau b/src/Formats/codecs/video/Theora/init.luau index dd99346..c607c0e 100644 --- a/src/Formats/codecs/video/Theora/init.luau +++ b/src/Formats/codecs/video/Theora/init.luau @@ -23,6 +23,8 @@ local Decoder = require("@formats/codecs/video/Theora/Decoder") local Theora = {} +export type Info = Header.Info + export type Options = { maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) } @@ -75,6 +77,24 @@ function Theora.splitConfig(c: buffer): { buffer }? return out end +-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err +function Theora.info(h: buffer): (Header.Info?, Err.Err?) + local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) + if not ok or not info then + return nil, Err.from(if ok then err else tostring(info)) + end + return info, nil +end + +-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err +function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) + local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) + if not ok or not vendor or not list then + return nil, nil, nil, Err.from(if ok then err else tostring(vendor)) + end + return vendor, list, (VorbisComment.tags(list)), nil +end + -- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) function Theora.granuleFrame(info: Header.Info, g: number): number if g < 0 then @@ -124,24 +144,23 @@ function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecode if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then return nil, Err.new(Err.CORRUPT, "missing Theora headers") end - local ok, info, ierr = pcall(Header.info, list[1], 0, buffer.len(list[1])) - if not ok or not info then - return nil, Err.from(if ok then ierr else tostring(info)) + local info, ierr = Theora.info(list[1]) + if not info then + return nil, ierr end local maxPixels = opts and opts.maxPixels or 4096 * 2304 if info.frameWidth * info.frameHeight > maxPixels then return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") end - local ok2, vendor, comments, cerr = pcall(Header.comment, list[2], 0, buffer.len(list[2])) - if not ok2 or not vendor or not comments then - return nil, Err.from(if ok2 then cerr else tostring(vendor)) + local vendor, comments, tags, cerr = Theora.comment(list[2]) + if not vendor or not comments or not tags then + return nil, cerr end local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) if not ok3 or not setup then return nil, Err.from(if ok3 then serr else tostring(setup)) end local st = Decoder.new(info, setup) - local tags = VorbisComment.tags(comments) return setmetatable({ info = info, vendor = vendor, diff --git a/src/Formats/video/ogv/init.luau b/src/Formats/video/ogv/init.luau new file mode 100644 index 0000000..0750440 --- /dev/null +++ b/src/Formats/video/ogv/init.luau @@ -0,0 +1,407 @@ +--!strict +-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, +-- RFC 3533 / 5334). New in formats-luau, on containers/Ogg and containers/Demux. +-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from +-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, +-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / +-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's +-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. +-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied +-- (the audio pages come from containers/AudioWrap and are interleaved by time). +-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), +-- encoding Theora (there is no encoder: other sources cannot be written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Demux = require("@formats/containers/Demux") +local AudioWrap = require("@formats/containers/AudioWrap") +local Theora = require("@formats/codecs/video/Theora") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogv = { + name = "ogv", + category = "video", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track id to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + verify: boolean?, -- false: skip the page CRC checks (default true) + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +export type EncodeOptions = { + audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO = { vorbis = true, opus = true, flac = true } + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain +-- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +function Ogv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local b, p, lim = r.buf, r.pos, r.limit + for _ = 1, 8 do + if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then + return 0 + end + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then + return 1 + end + if d > lim then + return 0 + end + local size = 0 + for i = 0, nseg - 1 do + size += buffer.readu8(b, p + 27 + i) + end + p = d + size + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the pages of an Ogg buffer: { offset, size, serial, granule, bos } +local function pages(b: buffer): { { number } } + local out = {} + local pos = 0 + while true do + local p = Ogg.Page.find(b, pos, nil, false) + if not p then + break + end + table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 }) + pos = p.offset + p.size + end + return out +end + +-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) +function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) + if not streams then + return nil, err + end + local vs: Source.Stream? = nil + local as: Source.Stream? = nil + for _, s in streams do + if s.kind == "video" and s.codec == "theora" and not vs then + vs = s + elseif s.kind == "audio" and s.copied and not as then + as = s + end + end + if not vs or not vs.config then + return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)") + end + local v = vs :: Source.Stream + local headers = Theora.splitConfig(v.config :: buffer) + local info = headers and Theora.info(headers[1]) + if not headers or not info then + return nil, Err.new(Err.CORRUPT, "Theora track without its three headers") + end + local fps = info.fpsNum / info.fpsDen + local scale = 2 ^ info.granuleShift + local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0 + -- video pages (serial 0x7468656F), granules from the frame numbers + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(0x7468656F) + s:packet(headers[1], 0, { flush = true }) + s:packet(headers[2], 0) + s:packet(headers[3], 0, { flush = true }) + local key = 0 + local start = if #v.packets > 0 then v.packets[1].pts else 0 + for i, p in v.packets do + local frame = math.floor((p.pts - start) * fps + 0.5) + if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then + key = frame + bias + end + s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) + end + local video = mux:finish() + -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time + local audio: buffer? = nil + local arate, askip = 1, 0 + if as and o.audio ~= false then + local a = as :: Source.Stream + local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels } + local shim = { + count = function(_: any, _t: number): number + return #a.packets + end, + get = function(_: any, _t: number, k: number): any + local p = a.packets[k] + return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data } + end, + } + local buf, _, aerr = AudioWrap.wrap(shim, track) + if not buf and o.audio == true then + return nil, aerr + end + audio = buf + if a.codec == "opus" then + arate = 48000 + local c = a.config + askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0 + else + arate = a.sampleRate or 44100 + end + elseif o.audio == true and not as then + return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus") + end + local vp = pages(video) + local ap = if audio then pages(audio) else {} + local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0)) + local function put(b: buffer, pg: { number }) + out:bytes(b, pg[1], pg[2]) + end + -- bos pages first (video, then audio), then the other header pages, then data by time + put(video, vp[1]) + if audio and ap[1] then + put(audio :: buffer, ap[1]) + end + local vi, ai = 2, 2 + local function headerPage(list: { { number } }, i: number): boolean + local pg = list[i] + return pg ~= nil and pg[3] == 0 + end + while headerPage(vp, vi) do + put(video, vp[vi]) + vi += 1 + end + while audio and headerPage(ap, ai) do + put(audio :: buffer, ap[ai]) + ai += 1 + end + local vt, at = 0, 0 + while vi <= #vp or ai <= #ap do + local nv, na = vp[vi], ap[ai] + if nv and nv[3] >= 0 then + vt = Theora.granuleFrame(info, nv[3]) / fps + end + if na and na[3] >= 0 then + at = (na[3] - askip) / arate + end + if nv and (not na or vt <= at) then + put(video, nv) + vi += 1 + else + put(audio :: buffer, na) + ai += 1 + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets +local function xiphLace(list: { buffer }): buffer + local w = Bytes.writer(64) + w:u8(#list - 1) + for i = 1, #list - 1 do + local n = buffer.len(list[i]) + while n >= 255 do + w:u8(255) + n -= 255 + end + w:u8(n) + end + for _, h in list do + w:bytes(h) + end + return w:finish() +end + +type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err +function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) + if not ogg then + return nil, err + end + local src: buffer = ogg.buf + local tracks: { Types.Track } = {} + local all: { Pending } = {} + local meta: { [string]: any } = {} + local function add(track: number, pts: number, key: boolean, p: any) + table.insert(all, { + track = track, + pts = pts, + key = key, + page = p.pageOffset, + data = p.data, + off = p.offset, + len = p.size, + own = p.data ~= src, + }) + end + for _, st in ogg:streams() do + local codec = st.codec + if codec ~= "theora" and not AUDIO[codec] then + continue + end + local rd = ogg:reader(st.serial) + local headers: { buffer } = {} + local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1 + while #headers < nh do + local p = rd:nextPacket() + if not p then + break + end + table.insert(headers, Ogg.copy(p)) + if codec == "flac" and #headers == 1 and p.size >= 9 then + nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256 + if nh > 64 then + nh = 1 + end + end + end + if #headers < nh then + continue + end + local id = #tracks + 1 + local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial } + if codec == "theora" then + local info = Theora.info(headers[1]) + if not info then + continue + end + track.kind = "video" + track.width, track.height = info.picWidth, info.picHeight + track.timescale = info.fpsNum + track.frameRate = info.fpsNum / info.fpsDen + track.config = xiphLace(headers) + local _, _, tags = Theora.comment(headers[2]) + meta.tags = tags + -- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1 + local packets = {} + local base: number? = nil + while true do + local p = rd:nextPacket() + if not p then + break + end + if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then + continue -- a stray header + end + table.insert(packets, p) + if base == nil and p.granule >= 0 then + base = Theora.granuleFrame(info, p.granule) - (#packets - 1) + end + end + local b0 = base or 0 + for k, p in packets do + local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0 + add(id, (b0 + k - 1) * info.fpsDen, key, p) + end + track.duration = (b0 + #packets) / track.frameRate + else + local h = headers[1] + local rate, channels, skip = 0, 0, 0 + if codec == "vorbis" and buffer.len(h) >= 16 then + channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12) + track.config = xiphLace(headers) + elseif codec == "opus" and buffer.len(h) >= 19 then + channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10) + track.config = h + track.codecDelay = skip / 48000 + elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then + local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field + rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16 + channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1 + local parts = { buffer.create(buffer.len(h) - 9) } + buffer.copy(parts[1], 0, h, 9) + for i = 2, #headers do + table.insert(parts, headers[i]) + end + local total = 0 + for _, x in parts do + total += buffer.len(x) + end + local cfg = buffer.create(total) + local o2 = 0 + for _, x in parts do + buffer.copy(cfg, o2, x) + o2 += buffer.len(x) + end + track.config = cfg + end + if rate <= 0 or channels <= 0 then + continue + end + track.sampleRate, track.channels, track.timescale = rate, channels, rate + local last = 0 + while true do + local p = rd:nextPacket() + if not p then + break + end + add(id, math.max(0, last - skip), true, p) + if p.granule >= 0 then + last = p.granule + end + end + track.duration = math.max(0, last - skip) / rate + end + table.insert(tracks, track) + end + if #tracks == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream") + end + -- the index in file order (by the page each packet ends on) + local order = table.create(#all, 0) + for i = 1, #all do + order[i] = i + end + table.sort(order, function(a: number, c: number): boolean + local pa, pc = all[a].page, all[c].page + if pa ~= pc then + return pa < pc + end + return a < c + end) + local dmx = Demux.new("ogv", tracks, src, meta) + for _, i in order do + local e = all[i] + if e.own then + dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data) + else + dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len) + end + end + dmx:finish() + return dmx, nil +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Ogv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ogv diff --git a/tests/video/ogv.luau b/tests/video/ogv.luau new file mode 100644 index 0000000..d1e0093 --- /dev/null +++ b/tests/video/ogv.luau @@ -0,0 +1,211 @@ +-- video/ogv tests: Ogg Theora files from ffmpeg (libtheora + libvorbis; tools/fixtures/theora.py): sniffing (Theora +-- BOS pages, plain Ogg Vorbis left to the audio formats), tracks, granule times, every frame through F.video.open +-- bit-exact with ffmpeg's (Adler-32 of yuv420p, its framecrc), an empty packet (a repeated frame), the Vorbis track +-- through the api's audio hook against ffmpeg's decode, tags, seeking, remuxing (ogv -> ogv, mkv -> ogv, ogv -> mkv) +-- read back, errors and the fuzz no-throw pass. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Ogv = require("@formats/video/ogv") +local Theora = require("@formats/codecs/video/Theora") +local AudioWrap = require("@formats/containers/AudioWrap") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Adler32 = require("@formats/core/Adler32") +local Err = require("@formats/core/Err") + +local t = T.suite("ogv") + +local AV = require("@tests/gen/theora_av") :: any +local Q0 = require("@tests/gen/theora_q0") :: any +local DUPE = require("@tests/gen/theora_dupe") :: any +local MKV = require("@tests/gen/theora_mkv") :: any +local OPUS = require("@tests/gen/theora_opus") :: any +local FLAC = require("@tests/gen/theora_flac") :: any + +local function file(fx: any): buffer + return Base64.decode(fx.file) :: buffer +end + +-- every frame of a VideoDecoder against ffmpeg's framecrc (yuv420p, keyed by frame number); frames ffmpeg does not +-- show (empty packets) must repeat the previous one +local function frames(v: any, fx: any, label: string, fps: number) + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + local n, bad, shown, prev = 0, 0, 0, nil :: number? + while true do + local f, err = v:nextFrame() + if not f then + t:check(err == nil, label .. ": decode error " .. tostring(err)) + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + local w = want[math.floor(f.pts * fps + 0.5)] + if w then + shown += 1 + if c ~= w then + bad += 1 + end + elseif c ~= prev then + bad += 1 + end + prev = c + end + t:eq(bad, 0, label .. ": frames equal to ffmpeg's (" .. n .. " frames)") + t:eq(shown, #fx.frames, label .. ": every frame ffmpeg shows") + return n +end + +-- 1. contract and sniffing +t:eq(Ogv.name, "ogv", "name") +t:eq(Ogv.category, "video", "category") +t:check(table.find(Ogv.extensions, "ogv") ~= nil, "ogv extension") +t:eq(Ogv.sniff(Bytes.reader(file(AV))), 1, "sniff: Theora + Vorbis") +t:eq(Ogv.sniff(Bytes.reader(file(Q0))), 1, "sniff: Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("OggS\0\2" .. string.rep("\0", 40)))), 0, "sniff: an Ogg page without Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff: not Ogg") + +-- 2. Theora + Vorbis through the api +local v, err = F.video.open(file(AV)) +t:check(v ~= nil, "open: " .. tostring(err)) +if v then + t:eq(v.format, "ogv", "format") + t:eq(v.codec, "theora", "codec") + t:eq(v.width * 1000 + v.height, 160120, "size") + t:eq(v.frameRate, 25, "frame rate") + local dmx = v.demuxer :: any + t:eq(#dmx.tracks, 2, "two tracks") + local vt, at = dmx:track("video"), dmx:track("audio") + t:check(vt and vt.codec == "theora" and vt.timescale == 25, "video track") + t:check(at and at.codec == "vorbis" and at.sampleRate == 44100 and at.channels == 2, "audio track") + t:check(vt and vt.config and #(Theora.splitConfig(vt.config) or {}) == 3, "video config: three Xiph-laced headers") + t:check(math.abs(v.duration - 1) < 0.05, "duration " .. v.duration) + t:check(v.meta.tags and v.meta.tags.encoder ~= nil, "tags from the comment header") + local first = dmx:get(vt.id, 1) + t:check(first and first.keyframe and first.pts == 0, "first packet: a keyframe at 0") + t:check(not dmx:get(vt.id, 2).keyframe, "second packet: an inter frame") + frames(v, AV, "av", 25) + local pcm = Base64.decode(AV.pcm) :: buffer + C.audio(t, v, { pcm = buffer.tostring(pcm) }, "av", false, 20) + -- seeking + v:seek(0.5) + local f = v:nextFrame() + t:check(f ~= nil and f.pts >= 0.5 - 1e-6 and f.pts < 0.6, "seek 0.5 -> " .. tostring(f and f.pts)) + if f then + local want = nil + for _, w in AV.frames do + if w[1] == math.floor(f.pts * 25 + 0.5) then + want = w[2] + end + end + t:eq(Adler32.of(f.image.pixels, nil, nil, 0), want, "the frame after seeking equals ffmpeg's") + end + -- remux ogv -> ogv + v:reset() + local out, rerr = F.save(v, nil, { format = "ogv" }) + t:check(out ~= nil, "remux: " .. tostring(rerr)) + if out then + t:eq(Ogv.sniff(Bytes.reader(out)), 1, "remux: sniff") + local v2 = F.video.open(out) :: any + t:check(v2 ~= nil and #v2.demuxer.tracks == 2, "remux: two tracks") + if v2 then + frames(v2, AV, "remux", 25) + C.audio(t, v2, { pcm = buffer.tostring(pcm) }, "remux", false, 20) + end + end + -- remux ogv -> mkv (V_THEORA) + v:reset() + local mk, merr = F.save(v, nil, { format = "mkv" }) + t:check(mk ~= nil, "to mkv: " .. tostring(merr)) + if mk then + local v3 = F.video.open(mk) :: any + t:check(v3 ~= nil and v3.codec == "theora", "to mkv: Theora track") + if v3 then + frames(v3, AV, "to mkv", 25) + end + end +end + +-- 3. Opus and FLAC audio tracks (FLAC: exact) +for _, c in { { OPUS, "opus", 48000 }, { FLAC, "flac", 22050 } } do + local fx, codec, rate = c[1], c[2], c[3] + local vd, e = F.video.open(file(fx)) + t:check(vd ~= nil, codec .. ": open: " .. tostring(e)) + if vd then + local at = (vd.demuxer :: any):track("audio") + t:check(at and at.codec == codec and at.sampleRate == rate and at.channels == 1, codec .. ": audio track") + frames(vd, fx, codec, 25) + C.audio(t, vd, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, codec, codec == "flac", 20) + if codec == "opus" then + vd:reset() + local out = F.save(vd, nil, { format = "ogv" }) + local v2 = out and F.video.open(out) :: any + t:check(v2 ~= nil and v2.audio ~= nil, "opus: remux keeps the audio") + if v2 then + C.audio(t, v2, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, "opus remux", false, 20) + end + end + end +end + +-- 4. an empty packet: a repeated frame with its own time +do + local vd = Ogv.open(Bytes.reader(file(DUPE))) :: any + local n = 0 + local prev, dupAt = nil, nil + while true do + local f = vd:nextFrame() + if not f then + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + if n == 6 then + dupAt = f.pts + t:eq(c, prev, "dupe: frame 6 repeats frame 5") + end + prev = c + end + t:eq(n, #DUPE.frames + 1, "dupe: one frame per packet") + t:check(dupAt ~= nil and math.abs((dupAt :: number) - 0.2) < 1e-6, "dupe: its time slot (0.2 s)") + t:check(vd.audio == nil and vd.audioError == nil, "no audio track, no audio error") +end + +-- 5. Theora in Matroska -> ogv +do + local mv = F.video.open(file(MKV)) :: any + local out, e = F.save(mv, nil, { format = "ogv" }) + t:check(out ~= nil, "mkv -> ogv: " .. tostring(e)) + if out then + local v2 = Ogv.open(Bytes.reader(out)) :: any + frames(v2, MKV, "mkv -> ogv", 25) + end +end + +-- 6. not Theora: plain Ogg Vorbis goes to the audio format, writing other codecs fails +do + local vd = Ogv.open(Bytes.reader(file(AV))) :: any + local at = vd.demuxer:track("audio") + local ogg = AudioWrap.wrap(vd.demuxer, at) :: buffer + t:eq(Ogv.sniff(Bytes.reader(ogg)), 0, "sniff: Ogg Vorbis is not ogv") + local a = F.load(ogg, { name = "x.ogg" }) + t:check(a ~= nil and a.kind == "audio", "F.load of Ogg Vorbis named .ogg: audio") + local v4, e4 = Ogv.open(Bytes.reader(ogg)) + t:check(v4 ~= nil and v4.decodeError ~= nil, "an Ogg without video: opens, frames UNSUPPORTED (" .. tostring(e4) .. ")") + local _, ee = Ogv.encode(Ogv.open(Bytes.reader(ogg)) :: any) + t:check(ee ~= nil and ee.code == Err.UNSUPPORTED, "encode without Theora: UNSUPPORTED") + local _, eg = Ogv.open(Bytes.reader(buffer.fromstring("OggS garbage"))) + t:check(eg ~= nil, "garbage: an error") + local cut = buffer.create(5000) + buffer.copy(cut, 0, file(Q0), 0, 5000) + local vc = Ogv.open(Bytes.reader(cut)) + t:check(vc ~= nil, "a truncated file opens") +end + +-- 7. fuzz +t:fuzz("open", C.fuzzOpen(Ogv), { buffer.tostring(file(Q0)) }, { mutations = 16, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py index 4395444..7d05299 100644 --- a/tools/fixtures/theora.py +++ b/tools/fixtures/theora.py @@ -8,6 +8,7 @@ # tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original) # tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64), # rate, channels } +# tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio # tests/gen/theora_mkv.luau { file (base64 .mkv), frames } # tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } for tools/bench.luau import base64, os, shutil, struct, subprocess, tempfile, zlib @@ -184,6 +185,15 @@ def generate(ctx): pcm = ff(["-i", av, "-map", "0:a", "-f", "f32le", "-"]) ctx.emit("theora_av", {"file": b64(open(av, "rb").read()), "frames": framecrc(av, "yuv420p"), "width": 160, "height": 120, "pcm": b64(pcm), "rate": 44100, "channels": 2}) + # Theora + Opus, Theora + FLAC (mono, 0.5 s) + for name, aenc, rate in (("opus", ["-c:a", "libopus", "-b:a", "48k"], 48000), ("flac", ["-c:a", "flac"], 22050)): + path = os.path.join(tmp, "a_" + name + ".ogv") + ff(src("testsrc2", 96, 64, 25, 0.5) + ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate, + "-t", "0.5", "-ac", "1", "-c:v", "libtheora", "-q:v", "4"] + aenc + + ["-shortest", path]) + pcm = ff(["-i", path, "-map", "0:a", "-f", "f32le", "-"]) + ctx.emit("theora_" + name, {"file": b64(open(path, "rb").read()), "frames": framecrc(path, "yuv420p"), + "width": 96, "height": 64, "pcm": b64(pcm), "rate": rate, "channels": 1}) # Theora in Matroska (CodecPrivate: the three headers, Xiph-laced) mkv = os.path.join(tmp, "t.mkv") ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv]) From a1d2e7218cd88f1a04f4b63e37502789ccabfb02 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:24:29 -0500 Subject: [PATCH 07/19] video/fli: FLI / FLC / FLX animations (read) Header (FLI 1/70 s, FLC ms, depths 8 / 15 / 16 / 24), frame chunks into containers/Demux, open() through the registry's flic decoder (codecs/video/Legacy/Flic); the ring frame is dropped unless opts.ringFrame. Fixtures encoded by tools/fixtures/fli.py (every chunk type) with ffmpeg's decode as the reference: bit-exact. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/video/fli/init.luau | 157 +++++++++++++ tests/video/fli.luau | 105 +++++++++ tools/fixtures/fli.py | 395 ++++++++++++++++++++++++++++++++ 5 files changed, 670 insertions(+) create mode 100644 src/Formats/video/fli/init.luau create mode 100644 tests/video/fli.luau create mode 100644 tools/fixtures/fli.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b7c26a7..13d1e91 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -28,6 +28,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | +| video | fli | .fli .flc .flx | yes | - | streaming: true, video: "flic", depths: 8, 15, 16, 24 | `tests/video/fli.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | | video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 288846f..d26e1e1 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -290,6 +290,18 @@ local list: { Entry } = { return require("@formats/video/avi") end, }, + { + name = "fli", + category = "video", + path = "video/fli", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, + load = function() + return require("@formats/video/fli") + end, + }, { name = "h264", category = "video", diff --git a/src/Formats/video/fli/init.luau b/src/Formats/video/fli/init.luau new file mode 100644 index 0000000..8224d48 --- /dev/null +++ b/src/Formats/video/fli/init.luau @@ -0,0 +1,157 @@ +--!strict +-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in formats-luau, written from the FLIC +-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). +-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: +-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, +-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 +-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the +-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. +-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Fli = { + name = "fli", + category = "video", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 128 +local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44 +local FRAME, FRAME2 = 0xF1FA, 0xF5FA + +-- ------------------------------------------------------------------------------------------------ sniff +function Fli.sniff(r: Bytes.Reader): number + local s = r:peek(18) + if #s < 18 then + return 0 + end + local magic = string.byte(s, 5) + string.byte(s, 6) * 256 + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return 0 + end + local w = string.byte(s, 9) + string.byte(s, 10) * 256 + local h = string.byte(s, 11) + string.byte(s, 12) * 256 + if w > 4096 or h > 4096 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer | nil, Err +function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local n = limit - base + if n < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header") + end + local hr = Bytes.reader(b, base, HEADER) + hr:skip(4) + local magic = hr:u16le() + local frames = hr:u16le() + local w, h = hr:u16le(), hr:u16le() + local depth = hr:u16le() + hr:skip(2) + local speed = hr:u32le() + if hr.err then + return nil, hr.err + end + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4) + end + if magic == FLI then + speed = speed % 65536 + end + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "no picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + if magic == FLI or depth == 0 then + depth = 8 + elseif magic == FLC and depth == 16 then + depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels + end + if speed == 0 then + speed = 5 + end + local scale = if magic == FLI then 70 else 1000 + local track: Types.Track = { + id = 1, + kind = "video", + codec = "flic", + codecTag = string.format("0x%04X", magic), + timescale = scale, + width = w, + height = h, + frameRate = scale / speed, + default = true, + bitsPerPixel = depth, + } + -- the frame chunks + local offs, sizes = {}, {} + local p = base + HEADER + while p + 6 <= limit do + local size = buffer.readu32(b, p) + local cm = buffer.readu16(b, p + 4) + if size < 6 then + break + end + if (cm == FRAME or cm == FRAME2) and size > 6 then + if p + size > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, size) + end + p += size + end + local count = #offs + if frames > 0 and count > frames and not (opts and opts.ringFrame) then + count = frames -- the ring frame is not a frame of the animation + end + local dmx = Demux.new("fli", { track }, b, { + type = magic, + frames = frames, + depth = depth, + speed = speed, + ringFrame = #offs > frames and frames > 0, + }) + for i = 1, count do + dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Fli.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Fli diff --git a/tests/video/fli.luau b/tests/video/fli.luau new file mode 100644 index 0000000..b163dc9 --- /dev/null +++ b/tests/video/fli.luau @@ -0,0 +1,105 @@ +-- video/fli tests: FLI (COLOR_64, BRUN, LC, BLACK, COPY, PSTAMP, a ring frame), FLC (prefix chunk, COLOR_256, SS2 with +-- line skips and the last-byte opcode, an empty frame), an odd-size FLC, and 15 / 16 / 24-bit FLCs (BRUN, DTA_BRUN, +-- DELTA, DTA_LC, COPY, DTA_COPY, BLACK), all encoded by the fixture script: every frame equals ffmpeg's decode +-- (CRC-32 of rgba), frame rates, the ring frame option, seeking, errors, the fuzz pass. Fixtures: tools/fixtures/fli.py. +local T = require("@tests/T") +local F = require("@formats") +local Fli = require("@formats/video/fli") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fli_cases") + +local t = T.suite("fli") +t:eq(Fli.name, "fli", "name") +t:eq(Fli.category, "video", "category") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +for _, c in Fx do + local label = c.name + t:check(Fli.sniff(reader(c.data)) > 0, label .. ": sniff") + t:eq(F.detect(buffer.fromstring(c.data)), "fli", label .. ": detect") + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:eq(v.codec, "flic", label .. ": codec") + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate) < 1e-9, label .. ": frame rate " .. v.frameRate) + t:eq(v.track.bitsPerPixel, c.depth, label .. ": depth") + local ring = v.demuxer.meta.ringFrame + local want = if ring then #c.frames - 1 else #c.frames + local n, bad = 0, 0 + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": " .. tostring(ferr)) + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad)) + v:seek(0.25) + local f = v:nextFrame() + local k = math.floor(0.25 * c.rate + 1 - 1e-9) + 1 + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k) + if ring then + local v2 = Fli.open(reader(c.data), { ringFrame = true }) + local m = 0 + while v2 and v2:nextFrame() do + m += 1 + end + t:eq(m, #c.frames, label .. ": with the ring frame") + end + end +end + +-- errors +do + local _, e = Fli.open(reader(string.sub(Fx[1].data, 1, 100))) + t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED") + local bad = Fx[1].data + bad = string.sub(bad, 1, 4) .. "\0\0" .. string.sub(bad, 7) + t:eq(Fli.sniff(reader(bad)), 0, "bad magic: no sniff") + local _, e2 = Fli.open(reader(bad)) + t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT") + local big = string.sub(Fx[1].data, 1, 8) .. "\255\15\255\15" .. string.sub(Fx[1].data, 13) + local _, e3 = Fli.open(reader(big), { maxPixels = 2 ^ 20 }) + t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("open", function(b: buffer) + local v = Fli.open(Bytes.reader(b)) + if v then + while v:nextFrame() do + end + end + return v +end, samples, { mutations = 12, garbage = 40, keepHeader = 16 }) +-- the frame decoder itself (codecs/video/Legacy/Flic, native: no pcall in between) +local Flic = require("@formats/codecs/video/Legacy").Flic +for _, c in { Fx[1], Fx[2], Fx[4], Fx[6] } do + local d = Fli.demux(reader(c.data)) + local packets = {} + for k = 1, math.min(4, d:count(1)) do + table.insert(packets, d:get(1, k).data) + end + t:fuzz(c.name .. " frames", function(b: buffer) + local st = Flic.state(c.width, c.height, c.depth) + if st then + Flic.decode(st, b) + return Flic.image(st) + end + return nil + end, packets, { mutations = 20, garbage = 30 }) +end +t:done() diff --git a/tools/fixtures/fli.py b/tools/fixtures/fli.py new file mode 100644 index 0000000..0428f02 --- /dev/null +++ b/tools/fixtures/fli.py @@ -0,0 +1,395 @@ +# FLI / FLC fixtures (tools/fixtures.py): ffmpeg cannot write FLICs, so this encodes them (every chunk type: COLOR_64, +# COLOR_256, BRUN, LC / DELTA_FLI, SS2 / DELTA_FLC with line skips and the last-byte opcode, BLACK, COPY, PSTAMP; a +# prefix chunk and a ring frame; 15-bit FLC, 16-bit DTA and 24-bit FLC with BRUN / DTA_BRUN / DELTA / DTA_LC / COPY / +# DTA_COPY) and uses ffmpeg's decode as the reference (CRC-32 of each frame as rgba). +# tests/gen/fli_cases.luau { { name, data, width, height, depth, rate, frames = { crc } } } +import importlib.util, os, random, struct, tempfile, zlib + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + + +def le16(v): + return struct.pack("= 2: + out.append(("rep", seq[i], j - i + 1)) + i = j + 1 + else: + k = i + while k < len(seq) and k - i < maxrun and not (k + 2 < len(seq) and seq[k] == seq[k + 1] == seq[k + 2]): + k += 1 + k = max(k, i + 1) + out.append(("lit", seq[i:k])) + i = k + return out + + +def brun_line(units, unit_bytes): + """BRUN line body: > 0 repeat, < 0 literal (units are byte strings of unit_bytes each)""" + out = bytes([0]) + for p in runs(units): + if p[0] == "rep": + out += bytes([p[2]]) + p[1] + else: + out += bytes([s8(-len(p[1]))]) + b"".join(p[1]) + return out + + +def brun(img, bpp, pixel_runs, typ=15): + lines = b"" + for row in img: + if pixel_runs: + units = [row[x] for x in range(len(row))] + else: + flat = b"".join(row) + units = [flat[i:i + 1] for i in range(len(flat))] + lines += brun_line(units, bpp) + return chunk(typ, lines) + + +def lc(img, prev): + """DELTA_FLI (LC): first changed line, line count, per line (skip, run) packets on bytes""" + h, w = len(img), len(img[0]) + ch = [y for y in range(h) if img[y] != prev[y]] + if not ch: + return chunk(12, le16(0) + le16(0)) + y0, y1 = ch[0], ch[-1] + 1 + out = le16(y0) + le16(y1 - y0) + for y in range(y0, y1): + row, prow = img[y], prev[y] + packets = [] + x = 0 + while x < w: + skip = 0 + while x < w and row[x] == prow[x] and skip < 255: + skip += 1 + x += 1 + if x >= w: + break + e = x + while e < w and row[e] != prow[e] and e - x < 127: + e += 1 + seg = [bytes([v]) for v in row[x:e]] + pieces = runs(seg) + first = True + for p in pieces: + sk = skip if first else 0 + first = False + if p[0] == "rep": + packets.append(bytes([sk, s8(-p[2])]) + p[1]) + else: + packets.append(bytes([sk, len(p[1])]) + b"".join(p[1])) + x = e + out += bytes([len(packets)]) + b"".join(packets) + return chunk(12, out) + + +def ss2(img, prev, last_byte=False): + """DELTA_FLC (SS2) on 8-bit pixels: word packets, line-skip words, the last-byte opcode on odd lines""" + h, w = len(img), len(img[0]) + out = b"" + count = 0 + skip_lines = 0 + for y in range(h): + row, prow = img[y], prev[y] + if row == prow: + skip_lines += 1 + continue + if skip_lines: + out += le16(-skip_lines) + skip_lines = 0 + body = b"" + packets = 0 + lastop = last_byte and y % 2 == 1 and row[w - 1] != prow[w - 1] + ww = w - (1 if lastop else 0) + words = [bytes(row[x:x + 2]) for x in range(0, ww - ww % 2, 2)] + pwords = [bytes(prow[x:x + 2]) for x in range(0, ww - ww % 2, 2)] + i = 0 + while i < len(words): + skip = 0 + while i < len(words) and words[i] == pwords[i] and skip < 127: + skip += 1 + i += 1 + if i >= len(words): + break + e = i + while e < len(words) and words[e] != pwords[e] and e - i < 127: + e += 1 + first = True + for p in runs(words[i:e]): + sk = skip * 2 if first else 0 + first = False + if p[0] == "rep": + body += bytes([sk, s8(-p[2])]) + p[1] + else: + body += bytes([sk, len(p[1])]) + b"".join(p[1]) + packets += 1 + i = e + if lastop: + out += le16(0x8000 | row[w - 1]) + out += le16(packets) + body + count += 1 + return chunk(7, le16(count) + out) + + +def delta_deep(img, prev, bpp, typ=7): + """DELTA / DTA_LC on 15/16/24-bit pixels: negative words skip lines, packets (skip pixels, run)""" + h, w = len(img), len(img[0]) + out, count, skip_lines = b"", 0, 0 + for y in range(h): + row, prow = img[y], prev[y] + if row == prow: + skip_lines += 1 + continue + if skip_lines: + out += le16(-skip_lines) + skip_lines = 0 + body, packets, x = b"", 0, 0 + while x < w: + skip = 0 + while x < w and row[x] == prow[x] and skip < 255: + skip += 1 + x += 1 + if x >= w: + break + e = x + while e < w and row[e] != prow[e] and e - x < 127: + e += 1 + first = True + for p in runs(row[x:e]): + sk = skip if first else 0 + first = False + if p[0] == "rep": + body += bytes([sk, s8(-p[2])]) + p[1] + else: + body += bytes([sk, len(p[1])]) + b"".join(p[1]) + packets += 1 + x = e + out += le16(packets) + body + count += 1 + return chunk(typ, le16(count) + out) + + +def copy8(img): + w = len(img[0]) + pad = (w + 3) // 4 * 4 - w + return le32(6 + len(img) * (w + pad)) + le16(16) + b"".join(bytes(r) + bytes(pad) for r in img) + + +def copy_deep(img, bpp, typ=16): + w = len(img[0]) + body = b"".join(b"".join(r) + (bytes(bpp) if w % 2 else b"") for r in img) + return le32(6 + len(body)) + le16(typ) + body + + +# ---------------------------------------------------------------------------------------------------- pictures +def idx_frames(w, h, n, colors, seed): + rnd = random.Random(seed) + out = [] + for t in range(n): + img = [[(x // 6 + y // 4 + (t // 4)) % colors for x in range(w)] for y in range(h)] + sx, sy = (t * 7) % (w - 16), (t * 3) % (h - 12) + for y in range(sy, sy + 12): + for x in range(sx, sx + 16): + img[y][x] = (200 + t) % colors + for y in range(h // 2, h // 2 + 4): + for x in range(w // 2, w // 2 + 10): + img[y][x] = rnd.randrange(colors) + out.append(img) + return out + + +def deep_frames(w, h, n, bpp, seed): + rnd = random.Random(seed) + out = [] + for t in range(n): + img = [] + for y in range(h): + row = [] + for x in range(w): + v = ((x * 37 + y * 11 + t * 3) // 8) & 0x7FFF if bpp == 2 else ((x * 4) & 255, (y * 5) & 255, (t * 20) & 255) + if 10 + t <= x < 26 + t and 8 <= y < 20: + v = 0x7C00 if bpp == 2 else (250, 10, 10) + if bpp == 2 and h // 2 <= y < h // 2 + 3 and w // 2 <= x < w // 2 + 7: + v = rnd.randrange(65536) + row.append(struct.pack(" Date: Sat, 31 Oct 2026 14:25:51 -0500 Subject: [PATCH 08/19] 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. --- 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 From 22db57f3489aa979f5419decff55ed24c5858c07 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:28:11 -0500 Subject: [PATCH 09/19] ws-video2: MPEG-2 in MPEG-TS (0x02 / private 0x80), MPEG-PS, MKV, AVI, MP4 caps; tests/video/mpeg2.luau --- docs/FORMATS.md | 10 ++-- src/Formats/Registry.luau | 10 ++-- src/Formats/video/avi/init.luau | 2 +- src/Formats/video/mkv/init.luau | 2 +- src/Formats/video/mp4/init.luau | 2 +- src/Formats/video/mpegps/init.luau | 11 ++-- src/Formats/video/mpegts/init.luau | 7 +-- tests/video/mpeg2.luau | 80 ++++++++++++++++++++++++++++++ 8 files changed, 103 insertions(+), 21 deletions(-) create mode 100644 tests/video/mpeg2.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d612dc3..c98a249 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -27,12 +27,12 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | -| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | +| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | -| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | -| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | -| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | -| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | +| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "mpeg2", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | +| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", "mpeg2", audio: true | `tests/video/mpegps.luau` | +| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "mpeg2", "h264", audio: true | `tests/video/mpegts.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 429bc2a..7dfc437 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -285,7 +285,7 @@ local list: { Entry } = { extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true }, load = function() return require("@formats/video/avi") end, @@ -309,7 +309,7 @@ local list: { Entry } = { extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") end, @@ -321,7 +321,7 @@ local list: { Entry } = { extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, load = function() return require("@formats/video/mp4") end, @@ -333,7 +333,7 @@ local list: { Entry } = { extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, load = function() return require("@formats/video/mpegps") end, @@ -345,7 +345,7 @@ local list: { Entry } = { extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, load = function() return require("@formats/video/mpegts") end, diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index fc46a32..1f0fdf0 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -25,7 +25,7 @@ local AviFormat = { extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 8e009e9..9e068c7 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -28,7 +28,7 @@ local Mkv = { extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 48b57c7..eb643df 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -30,7 +30,7 @@ local Mp4 = { extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mpegps/init.luau b/src/Formats/video/mpegps/init.luau index 8708894..91ef418 100644 --- a/src/Formats/video/mpegps/init.luau +++ b/src/Formats/video/mpegps/init.luau @@ -1,10 +1,11 @@ --!strict -- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / -- .vob / VCD .dat). New in formats-luau, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers); a --- picture takes the PTS of the PES it starts in, pictures without one get theirs from the GOP's temporal references. --- Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). open() returns a VideoDecoder: MPEG-1 --- video through the codecs/video/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook. +-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both +-- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get +-- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). +-- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its +-- sequence extension), audio through the api's opts.openAudio hook. -- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires @@ -23,7 +24,7 @@ local Ps = { extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mpegts/init.luau b/src/Formats/video/mpegts/init.luau index 1cac2a4..4213838 100644 --- a/src/Formats/video/mpegts/init.luau +++ b/src/Formats/video/mpegts/init.luau @@ -2,8 +2,9 @@ -- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, -- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS -- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/video/Video --- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the +-- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, +-- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / -- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. -- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, -- PES without PTS for video before the first one (dropped). @@ -24,7 +25,7 @@ local Ts = { extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/tests/video/mpeg2.luau b/tests/video/mpeg2.luau new file mode 100644 index 0000000..9fe1724 --- /dev/null +++ b/tests/video/mpeg2.luau @@ -0,0 +1,80 @@ +-- MPEG-2 video in the containers (tools/fixtures/mpeg2.py, "mpeg2_containers"): the same elementary stream copied by +-- ffmpeg into MPEG-TS (stream type 0x02, and the PMT patched to 0x80, private / DigiCipher II video), MPEG-PS (VOB), +-- Matroska (V_MPEG2) and AVI: each opens through F.video.open with codec "mpeg2", its frames equal ffmpeg's +-- `-idct int` decode (luma CRC per frame, display order), seeking lands on a frame; the raw .m2v opens too. +local T = require("@tests/T") +local F = require("@formats") +local Base64 = require("@formats/core/Base64") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/mpeg2_containers") +local Prog = require("@tests/gen/mpeg2_prog") + +local t = T.suite("video/mpeg2") + +local function lumaCrc(img: any): number + return Crc32.of(img.pixels, 0, img.width * img.height) +end + +local CASES = { + { "ts", "mpegts" }, + { "ts80", "mpegts" }, + { "mpg", "mpegps" }, + { "mkv", "mkv" }, + { "avi", "avi" }, +} +for _, c in CASES do + local key, format = c[1], c[2] + local data = Base64.decode(Fx[key]) :: buffer + local v, err = F.video.open(data) + t:check(v ~= nil, key .. ": opens: " .. tostring(err)) + if v then + t:eq(v.format, format, key .. ": format") + t:eq(v.codec, "mpeg2", key .. ": codec") + t:check(v.width == Prog.width and v.height == Prog.height, key .. ": size") + local frames, exact = 0, 0 + while true do + local f, ferr = v:nextFrame() + t:check(ferr == nil, key .. ": frame error " .. tostring(ferr)) + if not f then + break + end + frames += 1 + local ref = Fx.crcs[frames] + if ref and lumaCrc(f.image) == ref[1] then + exact += 1 + end + end + t:eq(frames, #Fx.crcs, key .. ": frame count") + -- the frames ffmpeg's encoder left with an uncoded macroblock are concealed differently (tests/codecs/mpeg2) + t:check(exact >= frames - 2, string.format("%s: %d of %d frames equal ffmpeg's", key, exact, frames)) + v:seek(0.4) + local f = v:nextFrame() + t:check(f ~= nil and math.abs(f.pts - 0.4) < 0.05, key .. ": seek") + t:note(" %-5s %-7s %d frames, %d bit-exact", key, format, frames, exact) + end +end + +-- the elementary stream itself +do + local v, err = F.video.open(Base64.decode(Prog.file) :: buffer) + t:check(v ~= nil and v.codec == "mpeg2", "m2v: opens as mpeg2: " .. tostring(err)) + if v then + local n = 0 + while v:nextFrame() do + n += 1 + end + t:eq(n, Prog.frames, "m2v: frame count") + end +end + +t:fuzz("open", function(b: buffer) + local v = F.video.open(b) + if v then + for _ = 1, 3 do + v:nextFrame() + end + end + return v +end, { Base64.decode(Fx.ts) :: buffer, Base64.decode(Fx.mpg) :: buffer }, { mutations = 30, garbage = 5 }) + +t:done() From 5585ce53cef2d020ecb364fb70ea00c261831c10 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:30:45 -0500 Subject: [PATCH 10/19] ws-video2: MPEG-1 tests bit-exact against ffmpeg -idct int (308 of 312 frames; 4 with concealed macroblocks) --- tests/codecs/mpeg1.luau | 27 +++++++++++++++++++++++++-- tools/fixtures/mpeg1.py | 15 +++++++++++---- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/tests/codecs/mpeg1.luau b/tests/codecs/mpeg1.luau index 34cafb4..d5ca329 100644 --- a/tests/codecs/mpeg1.luau +++ b/tests/codecs/mpeg1.luau @@ -1,4 +1,5 @@ --- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg +-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Every frame bit-exact with +-- `ffmpeg -idct int` (the IDCT codecs/video/Dsp reproduces; frames with concealed macroblocks excepted). Against ffmpeg -- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode, -- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per -- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p; @@ -11,6 +12,7 @@ local Mpeg1 = require("@formats/codecs/video/Mpeg1") local Base64 = require("@formats/core/Base64") local Deflate = require("@formats/codecs/compress/Deflate") local Types = require("@formats/Types") +local Crc32 = require("@formats/core/Crc32") local STREAMS = { require("@tests/gen/mpeg1_qcif_200k"), @@ -81,6 +83,7 @@ local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): nu end local MAE_LIMIT = 2 +local totalExact, totalConcealed = 0, 0 local MEAN_LIMIT = 1.5 -- 1. every stream against ffmpeg @@ -101,6 +104,7 @@ for _, fx in STREAMS do local hasB = string.find(name, "bframes") ~= nil local dec = Mpeg1.new({ reorder = hasB }) local frames = 0 + local exact, concealed = 0, 0 local maxMae, maxMeanErr = 0, 0 local sums = {} local function onFrame(f: any) @@ -136,6 +140,21 @@ for _, fx in STREAMS do end t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255") sums[frames] = buffer.tostring(px) + -- bit-exact against ffmpeg -idct int (outside macroblocks the decoder had to conceal) + local ex = fx.exact[frames] + if ex then + local img = Mpeg1.frameImage(f) :: Types.Image + local yc = Crc32.of(img.pixels, 0, n) + local uc = Crc32.of(img.pixels, n, cw * ch) + local vc = Crc32.of(img.pixels, n + cw * ch, cw * ch) + if yc == ex[1] and uc == ex[2] and vc == ex[3] then + exact += 1 + elseif next(f.concealed) ~= nil then + concealed += 1 + else + t:check(false, string.format("%s frame %d (type %d): differs from ffmpeg -idct int", name, frames, f.pictureType)) + end + end end local t0 = os.clock() for _, u in fx.units do @@ -155,7 +174,10 @@ for _, fx in STREAMS do t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)") t:eq(dec.stats.errors, 0, name .. ": no bitstream errors") worst = math.max(worst, maxMae) - t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt) + t:note("%-13s %4dx%-4d %3d frames %3d bit-exact worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, exact, maxMae, maxMeanErr, frames / dt) + t:eq(exact + concealed, frames, name .. ": frames equal to ffmpeg -idct int (or with concealed macroblocks)") + totalExact += exact + totalConcealed += concealed -- streamed: random pieces through write / decodeFrame, then flush local d2 = Mpeg1.new({ reorder = hasB }) @@ -187,6 +209,7 @@ for _, fx in STREAMS do t:eq(got, frames, name .. ": streamed frame count") end t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC) +t:note("%d frames bit-exact with ffmpeg -idct int, %d with concealed macroblocks (ffmpeg error concealment)", totalExact, totalConcealed) -- 2. a size change mid-stream do diff --git a/tools/fixtures/mpeg1.py b/tools/fixtures/mpeg1.py index 0400555..3b5dfd8 100644 --- a/tools/fixtures/mpeg1.py +++ b/tools/fixtures/mpeg1.py @@ -4,7 +4,9 @@ # tests/gen/mpeg1_.luau { name, width, height, frames, file (base64), units = { { offset, length } }, # means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA), # rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib), -# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) } +# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib), +# exact = { { y, u, v } } (CRC-32 of every frame's planes from `ffmpeg -idct int`, the IDCT +# codecs/video/Dsp reproduces: the decode must equal it) } # tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } } # tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with # B-frames) for tools/bench.luau @@ -122,9 +124,9 @@ def generate(ctx): es = open(path, "rb").read() return (patch_size(es, *size) if size else es), path - def reference(path, fmt): - out = path + "." + fmt - ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out]) + def reference(path, fmt, idct=None): + out = path + "." + fmt + (idct or "") + ff((["-idct", idct] if idct else []) + ["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out]) 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) w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2]) @@ -134,10 +136,13 @@ def generate(ctx): es, path = encode(name, args, size) rgba, w, h = reference(path, "rgba") yuv, _, _ = reference(path, "yuv420p") + exact, _, _ = reference(path, "yuv420p", "int") if size: rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1]) + exact = crop_yuv(exact, w, h, size[0], size[1]) w, h = size fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + c = ((w + 1) // 2) * ((h + 1) // 2) n = len(rgba) // fs means = [] for k in range(n): @@ -151,6 +156,8 @@ def generate(ctx): "means": means, "rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks], "yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks], + "exact": [[zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + c]), zlib.crc32(f[w * h + c:ys])] + for f in (exact[k * ys:(k + 1) * ys] for k in range(n))], }) # a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own) From bf639260e4cbb2dca13967c06fdecdab8a487b73 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:37:39 -0500 Subject: [PATCH 11/19] video/smk: Smacker (SMK2 / SMK4) with its video codec and audio containers into containers/Demux (palette updates ride on each video packet as packet.palette); the Smacker video codec (header Huffman trees with the escape cache, MONO / FULL (+ SMK4 doubled modes) / SKIP / FILL blocks) lives in codecs/video/Legacy/Smacker and registers as 'smackvid'; Smacker's packed DPCM-Huffman audio (8 / 16-bit, mono / stereo) and raw PCM tracks decode in video/smk/Audio, the Decoder built by the format over codecs/audio/Stream (Smk.openAudio; open() installs it as the openAudio hook). Fixtures encoded by tools/fixtures/smk.py: video and audio bit-exact with ffmpeg. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Legacy/Smacker.luau | 363 ++++++++++++++ src/Formats/codecs/video/Legacy/init.luau | 33 +- src/Formats/video/smk/Audio.luau | 123 +++++ src/Formats/video/smk/init.luau | 320 ++++++++++++ tests/video/smk.luau | 180 +++++++ tools/fixtures/smk.py | 493 +++++++++++++++++++ 8 files changed, 1522 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/video/Legacy/Smacker.luau create mode 100644 src/Formats/video/smk/Audio.luau create mode 100644 src/Formats/video/smk/init.luau create mode 100644 tests/video/smk.luau create mode 100644 tools/fixtures/smk.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 13d1e91..8b27918 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -34,6 +34,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | smk | .smk | yes | - | streaming: true, video: "smackvid", audio: "smackaudio", "pcm_u8", "pcm_s16le" | `tests/video/smk.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d26e1e1..ad48ba9 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -362,6 +362,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "smk", + category = "video", + path = "video/smk", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, + load = function() + return require("@formats/video/smk") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Legacy/Smacker.luau b/src/Formats/codecs/video/Legacy/Smacker.luau new file mode 100644 index 0000000..c5923ec --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Smacker.luau @@ -0,0 +1,363 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and +-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are +-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); +-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte +-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a +-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; +-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a +-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number) walked bit by bit. +-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give +-- zero bits, a frame whose codes run out of bits gives no picture. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smacker = {} + +local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder) +local MAX_DEPTH16 = 500 + +-- block runs (TYPE code bits 2..7) +local RUNS = table.create(64, 0) +for i = 1, 59 do + RUNS[i] = i +end +RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 + +-- a bit position over buf[0, nbits / 8) +export type Bits = { buf: buffer, pos: number, nbits: number } + +function Smacker.bits(buf: buffer, offset: number, length: number): Bits + return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } +end + +local function bit(br: Bits): number + local p = br.pos + br.pos = p + 1 + if p >= br.nbits then + return 0 + end + return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1) +end +Smacker.bit = bit + +-- read(br, n) -> n bits (LSB first; zeros past the end) +function Smacker.read(br: Bits, n: number): number + local v, m = 0, 1 + for _ = 1, n do + v += bit(br) * m + m *= 2 + end + return v +end +local readBits = Smacker.read + +-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +local function walk(tree: { number }, br: Bits): number + local i = 1 + local e = tree[1] + while e < 0 do + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = tree[i] + end + return e +end +Smacker.walk = walk + +-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) +local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) + local vals: { number } = {} + local n = 0 + local stack: { number } = {} + local state: { number } = {} + local sp = 0 + while true do + if sp > maxDepth then + return nil, "tree too deep" + end + if n >= maxEntries then + return nil, "tree too big" + end + if bigChecks and br.pos >= br.nbits then + return nil, "truncated tree" + end + if bit(br) == 1 then + n += 1 + vals[n] = -1 + sp += 1 + stack[sp], state[sp] = n, 0 + else + local v, msg = leaf(n) + if not v then + return nil, msg + end + n += 1 + vals[n] = v + local more = false + while sp > 0 do + if state[sp] == 0 then + local at = stack[sp] + vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries + state[sp] = 1 + more = true + break + end + sp -= 1 + end + if not more then + return vals, nil + end + end + end +end + +-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message +function Smacker.tree8(br: Bits): ({ number }?, string?) + local leaves = 0 + return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?) + if leaves >= 256 then + return nil, "tree too big" + end + leaves += 1 + if br.nbits - br.pos < 8 then + return nil, "truncated tree" + end + return readBits(br, 8), nil + end, false) +end +local tree8 = Smacker.tree8 + +export type BigTree = { vals: { number }, last: { number } } -- last: the escape leaves' indexes (1-based) + +-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) +local function bigTree(br: Bits, size: number): (BigTree?, string?) + if bit(br) == 0 then + return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 + end + local lohi: { { number } } = {} + for k = 1, 2 do + if bit(br) == 0 then + lohi[k] = { 0 } + else + local t, msg = tree8(br) + if not t then + return nil, msg + end + bit(br) + lohi[k] = t + end + end + local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } + local last = { -1, -1, -1 } + local lo, hi = lohi[1], lohi[2] + local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, function(index: number): (number?, string?) + local v = walk(lo, br) + walk(hi, br) * 256 + for k = 1, 3 do + if v == esc[k] then + last[k] = index + 1 + return 0, nil + end + end + return v, nil + end, true) + if not vals then + return nil, msg + end + bit(br) + for k = 1, 3 do + if last[k] == -1 then + table.insert(vals, 0) + last[k] = #vals + end + end + return { vals = vals, last = last }, nil +end + +export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } + +-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +function Smacker.trees(config: buffer): (Trees?, string?) + local n = buffer.len(config) + if n <= 16 then + return nil, "no trees" + end + local br = Smacker.bits(config, 16, n - 16) + local out: { BigTree } = {} + local present = 0 + for k = 1, 4 do + local size = buffer.readu32(config, (k - 1) * 4) + if size >= 2 ^ 28 then + return nil, "tree size too large" + end + local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1 + local t, msg = bigTree(br, size) + if not t then + return nil, msg + end + if here then + present += 1 + end + out[k] = t + end + if present == 0 or br.pos > br.nbits then + return nil, "bad trees" + end + return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil +end + +-- code(tree, br) -> the next value (updating the recent-value cache) | nil when the bits run out inside the tree +local function code(t: BigTree, br: Bits): number? + local vals = t.vals + local i = 1 + local e = vals[1] + while e < 0 do + if br.pos >= br.nbits then + return nil + end + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = vals[i] + end + local last = t.last + local l0, l1, l2 = last[1], last[2], last[3] + if e ~= vals[l0] then + vals[l2] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e +end + +local function reset(t: BigTree) + local vals, last = t.vals, t.last + vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 +end + +-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 +function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) + local px = pic.idx :: buffer + local stride = pic.stride + local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type + reset(mmap) + reset(mclr) + reset(full) + reset(typ) + local br = Smacker.bits(d, 0, buffer.len(d)) + local bw, bh = pic.w // 4, pic.h // 4 + local blocks = bw * bh + local blk = 0 + while blk < blocks do + local ty = code(typ, br) + if not ty then + return false, "truncated frame" + end + local run = RUNS[band(rshift(ty, 2), 63) + 1] + local kind = band(ty, 3) + if kind == 2 then + blk = math.min(blocks, blk + run) + elseif kind == 3 then + local v = rshift(ty, 8) * 0x01010101 + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + writeu32(px, o, v) + writeu32(px, o + stride, v) + writeu32(px, o + 2 * stride, v) + writeu32(px, o + 3 * stride, v) + blk += 1 + end + elseif kind == 0 then + for _ = 1, run do + if blk >= blocks then + break + end + local clr = code(mclr, br) + local map = code(mmap, br) + if not clr or not map then + return false, "truncated frame" + end + local hi, lo = rshift(clr, 8), band(clr, 255) + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + for r = 0, 3 do + local q = o + r * stride + writeu8(px, q, if band(map, 1) ~= 0 then hi else lo) + writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo) + writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo) + writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo) + map = rshift(map, 4) + end + blk += 1 + end + else + local mode = 0 + if v4 then + if br.pos >= br.nbits then + return false, "truncated frame" + end + if bit(br) == 1 then + mode = 1 + elseif bit(br) == 1 then + mode = 2 + end + end + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + if mode == 0 then + for r = 0, 3 do + local a = code(full, br) + local b = code(full, br) + if not a or not b then + return false, "truncated frame" + end + local q = o + r * stride + writeu8(px, q + 2, band(a, 255)) + writeu8(px, q + 3, rshift(a, 8)) + writeu8(px, q, band(b, 255)) + writeu8(px, q + 1, rshift(b, 8)) + end + elseif mode == 1 then + for half = 0, 1 do + local a = code(full, br) + if not a then + return false, "truncated frame" + end + local lo, hi = band(a, 255), rshift(a, 8) + local v = lo * 0x0101 + hi * 0x01010000 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + else + for half = 0, 1 do + local p2 = code(full, br) + local p1 = code(full, br) + if not p1 or not p2 then + return false, "truncated frame" + end + local v = p1 + p2 * 65536 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + end + blk += 1 + end + end + end + return true, nil +end + +return Smacker diff --git a/src/Formats/codecs/video/Legacy/init.luau b/src/Formats/codecs/video/Legacy/init.luau index 51729a4..f73885d 100644 --- a/src/Formats/codecs/video/Legacy/init.luau +++ b/src/Formats/codecs/video/Legacy/init.luau @@ -3,7 +3,8 @@ -- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk -- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", -- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation --- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey) and QuickTime Graphics ("smc", 'smc '). +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker +-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). -- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's -- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns -- a fresh copy. @@ -13,7 +14,7 @@ -- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). -- -- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder --- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } -- -- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). local Err = require("@formats/core/Err") @@ -24,6 +25,7 @@ local Cinepak = require("@formats/codecs/video/Legacy/Cinepak") local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1") local QtRle = require("@formats/codecs/video/Legacy/QtRle") local Smc = require("@formats/codecs/video/Legacy/Smc") +local Smacker = require("@formats/codecs/video/Legacy/Smacker") local Legacy = {} @@ -33,7 +35,8 @@ Legacy.Cinepak = Cinepak Legacy.Msvideo1 = Msvideo1 Legacy.QtRle = QtRle Legacy.Smc = Smc -Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +Legacy.Smacker = Smacker +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } export type Options = { maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) @@ -124,6 +127,30 @@ local CODECS: { [string]: Codec } = { return Picture.image(st.pic), nil end, }, + smackvid = { + make = function(t) + local cfg = t.config + if type(cfg) ~= "buffer" then + return nil, "no Smacker trees" + end + local trees, msg = Smacker.trees(cfg) + if not trees then + return nil, msg + end + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + if buffer.len(data) == 0 then + return nil, fail("empty frame") + end + local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, flic = { make = function(t) return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) diff --git a/src/Formats/video/smk/Audio.luau b/src/Formats/video/smk/Audio.luau new file mode 100644 index 0000000..2da8993 --- /dev/null +++ b/src/Formats/video/smk/Audio.luau @@ -0,0 +1,123 @@ +--!strict +--!native +--!optimize 2 +-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker +-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), +-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ +-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per +-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / +-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives +-- them. Never throws: trees are bounded and every read past the packet gives zero bits. +local Smacker = require("@formats/codecs/video/Legacy/Smacker") + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +local Audio = {} + +-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message +function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) + local n = buffer.len(d) + if not packed then + local bps = bits // 8 + local frames = n // (bps * channels) + local count = frames * channels + local out = table.create(count, 0) + if bps == 1 then + for i = 0, count - 1 do + out[i + 1] = (readu8(d, i) - 128) / 128 + end + else + for i = 0, count - 1 do + out[i + 1] = readi16(d, i * 2) / 32768 + end + end + return frames, out + end + if n <= 4 then + return nil, "packet too small" + end + local size = buffer.readu32(d, 0) + if size > 2 ^ 24 then + return nil, "packet too big" + end + local br = Smacker.bits(d, 4, n - 4) + local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk + if bit(br) == 0 then + return 0, {} -- no data + end + local stereo = bit(br) + local wide = bit(br) + if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then + return nil, "packet does not match the track's format" + end + local bytes = wide + 1 + local ch = stereo + 1 + if size % (ch * bytes) ~= 0 then + return nil, "unpacked size is not a whole number of samples" + end + local trees: { { number } } = {} + for k = 1, 2 ^ (wide + stereo) do + bit(br) + local t, msg = Smacker.tree8(br) + if not t then + return nil, msg or "bad tree" + end + bit(br) + trees[k] = t + end + if br.nbits - br.pos < ch * bytes * 8 then + return nil, "truncated packet" + end + -- whether any tree needs bits (else every delta is a constant and no end check applies) + local coded = false + for _, t in trees do + if #t > 1 then + coded = true + end + end + local frames = size // (ch * bytes) + local total = frames * ch + local out = table.create(total, 0) + if wide == 1 then + local pred = { 0, 0 } + for c = ch, 1, -1 do + local v = read(br, 16) + pred[c] = (v // 256) + (v % 256) * 256 + end + for c = 1, math.min(ch, total) do + local v = pred[c] + out[c] = (if v >= 32768 then v - 65536 else v) / 32768 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if coded and br.pos > br.nbits then + return nil, "truncated packet" + end + local lo = walk(trees[2 * c + 1], br) + local hi = walk(trees[2 * c + 2], br) + local v = (pred[c + 1] + lo + hi * 256) % 65536 + pred[c + 1] = v + out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768 + end + else + local pred = { 0, 0 } + for c = ch, 1, -1 do + pred[c] = read(br, 8) + end + for c = 1, math.min(ch, total) do + out[c] = (pred[c] - 128) / 128 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if br.pos > br.nbits then + return nil, "truncated packet" + end + local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256 + pred[c + 1] = v + out[i + 1] = (v - 128) / 128 + end + end + return frames, out +end + +return Audio diff --git a/src/Formats/video/smk/init.luau b/src/Formats/video/smk/init.luau new file mode 100644 index 0000000..11c4c45 --- /dev/null +++ b/src/Formats/video/smk/init.luau @@ -0,0 +1,320 @@ +--!strict +-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in formats-luau, written from the format description +-- (MultimediaWiki "Smacker"). +-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio +-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette +-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() +-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the +-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio +-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it +-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that +-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, +-- track) the Decoder of any of its audio tracks. +-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/video/Video") +local Stream = require("@formats/codecs/audio/Stream") +local Audio = require("@formats/video/smk/Audio") + +-- ------------------------------------------------------------------------------------------------ contract +local Smk = { + name = "smk", + category = "video", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + audio: boolean?, -- false: do not open the audio track + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 104 +local RING = 1 +-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4) +local PAL6 = table.create(64, 0) +for i = 0, 63 do + PAL6[i + 1] = i * 4 + i // 16 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Smk.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s ~= "SMK2" and s ~= "SMK4" then + return 0 + end + return 1 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed +local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) + local pal = buffer.create(1024) + buffer.copy(pal, 0, old, 0, 1024) + local function u8(): number + local v = if p < stop then buffer.readu8(b, p) else 0 + p += 1 + return v + end + local sz = 0 + while sz < 256 do + local t = u8() + if t >= 0x80 then + sz += t - 0x80 + 1 + elseif t >= 0x40 then + local off = u8() + local j = t - 0x40 + 1 + if off + j > 256 then + return nil + end + while j > 0 and sz < 256 do + buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4)) + sz += 1 + off += 1 + j -= 1 + end + else + local r = PAL6[t + 1] + local g = PAL6[u8() % 64 + 1] + local bl = PAL6[u8() % 64 + 1] + buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000) + sz += 1 + end + end + return pal +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the header") + end + local hr = Bytes.reader(b, base, HEADER) + local magic = hr:string(4) + local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le() + local ptsInc = hr:i32le() + local flags = hr:u32le() + hr:skip(28) + local treeSize = hr:u32le() + local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() } + local rates, aflags = {}, {} + for k = 1, 7 do + rates[k] = hr:u24le() + aflags[k] = hr:u8() + end + if hr.err then + return nil, hr.err + end + if magic ~= "SMK2" and magic ~= "SMK4" then + return nil, Err.new(Err.CORRUPT, "not a Smacker file") + end + if w == 0 or h == 0 or w > 32768 or h > 32768 then + return nil, Err.new(Err.CORRUPT, "bad picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + local shown = frames + if bit32.band(flags, RING) ~= 0 then + frames += 1 + end + local p = base + HEADER + if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then + return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file") + end + -- the trees (with the four sizes in front, as the video codec takes them) + local config = buffer.create(16 + treeSize) + for k = 1, 4 do + buffer.writeu32(config, (k - 1) * 4, sizes[k]) + end + buffer.copy(config, 16, b, p + frames * 5, treeSize) + -- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s) + local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000 + local tracks: { Types.Track } = { + { + id = 1, + kind = "video", + codec = "smackvid", + codecTag = magic, + timescale = 100000, + width = w, + height = h, + frameRate = 100000 / tick, + default = true, + config = config, + flags = flags, + } :: Types.Track, + } + local audio: { [number]: Types.Track } = {} + for k = 1, 7 do + if rates[k] > 0 then + local f = aflags[k] + local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8 + local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio" + elseif bit32.band(f, 0x80) ~= 0 then "smackaudio" + elseif bits == 16 then "pcm_s16le" + else "pcm_u8" + local t: Types.Track = { + id = k + 1, + kind = "audio", + codec = codec, + codecTag = string.format("0x%02X", f), + timescale = rates[k], + sampleRate = rates[k], + channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1, + bitsPerSample = bits, + default = #tracks == 1, + } + audio[k] = t + table.insert(tracks, t) + end + end + local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown }) + local count = if opts and opts.ringFrame then frames else shown + local pal = buffer.create(1024) + local apts = { 0, 0, 0, 0, 0, 0, 0 } + local at = p + frames * 5 + treeSize + for i = 0, frames - 1 do + local fsize = buffer.readu32(b, p + i * 4) + local fflags = buffer.readu8(b, p + frames * 4 + i) + local size = fsize - fsize % 4 + local q, stop = at, math.min(limit, at + size) + at += size + local ok = true + if fflags % 2 == 1 and q < stop then + local psize = buffer.readu8(b, q) * 4 + if psize > size then + ok = false + else + local np = palette(b, q + 1, math.min(stop, q + psize), pal) + if np then + pal = np + else + ok = false + end + q += psize + end + end + for k = 1, 7 do + if not ok then + break + end + if bit32.band(fflags, 2 ^ k) ~= 0 then + if q + 4 > stop then + ok = false + break + end + local asize = buffer.readu32(b, q) + local t = audio[k] + local min = if t and t.codec ~= "pcm_s16le" then 8 else 4 + if asize < min or q + asize > stop then + ok = false + break + end + if t then + local len = asize - 4 + local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8 + local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes + elseif t.codec == "binkaudio" then 0 + else len // frameBytes + dmx:add(t.id, apts[k], nil, n, true, q + 4, len) + apts[k] += n + end + q += asize + end + end + if ok and i < count then + dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q)) + dmx:setExtra("palette", pal) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err +function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) + local codec = track.codec + if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec) + end + local id = track.id + local count = dmx:count(id) + local starts: { number } = {} + local total = 0 + for k = 1, count do + local pts, _, dur = dmx:info(id, k) + starts[k] = pts or total + total = (pts or total) + (dur or 0) + end + starts[count + 1] = total + local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number + local packed = codec == "smackaudio" + local floats: { number } = {} + local dec: any = { + sampleRate = rate, + channels = ch, + frames = total, + duration = total / rate, + bitrate = rate * ch * bits, + tags = {}, + } + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return starts[math.clamp(i, 1, count + 1)] + end, + decode = function(i: number): (number?, Err.Err?) + local pkt = dmx:get(id, i) + if not pkt then + return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i) + end + local n, out = Audio.decode(pkt.data, ch, bits, packed) + if not n then + return nil, Err.from(out :: string) + end + floats = out :: { number } + return n, nil + end, + pcm = function(): { number } + return floats + end, + reset = function() end, + cumulative = true, + }) +end + +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Smk.demux(r, opts) + if not dmx then + return nil, err + end + local o: any = table.clone(opts or {}) + type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?) + local hook = o.openAudio :: Hook? + o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?) + if track.codec == "binkaudio" and hook then + return hook(d, track) + end + return Smk.openAudio(d, track) + end + return Video.open(dmx, o) +end + +return Smk diff --git a/tests/video/smk.luau b/tests/video/smk.luau new file mode 100644 index 0000000..6969cde --- /dev/null +++ b/tests/video/smk.luau @@ -0,0 +1,180 @@ +-- video/smk tests: Smacker files encoded by the fixture script (SMK2 and SMK4, every block type and run, the trees' +-- escape cache, palette updates, a ring frame, ms and 10 us frame times; packed 16-bit stereo / 8-bit mono / 16-bit +-- mono / 8-bit stereo audio and raw s16le / u8 tracks): every video frame and every audio track equal ffmpeg's +-- decode (CRC-32 of rgba / f32le), audio seeking, errors, and the fuzz pass on the container, the video codec and the +-- audio codec. Fixtures: tools/fixtures/smk.py. +local T = require("@tests/T") +local F = require("@formats") +local Smk = require("@formats/video/smk") +local SmkAudio = require("@formats/video/smk/Audio") +local Legacy = require("@formats/codecs/video/Legacy") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/smk_cases") + +local t = T.suite("smk") +t:eq(Smk.name, "smk", "name") +t:eq(Smk.category, "video", "category") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- every frame of an audio Decoder -> f32 buffer, frames +local function drain(dec: any): (buffer, number) + local chunks, total = {}, 0 + while true do + local b, n = dec:read(1000) + if n == 0 then + break + end + table.insert(chunks, { b, n }) + total += n + end + local out = buffer.create(total * dec.channels * 4) + local at = 0 + for _, c in chunks do + buffer.copy(out, at, c[1], 0, c[2] * dec.channels * 4) + at += c[2] * dec.channels * 4 + end + return out, total +end + +for _, c in Fx do + local label = c.name + t:check(Smk.sniff(reader(c.data)) == 1, label .. ": sniff") + t:eq(F.detect(buffer.fromstring(c.data)), "smk", label .. ": detect") + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:eq(v.codec, "smackvid", label .. ": codec") + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate) < 1e-6, label .. ": frame rate " .. v.frameRate) + local want = if c.ring then #c.frames - 1 else #c.frames + local n, bad = 0, 0 + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": " .. tostring(ferr)) + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad)) + v:seek(0.2) + local f = v:nextFrame() + local k = math.floor(0.2 * c.rate - 1e-9) + 2 + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k) + -- audio: the first track through the VideoDecoder, every track through Smk.openAudio + if #c.audio > 0 then + t:check(v.audio ~= nil, label .. ": audio " .. tostring(v.audioError)) + end + local tracks = {} + for _, tr in v.demuxer.tracks do + if tr.kind == "audio" then + table.insert(tracks, tr) + end + end + t:eq(#tracks, #c.audio, label .. ": audio tracks") + for i, a in c.audio do + local tr = tracks[i] + t:eq(tr.codec, a.codec, label .. ": audio " .. i .. " codec") + local dec, aerr = Smk.openAudio(v.demuxer, tr) + t:check(dec ~= nil, label .. ": audio " .. i .. ": " .. tostring(aerr)) + if dec then + t:check(dec.sampleRate == a.rate and dec.channels == a.channels, label .. ": audio " .. i .. " format") + local pcm, frames = drain(dec) + t:eq(frames, a.frames, label .. ": audio " .. i .. " frames") + t:eq(Crc32.of(pcm), a.crc, label .. ": audio " .. i .. " equals ffmpeg's") + dec:seek(0) + local again = drain(dec) + t:eq(Crc32.of(again), a.crc, label .. ": audio " .. i .. " after seek(0)") + dec:seek(0.3) + local tail, rest = drain(dec) + local skip = a.frames - rest + t:check(math.abs(skip - 0.3 * a.rate) <= 1, label .. ": audio " .. i .. " seek(0.3) at frame " .. skip) + local same = buffer.len(tail) > 0 + for q = 0, math.min(buffer.len(tail), 4000) - 4, 4 do + if buffer.readu32(tail, q) ~= buffer.readu32(pcm, skip * a.channels * 4 + q) then + same = false + break + end + end + t:check(same, label .. ": audio " .. i .. " seek(0.3) samples") + end + end + if c.ring then + local v2 = Smk.open(reader(c.data), { ringFrame = true }) + local m = 0 + while v2 and v2:nextFrame() do + m += 1 + end + t:eq(m, #c.frames, label .. ": with the ring frame") + end + end +end + +-- errors +do + local _, e = Smk.open(reader(string.sub(Fx[1].data, 1, 60))) + t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED") + local _, e2 = Smk.open(reader("SMK3" .. string.sub(Fx[1].data, 5))) + t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT") + t:eq(Smk.sniff(reader("SMK3" .. string.sub(Fx[1].data, 5))), 0, "bad magic: no sniff") + local _, e3 = Smk.open(reader(Fx[1].data), { maxPixels = 100 }) + t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT") + local _, e4 = Smk.open(reader(string.sub(Fx[1].data, 1, 200))) + t:check(e4 ~= nil and e4.code == Err.TRUNCATED, "trees past the end: TRUNCATED") +end + +-- fuzz: the container, the video codec (native, no pcall in between) and the audio codec +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("open", function(b: buffer) + local v = Smk.open(Bytes.reader(b)) + if v then + for _ = 1, 4 do + if not v:nextFrame() then + break + end + end + if v.audio then + v.audio:read(500) + end + end + return v +end, samples, { mutations = 16, garbage = 40, keepHeader = 4 }) +local S, P = Legacy.Smacker, Legacy.Picture +for _, c in { Fx[1], Fx[2] } do + local d = Smk.demux(reader(c.data)) + local tr = d.tracks[1] + local packets = {} + for k = 1, math.min(3, d:count(1)) do + table.insert(packets, d:get(1, k).data) + end + t:fuzz(c.name .. " trees", function(b: buffer) + return S.trees(b) + end, { tr.config }, { mutations = 30, garbage = 30, keepHeader = 16 }) + local trees = assert(S.trees(tr.config)) + t:fuzz(c.name .. " frames", function(b: buffer) + return S.decode(P.new(c.width, c.height, true, 4, 4), b, trees, tr.codecTag == "SMK4") + end, packets, { mutations = 30, garbage = 30 }) + for _, at in d.tracks do + if at.kind == "audio" then + local ap = {} + for k = 1, math.min(2, d:count(at.id)) do + table.insert(ap, d:get(at.id, k).data) + end + t:fuzz(c.name .. " audio " .. at.codec, function(b: buffer) + return SmkAudio.decode(b, at.channels, at.bitsPerSample, at.codec == "smackaudio") + end, ap, { mutations = 20, garbage = 20 }) + end + end +end +t:done() diff --git a/tools/fixtures/smk.py b/tools/fixtures/smk.py new file mode 100644 index 0000000..0d9ee5a --- /dev/null +++ b/tools/fixtures/smk.py @@ -0,0 +1,493 @@ +# Smacker fixtures (tools/fixtures.py): ffmpeg cannot write Smacker, so this encodes SMK2 / SMK4 files: the four +# header trees (8-bit low / high byte trees, escape leaves used through the recent-value cache, absent trees), every +# block type (MONO, FULL with the SMK4 doubled modes, SKIP, FILL) with block runs, palette updates (new entries, skips, +# copies from the old palette), a ring frame, both frame-time units, and audio tracks: packed DPCM 16-bit stereo and +# 8-bit mono, raw s16le and u8. The reference is ffmpeg's decode: the CRC-32 of each video frame as rgba and of each +# audio track as f32le. +# tests/gen/smk_cases.luau { { name, data, width, height, rate, frames = { crc }, audio = { { rate, channels, +# bits, codec, frames, crc } } } } +import heapq, importlib.util, math, os, random, struct, tempfile, zlib + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +RUNS = list(range(1, 60)) + [128, 256, 512, 1024, 2048] + + +# ---------------------------------------------------------------------------------------------------- bits / trees +class Bits: + def __init__(self): + self.bits = [] + + def put(self, v, n): + for i in range(n): + self.bits.append((v >> i) & 1) + + def code(self, c): + self.bits.extend(c) + + def bytes(self): + out = bytearray((len(self.bits) + 7) // 8) + for i, b in enumerate(self.bits): + out[i >> 3] |= b << (i & 7) + return bytes(out) + + +def huffman(freqs, maxdepth): + """a Huffman tree over freqs {value: count}: nested (left, right) tuples / ('leaf', value)""" + f = dict(freqs) + while True: + heap = [(c, i, ("leaf", v)) for i, (v, c) in enumerate(sorted(f.items()))] + heapq.heapify(heap) + k = len(heap) + while len(heap) > 1: + a = heapq.heappop(heap) + b = heapq.heappop(heap) + heapq.heappush(heap, (a[0] + b[0], k, (a[2], b[2]))) + k += 1 + tree = heap[0][2] + if depth(tree) <= maxdepth: + return tree + f = {v: c // 2 + 1 for v, c in f.items()} + + +def depth(t): + return 0 if t[0] == "leaf" else 1 + max(depth(t[0]), depth(t[1])) + + +def codes(t, prefix=(), out=None): + out = {} if out is None else out + if t[0] == "leaf": + out[t[1]] = list(prefix) + else: + codes(t[0], prefix + (0,), out) + codes(t[1], prefix + (1,), out) + return out + + +def write_tree8(bw, t): + if t[0] == "leaf": + bw.put(0, 1) + bw.put(t[1], 8) + else: + bw.put(1, 1) + write_tree8(bw, t[0]) + write_tree8(bw, t[1]) + + +class BigTree: + """a header tree: values (16-bit) with three escape leaves for the recent-value cache""" + + def __init__(self, freqs, rnd, absent_ok=True): + self.absent = not freqs + if self.absent: + return + lo = {} + hi = {} + for v, c in freqs.items(): + lo[v & 255] = lo.get(v & 255, 0) + c + hi[v >> 8] = hi.get(v >> 8, 0) + c + # three escape values made of bytes the byte trees have, not used as values (a high-byte tree of only 0 is + # left out: absent byte trees decode as 0) + esc = [] + for l in sorted(lo): + for h in sorted(hi): + v = l | h << 8 + if v not in freqs and len(esc) < 3: + esc.append(v) + while len(esc) < 3: # every combination used: widen the low byte tree + nl = next(x for x in range(256) if x not in lo) + lo[nl] = 1 + esc.append(nl | sorted(hi)[0] << 8) + self.esc = esc + self.lo = huffman(lo, 27) + self.hi = huffman(hi, 27) + allv = dict(freqs) + for i, e in enumerate(esc): + allv[e] = max(1, sum(freqs.values()) // (8 + i)) + self.tree = huffman(allv, 200) + self.lcodes, self.hcodes, self.vcodes = codes(self.lo), codes(self.hi), codes(self.tree) + self.entries = count_entries(self.tree) + self.hi_absent = len(hi) == 1 and 0 in hi + self.rnd = rnd + + def write(self, bw): + if self.absent: + bw.put(0, 1) + return + bw.put(1, 1) + bw.put(1, 1) + write_tree8(bw, self.lo) + bw.put(0, 1) + if self.hi_absent: + bw.put(0, 1) + else: + bw.put(1, 1) + write_tree8(bw, self.hi) + bw.put(0, 1) + for e in self.esc: + bw.put(e, 16) + self._write_big(bw, self.tree) + bw.put(0, 1) + + def _write_big(self, bw, t): + if t[0] == "leaf": + bw.put(0, 1) + v = t[1] + bw.code(self.lcodes[v & 255]) + if not self.hi_absent: + bw.code(self.hcodes[v >> 8]) + else: + bw.put(1, 1) + self._write_big(bw, t[0]) + self._write_big(bw, t[1]) + + def size(self): + return 0 if self.absent else (self.entries + 3) * 4 + + def reset(self): + self.cache = [0, 0, 0] + + def emit(self, bw, v): + if self.absent: + assert v == 0 + return + hit = [k for k in range(3) if self.cache[k] == v] + if hit and self.rnd.random() < 0.7: + bw.code(self.vcodes[self.esc[hit[0]]]) + else: + bw.code(self.vcodes[v]) + if v != self.cache[0]: + self.cache[2] = self.cache[1] + self.cache[1] = self.cache[0] + self.cache[0] = v + + +def count_entries(t): + return 1 if t[0] == "leaf" else 1 + count_entries(t[0]) + count_entries(t[1]) + + +# ---------------------------------------------------------------------------------------------------- video +def blocks_of(img, w, h): + return [[[img[by * 4 + r][bx * 4 + x] for x in range(4)] for r in range(4)] for by in range(h // 4) for bx in range(w // 4)] + + +def classify(b, prev, v4): + if prev is not None and b == prev: + return ("skip",) + flat = [p for r in b for p in r] + cols = sorted(set(flat)) + if len(cols) == 1: + return ("fill", cols[0]) + if len(cols) == 2: + lo, hi = cols + m = 0 + for i, p in enumerate(flat): + if p == hi: + m |= 1 << i + return ("mono", hi << 8 | lo, m) + if v4 and b[0] == b[1] and b[2] == b[3] and b[0][0] == b[0][1] and b[0][2] == b[0][3] and b[2][0] == b[2][1] and b[2][2] == b[2][3]: + return ("full", 1) + if v4 and b[0] == b[1] and b[2] == b[3]: + return ("full", 2) + return ("full", 0) + + +def full_codes(b, mode): + if mode == 0: + out = [] + for r in b: + out += [r[2] | r[3] << 8, r[0] | r[1] << 8] + return out + if mode == 1: + return [b[0][0] | b[0][2] << 8, b[2][0] | b[2][2] << 8] + return [b[0][2] | b[0][3] << 8, b[0][0] | b[0][1] << 8, b[2][2] | b[2][3] << 8, b[2][0] | b[2][1] << 8] + + +def plan(frames, w, h, v4): + """per frame the list of runs: (kind, extra, [blocks])""" + out = [] + prev = None + for img in frames: + bl = blocks_of(img, w, h) + cls = [classify(b, prev[i] if prev else None, v4) for i, b in enumerate(bl)] + runs = [] + i = 0 + while i < len(bl): + c = cls[i] + key = c[:2] if c[0] in ("fill", "full") else c[:1] + j = i + while j + 1 < len(bl) and (cls[j + 1][:2] if cls[j + 1][0] in ("fill", "full") else cls[j + 1][:1]) == key: + j += 1 + n = j - i + 1 + # the largest run length of the table that fits + k = max(r for r in RUNS if r <= n) + runs.append((c, [bl[x] for x in range(i, i + k)], [cls[x] for x in range(i, i + k)], RUNS.index(k))) + i += k + out.append(runs) + prev = bl + return out + + +def type_value(c, ri): + kind = {"mono": 0, "full": 1, "skip": 2, "fill": 3}[c[0]] + v = kind | ri << 2 + if c[0] == "fill": + v |= c[1] << 8 + return v + + +def stats(plans, v4): + f = {"type": {}, "mclr": {}, "mmap": {}, "full": {}} + + def add(t, v): + f[t][v] = f[t].get(v, 0) + 1 + + for runs in plans: + for c, bl, cl, ri in runs: + add("type", type_value(c, ri)) + if c[0] == "mono": + for x in cl: + add("mclr", x[1]) + add("mmap", x[2]) + elif c[0] == "full": + for b in bl: + for v in full_codes(b, c[1]): + add("full", v) + return f + + +def encode_video(frames, w, h, v4, rnd): + plans = plan(frames, w, h, v4) + f = stats(plans, v4) + trees = {k: BigTree(f[k], rnd) for k in ("mmap", "mclr", "full", "type")} + tb = Bits() + for k in ("mmap", "mclr", "full", "type"): + trees[k].write(tb) + treebytes = tb.bytes() + out = [] + for runs in plans: + for t in trees.values(): + t.reset() + bw = Bits() + for c, bl, cl, ri in runs: + trees["type"].emit(bw, type_value(c, ri)) + if c[0] == "mono": + for x in cl: + trees["mclr"].emit(bw, x[1]) + trees["mmap"].emit(bw, x[2]) + elif c[0] == "full": + if v4: + bw.code([1] if c[1] == 1 else [0, 1] if c[1] == 2 else [0, 0]) + for b in bl: + for v in full_codes(b, c[1]): + trees["full"].emit(bw, v) + out.append(bw.bytes() or b"\0") + return treebytes, [trees[k].size() for k in ("mmap", "mclr", "full", "type")], out + + +# ---------------------------------------------------------------------------------------------------- palettes +def pal_chunk(new, old, first): + """a palette update: new / old are lists of 256 6-bit (r, g, b)""" + body = bytearray() + i = 0 + while i < 256: + if not first and new[i] == old[i]: + j = i + while j < 256 and j - i < 128 and new[j] == old[j]: + j += 1 + body.append(0x80 | (j - i - 1)) + i = j + continue + # a copy from the old palette when the next entries appear there in a row + if not first: + for off in range(256): + n = 0 + while i + n < 256 and off + n < 256 and n < 64 and new[i + n] == old[off + n]: + n += 1 + if n >= 2: + body += bytes([0x40 | (n - 1), off]) + i += n + break + else: + off = None + if off is not None: + continue + body += bytes(new[i]) + i += 1 + size = 1 + len(body) + size = (size + 3) // 4 * 4 + return bytes([size // 4]) + bytes(body) + bytes(size - 1 - len(body)) + + +# ---------------------------------------------------------------------------------------------------- audio +def pack_audio(samples, ch, bits): + """one packed (SMKA) chunk body: samples interleaved (s16 or u8)""" + nb = bits // 8 + bw = Bits() + bw.put(1, 1) + bw.put(1 if ch == 2 else 0, 1) + bw.put(1 if bits == 16 else 0, 1) + mod = 65536 if bits == 16 else 256 + pred = list(samples[:ch]) + deltas = [] + for i in range(ch, len(samples)): + c = i % ch + d = (samples[i] - pred[c]) % mod + pred[c] = samples[i] + deltas.append((c, d)) + ntrees = (2 if bits == 16 else 1) * ch + freqs = [dict() for _ in range(ntrees)] + for c, d in deltas: + if bits == 16: + freqs[2 * c][d & 255] = freqs[2 * c].get(d & 255, 0) + 1 + freqs[2 * c + 1][d >> 8] = freqs[2 * c + 1].get(d >> 8, 0) + 1 + else: + freqs[c][d] = freqs[c].get(d, 0) + 1 + trees = [huffman(f or {0: 1}, 27) for f in freqs] + cds = [codes(t) for t in trees] + for t in trees: + bw.put(1, 1) + write_tree8(bw, t) + bw.put(0, 1) + for c in range(ch - 1, -1, -1): + v = samples[c] % mod + if bits == 16: + v = ((v & 255) << 8) | (v >> 8) # stored byte-swapped + bw.put(v, bits) + for c, d in deltas: + if bits == 16: + bw.code(cds[2 * c][d & 255]) + bw.code(cds[2 * c + 1][d >> 8]) + else: + bw.code(cds[c][d]) + return struct.pack(" 0 else -pts_inc / 100000.0) + achunks = [] + for ti, (kind, rate, ch, bits) in enumerate(tracks): + per = [] + done = 0 + for t in range(total): + n = int(round((t + 1) * seconds * rate)) - done + done += n + s = tone(n, ch, bits, rate, seed * 10 + ti * 100 + t, 440 + 110 * ti) + if kind == "packed": + per.append(pack_audio(s, ch, bits)) + else: + per.append(b"".join(struct.pack(" 0 else 100000 / -pts + cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio, + "ring": ring}) + ctx.emit("smk_cases", cases) From d99b026b0711e60a59317e432a3703f74a8dbd9f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:29 -0500 Subject: [PATCH 12/19] legacy video: bench lines (320x240 / 320x200 fixtures), Smacker frame decoder through 10-bit lookup tables --- src/Formats/codecs/video/Legacy/Smacker.luau | 146 ++++++++++++------- tools/bench.luau | 39 +++++ tools/fixtures/fli.py | 6 + tools/fixtures/legacy.py | 8 + tools/fixtures/smk.py | 14 +- 5 files changed, 157 insertions(+), 56 deletions(-) diff --git a/src/Formats/codecs/video/Legacy/Smacker.luau b/src/Formats/codecs/video/Legacy/Smacker.luau index c5923ec..eab6650 100644 --- a/src/Formats/codecs/video/Legacy/Smacker.luau +++ b/src/Formats/codecs/video/Legacy/Smacker.luau @@ -9,12 +9,13 @@ -- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; -- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a -- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). --- Trees are flat arrays (a node stores the size of its left subtree, as a negative number) walked bit by bit. +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads +-- 10 bits at a time through a lookup table into them. -- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give -- zero bits, a frame whose codes run out of bits gives no picture. local Picture = require("@formats/codecs/video/Legacy/Picture") -local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local band, rshift = bit32.band, bit32.rshift local Smacker = {} @@ -135,7 +136,7 @@ function Smacker.tree8(br: Bits): ({ number }?, string?) end local tree8 = Smacker.tree8 -export type BigTree = { vals: { number }, last: { number } } -- last: the escape leaves' indexes (1-based) +export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) -- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) local function bigTree(br: Bits, size: number): (BigTree?, string?) @@ -213,29 +214,26 @@ function Smacker.trees(config: buffer): (Trees?, string?) return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil end --- code(tree, br) -> the next value (updating the recent-value cache) | nil when the bits run out inside the tree -local function code(t: BigTree, br: Bits): number? - local vals = t.vals - local i = 1 - local e = vals[1] - while e < 0 do - if br.pos >= br.nbits then - return nil +local LUT_BITS = 10 + +-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits +local function lut(vals: { number }): buffer + local size = 2 ^ LUT_BITS + local t = buffer.create(size * 4) + for pat = 0, size - 1 do + local i, len = 1, 0 + local e = vals[1] + while e < 0 and len < LUT_BITS do + if band(rshift(pat, len), 1) == 1 then + i += -e - 1 + end + i += 1 + len += 1 + e = vals[i] end - if bit(br) == 1 then - i += -e - 1 - end - i += 1 - e = vals[i] + writeu32(t, pat * 4, i * 32 + len) end - local last = t.last - local l0, l1, l2 = last[1], last[2], last[3] - if e ~= vals[l0] then - vals[l2] = vals[l1] - vals[l1] = vals[l0] - vals[l0] = e - end - return e + return t end local function reset(t: BigTree) @@ -248,17 +246,65 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole local px = pic.idx :: buffer local stride = pic.stride local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type - reset(mmap) - reset(mclr) - reset(full) - reset(typ) - local br = Smacker.bits(d, 0, buffer.len(d)) + for _, t in { mmap, mclr, full, typ } do + reset(t) + if not t.lut then + t.lut = lut(t.vals) + end + end + local n = buffer.len(d) + local nbits = n * 8 + local pos = 0 + -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree + local function code(t: BigTree): number + local vals = t.vals + local i, p + local byte = rshift(pos, 3) + if byte + 3 <= n then + local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023) + local ent = readu32(t.lut :: buffer, v * 4) + i = rshift(ent, 5) + p = pos + band(ent, 31) + else + i, p = 1, pos + end + local e = vals[i] + while e < 0 do + if p >= nbits then + return -1 + end + if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then + i += -e - 1 + end + p += 1 + i += 1 + e = vals[i] + end + pos = p + local last = t.last + local l0 = last[1] + if e ~= vals[l0] then + local l1 = last[2] + vals[last[3]] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e + end + local function bit(): number + local p = pos + pos = p + 1 + if p >= nbits then + return 0 + end + return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) + end local bw, bh = pic.w // 4, pic.h // 4 local blocks = bw * bh local blk = 0 while blk < blocks do - local ty = code(typ, br) - if not ty then + local ty = code(typ) + if ty < 0 then return false, "truncated frame" end local run = RUNS[band(rshift(ty, 2), 63) + 1] @@ -283,9 +329,9 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole if blk >= blocks then break end - local clr = code(mclr, br) - local map = code(mmap, br) - if not clr or not map then + local clr = code(mclr) + local map = code(mmap) + if clr < 0 or map < 0 then return false, "truncated frame" end local hi, lo = rshift(clr, 8), band(clr, 255) @@ -303,12 +349,12 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole else local mode = 0 if v4 then - if br.pos >= br.nbits then + if pos >= nbits then return false, "truncated frame" end - if bit(br) == 1 then + if bit() == 1 then mode = 1 - elseif bit(br) == 1 then + elseif bit() == 1 then mode = 2 end end @@ -319,33 +365,29 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole local o = (blk // bw) * stride * 4 + (blk % bw) * 4 if mode == 0 then for r = 0, 3 do - local a = code(full, br) - local b = code(full, br) - if not a or not b then + local a = code(full) + local b = code(full) + if a < 0 or b < 0 then return false, "truncated frame" end - local q = o + r * stride - writeu8(px, q + 2, band(a, 255)) - writeu8(px, q + 3, rshift(a, 8)) - writeu8(px, q, band(b, 255)) - writeu8(px, q + 1, rshift(b, 8)) + -- the first code is the right pixel pair, the second the left one + writeu32(px, o + r * stride, b + a * 65536) end elseif mode == 1 then for half = 0, 1 do - local a = code(full, br) - if not a then + local a = code(full) + if a < 0 then return false, "truncated frame" end - local lo, hi = band(a, 255), rshift(a, 8) - local v = lo * 0x0101 + hi * 0x01010000 + local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000 writeu32(px, o + half * 2 * stride, v) writeu32(px, o + (half * 2 + 1) * stride, v) end else for half = 0, 1 do - local p2 = code(full, br) - local p1 = code(full, br) - if not p1 or not p2 then + local p2 = code(full) + local p1 = code(full) + if p1 < 0 or p2 < 0 then return false, "truncated frame" end local v = p1 + p2 * 65536 diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..f593634 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,42 @@ do jitTune(false) end end +-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps +do + -- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240 + -- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks); + -- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second) + local F = require("@formats") + local LB = require("@tests/gen/legacy_bench") + local cases = table.clone(LB) + table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 }) + table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 }) + for _, c in cases do + local data = buffer.fromstring(c.data) + local frames = 0 + local dt = math.huge + for _ = 1, 3 do + local t0 = os.clock() + local v = assert(F.video.open(data, { audio = false })) + frames = 0 + while v:nextFrame() do + frames += 1 + end + dt = math.min(dt, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt)) + end + local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data))) + local a = assert(v.audio) + local t0 = os.clock() + local n = 0 + while true do + local _, got = a:read(4096) + if got == 0 then + break + end + n += got + end + local dt = os.clock() - t0 + print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt)) +end diff --git a/tools/fixtures/fli.py b/tools/fixtures/fli.py index 0428f02..e7ad3d6 100644 --- a/tools/fixtures/fli.py +++ b/tools/fixtures/fli.py @@ -393,3 +393,9 @@ def generate(ctx): assert crcs, name cases.append({"name": name, "data": data, "width": w, "height": h, "depth": depth, "rate": rate, "frames": crcs}) ctx.emit("fli_cases", cases) + # tools/bench.luau: a 320x200 FLC, 10 frames (BRUN then SS2 deltas) + w, h, n = 320, 200, 10 + imgs = idx_frames(w, h, n, 256, 9) + frames = [frame([color([(0, pal(256, 9, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])] + frames += [frame([ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)] + ctx.emit("fli_bench", {"data": file(0xAF12, w, h, 8, 66, frames), "width": w, "height": h, "frames": n}) diff --git a/tools/fixtures/legacy.py b/tools/fixtures/legacy.py index 863b866..76353ce 100644 --- a/tools/fixtures/legacy.py +++ b/tools/fixtures/legacy.py @@ -98,3 +98,11 @@ def generate(ctx): for c in cases: assert c["frames"], c["name"] + ": ffmpeg decoded no frame" ctx.emit("legacy_cases", cases) + # tools/bench.luau: 320x240, 10 frames of each codec + bench = [] + big = ["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=10", "-t", "1"] + for name, args in [("cinepak.avi", ["-c:v", "cinepak"]), ("msvideo1.avi", ["-c:v", "msvideo1"]), + ("qtrle.mov", ["-c:v", "qtrle", "-pix_fmt", "rgb24"]), ("smc.mov", ["-c:v", "smc"])]: + ff(*big, *args, "bench_" + name) + bench.append({"name": name, "data": open(os.path.join(tmp, "bench_" + name), "rb").read(), "width": 320, "height": 240}) + ctx.emit("legacy_bench", bench) diff --git a/tools/fixtures/smk.py b/tools/fixtures/smk.py index 0d9ee5a..0bfba7a 100644 --- a/tools/fixtures/smk.py +++ b/tools/fixtures/smk.py @@ -381,11 +381,14 @@ def tone(n, ch, bits, rate, seed, f0): # ---------------------------------------------------------------------------------------------------- files -def idx_frames(w, h, n, seed): +def idx_frames(w, h, n, seed, busy=False): rnd = random.Random(seed) out = [] for t in range(n): - img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)] + if busy: # textured, moving: mostly FULL blocks (the bench) + img = [[(x * 3 + y * 5 + ((x + t * 4) * (y + t)) // 7) % 251 for x in range(w)] for y in range(h)] + else: + img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)] for y in range(8, 24): for x in range(8 + t * 4, 24 + t * 4): img[y][x] = 100 + (x + y) % 2 # two colours: MONO blocks @@ -399,10 +402,10 @@ def idx_frames(w, h, n, seed): return out -def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed): +def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed, busy=False): """version 2 / 4; tracks = [(kind, rate, ch, bits)] kind "packed" / "raw"; returns bytes, track info""" rnd = random.Random(seed) - frames = idx_frames(w, h, nframes, seed) + frames = idx_frames(w, h, nframes, seed, busy) if ring: frames = frames + [frames[0]] treebytes, sizes, video = encode_video(frames, w, h, version == 4, rnd) @@ -491,3 +494,6 @@ def generate(ctx): cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio, "ring": ring}) ctx.emit("smk_cases", cases) + # tools/bench.luau: a 320x200 SMK4 with 22.05 kHz packed stereo audio, 10 frames + ctx.emit("smk_bench", {"data": smk_file(4, 320, 200, 10, 100, [("packed", 22050, 2, 16)], False, 9, True), "width": 320, + "height": 200, "frames": 10}) From 1013925a85fe3c3435cac17823f60a58e0907b1d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:22 -0500 Subject: [PATCH 13/19] ws-video2-theora: Theora speed (fused prediction + IDCT add, inlined token decode, table-driven tokens), bench lines, guide section tools/bench.luau: a ws-video2-theora block (320x240 testsrc2 / mandelbrot, decode and decode + image()). docs/guide/video.md: an Ogg Theora section (tested snippet; inputs from the new tools/fixtures/docs_theora.py) and the formats / writers tables. --- docs/guide/video.md | 28 +- src/Formats/codecs/video/Theora/Decoder.luau | 462 ++++++++++--------- src/Formats/codecs/video/Theora/Header.luau | 2 +- tools/bench.luau | 39 ++ tools/fixtures/docs_theora.py | 20 + tools/fixtures/theora.py | 13 +- 6 files changed, 342 insertions(+), 222 deletions(-) create mode 100644 tools/fixtures/docs_theora.py diff --git a/docs/guide/video.md b/docs/guide/video.md index 99e0395..6d2ed39 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -179,6 +179,7 @@ Images and animated images save as videos too. | Destination | Video | Audio | |---|---|---| | webm | VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) | Opus / Vorbis copied | +| ogv | Theora copied (the source must be Theora: ogv or mkv) | Vorbis / Opus copied | | mkv | any codec copied, else MJPEG | copied, else PCM s16 | | mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only | | avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 | @@ -235,6 +236,30 @@ assert(C.register({ assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid")) ``` +## Ogg Theora + +Ogg video (`.ogv`, or `.ogg` with a Theora stream) opens like any other container: the `ogv` format demuxes every +Ogg stream, Theora video decodes bit-exactly (as libtheora / ffmpeg) in all three pixel formats (4:2:2 and 4:4:4 +chroma is averaged down to yuv420p), and a Vorbis, Opus or FLAC track becomes `v.audio`. Plain Ogg Vorbis / Opus / +FLAC files stay audio. Theora in Matroska (`V_THEORA`) decodes too, and an Ogg Theora video remuxes to ogv or mkv +(there is no Theora encoder). + +```luau +local v = assert(F.video.open(ogvBytes)) -- Theora + Vorbis +assert(v.format == "ogv" and v.codec == "theora" and v.width == 64 and v.height == 48) +assert(v.frameRate == 10 and v.audio ~= nil) +local n = 0 +while v:nextFrame() do n += 1 end -- dropped frames repeat the previous picture +assert(n == 10) +local Theora = F.format("ogv") -- the format module: sniff / demux / open / encode +local d = assert(Theora.demux(F.Bytes.reader(ogvBytes))) +local vt = d:track("video") +assert(vt.codec == "theora" and vt.timescale == 10) -- packet times are frame numbers here +v:reset() +local mkv = assert(F.save(v, nil, { format = "mkv" })) -- Theora + Vorbis copied into Matroska +assert(F.video.open(mkv).codec == "theora") +``` + ## Playing in a game loop Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes @@ -279,7 +304,8 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) | Format | Read | Write | Video codecs (decode) | |---|---|---|---| | mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 | -| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | +| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw, Theora (+ H.264) | +| ogv (Ogg Theora) | yes | yes (Theora + Vorbis / Opus copied) | Theora | | avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | | mpegts, mpegps | yes | - | MPEG-1, H.264 | | y4m | yes | yes | raw | diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau index d29b8cf..aad8f1c 100644 --- a/src/Formats/codecs/video/Theora/Decoder.luau +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -24,9 +24,10 @@ local writeu8 = buffer.writeu8 local readu16 = buffer.readu16 local readi16 = buffer.readi16 local writei16 = buffer.writei16 -local readi32 = buffer.readi32 -local writei32 = buffer.writei32 local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local band = bit32.band +local bxor = bit32.bxor local bcopy = buffer.copy local bfill = buffer.fill local lshift = bit32.lshift @@ -93,10 +94,56 @@ do end -- DCT tokens: extra bits per token -local TOKEN_EXTRA = { - [0] = 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +local TOKEN_EXTRA = { -- [token + 1] + 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, } +-- the zero-run / coefficient tokens (7..31) by token * 1024 + extra bits + 1: run * 4096 + value + 2048, where run is +-- the zeros before the value (value 0: a pure zero run of run + 1) +local TOKEN_VALUE = table.create(32 * 1024, 2048) +for tok = 7, 31 do + local ex = TOKEN_EXTRA[tok + 1] + for eb = 0, 2 ^ ex - 1 do + local v, r = 0, 0 + if tok < 9 then + r = eb -- zero runs: eb + 1 zeros + elseif tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) -- the top extra bit is the sign + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + TOKEN_VALUE[tok * 1024 + eb + 1] = r * 4096 + v + 2048 + end +end + -- natural index of zig-zag position (1-based by position + 1) local ZIGZAG = Header.ZIGZAG @@ -158,9 +205,8 @@ export type State = { lflim: { number }, huff: { number }, roots: { number }, - blk: buffer, -- i32 x 64 work blocks + blk: buffer, -- i16 x 64 work blocks tmp: buffer, - res: buffer, bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] keyframes: number, } @@ -191,9 +237,8 @@ function D.new(info: Header.Info, setup: Header.Setup): State lflim = setup.lflim, huff = setup.huff, roots = setup.roots, - blk = buffer.create(256), - tmp = buffer.create(256), - res = buffer.create(256), + blk = buffer.create(128), + tmp = buffer.create(128), bv = table.create(257, 0), keyframes = 0, } @@ -366,23 +411,24 @@ local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 end --- 2-D IDCT of blk (i16, natural order) into res (i32 residuals). Like libtheora, the dequantised coefficients and --- the first pass's outputs are 16-bit (the i16 buffers wrap them), which also bounds every residual to +-24000. -local function idct(blk: buffer, tmp: buffer, res: buffer) +-- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the +-- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) +local function idctRows(blk: buffer, tmp: buffer) for i = 0, 7 do local o = i * 16 local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) local c = i * 2 - if x0 == 0 and x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then - writei16(tmp, c, 0) - writei16(tmp, c + 16, 0) - writei16(tmp, c + 32, 0) - writei16(tmp, c + 48, 0) - writei16(tmp, c + 64, 0) - writei16(tmp, c + 80, 0) - writei16(tmp, c + 96, 0) - writei16(tmp, c + 112, 0) + if x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + local y = (C4 * x0) // 65536 + writei16(tmp, c, y) + writei16(tmp, c + 16, y) + writei16(tmp, c + 32, y) + writei16(tmp, c + 48, y) + writei16(tmp, c + 64, y) + writei16(tmp, c + 80, y) + writei16(tmp, c + 96, y) + writei16(tmp, c + 112, y) else local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) writei16(tmp, c, y0) @@ -395,20 +441,29 @@ local function idct(blk: buffer, tmp: buffer, res: buffer) writei16(tmp, c + 112, y7) end end - for i = 0, 7 do - local o = i * 16 - local x0, x1, x2, x3 = readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6) - local x4, x5, x6, x7 = readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14) - local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) - local c = i * 4 - writei32(res, c, (y0 + 8) // 16) - writei32(res, c + 32, (y1 + 8) // 16) - writei32(res, c + 64, (y2 + 8) // 16) - writei32(res, c + 96, (y3 + 8) // 16) - writei32(res, c + 128, (y4 + 8) // 16) - writei32(res, c + 160, (y5 + 8) // 16) - writei32(res, c + 192, (y6 + 8) // 16) - writei32(res, c + 224, (y7 + 8) // 16) +end + +-- the second pass, added to the prediction already in dst: column c of the block is row c of tmp +local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) + for c = 0, 7 do + local o = c * 16 + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) + local p = pos + c + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y0 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y1 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y2 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y3 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y4 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y5 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y6 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y7 + 8) // 16 + COFF)) end end @@ -426,7 +481,8 @@ local function mvSplit(d: number, q: boolean): (number, number) return a, b end --- reconstruct one coded fragment into dst (the SELF reference planes) +-- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the +-- reference block or the average of two for inter ones) goes to dst first, then the residual is added local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) local pli = st.fpl[fi] local mode = st.fmode[fi] @@ -435,12 +491,20 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) local dc = st.dcv[fi] local last = st.last[fi] - local res = st.res - local flat = false + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] local fv = 0 if last == 0 then - flat = true fv = wrap16((dc * dcq + 15) // 32) + if ri == SELF then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + return + end else local blk = st.blk bfill(blk, 0, 0, 128) @@ -456,50 +520,44 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu end end st.last[fi] = 0 - idct(blk, st.tmp, res) + idctRows(blk, st.tmp) end - local stride = st.stride[pli + 1] - local dst = dstPlanes[pli + 1] - local pos = st.fpos[fi] - local ri = st.refi[fi] + -- the prediction if ri == SELF then - if flat then - local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, 128, 8) + end + else + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local mx, mx2 = mvSplit(st.mvx[fi], pli > 0 and st.hdec == 1) + local my, my2 = mvSplit(st.mvy[fi], pli > 0 and st.vdec == 1) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + -- (a + b) >> 1 per byte, four at a time + local s2 = s1 + my2 * stride + mx2 for y = 0, 7 do - bfill(dst, pos + y * stride, v, 8) + local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride + local u, v = readu32(ref, a), readu32(ref, b) + writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + u, v = readu32(ref, a + 4), readu32(ref, b + 4) + writeu32(dst, d + 4, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) end else for y = 0, 7 do - local d, s = pos + y * stride, y * 32 - for x = 0, 7 do - writeu8(dst, d + x, readu8(CLAMP, readi32(res, s + x * 4) + 128 + COFF)) - end + local d, a = pos + y * stride, s1 + y * stride + writeu32(dst, d, readu32(ref, a)) + writeu32(dst, d + 4, readu32(ref, a + 4)) end end - return end - local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] - local qx = pli > 0 and st.hdec == 1 - local qy = pli > 0 and st.vdec == 1 - local mx, mx2 = mvSplit(st.mvx[fi], qx) - local my, my2 = mvSplit(st.mvy[fi], qy) - local s1 = pos + my * stride + mx - if mx2 ~= 0 or my2 ~= 0 then - local s2 = s1 + my2 * stride + mx2 + -- the residual + if last ~= 0 then + idctAdd(st.tmp, dst, pos, stride) + elseif fv ~= 0 then for y = 0, 7 do - local d, a, b, r = pos + y * stride, s1 + y * stride, s2 + y * stride, y * 32 - for x = 0, 7 do - local p = (readu8(ref, a + x) + readu8(ref, b + x)) // 2 - local v = if flat then fv else readi32(res, r + x * 4) - writeu8(dst, d + x, readu8(CLAMP, p + v + COFF)) - end - end - else - for y = 0, 7 do - local d, a, r = pos + y * stride, s1 + y * stride, y * 32 - for x = 0, 7 do - local v = if flat then fv else readi32(res, r + x * 4) - writeu8(dst, d + x, readu8(CLAMP, readu8(ref, a + x) + v + COFF)) + local d = pos + y * stride + for x = d, d + 7 do + writeu8(dst, x, readu8(CLAMP, readu8(dst, x) + fv + COFF)) end end end @@ -593,6 +651,88 @@ local function borders(st: State, planes: { buffer }) end end +-- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours +-- coded from the same reference frame (or the last such DC in the plane) +local function dcPredict(st: State) + local coded, refi, dcv = st.coded, st.refi, st.dcv + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end +end + -- ------------------------------------------------------------------------------------------------ frame decode -- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in -- st.refs[st.shown]. @@ -609,31 +749,11 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, if pos > maxp then pos = maxp end - local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + local w = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - n) pos += n return w end local huff = st.huff - local function token(root: number): number - if pos > maxp then - pos = maxp - end - local o = root - while true do - local n = huff[o] - local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) - local e = huff[o + 1 + w] - if e >= 0 then - pos += e // 64 - return e % 64 - end - pos += n - o = -e - if pos > maxp then - pos = maxp - end - end - end local function sbRun(): number if bits(1) == 0 then return 1 @@ -1028,9 +1148,28 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, eobs -= 1 t = 64 else - local tok = token(root) - local ex = TOKEN_EXTRA[tok] - local eb = if ex > 0 then bits(ex) else 0 + -- the token (inlined: the hottest loop), then its extra bits + if pos > maxp then + pos = maxp + end + local o, tok = root, 0 + while true do + local nb = huff[o] + local e = huff[o + 1 + rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - nb)] + if e >= 0 then + pos += rshift(e, 6) + tok = band(e, 63) + break + end + pos += nb + o = -e + end + local ex = TOKEN_EXTRA[tok + 1] + local eb = 0 + if ex > 0 then + eb = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - ex) + pos += ex + end if tok < 7 then local run: number if tok < 3 then @@ -1046,49 +1185,18 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, end eobs = run - 1 t = 64 - elseif tok < 9 then - t = zzi + eb + 1 else - local v, r = 0, 0 - if tok < 13 then - v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 - elseif tok < 17 then - v = if eb == 1 then -(tok - 10) else tok - 10 - elseif tok < 23 then - local half = 2 ^ (ex - 1) - local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 - v = base + eb % half - if eb >= half then - v = -v + -- zero runs and coefficients: run * 4096 + value + 2048 (value 0: a zero run) + local e = TOKEN_VALUE[tok * 1024 + eb + 1] + local p = zzi + rshift(e, 12) + local v = band(e, 4095) - 2048 + if v ~= 0 then + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p end - elseif tok < 28 then - r = tok - 22 - v = if eb == 1 then -1 else 1 - elseif tok == 28 then - r = 6 + eb % 4 - v = if eb >= 4 then -1 else 1 - elseif tok == 29 then - r = 10 + eb % 8 - v = if eb >= 8 then -1 else 1 - elseif tok == 30 then - r = 1 - v = 2 + eb % 2 - if eb >= 2 then - v = -v - end - else - r = 2 + eb % 2 - v = 2 + (eb // 2) % 2 - if eb >= 4 then - v = -v - end - end - local p = zzi + r - if p == 0 then - dcv[fi] = v - elseif p < 64 then - writei16(coef, (fi - 1) * 128 + p * 2, v) - last[fi] = p end t = p + 1 end @@ -1104,83 +1212,7 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, end end - -- DC prediction (raster order per plane) - for pli = 0, 2 do - local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] - local base = st.foff[pli + 1] - local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) - for fy = 0, nv - 1 do - local row = base + fy * nh - local lref, ulref, uref = -1, -1, -1 - if fy > 0 then - uref = refi[row - nh + 1] - end - for fx = 0, nh - 1 do - local fi = row + fx + 1 - local urref = -1 - if fy > 0 and fx + 1 < nh then - urref = refi[fi - nh + 1] - end - if coded[fi] ~= 0 then - local r = refi[fi] - local pred: number - if fy == 0 then - pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 - else - local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) - if m == 0 then - pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 - elseif m == 1 or m == 3 then - pred = dcv[fi - 1] - elseif m == 2 then - pred = dcv[fi - nh - 1] - elseif m == 4 or m == 6 or m == 12 then - pred = dcv[fi - nh] - elseif m == 5 then - local s = dcv[fi - 1] + dcv[fi - nh] - pred = if s < 0 then -((-s) // 2) else s // 2 - elseif m == 8 then - pred = dcv[fi - nh + 1] - elseif m == 9 or m == 11 or m == 13 then - local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] - pred = if s < 0 then -((-s) // 128) else s // 128 - elseif m == 10 then - local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] - pred = if s < 0 then -((-s) // 2) else s // 2 - elseif m == 14 then - local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] - pred = if s < 0 then -((-s) // 16) else s // 16 - else - local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] - local s = 29 * (p0 + p2) - 26 * p1 - pred = if s < 0 then -((-s) // 32) else s // 32 - if math.abs(pred - p2) > 128 then - pred = p2 - elseif math.abs(pred - p0) > 128 then - pred = p0 - elseif math.abs(pred - p1) > 128 then - pred = p1 - end - end - end - local v = wrap16(dcv[fi] + pred) - dcv[fi] = v - if r == 0 then - pl0 = v - elseif r == 1 then - pl1 = v - else - pl2 = v - end - lref = r - else - lref = -1 - end - ulref = uref - uref = urref - end - end - end + dcPredict(st) -- reconstruction into a free reference buffer local self = 1 diff --git a/src/Formats/codecs/video/Theora/Header.luau b/src/Formats/codecs/video/Theora/Header.luau index 2d88abd..2259c19 100644 --- a/src/Formats/codecs/video/Theora/Header.luau +++ b/src/Formats/codecs/video/Theora/Header.luau @@ -226,7 +226,7 @@ local function buildTable(out: { number }, kid0: { number }, kid1: { number }, t for i = 0, size - 1 do local cur, d = n, 0 while d < nb and tok[cur] < 0 do - local bit = (i // 2 ^ (nb - 1 - d)) % 2 + local bit = bit32.extract(i, nb - 1 - d, 1) local nx = if bit == 0 then kid0[cur] else kid1[cur] d += 1 cur = nx diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..afd0966 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,42 @@ do jitTune(false) end end +do + -- ------------------------------------------------------------------------------------- ws-video2-theora: fps + -- Theora (codecs/video/Theora): 320x240 clips, 50 frames, keyframe every 25: testsrc2 at 600 kbit/s (mostly static: + -- few coded blocks) and a mandelbrot zoom at 1200 kbit/s (every block coded, moving); decode alone and decode + + -- image() (the yuv420p copy every VideoDecoder frame makes) + local Theora = require("@formats/codecs/video/Theora") + local Ogg = require("@formats/containers/Ogg") + local Base64 = require("@formats/core/Base64") + local TB = require("@tests/gen/theora_bench") + local function run(tag: string) + for _, c in TB do + local d = Ogg.open(Base64.decode(c.file) :: buffer) + local hdrs, data = {}, {} + for p in d:packets(d:find("theora")) do + table.insert(if #hdrs < 3 then hdrs else data, Ogg.copy(p)) + end + for _, image in { false, true } do + local n = c.width * c.height * 3 // 2 * #data + local dt = bench(string.format("theora %s %dx%d%s%s", c.name, c.width, c.height, if image then " +img" else "", tag), 3, n, function() + local dec = Theora.new(hdrs) :: any + for _, p in data do + dec:decode(p) + if image then + dec:image() + end + end + end) + print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #data .. " frames)", #data / dt)) + end + end + end + jitTune(false) + run("") + if runtime == "luajit" then + jitTune(true) + run(" (jit tuned)") + jitTune(false) + end +end diff --git a/tools/fixtures/docs_theora.py b/tools/fixtures/docs_theora.py new file mode 100644 index 0000000..1b85b57 --- /dev/null +++ b/tools/fixtures/docs_theora.py @@ -0,0 +1,20 @@ +# Docs inputs for the Ogg Theora section of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): a +# tiny ffmpeg clip (testsrc 64x48, 10 frames at 10 fps, libtheora + a libvorbis sine track) as Ogg video. +# tests/gen/docs_theora.luau { files = { ["clip.ogv"] = bytes }, vars = { ogvBytes = "clip.ogv" } } +import importlib.util, os, shutil, subprocess, tempfile + +INPUTS = ["tools/docs_check.py"] + + +def generate(ctx): + spec = importlib.util.spec_from_file_location("docs_theora_check", os.path.join(ctx.root, "tools", "docs_check.py")) + dc = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dc) + ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip() + with tempfile.TemporaryDirectory() as d: + out = os.path.join(d, "clip.ogv") + subprocess.run([ffmpeg, "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libtheora", + "-q:v", "6", "-g", "5", "-c:a", "libvorbis", "-q:a", "2", out], check=True, capture_output=True) + files = {"clip.ogv": open(out, "rb").read()} + dc.emit_inputs(ctx, files, {"ogvBytes": "clip.ogv"}) diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py index 7d05299..6bcfd6a 100644 --- a/tools/fixtures/theora.py +++ b/tools/fixtures/theora.py @@ -10,7 +10,7 @@ # rate, channels } # tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio # tests/gen/theora_mkv.luau { file (base64 .mkv), frames } -# tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } for tools/bench.luau +# tests/gen/theora_bench.luau { { name, file (base64 .ogv, 320x240), width, height } } for tools/bench.luau import base64, os, shutil, struct, subprocess, tempfile, zlib FF = ["-hide_banner", "-loglevel", "error", "-y"] @@ -199,7 +199,10 @@ def generate(ctx): ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv]) ctx.emit("theora_mkv", {"file": b64(open(mkv, "rb").read()), "frames": framecrc(mkv, "yuv420p"), "width": 174, "height": 98}) - # the bench stream - bench = os.path.join(tmp, "bench.ogv") - ff(src("testsrc2", 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", "600k", "-g", "25", bench]) - ctx.emit("theora_bench", {"file": b64(open(bench, "rb").read()), "width": 320, "height": 240}) + # the bench streams: an easy clip (testsrc2, mostly static) and a hard one (a mandelbrot zoom: every block moves) + bench = [] + for kind, rate in (("testsrc2", "600k"), ("mandelbrot", "1200k")): + path = os.path.join(tmp, "bench_" + kind + ".ogv") + ff(src(kind, 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", rate, "-g", "25", path]) + bench.append({"name": kind, "file": b64(open(path, "rb").read()), "width": 320, "height": 240}) + ctx.emit("theora_bench", bench) From 3e336392728f51f6bd0856697405e648b4a3867b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:48 -0500 Subject: [PATCH 14/19] docs: legacy video (guide section, formats table rows, docs/video.md layers row); docs_legacy inputs --- docs/guide/video.md | 71 +++++++++++++++++++++++++++++++++++ docs/video.md | 1 + tools/fixtures/docs_legacy.py | 33 ++++++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 tools/fixtures/docs_legacy.py diff --git a/docs/guide/video.md b/docs/guide/video.md index 99e0395..28e87c7 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -288,6 +288,77 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`. + +| fli / flc / flx | yes | - | FLIC (8-bit palettised, 15 / 16 / 24-bit) | +| smk | yes | - | Smacker video (SMK2 / SMK4) + Smacker audio / PCM | + +AVI, MOV / MP4 and MKV (V_MS/VFW/FOURCC, V_QUICKTIME) also decode the legacy codecs: Cinepak, Microsoft Video 1, +QuickTime Animation (RLE) and QuickTime Graphics (SMC). See [Legacy video](#legacy-video). + + +## Legacy video + +The 1990s formats and codecs decode to **rgba8** frames (they are palettised or RGB, not YUV), each frame painted +over the previous one, as the codecs define. Decoding is bit-exact with ffmpeg's. + +| Codec id | Name | Containers | Depths | +|---|---|---|---| +| `flic` | Autodesk FLI / FLC | fli | 8-bit palettised, 15 / 16 / 24-bit | +| `smackvid` | Smacker video | smk | 8-bit palettised | +| `cinepak` | Cinepak (`cvid`) | avi, mov, mkv | 24-bit, grey, 8-bit palettised | +| `msvideo1` | Microsoft Video 1 (`CRAM`, `MSVC`, `WHAM`) | avi, mov, mkv | 16-bit (5-5-5), 8-bit palettised | +| `qtrle` | QuickTime Animation (`rle `) | mov, mkv | 1, 2, 4, 8 (palettised or grey), 16, 24, 32 (alpha) | +| `smc` | QuickTime Graphics (`smc `) | mov, mkv | 8-bit palettised | + +Palettes come from the container: `track.palette` (256 entries, 4 bytes each: R, G, B, A) holds the AVI +BITMAPINFO palette or the QuickTime colour table (or the Macintosh default table it refers to); FLIC and Smacker +frames carry their own palette changes. + +```luau +local v = assert(F.video.open(cinepakBytes)) -- Cinepak in a QuickTime movie +assert(v.format == "mov" and v.codec == "cinepak") +local frames = 0 +while true do + local f = v:nextFrame() + if not f then break end + assert(f.image.format == "rgba8" and f.image.width == 64) + frames += 1 +end +assert(frames == v.frames) +``` + +FLIC files (`.fli` at 70 Hz ticks, `.flc` / `.flx` in milliseconds) open as videos; the ring frame (an extra frame +leading back to the first, for looping) is not shown unless you ask for it. + +```luau +local v = assert(F.video.open(flcBytes)) +print(v.format, v.codec, v.width, v.height, v.frameRate) -- fli flic 64 48 10 +assert(v.track.bitsPerPixel == 8 and v.frames == 10) +local f = assert(v:nextFrame()) +local r, g, b, a = F.ops.image.getPixel(f.image, 0, 0) -- palette colours, opaque +assert(r and g and b and a == 255) +local all = assert(F.format("fli").open(F.Bytes.reader(flcBytes), { ringFrame = true })) +assert(all.codec == "flic") +``` + +Smacker files carry up to seven audio tracks. The format decodes Smacker's packed audio (and raw PCM tracks) itself: +`v.audio` is the first track, `F.format("smk").openAudio(demuxer, track)` opens any of them. + +```luau +local v = assert(F.video.open(smkBytes)) +assert(v.format == "smk" and v.codec == "smackvid") +local a = assert(v.audio, tostring(v.audioError)) -- packed 16-bit stereo, 22050 Hz +assert(a.sampleRate == 22050 and a.channels == 2) +local Smk = F.format("smk") +for _, t in v.demuxer.tracks do + if t.kind == "audio" then + local dec = assert(Smk.openAudio(v.demuxer, t)) -- smackaudio, pcm_u8 or pcm_s16le + local pcm, n = dec:read(1000) + assert(n == 1000 and buffer.len(pcm) == n * dec.channels * 4) + end +end +``` + ## Gotchas - Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with `tools/bench.luau` diff --git a/docs/video.md b/docs/video.md index 184ca45..f2469d6 100644 --- a/docs/video.md +++ b/docs/video.md @@ -28,6 +28,7 @@ F.convert(gif, "avi") -- animated images become videos (un | `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | | `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | | `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `codecs/video/Legacy` | FLIC, Smacker, Cinepak, Microsoft Video 1, QuickTime RLE / SMC: rgba8, palettes from `track.palette` | | `video/` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires diff --git a/tools/fixtures/docs_legacy.py b/tools/fixtures/docs_legacy.py new file mode 100644 index 0000000..719f8fd --- /dev/null +++ b/tools/fixtures/docs_legacy.py @@ -0,0 +1,33 @@ +# Docs inputs for the legacy video sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): +# a 64x48 FLC (tools/fixtures/fli.py's encoder), a 64x48 SMK4 with a packed stereo and a raw mono audio track +# (tools/fixtures/smk.py's encoder) and a 64x48 Cinepak MOV from ffmpeg. +# tests/gen/docs_legacy.luau { files = { [name] = bytes }, vars = { flcBytes = "anim.flc", ... } } +import importlib.util, os, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/fli.py", "tools/fixtures/smk.py", "tools/fixtures/_video.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_legacy_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + dc = load(ctx, "docs_check") + fli = load(ctx, "fixtures/fli") + smk = load(ctx, "fixtures/smk") + v = load(ctx, "fixtures/_video") + files = {} + w, h, n = 64, 48, 10 + imgs = fli.idx_frames(w, h, n, 256, 5) + frames = [fli.frame([fli.color([(0, fli.pal(256, 5, False))], False), fli.brun([[bytes([x]) for x in r] for r in imgs[0]], 1, True)])] + frames += [fli.frame([fli.ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)] + files["anim.flc"] = fli.file(0xAF12, w, h, 8, 100, frames) + files["intro.smk"] = smk.smk_file(4, 64, 48, 10, 100, [("packed", 22050, 2, 16), ("raw", 11025, 1, 8)], False, 7) + with tempfile.TemporaryDirectory() as d: + out = os.path.join(d, "cinepak.mov") + v.ffmpeg(["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "cinepak", out]) + files["cinepak.mov"] = open(out, "rb").read() + dc.emit_inputs(ctx, files, {"flcBytes": "anim.flc", "smkBytes": "intro.smk", "cinepakBytes": "cinepak.mov"}) From d22c72c1bc967dc4ff2a0628e50c4298e40e91dd Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:50:27 -0500 Subject: [PATCH 15/19] ws-video2: MPEG-2 field-picture / concealment-vector fixtures (a syntax-level writer in tools/fixtures/mpeg2.py), bit-exact; LuaJIT-friendlier hot paths; mpeg2 bench line --- src/Formats/codecs/video/Mpeg2/Decoder.luau | 67 ++++-- tests/codecs/mpeg2.luau | 4 +- tools/bench.luau | 17 ++ tools/fixtures/mpeg2.py | 252 +++++++++++++++++++- 4 files changed, 322 insertions(+), 18 deletions(-) diff --git a/src/Formats/codecs/video/Mpeg2/Decoder.luau b/src/Formats/codecs/video/Mpeg2/Decoder.luau index 4cd982c..e25801d 100644 --- a/src/Formats/codecs/video/Mpeg2/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg2/Decoder.luau @@ -31,6 +31,7 @@ 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 @@ -549,12 +550,18 @@ function D.new(maxPixels: number?): Core 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 mx = mvx // 2 + if mvx < 0 then + mx = -((-mvx) // 2) + end local cx, cy, chh, cph, chx, chy chx = band(mx, 1) cx = mbCol * 8 + (mx - chx) // 2 if chroma == 1 then - local my = if mvy < 0 then -((-mvy) // 2) else mvy // 2 + local my = mvy // 2 + if mvy < 0 then + my = -((-mvy) // 2) + end chy = band(my, 1) cy = rowY // 2 + (my - chy) // 2 chh, cph = h // 2, ph // 2 @@ -563,7 +570,11 @@ function D.new(maxPixels: number?): Core cy = rowY + (mvy - chy) // 2 chh, cph = h, ph end - local cdOff = cdb + (if chroma == 1 then rowY // 2 else rowY) * cs + mbCol * 8 + local crow = rowY + if chroma == 1 then + crow = rowY // 2 + end + local cdOff = cdb + crow * cs + mbCol * 8 if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) @@ -592,8 +603,15 @@ function D.new(maxPixels: number?): Core 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 + local r = bwS + if d == 0 then + r = fwS + end + if r == nil then + r = cur + end + local ref = r :: Store + local ry, rcb, rcr = ref.y, ref.cb, ref.cr if motionType == 1 then mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) elseif motionType == 2 then @@ -736,7 +754,10 @@ function D.new(maxPixels: number?): Core dc = dcY else size = vlc(DC_CHROMA, DC_CHROMA_BITS) - dc = if b % 2 == 0 then dcCb else dcCr + dc = dcCr + if b % 2 == 0 then + dc = dcCb + end end if size > 0 then local diff = read(size) @@ -761,14 +782,24 @@ function D.new(maxPixels: number?): Core 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 + parityOdd = bxor(1, band(v, 1)) + q = chromaIntraQ + if luma then + q = intraQ + end n = 1 else - q = if luma then nonIntraQ else chromaNonIntraQ + q = chromaNonIntraQ + if luma then + q = nonIntraQ + end + end + local lut, nextLut = DCT_NEXT, DCT_NEXT + if mbIntra and intraVlc then + lut, nextLut = DCT_B15, DCT_B15 + elseif n == 0 then + lut = DCT_FIRST end - local 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 @@ -853,7 +884,9 @@ function D.new(maxPixels: number?): Core if neg then m = -m end - parityOdd = bit32.bxor(parityOdd, band(m, 1)) + if m2 then + parityOdd = bxor(parityOdd, band(m, 1)) + end -- saturate if m > 2047 then m = 2047 @@ -887,7 +920,10 @@ function D.new(maxPixels: number?): Core 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 + dst = curCr + if b % 2 == 0 then + dst = curCb + end local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock if chroma == 1 then stride = cstride @@ -923,7 +959,10 @@ function D.new(maxPixels: number?): Core -- 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 fh, fv = fc10, fc11 + if d == 0 then + fh, fv = fc00, fc01 + end local o, p, f = d * 8, d * 4, d * 2 if motionType == 1 and not fieldPic then local x = decodeMotion(fh, PMV[p + 1]) diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau index fb3da3f..cd88a82 100644 --- a/tests/codecs/mpeg2.luau +++ b/tests/codecs/mpeg2.luau @@ -1,7 +1,7 @@ -- 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 +-- size, B-frames, dual prime, field pictures, concealment vectors) 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. @@ -24,6 +24,8 @@ local STREAMS = { require("@tests/gen/mpeg2_c422"), require("@tests/gen/mpeg2_c422_ilace"), require("@tests/gen/mpeg2_dualprime"), + require("@tests/gen/mpeg2_fields"), + require("@tests/gen/mpeg2_fields_conceal"), } local t = T.suite("codecs/mpeg2") diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..4712a7c 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -964,11 +964,28 @@ do end end end + -- MPEG-2: 720x576 interlaced (field prediction / field DCT, B-frames), as on a DVD (ws-video2) + local M2 = require("@tests/gen/mpeg2_bench") + local function mpeg2(tag: string) + for _, s in M2 do + local file = Base64.decode(s.file) :: buffer + fps(string.format("mpeg2 decode yuv %dx%d interlaced%s", s.width, s.height, tag), 3, #s.units, function() + local dec = Mpeg1.new({ reorder = true, rgba = false }) + for i, u in s.units do + dec:decode(file, u[1], u[2], i) + end + while dec:flush() do + end + end) + end + end jitTune(false) mpeg1("") + mpeg2("") if runtime == "luajit" then jitTune(true) mpeg1(" (jit tuned)") + mpeg2(" (jit tuned)") jitTune(false) end end diff --git a/tools/fixtures/mpeg2.py b/tools/fixtures/mpeg2.py index b9e1f00..17a931b 100644 --- a/tools/fixtures/mpeg2.py +++ b/tools/fixtures/mpeg2.py @@ -1,9 +1,11 @@ # 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. +# chroma matrices, large motion (f_code > 1), odd sizes, B-frames), from mjpegtools' mpeg2enc (dual-prime +# prediction in interlaced frame pictures) and from field_stream below (field pictures: I / P / B fields, the second +# field predicted from the first, field / 16x8 / dual-prime prediction, skipped macroblocks; concealment vectors), +# 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 @@ -126,6 +128,14 @@ def generate(ctx): % (dp, y4m)]) emit("dualprime", open(dp, "rb").read(), dp, 1) + # field pictures and concealment vectors (field_stream below: no encoder at hand writes them) + seq = [("I", "P"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B")] + for name, seed, dims, conceal in (("fields", 5, (320, 240), False), ("fields_conceal", 6, (176, 144), True)): + path = os.path.join(tmp, name + ".m2v") + es = field_stream(ctx.rng(seed), dims[0], dims[1], seq, conceal) + open(path, "wb").write(es) + emit(name, es, path, 1) + # the prog stream in the containers (stream copy) prog = os.path.join(tmp, "prog.m2v") cont = {"crcs": crcs["prog"]} @@ -176,3 +186,239 @@ def zlib_crc32_mpeg(data): for _ in range(8): crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF return crc + + +# --------------------------------------------------------------------------------------------------------------------- +# A syntax-level MPEG-2 writer for what no encoder at hand produces: field pictures (I + P fields, the P field +# predicted from the first field of its own frame, P / B field pictures, field and 16x8 prediction, dual prime in +# field pictures, skipped macroblocks) and concealment motion vectors. The content is random (DC levels, sparse +# escape-coded coefficients, motion vectors kept inside the picture): any valid stream will do, ffmpeg's decode is +# the reference. The tables are those of ISO/IEC 13818-2 annex B (only the entries used here). +MBAI = {1: "1", 2: "011", 3: "010"} +DC_LUMA = ["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"] +DC_CHROMA = ["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"] +# |motion_code| 0..16 (Table B-10), then the sign bit +MOTION = ["1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", "000001001", + "0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100"] +CBP = {60: "111", 4: "1101", 8: "1100", 16: "1011", 32: "1010"} +MBTYPE_P = {"mc_coded": "1", "nomc_coded": "01", "mc": "001", "intra": "00011"} +MBTYPE_B = {"interp": "10", "interp_coded": "11", "bwd": "010", "bwd_coded": "011", "fwd": "0010", "fwd_coded": "0011", + "intra": "00011"} + + +class Bits: + def __init__(self): + self.s = [] + + def put(self, v, n): + self.s.append(format(v & ((1 << n) - 1), "0%db" % n) if n else "") + + def code(self, c): + self.s.append(c) + + def start(self, code): + # next_start_code: zero stuffing to a byte boundary, then 00 00 01 code + n = len("".join(self.s)) + if n % 8: + self.s.append("0" * (8 - n % 8)) + self.put(0x000001, 24) + self.put(code, 8) + + def bytes(self): + s = "".join(self.s) + s += "0" * (-len(s) % 8) + return bytes(int(s[i:i + 8], 2) for i in range(0, len(s), 8)) + + +def field_stream(rng, w, h, frames, conceal=False): + """frames: [(picture type per field, ...)] in decode order, e.g. [("I", "P"), ("P", "P"), ("B", "B")]""" + b = Bits() + mbw, mbh = (w + 15) // 16, 2 * ((h + 31) // 32) + fh = mbh * 8 # field height in lines (coded) + b.start(0xB3) + b.put(w, 12), b.put(h, 12), b.put(1, 4), b.put(3, 4), b.put(5000, 18), b.put(1, 1), b.put(112, 10), b.put(0, 1) + b.put(0, 1), b.put(0, 1) + b.start(0xB5) + b.put(1, 4), b.put(0x48, 8), b.put(0, 1), b.put(1, 2), b.put(0, 2), b.put(0, 2), b.put(0, 12), b.put(1, 1) + b.put(0, 8), b.put(0, 1), b.put(0, 2), b.put(0, 5) + b.start(0xB8) + b.put(0, 25), b.put(1, 1), b.put(0, 1) + # temporal references: decode order I P B P B ... is display order I B P B P (each B before the reference decoded + # just before it) + tr, d, last_ref = {}, 0, None + for k, f in enumerate(frames): + if f[0] != "B": + if last_ref is not None: + tr[last_ref] = d + d += 1 + last_ref = k + else: + tr[k] = d + d += 1 + tr[last_ref] = d + for k, (t0, t1) in enumerate(frames): + for fi, ptype in enumerate((t0, t1)): + parity = fi # top field first + pt = {"I": 1, "P": 2, "B": 3}[ptype] + b.start(0x00) + b.put(tr[k], 10), b.put(pt, 3), b.put(0xFFFF, 16) + if pt >= 2: + b.put(0, 1), b.put(7, 3) + if pt == 3: + b.put(0, 1), b.put(7, 3) + b.put(0, 1) + b.start(0xB5) + fc = (1, 1, 15, 15) if pt == 2 else (1, 1, 1, 1) if pt == 3 else (15, 15, 15, 15) + if pt == 1 and conceal: + fc = (1, 1, 15, 15) + b.put(8, 4) + for f in fc: + b.put(f, 4) + b.put(0, 2), b.put(1 + parity, 2), b.put(0, 1), b.put(0, 1), b.put(1 if conceal else 0, 1), b.put(0, 1) + b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1) + # the second field of the first frame has one reference: the first field (no skips, zero-vector or + # dual-prime prediction from its own parity) + only_first = k == 0 and fi == 1 + for row in range(mbh // 2): + b.start(row + 1) + b.put(rng.choice((2, 4, 8)), 5), b.put(0, 1) + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] # [dir][r * 2 + c] + dc = [128, 128, 128] + col = 0 + prev_dirs = None + while col < mbw: + # B skips repeat the previous vectors: only after zero ones (they stay inside the picture) + skip = (pt != 1 and not only_first and col > 0 and col < mbw - 1 and rng.random() < 0.15 and + prev_dirs is not None and (pt == 2 or not any(pmv[0] + pmv[1]))) + if skip: + b.code(MBAI[2]) + col += 1 # the skipped one + dc = [128, 128, 128] + if pt == 2: + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] + else: + b.code(MBAI[1]) + if pt == 1 or rng.random() < 0.08: + b.code("1" if pt == 1 else (MBTYPE_P if pt == 2 else MBTYPE_B)["intra"]) + if conceal: + # field_select, a concealment vector (the predictor again: motion codes 0), marker + b.put(0, 1), b.code(MOTION[0]), b.code(MOTION[0]), b.put(1, 1) + pmv[0][2:] = pmv[0][:2] + else: + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] + for blk in range(6): + comp = 0 if blk < 4 else blk - 3 + target = rng.randrange(40, 216) + diff = target - dc[comp] + dc[comp] = target + size = abs(diff).bit_length() + b.code((DC_LUMA if comp == 0 else DC_CHROMA)[size]) + if size: + b.put(diff if diff > 0 else diff + (1 << size) - 1, size) + ac_block(b, rng, 1, 0.5) + prev_dirs = None + col += 1 + continue + dc = [128, 128, 128] + if pt == 2: + kind = rng.choice(("mc", "mc_coded", "mc_coded", "mc") if only_first else + ("mc", "mc_coded", "mc_coded", "nomc_coded", "mc")) + dirs = (0,) if kind != "nomc_coded" else () + b.code(MBTYPE_P[kind]) + coded = kind != "mc" + else: + kind = rng.choice(("interp", "interp_coded", "bwd", "bwd_coded", "fwd", "fwd_coded")) + dirs = (0, 1) if kind.startswith("interp") else (1,) if kind.startswith("bwd") else (0,) + b.code(MBTYPE_B[kind]) + coded = kind.endswith("coded") + if dirs: + choices = ["field", "16x8"] + (["dmv"] if pt == 2 and not only_first else []) + mt = rng.choice(choices) + b.put({"field": 1, "16x8": 2, "dmv": 3}[mt], 2) + for d in dirs: + motion(b, rng, pmv[d], mt, col, row, mbw, fh, parity, 0 if only_first else None) + else: + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] + if coded: + cbp = rng.choice(list(CBP)) + b.code(CBP[cbp]) + for blk in range(6): + if cbp & (32 >> blk): + ac_block(b, rng, 0, 0.6) + prev_dirs = dirs + col += 1 + b.start(0xB7) + return b.bytes() + + +def ac_block(b, rng, first, more): + # escape-coded coefficients (6-bit run, 12-bit level), then end_of_block ("10"); a non-intra block needs one + n = first + count = 0 + while n < 64 and (count == 0 and first == 0 or rng.random() < more): + run = rng.randrange(0, 6) + if n + run > 63: + break + level = rng.choice((-1, 1)) * rng.randrange(1, 24) + b.code("000001"), b.put(run, 6), b.put(level, 12) + n += run + 1 + count += 1 + b.code("10") + + +def put_motion(b, delta): + b.code(MOTION[abs(delta)]) + if delta: + b.put(1 if delta < 0 else 0, 1) + + +def wrap(v): + return (v + 16) % 32 - 16 + + +def motion(b, rng, pmv, mt, col, row, mbw, fh, parity, force_sel): + """one direction's vectors for a field-picture macroblock, kept inside the reference field""" + def ok(mx, my, rows, y0): + sx, sy = col * 16 + (mx >> 1), y0 + (my >> 1) + return sx >= 0 and sx + 16 + (mx & 1) <= mbw * 16 and sy >= 0 and sy + rows + (my & 1) <= fh + + def pick(px, py, rows, y0, extra=None): + for _ in range(50): + mx, my = rng.randrange(-12, 13), rng.randrange(-10, 11) + dx, dy = wrap(mx - px), wrap(my - py) + if ok(mx, my, rows, y0) and (extra is None or extra(mx, my)): + return dx, dy, mx, my + return None + + if mt == "field": + sel = rng.randrange(2) if force_sel is None else force_sel + r = pick(pmv[0], pmv[1], 16, row * 16) or (wrap(-pmv[0]), wrap(-pmv[1]), 0, 0) + b.put(sel, 1) + put_motion(b, r[0]), put_motion(b, r[1]) + mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1]) + pmv[:] = [mx, my, mx, my] + elif mt == "16x8": + for half in range(2): + sel = rng.randrange(2) if force_sel is None else force_sel + px, py = pmv[half * 2], pmv[half * 2 + 1] + r = pick(px, py, 8, row * 16 + half * 8) or (wrap(-px), wrap(-py), 0, 0) + b.put(sel, 1) + put_motion(b, r[0]), put_motion(b, r[1]) + pmv[half * 2], pmv[half * 2 + 1] = wrap(px + r[0]), wrap(py + r[1]) + else: + # dual prime: the vector, its differential (0, +1, -1) and the derived opposite-parity vector + def dmv_ok(dmx, dmy): + def f(mx, my): + ox = ((mx + (mx > 0)) >> 1) + dmx + oy = ((my + (my > 0)) >> 1) + dmy + (-1 if parity == 0 else 1) + return ok(ox, oy, 16, row * 16) + return f + for dmx, dmy in rng.sample([(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1)], 7): + r = pick(pmv[0], pmv[1], 16, row * 16, dmv_ok(dmx, dmy)) + if r: + break + assert r, "dual prime: no vector fits" + put_motion(b, r[0]), b.code({0: "0", 1: "10", -1: "11"}[dmx]) + put_motion(b, r[1]), b.code({0: "0", 1: "10", -1: "11"}[dmy]) + mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1]) + pmv[:] = [mx, my, mx, my] From 6e0b80a7f2078685e0e64466659799b203e75451 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:51:14 -0500 Subject: [PATCH 16/19] ws-video2: MpegEs Picture type annotation (type baseline) --- src/Formats/containers/MpegEs.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Formats/containers/MpegEs.luau b/src/Formats/containers/MpegEs.luau index 704db06..77be2ef 100644 --- a/src/Formats/containers/MpegEs.luau +++ b/src/Formats/containers/MpegEs.luau @@ -134,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, structure = st } + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } :: Picture unitStart, seq, gop = nil, false, false elseif code == 0xB7 and cur then cur.size = p + 4 - cur.offset From 36770d7a8bf7822e5d1c02385d6b6527edbdbbd9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:53:04 -0500 Subject: [PATCH 17/19] ws-video2: docs/guide/video.md MPEG-2 section (tested snippet, tsBytes clip), formats table; docs/video.md layers --- docs/guide/video.md | 34 +++++++++++++++++++++++++++++----- docs/video.md | 2 ++ tools/fixtures/docs_av.py | 10 +++++++--- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/docs/guide/video.md b/docs/guide/video.md index cbabe27..996da6f 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -2,7 +2,7 @@ A video file opens as a **VideoDecoder**: frames come out one at a time, as Images, with their presentation time. Underneath sits a **Demuxer**: the container's tracks and their compressed packets. Video tracks decode through a -codec registry (H.264, VP8, MPEG-1, Motion-JPEG, raw), and the first audio track opens as an audio +codec registry (H.264, VP8, MPEG-1, MPEG-2, Motion-JPEG, raw), and the first audio track opens as an audio [Decoder](audio.md#decoder). Animated GIF, APNG and WebP open as videos too. [docs/video.md](../video.md) covers the internals and how to add a codec. @@ -263,6 +263,30 @@ assert(C.register({ assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid")) ``` +## MPEG-2 (DVD, broadcast TS) + +MPEG-1 and MPEG-2 video decode through one decoder (`codecs/video/Mpeg2`; `codecs/video/Mpeg1` is the same module): +Main profile, progressive and interlaced, frame and field pictures, 4:2:0 and 4:2:2. It reads `.mpg` / `.vob` +program streams, transport streams (stream type 0x02, or a private type such as 0x80 carrying a video PES), raw +`.m2v` elementary streams, and MPEG-2 tracks of MP4 / MOV, Matroska and AVI. The output equals `ffmpeg -idct int` +sample for sample (the integer IDCT of the IJG; ffmpeg's default IDCT differs from it by at most a level or two). + +```luau +local v = assert(F.video.open(tsBytes)) -- MPEG-TS: interlaced MPEG-2 + MP2 +assert(v.format == "mpegts" and v.codec == "mpeg2") +local f = assert(v:nextFrame()) +local src = f.image.meta.source +assert(src.format == "mpeg2" and src.interlaced and src.topFieldFirst) +assert(f.image.format == "yuv420p") -- both fields woven: the top field on the even lines +local a = assert(v.audio, tostring(v.audioError)) -- the MP2 track through the audio hook +assert(a.sampleRate == 44100) +``` + +Interlaced frames come out woven, as they were coded: deinterlace them yourself if needed (`src.interlaced`, +`src.topFieldFirst`). 4:2:2 streams (studio / XDCAM) are converted to 4:2:0 for the frame Image, averaging chroma +lines of the same field. A 720x576 interlaced stream decodes at about 130 frames per second in Luau on one desktop +core (`tools/bench.luau`): real time with room to spare on a PC, less so on phones. + ## Playing in a game loop Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes @@ -306,10 +330,10 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) | Format | Read | Write | Video codecs (decode) | |---|---|---|---| -| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 | -| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | -| avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | -| mpegts, mpegps | yes | - | MPEG-1, H.264 | +| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1, MPEG-2 | +| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, MPEG-2, raw (+ H.264) | +| avi | yes | yes | MJPEG, MPEG-1, MPEG-2, raw (+ H.264) | +| mpegts, mpegps | yes | - | MPEG-1, MPEG-2, H.264 | | y4m | yes | yes | raw | | h264 (Annex B) | yes | yes (copy) | H.264 | | gif, png (APNG), webp | as video | as video via the image writers | frames | diff --git a/docs/video.md b/docs/video.md index 184ca45..8f5b6f5 100644 --- a/docs/video.md +++ b/docs/video.md @@ -28,6 +28,8 @@ F.convert(gif, "avi") -- animated images become videos (un | `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | | `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | | `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `codecs/video/Mpeg2` (`Mpeg1` is the same module), `H264` | MPEG-1 / MPEG-2 and H.264 video decoders | +| `codecs/video/Dsp` | 8x8 IDCT (bit-exact with `ffmpeg -idct int`) and half-pel motion compensation for the MPEG-style codecs | | `video/` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires diff --git a/tools/fixtures/docs_av.py b/tools/fixtures/docs_av.py index 8019408..9beb3a2 100644 --- a/tools/fixtures/docs_av.py +++ b/tools/fixtures/docs_av.py @@ -1,8 +1,8 @@ # Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them): # tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG + -# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of -# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT / -# ASS subtitles. +# PCM), WebM (VP8 + Vorbis), MPEG-TS (interlaced MPEG-2 + MP2); a MIDI file written here (SMF 1: a tempo track and a +# melody), the SoundFont of tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py +# (song_basic), and SRT / WebVTT / ASS subtitles. # tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } } import importlib.util, os, struct, tempfile @@ -91,6 +91,9 @@ def generate(ctx): "-c:a", "aac", "-b:a", "64k"]), ("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]), ("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]), + ("clip.ts", ["-c:v", "mpeg2video", "-b:v", "300k", "-g", "5", "-bf", "2", "-vf", "setfield=tff", + "-flags", "+ilme+ildct", + "-c:a", "mp2", "-b:a", "64k"]), ): out = os.path.join(d, name) ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out]) @@ -107,6 +110,7 @@ def generate(ctx): "mp4Bytes": "clip.mp4", "aviBytes": "clip.avi", "webmBytes": "clip.webm", + "tsBytes": "clip.ts", "midiBytes": "tune.mid", "sf2Bytes": "bank.sf2", "modBytes": "song.mod", From 48c0366528e67854d8b7c1e6549513f6bc5483e4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:54:03 -0500 Subject: [PATCH 18/19] ws-video2: mpeg2 test: field pictures written in random pieces --- tests/codecs/mpeg2.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau index cd88a82..b111d68 100644 --- a/tests/codecs/mpeg2.luau +++ b/tests/codecs/mpeg2.luau @@ -165,7 +165,7 @@ do end -- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit -for _, idx in { 2, 9 } do +for _, idx in { 2, 9, 12 } do local fx = STREAMS[idx] local file = b64(fx.file) local want = decodeUnits(fx, file) From 88d5fe7d2f05379a4e297fd3f36311026d145d37 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:01:19 -0500 Subject: [PATCH 19/19] ws-video2-theora: Theora MC average without type diagnostics (lint TYPES back to the baseline) --- src/Formats/codecs/video/Theora/Decoder.luau | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau index aad8f1c..d7a7afc 100644 --- a/src/Formats/codecs/video/Theora/Decoder.luau +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -537,10 +537,12 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu local s2 = s1 + my2 * stride + mx2 for y = 0, 7 do local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride - local u, v = readu32(ref, a), readu32(ref, b) + local u: number = readu32(ref, a) + local v: number = readu32(ref, b) writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) - u, v = readu32(ref, a + 4), readu32(ref, b + 4) - writeu32(dst, d + 4, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + local u2: number = readu32(ref, a + 4) + local v2: number = readu32(ref, b + 4) + writeu32(dst, d + 4, band(u2, v2) + rshift(band(bxor(u2, v2), 0xFEFEFEFE), 1)) end else for y = 0, 7 do