merge ws/video2

This commit is contained in:
4DBug committed 2026-10-31 15:31:56 -05:00
commit c5f27770fc
63 files changed
+12207 -1509

No files matched your search

+156
View File
@@ -1203,3 +1203,159 @@ do
Qb.decode(Bytes.reader(qb))
end)
end
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
do
local Jpeg = require("@formats/codecs/image/Jpeg")
local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local Base64 = require("@formats/core/Base64")
local Types = require("@formats/Types")
local MB = require("@tests/gen/mjpeg_bench")
local M1 = require("@tests/gen/mpeg1_bench")
-- best of n runs of f (which handles `frames` frames): ms per frame and frames per second
local function fps(label: string, n: number, frames: number, f: () -> ())
f()
local dt = math.huge
for _ = 1, n do
local t0 = os.clock()
f()
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, label, dt * 1000 / frames, frames / dt))
end
for _, c in MB.frames do
local b = Base64.decode(c.data) :: buffer
local img = assert(Jpeg.decode(b, 0, nil, { yuv = true }))
assert(Crc32.of(img.pixels) == c.yuv, "mjpeg bench: " .. c.name .. " does not match TurboJPEG")
fps("mjpeg decode yuv " .. c.name, 10, 1, function()
Jpeg.decode(b, 0, nil, { yuv = true })
end)
fps("mjpeg decode rgba " .. c.name, 10, 1, function()
Jpeg.decode(b)
end)
end
for _, s in MB.sources do
local img = Types.Image.new(s.width, s.height, "yuv420p")
img.pixels = assert(Deflate.zlib(Base64.decode(s.yuv) :: buffer))
fps(string.format("mjpeg encode yuv %dx%d q85", s.width, s.height), 5, 1, function()
Jpeg.encode(img, { quality = 85 })
end)
end
-- (LuaJIT also with the trace limits the api sets, host/init.luau: the default 1000 traces thrash on MPEG-1)
local function mpeg1(tag: string)
for _, s in M1 do
local file = Base64.decode(s.file) :: buffer
for _, rgba in { false, true } do
fps(string.format("mpeg1 decode %s %dx%d%s", if rgba then "rgba" else "yuv", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = rgba })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
end
-- MPEG-2: 720x576 interlaced (field prediction / field DCT, B-frames), as on a DVD (ws-video2)
local M2 = require("@tests/gen/mpeg2_bench")
local function mpeg2(tag: string)
for _, s in M2 do
local file = Base64.decode(s.file) :: buffer
fps(string.format("mpeg2 decode yuv %dx%d interlaced%s", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = false })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
jitTune(false)
mpeg1("")
mpeg2("")
if runtime == "luajit" then
jitTune(true)
mpeg1(" (jit tuned)")
mpeg2(" (jit tuned)")
jitTune(false)
end
end
do
-- ------------------------------------------------------------------------------------- ws-video2-theora: fps
-- Theora (codecs/video/Theora): 320x240 clips, 50 frames, keyframe every 25: testsrc2 at 600 kbit/s (mostly static:
-- few coded blocks) and a mandelbrot zoom at 1200 kbit/s (every block coded, moving); decode alone and decode +
-- image() (the yuv420p copy every VideoDecoder frame makes)
local Theora = require("@formats/codecs/video/Theora")
local Ogg = require("@formats/containers/Ogg")
local Base64 = require("@formats/core/Base64")
local TB = require("@tests/gen/theora_bench")
local function run(tag: string)
for _, c in TB do
local d = Ogg.open(Base64.decode(c.file) :: buffer)
local hdrs, data = {}, {}
for p in d:packets(d:find("theora")) do
table.insert(if #hdrs < 3 then hdrs else data, Ogg.copy(p))
end
for _, image in { false, true } do
local n = c.width * c.height * 3 // 2 * #data
local dt = bench(string.format("theora %s %dx%d%s%s", c.name, c.width, c.height, if image then " +img" else "", tag), 3, n, function()
local dec = Theora.new(hdrs) :: any
for _, p in data do
dec:decode(p)
if image then
dec:image()
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #data .. " frames)", #data / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
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
+7 -3
View File
@@ -1,8 +1,8 @@
# Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them):
# tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG +
# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of
# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT /
# ASS subtitles.
# PCM), WebM (VP8 + Vorbis), MPEG-TS (interlaced MPEG-2 + MP2); a MIDI file written here (SMF 1: a tempo track and a
# melody), the SoundFont of tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py
# (song_basic), and SRT / WebVTT / ASS subtitles.
# tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } }
import importlib.util, os, struct, tempfile
@@ -91,6 +91,9 @@ def generate(ctx):
"-c:a", "aac", "-b:a", "64k"]),
("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]),
("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]),
("clip.ts", ["-c:v", "mpeg2video", "-b:v", "300k", "-g", "5", "-bf", "2", "-vf", "setfield=tff",
"-flags", "+ilme+ildct",
"-c:a", "mp2", "-b:a", "64k"]),
):
out = os.path.join(d, name)
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out])
@@ -107,6 +110,7 @@ def generate(ctx):
"mp4Bytes": "clip.mp4",
"aviBytes": "clip.avi",
"webmBytes": "clip.webm",
"tsBytes": "clip.ts",
"midiBytes": "tune.mid",
"sf2Bytes": "bank.sf2",
"modBytes": "song.mod",
+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"})
+20
View File
@@ -0,0 +1,20 @@
# Docs inputs for the Ogg Theora section of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): a
# tiny ffmpeg clip (testsrc 64x48, 10 frames at 10 fps, libtheora + a libvorbis sine track) as Ogg video.
# tests/gen/docs_theora.luau { files = { ["clip.ogv"] = bytes }, vars = { ogvBytes = "clip.ogv" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_theora_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "clip.ogv")
subprocess.run([ffmpeg, "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libtheora",
"-q:v", "6", "-g", "5", "-c:a", "libvorbis", "-q:a", "2", out], check=True, capture_output=True)
files = {"clip.ogv": open(out, "rb").read()}
dc.emit_inputs(ctx, files, {"ogvBytes": "clip.ogv"})
+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)
+11 -4
View File
@@ -4,7 +4,9 @@
# tests/gen/mpeg1_<name>.luau { name, width, height, frames, file (base64), units = { { offset, length } },
# means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA),
# rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib),
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) }
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib),
# exact = { { y, u, v } } (CRC-32 of every frame's planes from `ffmpeg -idct int`, the IDCT
# codecs/video/Dsp reproduces: the decode must equal it) }
# tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } }
# tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with
# B-frames) for tools/bench.luau
@@ -122,9 +124,9 @@ def generate(ctx):
es = open(path, "rb").read()
return (patch_size(es, *size) if size else es), path
def reference(path, fmt):
out = path + "." + fmt
ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
def reference(path, fmt, idct=None):
out = path + "." + fmt + (idct or "")
ff((["-idct", idct] if idct else []) + ["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2])
@@ -134,10 +136,13 @@ def generate(ctx):
es, path = encode(name, args, size)
rgba, w, h = reference(path, "rgba")
yuv, _, _ = reference(path, "yuv420p")
exact, _, _ = reference(path, "yuv420p", "int")
if size:
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
exact = crop_yuv(exact, w, h, size[0], size[1])
w, h = size
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
c = ((w + 1) // 2) * ((h + 1) // 2)
n = len(rgba) // fs
means = []
for k in range(n):
@@ -151,6 +156,8 @@ def generate(ctx):
"means": means,
"rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks],
"yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks],
"exact": [[zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + c]), zlib.crc32(f[w * h + c:ys])]
for f in (exact[k * ys:(k + 1) * ys] for k in range(n))],
})
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
+424
View File
@@ -0,0 +1,424 @@
# MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder
# (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the
# alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and
# chroma matrices, large motion (f_code > 1), odd sizes, B-frames), from mjpegtools' mpeg2enc (dual-prime
# prediction in interlaced frame pictures) and from field_stream below (field pictures: I / P / B fields, the second
# field predicted from the first, field / 16x8 / dual-prime prediction, skipped macroblocks; concealment vectors),
# each with `ffmpeg -idct int` decoding as the reference: the IJG integer IDCT that codecs/video/Dsp reproduces, so
# the planes must match exactly.
# tests/gen/mpeg2_<name>.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64),
# units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of
# every frame's cropped planes, display order), bands = { { crc } } (per frame, of
# each 16-line luma band), first / last = the yuv frame (base64 zlib) }
# tests/gen/mpeg2_containers.luau the prog stream in MPEG-TS (stream type 0x02, and patched to 0x80), MPEG-PS,
# Matroska and AVI, base64, with the stream's crcs
# tests/gen/mpeg2_bench.luau { { width, height, file, units } }: 720x576 interlaced (DVD-like) for tools/bench.luau
import base64, os, shutil, subprocess, tempfile, zlib
def b64(b):
return base64.b64encode(b).decode()
def z64(b):
return base64.b64encode(zlib.compress(b, 9)).decode()
FF = ["-hide_banner", "-loglevel", "error", "-y"]
ENC = ["-c:v", "mpeg2video", "-f", "mpeg2video"]
ILACE = ["-flags", "+ilme+ildct"]
CHROMA_INTRA = ",".join(str(8 + (i // 8) * 2 + (i % 8)) for i in range(64))
INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64))
INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64))
def src(kind, w, h, t, rate=25, vf=None):
s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate)
if vf:
s += "," + vf
return ["-f", "lavfi", "-i", s, "-t", str(t)]
# name: (ffmpeg input + encoder args, chroma)
CASES = {
"prog": (src("testsrc2", 352, 288, 0.8) + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"tff": (src("mandelbrot", 352, 288, 0.8, vf="setfield=tff") + ILACE + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"bff_alt": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.01:v=0.02,setfield=bff") + ILACE + ["-alternate_scan", "1",
"-b:v", "1500k", "-bf", "1", "-g", "9"], 1),
"tools": (src("mandelbrot", 320, 240, 0.6) + ["-intra_vlc", "1", "-non_linear_quant", "1", "-qmax", "28", "-dc", "10", "-b:v", "1500k",
"-bf", "2", "-g", "8"], 1),
"dc9_matrix": (src("testsrc2", 176, 144, 0.6) + ["-dc", "9", "-intra_matrix", INTRA, "-inter_matrix", INTER,
"-b:v", "800k", "-bf", "1", "-g", "6"], 1),
"dc11_q1": (src("mandelbrot", 176, 144, 0.32) + ["-dc", "11", "-q:v", "1", "-qmin", "1", "-bf", "0", "-g", "4"], 1),
"motion": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.04:v=0.03") + ["-b:v", "3M", "-bf", "3", "-g", "15"], 1),
"odd_ilace": (src("testsrc2", 346, 258, 0.48) + ILACE + ["-b:v", "1500k", "-bf", "2", "-g", "6"], 1),
"c422": (src("mandelbrot", 352, 288, 0.48) + ["-pix_fmt", "yuv422p", "-b:v", "3M", "-bf", "2", "-g", "6",
"-chroma_intra_matrix", CHROMA_INTRA], 2),
"c422_ilace": (src("testsrc2", 320, 240, 0.48, vf="scroll=h=0.02,setfield=tff") + ["-pix_fmt", "yuv422p"] + ILACE +
["-alternate_scan", "1", "-b:v", "3M", "-bf", "1", "-g", "6"], 2),
}
def access_units(es):
# one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start
starts = []
i = 0
pending = None
while True:
i = es.find(b"\x00\x00\x01", i)
if i < 0 or i + 3 >= len(es):
break
code = es[i + 3]
if code in (0xB3, 0xB8) and pending is None:
pending = i
elif code == 0x00:
starts.append(pending if pending is not None else i)
pending = None
i += 3
return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)]
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe")
def ff(args):
subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True)
def size(path):
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2])
def reference(path, chroma):
out = path + ".yuv"
ff(["-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo",
"-pix_fmt", "yuv422p" if chroma == 2 else "yuv420p", out])
return open(out, "rb").read()
def emit(name, es, path, chroma):
w, h = size(path)
yuv = reference(path, chroma)
cw, ch = (w + 1) // 2, (h if chroma == 2 else (h + 1) // 2)
fs = w * h + 2 * cw * ch
n = len(yuv) // fs
crcs, bands = [], []
for k in range(n):
f = yuv[k * fs:(k + 1) * fs]
crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])])
bands.append([zlib.crc32(f[y * w:min(h, y + 16) * w]) for y in range(0, h, 16)])
ctx.emit("mpeg2_" + name, {
"name": name, "width": w, "height": h, "chroma": chroma, "frames": n, "file": b64(es),
"units": access_units(es), "crcs": crcs, "bands": bands, "first": z64(yuv[:fs]), "last": z64(yuv[(n - 1) * fs:n * fs]),
})
return crcs
with tempfile.TemporaryDirectory(prefix="formats-mpeg2-") as tmp:
crcs = {}
for name, (args, chroma) in CASES.items():
path = os.path.join(tmp, name + ".m2v")
ff(args + ENC + [path])
crcs[name] = emit(name, open(path, "rb").read(), path, chroma)
# mjpegtools' mpeg2enc: interlaced frame pictures with dual-prime prediction (P only, as dual prime requires)
y4m = os.path.join(tmp, "src.y4m")
ff(src("mandelbrot", 352, 288, 0.6) + ["-vf", "setfield=tff", "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", y4m])
dp = os.path.join(tmp, "dualprime.m2v")
ctx.nix("mjpegtools", ["sh", "-c", "mpeg2enc -v 0 -f 3 -I 1 --dualprime-mpeg2 -R 0 -b 2500 -g 9 -G 9 -o '%s' < '%s'"
% (dp, y4m)])
emit("dualprime", open(dp, "rb").read(), dp, 1)
# field pictures and concealment vectors (field_stream below: no encoder at hand writes them)
seq = [("I", "P"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B")]
for name, seed, dims, conceal in (("fields", 5, (320, 240), False), ("fields_conceal", 6, (176, 144), True)):
path = os.path.join(tmp, name + ".m2v")
es = field_stream(ctx.rng(seed), dims[0], dims[1], seq, conceal)
open(path, "wb").write(es)
emit(name, es, path, 1)
# the prog stream in the containers (stream copy)
prog = os.path.join(tmp, "prog.m2v")
cont = {"crcs": crcs["prog"]}
for fmt, ext in (("mpegts", "ts"), ("vob", "mpg"), ("matroska", "mkv"), ("avi", "avi")):
out = os.path.join(tmp, "prog." + ext)
ff(["-fflags", "+genpts", "-r", "25", "-i", prog, "-c", "copy", "-f", fmt, out])
cont[ext] = b64(open(out, "rb").read())
# stream type 0x80 (private / DigiCipher II video): the PMT's 0x02 entry patched, its CRC redone
ts = bytearray(base64.b64decode(cont["ts"]))
patched = False
for p in range(0, len(ts), 188):
pkt = ts[p:p + 188]
if pkt[0] != 0x47 or not (pkt[1] & 0x40):
continue
pid = ((pkt[1] & 0x1F) << 8) | pkt[2]
if pid == 0 or pid == 0x11 or pkt[3] & 0x20:
continue
o = p + 5 + pkt[4]
if ts[o] != 0x02: # table_id of a PMT
continue
slen = ((ts[o + 1] & 0x0F) << 8) | ts[o + 2]
pinfo = ((ts[o + 10] & 0x0F) << 8) | ts[o + 11]
e = o + 12 + pinfo
while e < o + 3 + slen - 4:
if ts[e] == 0x02:
ts[e] = 0x80
patched = True
e += 5 + (((ts[e + 3] & 0x0F) << 8) | ts[e + 4])
crc = zlib_crc32_mpeg(bytes(ts[o:o + 3 + slen - 4]))
ts[o + 3 + slen - 4:o + 3 + slen] = crc.to_bytes(4, "big")
assert patched, "mpeg2: no PMT entry patched"
cont["ts80"] = b64(bytes(ts))
ctx.emit("mpeg2_containers", cont)
bench = []
path = os.path.join(tmp, "bench.m2v")
ff(src("mandelbrot", 720, 576, 1.0) + ILACE + ["-b:v", "6M", "-bf", "2", "-g", "12"] + ENC + [path])
es = open(path, "rb").read()
bench.append({"width": 720, "height": 576, "file": b64(es), "units": access_units(es)})
ctx.emit("mpeg2_bench", bench)
def zlib_crc32_mpeg(data):
# CRC-32/MPEG-2: poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor
crc = 0xFFFFFFFF
for b in data:
crc ^= b << 24
for _ in range(8):
crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF
return crc
# ---------------------------------------------------------------------------------------------------------------------
# A syntax-level MPEG-2 writer for what no encoder at hand produces: field pictures (I + P fields, the P field
# predicted from the first field of its own frame, P / B field pictures, field and 16x8 prediction, dual prime in
# field pictures, skipped macroblocks) and concealment motion vectors. The content is random (DC levels, sparse
# escape-coded coefficients, motion vectors kept inside the picture): any valid stream will do, ffmpeg's decode is
# the reference. The tables are those of ISO/IEC 13818-2 annex B (only the entries used here).
MBAI = {1: "1", 2: "011", 3: "010"}
DC_LUMA = ["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"]
DC_CHROMA = ["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"]
# |motion_code| 0..16 (Table B-10), then the sign bit
MOTION = ["1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", "000001001",
"0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100"]
CBP = {60: "111", 4: "1101", 8: "1100", 16: "1011", 32: "1010"}
MBTYPE_P = {"mc_coded": "1", "nomc_coded": "01", "mc": "001", "intra": "00011"}
MBTYPE_B = {"interp": "10", "interp_coded": "11", "bwd": "010", "bwd_coded": "011", "fwd": "0010", "fwd_coded": "0011",
"intra": "00011"}
class Bits:
def __init__(self):
self.s = []
def put(self, v, n):
self.s.append(format(v & ((1 << n) - 1), "0%db" % n) if n else "")
def code(self, c):
self.s.append(c)
def start(self, code):
# next_start_code: zero stuffing to a byte boundary, then 00 00 01 code
n = len("".join(self.s))
if n % 8:
self.s.append("0" * (8 - n % 8))
self.put(0x000001, 24)
self.put(code, 8)
def bytes(self):
s = "".join(self.s)
s += "0" * (-len(s) % 8)
return bytes(int(s[i:i + 8], 2) for i in range(0, len(s), 8))
def field_stream(rng, w, h, frames, conceal=False):
"""frames: [(picture type per field, ...)] in decode order, e.g. [("I", "P"), ("P", "P"), ("B", "B")]"""
b = Bits()
mbw, mbh = (w + 15) // 16, 2 * ((h + 31) // 32)
fh = mbh * 8 # field height in lines (coded)
b.start(0xB3)
b.put(w, 12), b.put(h, 12), b.put(1, 4), b.put(3, 4), b.put(5000, 18), b.put(1, 1), b.put(112, 10), b.put(0, 1)
b.put(0, 1), b.put(0, 1)
b.start(0xB5)
b.put(1, 4), b.put(0x48, 8), b.put(0, 1), b.put(1, 2), b.put(0, 2), b.put(0, 2), b.put(0, 12), b.put(1, 1)
b.put(0, 8), b.put(0, 1), b.put(0, 2), b.put(0, 5)
b.start(0xB8)
b.put(0, 25), b.put(1, 1), b.put(0, 1)
# temporal references: decode order I P B P B ... is display order I B P B P (each B before the reference decoded
# just before it)
tr, d, last_ref = {}, 0, None
for k, f in enumerate(frames):
if f[0] != "B":
if last_ref is not None:
tr[last_ref] = d
d += 1
last_ref = k
else:
tr[k] = d
d += 1
tr[last_ref] = d
for k, (t0, t1) in enumerate(frames):
for fi, ptype in enumerate((t0, t1)):
parity = fi # top field first
pt = {"I": 1, "P": 2, "B": 3}[ptype]
b.start(0x00)
b.put(tr[k], 10), b.put(pt, 3), b.put(0xFFFF, 16)
if pt >= 2:
b.put(0, 1), b.put(7, 3)
if pt == 3:
b.put(0, 1), b.put(7, 3)
b.put(0, 1)
b.start(0xB5)
fc = (1, 1, 15, 15) if pt == 2 else (1, 1, 1, 1) if pt == 3 else (15, 15, 15, 15)
if pt == 1 and conceal:
fc = (1, 1, 15, 15)
b.put(8, 4)
for f in fc:
b.put(f, 4)
b.put(0, 2), b.put(1 + parity, 2), b.put(0, 1), b.put(0, 1), b.put(1 if conceal else 0, 1), b.put(0, 1)
b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1)
# the second field of the first frame has one reference: the first field (no skips, zero-vector or
# dual-prime prediction from its own parity)
only_first = k == 0 and fi == 1
for row in range(mbh // 2):
b.start(row + 1)
b.put(rng.choice((2, 4, 8)), 5), b.put(0, 1)
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] # [dir][r * 2 + c]
dc = [128, 128, 128]
col = 0
prev_dirs = None
while col < mbw:
# B skips repeat the previous vectors: only after zero ones (they stay inside the picture)
skip = (pt != 1 and not only_first and col > 0 and col < mbw - 1 and rng.random() < 0.15 and
prev_dirs is not None and (pt == 2 or not any(pmv[0] + pmv[1])))
if skip:
b.code(MBAI[2])
col += 1 # the skipped one
dc = [128, 128, 128]
if pt == 2:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
else:
b.code(MBAI[1])
if pt == 1 or rng.random() < 0.08:
b.code("1" if pt == 1 else (MBTYPE_P if pt == 2 else MBTYPE_B)["intra"])
if conceal:
# field_select, a concealment vector (the predictor again: motion codes 0), marker
b.put(0, 1), b.code(MOTION[0]), b.code(MOTION[0]), b.put(1, 1)
pmv[0][2:] = pmv[0][:2]
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
for blk in range(6):
comp = 0 if blk < 4 else blk - 3
target = rng.randrange(40, 216)
diff = target - dc[comp]
dc[comp] = target
size = abs(diff).bit_length()
b.code((DC_LUMA if comp == 0 else DC_CHROMA)[size])
if size:
b.put(diff if diff > 0 else diff + (1 << size) - 1, size)
ac_block(b, rng, 1, 0.5)
prev_dirs = None
col += 1
continue
dc = [128, 128, 128]
if pt == 2:
kind = rng.choice(("mc", "mc_coded", "mc_coded", "mc") if only_first else
("mc", "mc_coded", "mc_coded", "nomc_coded", "mc"))
dirs = (0,) if kind != "nomc_coded" else ()
b.code(MBTYPE_P[kind])
coded = kind != "mc"
else:
kind = rng.choice(("interp", "interp_coded", "bwd", "bwd_coded", "fwd", "fwd_coded"))
dirs = (0, 1) if kind.startswith("interp") else (1,) if kind.startswith("bwd") else (0,)
b.code(MBTYPE_B[kind])
coded = kind.endswith("coded")
if dirs:
choices = ["field", "16x8"] + (["dmv"] if pt == 2 and not only_first else [])
mt = rng.choice(choices)
b.put({"field": 1, "16x8": 2, "dmv": 3}[mt], 2)
for d in dirs:
motion(b, rng, pmv[d], mt, col, row, mbw, fh, parity, 0 if only_first else None)
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
if coded:
cbp = rng.choice(list(CBP))
b.code(CBP[cbp])
for blk in range(6):
if cbp & (32 >> blk):
ac_block(b, rng, 0, 0.6)
prev_dirs = dirs
col += 1
b.start(0xB7)
return b.bytes()
def ac_block(b, rng, first, more):
# escape-coded coefficients (6-bit run, 12-bit level), then end_of_block ("10"); a non-intra block needs one
n = first
count = 0
while n < 64 and (count == 0 and first == 0 or rng.random() < more):
run = rng.randrange(0, 6)
if n + run > 63:
break
level = rng.choice((-1, 1)) * rng.randrange(1, 24)
b.code("000001"), b.put(run, 6), b.put(level, 12)
n += run + 1
count += 1
b.code("10")
def put_motion(b, delta):
b.code(MOTION[abs(delta)])
if delta:
b.put(1 if delta < 0 else 0, 1)
def wrap(v):
return (v + 16) % 32 - 16
def motion(b, rng, pmv, mt, col, row, mbw, fh, parity, force_sel):
"""one direction's vectors for a field-picture macroblock, kept inside the reference field"""
def ok(mx, my, rows, y0):
sx, sy = col * 16 + (mx >> 1), y0 + (my >> 1)
return sx >= 0 and sx + 16 + (mx & 1) <= mbw * 16 and sy >= 0 and sy + rows + (my & 1) <= fh
def pick(px, py, rows, y0, extra=None):
for _ in range(50):
mx, my = rng.randrange(-12, 13), rng.randrange(-10, 11)
dx, dy = wrap(mx - px), wrap(my - py)
if ok(mx, my, rows, y0) and (extra is None or extra(mx, my)):
return dx, dy, mx, my
return None
if mt == "field":
sel = rng.randrange(2) if force_sel is None else force_sel
r = pick(pmv[0], pmv[1], 16, row * 16) or (wrap(-pmv[0]), wrap(-pmv[1]), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
elif mt == "16x8":
for half in range(2):
sel = rng.randrange(2) if force_sel is None else force_sel
px, py = pmv[half * 2], pmv[half * 2 + 1]
r = pick(px, py, 8, row * 16 + half * 8) or (wrap(-px), wrap(-py), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
pmv[half * 2], pmv[half * 2 + 1] = wrap(px + r[0]), wrap(py + r[1])
else:
# dual prime: the vector, its differential (0, +1, -1) and the derived opposite-parity vector
def dmv_ok(dmx, dmy):
def f(mx, my):
ox = ((mx + (mx > 0)) >> 1) + dmx
oy = ((my + (my > 0)) >> 1) + dmy + (-1 if parity == 0 else 1)
return ok(ox, oy, 16, row * 16)
return f
for dmx, dmy in rng.sample([(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1)], 7):
r = pick(pmv[0], pmv[1], 16, row * 16, dmv_ok(dmx, dmy))
if r:
break
assert r, "dual prime: no vector fits"
put_motion(b, r[0]), b.code({0: "0", 1: "10", -1: "11"}[dmx])
put_motion(b, r[1]), b.code({0: "0", 1: "10", -1: "11"}[dmy])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
+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})
+208
View File
@@ -0,0 +1,208 @@
# 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)