codecs/video/Legacy: Cinepak, Microsoft Video 1, QuickTime RLE / SMC and FLIC decoders

Registry decoders (codecs/video/Video BUILTIN: cvid, CRAM / MSVC / WHAM, 'rle ', 'smc ', AFLC), rgba8 pictures
painted over the previous picture, palettes from track.palette (or packet.palette). Bit-exact with ffmpeg on
28 AVI / MOV / MKV fixtures (tools/fixtures/legacy.py: ffmpeg's encoders plus encoders in _legacy_mux.py for
QuickTime RLE 1/2/4/8-bit, 8-bit MS Video 1 and Cinepak). Also fixes QtPalette's big-endian reads.
This commit is contained in:
4DBug committed 2026-10-31 14:20:17 -05:00
1 parent 7b4bf1ee43
commit 8e3873c9fb
14 files changed
+2171 -3

No files matched your search

+1
View File
@@ -133,5 +133,6 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
- **video**
- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
@@ -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
+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
+187
View File
@@ -0,0 +1,187 @@
--!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) and QuickTime Graphics ("smc", 'smc ').
-- 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" }
--
-- 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 Legacy = {}
Legacy.Picture = Picture
Legacy.Flic = Flic
Legacy.Cinepak = Cinepak
Legacy.Msvideo1 = Msvideo1
Legacy.QtRle = QtRle
Legacy.Smc = Smc
Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" }
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,
},
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
@@ -294,6 +294,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec
return H264.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 } = {
@@ -309,6 +316,13 @@ local BUILTIN: { Entry } = {
{ id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } },
{ id = "theora", name = "Theora", matroska = { "V_THEORA" } },
{ 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 } = {}
@@ -10,7 +10,14 @@
-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil
--
-- Never throws.
local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32
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 = {}
+3 -2
View File
@@ -313,8 +313,9 @@ 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)
if t.kind == "video" and t.config then
vfwOrQuickTime(t, codecId, t.config)
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
+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()
+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
+100
View File
@@ -0,0 +1,100 @@
# 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)