Files
rosetta/tools/fixtures/theora.py
T
4DBug 1013925a85 ws-video2-theora: Theora speed (fused prediction + IDCT add, inlined token decode, table-driven tokens), bench lines, guide section
tools/bench.luau: a ws-video2-theora block (320x240 testsrc2 / mandelbrot, decode and
decode + image()). docs/guide/video.md: an Ogg Theora section (tested snippet; inputs
from the new tools/fixtures/docs_theora.py) and the formats / writers tables.
2026-10-31 14:43:22 -05:00

209 lines
11 KiB
Python

# Theora fixtures for codecs/video/Theora and video/ogv (tools/fixtures.py): Ogg Theora files made by ffmpeg's
# libtheora encoder (testsrc2 / mandelbrot / static bars, several qualities and bit rates, odd sizes = picture regions
# smaller than the coded frame (the encoder keeps even sizes; two cases patch odd ones at offsets), 4:2:2 and 4:4:4, short and long keyframe intervals), one with an empty packet (a
# repeated frame) spliced in, an Ogg with Vorbis audio, and Theora in Matroska. The reference is ffmpeg's own decode
# (its vp3 decoder, bit-exact with libtheora): `-f framecrc` in the stream's native pixel format, one Adler-32 per
# frame over the packed planes of the picture region, with the frame's pts.
# tests/gen/theora_<name>.luau { name, width, height, pixfmt, file (base64 .ogv), frames = { { pts, adler } } }
# tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original)
# tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64),
# rate, channels }
# tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio
# tests/gen/theora_mkv.luau { file (base64 .mkv), frames }
# tests/gen/theora_bench.luau { { name, file (base64 .ogv, 320x240), width, height } } for tools/bench.luau
import base64, os, shutil, struct, subprocess, tempfile, zlib
FF = ["-hide_banner", "-loglevel", "error", "-y"]
def b64(b):
return base64.b64encode(b).decode()
def src(kind, w, h, rate, t):
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
# name: (input args, encoder args, pixel format)
CASES = {
"q6": (src("testsrc2", 320, 240, 25, 1.2), ["-q:v", "6", "-g", "12"], "yuv420p"),
"q0": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "0", "-g", "30"], "yuv420p"),
"q10": (src("mandelbrot", 176, 144, 25, 0.6), ["-q:v", "10", "-g", "8"], "yuv420p"),
"motion": (src("mandelbrot", 240, 160, 30, 1.5), ["-b:v", "300k", "-g", "64"], "yuv420p"),
"odd": (src("testsrc2", 174, 98, 25, 1), ["-q:v", "5", "-g", "10"], "yuv420p"),
"static": (src("smptebars", 160, 120, 25, 1.2), ["-q:v", "4", "-g", "100"], "yuv420p"),
"yuv422": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "6", "-g", "12"], "yuv422p"),
"yuv444": (src("mandelbrot", 144, 112, 25, 1), ["-q:v", "6", "-g", "12"], "yuv444p"),
"odd444": (src("testsrc2", 98, 62, 25, 0.6), ["-q:v", "7", "-g", "6"], "yuv444p"),
}
# ffmpeg's encoder writes even picture sizes at offset 0: these cases patch the identification header to an odd
# picture region at an offset (width, height, x, y from the bottom); the reference is ffmpeg's decode of the patched
# file (-flags unaligned: the exact crop)
PATCH = {
"crop": (src("testsrc2", 176, 112, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv420p", (171, 97, 3, 5)),
"crop422": (src("mandelbrot", 128, 96, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv422p", (117, 81, 5, 2)),
}
def crc32(b):
return zlib.crc32(b) & 0xFFFFFFFF
def ogg_pages(data):
"""yield (header fields, segment table, body) of each Ogg page"""
i = 0
while i + 27 <= len(data):
assert data[i:i + 4] == b"OggS"
flags, granule, serial, seq = data[i + 5], struct.unpack_from("<q", data, i + 6)[0], \
struct.unpack_from("<I", data, i + 14)[0], struct.unpack_from("<I", data, i + 18)[0]
n = data[i + 26]
segs = list(data[i + 27:i + 27 + n])
body = data[i + 27 + n:i + 27 + n + sum(segs)]
yield flags, granule, serial, seq, segs, body
i += 27 + n + sum(segs)
OGG_CRC = []
for _i in range(256):
r = _i << 24
for _ in range(8):
r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1)
OGG_CRC.append(r & 0xFFFFFFFF)
def ogg_crc(b):
c = 0
for x in b:
c = ((c << 8) ^ OGG_CRC[((c >> 24) ^ x) & 0xFF]) & 0xFFFFFFFF
return c
def page(flags, granule, serial, seq, packets_segs, body):
head = b"OggS" + bytes([0, flags]) + struct.pack("<qII", granule, serial, seq) + b"\0\0\0\0" + \
bytes([len(packets_segs)]) + bytes(packets_segs)
p = bytearray(head + body)
struct.pack_into("<I", p, 22, ogg_crc(p))
return bytes(p)
def splice_empty(data, after):
"""rewrite a single-stream Ogg Theora file with one page per packet and an empty packet after data packet
`after` (1-based); granules are recomputed as frame counts since the last keyframe (bitstream 3.2.1 numbering)"""
packets, cur = [], b""
shift = None
for flags, granule, serial, seq, segs, body in ogg_pages(data):
o = 0
for s in segs:
cur += body[o:o + s]
o += s
if s < 255:
packets.append(cur)
cur = b""
sid = serial
shift = (packets[0][40] & 0x03) << 3 | packets[0][41] >> 5
out = []
seq = 0
frames = []
data_packets = packets[3:]
data_packets = data_packets[:after] + [b""] + data_packets[after:]
key = 0
for k, p in enumerate(packets[:3]):
segs = [255] * (len(p) // 255) + [len(p) % 255]
out.append(page(2 if k == 0 else 0, 0, sid, seq, segs, p))
seq += 1
for k, p in enumerate(data_packets):
n = k + 1
if len(p) > 0 and not (p[0] & 0x40):
key = n
segs = [255] * (len(p) // 255) + [len(p) % 255]
g = (key << shift) | (n - key)
out.append(page(4 if k == len(data_packets) - 1 else 0, g, sid, seq, segs, p))
seq += 1
return b"".join(out)
def patch_picture(data, w, h, x, y):
"""rewrite the first page (the identification header) with another picture region"""
out = bytearray(data)
n = out[26]
o = 27 + n # the packet starts here
assert out[o:o + 7] == b"\x80theora"
out[o + 14:o + 17] = w.to_bytes(3, "big")
out[o + 17:o + 20] = h.to_bytes(3, "big")
out[o + 20] = x
out[o + 21] = y
plen = 27 + n + sum(out[27:27 + n])
out[22:26] = b"\0\0\0\0"
struct.pack_into("<I", out, 22, ogg_crc(bytes(out[:plen])))
return bytes(out)
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
def ff(args):
return subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True).stdout
def framecrc(path, pixfmt, extra=None):
out = ff(["-flags", "unaligned", "-i", path] + (extra or []) + ["-map", "0:v", "-fps_mode", "passthrough", "-pix_fmt", pixfmt,
"-f", "framecrc", "-"]).decode()
frames = []
for line in out.splitlines():
if line.startswith("#"):
continue
parts = [x.strip() for x in line.split(",")]
frames.append([int(parts[1]), int(parts[5], 16)])
return frames
with tempfile.TemporaryDirectory(prefix="formats-theora-") as tmp:
for name, (inp, enc, pixfmt) in CASES.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = open(path, "rb").read()
w, h = [int(x) for x in inp[3].split("=")[2].split(":")[0].split("x")]
ctx.emit("theora_" + name, {"name": name, "width": w, "height": h, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
if name == "q6":
# an empty packet (a dropped / repeated frame) after the 5th frame
dupe = splice_empty(data, 5)
dpath = os.path.join(tmp, "dupe.ogv")
open(dpath, "wb").write(dupe)
ctx.emit("theora_dupe", {"name": "dupe", "width": w, "height": h, "pixfmt": pixfmt, "file": b64(dupe),
"frames": framecrc(path, pixfmt)})
for name, (inp, enc, pixfmt, (pw, ph, px, py)) in PATCH.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = patch_picture(open(path, "rb").read(), pw, ph, px, py)
open(path, "wb").write(data)
ctx.emit("theora_" + name, {"name": name, "width": pw, "height": ph, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
# Theora + Vorbis (stereo 44.1 kHz)
av = os.path.join(tmp, "av.ogv")
ff(src("testsrc2", 160, 120, 25, 1) + ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "1",
"-ac", "2", "-c:v", "libtheora", "-q:v", "5", "-c:a", "libvorbis",
"-q:a", "3", "-shortest", av])
pcm = ff(["-i", av, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_av", {"file": b64(open(av, "rb").read()), "frames": framecrc(av, "yuv420p"),
"width": 160, "height": 120, "pcm": b64(pcm), "rate": 44100, "channels": 2})
# Theora + Opus, Theora + FLAC (mono, 0.5 s)
for name, aenc, rate in (("opus", ["-c:a", "libopus", "-b:a", "48k"], 48000), ("flac", ["-c:a", "flac"], 22050)):
path = os.path.join(tmp, "a_" + name + ".ogv")
ff(src("testsrc2", 96, 64, 25, 0.5) + ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate,
"-t", "0.5", "-ac", "1", "-c:v", "libtheora", "-q:v", "4"] + aenc +
["-shortest", path])
pcm = ff(["-i", path, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_" + name, {"file": b64(open(path, "rb").read()), "frames": framecrc(path, "yuv420p"),
"width": 96, "height": 64, "pcm": b64(pcm), "rate": rate, "channels": 1})
# Theora in Matroska (CodecPrivate: the three headers, Xiph-laced)
mkv = os.path.join(tmp, "t.mkv")
ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv])
ctx.emit("theora_mkv", {"file": b64(open(mkv, "rb").read()), "frames": framecrc(mkv, "yuv420p"),
"width": 174, "height": 98})
# the bench streams: an easy clip (testsrc2, mostly static) and a hard one (a mandelbrot zoom: every block moves)
bench = []
for kind, rate in (("testsrc2", "600k"), ("mandelbrot", "1200k")):
path = os.path.join(tmp, "bench_" + kind + ".ogv")
ff(src(kind, 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", rate, "-g", "25", path])
bench.append({"name": kind, "file": b64(open(path, "rb").read()), "width": 320, "height": 240})
ctx.emit("theora_bench", bench)