Files
4DBug 8e3873c9fb 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.
2026-10-31 14:20:17 -05:00

376 lines
15 KiB
Python

# 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