# 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(" 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(" 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})