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.
This commit is contained in:
4DBug committed 2026-10-31 14:37:39 -05:00
1 parent a1d2e7218c
commit bf639260e4
8 files changed
+1522 -3

No files matched your search

+12
View File
@@ -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",
@@ -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
+30 -3
View File
@@ -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)
+123
View File
@@ -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
+320
View File
@@ -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