diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b7c26a7..13d1e91 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -28,6 +28,7 @@ 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", "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", "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", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 288846f..d26e1e1 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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", diff --git a/src/Formats/video/fli/init.luau b/src/Formats/video/fli/init.luau new file mode 100644 index 0000000..8224d48 --- /dev/null +++ b/src/Formats/video/fli/init.luau @@ -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 diff --git a/tests/video/fli.luau b/tests/video/fli.luau new file mode 100644 index 0000000..b163dc9 --- /dev/null +++ b/tests/video/fli.luau @@ -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() diff --git a/tools/fixtures/fli.py b/tools/fixtures/fli.py new file mode 100644 index 0000000..0428f02 --- /dev/null +++ b/tools/fixtures/fli.py @@ -0,0 +1,395 @@ +# 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("= 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("