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

+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})