merge ws/video2-legacy (FLIC, Cinepak, MSV1, QT RLE / SMC, Smacker; video/fli, video/smk)

This commit is contained in:
4DBug committed 2026-10-31 15:23:13 -05:00
commit 9694c652ec
32 files changed
+4786 -5

No files matched your search

+4 -1
View File
@@ -28,12 +28,14 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` |
| video | fli | .fli .flc .flx | yes | - | streaming: true, video: "flic", depths: 8, 15, 16, 24 | `tests/video/fli.luau` |
| video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` |
| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` |
| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` |
| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "mpeg2", "h264", audio: true, fragments: true | `tests/video/mp4.luau` |
| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", "mpeg2", audio: true | `tests/video/mpegps.luau` |
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "mpeg2", "h264", audio: true | `tests/video/mpegts.luau` |
| video | ogv | .ogv .ogg | yes | yes | streaming: true, remux: true, video: "theora", audio: true | `tests/video/ogv.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` |
@@ -135,6 +137,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- **video**
- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs.
- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder
- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska
+71
View File
@@ -366,6 +366,77 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels)
See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`.
<!-- ws-video2-legacy: formats table addition -->
| fli / flc / flx | yes | - | FLIC (8-bit palettised, 15 / 16 / 24-bit) |
| smk | yes | - | Smacker video (SMK2 / SMK4) + Smacker audio / PCM |
AVI, MOV / MP4 and MKV (V_MS/VFW/FOURCC, V_QUICKTIME) also decode the legacy codecs: Cinepak, Microsoft Video 1,
QuickTime Animation (RLE) and QuickTime Graphics (SMC). See [Legacy video](#legacy-video).
<!-- ws-video2-legacy: section -->
## Legacy video
The 1990s formats and codecs decode to **rgba8** frames (they are palettised or RGB, not YUV), each frame painted
over the previous one, as the codecs define. Decoding is bit-exact with ffmpeg's.
| Codec id | Name | Containers | Depths |
|---|---|---|---|
| `flic` | Autodesk FLI / FLC | fli | 8-bit palettised, 15 / 16 / 24-bit |
| `smackvid` | Smacker video | smk | 8-bit palettised |
| `cinepak` | Cinepak (`cvid`) | avi, mov, mkv | 24-bit, grey, 8-bit palettised |
| `msvideo1` | Microsoft Video 1 (`CRAM`, `MSVC`, `WHAM`) | avi, mov, mkv | 16-bit (5-5-5), 8-bit palettised |
| `qtrle` | QuickTime Animation (`rle `) | mov, mkv | 1, 2, 4, 8 (palettised or grey), 16, 24, 32 (alpha) |
| `smc` | QuickTime Graphics (`smc `) | mov, mkv | 8-bit palettised |
Palettes come from the container: `track.palette` (256 entries, 4 bytes each: R, G, B, A) holds the AVI
BITMAPINFO palette or the QuickTime colour table (or the Macintosh default table it refers to); FLIC and Smacker
frames carry their own palette changes.
```luau
local v = assert(F.video.open(cinepakBytes)) -- Cinepak in a QuickTime movie
assert(v.format == "mov" and v.codec == "cinepak")
local frames = 0
while true do
local f = v:nextFrame()
if not f then break end
assert(f.image.format == "rgba8" and f.image.width == 64)
frames += 1
end
assert(frames == v.frames)
```
FLIC files (`.fli` at 70 Hz ticks, `.flc` / `.flx` in milliseconds) open as videos; the ring frame (an extra frame
leading back to the first, for looping) is not shown unless you ask for it.
```luau
local v = assert(F.video.open(flcBytes))
print(v.format, v.codec, v.width, v.height, v.frameRate) -- fli flic 64 48 10
assert(v.track.bitsPerPixel == 8 and v.frames == 10)
local f = assert(v:nextFrame())
local r, g, b, a = F.ops.image.getPixel(f.image, 0, 0) -- palette colours, opaque
assert(r and g and b and a == 255)
local all = assert(F.format("fli").open(F.Bytes.reader(flcBytes), { ringFrame = true }))
assert(all.codec == "flic")
```
Smacker files carry up to seven audio tracks. The format decodes Smacker's packed audio (and raw PCM tracks) itself:
`v.audio` is the first track, `F.format("smk").openAudio(demuxer, track)` opens any of them.
```luau
local v = assert(F.video.open(smkBytes))
assert(v.format == "smk" and v.codec == "smackvid")
local a = assert(v.audio, tostring(v.audioError)) -- packed 16-bit stereo, 22050 Hz
assert(a.sampleRate == 22050 and a.channels == 2)
local Smk = F.format("smk")
for _, t in v.demuxer.tracks do
if t.kind == "audio" then
local dec = assert(Smk.openAudio(v.demuxer, t)) -- smackaudio, pcm_u8 or pcm_s16le
local pcm, n = dec:read(1000)
assert(n == 1000 and buffer.len(pcm) == n * dec.channels * 4)
end
end
```
## Gotchas
- Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with `tools/bench.luau`
+1
View File
@@ -30,6 +30,7 @@ F.convert(gif, "avi") -- animated images become videos (un
| `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) |
| `codecs/video/Mpeg2` (`Mpeg1` is the same module), `H264` | MPEG-1 / MPEG-2 and H.264 video decoders |
| `codecs/video/Dsp` | 8x8 IDCT (bit-exact with `ffmpeg -idct int`) and half-pel motion compensation for the MPEG-style codecs |
| `codecs/video/Legacy` | FLIC, Smacker, Cinepak, Microsoft Video 1, QuickTime RLE / SMC: rgba8, palettes from `track.palette` |
| `video/<fmt>` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source |
Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires
+26 -2
View File
@@ -290,6 +290,18 @@ local list: { Entry } = {
return require("@formats/video/avi")
end,
},
{
name = "fli",
category = "video",
path = "video/fli",
extensions = { "fli", "flc", "flx" },
mime = { "video/x-fli", "video/fli", "video/x-flc" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } },
load = function()
return require("@formats/video/fli")
end,
},
{
name = "h264",
category = "video",
@@ -308,8 +320,8 @@ local list: { Entry } = {
path = "video/mkv",
extensions = { "mkv", "webm", "mka", "mk3d" },
mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true },
load = function()
return require("@formats/video/mkv")
end,
@@ -362,6 +374,18 @@ local list: { Entry } = {
return require("@formats/video/ogv")
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,303 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4
-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description
-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4
-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame
-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are
-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra
-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak
-- decoder. Never throws: every read is range-checked against its chunk.
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
local band = bit32.band
local Cinepak = {}
local MAX_STRIPS = 32
-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index)
local ENTRY = 16
local BOOK = 256 * ENTRY
export type State = {
books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip)
filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet)
}
function Cinepak.state(): State
return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 }
end
local function be16(d: buffer, o: number): number
return readu8(d, o) * 256 + readu8(d, o + 1)
end
local function be24(d: buffer, o: number): number
return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2)
end
local function be32(d: buffer, o: number): number
return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3)
end
local function clip(v: number): number
return if v < 0 then 0 elseif v > 255 then 255 else v
end
-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set
local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number)
local six = band(id, 4) == 0
local partial = band(id, 1) ~= 0
local size = if six then 6 else 4
local flag, mask = 0, 0
for i = 0, 255 do
if partial then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
end
if not partial or band(flag, mask) ~= 0 then
if p + size > stop then
return
end
local e = book + i * ENTRY
local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3)
if six then
local u, v = readu8(d, p + 4), readu8(d, p + 5)
if u >= 128 then
u -= 256
end
if v >= 128 then
v -= 256
end
local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero)
local dr, dg, db = 2 * v, -uh - v, 2 * u
writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000)
writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000)
writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000)
writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000)
else
writeu32(books, e, y0 * 0x10101 + 0xFF000000)
writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000)
writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000)
writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000)
end
p += size
end
end
end
-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data
local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number,
stop: number, x1: number, y1: number, x2: number, y2: number): boolean
local stride = pic.stride
local pal = pic.idx
local px = (pal or pic.rgba) :: buffer
local flag, mask = 0, 0
local inter = band(id, 1) ~= 0
local v1only = band(id, 2) ~= 0
for y = y1, y2 - 1, 4 do
for x = x1, x2 - 1, 4 do
local paint = true
if inter then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return false
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
paint = band(flag, mask) ~= 0
end
if paint then
local useV1 = v1only
if not v1only then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return false
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
useV1 = band(flag, mask) == 0
end
local o = y * stride + x
if useV1 then
if p >= stop then
return false
end
local e = v1 + readu8(d, p) * ENTRY
p += 1
-- each of the 4 entries fills a 2x2 square
local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12)
if pal then
a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256
writeu32(px, o, a * 0x0101 + b * 0x01010000)
writeu32(px, o + stride, a * 0x0101 + b * 0x01010000)
writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000)
writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000)
else
for r = 0, 3 do
local q = (o + r * stride) * 4
local l, rr = if r < 2 then a else c, if r < 2 then b else e4
writeu32(px, q, l)
writeu32(px, q + 4, l)
writeu32(px, q + 8, rr)
writeu32(px, q + 12, rr)
end
end
else
if p + 4 > stop then
return false
end
local e0 = v4 + readu8(d, p) * ENTRY
local e1 = v4 + readu8(d, p + 1) * ENTRY
local e2 = v4 + readu8(d, p + 2) * ENTRY
local e3 = v4 + readu8(d, p + 3) * ENTRY
p += 4
-- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right)
if pal then
for r = 0, 3 do
local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3
local off = (r % 2) * 8
local q = o + r * stride
writeu8(px, q, readu8(books, l + off))
writeu8(px, q + 1, readu8(books, l + off + 4))
writeu8(px, q + 2, readu8(books, rr + off))
writeu8(px, q + 3, readu8(books, rr + off + 4))
end
else
for r = 0, 3 do
local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3
local off = (r % 2) * 8
local q = (o + r * stride) * 4
writeu32(px, q, readu32(books, l + off))
writeu32(px, q + 4, readu32(books, l + off + 4))
writeu32(px, q + 8, readu32(books, rr + off))
writeu32(px, q + 12, readu32(books, rr + off + 4))
end
end
end
end
end
end
return true
end
-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this
-- packet (an empty frame); false + message = an error
function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?)
local n = buffer.len(d)
if n < 10 then
return false, "frame too short"
end
local strips = be16(d, 8)
if strips == 0 and not (pic.idx and newPalette) then
return false, nil
end
local size = be24(d, 1)
if n < size * 5 // 100 then
return false, "frame shorter than its header says"
end
if st.filmSkip < 0 then
if size == 0 then
return false, "unsupported: a zero frame size"
end
if size ~= n and n % size ~= 0 then
if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6
and readu8(d, 14) == 0 and readu8(d, 15) == 0 then
st.filmSkip = 6
else
st.filmSkip = 2
end
else
st.filmSkip = 0
end
end
local skip = st.filmSkip
if n < 10 + skip + strips * 12 then
return false, "truncated strip headers"
end
if strips > 0 then
local ss = be24(d, 10 + skip + 1)
if ss < 12 or ss > size then
return false, "bad strip size"
end
end
local flags = readu8(d, 0)
local p = 10 + skip
strips = math.min(strips, MAX_STRIPS)
local books = st.books
-- the coded area: the size rounded up to whole blocks (the picture's plane)
local cw, ch = pic.stride, pic.rows
local y0 = 0
for i = 0, strips - 1 do
if p + 12 > n then
return true, nil
end
local sy1 = be16(d, p + 4)
local sx1 = be16(d, p + 6)
local sy2, sx2 = be16(d, p + 8), be16(d, p + 10)
if sy1 == 0 then
sy1 = y0
sy2 = y0 + sy2
end
local ssize = be24(d, p + 1) - 12
if ssize < 0 then
return true, nil
end
p += 12
local stop = math.min(n, p + ssize)
local v4 = i * 2 * BOOK
local v1 = v4 + BOOK
if i > 0 and band(flags, 1) == 0 then
buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK)
end
-- the strip's chunks: codebooks, then one vector chunk
-- (strips start on block boundaries in every known stream: the plane holds whole blocks only)
if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then
return true, nil
end
local q = p
local done = false
while q + 4 <= stop do
local id = readu8(d, q)
local csize = be24(d, q + 1) - 4
if csize < 0 then
return true, nil
end
q += 4
local cstop = math.min(stop, q + csize)
if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then
codebook(books, v4, id, d, q, cstop)
elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then
codebook(books, v1, id, d, q, cstop)
elseif id == 0x30 or id == 0x31 or id == 0x32 then
if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then
return true, nil
end
done = true
break
end
q = cstop
end
if not done then
return true, nil
end
p = stop
y0 = sy2
end
return true, nil
end
return Cinepak
+372
View File
@@ -0,0 +1,372 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is
-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's
-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit
-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK
-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX
-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26);
-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet
-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames.
-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture).
local Types = require("@formats/Types")
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bfill = buffer.fill
local Flic = {}
-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette
export type State = {
pic: Picture.Picture,
depth: number, -- 8, 15, 16, 24
bpp: number, -- bytes per pixel
}
-- state(w, h, depth) -> State | nil, message
function Flic.state(w: number, h: number, depth: number): (State?, string?)
local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0
if bpp == 0 then
return nil, "unsupported: " .. depth .. "-bit FLIC"
end
local pic = Picture.new(w * bpp, h, true)
pic.w = w
return { pic = pic, depth = depth, bpp = bpp }, nil
end
local function s8(v: number): number
return if v >= 128 then v - 256 else v
end
-- decode(st, data) -> true | false, message
function Flic.decode(st: State, d: buffer): (boolean, string?)
local pic = st.pic
local px = pic.idx :: buffer
local pal = pic.pal
local w, h = pic.w, pic.h
local bpp = st.bpp
local deep = bpp > 1
local stride = pic.stride
local limit = stride * h
local n = buffer.len(d)
if n < 16 then
return false, "frame too short"
end
local p = 0
local function u8(): number
local v = if p < n then readu8(d, p) else 0
p += 1
return v
end
local function u16(): number
local a = u8()
return a + u8() * 256
end
local frameSize = math.min(readu32(d, 0), n)
local chunks = readu8(d, 6) + readu8(d, 7) * 256
if frameSize < 16 then
return false, "bad frame size"
end
frameSize -= 16
p = 16
while frameSize >= 6 and chunks > 0 and n - p >= 4 do
local size = readu32(d, p)
if size > frameSize then
size = frameSize
end
local after = p + size
p += 4
local typ = u16()
if typ == 4 or typ == 11 then
if not deep then
-- palette packets: skip count, change count (0 = 256), r g b
local shift = typ == 11
local packets = u16()
local at = 0
for _ = 1, packets do
at += u8()
local count = u8()
if count == 0 then
count = 256
end
if p + count * 3 > after then
break
end
for _ = 1, count do
if at >= 256 then
at = 0
end
local r, g, b = u8(), u8(), u8()
if shift then
-- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below
r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256
r, g, b = r + r // 64, g + g // 64, b + b // 64
end
writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000)
at += 1
end
end
end
elseif typ == 7 or (deep and typ == 27) then
-- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode)
local y = 0
local lines = u16()
while lines > 0 do
if p + 2 > after then
break
end
if y > limit then
return false, "delta past the picture"
end
local lp = u16()
if lp >= 0x8000 then
lp -= 0x10000
end
if deep then
if lp < 0 then
if -lp > h then
return false, "bad line skip"
end
y += -lp * stride
continue
end
elseif lp < 0 and lp >= -0x4000 then
-- 0xC000 .. 0xFFFF: skip lines
if -lp > h then
return false, "bad line skip"
end
y += -lp * stride
continue
elseif lp < 0 then
-- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its
-- padded row instead: the same pixel when rows are not padded)
local q = y + w - 1
if q < 0 or q >= limit then
return false, "delta past the picture"
end
writeu8(px, q, lp % 256)
continue
elseif lp >= 0x4000 then
continue -- undefined opcode
end
lines -= 1
local q = y
for _ = 1, lp do
if p + 2 > after then
break
end
q += u8() * bpp
local run = s8(u8())
if deep then
local cnt = if run < 0 then -run else run
if q + cnt * bpp > limit then
return false, "delta past the picture"
end
if run < 0 then
local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0
for _ = 1, cnt do
writeu8(px, q, a)
writeu8(px, q + 1, b)
if bpp == 3 then
writeu8(px, q + 2, c)
end
q += bpp
end
else
if p + cnt * bpp > after then
break
end
buffer.copy(px, q, d, p, cnt * bpp)
p += cnt * bpp
q += cnt * bpp
end
elseif run < 0 then
local cnt = -run
local a, b = u8(), u8()
if q + cnt * 2 > limit then
return false, "delta past the picture"
end
for _ = 1, cnt do
writeu8(px, q, a)
writeu8(px, q + 1, b)
q += 2
end
else
if q + run * 2 > limit then
return false, "delta past the picture"
end
if p + run * 2 > after then
break
end
buffer.copy(px, q, d, p, run * 2)
p += run * 2
q += run * 2
end
end
y += stride
end
elseif typ == 12 and not deep then
-- byte-oriented delta (LC): first line, line count, per line packets of (skip, run)
local first = u16()
if first >= h then
return false, "bad first line"
end
local y = first * stride
local lines = u16()
while lines > 0 do
local q = y
if q > limit then
return false, "delta past the picture"
end
if p + 1 > after then
break
end
local packets = u8()
for _ = 1, packets do
if p + 1 > after then
break
end
q += u8()
local run = s8(u8())
if run > 0 then
if q + run > limit then
return false, "delta past the picture"
end
if p + run > after then
break
end
buffer.copy(px, q, d, p, run)
p += run
q += run
elseif run < 0 then
local v = u8()
if q - run > limit then
return false, "delta past the picture"
end
bfill(px, q, v, -run)
q -= run
end
end
y += stride
lines -= 1
end
elseif typ == 13 then
bfill(px, 0, 0, limit)
elseif typ == 15 or (deep and typ == 25) then
-- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals
local unit = if typ == 25 then bpp else 1
local y = 0
for _ = 1, h do
local q = y
p += 1 -- the packet count (unused)
local left = if typ == 25 then w else w * bpp
while left > 0 do
if p + 1 > after then
break
end
local run = s8(u8())
if run == 0 and not deep then
return false, "zero byte run"
end
if run > 0 then
if q + run * unit > limit then
return false, "run past the picture"
end
if unit == 1 then
bfill(px, q, u8(), run)
q += run
else
local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0
for _ = 1, run do
writeu8(px, q, a)
writeu8(px, q + 1, b)
if bpp == 3 then
writeu8(px, q + 2, c)
end
q += bpp
end
end
left -= run
else
local cnt = -run
if q + cnt * unit > limit then
return false, "run past the picture"
end
if p + cnt * unit > after then
break
end
buffer.copy(px, q, d, p, cnt * unit)
p += cnt * unit
q += cnt * unit
left -= cnt
end
end
y += stride
end
elseif typ == 16 or (deep and typ == 26) then
-- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more)
local row = w * bpp
local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4
local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h
if ok then
if deep and n - p < row * h then
return false, "truncated copy chunk"
end
for y = 0, h - 1 do
local s = p + y * padded
local cnt = math.max(0, math.min(row, n - s))
if cnt > 0 then
buffer.copy(px, y * stride, d, s, cnt)
end
end
p += padded * h
end
end
-- typ 18 (PSTAMP) and unknown chunks are skipped
if after - p >= 0 then
p = after
else
break
end
frameSize -= size
chunks -= 1
end
return true, nil
end
-- image(st) -> a fresh rgba8 Image
function Flic.image(st: State): Types.Image
local pic = st.pic
if st.bpp == 1 then
return Picture.image(pic)
end
local w, h = pic.w, pic.h
local img = Types.Image.new(w, h, "rgba8")
local out = img.pixels
local px = pic.idx :: buffer
local stride = pic.stride
if st.bpp == 3 then
for y = 0, h - 1 do
local s, o = y * stride, y * w * 4
for x = 0, w - 1 do
local q = s + x * 3
writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000)
end
end
else
local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565()
local mask = if st.depth == 15 then 32768 else 65536
for y = 0, h - 1 do
local s, o = y * stride, y * w * 4
for x = 0, w - 1 do
local q = s + x * 2
writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4))
end
end
end
return img
end
return Flic
@@ -0,0 +1,121 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit
-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows
-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour
-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour
-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture.
-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there).
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local band = bit32.band
local Msvideo1 = {}
-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1
-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)]
local function quadrant(x: number, y: number): number
return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0)
end
-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit)
function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?)
local n = buffer.len(d)
local bw, bh = pic.w // 4, pic.h // 4
if n < bw * bh // 512 then
return false, "frame too small"
end
local stride = pic.stride
local total = bw * bh
local skip = 0
local p = 0
local wide = bits ~= 8
local px = (if wide then pic.rgba else pic.idx) :: buffer
local lut = if wide then Picture.rgb555() else nil
local c = table.create(8, 0)
for by = bh - 1, 0, -1 do
for bx = 0, bw - 1 do
if skip ~= 0 then
skip -= 1
total -= 1
continue
end
if p + 2 > n then
return true, nil
end
local a, b = readu8(d, p), readu8(d, p + 1)
p += 2
if a == 0 and b == 0 and total == 0 then
return true, nil
end
-- the block's bottom-left pixel; its rows go up
local o = (by * 4 + 3) * stride + bx * 4
if band(b, 0xFC) == 0x84 then
skip = (b - 0x84) * 256 + a - 1
elseif b < 0x80 or (not wide and b >= 0x90) then
local flags = b * 256 + a
local eight
if wide then
if p + 4 > n then
return true, nil
end
c[1], c[2] = readu16(d, p), readu16(d, p + 2)
p += 4
eight = c[1] >= 0x8000
if eight then
if p + 12 > n then
return true, nil
end
for k = 3, 8 do
c[k] = readu16(d, p)
p += 2
end
end
else
eight = b >= 0x90
local cnt = if eight then 8 else 2
if p + cnt > n then
return true, nil
end
for k = 1, cnt do
c[k] = readu8(d, p)
p += 1
end
end
for y = 0, 3 do
local row = o - y * stride
for x = 0, 3 do
local k = (if band(flags, 1) == 1 then 1 else 2)
if eight then
k += quadrant(x, y)
end
flags = flags // 2
if lut then
writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4))
else
writeu8(px, row + x, c[k])
end
end
end
else
local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a
for y = 0, 3 do
local row = o - y * stride
if lut then
for x = 0, 3 do
writeu32(px, (row + x) * 4, v)
end
else
writeu32(px, row, v * 0x01010101)
end
end
end
total -= 1
end
end
return true, nil
end
return Msvideo1
@@ -0,0 +1,115 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame
-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette,
-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past
-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication
-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in formats-luau.
local Types = require("@formats/Types")
local Pixels = require("@formats/codecs/image/Pixels")
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local Picture = {}
export type Picture = {
w: number,
h: number,
stride: number, -- index plane: bytes per row; rgba plane: pixels per row
rows: number,
idx: buffer?, -- u8 index plane, stride * rows bytes (palettised)
rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour)
pal: buffer, -- 256 u32 entries, bytes R, G, B, A
}
-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...)
function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture
local pw, ph = padW or 1, padH or 1
local stride = ((w + pw - 1) // pw) * pw
local rows = ((h + ph - 1) // ph) * ph
local pal = buffer.create(1024)
if palette and buffer.len(palette) >= 1024 then
buffer.copy(pal, 0, palette, 0, 1024)
end
local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal }
if palettised then
p.idx = buffer.create(stride * rows)
else
p.rgba = buffer.create(stride * rows * 4)
end
return p
end
-- image(p) -> a fresh rgba8 Image of the visible w x h
function Picture.image(p: Picture): Types.Image
local w, h = p.w, p.h
local img = Types.Image.new(w, h, "rgba8")
local idx, rgba = p.idx, p.rgba
if idx then
Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal)
elseif rgba then
if p.stride == w then
buffer.copy(img.pixels, 0, rgba, 0, w * h * 4)
else
for y = 0, h - 1 do
buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4)
end
end
end
return img
end
-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track
function Picture.setPalette(p: Picture, src: buffer)
if buffer.len(src) >= 1024 then
buffer.copy(p.pal, 0, src, 0, 1024)
end
end
local lut555: buffer? = nil
local lut565: buffer? = nil
-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries
function Picture.rgb555(): buffer
local t = lut555
if t then
return t
end
local b = buffer.create(32768 * 4)
for v = 0, 32767 do
local r, g, bl = v // 1024, (v // 32) % 32, v % 32
r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4
writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000)
end
lut555 = b
return b
end
-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries
function Picture.rgb565(): buffer
local t = lut565
if t then
return t
end
local b = buffer.create(65536 * 4)
for v = 0, 65535 do
local r, g, bl = v // 2048, (v // 32) % 64, v % 32
r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4
writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000)
end
lut565 = b
return b
end
-- copy of a picture's plane (for decoders that read the previous picture while writing the next)
function Picture.clonePlane(p: Picture): buffer
local src = (p.idx or p.rgba) :: buffer
local c = buffer.create(buffer.len(src))
buffer.copy(c, 0, src, 0)
return c
end
local _ = readu32
return Picture
+276
View File
@@ -0,0 +1,276 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and
-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File
-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per
-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups).
-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its
-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames
-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read
-- and write is range-checked (a damaged frame stops where the damage is).
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local QtRle = {}
local function s8(v: number): number
return if v >= 128 then v - 256 else v
end
-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line)
local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number)
row -= stride
local q = row
lines += 1
while lines > 0 do
if p + 2 > n then
return
end
local skip = readu8(d, p)
local code = s8(readu8(d, p + 1))
p += 2
if code == 0 then
return
end
if skip >= 128 then
lines -= 1
row += stride
q = row + 16 * (skip - 128)
else
q += 16 * skip
end
if q < 0 or q > limit then
return
end
if code ~= -1 then
if code < 0 then
local cnt = -code
if p + 2 > n or q + cnt * 16 > limit then
return
end
local a, b = readu8(d, p), readu8(d, p + 1)
p += 2
for _ = 1, cnt do
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(a, k), 1))
q += 1
end
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(b, k), 1))
q += 1
end
end
else
local cnt = code * 2
if p + cnt > n or q + cnt * 8 > limit then
return
end
for _ = 1, cnt do
local a = readu8(d, p)
p += 1
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(a, k), 1))
q += 1
end
end
end
end
end
end
-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups
local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number)
local group = 32 // bpp -- pixels per 4 bytes
local per = 8 // bpp -- pixels per byte
local mask = 2 ^ bpp - 1
for _ = 1, lines do
if p >= n then
return
end
local q = row + group * (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
while true do
if p >= n then
return
end
local code = s8(readu8(d, p))
p += 1
if code == -1 then
break
end
if p >= n then
return
end
if code == 0 then
q += group * (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
elseif code < 0 then
local cnt = -code
if p + 4 > n or q + cnt * group > limit then
return
end
if bpp == 8 then
local v = readu32(d, p)
for _ = 1, cnt do
writeu32(px, q, v)
q += 4
end
else
local v0 = q
for b = 0, 3 do
local byte = readu8(d, p + b)
for k = per - 1, 0, -1 do
writeu8(px, q, band(rshift(byte, k * bpp), mask))
q += 1
end
end
for _ = 2, cnt do
buffer.copy(px, q, px, v0, group)
q += group
end
end
p += 4
else
local bytes = code * 4
if p + bytes > n or q + bytes * per > limit then
return
end
if bpp == 8 then
buffer.copy(px, q, d, p, bytes)
q += bytes
else
for b = 0, bytes - 1 do
local byte = readu8(d, p + b)
for k = per - 1, 0, -1 do
writeu8(px, q, band(rshift(byte, k * bpp), mask))
q += 1
end
end
end
p += bytes
end
end
row += stride
end
end
-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels)
local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number)
local bpp = depth // 8
local lut = if depth == 16 then Picture.rgb555() else nil
for _ = 1, lines do
if p >= n then
return
end
local q = row + (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
while true do
if p >= n then
return
end
local code = s8(readu8(d, p))
p += 1
if code == -1 then
break
end
if p >= n then
return
end
if code == 0 then
q += readu8(d, p) - 1
p += 1
if q < 0 or q > limit then
return
end
else
local cnt = if code < 0 then -code else code
local need = if code < 0 then bpp else bpp * cnt
if p + need > n or q + cnt > limit then
return
end
for _ = 1, cnt do
local v
if lut then
v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4)
elseif bpp == 3 then
v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000
else
v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216
end
writeu32(px, q * 4, v)
q += 1
if code > 0 then
p += bpp
end
end
if code < 0 then
p += bpp
end
end
end
row += stride
end
end
-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message
function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?)
local n = buffer.len(d)
if n < 8 then
return true, nil -- no change
end
local p = 4
local header = readu8(d, p) * 256 + readu8(d, p + 1)
p += 2
local h = pic.h
local start, lines = 0, h
if band(header, 8) ~= 0 then
if n < 14 then
return true, nil
end
start = readu8(d, p) * 256 + readu8(d, p + 1)
lines = readu8(d, p + 4) * 256 + readu8(d, p + 5)
p += 8
if lines > h - start then
return true, nil
end
end
local stride = pic.stride
local bits = if depth > 32 then depth - 32 else depth
local idx, rgba = pic.idx, pic.rgba
if idx and bits <= 8 then
local limit = stride * h
if bits == 1 then
decode1(idx, stride, limit, d, p, n, start * stride, lines)
else
decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits)
end
elseif rgba and (bits == 16 or bits == 24 or bits == 32) then
decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits)
else
return false, "unsupported: depth " .. depth
end
return true, nil
end
-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs
function QtRle.palettised(depth: number): boolean
return depth <= 8 or depth > 32
end
function QtRle.pad(depth: number): number
local bits = if depth > 32 then depth - 32 else depth
return if bits <= 8 then 32 // math.max(1, bits) else 1
end
return QtRle
@@ -0,0 +1,405 @@
--!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); the frame decoder reads
-- 10 bits at a time through a lookup table into them.
-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give
-- zero bits, a frame whose codes run out of bits gives no picture.
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, 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 }, lut: buffer? } -- last: the escape leaves' indexes (1-based)
-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries)
local function bigTree(br: Bits, size: number): (BigTree?, string?)
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
local LUT_BITS = 10
-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits
local function lut(vals: { number }): buffer
local size = 2 ^ LUT_BITS
local t = buffer.create(size * 4)
for pat = 0, size - 1 do
local i, len = 1, 0
local e = vals[1]
while e < 0 and len < LUT_BITS do
if band(rshift(pat, len), 1) == 1 then
i += -e - 1
end
i += 1
len += 1
e = vals[i]
end
writeu32(t, pat * 4, i * 32 + len)
end
return t
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
for _, t in { mmap, mclr, full, typ } do
reset(t)
if not t.lut then
t.lut = lut(t.vals)
end
end
local n = buffer.len(d)
local nbits = n * 8
local pos = 0
-- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree
local function code(t: BigTree): number
local vals = t.vals
local i, p
local byte = rshift(pos, 3)
if byte + 3 <= n then
local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023)
local ent = readu32(t.lut :: buffer, v * 4)
i = rshift(ent, 5)
p = pos + band(ent, 31)
else
i, p = 1, pos
end
local e = vals[i]
while e < 0 do
if p >= nbits then
return -1
end
if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then
i += -e - 1
end
p += 1
i += 1
e = vals[i]
end
pos = p
local last = t.last
local l0 = last[1]
if e ~= vals[l0] then
local l1 = last[2]
vals[last[3]] = vals[l1]
vals[l1] = vals[l0]
vals[l0] = e
end
return e
end
local function bit(): number
local p = pos
pos = p + 1
if p >= nbits then
return 0
end
return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1)
end
local bw, bh = pic.w // 4, pic.h // 4
local blocks = bw * bh
local blk = 0
while blk < blocks do
local ty = code(typ)
if ty < 0 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)
local map = code(mmap)
if clr < 0 or map < 0 then
return false, "truncated frame"
end
local hi, lo = rshift(clr, 8), band(clr, 255)
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 pos >= nbits then
return false, "truncated frame"
end
if bit() == 1 then
mode = 1
elseif bit() == 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)
local b = code(full)
if a < 0 or b < 0 then
return false, "truncated frame"
end
-- the first code is the right pixel pair, the second the left one
writeu32(px, o + r * stride, b + a * 65536)
end
elseif mode == 1 then
for half = 0, 1 do
local a = code(full)
if a < 0 then
return false, "truncated frame"
end
local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000
writeu32(px, o + half * 2 * stride, v)
writeu32(px, o + (half * 2 + 1) * stride, v)
end
else
for half = 0, 1 do
local p2 = code(full)
local p1 = code(full)
if p1 < 0 or p2 < 0 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
+183
View File
@@ -0,0 +1,183 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description
-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble
-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour
-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index:
-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc
-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row
-- above). Never throws: reads past the data give zeros, the block count bounds every write.
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local Smc = {}
-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames)
function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?)
local px = pic.idx :: buffer
local n = buffer.len(d)
local stride = pic.stride -- a multiple of 4: the plane holds whole blocks
local bh = pic.rows // 4
local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4)
if total // 1024 > n then
return false, "frame too small"
end
local blocksWide = (pic.w + 3) // 4
local p = 4 -- flags byte + 24-bit chunk size
-- block position: bx, by (blocks)
local bx, by = 0, 0
local pairI, quadI, octI = 0, 0, 0
-- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8)
local function u8(): number
if p < n then
local v = readu8(d, p)
p += 1
return v
end
return 0
end
local function advance()
bx += 1
if bx >= blocksWide then
bx = 0
by += 1
end
total -= 1
end
while total > 0 do
if p >= n then
return false, "truncated"
end
local op = readu8(d, p)
p += 1
local kind = rshift(op, 4)
local count: number
if kind < 8 then
count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15)
else
count = band(op, 15) + 1
end
if kind <= 1 then
for _ = 1, count do
if total <= 0 then
break
end
advance()
end
elseif kind <= 5 then
-- repeat the last block (2, 3) or the last pair of blocks (4, 5)
local pair = kind >= 4
local back = if pair then 2 else 1
local pos = by * blocksWide + bx
if pos < back then
return false, "repeat before any block"
end
local reps = if pair then count * 2 else count
local srcA = pos - back
local srcB = pos - 1
for k = 0, reps - 1 do
if total <= 0 or by >= bh then
break
end
local s = if pair and k % 2 == 1 then srcB else srcA
local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4
local o, so = by * 4 * stride + bx * 4, sy * stride + sx
for r = 0, 3 do
writeu32(px, o + r * stride, readu32(px, so + r * stride))
end
advance()
end
elseif kind <= 7 then
local c = u8()
local v = c * 0x01010101
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
for r = 0, 3 do
writeu32(px, o + r * stride, v)
end
advance()
end
elseif kind <= 13 then
-- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds)
local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8
local base = if size == 2 then 0 elseif size == 4 then 512 else 1536
local entry: number
if kind % 2 == 0 then
local i = if size == 2 then pairI elseif size == 4 then quadI else octI
for k = 0, size - 1 do
writeu8(tables, base + i * size + k, u8())
end
entry = i
i = (i + 1) % 256
if size == 2 then
pairI = i
elseif size == 4 then
quadI = i
else
octI = i
end
else
entry = u8()
end
local t = base + entry * size
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
if size == 2 then
local f = u8() * 256 + u8()
for k = 0, 15 do
local bit = band(rshift(f, 15 - k), 1)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit))
end
elseif size == 4 then
local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8()
for k = 0, 15 do
local i = band(rshift(f, 30 - 2 * k), 3)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i))
end
else
-- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel)
local v1 = u8() * 256 + u8()
local v2 = u8() * 256 + u8()
local v3 = u8() * 256 + u8()
local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4)
local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15)
for k = 0, 15 do
local f = if k < 8 then fa else fb
local i = band(rshift(f, 21 - 3 * (k % 8)), 7)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i))
end
end
advance()
end
else
-- 16-colour blocks
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
for k = 0, 15 do
writeu8(px, o + (k // 4) * stride + k % 4, u8())
end
advance()
end
end
end
return true, nil
end
-- tables() -> the colour group scratch (pairs, quads, octets)
function Smc.tables(): buffer
return buffer.create(512 + 1024 + 2048)
end
return Smc
+214
View File
@@ -0,0 +1,214 @@
--!strict
-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk
-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak",
-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation
-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), 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.
--
-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the
-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that
-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth).
--
-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder
-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
--
-- Never throws: bad tracks return nil, Err; bad packets return Err from decode().
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Picture = require("@formats/codecs/video/Legacy/Picture")
local Flic = require("@formats/codecs/video/Legacy/Flic")
local Cinepak = require("@formats/codecs/video/Legacy/Cinepak")
local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1")
local QtRle = require("@formats/codecs/video/Legacy/QtRle")
local Smc = require("@formats/codecs/video/Legacy/Smc")
local Smacker = require("@formats/codecs/video/Legacy/Smacker")
local Legacy = {}
Legacy.Picture = Picture
Legacy.Flic = Flic
Legacy.Cinepak = Cinepak
Legacy.Msvideo1 = Msvideo1
Legacy.QtRle = QtRle
Legacy.Smc = Smc
Legacy.Smacker = Smacker
Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
export type Options = {
maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26)
[string]: any,
}
-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err?
type Codec = {
make: (track: Types.Track) -> (any, string?),
step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?),
}
local function fail(msg: string?): Err.Err
return Err.from(msg or "corrupt frame")
end
local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean
local pal = (packet :: any).palette
if type(pal) == "buffer" then
Picture.setPalette(pic, pal)
return true
end
return false
end
local CODECS: { [string]: Codec } = {
qtrle = {
make = function(t)
local depth = t.bitsPerPixel or 24
local bits = if depth > 32 then depth - 32 else depth
if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then
return nil, "unsupported: depth " .. depth
end
return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
local ok, msg = QtRle.decode(st.pic, data, st.depth)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
smc = {
make = function(t)
return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
local ok, msg = Smc.decode(st.pic, data, st.tables)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
msvideo1 = {
make = function(t)
if (t.width :: number) < 4 or (t.height :: number) < 4 then
return nil, "smaller than one block"
end
local bits = if t.bitsPerPixel == 8 then 8 else 16
return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil
end,
step = function(st, data, packet)
if st.bits == 8 then
packetPalette(st.pic, packet)
end
local ok, msg = Msvideo1.decode(st.pic, data, st.bits)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
cinepak = {
make = function(t)
local pal = t.bitsPerPixel == 8
return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil
end,
step = function(st, data, packet)
local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet)
local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal)
if not ok then
return nil, if msg then fail(msg) else nil
end
return Picture.image(st.pic), nil
end,
},
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)
end,
step = function(st, data, _packet)
local ok, msg = Flic.decode(st, data)
if not ok then
return nil, fail(msg)
end
return Flic.image(st), nil
end,
},
}
-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err
function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?)
local codec = CODECS[id]
if not codec then
return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id))
end
local w, h = track.width or 0, track.height or 0
if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then
return nil, Err.new(Err.CORRUPT, "video track without a valid size")
end
local max = (opts and opts.maxPixels) or 2 ^ 26
if w * h > max or w > 32768 or h > 32768 then
return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit")
end
local st, msg = codec.make(track)
if not st then
return nil, fail(msg)
end
-- Video.simpleDecoder, without requiring the registry (which requires this module)
local queue: { any } = {}
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, img, err = pcall(codec.step, st, packet.data, packet)
if not ok then
return Err.new(Err.CORRUPT, "decoder failed: " .. tostring(img))
end
if img then
table.insert(queue, { img, packet.pts, packet.keyframe })
end
return err
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil, nil, nil
end
function self.flush(_: any) end
function self.reset(_: any)
table.clear(queue)
st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe)
end
return self :: any, nil
end
return Legacy
+14
View File
@@ -260,6 +260,13 @@ local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecD
return Theora.newVideoDecoder(track, opts)
end
-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy)
local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?)
return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
return require("@formats/codecs/video/Legacy").newDecoder(id, track, opts)
end
end
-- ------------------------------------------------------------------------------------------------ registry
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
local BUILTIN: { Entry } = {
@@ -275,6 +282,13 @@ local BUILTIN: { Entry } = {
{ id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } },
{ id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
-- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette)
{ id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") },
{ id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") },
{ id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") },
{ id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") },
{ id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") },
{ id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") },
}
local byId: { [string]: Entry } = {}
+47
View File
@@ -9,6 +9,7 @@
-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf
-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute
-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish()
-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW)
--
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
local Err = require("@formats/core/Err")
@@ -520,4 +521,50 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
return w:finish()
end
-- ------------------------------------------------------------------------------------------------ BITMAPINFO
export type BitmapInfo = {
width: number,
height: number, -- signed: > 0 = bottom-up rows
bits: number, -- biBitCount
compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB)
palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0
extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none
}
-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) |
-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries;
-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it.
function Avi.bitmapInfo(f: buffer): BitmapInfo?
local n = buffer.len(f)
if n < 40 then
return nil
end
local bits = readu16(f, 14)
local info: BitmapInfo = {
width = buffer.readi32(f, 4),
height = buffer.readi32(f, 8),
bits = bits,
compression = readstring(f, 16, 4),
}
if n > 40 then
local e = buffer.create(n - 40)
buffer.copy(e, 0, f, 40)
info.extra = e
if bits >= 1 and bits <= 8 then
local count = math.min(2 ^ bits, (n - 40) // 4)
local at = n - count * 4
if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then
at -= 9
end
local pal = buffer.create(1024)
for i = 0, count - 1 do
local o = at + i * 4
buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000)
end
info.palette = pal
end
end
return info
end
return Avi
+14
View File
@@ -8,9 +8,14 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local QtPalette = require("@formats/containers/IsoBmff/QtPalette")
local readstring = buffer.readstring
local function readu16be(b: buffer, o: number): number
return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
end
local Demux = {}
export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty)
@@ -33,6 +38,8 @@ export type Track = {
channels: number?,
bitsPerSample: number?,
config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...)
bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...)
palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF)
objectType: number?, -- esds objectTypeIndication
pcm: { bits: number, float: boolean, little: boolean }?,
entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...)
@@ -194,6 +201,13 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
t.height = r:u16be()
r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2)
childStart = r.pos
-- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...)
local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ)
t.bitsPerPixel = depth
t.palette = pal
if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then
childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8)
end
else
childStart = r.pos
end
@@ -0,0 +1,120 @@
--!strict
-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime
-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0).
-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1,
-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey
-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the
-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps).
--
-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec)
-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil
--
-- Never throws.
local readu8, writeu32 = buffer.readu8, buffer.writeu32
local function readu16(b: buffer, o: number): number -- big-endian
return readu8(b, o) * 256 + readu8(b, o + 1)
end
local function readu32(b: buffer, o: number): number
return readu16(b, o) * 65536 + readu16(b, o + 2)
end
local QtPalette = {}
local function rgb(r: number, g: number, b: number): number
return r + g * 256 + b * 65536 + 0xFF000000
end
-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette)
local SMALL: { [number]: { number } } = {
[1] = { 0xFFFFFF, 0x000000 },
[2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 },
[4] = {
0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA,
0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000,
},
}
local function defaultTable(bits: number): buffer
local pal = buffer.create(1024)
local small = SMALL[bits]
if small then
for i, c in small do
writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256))
end
return pal
end
local i = 0
for r = 5, 0, -1 do
for g = 5, 0, -1 do
for b = 5, 0, -1 do
if i < 215 then
writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51))
end
i += 1
end
end
end
-- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black
local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 }
i = 215
for ch = 0, 3 do
for _, v in RAMP do
local r = if ch == 0 or ch == 3 then v else 0
local g = if ch == 1 or ch == 3 then v else 0
local b = if ch == 2 or ch == 3 then v else 0
writeu32(pal, i * 4, rgb(r, g, b))
i += 1
end
end
writeu32(pal, 255 * 4, rgb(0, 0, 0))
return pal
end
-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size
-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it.
function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?)
if start + 86 > stop or stop > buffer.len(b) then
return nil, nil
end
local raw = readu16(b, start + 82)
local id = readu16(b, start + 84)
local bits = raw % 32
local grey = raw >= 32 and (raw // 32) % 2 == 1
if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then
return raw, nil
end
if grey and codec == "cinepak" then
return raw, nil
end
if grey and bits > 1 and id ~= 0 then
local pal = buffer.create(1024)
local count = 2 ^ bits
local step = 256 // (count - 1)
local v = 255
for i = 0, count - 1 do
writeu32(pal, i * 4, rgb(v, v, v))
v = math.max(0, v - step)
end
return bits, pal
elseif id ~= 0 then
return bits, defaultTable(bits)
end
local pal = buffer.create(1024)
if start + 94 <= stop then
local first = readu32(b, start + 86)
local last = readu16(b, start + 92)
if first <= 255 and last <= 255 then
for i = first, last do
local o = start + 94 + (i - first) * 8
if o + 8 > stop then
break
end
writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6)))
end
end
end
return bits, pal
end
return QtPalette
+4
View File
@@ -110,6 +110,10 @@ local function videoTrack(s: Avi.Stream, id: number): Types.Track
t.pixelFormat = "yuv420p"
end
end
local bi = Avi.bitmapInfo(f)
if bi and bi.palette then
t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...)
end
local size = buffer.readu32(f, 0)
if size > 40 and buffer.len(f) > 40 then
local c = buffer.create(buffer.len(f) - 40)
+157
View File
@@ -0,0 +1,157 @@
--!strict
-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in formats-luau, written from the FLIC
-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC").
-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24:
-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped,
-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8
-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the
-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer.
-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/video/Video")
-- ------------------------------------------------------------------------------------------------ contract
local Fli = {
name = "fli",
category = "video",
extensions = { "fli", "flc", "flx" },
mime = { "video/x-fli", "video/fli", "video/x-flc" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- (frames are rgba8 already)
maxPixels: number?, -- default 2^26
ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does)
}
-- ------------------------------------------------------------------------------------------------ constants
local HEADER = 128
local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44
local FRAME, FRAME2 = 0xF1FA, 0xF5FA
-- ------------------------------------------------------------------------------------------------ sniff
function Fli.sniff(r: Bytes.Reader): number
local s = r:peek(18)
if #s < 18 then
return 0
end
local magic = string.byte(s, 5) + string.byte(s, 6) * 256
if magic ~= FLI and magic ~= FLC and magic ~= DTA then
return 0
end
local w = string.byte(s, 9) + string.byte(s, 10) * 256
local h = string.byte(s, 11) + string.byte(s, 12) * 256
if w > 4096 or h > 4096 then
return 0
end
return 0.9
end
-- ------------------------------------------------------------------------------------------------ decode
-- demux(r, opts?) -> the Demuxer | nil, Err
function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
local n = limit - base
if n < HEADER then
return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header")
end
local hr = Bytes.reader(b, base, HEADER)
hr:skip(4)
local magic = hr:u16le()
local frames = hr:u16le()
local w, h = hr:u16le(), hr:u16le()
local depth = hr:u16le()
hr:skip(2)
local speed = hr:u32le()
if hr.err then
return nil, hr.err
end
if magic ~= FLI and magic ~= FLC and magic ~= DTA then
return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4)
end
if magic == FLI then
speed = speed % 65536
end
if w == 0 or h == 0 then
return nil, Err.new(Err.CORRUPT, "no picture size")
end
local max = (opts and opts.maxPixels) or 2 ^ 26
if w * h > max then
return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels")
end
if magic == FLI or depth == 0 then
depth = 8
elseif magic == FLC and depth == 16 then
depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels
end
if speed == 0 then
speed = 5
end
local scale = if magic == FLI then 70 else 1000
local track: Types.Track = {
id = 1,
kind = "video",
codec = "flic",
codecTag = string.format("0x%04X", magic),
timescale = scale,
width = w,
height = h,
frameRate = scale / speed,
default = true,
bitsPerPixel = depth,
}
-- the frame chunks
local offs, sizes = {}, {}
local p = base + HEADER
while p + 6 <= limit do
local size = buffer.readu32(b, p)
local cm = buffer.readu16(b, p + 4)
if size < 6 then
break
end
if (cm == FRAME or cm == FRAME2) and size > 6 then
if p + size > limit then
break -- a truncated last frame
end
table.insert(offs, p)
table.insert(sizes, size)
end
p += size
end
local count = #offs
if frames > 0 and count > frames and not (opts and opts.ringFrame) then
count = frames -- the ring frame is not a frame of the animation
end
local dmx = Demux.new("fli", { track }, b, {
type = magic,
frames = frames,
depth = depth,
speed = speed,
ringFrame = #offs > frames and frames > 0,
})
for i = 1, count do
dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i])
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder | nil, Err
function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Fli.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts :: Video.OpenOptions?)
end
return Fli
+39
View File
@@ -9,6 +9,8 @@ local Types = require("@formats/Types")
local Ebml = require("@formats/containers/Ebml")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/video/Video")
local Avi = require("@formats/containers/Avi")
local QtPalette = require("@formats/containers/IsoBmff/QtPalette")
local Deflate = require("@formats/codecs/compress/Deflate")
local Parse = {}
@@ -152,6 +154,39 @@ local function codecFor(id: string, kind: string, bits: number?): string
end
Parse.codecFor = codecFor
-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample
-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata
local function vfwOrQuickTime(t: any, codecId: string, priv: buffer)
local n = buffer.len(priv)
if codecId == "V_MS/VFW/FOURCC" then
local bi = Avi.bitmapInfo(priv)
if bi then
t.codec = Video.fromFourcc(bi.compression) or t.codec
t.codecTag = bi.compression
t.bitsPerPixel = bi.bits
t.palette = bi.palette
t.config = bi.extra
end
elseif codecId == "V_QUICKTIME" and n >= 21 then
local desc = priv
if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then
desc = buffer.create(n + 4)
local size = n + 4
buffer.writeu8(desc, 0, size // 16777216 % 256)
buffer.writeu8(desc, 1, size // 65536 % 256)
buffer.writeu8(desc, 2, size // 256 % 256)
buffer.writeu8(desc, 3, size % 256)
buffer.copy(desc, 4, priv, 0, n)
end
local fcc = buffer.readstring(desc, 4, 4)
t.codec = Video.fromFourcc(fcc) or t.codec
t.codecTag = fcc
local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec)
t.bitsPerPixel = depth
t.palette = pal
end
end
type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? }
local function parseVideo(buf: buffer, off: number, len: number, t: any)
@@ -278,6 +313,10 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe
t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data"
t.codecTag = codecId
t.codec = codecFor(codecId, t.kind, t.bitsPerSample)
local cfg: buffer? = t.config
if t.kind == "video" and cfg then
vfwOrQuickTime(t, codecId, cfg)
end
if t.kind == "audio" then
t.sampleRate = t.sampleRate or 8000
t.channels = t.channels or 1
+2 -2
View File
@@ -27,8 +27,8 @@ local Mkv = {
category = "video",
extensions = { "mkv", "webm", "mka", "mk3d" },
mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true },
}
-- ------------------------------------------------------------------------------------------------ types
+2
View File
@@ -133,6 +133,8 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
bitsPerSample = it.bitsPerSample,
config = it.config,
default = true,
bitsPerPixel = it.bitsPerPixel,
palette = it.palette,
}
if it.kind == "video" then
if not Video.entry(t.codec) then
+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
+113
View File
@@ -0,0 +1,113 @@
-- codecs/video/Legacy tests: Cinepak (24-bit, grey, 8-bit palettised, several strips, a 92x68 size), Microsoft Video 1
-- (16-bit, 8-bit with an AVI palette), QuickTime RLE (depths 1 / 2 / 4 / 8 with colour tables, default Macintosh
-- tables and grey ramps; 16 / 24 / 32-bit and grey from ffmpeg) and QuickTime SMC, in AVI, MOV and MKV: every frame
-- equals ffmpeg's decode (CRC-32 of rgba); seeking; the registry entries; the fuzz pass on each codec's packet decoder.
-- Fixtures: tools/fixtures/legacy.py.
local T = require("@tests/T")
local F = require("@formats")
local Crc32 = require("@formats/core/Crc32")
local Video = require("@formats/codecs/video/Video")
local Legacy = require("@formats/codecs/video/Legacy")
local Fx = require("@tests/gen/legacy_cases")
local t = T.suite("legacy")
-- the registry
t:eq(Video.fromFourcc("cvid"), "cinepak", "cvid")
t:eq(Video.fromFourcc("CRAM"), "msvideo1", "CRAM")
t:eq(Video.fromFourcc("msvc"), "msvideo1", "msvc")
t:eq(Video.fromFourcc("rle "), "qtrle", "rle ")
t:eq(Video.fromFourcc("smc "), "smc", "smc ")
for _, id in Legacy.CODECS do
t:check(Video.canDecode(id), id .. ": decodable")
end
local samples: { [string]: { any } } = {}
for _, c in Fx do
local label = c.name
local v, err = F.video.open(c.data)
t:check(v ~= nil, label .. ": open: " .. tostring(err))
if v then
t:eq(v.codec, c.codec, label .. ": codec")
t:eq(v.width, c.width, label .. ": width")
local n, bad, first = 0, 0, nil
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": decode error " .. tostring(ferr))
break
end
n += 1
local img = f.image
if img.format ~= "rgba8" or img.width ~= c.width or Crc32.of(img.pixels) ~= c.frames[n] then
bad += 1
first = first or n
end
end
t:check(n == #c.frames and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ, first %s)", label, n - bad, #c.frames, bad, tostring(first)))
-- seeking: back to the start, the first frame again
v:seek(0)
local f = v:nextFrame()
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[1], label .. ": seek(0)")
-- packets for the fuzz pass
local dmx = v.demuxer
local tr = dmx:track("video")
if not samples[c.codec] then
local list = {}
for k = 1, math.min(3, dmx:count(tr.id)) do
table.insert(list, dmx:get(tr.id, k).data)
end
samples[c.codec] = { track = tr, packets = list }
end
end
end
-- the fuzz pass on the native packet decoders (no pcall in between)
local P = Legacy.Picture
local raw: { [string]: (tr: any) -> (buffer) -> any } = {
cinepak = function(tr)
return function(b)
local pic = P.new(tr.width, tr.height, tr.bitsPerPixel == 8, 4, 4, tr.palette)
return Legacy.Cinepak.decode(pic, b, Legacy.Cinepak.state(), false)
end
end,
msvideo1 = function(tr)
return function(b)
local bits = if tr.bitsPerPixel == 8 then 8 else 16
return Legacy.Msvideo1.decode(P.new(tr.width, tr.height, bits == 8, 4, 4), b, bits)
end
end,
qtrle = function(tr)
return function(b)
local d = tr.bitsPerPixel or 24
for _, depth in { d, 1, 2, 4, 8, 16, 32 } do
Legacy.QtRle.decode(P.new(tr.width, tr.height, Legacy.QtRle.palettised(depth), Legacy.QtRle.pad(depth), 1), b, depth)
end
return true
end
end,
smc = function(tr)
return function(b)
return Legacy.Smc.decode(P.new(tr.width, tr.height, true, 4, 4), b, Legacy.Smc.tables())
end
end,
}
for id, s in samples do
local fn = raw[id]
if fn then
t:fuzz(id .. " packets", fn(s.track), s.packets, { mutations = 24, garbage = 60 })
end
end
t:fuzz("open", function(b: buffer)
local v = F.video.open(b)
if v then
for _ = 1, 3 do
if not v:nextFrame() then
break
end
end
end
return v
end, { Fx[1].data, Fx[#Fx].data }, { mutations = 8, garbage = 20 })
t:done()
+105
View File
@@ -0,0 +1,105 @@
-- video/fli tests: FLI (COLOR_64, BRUN, LC, BLACK, COPY, PSTAMP, a ring frame), FLC (prefix chunk, COLOR_256, SS2 with
-- line skips and the last-byte opcode, an empty frame), an odd-size FLC, and 15 / 16 / 24-bit FLCs (BRUN, DTA_BRUN,
-- DELTA, DTA_LC, COPY, DTA_COPY, BLACK), all encoded by the fixture script: every frame equals ffmpeg's decode
-- (CRC-32 of rgba), frame rates, the ring frame option, seeking, errors, the fuzz pass. Fixtures: tools/fixtures/fli.py.
local T = require("@tests/T")
local F = require("@formats")
local Fli = require("@formats/video/fli")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/fli_cases")
local t = T.suite("fli")
t:eq(Fli.name, "fli", "name")
t:eq(Fli.category, "video", "category")
local function reader(s: string): Bytes.Reader
return Bytes.reader(buffer.fromstring(s))
end
for _, c in Fx do
local label = c.name
t:check(Fli.sniff(reader(c.data)) > 0, label .. ": sniff")
t:eq(F.detect(buffer.fromstring(c.data)), "fli", label .. ": detect")
local v, err = F.video.open(buffer.fromstring(c.data))
t:check(v ~= nil, label .. ": open " .. tostring(err))
if v then
t:eq(v.codec, "flic", label .. ": codec")
t:check(v.width == c.width and v.height == c.height, label .. ": size")
t:check(math.abs(v.frameRate - c.rate) < 1e-9, label .. ": frame rate " .. v.frameRate)
t:eq(v.track.bitsPerPixel, c.depth, label .. ": depth")
local ring = v.demuxer.meta.ringFrame
local want = if ring then #c.frames - 1 else #c.frames
local n, bad = 0, 0
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": " .. tostring(ferr))
break
end
n += 1
if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then
bad += 1
end
end
t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad))
v:seek(0.25)
local f = v:nextFrame()
local k = math.floor(0.25 * c.rate + 1 - 1e-9) + 1
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k)
if ring then
local v2 = Fli.open(reader(c.data), { ringFrame = true })
local m = 0
while v2 and v2:nextFrame() do
m += 1
end
t:eq(m, #c.frames, label .. ": with the ring frame")
end
end
end
-- errors
do
local _, e = Fli.open(reader(string.sub(Fx[1].data, 1, 100)))
t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED")
local bad = Fx[1].data
bad = string.sub(bad, 1, 4) .. "\0\0" .. string.sub(bad, 7)
t:eq(Fli.sniff(reader(bad)), 0, "bad magic: no sniff")
local _, e2 = Fli.open(reader(bad))
t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT")
local big = string.sub(Fx[1].data, 1, 8) .. "\255\15\255\15" .. string.sub(Fx[1].data, 13)
local _, e3 = Fli.open(reader(big), { maxPixels = 2 ^ 20 })
t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT")
end
local samples = {}
for _, c in Fx do
table.insert(samples, c.data)
end
t:fuzz("open", function(b: buffer)
local v = Fli.open(Bytes.reader(b))
if v then
while v:nextFrame() do
end
end
return v
end, samples, { mutations = 12, garbage = 40, keepHeader = 16 })
-- the frame decoder itself (codecs/video/Legacy/Flic, native: no pcall in between)
local Flic = require("@formats/codecs/video/Legacy").Flic
for _, c in { Fx[1], Fx[2], Fx[4], Fx[6] } do
local d = Fli.demux(reader(c.data))
local packets = {}
for k = 1, math.min(4, d:count(1)) do
table.insert(packets, d:get(1, k).data)
end
t:fuzz(c.name .. " frames", function(b: buffer)
local st = Flic.state(c.width, c.height, c.depth)
if st then
Flic.decode(st, b)
return Flic.image(st)
end
return nil
end, packets, { mutations = 20, garbage = 30 })
end
t:done()
+180
View File
@@ -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()
+39
View File
@@ -1134,3 +1134,42 @@ do
jitTune(false)
end
end
-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps
do
-- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240
-- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks);
-- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second)
local F = require("@formats")
local LB = require("@tests/gen/legacy_bench")
local cases = table.clone(LB)
table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 })
table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 })
for _, c in cases do
local data = buffer.fromstring(c.data)
local frames = 0
local dt = math.huge
for _ = 1, 3 do
local t0 = os.clock()
local v = assert(F.video.open(data, { audio = false }))
frames = 0
while v:nextFrame() do
frames += 1
end
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt))
end
local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data)))
local a = assert(v.audio)
local t0 = os.clock()
local n = 0
while true do
local _, got = a:read(4096)
if got == 0 then
break
end
n += got
end
local dt = os.clock() - t0
print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt))
end
+375
View File
@@ -0,0 +1,375 @@
# Shared helpers for the legacy video fixture generators (legacy.py), loaded by path: tiny AVI and QuickTime MOV
# writers (one video track, constant frame rate) for streams encoded here, and small encoders for what ffmpeg cannot
# encode: QuickTime RLE at depths 1 / 2 / 4 / 8, Microsoft Video 1 at 8 bits, Cinepak at 8 bits (palettised).
import struct
def le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def be16(v):
return struct.pack(">H", v & 0xFFFF)
def be32(v):
return struct.pack(">I", v & 0xFFFFFFFF)
# ---------------------------------------------------------------------------------------------------- AVI
def _ck(cid, body):
return cid + le32(len(body)) + body + (b"\0" if len(body) & 1 else b"")
def _lst(kind, body):
return b"LIST" + le32(len(body) + 4) + kind + body
def bitmapinfo(w, h, bits, fourcc, palette=None):
"""BITMAPINFOHEADER (+ palette: a list of (r, g, b) stored as B, G, R, 0)"""
n = len(palette) if palette else 0
out = le32(40) + le32(w) + le32(h) + le16(1) + le16(bits) + fourcc + le32(w * h * max(1, bits // 8)) + \
le32(0) + le32(0) + le32(n) + le32(0)
for r, g, b in palette or []:
out += bytes([b, g, r, 0])
return out
def avi(w, h, fourcc, strf, frames, keys, fps=10):
"""an AVI file: one video stream, frames = [bytes], keys = [bool]"""
n = len(frames)
avih = le32(1000000 // fps) + le32(0) + le32(0) + le32(0x10) + le32(n) + le32(0) + le32(1) + \
le32(max(len(f) for f in frames)) + le32(w) + le32(h) + bytes(16)
strh = b"vids" + fourcc + le32(0) + le16(0) + le16(0) + le32(0) + le32(1) + le32(fps) + le32(0) + le32(n) + \
le32(max(len(f) for f in frames)) + struct.pack("<i", -1) + le32(0) + struct.pack("<hhhh", 0, 0, w, h)
hdrl = _lst(b"hdrl", _ck(b"avih", avih) + _lst(b"strl", _ck(b"strh", strh) + _ck(b"strf", strf)))
movi = b""
idx = b""
for f, k in zip(frames, keys):
idx += b"00dc" + le32(0x10 if k else 0) + le32(4 + len(movi)) + le32(len(f))
movi += _ck(b"00dc", f)
body = b"AVI " + hdrl + _lst(b"movi", movi) + _ck(b"idx1", idx)
return b"RIFF" + le32(len(body)) + body
# ---------------------------------------------------------------------------------------------------- MOV
def _box(t, body):
return be32(8 + len(body)) + t + body
def qt_entry(fourcc, w, h, depth, ctab_id=0xFFFF, colors=None):
"""a QuickTime video sample description; colors = [(r, g, b)] makes a colour table (ctab_id 0)"""
body = bytes(6) + be16(1) + be16(0) + be16(0) + b"appl" + be32(0) + be32(512) + be16(w) + be16(h) + \
be32(72 << 16) + be32(72 << 16) + be32(0) + be16(1) + bytes([4]) + b"test" + bytes(27) + be16(depth)
if colors is not None:
body += be16(0) + be32(0) + be16(0x8000) + be16(len(colors) - 1)
for i, (r, g, b) in enumerate(colors):
body += be16(i) + bytes([r, r, g, g, b, b])
else:
body += be16(ctab_id)
return _box(fourcc, body)
def mov(w, h, entry, frames, keys, fps=10):
"""a QuickTime file: one video track with the sample description `entry`"""
scale, delta = fps * 100, 100
n = len(frames)
ftyp = _box(b"ftyp", b"qt " + be32(0x200) + b"qt ")
mdat_off = len(ftyp) + 8
offs, pos = [], mdat_off
for f in frames:
offs.append(pos)
pos += len(f)
mdat = _box(b"mdat", b"".join(frames))
matrix = be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x40000000)
dur = n * delta
mvhd = _box(b"mvhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be32(0x10000) + be16(0x100) +
bytes(10) + matrix + bytes(24) + be32(2))
tkhd = _box(b"tkhd", be32(3) + be32(0) + be32(0) + be32(1) + be32(0) + be32(dur) + bytes(8) + be16(0) + be16(0) +
be16(0) + be16(0) + matrix + be32(w << 16) + be32(h << 16))
mdhd = _box(b"mdhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be16(0) + be16(0))
hdlr = _box(b"hdlr", be32(0) + b"mhlr" + b"vide" + bytes(12) + b"\x05Video")
vmhd = _box(b"vmhd", be32(1) + bytes(8))
dinf = _box(b"dinf", _box(b"dref", be32(0) + be32(1) + _box(b"alis", be32(1))))
stsd = _box(b"stsd", be32(0) + be32(1) + entry)
stts = _box(b"stts", be32(0) + be32(1) + be32(n) + be32(delta))
sync = [i + 1 for i, k in enumerate(keys) if k]
stss = _box(b"stss", be32(0) + be32(len(sync)) + b"".join(be32(i) for i in sync))
stsc = _box(b"stsc", be32(0) + be32(1) + be32(1) + be32(1) + be32(1))
stsz = _box(b"stsz", be32(0) + be32(0) + be32(n) + b"".join(be32(len(f)) for f in frames))
stco = _box(b"stco", be32(0) + be32(n) + b"".join(be32(o) for o in offs))
stbl = _box(b"stbl", stsd + stts + stss + stsc + stsz + stco)
minf = _box(b"minf", vmhd + dinf + stbl)
mdia = _box(b"mdia", mdhd + hdlr + minf)
trak = _box(b"trak", tkhd + mdia)
moov = _box(b"moov", mvhd + trak)
return ftyp + mdat + moov
# ---------------------------------------------------------------------------------------------------- pictures
def index_frames(w, h, n, colors, seed=1):
"""n palettised pictures (rows of indexes < colors): bands, a moving square, a noisy patch; most of each frame
stays the same as the previous one (inter-frame codecs get skips)"""
import random
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[((x // 7 + y // 5) % colors) for x in range(w)] for y in range(h)]
sx, sy = (t * 5) % max(1, w - 12), (t * 3) % max(1, h - 10)
for y in range(sy, min(h, sy + 10)):
for x in range(sx, min(w, sx + 12)):
img[y][x] = (t + 1) % colors
for y in range(h // 2, min(h, h // 2 + 6)):
for x in range(w // 3, min(w, w // 3 + 9)):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def palette(n, seed=7):
import random
rnd = random.Random(seed)
return [(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- QuickTime RLE
def _groups(row, per):
return [tuple(row[i:i + per]) for i in range(0, len(row), per)]
def _pack(group, bits):
out = bytearray()
per = 8 // bits
for i in range(0, len(group), per):
v = 0
for k in range(per):
v = (v << bits) | group[i + k]
out.append(v)
return bytes(out)
def qtrle_frame(img, prev, bits):
"""one 'rle ' frame at 1 / 2 / 4 / 8 bits (prev = the previous picture or None: changed line range only, with
skip codes inside lines)"""
h, w = len(img), len(img[0])
per = 16 if bits == 1 else 32 // bits # pixels per group
pw = (w + per - 1) // per * per
rows = [r + [0] * (pw - w) for r in img]
prow = [r + [0] * (pw - w) for r in prev] if prev else None
changed = [y for y in range(h) if not prow or rows[y] != prow[y]]
if not changed:
return be32(6) + be16(0)
y0, y1 = changed[0], changed[-1] + 1
body = bytearray()
for y in range(y0, y1):
g = _groups(rows[y], per)
pg = _groups(prow[y], per) if prow else None
if bits == 1:
# (skip, code) pairs: the first of a line has bit 7 set
first = True
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 127:
skip += 1
i += 1
if i >= len(g):
if first:
body += bytes([0x80 | skip, 0xFF])
first = False
break
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
sb = (0x80 if first else 0) | skip
first = False
if j > i:
body += bytes([sb, 256 - (j - i + 1)]) + _pack(g[i], 1)
i = j + 1
else:
k = i
while k < len(g) and k - i < 63 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
body += bytes([sb, k - i]) + b"".join(_pack(x, 1) for x in g[i:k])
i = k
if first:
body += bytes([0x80, 0xFF])
continue
line = bytearray([1])
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 250:
skip += 1
i += 1
if i >= len(g):
break
if skip:
line += bytes([0, skip + 1])
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
if j > i:
line += bytes([256 - (j - i + 1)]) + _pack(g[i], bits)
i = j + 1
else:
k = i
while k < len(g) and k - i < 127 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
line += bytes([k - i]) + b"".join(_pack(x, bits) for x in g[i:k])
i = k
line += b"\xff"
body += line
if bits == 1:
body += b"\x00\x00"
else:
body += b"\x00"
head = be16(8) + be16(y0) + be16(0) + be16(y1 - y0) + be16(0)
return be32(4 + len(head) + len(body)) + head + bytes(body)
# ---------------------------------------------------------------------------------------------------- MS Video 1
def _block(img, bx, by):
"""the 16 pixels of a block, MS Video 1 order: bottom row first, left to right"""
return [img[by * 4 + 3 - y][bx * 4 + x] for y in range(4) for x in range(4)]
def msvc8_frame(img, prev):
"""one 8-bit CRAM frame: skips for unchanged blocks, 1-colour, 2-colour or 8-colour blocks"""
h, w = len(img), len(img[0])
bw, bh = w // 4, h // 4
out = bytearray()
skip = 0
def flush():
nonlocal skip
while skip:
k = min(skip, 1023)
out.extend([k & 0xFF, 0x84 + (k >> 8)])
skip -= k
for by in range(bh - 1, -1, -1):
for bx in range(bw):
px = _block(img, bx, by)
if prev and px == _block(prev, bx, by):
skip += 1
continue
flush()
cols = sorted(set(px), key=lambda c: (-px.count(c), c))
if len(cols) == 1:
out.extend([px[0], 0x80])
elif len(cols) == 2:
c0 = px[15] # pixel 15's flag bit is 0: it takes colours[1]
c1 = cols[0] if cols[0] != c0 else cols[1]
flags = sum(1 << i for i in range(16) if px[i] == c1)
out.extend([flags & 0xFF, flags >> 8, c1, c0])
else:
# 8-colour: a pair per quadrant; pixel 12 and 15 take the first colour of their quadrant (flags >= 0x9000)
colours = [0] * 8
flags = 0
for q, (qx, qy) in enumerate([(0, 0), (2, 0), (0, 2), (2, 2)]):
ids = [(qy + y) * 4 + qx + x for y in range(2) for x in range(2)]
vals = [px[i] for i in ids]
key = {2: 12, 3: 15}.get(q)
a = px[key] if key is not None else sorted(set(vals), key=lambda c: (-vals.count(c), c))[0]
rest = [v for v in vals if v != a]
b = rest[0] if rest else a
base = ((qy & 2) << 1) + (qx & 2)
colours[base], colours[base + 1] = a, b
for i in ids:
if px[i] == a:
flags |= 1 << i
else:
px[i] = b
out.extend([flags & 0xFF, flags >> 8] + colours)
flush()
return bytes(out)
# ---------------------------------------------------------------------------------------------------- Cinepak (8-bit)
def cvid8_frame(img, prev, first):
"""one palettised Cinepak frame: one strip, a V1 codebook of 4-index entries (each a 2x2 square of one colour per
entry quarter) and a V4 codebook; blocks are V1 when their four 2x2 squares are uniform, else V4 (from the
codebook of 2x2 squares); inter frames skip unchanged blocks"""
h, w = len(img), len(img[0])
blocks = [(x, y) for y in range(0, h, 4) for x in range(0, w, 4)]
v1, v4 = {}, {}
def sq(x, y):
return (img[y][x], img[y][x + 1], img[y + 1][x], img[y + 1][x + 1])
plan = []
for (x, y) in blocks:
if prev is not None and all(img[y + j][x + i] == prev[y + j][x + i] for j in range(4) for i in range(4)):
plan.append(None)
continue
q = [sq(x, y), sq(x + 2, y), sq(x, y + 2), sq(x + 2, y + 2)]
if all(len(set(s)) == 1 for s in q) and len(v1) < 256:
e = (q[0][0], q[1][0], q[2][0], q[3][0])
v1.setdefault(e, len(v1))
plan.append(("v1", v1[e]))
else:
ids = []
for s in q:
if s not in v4 and len(v4) < 256:
v4[s] = len(v4)
ids.append(v4.get(s, 0))
plan.append(("v4", ids))
def book(cid, entries):
data = b"".join(bytes(e) for e, _ in sorted(entries.items(), key=lambda kv: kv[1]))
return bytes([cid]) + (4 + len(data)).to_bytes(3, "big") + data
chunks = b""
if v4:
chunks += book(0x24, v4)
if v1:
chunks += book(0x26, v1)
bits, data = [], bytearray()
inter = prev is not None
# flags (MSB first, 32 per word) are interleaved with the indexes in decode order
words = bytearray()
flagbuf = []
def flag(b):
flagbuf.append(b)
if len(flagbuf) == 1:
words.extend(b"FLAG") # placeholder, patched below
pos_stack.append(len(words) - 4)
if len(flagbuf) == 32:
patch()
pos_stack = []
def patch():
v = 0
for i, b in enumerate(flagbuf):
v |= b << (31 - i)
p = pos_stack.pop()
words[p:p + 4] = v.to_bytes(4, "big")
flagbuf.clear()
for item in plan:
if inter:
flag(0 if item is None else 1)
if item is None:
continue
flag(1 if item[0] == "v4" else 0)
if item[0] == "v1":
words.append(item[1])
else:
words.extend(item[1])
if flagbuf:
patch()
vid = (0x31 if inter else 0x30)
chunks += bytes([vid]) + (4 + len(words)).to_bytes(3, "big") + bytes(words)
strip = bytes([0x10 if first else 0x11]) + (12 + len(chunks)).to_bytes(3, "big") + be16(0) + be16(0) + be16(h) + \
be16(w) + chunks
size = 10 + len(strip)
return bytes([0]) + size.to_bytes(3, "big") + be16(w) + be16(h) + be16(1) + strip
+33
View File
@@ -0,0 +1,33 @@
# Docs inputs for the legacy video sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them):
# a 64x48 FLC (tools/fixtures/fli.py's encoder), a 64x48 SMK4 with a packed stereo and a raw mono audio track
# (tools/fixtures/smk.py's encoder) and a 64x48 Cinepak MOV from ffmpeg.
# tests/gen/docs_legacy.luau { files = { [name] = bytes }, vars = { flcBytes = "anim.flc", ... } }
import importlib.util, os, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/fli.py", "tools/fixtures/smk.py", "tools/fixtures/_video.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_legacy_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = load(ctx, "docs_check")
fli = load(ctx, "fixtures/fli")
smk = load(ctx, "fixtures/smk")
v = load(ctx, "fixtures/_video")
files = {}
w, h, n = 64, 48, 10
imgs = fli.idx_frames(w, h, n, 256, 5)
frames = [fli.frame([fli.color([(0, fli.pal(256, 5, False))], False), fli.brun([[bytes([x]) for x in r] for r in imgs[0]], 1, True)])]
frames += [fli.frame([fli.ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
files["anim.flc"] = fli.file(0xAF12, w, h, 8, 100, frames)
files["intro.smk"] = smk.smk_file(4, 64, 48, 10, 100, [("packed", 22050, 2, 16), ("raw", 11025, 1, 8)], False, 7)
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "cinepak.mov")
v.ffmpeg(["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "cinepak", out])
files["cinepak.mov"] = open(out, "rb").read()
dc.emit_inputs(ctx, files, {"flcBytes": "anim.flc", "smkBytes": "intro.smk", "cinepakBytes": "cinepak.mov"})
+401
View File
@@ -0,0 +1,401 @@
# FLI / FLC fixtures (tools/fixtures.py): ffmpeg cannot write FLICs, so this encodes them (every chunk type: COLOR_64,
# COLOR_256, BRUN, LC / DELTA_FLI, SS2 / DELTA_FLC with line skips and the last-byte opcode, BLACK, COPY, PSTAMP; a
# prefix chunk and a ring frame; 15-bit FLC, 16-bit DTA and 24-bit FLC with BRUN / DTA_BRUN / DELTA / DTA_LC / COPY /
# DTA_COPY) and uses ffmpeg's decode as the reference (CRC-32 of each frame as rgba).
# tests/gen/fli_cases.luau { { name, data, width, height, depth, rate, frames = { crc } } }
import importlib.util, os, random, struct, tempfile, zlib
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
V = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(V)
INPUTS = ["tools/fixtures/_video.py"]
def le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def s8(v):
return v & 0xFF
def chunk(typ, body):
if len(body) & 1:
body += b"\0"
return le32(6 + len(body)) + le16(typ) + body
def frame(chunks, magic=0xF1FA):
body = b"".join(chunks)
return le32(16 + len(body)) + le16(magic) + le16(len(chunks)) + bytes(8) + body
# ---------------------------------------------------------------------------------------------------- chunks
def color(entries, six):
"""COLOR_64 / COLOR_256: entries = [(skip, [(r, g, b), ...])]"""
out = le16(len(entries))
for skip, cols in entries:
out += bytes([skip, len(cols) & 0xFF])
for c in cols:
out += bytes(c)
return chunk(11 if six else 4, out)
def runs(seq, maxrun=127):
"""split a sequence into ('rep', value, n) and ('lit', [values]) pieces"""
out, i = [], 0
while i < len(seq):
j = i
while j + 1 < len(seq) and seq[j + 1] == seq[i] and j - i + 1 < maxrun:
j += 1
if j - i >= 2:
out.append(("rep", seq[i], j - i + 1))
i = j + 1
else:
k = i
while k < len(seq) and k - i < maxrun and not (k + 2 < len(seq) and seq[k] == seq[k + 1] == seq[k + 2]):
k += 1
k = max(k, i + 1)
out.append(("lit", seq[i:k]))
i = k
return out
def brun_line(units, unit_bytes):
"""BRUN line body: > 0 repeat, < 0 literal (units are byte strings of unit_bytes each)"""
out = bytes([0])
for p in runs(units):
if p[0] == "rep":
out += bytes([p[2]]) + p[1]
else:
out += bytes([s8(-len(p[1]))]) + b"".join(p[1])
return out
def brun(img, bpp, pixel_runs, typ=15):
lines = b""
for row in img:
if pixel_runs:
units = [row[x] for x in range(len(row))]
else:
flat = b"".join(row)
units = [flat[i:i + 1] for i in range(len(flat))]
lines += brun_line(units, bpp)
return chunk(typ, lines)
def lc(img, prev):
"""DELTA_FLI (LC): first changed line, line count, per line (skip, run) packets on bytes"""
h, w = len(img), len(img[0])
ch = [y for y in range(h) if img[y] != prev[y]]
if not ch:
return chunk(12, le16(0) + le16(0))
y0, y1 = ch[0], ch[-1] + 1
out = le16(y0) + le16(y1 - y0)
for y in range(y0, y1):
row, prow = img[y], prev[y]
packets = []
x = 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
seg = [bytes([v]) for v in row[x:e]]
pieces = runs(seg)
first = True
for p in pieces:
sk = skip if first else 0
first = False
if p[0] == "rep":
packets.append(bytes([sk, s8(-p[2])]) + p[1])
else:
packets.append(bytes([sk, len(p[1])]) + b"".join(p[1]))
x = e
out += bytes([len(packets)]) + b"".join(packets)
return chunk(12, out)
def ss2(img, prev, last_byte=False):
"""DELTA_FLC (SS2) on 8-bit pixels: word packets, line-skip words, the last-byte opcode on odd lines"""
h, w = len(img), len(img[0])
out = b""
count = 0
skip_lines = 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body = b""
packets = 0
lastop = last_byte and y % 2 == 1 and row[w - 1] != prow[w - 1]
ww = w - (1 if lastop else 0)
words = [bytes(row[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
pwords = [bytes(prow[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
i = 0
while i < len(words):
skip = 0
while i < len(words) and words[i] == pwords[i] and skip < 127:
skip += 1
i += 1
if i >= len(words):
break
e = i
while e < len(words) and words[e] != pwords[e] and e - i < 127:
e += 1
first = True
for p in runs(words[i:e]):
sk = skip * 2 if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
i = e
if lastop:
out += le16(0x8000 | row[w - 1])
out += le16(packets) + body
count += 1
return chunk(7, le16(count) + out)
def delta_deep(img, prev, bpp, typ=7):
"""DELTA / DTA_LC on 15/16/24-bit pixels: negative words skip lines, packets (skip pixels, run)"""
h, w = len(img), len(img[0])
out, count, skip_lines = b"", 0, 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body, packets, x = b"", 0, 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
first = True
for p in runs(row[x:e]):
sk = skip if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
x = e
out += le16(packets) + body
count += 1
return chunk(typ, le16(count) + out)
def copy8(img):
w = len(img[0])
pad = (w + 3) // 4 * 4 - w
return le32(6 + len(img) * (w + pad)) + le16(16) + b"".join(bytes(r) + bytes(pad) for r in img)
def copy_deep(img, bpp, typ=16):
w = len(img[0])
body = b"".join(b"".join(r) + (bytes(bpp) if w % 2 else b"") for r in img)
return le32(6 + len(body)) + le16(typ) + body
# ---------------------------------------------------------------------------------------------------- pictures
def idx_frames(w, h, n, colors, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[(x // 6 + y // 4 + (t // 4)) % colors for x in range(w)] for y in range(h)]
sx, sy = (t * 7) % (w - 16), (t * 3) % (h - 12)
for y in range(sy, sy + 12):
for x in range(sx, sx + 16):
img[y][x] = (200 + t) % colors
for y in range(h // 2, h // 2 + 4):
for x in range(w // 2, w // 2 + 10):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def deep_frames(w, h, n, bpp, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = []
for y in range(h):
row = []
for x in range(w):
v = ((x * 37 + y * 11 + t * 3) // 8) & 0x7FFF if bpp == 2 else ((x * 4) & 255, (y * 5) & 255, (t * 20) & 255)
if 10 + t <= x < 26 + t and 8 <= y < 20:
v = 0x7C00 if bpp == 2 else (250, 10, 10)
if bpp == 2 and h // 2 <= y < h // 2 + 3 and w // 2 <= x < w // 2 + 7:
v = rnd.randrange(65536)
row.append(struct.pack("<H", v) if bpp == 2 else bytes([v[2], v[1], v[0]]))
img.append(row)
out.append(img)
return out
def header(typ, frames, w, h, depth, speed, oframes=(0, 0)):
hd = bytearray(128)
hd[4:6] = le16(typ)
hd[6:8] = le16(frames)
hd[8:10] = le16(w)
hd[10:12] = le16(h)
hd[12:14] = le16(depth)
hd[14:16] = le16(3)
if typ == 0xAF11:
hd[16:18] = le16(speed)
else:
hd[16:20] = le32(speed)
hd[80:84] = le32(oframes[0])
hd[84:88] = le32(oframes[1])
return hd
def file(typ, w, h, depth, speed, frames, prefix=b"", nframes=None):
hd = header(typ, nframes if nframes is not None else len(frames), w, h, depth, speed)
body = prefix + b"".join(frames)
hd[0:4] = le32(128 + len(body))
if typ != 0xAF11 and frames:
hd[80:84] = le32(128 + len(prefix))
hd[84:88] = le32(128 + len(prefix) + len(frames[0]))
return bytes(hd) + body
def pal(n, seed, six):
rnd = random.Random(seed)
m = 64 if six else 256
return [(rnd.randrange(m), rnd.randrange(m), rnd.randrange(m)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- files
def fli_8():
"""FLI (AF11), 70 Hz jiffies: COLOR_64 + BRUN, LC deltas, a BLACK frame, a COPY frame, a palette change, PSTAMP"""
w, h, n = 80, 50, 10
imgs = idx_frames(w, h, n, 256, 1)
frames = [frame([color([(0, pal(256, 1, True))], True), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 4:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy8(imgs[t]), chunk(18, le16(10) + le16(6) + bytes(20))]))
elif t == 7:
frames.append(frame([color([(10, pal(20, 9, True)), (30, pal(5, 10, True))], True), lc(imgs[t], imgs[t - 1])]))
else:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
frames.append(frame([lc(imgs[0], imgs[-1])])) # the ring frame
return file(0xAF11, w, h, 8, 5, frames, nframes=n)
def flc_8():
"""FLC (AF12), ms: a prefix chunk, COLOR_256 + BRUN, SS2 deltas (line skips, last-byte opcode), COPY, BLACK, an
empty frame, COLOR_256 updates"""
w, h, n = 128, 64, 12
imgs = idx_frames(w, h, n, 256, 2)
frames = [frame([color([(0, pal(256, 2, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 3:
imgs[t] = imgs[t - 1]
frames.append(frame([]))
elif t == 6:
frames.append(frame([copy8(imgs[t])]))
elif t == 8:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b""), color([(0, pal(16, 3, False)), (100, pal(50, 4, False))], False)]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1], last_byte=True)]))
prefix = le32(16) + le16(0xF100) + le16(0) + bytes(8)
return file(0xAF12, w, h, 8, 66, frames, prefix=prefix)
def flc_8_odd():
"""FLC 8-bit at an odd size: BRUN, LC, SS2 without the last-byte opcode, COPY with padded rows"""
w, h, n = 61, 37, 6
imgs = idx_frames(w, h, n, 256, 3)
frames = [frame([color([(0, pal(256, 5, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 2:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
elif t == 4:
frames.append(frame([copy8(imgs[t])]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1])]))
return file(0xAF12, w, h, 8, 100, frames)
def flc_deep(typ, depth, bpp, w, h):
"""15 / 16 / 24-bit: BRUN (bytes) or DTA_BRUN (pixels), DELTA / DTA_LC, BLACK, COPY / DTA_COPY"""
n = 7
imgs = deep_frames(w, h, n, bpp, depth)
frames = [frame([brun(imgs[0], bpp, False)])]
for t in range(1, n):
if t == 2:
frames.append(frame([copy_deep(imgs[t], bpp, 16)]))
elif t == 3:
frames.append(frame([brun(imgs[t], bpp, True, 25)]))
elif t == 4:
imgs[t] = [[bytes(bpp)] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy_deep(imgs[t], bpp, 26)]))
else:
frames.append(frame([delta_deep(imgs[t], imgs[t - 1], bpp, 7 if t % 2 else 27)]))
return file(typ, w, h, depth, 50, frames)
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="flifx_")
files = [
("anim.fli", fli_8(), 80, 50, 8, 70 / 5),
("anim.flc", flc_8(), 128, 64, 8, 1000 / 66),
("odd.flc", flc_8_odd(), 61, 37, 8, 10),
("rgb15.flc", flc_deep(0xAF12, 16, 2, 63, 40), 63, 40, 15, 20),
("rgb565.flc", flc_deep(0xAF44, 16, 2, 48, 30), 48, 30, 16, 20),
("bgr24.flc", flc_deep(0xAF12, 24, 3, 41, 30), 41, 30, 24, 20),
]
cases = []
for name, data, w, h, depth, rate in files:
path = os.path.join(tmp, name)
open(path, "wb").write(data)
crcs = rgba_crcs(path, w, h)
assert crcs, name
cases.append({"name": name, "data": data, "width": w, "height": h, "depth": depth, "rate": rate, "frames": crcs})
ctx.emit("fli_cases", cases)
# tools/bench.luau: a 320x200 FLC, 10 frames (BRUN then SS2 deltas)
w, h, n = 320, 200, 10
imgs = idx_frames(w, h, n, 256, 9)
frames = [frame([color([(0, pal(256, 9, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
frames += [frame([ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
ctx.emit("fli_bench", {"data": file(0xAF12, w, h, 8, 66, frames), "width": w, "height": h, "frames": n})
+108
View File
@@ -0,0 +1,108 @@
# Legacy video codec fixtures (tools/fixtures.py): Cinepak, Microsoft Video 1, QuickTime RLE and QuickTime SMC
# streams in AVI, MOV and MKV. ffmpeg encodes what it can (cinepak rgb24 / gray, msvideo1 rgb555, qtrle rgb24 /
# rgb555 / argb / gray, smc pal8); tools/fixtures/_legacy_mux.py encodes the rest (QuickTime RLE at 1 / 2 / 4 / 8 bits
# with colour tables and the default Macintosh palettes, 8-bit Microsoft Video 1 and Cinepak with AVI palettes). The
# reference is ffmpeg's decode of every file: the CRC-32 of each frame as rgba.
# tests/gen/legacy_cases.luau { { name, data, codec, width, height, frames = { crc } } }
import importlib.util, os, tempfile, zlib
_here = os.path.dirname(os.path.abspath(__file__))
def _load(name):
spec = importlib.util.spec_from_file_location(name, os.path.join(_here, name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
V = _load("_video")
M = _load("_legacy_mux")
INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_legacy_mux.py"]
W, H = 128, 96
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H), "-t", "1"]
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def case(tmp, name, codec, w=W, h=H):
path = os.path.join(tmp, name)
return {"name": name, "data": open(path, "rb").read(), "codec": codec, "width": w, "height": h,
"frames": rgba_crcs(path, w, h)}
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="legacyfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
cases = []
# ffmpeg's encoders
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "cinepak", "cinepak." + ext)
cases.append(case(tmp, "cinepak." + ext, "cinepak"))
ff(*SRC, "-c:v", "cinepak", "-pix_fmt", "gray", "cinepak_gray.avi")
cases.append(case(tmp, "cinepak_gray.avi", "cinepak"))
ff("-f", "lavfi", "-i", "testsrc2=size=92x68:rate=10", "-t", "0.5", "-c:v", "cinepak", "cinepak_odd.mov")
cases.append(case(tmp, "cinepak_odd.mov", "cinepak", 92, 68))
ff(*SRC, "-c:v", "cinepak", "-min_strips", "3", "-max_strips", "3", "-skip_empty_cb", "1", "cinepak_strips.avi")
cases.append(case(tmp, "cinepak_strips.avi", "cinepak"))
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "msvideo1", "msvideo1." + ext)
cases.append(case(tmp, "msvideo1." + ext, "msvideo1"))
for pf in ("rgb24", "rgb555be", "argb", "gray"):
ff(*SRC, "-c:v", "qtrle", "-pix_fmt", pf, "qtrle_%s.mov" % pf)
cases.append(case(tmp, "qtrle_%s.mov" % pf, "qtrle"))
ff("-f", "lavfi", "-i", "testsrc2=size=100x60:rate=10", "-t", "0.5", "-c:v", "qtrle", "-pix_fmt", "argb", "qtrle_odd.mov")
cases.append(case(tmp, "qtrle_odd.mov", "qtrle", 100, 60))
for ext in ("mov", "mkv"): # (ffmpeg's AVI muxer has no tag for smc: it writes raw pal8)
ff(*SRC, "-c:v", "smc", "smc." + ext)
cases.append(case(tmp, "smc." + ext, "smc"))
# streams encoded here
w, h, n = 64, 48, 8
for bits in (1, 2, 4, 8):
imgs = M.index_frames(w, h, n, 1 << bits, seed=bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
keys = [i == 0 for i in range(n)]
# a colour table in the sample description, and the Macintosh default table
pal = M.palette(1 << bits, seed=bits)
name = "qtrle_%d_ctab.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits, colors=pal), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
name = "qtrle_%d_default.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
# grey depths (0x20 + bits) with the default table id: grey ramps
for bits in (2, 4):
imgs = M.index_frames(w, h, 4, 1 << bits, seed=10 + bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
name = "qtrle_%d_grey.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, 32 + bits), frames, [True] + [False] * 3))
cases.append(case(tmp, name, "qtrle", w, h))
# 8-bit Microsoft Video 1 and Cinepak with an AVI palette
pal = M.palette(256, seed=3)
imgs = M.index_frames(w, h, n, 256, seed=5)
frames = [M.msvc8_frame(img, imgs[i - 1] if i else None) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "msvideo1_8.avi"), "wb").write(
M.avi(w, h, b"CRAM", M.bitmapinfo(w, h, 8, b"CRAM", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "msvideo1_8.avi", "msvideo1", w, h))
imgs = M.index_frames(w, h, n, 200, seed=6)
frames = [M.cvid8_frame(img, imgs[i - 1] if i else None, i == 0) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "cinepak_8.avi"), "wb").write(
M.avi(w, h, b"cvid", M.bitmapinfo(w, h, 8, b"cvid", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "cinepak_8.avi", "cinepak", w, h))
for c in cases:
assert c["frames"], c["name"] + ": ffmpeg decoded no frame"
ctx.emit("legacy_cases", cases)
# tools/bench.luau: 320x240, 10 frames of each codec
bench = []
big = ["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=10", "-t", "1"]
for name, args in [("cinepak.avi", ["-c:v", "cinepak"]), ("msvideo1.avi", ["-c:v", "msvideo1"]),
("qtrle.mov", ["-c:v", "qtrle", "-pix_fmt", "rgb24"]), ("smc.mov", ["-c:v", "smc"])]:
ff(*big, *args, "bench_" + name)
bench.append({"name": name, "data": open(os.path.join(tmp, "bench_" + name), "rb").read(), "width": 320, "height": 240})
ctx.emit("legacy_bench", bench)
+499
View File
@@ -0,0 +1,499 @@
# 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("<I", len(samples) * nb) + bw.bytes()
def tone(n, ch, bits, rate, seed, f0):
rnd = random.Random(seed)
out = []
for i in range(n):
for c in range(ch):
v = 0.5 * math.sin(2 * math.pi * f0 * (c + 1) * i / rate) + 0.05 * (rnd.random() - 0.5)
if bits == 16:
out.append(int(v * 30000))
else:
out.append(int(128 + v * 120))
return out
# ---------------------------------------------------------------------------------------------------- files
def idx_frames(w, h, n, seed, busy=False):
rnd = random.Random(seed)
out = []
for t in range(n):
if busy: # textured, moving: mostly FULL blocks (the bench)
img = [[(x * 3 + y * 5 + ((x + t * 4) * (y + t)) // 7) % 251 for x in range(w)] for y in range(h)]
else:
img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)]
for y in range(8, 24):
for x in range(8 + t * 4, 24 + t * 4):
img[y][x] = 100 + (x + y) % 2 # two colours: MONO blocks
for y in range(h - 16, h - 8):
for x in range(0, w):
img[y][x] = 50 + ((x // 2) % 5) if (t % 2 == 0) else 60 # doubled pixels: SMK4 modes
for y in range(28, 36):
for x in range(w // 2, w // 2 + 12):
img[y][x] = rnd.randrange(256)
out.append(img)
return out
def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed, busy=False):
"""version 2 / 4; tracks = [(kind, rate, ch, bits)] kind "packed" / "raw"; returns bytes, track info"""
rnd = random.Random(seed)
frames = idx_frames(w, h, nframes, seed, busy)
if ring:
frames = frames + [frames[0]]
treebytes, sizes, video = encode_video(frames, w, h, version == 4, rnd)
total = len(frames)
# palettes (6-bit), changing on some frames
pals = []
cur = [(rnd.randrange(64), rnd.randrange(64), rnd.randrange(64)) for _ in range(256)]
for t in range(total):
if t in (3, 5):
cur = list(cur)
for k in range(20 + t, 40 + t):
cur[k] = (rnd.randrange(64), rnd.randrange(64), rnd.randrange(64))
cur[200:210] = pals[0][10:20] # a copy from the old palette
pals.append(list(cur))
# audio per frame
seconds = (pts_inc / 1000.0 if pts_inc > 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("<h", v) if bits == 16 else bytes([v]) for v in s))
achunks.append(per)
data = []
flags = []
for t in range(total):
body = b""
fl = 0
if t == 0 or pals[t] != pals[t - 1]:
body += pal_chunk(pals[t], pals[t - 1] if t else None, t == 0)
fl |= 1
for ti in range(len(tracks)):
a = achunks[ti][t]
body += struct.pack("<I", 4 + len(a)) + a
fl |= 2 << ti
body += video[t]
body += bytes((-len(body)) % 4)
data.append(body)
flags.append(fl)
hd = b"SMK%d" % version + struct.pack("<IIIiI", w, h, nframes, pts_inc, 1 if ring else 0)
hd += struct.pack("<7I", *[max(len(a) for a in achunks[i]) if i < len(tracks) else 0 for i in range(7)])
hd += struct.pack("<I", len(treebytes)) + struct.pack("<4I", *sizes)
for i in range(7):
if i < len(tracks):
kind, rate, ch, bits = tracks[i]
f = 0x40 | (0x80 if kind == "packed" else 0) | (0x20 if bits == 16 else 0) | (0x10 if ch == 2 else 0)
hd += struct.pack("<I", rate | f << 24)
else:
hd += struct.pack("<I", 0)
hd += struct.pack("<I", 0)
hd += b"".join(struct.pack("<I", len(d) | (1 if t == 0 else 0)) for t, d in enumerate(data))
hd += bytes(flags)
return hd + treebytes + b"".join(data)
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="smkfx_")
specs = [
("smk2_audio.smk", 2, 64, 48, 8, 100, [("packed", 22050, 2, 16), ("packed", 11025, 1, 8)], False, 1),
("smk4_ring.smk", 4, 96, 64, 9, -6667, [("raw", 16000, 1, 16), ("raw", 8000, 2, 8)], True, 2),
("smk4_mono.smk", 4, 64, 48, 6, 80, [("packed", 22050, 1, 16), ("packed", 11025, 2, 8)], False, 3),
("smk2_silent.smk", 2, 128, 64, 5, 66, [], False, 4),
]
cases = []
for name, ver, w, h, n, pts, tracks, ring, seed in specs:
data = smk_file(ver, w, h, n, pts, tracks, ring, seed)
path = os.path.join(tmp, name)
open(path, "wb").write(data)
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
sz = w * h * 4
crcs = [zlib.crc32(raw[i:i + sz]) & 0xffffffff for i in range(0, len(raw) - sz + 1, sz)]
assert len(crcs) == n + (1 if ring else 0), (name, len(crcs))
audio = []
for i, (kind, rate, ch, bits) in enumerate(tracks):
pcm = V.ffmpeg(["-i", path, "-map", "0:a:%d" % i, "-f", "f32le", "-"])
audio.append({"rate": rate, "channels": ch, "bits": bits,
"codec": "smackaudio" if kind == "packed" else ("pcm_s16le" if bits == 16 else "pcm_u8"),
"frames": len(pcm) // (4 * ch), "crc": zlib.crc32(pcm) & 0xffffffff})
rate = 1000 / pts if pts > 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)
# tools/bench.luau: a 320x200 SMK4 with 22.05 kHz packed stereo audio, 10 frames
ctx.emit("smk_bench", {"data": smk_file(4, 320, 200, 10, 100, [("packed", 22050, 2, 16)], False, 9, True), "width": 320,
"height": 200, "frames": 10})