From 4b098276e2fa04738dca117d63e2ca991b33b96c Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:37:39 -0500 Subject: [PATCH] video/smk: Smacker (SMK2 / SMK4) with its video codec and audio containers into containers/Demux (palette updates ride on each video packet as packet.palette); the Smacker video codec (header Huffman trees with the escape cache, MONO / FULL (+ SMK4 doubled modes) / SKIP / FILL blocks) lives in codecs/video/Legacy/Smacker and registers as 'smackvid'; Smacker's packed DPCM-Huffman audio (8 / 16-bit, mono / stereo) and raw PCM tracks decode in video/smk/Audio, the Decoder built by the format over codecs/audio/Stream (Smk.openAudio; open() installs it as the openAudio hook). Fixtures encoded by tools/fixtures/smk.py: video and audio bit-exact with ffmpeg. Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Legacy/Smacker.luau | 363 ++++++++++++++ src/Formats/codecs/video/Legacy/init.luau | 33 +- src/Formats/video/smk/Audio.luau | 123 +++++ src/Formats/video/smk/init.luau | 320 ++++++++++++ tests/video/smk.luau | 180 +++++++ tools/fixtures/smk.py | 493 +++++++++++++++++++ 8 files changed, 1522 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/video/Legacy/Smacker.luau create mode 100644 src/Formats/video/smk/Audio.luau create mode 100644 src/Formats/video/smk/init.luau create mode 100644 tests/video/smk.luau create mode 100644 tools/fixtures/smk.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 13d1e91..8b27918 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -34,6 +34,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | smk | .smk | yes | - | streaming: true, video: "smackvid", audio: "smackaudio", "pcm_u8", "pcm_s16le" | `tests/video/smk.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d26e1e1..ad48ba9 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -362,6 +362,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "smk", + category = "video", + path = "video/smk", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, + load = function() + return require("@formats/video/smk") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Legacy/Smacker.luau b/src/Formats/codecs/video/Legacy/Smacker.luau new file mode 100644 index 0000000..c5923ec --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Smacker.luau @@ -0,0 +1,363 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and +-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are +-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); +-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte +-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a +-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; +-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a +-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number) walked bit by bit. +-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give +-- zero bits, a frame whose codes run out of bits gives no picture. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smacker = {} + +local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder) +local MAX_DEPTH16 = 500 + +-- block runs (TYPE code bits 2..7) +local RUNS = table.create(64, 0) +for i = 1, 59 do + RUNS[i] = i +end +RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 + +-- a bit position over buf[0, nbits / 8) +export type Bits = { buf: buffer, pos: number, nbits: number } + +function Smacker.bits(buf: buffer, offset: number, length: number): Bits + return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } +end + +local function bit(br: Bits): number + local p = br.pos + br.pos = p + 1 + if p >= br.nbits then + return 0 + end + return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1) +end +Smacker.bit = bit + +-- read(br, n) -> n bits (LSB first; zeros past the end) +function Smacker.read(br: Bits, n: number): number + local v, m = 0, 1 + for _ = 1, n do + v += bit(br) * m + m *= 2 + end + return v +end +local readBits = Smacker.read + +-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +local function walk(tree: { number }, br: Bits): number + local i = 1 + local e = tree[1] + while e < 0 do + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = tree[i] + end + return e +end +Smacker.walk = walk + +-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) +local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) + local vals: { number } = {} + local n = 0 + local stack: { number } = {} + local state: { number } = {} + local sp = 0 + while true do + if sp > maxDepth then + return nil, "tree too deep" + end + if n >= maxEntries then + return nil, "tree too big" + end + if bigChecks and br.pos >= br.nbits then + return nil, "truncated tree" + end + if bit(br) == 1 then + n += 1 + vals[n] = -1 + sp += 1 + stack[sp], state[sp] = n, 0 + else + local v, msg = leaf(n) + if not v then + return nil, msg + end + n += 1 + vals[n] = v + local more = false + while sp > 0 do + if state[sp] == 0 then + local at = stack[sp] + vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries + state[sp] = 1 + more = true + break + end + sp -= 1 + end + if not more then + return vals, nil + end + end + end +end + +-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message +function Smacker.tree8(br: Bits): ({ number }?, string?) + local leaves = 0 + return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?) + if leaves >= 256 then + return nil, "tree too big" + end + leaves += 1 + if br.nbits - br.pos < 8 then + return nil, "truncated tree" + end + return readBits(br, 8), nil + end, false) +end +local tree8 = Smacker.tree8 + +export type BigTree = { vals: { number }, last: { number } } -- last: the escape leaves' indexes (1-based) + +-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) +local function bigTree(br: Bits, size: number): (BigTree?, string?) + if bit(br) == 0 then + return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 + end + local lohi: { { number } } = {} + for k = 1, 2 do + if bit(br) == 0 then + lohi[k] = { 0 } + else + local t, msg = tree8(br) + if not t then + return nil, msg + end + bit(br) + lohi[k] = t + end + end + local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } + local last = { -1, -1, -1 } + local lo, hi = lohi[1], lohi[2] + local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, function(index: number): (number?, string?) + local v = walk(lo, br) + walk(hi, br) * 256 + for k = 1, 3 do + if v == esc[k] then + last[k] = index + 1 + return 0, nil + end + end + return v, nil + end, true) + if not vals then + return nil, msg + end + bit(br) + for k = 1, 3 do + if last[k] == -1 then + table.insert(vals, 0) + last[k] = #vals + end + end + return { vals = vals, last = last }, nil +end + +export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } + +-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +function Smacker.trees(config: buffer): (Trees?, string?) + local n = buffer.len(config) + if n <= 16 then + return nil, "no trees" + end + local br = Smacker.bits(config, 16, n - 16) + local out: { BigTree } = {} + local present = 0 + for k = 1, 4 do + local size = buffer.readu32(config, (k - 1) * 4) + if size >= 2 ^ 28 then + return nil, "tree size too large" + end + local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1 + local t, msg = bigTree(br, size) + if not t then + return nil, msg + end + if here then + present += 1 + end + out[k] = t + end + if present == 0 or br.pos > br.nbits then + return nil, "bad trees" + end + return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil +end + +-- code(tree, br) -> the next value (updating the recent-value cache) | nil when the bits run out inside the tree +local function code(t: BigTree, br: Bits): number? + local vals = t.vals + local i = 1 + local e = vals[1] + while e < 0 do + if br.pos >= br.nbits then + return nil + end + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = vals[i] + end + local last = t.last + local l0, l1, l2 = last[1], last[2], last[3] + if e ~= vals[l0] then + vals[l2] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e +end + +local function reset(t: BigTree) + local vals, last = t.vals, t.last + vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 +end + +-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 +function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) + local px = pic.idx :: buffer + local stride = pic.stride + local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type + reset(mmap) + reset(mclr) + reset(full) + reset(typ) + local br = Smacker.bits(d, 0, buffer.len(d)) + local bw, bh = pic.w // 4, pic.h // 4 + local blocks = bw * bh + local blk = 0 + while blk < blocks do + local ty = code(typ, br) + if not ty then + return false, "truncated frame" + end + local run = RUNS[band(rshift(ty, 2), 63) + 1] + local kind = band(ty, 3) + if kind == 2 then + blk = math.min(blocks, blk + run) + elseif kind == 3 then + local v = rshift(ty, 8) * 0x01010101 + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + writeu32(px, o, v) + writeu32(px, o + stride, v) + writeu32(px, o + 2 * stride, v) + writeu32(px, o + 3 * stride, v) + blk += 1 + end + elseif kind == 0 then + for _ = 1, run do + if blk >= blocks then + break + end + local clr = code(mclr, br) + local map = code(mmap, br) + if not clr or not map then + return false, "truncated frame" + end + local hi, lo = rshift(clr, 8), band(clr, 255) + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + for r = 0, 3 do + local q = o + r * stride + writeu8(px, q, if band(map, 1) ~= 0 then hi else lo) + writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo) + writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo) + writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo) + map = rshift(map, 4) + end + blk += 1 + end + else + local mode = 0 + if v4 then + if br.pos >= br.nbits then + return false, "truncated frame" + end + if bit(br) == 1 then + mode = 1 + elseif bit(br) == 1 then + mode = 2 + end + end + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + if mode == 0 then + for r = 0, 3 do + local a = code(full, br) + local b = code(full, br) + if not a or not b then + return false, "truncated frame" + end + local q = o + r * stride + writeu8(px, q + 2, band(a, 255)) + writeu8(px, q + 3, rshift(a, 8)) + writeu8(px, q, band(b, 255)) + writeu8(px, q + 1, rshift(b, 8)) + end + elseif mode == 1 then + for half = 0, 1 do + local a = code(full, br) + if not a then + return false, "truncated frame" + end + local lo, hi = band(a, 255), rshift(a, 8) + local v = lo * 0x0101 + hi * 0x01010000 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + else + for half = 0, 1 do + local p2 = code(full, br) + local p1 = code(full, br) + if not p1 or not p2 then + return false, "truncated frame" + end + local v = p1 + p2 * 65536 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + end + blk += 1 + end + end + end + return true, nil +end + +return Smacker diff --git a/src/Formats/codecs/video/Legacy/init.luau b/src/Formats/codecs/video/Legacy/init.luau index 51729a4..f73885d 100644 --- a/src/Formats/codecs/video/Legacy/init.luau +++ b/src/Formats/codecs/video/Legacy/init.luau @@ -3,7 +3,8 @@ -- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk -- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", -- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation --- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey) and QuickTime Graphics ("smc", 'smc '). +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker +-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). -- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's -- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns -- a fresh copy. @@ -13,7 +14,7 @@ -- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). -- -- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder --- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } -- -- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). local Err = require("@formats/core/Err") @@ -24,6 +25,7 @@ local Cinepak = require("@formats/codecs/video/Legacy/Cinepak") local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1") local QtRle = require("@formats/codecs/video/Legacy/QtRle") local Smc = require("@formats/codecs/video/Legacy/Smc") +local Smacker = require("@formats/codecs/video/Legacy/Smacker") local Legacy = {} @@ -33,7 +35,8 @@ Legacy.Cinepak = Cinepak Legacy.Msvideo1 = Msvideo1 Legacy.QtRle = QtRle Legacy.Smc = Smc -Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +Legacy.Smacker = Smacker +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } export type Options = { maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) @@ -124,6 +127,30 @@ local CODECS: { [string]: Codec } = { return Picture.image(st.pic), nil end, }, + smackvid = { + make = function(t) + local cfg = t.config + if type(cfg) ~= "buffer" then + return nil, "no Smacker trees" + end + local trees, msg = Smacker.trees(cfg) + if not trees then + return nil, msg + end + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + if buffer.len(data) == 0 then + return nil, fail("empty frame") + end + local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, flic = { make = function(t) return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) diff --git a/src/Formats/video/smk/Audio.luau b/src/Formats/video/smk/Audio.luau new file mode 100644 index 0000000..2da8993 --- /dev/null +++ b/src/Formats/video/smk/Audio.luau @@ -0,0 +1,123 @@ +--!strict +--!native +--!optimize 2 +-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker +-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), +-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ +-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per +-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / +-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives +-- them. Never throws: trees are bounded and every read past the packet gives zero bits. +local Smacker = require("@formats/codecs/video/Legacy/Smacker") + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +local Audio = {} + +-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message +function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) + local n = buffer.len(d) + if not packed then + local bps = bits // 8 + local frames = n // (bps * channels) + local count = frames * channels + local out = table.create(count, 0) + if bps == 1 then + for i = 0, count - 1 do + out[i + 1] = (readu8(d, i) - 128) / 128 + end + else + for i = 0, count - 1 do + out[i + 1] = readi16(d, i * 2) / 32768 + end + end + return frames, out + end + if n <= 4 then + return nil, "packet too small" + end + local size = buffer.readu32(d, 0) + if size > 2 ^ 24 then + return nil, "packet too big" + end + local br = Smacker.bits(d, 4, n - 4) + local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk + if bit(br) == 0 then + return 0, {} -- no data + end + local stereo = bit(br) + local wide = bit(br) + if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then + return nil, "packet does not match the track's format" + end + local bytes = wide + 1 + local ch = stereo + 1 + if size % (ch * bytes) ~= 0 then + return nil, "unpacked size is not a whole number of samples" + end + local trees: { { number } } = {} + for k = 1, 2 ^ (wide + stereo) do + bit(br) + local t, msg = Smacker.tree8(br) + if not t then + return nil, msg or "bad tree" + end + bit(br) + trees[k] = t + end + if br.nbits - br.pos < ch * bytes * 8 then + return nil, "truncated packet" + end + -- whether any tree needs bits (else every delta is a constant and no end check applies) + local coded = false + for _, t in trees do + if #t > 1 then + coded = true + end + end + local frames = size // (ch * bytes) + local total = frames * ch + local out = table.create(total, 0) + if wide == 1 then + local pred = { 0, 0 } + for c = ch, 1, -1 do + local v = read(br, 16) + pred[c] = (v // 256) + (v % 256) * 256 + end + for c = 1, math.min(ch, total) do + local v = pred[c] + out[c] = (if v >= 32768 then v - 65536 else v) / 32768 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if coded and br.pos > br.nbits then + return nil, "truncated packet" + end + local lo = walk(trees[2 * c + 1], br) + local hi = walk(trees[2 * c + 2], br) + local v = (pred[c + 1] + lo + hi * 256) % 65536 + pred[c + 1] = v + out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768 + end + else + local pred = { 0, 0 } + for c = ch, 1, -1 do + pred[c] = read(br, 8) + end + for c = 1, math.min(ch, total) do + out[c] = (pred[c] - 128) / 128 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if br.pos > br.nbits then + return nil, "truncated packet" + end + local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256 + pred[c + 1] = v + out[i + 1] = (v - 128) / 128 + end + end + return frames, out +end + +return Audio diff --git a/src/Formats/video/smk/init.luau b/src/Formats/video/smk/init.luau new file mode 100644 index 0000000..11c4c45 --- /dev/null +++ b/src/Formats/video/smk/init.luau @@ -0,0 +1,320 @@ +--!strict +-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in formats-luau, written from the format description +-- (MultimediaWiki "Smacker"). +-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio +-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette +-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() +-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the +-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio +-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it +-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that +-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, +-- track) the Decoder of any of its audio tracks. +-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/video/Video") +local Stream = require("@formats/codecs/audio/Stream") +local Audio = require("@formats/video/smk/Audio") + +-- ------------------------------------------------------------------------------------------------ contract +local Smk = { + name = "smk", + category = "video", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + audio: boolean?, -- false: do not open the audio track + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 104 +local RING = 1 +-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4) +local PAL6 = table.create(64, 0) +for i = 0, 63 do + PAL6[i + 1] = i * 4 + i // 16 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Smk.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s ~= "SMK2" and s ~= "SMK4" then + return 0 + end + return 1 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed +local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) + local pal = buffer.create(1024) + buffer.copy(pal, 0, old, 0, 1024) + local function u8(): number + local v = if p < stop then buffer.readu8(b, p) else 0 + p += 1 + return v + end + local sz = 0 + while sz < 256 do + local t = u8() + if t >= 0x80 then + sz += t - 0x80 + 1 + elseif t >= 0x40 then + local off = u8() + local j = t - 0x40 + 1 + if off + j > 256 then + return nil + end + while j > 0 and sz < 256 do + buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4)) + sz += 1 + off += 1 + j -= 1 + end + else + local r = PAL6[t + 1] + local g = PAL6[u8() % 64 + 1] + local bl = PAL6[u8() % 64 + 1] + buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000) + sz += 1 + end + end + return pal +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the header") + end + local hr = Bytes.reader(b, base, HEADER) + local magic = hr:string(4) + local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le() + local ptsInc = hr:i32le() + local flags = hr:u32le() + hr:skip(28) + local treeSize = hr:u32le() + local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() } + local rates, aflags = {}, {} + for k = 1, 7 do + rates[k] = hr:u24le() + aflags[k] = hr:u8() + end + if hr.err then + return nil, hr.err + end + if magic ~= "SMK2" and magic ~= "SMK4" then + return nil, Err.new(Err.CORRUPT, "not a Smacker file") + end + if w == 0 or h == 0 or w > 32768 or h > 32768 then + return nil, Err.new(Err.CORRUPT, "bad picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + local shown = frames + if bit32.band(flags, RING) ~= 0 then + frames += 1 + end + local p = base + HEADER + if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then + return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file") + end + -- the trees (with the four sizes in front, as the video codec takes them) + local config = buffer.create(16 + treeSize) + for k = 1, 4 do + buffer.writeu32(config, (k - 1) * 4, sizes[k]) + end + buffer.copy(config, 16, b, p + frames * 5, treeSize) + -- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s) + local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000 + local tracks: { Types.Track } = { + { + id = 1, + kind = "video", + codec = "smackvid", + codecTag = magic, + timescale = 100000, + width = w, + height = h, + frameRate = 100000 / tick, + default = true, + config = config, + flags = flags, + } :: Types.Track, + } + local audio: { [number]: Types.Track } = {} + for k = 1, 7 do + if rates[k] > 0 then + local f = aflags[k] + local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8 + local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio" + elseif bit32.band(f, 0x80) ~= 0 then "smackaudio" + elseif bits == 16 then "pcm_s16le" + else "pcm_u8" + local t: Types.Track = { + id = k + 1, + kind = "audio", + codec = codec, + codecTag = string.format("0x%02X", f), + timescale = rates[k], + sampleRate = rates[k], + channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1, + bitsPerSample = bits, + default = #tracks == 1, + } + audio[k] = t + table.insert(tracks, t) + end + end + local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown }) + local count = if opts and opts.ringFrame then frames else shown + local pal = buffer.create(1024) + local apts = { 0, 0, 0, 0, 0, 0, 0 } + local at = p + frames * 5 + treeSize + for i = 0, frames - 1 do + local fsize = buffer.readu32(b, p + i * 4) + local fflags = buffer.readu8(b, p + frames * 4 + i) + local size = fsize - fsize % 4 + local q, stop = at, math.min(limit, at + size) + at += size + local ok = true + if fflags % 2 == 1 and q < stop then + local psize = buffer.readu8(b, q) * 4 + if psize > size then + ok = false + else + local np = palette(b, q + 1, math.min(stop, q + psize), pal) + if np then + pal = np + else + ok = false + end + q += psize + end + end + for k = 1, 7 do + if not ok then + break + end + if bit32.band(fflags, 2 ^ k) ~= 0 then + if q + 4 > stop then + ok = false + break + end + local asize = buffer.readu32(b, q) + local t = audio[k] + local min = if t and t.codec ~= "pcm_s16le" then 8 else 4 + if asize < min or q + asize > stop then + ok = false + break + end + if t then + local len = asize - 4 + local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8 + local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes + elseif t.codec == "binkaudio" then 0 + else len // frameBytes + dmx:add(t.id, apts[k], nil, n, true, q + 4, len) + apts[k] += n + end + q += asize + end + end + if ok and i < count then + dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q)) + dmx:setExtra("palette", pal) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err +function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) + local codec = track.codec + if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec) + end + local id = track.id + local count = dmx:count(id) + local starts: { number } = {} + local total = 0 + for k = 1, count do + local pts, _, dur = dmx:info(id, k) + starts[k] = pts or total + total = (pts or total) + (dur or 0) + end + starts[count + 1] = total + local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number + local packed = codec == "smackaudio" + local floats: { number } = {} + local dec: any = { + sampleRate = rate, + channels = ch, + frames = total, + duration = total / rate, + bitrate = rate * ch * bits, + tags = {}, + } + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return starts[math.clamp(i, 1, count + 1)] + end, + decode = function(i: number): (number?, Err.Err?) + local pkt = dmx:get(id, i) + if not pkt then + return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i) + end + local n, out = Audio.decode(pkt.data, ch, bits, packed) + if not n then + return nil, Err.from(out :: string) + end + floats = out :: { number } + return n, nil + end, + pcm = function(): { number } + return floats + end, + reset = function() end, + cumulative = true, + }) +end + +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Smk.demux(r, opts) + if not dmx then + return nil, err + end + local o: any = table.clone(opts or {}) + type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?) + local hook = o.openAudio :: Hook? + o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?) + if track.codec == "binkaudio" and hook then + return hook(d, track) + end + return Smk.openAudio(d, track) + end + return Video.open(dmx, o) +end + +return Smk diff --git a/tests/video/smk.luau b/tests/video/smk.luau new file mode 100644 index 0000000..6969cde --- /dev/null +++ b/tests/video/smk.luau @@ -0,0 +1,180 @@ +-- video/smk tests: Smacker files encoded by the fixture script (SMK2 and SMK4, every block type and run, the trees' +-- escape cache, palette updates, a ring frame, ms and 10 us frame times; packed 16-bit stereo / 8-bit mono / 16-bit +-- mono / 8-bit stereo audio and raw s16le / u8 tracks): every video frame and every audio track equal ffmpeg's +-- decode (CRC-32 of rgba / f32le), audio seeking, errors, and the fuzz pass on the container, the video codec and the +-- audio codec. Fixtures: tools/fixtures/smk.py. +local T = require("@tests/T") +local F = require("@formats") +local Smk = require("@formats/video/smk") +local SmkAudio = require("@formats/video/smk/Audio") +local Legacy = require("@formats/codecs/video/Legacy") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/smk_cases") + +local t = T.suite("smk") +t:eq(Smk.name, "smk", "name") +t:eq(Smk.category, "video", "category") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- every frame of an audio Decoder -> f32 buffer, frames +local function drain(dec: any): (buffer, number) + local chunks, total = {}, 0 + while true do + local b, n = dec:read(1000) + if n == 0 then + break + end + table.insert(chunks, { b, n }) + total += n + end + local out = buffer.create(total * dec.channels * 4) + local at = 0 + for _, c in chunks do + buffer.copy(out, at, c[1], 0, c[2] * dec.channels * 4) + at += c[2] * dec.channels * 4 + end + return out, total +end + +for _, c in Fx do + local label = c.name + t:check(Smk.sniff(reader(c.data)) == 1, label .. ": sniff") + t:eq(F.detect(buffer.fromstring(c.data)), "smk", label .. ": detect") + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:eq(v.codec, "smackvid", label .. ": codec") + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate) < 1e-6, label .. ": frame rate " .. v.frameRate) + local want = if c.ring then #c.frames - 1 else #c.frames + local n, bad = 0, 0 + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": " .. tostring(ferr)) + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad)) + v:seek(0.2) + local f = v:nextFrame() + local k = math.floor(0.2 * c.rate - 1e-9) + 2 + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k) + -- audio: the first track through the VideoDecoder, every track through Smk.openAudio + if #c.audio > 0 then + t:check(v.audio ~= nil, label .. ": audio " .. tostring(v.audioError)) + end + local tracks = {} + for _, tr in v.demuxer.tracks do + if tr.kind == "audio" then + table.insert(tracks, tr) + end + end + t:eq(#tracks, #c.audio, label .. ": audio tracks") + for i, a in c.audio do + local tr = tracks[i] + t:eq(tr.codec, a.codec, label .. ": audio " .. i .. " codec") + local dec, aerr = Smk.openAudio(v.demuxer, tr) + t:check(dec ~= nil, label .. ": audio " .. i .. ": " .. tostring(aerr)) + if dec then + t:check(dec.sampleRate == a.rate and dec.channels == a.channels, label .. ": audio " .. i .. " format") + local pcm, frames = drain(dec) + t:eq(frames, a.frames, label .. ": audio " .. i .. " frames") + t:eq(Crc32.of(pcm), a.crc, label .. ": audio " .. i .. " equals ffmpeg's") + dec:seek(0) + local again = drain(dec) + t:eq(Crc32.of(again), a.crc, label .. ": audio " .. i .. " after seek(0)") + dec:seek(0.3) + local tail, rest = drain(dec) + local skip = a.frames - rest + t:check(math.abs(skip - 0.3 * a.rate) <= 1, label .. ": audio " .. i .. " seek(0.3) at frame " .. skip) + local same = buffer.len(tail) > 0 + for q = 0, math.min(buffer.len(tail), 4000) - 4, 4 do + if buffer.readu32(tail, q) ~= buffer.readu32(pcm, skip * a.channels * 4 + q) then + same = false + break + end + end + t:check(same, label .. ": audio " .. i .. " seek(0.3) samples") + end + end + if c.ring then + local v2 = Smk.open(reader(c.data), { ringFrame = true }) + local m = 0 + while v2 and v2:nextFrame() do + m += 1 + end + t:eq(m, #c.frames, label .. ": with the ring frame") + end + end +end + +-- errors +do + local _, e = Smk.open(reader(string.sub(Fx[1].data, 1, 60))) + t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED") + local _, e2 = Smk.open(reader("SMK3" .. string.sub(Fx[1].data, 5))) + t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT") + t:eq(Smk.sniff(reader("SMK3" .. string.sub(Fx[1].data, 5))), 0, "bad magic: no sniff") + local _, e3 = Smk.open(reader(Fx[1].data), { maxPixels = 100 }) + t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT") + local _, e4 = Smk.open(reader(string.sub(Fx[1].data, 1, 200))) + t:check(e4 ~= nil and e4.code == Err.TRUNCATED, "trees past the end: TRUNCATED") +end + +-- fuzz: the container, the video codec (native, no pcall in between) and the audio codec +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("open", function(b: buffer) + local v = Smk.open(Bytes.reader(b)) + if v then + for _ = 1, 4 do + if not v:nextFrame() then + break + end + end + if v.audio then + v.audio:read(500) + end + end + return v +end, samples, { mutations = 16, garbage = 40, keepHeader = 4 }) +local S, P = Legacy.Smacker, Legacy.Picture +for _, c in { Fx[1], Fx[2] } do + local d = Smk.demux(reader(c.data)) + local tr = d.tracks[1] + local packets = {} + for k = 1, math.min(3, d:count(1)) do + table.insert(packets, d:get(1, k).data) + end + t:fuzz(c.name .. " trees", function(b: buffer) + return S.trees(b) + end, { tr.config }, { mutations = 30, garbage = 30, keepHeader = 16 }) + local trees = assert(S.trees(tr.config)) + t:fuzz(c.name .. " frames", function(b: buffer) + return S.decode(P.new(c.width, c.height, true, 4, 4), b, trees, tr.codecTag == "SMK4") + end, packets, { mutations = 30, garbage = 30 }) + for _, at in d.tracks do + if at.kind == "audio" then + local ap = {} + for k = 1, math.min(2, d:count(at.id)) do + table.insert(ap, d:get(at.id, k).data) + end + t:fuzz(c.name .. " audio " .. at.codec, function(b: buffer) + return SmkAudio.decode(b, at.channels, at.bitsPerSample, at.codec == "smackaudio") + end, ap, { mutations = 20, garbage = 20 }) + end + end +end +t:done() diff --git a/tools/fixtures/smk.py b/tools/fixtures/smk.py new file mode 100644 index 0000000..0d9ee5a --- /dev/null +++ b/tools/fixtures/smk.py @@ -0,0 +1,493 @@ +# Smacker fixtures (tools/fixtures.py): ffmpeg cannot write Smacker, so this encodes SMK2 / SMK4 files: the four +# header trees (8-bit low / high byte trees, escape leaves used through the recent-value cache, absent trees), every +# block type (MONO, FULL with the SMK4 doubled modes, SKIP, FILL) with block runs, palette updates (new entries, skips, +# copies from the old palette), a ring frame, both frame-time units, and audio tracks: packed DPCM 16-bit stereo and +# 8-bit mono, raw s16le and u8. The reference is ffmpeg's decode: the CRC-32 of each video frame as rgba and of each +# audio track as f32le. +# tests/gen/smk_cases.luau { { name, data, width, height, rate, frames = { crc }, audio = { { rate, channels, +# bits, codec, frames, crc } } } } +import heapq, importlib.util, math, os, random, struct, tempfile, zlib + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +RUNS = list(range(1, 60)) + [128, 256, 512, 1024, 2048] + + +# ---------------------------------------------------------------------------------------------------- bits / trees +class Bits: + def __init__(self): + self.bits = [] + + def put(self, v, n): + for i in range(n): + self.bits.append((v >> i) & 1) + + def code(self, c): + self.bits.extend(c) + + def bytes(self): + out = bytearray((len(self.bits) + 7) // 8) + for i, b in enumerate(self.bits): + out[i >> 3] |= b << (i & 7) + return bytes(out) + + +def huffman(freqs, maxdepth): + """a Huffman tree over freqs {value: count}: nested (left, right) tuples / ('leaf', value)""" + f = dict(freqs) + while True: + heap = [(c, i, ("leaf", v)) for i, (v, c) in enumerate(sorted(f.items()))] + heapq.heapify(heap) + k = len(heap) + while len(heap) > 1: + a = heapq.heappop(heap) + b = heapq.heappop(heap) + heapq.heappush(heap, (a[0] + b[0], k, (a[2], b[2]))) + k += 1 + tree = heap[0][2] + if depth(tree) <= maxdepth: + return tree + f = {v: c // 2 + 1 for v, c in f.items()} + + +def depth(t): + return 0 if t[0] == "leaf" else 1 + max(depth(t[0]), depth(t[1])) + + +def codes(t, prefix=(), out=None): + out = {} if out is None else out + if t[0] == "leaf": + out[t[1]] = list(prefix) + else: + codes(t[0], prefix + (0,), out) + codes(t[1], prefix + (1,), out) + return out + + +def write_tree8(bw, t): + if t[0] == "leaf": + bw.put(0, 1) + bw.put(t[1], 8) + else: + bw.put(1, 1) + write_tree8(bw, t[0]) + write_tree8(bw, t[1]) + + +class BigTree: + """a header tree: values (16-bit) with three escape leaves for the recent-value cache""" + + def __init__(self, freqs, rnd, absent_ok=True): + self.absent = not freqs + if self.absent: + return + lo = {} + hi = {} + for v, c in freqs.items(): + lo[v & 255] = lo.get(v & 255, 0) + c + hi[v >> 8] = hi.get(v >> 8, 0) + c + # three escape values made of bytes the byte trees have, not used as values (a high-byte tree of only 0 is + # left out: absent byte trees decode as 0) + esc = [] + for l in sorted(lo): + for h in sorted(hi): + v = l | h << 8 + if v not in freqs and len(esc) < 3: + esc.append(v) + while len(esc) < 3: # every combination used: widen the low byte tree + nl = next(x for x in range(256) if x not in lo) + lo[nl] = 1 + esc.append(nl | sorted(hi)[0] << 8) + self.esc = esc + self.lo = huffman(lo, 27) + self.hi = huffman(hi, 27) + allv = dict(freqs) + for i, e in enumerate(esc): + allv[e] = max(1, sum(freqs.values()) // (8 + i)) + self.tree = huffman(allv, 200) + self.lcodes, self.hcodes, self.vcodes = codes(self.lo), codes(self.hi), codes(self.tree) + self.entries = count_entries(self.tree) + self.hi_absent = len(hi) == 1 and 0 in hi + self.rnd = rnd + + def write(self, bw): + if self.absent: + bw.put(0, 1) + return + bw.put(1, 1) + bw.put(1, 1) + write_tree8(bw, self.lo) + bw.put(0, 1) + if self.hi_absent: + bw.put(0, 1) + else: + bw.put(1, 1) + write_tree8(bw, self.hi) + bw.put(0, 1) + for e in self.esc: + bw.put(e, 16) + self._write_big(bw, self.tree) + bw.put(0, 1) + + def _write_big(self, bw, t): + if t[0] == "leaf": + bw.put(0, 1) + v = t[1] + bw.code(self.lcodes[v & 255]) + if not self.hi_absent: + bw.code(self.hcodes[v >> 8]) + else: + bw.put(1, 1) + self._write_big(bw, t[0]) + self._write_big(bw, t[1]) + + def size(self): + return 0 if self.absent else (self.entries + 3) * 4 + + def reset(self): + self.cache = [0, 0, 0] + + def emit(self, bw, v): + if self.absent: + assert v == 0 + return + hit = [k for k in range(3) if self.cache[k] == v] + if hit and self.rnd.random() < 0.7: + bw.code(self.vcodes[self.esc[hit[0]]]) + else: + bw.code(self.vcodes[v]) + if v != self.cache[0]: + self.cache[2] = self.cache[1] + self.cache[1] = self.cache[0] + self.cache[0] = v + + +def count_entries(t): + return 1 if t[0] == "leaf" else 1 + count_entries(t[0]) + count_entries(t[1]) + + +# ---------------------------------------------------------------------------------------------------- video +def blocks_of(img, w, h): + return [[[img[by * 4 + r][bx * 4 + x] for x in range(4)] for r in range(4)] for by in range(h // 4) for bx in range(w // 4)] + + +def classify(b, prev, v4): + if prev is not None and b == prev: + return ("skip",) + flat = [p for r in b for p in r] + cols = sorted(set(flat)) + if len(cols) == 1: + return ("fill", cols[0]) + if len(cols) == 2: + lo, hi = cols + m = 0 + for i, p in enumerate(flat): + if p == hi: + m |= 1 << i + return ("mono", hi << 8 | lo, m) + if v4 and b[0] == b[1] and b[2] == b[3] and b[0][0] == b[0][1] and b[0][2] == b[0][3] and b[2][0] == b[2][1] and b[2][2] == b[2][3]: + return ("full", 1) + if v4 and b[0] == b[1] and b[2] == b[3]: + return ("full", 2) + return ("full", 0) + + +def full_codes(b, mode): + if mode == 0: + out = [] + for r in b: + out += [r[2] | r[3] << 8, r[0] | r[1] << 8] + return out + if mode == 1: + return [b[0][0] | b[0][2] << 8, b[2][0] | b[2][2] << 8] + return [b[0][2] | b[0][3] << 8, b[0][0] | b[0][1] << 8, b[2][2] | b[2][3] << 8, b[2][0] | b[2][1] << 8] + + +def plan(frames, w, h, v4): + """per frame the list of runs: (kind, extra, [blocks])""" + out = [] + prev = None + for img in frames: + bl = blocks_of(img, w, h) + cls = [classify(b, prev[i] if prev else None, v4) for i, b in enumerate(bl)] + runs = [] + i = 0 + while i < len(bl): + c = cls[i] + key = c[:2] if c[0] in ("fill", "full") else c[:1] + j = i + while j + 1 < len(bl) and (cls[j + 1][:2] if cls[j + 1][0] in ("fill", "full") else cls[j + 1][:1]) == key: + j += 1 + n = j - i + 1 + # the largest run length of the table that fits + k = max(r for r in RUNS if r <= n) + runs.append((c, [bl[x] for x in range(i, i + k)], [cls[x] for x in range(i, i + k)], RUNS.index(k))) + i += k + out.append(runs) + prev = bl + return out + + +def type_value(c, ri): + kind = {"mono": 0, "full": 1, "skip": 2, "fill": 3}[c[0]] + v = kind | ri << 2 + if c[0] == "fill": + v |= c[1] << 8 + return v + + +def stats(plans, v4): + f = {"type": {}, "mclr": {}, "mmap": {}, "full": {}} + + def add(t, v): + f[t][v] = f[t].get(v, 0) + 1 + + for runs in plans: + for c, bl, cl, ri in runs: + add("type", type_value(c, ri)) + if c[0] == "mono": + for x in cl: + add("mclr", x[1]) + add("mmap", x[2]) + elif c[0] == "full": + for b in bl: + for v in full_codes(b, c[1]): + add("full", v) + return f + + +def encode_video(frames, w, h, v4, rnd): + plans = plan(frames, w, h, v4) + f = stats(plans, v4) + trees = {k: BigTree(f[k], rnd) for k in ("mmap", "mclr", "full", "type")} + tb = Bits() + for k in ("mmap", "mclr", "full", "type"): + trees[k].write(tb) + treebytes = tb.bytes() + out = [] + for runs in plans: + for t in trees.values(): + t.reset() + bw = Bits() + for c, bl, cl, ri in runs: + trees["type"].emit(bw, type_value(c, ri)) + if c[0] == "mono": + for x in cl: + trees["mclr"].emit(bw, x[1]) + trees["mmap"].emit(bw, x[2]) + elif c[0] == "full": + if v4: + bw.code([1] if c[1] == 1 else [0, 1] if c[1] == 2 else [0, 0]) + for b in bl: + for v in full_codes(b, c[1]): + trees["full"].emit(bw, v) + out.append(bw.bytes() or b"\0") + return treebytes, [trees[k].size() for k in ("mmap", "mclr", "full", "type")], out + + +# ---------------------------------------------------------------------------------------------------- palettes +def pal_chunk(new, old, first): + """a palette update: new / old are lists of 256 6-bit (r, g, b)""" + body = bytearray() + i = 0 + while i < 256: + if not first and new[i] == old[i]: + j = i + while j < 256 and j - i < 128 and new[j] == old[j]: + j += 1 + body.append(0x80 | (j - i - 1)) + i = j + continue + # a copy from the old palette when the next entries appear there in a row + if not first: + for off in range(256): + n = 0 + while i + n < 256 and off + n < 256 and n < 64 and new[i + n] == old[off + n]: + n += 1 + if n >= 2: + body += bytes([0x40 | (n - 1), off]) + i += n + break + else: + off = None + if off is not None: + continue + body += bytes(new[i]) + i += 1 + size = 1 + len(body) + size = (size + 3) // 4 * 4 + return bytes([size // 4]) + bytes(body) + bytes(size - 1 - len(body)) + + +# ---------------------------------------------------------------------------------------------------- audio +def pack_audio(samples, ch, bits): + """one packed (SMKA) chunk body: samples interleaved (s16 or u8)""" + nb = bits // 8 + bw = Bits() + bw.put(1, 1) + bw.put(1 if ch == 2 else 0, 1) + bw.put(1 if bits == 16 else 0, 1) + mod = 65536 if bits == 16 else 256 + pred = list(samples[:ch]) + deltas = [] + for i in range(ch, len(samples)): + c = i % ch + d = (samples[i] - pred[c]) % mod + pred[c] = samples[i] + deltas.append((c, d)) + ntrees = (2 if bits == 16 else 1) * ch + freqs = [dict() for _ in range(ntrees)] + for c, d in deltas: + if bits == 16: + freqs[2 * c][d & 255] = freqs[2 * c].get(d & 255, 0) + 1 + freqs[2 * c + 1][d >> 8] = freqs[2 * c + 1].get(d >> 8, 0) + 1 + else: + freqs[c][d] = freqs[c].get(d, 0) + 1 + trees = [huffman(f or {0: 1}, 27) for f in freqs] + cds = [codes(t) for t in trees] + for t in trees: + bw.put(1, 1) + write_tree8(bw, t) + bw.put(0, 1) + for c in range(ch - 1, -1, -1): + v = samples[c] % mod + if bits == 16: + v = ((v & 255) << 8) | (v >> 8) # stored byte-swapped + bw.put(v, bits) + for c, d in deltas: + if bits == 16: + bw.code(cds[2 * c][d & 255]) + bw.code(cds[2 * c + 1][d >> 8]) + else: + bw.code(cds[c][d]) + return struct.pack(" 0 else -pts_inc / 100000.0) + achunks = [] + for ti, (kind, rate, ch, bits) in enumerate(tracks): + per = [] + done = 0 + for t in range(total): + n = int(round((t + 1) * seconds * rate)) - done + done += n + s = tone(n, ch, bits, rate, seed * 10 + ti * 100 + t, 440 + 110 * ti) + if kind == "packed": + per.append(pack_audio(s, ch, bits)) + else: + per.append(b"".join(struct.pack(" 0 else 100000 / -pts + cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio, + "ring": ring}) + ctx.emit("smk_cases", cases)