From 8183f4d2d7bb50d66d72fa8ab89667b127d3a2b9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:16:35 -0500 Subject: [PATCH 1/4] 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:22:39 -0500 Subject: [PATCH 2/4] 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 1013925a85fe3c3435cac17823f60a58e0907b1d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:22 -0500 Subject: [PATCH 3/4] 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 88d5fe7d2f05379a4e297fd3f36311026d145d37 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:01:19 -0500 Subject: [PATCH 4/4] 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