--!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