merge ws/video: containers mkv/avi/mp4/ts/ps/y4m (+writers), codecs Jpeg/Mpeg1/Vp8 inter/Video registry, AudioWrap, F.video.open

This commit is contained in:
4DBug committed 2026-10-31 10:22:17 -05:00
commit 2eaed46eea
96 files changed
+13398 -517

No files matched your search

+132
View File
@@ -898,3 +898,135 @@ do
Step.encode(cad)
end)
end
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
do
local Jpeg = require("@formats/codecs/Jpeg")
local Mpeg1 = require("@formats/codecs/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
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", if rgba then "rgba" else "yuv", s.width, s.height), 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
-- ------------------------------------------------------------------------------------------- ws-video: containers
do
local F = require("@formats")
local VB = require("@tests/gen/videobench")
local function clock(n: number, f: () -> number): (number, number)
local frames = f()
local dt = math.huge
for _ = 1, n do
local t0 = os.clock()
frames = f()
dt = math.min(dt, os.clock() - t0)
end
return dt, frames
end
for _, c in VB do
local data = buffer.fromstring(c.data)
local dtOpen = clock(3, function(): number
F.video.open(data, { audio = false })
return 1
end)
for _, rgba in { false, true } do
local ok, dt, frames = pcall(clock, 2, function(): number
local v = assert(F.video.open(data, { audio = false, rgba = rgba }))
local n = 0
while true do
local f, err = v:nextFrame()
if not f then
assert(err == nil, tostring(err))
break
end
n += 1
end
return n
end)
if ok then
print(string.format("%-8s %-30s %8.2f ms %7.1f fps (open %.1f ms)", runtime, string.format("video %s %s %s", c.size, c.name, if rgba then "rgba" else "yuv"), dt * 1000 / frames, frames / dt, dtOpen * 1000))
else
print(string.format("%-8s %-30s %s", runtime, "video " .. c.size .. " " .. c.name, tostring(dt)))
end
end
if c.name == "raw.y4m" then
local dt, frames = clock(2, function(): number
assert(F.convert(data, "avi", { quality = 85 }))
return 8
end)
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, "video " .. c.size .. " y4m -> mjpeg avi", dt * 1000 / frames, frames / dt))
end
end
end
-- ------------------------------------------------------------------------------------------- ws-video-vp8: fps
do
-- VP8 video (codecs/Vp8, tools/fixtures/vp8video.py): whole IVF streams (libvpx, panning testsrc2) through one
-- decoder object; frames per second. On LuaJIT the library's host module raises the trace limits (maxtrace=8000,
-- see src/Formats/host/init.luau): the second pair of lines runs with them, as the api does.
local Vp8 = require("@formats/codecs/Vp8")
local VB = require("@tests/gen/vp8video_bench")
local function run(tag: string)
for _, c in VB do
local b = buffer.fromstring(c.ivf)
local frames = {}
local p = 32
while p + 12 <= buffer.len(b) do
local n = buffer.readu32(b, p)
table.insert(frames, { p + 12, n })
p += 12 + n
end
local dt = bench(string.format("vp8 decode %dx%d%s", c.width, c.height, tag), 3, c.width * c.height * 1.5 * #frames, function()
local dec = Vp8.newDecoder()
for _, f in frames do
dec:decodeFrame(b, f[1], f[2])
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #frames .. " frames)", #frames / dt))
end
end
run("")
if runtime == "luajit" then
require("@formats/host")
run(" (jit tuned)")
end
end
+122
View File
@@ -0,0 +1,122 @@
# Shared helpers for the video fixture generators (mkv.py, avi.py, y4m.py, mpegts.py, videoapi.py), loaded by path.
# ffmpeg / ffprobe come from PATH when present (a build with libvpx / libopus / libvorbis), else nix (ffmpeg-full).
import json, os, shutil, subprocess, zlib
_FF = None
def ff_prefix():
global _FF
if _FF is None:
if shutil.which("ffmpeg") and shutil.which("ffprobe"):
_FF = []
else:
_FF = ["nix", "shell", "nixpkgs#ffmpeg-full", "-c"]
return _FF
def ffmpeg(args, cwd=None, input=None):
return subprocess.run(ff_prefix() + ["ffmpeg", "-v", "error", "-y"] + args, cwd=cwd, input=input,
capture_output=True, check=True).stdout
def ffprobe_json(path, extra):
out = subprocess.run(ff_prefix() + ["ffprobe", "-v", "error", "-of", "json"] + extra + [path],
capture_output=True, check=True).stdout
return json.loads(out)
def streams(path):
"""ffprobe streams: [{index, kind, codec, width, height, rate, channels, time_base}]"""
d = ffprobe_json(path, ["-show_streams"])
out = []
for s in d.get("streams", []):
e = {"index": s["index"], "kind": s.get("codec_type", ""), "codec": s.get("codec_name", "")}
if "width" in s:
e["width"], e["height"] = s["width"], s["height"]
if "sample_rate" in s:
e["rate"] = int(s["sample_rate"])
e["channels"] = s.get("channels", 0)
tb = s.get("time_base", "1/1").split("/")
e["tbn"], e["tbd"] = int(tb[0]), int(tb[1])
out.append(e)
return out
def packets(path):
"""ffprobe packets in file order: [{stream, pts, dur, key, size, crc}] (pts / dur in the stream time base)"""
d = ffprobe_json(path, ["-show_packets", "-show_data_hash", "crc32"])
out = []
for p in d.get("packets", []):
e = {"stream": p["stream_index"], "key": "K" in p.get("flags", ""), "size": int(p["size"]),
"crc": int(p["data_hash"].split(":")[1], 16)}
if p.get("pts") not in (None, "N/A"):
e["pts"] = int(p["pts"])
if p.get("duration") not in (None, "N/A"):
e["dur"] = int(p["duration"])
out.append(e)
return out
def yuv_frames(path, w, h, extra=None, codec=None):
"""the first video stream decoded by ffmpeg to yuv420p (yuvj420p for MJPEG: full range, no conversion): a list of
frame bytes"""
pix = "yuvj420p" if codec == "mjpeg" else "yuv420p"
raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix, "-"])
n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
return [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)]
def pcm_f32(path, extra=None):
"""the first audio stream decoded by ffmpeg to interleaved f32le"""
return ffmpeg(["-i", path] + (extra or []) + ["-map", "0:a:0", "-f", "f32le", "-"])
def crc(b):
return zlib.crc32(b) & 0xffffffff
def ebml_vint(b, p):
"""(value, length) of an EBML vint (marker removed; all ones -> -1)"""
first = b[p]
n = 1
mask = 0x80
while n <= 8 and not first & mask:
n += 1
mask >>= 1
v = first & (mask - 1)
ones = v == mask - 1
for i in range(1, n):
v = (v << 8) | b[p + i]
ones = ones and b[p + i] == 255
return (-1 if ones else v), n
def ebml_id(b, p):
first = b[p]
n = 1 if first >= 0x80 else 2 if first >= 0x40 else 3 if first >= 0x20 else 4
return int.from_bytes(b[p:p + n], "big"), n
def mkv_unknown_clusters(data):
"""the same Matroska file with every Cluster's size field rewritten to 'unknown' (same length)"""
b = bytearray(data)
p = 0
# EBML header
i, n = ebml_id(b, p)
s, m = ebml_vint(b, p + n)
p += n + m + s
i, n = ebml_id(b, p) # Segment
s, m = ebml_vint(b, p + n)
p += n + m
while p < len(b):
i, n = ebml_id(b, p)
s, m = ebml_vint(b, p + n)
if i == 0x1F43B675:
b[p + n] = (0xFF >> (m - 1)) if m < 8 else 0x01
for k in range(1, m):
b[p + n + k] = 0xFF
if m == 1:
b[p + n] = 0xFF
p += n + m + s
return bytes(b)
+53
View File
@@ -0,0 +1,53 @@
-- tools/fixtures/_video_encode: run by tools/fixtures/videoenc.py (luau, from the repo root) so ffprobe / ffmpeg can
-- check our video writers: remuxes and re-encodes the container fixtures (tests/gen/mkv_cases, avi_cases, mp4_cases) and the
-- animated GIF of tests/gen/videoenc_src, and prints "<name> <hex>" lines (or "<name> ERR <message>").
local F = require("@formats")
local Mkv = require("@tests/gen/mkv_cases")
local Avi = require("@tests/gen/avi_cases")
local Mp4 = require("@tests/gen/mp4_cases")
local Src = require("@tests/gen/videoenc_src")
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
local function find(list: any, name: string): string
for _, c in list do
if c.name == name then
return c.data
end
end
error("no fixture " .. name)
end
local JOBS = {
{ "remux.webm", find(Mkv, "vp8_opus.webm"), "webm", {} },
{ "copy.mkv", find(Mkv, "mjpeg_pcm.mkv"), "mkv", {} },
{ "vp8_mjpeg.mkv", find(Mkv, "vp8_opus.webm"), "mkv", { reencode = true, quality = 92 } },
{ "copy.avi", find(Avi, "mjpeg_pcm.avi"), "avi", {} },
{ "vp8_mjpeg.avi", find(Mkv, "vp8_opus.webm"), "avi", { quality = 92 } },
{ "mpeg1_mjpeg.avi", find(Mkv, "mpeg1_mp2.mkv"), "avi", { quality = 92 } },
{ "gif.avi", Src.gif, "avi", { quality = 95 } },
{ "gif.mkv", Src.gif, "mkv", { quality = 95 } },
{ "gif.y4m", Src.gif, "y4m", {} },
{ "webm.y4m", find(Mkv, "vp8_opus.webm"), "y4m", {} },
{ "gif.mp4", Src.gif, "mp4", { quality = 95 } },
{ "pcm.mov", find(Mkv, "mjpeg_pcm.mkv"), "mov", {} },
{ "h264_aac.mov", find(Mp4, "h264_aac.mp4"), "mov", {} },
{ "h264_aac.mkv", find(Mp4, "h264_aac.mp4"), "mkv", {} },
{ "vp8_mjpeg.mp4", find(Mkv, "vp8_opus.webm"), "mp4", { quality = 92 } },
{ "flac.mp4", find(Mp4, "mjpeg_flac.mp4"), "mp4", {} },
}
for _, j in JOBS do
local name, data, fmt, opts = j[1], j[2], j[3], j[4]
local out, err = F.convert(buffer.fromstring(data), fmt, opts)
if out then
print(name .. " " .. hex(out))
else
print(name .. " ERR " .. string.gsub(tostring(err), "%s", "_"))
end
end
+152
View File
@@ -0,0 +1,152 @@
# AVI fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + PCM with idx1, the same with OpenDML indexes added
# here, MJPEG + IMA
# ADPCM, MPEG-1 + MP2, uncompressed BGR24 / BGRA / I420 video) and edits made here (the OpenDML indexes renamed to
# JUNK so idx1 is used; idx1 renamed too so the movi list is scanned; a truncated file). For each file: ffprobe's
# streams and packets, ffmpeg's frames (CRC-32 of yuv420p, or of rgba for uncompressed RGB; the first frames raw for
# PSNR checks) and ffmpeg's decoded audio (f32).
# tests/gen/avi_cases.luau { { name, data, streams, packets, frames, yuv, rgba, pcm, ... } }
import importlib.util, os, tempfile
_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"]
W, H = 160, 120
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H)]
def sine(rate, ch=1):
return ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate, "-ac", str(ch)]
def rename(data, old, new):
"""every chunk id `old` renamed to `new` (same length), found by walking the RIFF lists"""
b = bytearray(data)
def walk(p, end):
while p + 8 <= end:
cid = bytes(b[p:p + 4])
size = int.from_bytes(b[p + 4:p + 8], "little")
if cid in (b"RIFF", b"LIST"):
walk(p + 12, min(end, p + 8 + size))
elif cid == old:
b[p:p + 4] = new
p += 8 + size + (size & 1)
walk(0, len(b))
return bytes(b)
def chunks(b, p, end):
out = []
while p + 8 <= end:
cid = b[p:p + 4]
size = int.from_bytes(b[p + 4:p + 8], "little")
out.append((cid, p, size))
p += 8 + size + (size & 1)
return out
def ck(cid, body):
return cid + len(body).to_bytes(4, "little") + body + (b"\0" if len(body) & 1 else b"")
def add_odml(data):
"""the same AVI with OpenDML indexes: an indx super index in every strl pointing at an ix## standard index
appended to the movi list (built from idx1, which is kept)"""
b = data
top = chunks(b, 12, len(b))
hdrl = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"hdrl")
movi = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"movi")
idx1 = next(c for c in top if c[0] == b"idx1")
movi_base = movi[1] + 8 # the 'movi' fourcc
streams = {}
for k in range(idx1[2] // 16):
e = idx1[1] + 8 + k * 16
cid = b[e:e + 4]
flags, off, size = (int.from_bytes(b[e + 4 + 4 * i:e + 8 + 4 * i], "little") for i in range(3))
sn = int(cid[:2])
streams.setdefault(sn, (cid, []))[1].append((movi_base + off + 8, size, bool(flags & 0x10)))
n = len([c for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]) if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl"])
INDX = 8 + 24 + 16 # one super index entry
delta = n * INDX
# the ix## chunks at the end of the movi list
ixs = []
pos = movi[1] + 8 + movi[2] + delta # where the first ix chunk starts (movi grows by them)
for sn in range(n):
cid, ents = streams.get(sn, (b"%02dwb" % sn, []))
body = (2).to_bytes(2, "little") + bytes([0, 1]) + len(ents).to_bytes(4, "little") + cid + \
(0).to_bytes(8, "little") + bytes(4)
for off, size, key in ents:
body += (off + delta).to_bytes(4, "little") + (size | (0 if key else 0x80000000)).to_bytes(4, "little")
chunk = ck(b"ix%02d" % sn, body)
ixs.append((pos, len(chunk), len(ents), cid, chunk))
pos += len(chunk)
# hdrl with an indx in every strl
out_h = b""
si = 0
for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]):
raw = b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)]
if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl":
p, ln, cnt, cid, _ = ixs[si]
indx = (4).to_bytes(2, "little") + bytes([0, 0]) + (1).to_bytes(4, "little") + cid + bytes(12) + \
p.to_bytes(8, "little") + ln.to_bytes(4, "little") + cnt.to_bytes(4, "little")
raw = ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + ck(b"indx", indx))
si += 1
out_h += raw
out = b""
for c in top:
if c is hdrl:
out += ck(b"LIST", b"hdrl" + out_h)
elif c is movi:
out += ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + b"".join(x[4] for x in ixs))
else:
out += b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)]
res = b"RIFF" + (len(out) + 4).to_bytes(4, "little") + b"AVI " + out
assert res[ixs[0][0]:ixs[0][0] + 2] == b"ix", "odml layout"
return res
def case(tmp, name, rgba=False, raw_frames=2, pcm_frames=8192):
path = os.path.join(tmp, name)
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
vs = [s for s in c["streams"] if s["kind"] == "video"]
if vs:
w, h = vs[0]["width"], vs[0]["height"]
if rgba:
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
c["rgba"] = [V.crc(raw[i:i + n]) for i in range(0, len(raw) - n + 1, n)]
else:
frames = V.yuv_frames(path, w, h, codec=vs[0]["codec"])
c["frames"] = [V.crc(f) for f in frames]
c["yuv"] = frames[:raw_frames]
if any(s["kind"] == "audio" for s in c["streams"]):
pcm = V.pcm_f32(path)
c["pcm"] = pcm[:pcm_frames * 4]
c["pcmBytes"] = len(pcm)
return c
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="avifx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.avi")
ff(*SRC, *sine(22050), "-t", "1", "-c:v", "mjpeg", "-q:v", "5", "-c:a", "adpcm_ima_wav", "mjpeg_ima.avi")
ff(*SRC, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "500k", "-c:a", "mp2", "mpeg1_mp2.avi")
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgr24", "bgr24.avi")
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgra", "bgra.avi")
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "yuv420p", "i420.avi")
ff(*SRC, *sine(8000), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_u8", "pcm_u8.avi")
full = open(os.path.join(tmp, "mjpeg_pcm.avi"), "rb").read()
idx1 = rename(full, b"indx", b"JUNK")
open(os.path.join(tmp, "idx1_only.avi"), "wb").write(idx1)
open(os.path.join(tmp, "no_index.avi"), "wb").write(rename(idx1, b"idx1", b"JUNK"))
open(os.path.join(tmp, "odml.avi"), "wb").write(add_odml(full))
cases = [case(tmp, "mjpeg_pcm.avi"), case(tmp, "mjpeg_ima.avi"), case(tmp, "mpeg1_mp2.avi"),
case(tmp, "bgr24.avi", rgba=True), case(tmp, "bgra.avi", rgba=True), case(tmp, "i420.avi"),
case(tmp, "pcm_u8.avi"), case(tmp, "idx1_only.avi"), case(tmp, "no_index.avi"),
case(tmp, "odml.avi")]
cases.append({"name": "truncated.avi", "data": full[: len(full) * 6 // 10], "truncated": True})
ctx.emit("avi_cases", cases)
+317
View File
@@ -0,0 +1,317 @@
# Motion-JPEG fixtures for codecs/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources,
# yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame:
# yuv CRC-32 of the yuv420p planes codecs/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes
# (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged
# ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact
# rgba CRC-32 of djpeg -dct int (bit-exact)
# ff for the first frame of each stream: ffmpeg's own decode as yuvj420p and rgba (PSNR thresholds: ffmpeg's
# IDCT and its swscale conversions differ from libjpeg's; rgba for the small streams and one 320x240)
# Variants: frames written with ffmpeg's default (annex K) Huffman tables and their DHT segments stripped, as
# Motion-JPEG in AVI leaves them out; an AVI1 APP0 segment and junk after EOI; an interlaced frame (two fields,
# each its own half-height JPEG with an AVI1 segment of polarity 1, back to back).
# tests/gen/mjpeg_cases.luau { streams = { { name, width, height, sampling, frames = { { data, yuv, rgba } },
# ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } }
# tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our
# encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file
# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources
# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/Deflate):
# Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33.
import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib
FF = ["-hide_banner", "-loglevel", "error", "-y"]
def b64(b):
return base64.b64encode(b).decode()
def z64(b):
return base64.b64encode(zlib.compress(b, 9)).decode()
def tool(ctx, pkg, name):
p = shutil.which(name)
if p:
return p
return ctx.nix(pkg, ["sh", "-c", "command -v " + name]).decode().strip()
def store(attr):
return subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], check=True,
capture_output=True, text=True).stdout.strip().split("\n")[0]
class TurboJpeg:
"""the TurboJPEG 3 API (libjpeg-turbo) through ctypes: raw YUV planes in and out"""
def __init__(self):
lib = ctypes.CDLL(os.path.join(store("libjpeg_turbo.out"), "lib", "libturbojpeg.so"))
lib.tj3Init.restype = ctypes.c_void_p
lib.tj3Init.argtypes = [ctypes.c_int]
lib.tj3Set.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
lib.tj3Get.argtypes = [ctypes.c_void_p, ctypes.c_int]
lib.tj3DecompressHeader.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
lib.tj3DecompressToYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_int]
lib.tj3CompressFromYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)]
lib.tj3Free.argtypes = [ctypes.c_void_p]
self.lib = lib
self.dec = lib.tj3Init(1)
self.enc = lib.tj3Init(0)
def planes(self, jpeg):
"""-> w, h, subsamp (0 444, 1 422, 2 420), Y, Cb, Cr (TurboJPEG's unpadded-alignment plane layout)"""
L = self.lib
assert L.tj3DecompressHeader(self.dec, jpeg, len(jpeg)) == 0
w, h, ss = L.tj3Get(self.dec, 5), L.tj3Get(self.dec, 6), L.tj3Get(self.dec, 4)
mw, mh = {0: (1, 1), 1: (2, 1), 2: (2, 2)}[ss]
pw, ph = -(-w // mw) * mw, -(-h // mh) * mh
cw, ch = pw // mw, ph // mh
out = ctypes.create_string_buffer(pw * ph + 2 * cw * ch)
assert L.tj3DecompressToYUV8(self.dec, jpeg, len(jpeg), out, 1) == 0
raw = out.raw
return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch)
def yuv420(self, jpeg):
"""what codecs/Jpeg { yuv = true } must produce for this frame"""
w, h, ss, (Y, pw), cb, cr = self.planes(jpeg)
out = bytearray()
for y in range(h):
out += Y[y * pw:y * pw + w]
ow, oh = (w + 1) // 2, (h + 1) // 2
for P, cw, ch in (cb, cr):
for y in range(oh):
if ss == 2:
out += P[y * cw:y * cw + ow]
elif ss == 1:
a = P[2 * y * cw:2 * y * cw + ow]
b = P[(2 * y + 1) * cw:(2 * y + 1) * cw + ow] if 2 * y + 1 < ch else a
out += bytes((p + q + 1) >> 1 for p, q in zip(a, b))
else:
r0 = P[2 * y * cw:2 * y * cw + cw]
r1 = P[(2 * y + 1) * cw:(2 * y + 1) * cw + cw] if 2 * y + 1 < ch else r0
row = bytearray()
for x in range(ow):
x1 = min(2 * x + 1, w - 1)
row.append((r0[2 * x] + r0[x1] + r1[2 * x] + r1[x1] + 2) >> 2)
out += row
return bytes(out)
def compress420(self, yuv, w, h, quality):
"""yuv420p (w x h luma) -> tj3CompressFromYUV8's JPEG; TurboJPEG wants the luma plane padded to even sizes"""
pw, ph = w + (w & 1), h + (h & 1)
Y = yuv[:w * h]
buf = bytearray()
for y in range(ph):
r = Y[min(y, h - 1) * w:min(y, h - 1) * w + w]
buf += r + r[-1:] * (pw - w)
buf += yuv[w * h:]
L = self.lib
L.tj3Set(self.enc, 3, quality)
L.tj3Set(self.enc, 4, 2)
p, n = ctypes.c_void_p(), ctypes.c_size_t(0)
assert L.tj3CompressFromYUV8(self.enc, bytes(buf), w, 1, h, ctypes.byref(p), ctypes.byref(n)) == 0
data = ctypes.string_at(p, n.value)
L.tj3Free(p)
return data
def split(stream):
"""a Motion-JPEG elementary stream -> its JPEG frames (SOI .. EOI)"""
frames, pos = [], 0
while True:
s = stream.find(b"\xff\xd8", pos)
if s < 0:
return frames
p = s + 2
while True:
m = stream[p + 1]
if m == 0xD9:
p += 2
break
ln = (stream[p + 2] << 8) | stream[p + 3]
p += 2 + ln
if m == 0xDA:
while not (stream[p] == 0xFF and stream[p + 1] not in (0,) and not 0xD0 <= stream[p + 1] <= 0xD7):
p += 1
frames.append(stream[s:p])
pos = p
def strip_dht(jpeg):
out, pos = bytearray(jpeg[:2]), 2
while pos < len(jpeg):
m = jpeg[pos + 1]
if m == 0xDA:
out += jpeg[pos:]
break
ln = (jpeg[pos + 2] << 8) | jpeg[pos + 3]
if m != 0xC4:
out += jpeg[pos:pos + 2 + ln]
pos += 2 + ln
return bytes(out)
def avi1(jpeg, polarity):
"""an AVI1 APP0 segment right after SOI (polarity, 0, field size, field size less padding)"""
n = len(jpeg) + 18
body = b"AVI1" + bytes([polarity, 0]) + n.to_bytes(4, "big") + n.to_bytes(4, "big")
return jpeg[:2] + b"\xff\xe0" + (len(body) + 2).to_bytes(2, "big") + body + jpeg[2:]
def generate(ctx):
work = tempfile.mkdtemp(prefix="formats-mjpeg-")
try:
_generate(ctx, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def _generate(ctx, work):
ffmpeg = tool(ctx, "ffmpeg", "ffmpeg")
djpeg = os.path.join(os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v djpeg"]).decode().strip()), "djpeg")
tj = TurboJpeg()
W = lambda n: os.path.join(work, n)
def ff(*args):
subprocess.run([ffmpeg] + FF + list(args), check=True, capture_output=True)
def source(src, w, h, frames, extra=()):
# a raw yuv420p / yuv444p source scaled to w x h (ffmpeg's lavfi sources only make even sizes)
sw, sh = w + (w & 1), h + (h & 1)
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=25" % (src, sw, sh), "-frames:v", str(frames),
"-vf", "scale=%d:%d" % (w, h)] + list(extra)
def rgba_crc(jpeg):
p = W("f.jpg")
open(p, "wb").write(jpeg)
r = subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout
return zlib.crc32(rgba_of_pnm(r))
def rgba_of_pnm(d):
# djpeg's "P6\n<w> <h>\n255\n" + RGB -> RGBA
parts = d.split(maxsplit=3)
w, h = int(parts[1]), int(parts[2])
rgb = d[len(d) - w * h * 3:]
out = bytearray(w * h * 4)
out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
out[3::4] = b"\xff" * (w * h)
return bytes(out)
def ffdecode(jpeg, fmt):
p = W("ff.jpg")
open(p, "wb").write(jpeg)
o = W("ff.raw")
ff("-f", "mjpeg", "-i", p, "-f", "rawvideo", "-pix_fmt", fmt, o)
return open(o, "rb").read()
streams = []
def stream(name, src, w, h, pix, nframes, encargs=(), mutate=None):
out = W(name + ".mjpeg")
ff(*source(src, w, h, nframes), "-pix_fmt", pix, "-c:v", "mjpeg", *encargs, "-f", "mjpeg", out)
frames = split(open(out, "rb").read())
assert len(frames) == nframes, (name, len(frames))
entries = []
for fr in frames:
ref = fr
data = mutate(fr) if mutate else fr
entries.append({"data": b64(data), "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)})
ref = {"yuv": z64(ffdecode(frames[0], "yuvj420p"))}
if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240
ref["rgba"] = z64(ffdecode(frames[0], "rgba"))
streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref})
stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3"))
stream("testsrc_422", "testsrc2", 320, 240, "yuvj422p", 4, ("-q:v", "3"))
stream("mandel_444", "mandelbrot", 176, 144, "yuvj444p", 2, ("-q:v", "4"))
stream("odd_420", "mandelbrot", 173, 97, "yuvj420p", 3, ("-q:v", "6"))
stream("odd_422", "testsrc2", 97, 61, "yuvj422p", 3, ("-q:v", "2"))
stream("odd_444", "testsrc2", 33, 17, "yuvj444p", 2, ("-q:v", "2"))
stream("q31_420", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "31"))
# Motion-JPEG as AVI stores it: the annex K tables left out
stream("nodht_420", "mandelbrot", 320, 240, "yuvj420p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
stream("nodht_422", "testsrc2", 176, 144, "yuvj422p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
# an AVI1 segment (progressive, polarity 0) and padding / junk after EOI
stream("avi1_junk", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "5"),
lambda f: avi1(f, 0) + b"\0\0\0\0\xff\xd9junk after the image\xff\xd8")
# an interlaced frame: two fields of 320 x 120, each its own JPEG with AVI1 polarity 1, back to back
full = W("full.yuv")
ff(*source("testsrc2", 320, 240, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", full)
fy = open(full, "rb").read()
fw, fh = 320, 240
fields, fsrc = [], []
for k in range(2):
rows = b"".join(fy[y * fw:(y + 1) * fw] for y in range(k, fh, 2))
cw = fw // 2
chroma = b""
for pl in range(2):
base = fw * fh + pl * cw * (fh // 2)
chroma += b"".join(fy[base + y * cw:base + (y + 1) * cw] for y in range(k, fh // 2, 2))
p = W("field%d.yuv" % k)
open(p, "wb").write(rows + chroma)
o = W("field%d.jpg" % k)
ff("-f", "rawvideo", "-pix_fmt", "yuvj420p", "-s", "%dx%d" % (fw, fh // 2), "-i", p, "-pix_fmt", "yuvj420p",
"-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
fields.append(open(o, "rb").read())
data = avi1(fields[0], 1) + b"\0" * 7 + avi1(fields[1], 1)
def weave(a, b, w, hf, bpp):
out = bytearray()
for y in range(2 * hf):
src, k = (a, y // 2) if y % 2 == 0 else (b, y // 2)
out += src[k * w * bpp:(k + 1) * w * bpp]
return bytes(out)
ya, yb = tj.yuv420(fields[0]), tj.yuv420(fields[1])
hf, cw, chf = fh // 2, fw // 2, fh // 4
wy = weave(ya[:fw * hf], yb[:fw * hf], fw, hf, 1)
for pl in range(2):
o = fw * hf + pl * cw * chf
wy += weave(ya[o:o + cw * chf], yb[o:o + cw * chf], cw, chf, 1)
def rgba_raw(jpeg):
p = W("f.jpg")
open(p, "wb").write(jpeg)
return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout)
wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4)
ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": b64(data), "width": fw, "height": fh,
"yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": z64(fy)}})
# the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8
enc = []
for name, src, w, h, qs in (("testsrc_320x240", "testsrc2", 320, 240, (50, 75, 90)),
("mandel_176x144", "mandelbrot", 176, 144, (30, 95)),
("odd_97x61", "testsrc2", 97, 61, (75,)), ("tiny_7x5", "mandelbrot", 7, 5, (90,)),
("one_1x1", "testsrc2", 1, 1, (90,))):
p = W(name + ".yuv")
ff(*source(src, max(w, 2), max(h, 2), 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("s.yuv"))
raw = open(W("s.yuv"), "rb").read()
if (w, h) == (1, 1):
raw = raw[:1] + raw[4:5] + raw[5:6] # the top-left luma and chroma samples of a 2x2 source
open(p, "wb").write(raw)
for q in qs:
want = tj.compress420(raw, w, h, q)
got = ffdecode(want, "yuvj420p") if w > 1 else None
psnr = 99.0
if got:
se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h]))
psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se)
enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": z64(raw),
"want": b64(want), "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)})
ctx.emit("mjpeg_enc", enc)
bench = []
for name, w, h, pix in (("320x240 4:2:0", 320, 240, "yuvj420p"), ("640x480 4:2:0", 640, 480, "yuvj420p"),
("640x480 4:2:2", 640, 480, "yuvj422p")):
o = W("bench.mjpeg")
ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
fr = split(open(o, "rb").read())[0]
bench.append({"name": name, "width": w, "height": h, "data": b64(fr), "yuv": zlib.crc32(tj.yuv420(fr))})
srcs = []
for w, h in ((320, 240), (640, 480)):
ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv"))
srcs.append({"width": w, "height": h, "yuv": z64(open(W("b.yuv"), "rb").read())})
ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs})
+131
View File
@@ -0,0 +1,131 @@
# Matroska / WebM fixtures (tools/fixtures.py): files made by ffmpeg (libvpx VP8 + Opus / Vorbis WebM, MJPEG + PCM,
# MPEG-1 + MP3, srt subtitles) and mkvmerge (Xiph / EBML / fixed lacing, header-removal compression), plus edits made
# here (every cluster rewritten to an unknown size, a truncated file). For each file: ffprobe's streams and packets
# (pts, duration, keyframe flag, size, CRC-32 of the data), ffmpeg's yuv420p frames (CRC-32 each; the first frames
# raw for PSNR checks) and ffmpeg's decoded audio (f32).
# tests/gen/mkv_cases.luau { { name, data, streams, packets, frames = { crc }, yuv = { raw frame }, pcm, ... } }
import importlib.util, os, subprocess, tempfile
_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"]
W, H = 160, 120
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=15" % (W, H)]
MOVE = ["-f", "lavfi", "-i", "mandelbrot=size=%dx%d:rate=15" % (W, H)]
def sine(rate, ch=1):
if ch == 1:
return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate]
return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate, "-ac", str(ch)]
def case(ctx, tmp, name, raw_frames=2, audio=True, video=True, pcm_frames=8192):
path = os.path.join(tmp, name)
data = open(path, "rb").read()
c = {"name": name, "data": data, "streams": V.streams(path), "packets": V.packets(path)}
vs = [s for s in c["streams"] if s["kind"] == "video"]
if video and vs:
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
c["frames"] = [V.crc(f) for f in frames]
c["yuv"] = frames[:raw_frames]
if audio and any(s["kind"] == "audio" for s in c["streams"]):
pcm = V.pcm_f32(path)
c["pcm"] = pcm if pcm_frames is None else pcm[:pcm_frames * 4]
c["pcmBytes"] = len(pcm)
return c
def el(i, payload):
"""an EBML element: id (int), payload bytes"""
n = len(payload)
size = bytes([0x01]) + n.to_bytes(7, "big")
return i.to_bytes((i.bit_length() + 7) // 8, "big") + size + payload
def uint(v):
return v.to_bytes(max(1, (v.bit_length() + 7) // 8), "big")
def lacing_file(ctx):
"""A_PCM/INT/LIT mono 8 kHz s16 in three SimpleBlocks, Xiph-, EBML- and fixed-laced (DefaultDuration 10 ms)"""
rng = ctx.rng(7)
frames = [bytes(rng.randrange(256) for _ in range(2 * n)) for n in (80, 40, 120, 80, 80, 80, 80, 80, 80, 80)]
head = el(0x1A45DFA3, el(0x4282, b"matroska") + el(0x4287, uint(4)) + el(0x4285, uint(2)))
info = el(0x1549A966, el(0x2AD7B1, uint(1000000)) + el(0x4D80, b"fixture") + el(0x5741, b"fixture"))
track = el(0xAE, el(0xD7, uint(1)) + el(0x73C5, uint(1)) + el(0x83, uint(2)) + el(0x86, b"A_PCM/INT/LIT") +
el(0x23E383, uint(10000000)) + el(0xE1, el(0xB5, __import__("struct").pack(">d", 8000.0)) +
el(0x9F, uint(1)) + el(0x6264, uint(16))))
tracks = el(0x1654AE6B, track)
def xiph(sizes):
out = b""
for s in sizes:
out += b"\xff" * (s // 255) + bytes([s % 255])
return out
def ebmlnum(v):
n = 1
while v >= (1 << (7 * n)) - 1:
n += 1
return ((1 << (7 * n)) | v).to_bytes(n, "big")
def sebml(v, n=2):
return ((1 << (7 * n)) | (v + (1 << (7 * n - 1)) - 1)).to_bytes(n, "big")
def block(rel, flags, body):
return el(0xA3, b"\x81" + rel.to_bytes(2, "big") + bytes([flags]) + body)
f = frames
b1 = block(0, 0x80 | 0x02, bytes([2]) + xiph([len(f[0]), len(f[1])]) + f[0] + f[1] + f[2])
sizes = [len(f[3]), len(f[4]), len(f[5])]
b2 = block(40, 0x80 | 0x06, bytes([2]) + ebmlnum(sizes[0]) + sebml(sizes[1] - sizes[0]) + f[3] + f[4] + f[5])
b3 = block(70, 0x80 | 0x04, bytes([3]) + f[6] + f[7] + f[8] + f[9])
cluster = el(0x1F43B675, el(0xE7, uint(0)) + b1 + b2 + b3)
return head + el(0x18538067, info + tracks + cluster)
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="mkvfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
ff(*SRC, *sine(48000), "-t", "1", "-c:v", "libvpx", "-g", "8", "-auto-alt-ref", "1", "-lag-in-frames", "8",
"-b:v", "300k", "-c:a", "libopus", "-b:a", "48k", "vp8_opus.webm")
ff(*MOVE, *sine(44100, 2), "-t", "1", "-c:v", "libvpx", "-g", "30", "-b:v", "200k", "-c:a", "libvorbis",
"vp8_vorbis.webm")
ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.mkv")
ff(*MOVE, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "400k", "-c:a", "mp2", "-b:a", "64k",
"mpeg1_mp2.mkv")
ff(*SRC, *sine(48000, 2), "-t", "1", "-c:v", "libvpx", "-g", "15", "-c:a", "flac", "vp8_flac.mkv")
open(os.path.join(tmp, "subs.srt"), "w").write(
"1\n00:00:00,100 --> 00:00:00,500\nHello\n\n2\n00:00:00,600 --> 00:00:00,900\nWorld <b>bold</b>\n\n")
ff(*SRC, "-i", "subs.srt", "-t", "1", "-c:v", "mjpeg", "-c:s", "srt", "subs.mkv")
# mkvmerge: Xiph lacing (Vorbis) and zlib content compression; a file crafted here with all three lacings
mk = lambda *a: subprocess.run(["nix", "shell", "nixpkgs#mkvtoolnix-cli", "-c", "mkvmerge", "-q"] + list(a),
cwd=tmp, check=False, capture_output=True)
mk("-o", "laced_vorbis.mkv", "vp8_vorbis.webm")
ff(*sine(44100), "-t", "1", "-c:a", "libvorbis", "v.ogg")
mk("-o", "zlib_vorbis.mka", "--compression", "0:zlib", "v.ogg")
open(os.path.join(tmp, "lacing.mka"), "wb").write(lacing_file(ctx))
# unknown-size clusters, a truncated file
open(os.path.join(tmp, "unknown_clusters.webm"), "wb").write(
V.mkv_unknown_clusters(open(os.path.join(tmp, "vp8_opus.webm"), "rb").read()))
full = open(os.path.join(tmp, "mjpeg_pcm.mkv"), "rb").read()
cases = [
case(ctx, tmp, "vp8_opus.webm"),
case(ctx, tmp, "vp8_vorbis.webm"),
case(ctx, tmp, "mjpeg_pcm.mkv"),
case(ctx, tmp, "mpeg1_mp2.mkv"),
case(ctx, tmp, "vp8_flac.mkv"),
case(ctx, tmp, "subs.mkv", audio=False),
case(ctx, tmp, "unknown_clusters.webm"),
]
for name in ("laced_vorbis.mkv", "zlib_vorbis.mka", "lacing.mka"):
if os.path.exists(os.path.join(tmp, name)):
cases.append(case(ctx, tmp, name))
cut = full[: len(full) * 7 // 10]
cases.append({"name": "truncated.mkv", "data": cut, "truncated": True})
ctx.emit("mkv_cases", cases)
+50
View File
@@ -0,0 +1,50 @@
# MP4 / MOV fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + AAC MP4, MJPEG + PCM MOV, H.264 with B-frames
# + AAC (edit lists), fragmented MP4, MPEG-1 + Opus, MJPEG + FLAC, MJPEG + MP2 MOV) with ffprobe's streams and packets,
# ffmpeg's frames (CRC-32; the first raw) and audio (f32). Our MP4 / MOV writer's files are checked in
# tools/fixtures/videoenc.py.
# tests/gen/mp4_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } }
import importlib.util, os, tempfile
_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"]
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=12"]
def aud(rate, ch=1):
return ["-f", "lavfi", "-i", "sine=frequency=550:sample_rate=%d" % rate, "-ac", str(ch)]
def case(tmp, name):
path = os.path.join(tmp, name)
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
vs = [s for s in c["streams"] if s["kind"] == "video"]
if vs:
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
c["frames"] = [V.crc(f) for f in frames]
c["yuv"] = frames[:2]
if any(s["kind"] == "audio" for s in c["streams"]):
pcm = V.pcm_f32(path)
c["pcm"] = pcm[:8192 * 4]
c["pcmBytes"] = len(pcm)
return c
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="mp4fx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-q:v", "4", "-c:a", "aac", "-b:a", "96k", "mjpeg_aac.mp4")
ff(*SRC, *aud(48000, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_s16le", "mjpeg_pcm.mov")
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac",
"h264_aac.mp4")
ff(*SRC, *aud(48000), "-t", "1", "-c:v", "mjpeg", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov",
"fragmented.mp4")
ff(*SRC, *aud(48000), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-c:a", "libopus", "mpeg1_opus.mp4")
ff(*SRC, *aud(44100, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "flac", "mjpeg_flac.mp4")
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-c:a", "mp2", "mjpeg_mp2.mov")
cases = [case(tmp, n) for n in ("mjpeg_aac.mp4", "mjpeg_pcm.mov", "h264_aac.mp4", "fragmented.mp4",
"mpeg1_opus.mp4", "mjpeg_flac.mp4", "mjpeg_mp2.mov")]
ctx.emit("mp4_cases", cases)
+170
View File
@@ -0,0 +1,170 @@
# MPEG-1 video fixtures for codecs/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary
# streams made by ffmpeg's mpeg1video encoder (testsrc2 / mandelbrot, several bit rates, odd sizes, custom matrices,
# B-frames, a size change), their access units, and ffmpeg's own decode of each as references:
# 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) }
# 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
# Binary fields are base64 (file, units' data) or base64 of zlib data (frames: the test inflates them with
# codecs/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and
# few whole frames the set stays near 10 MB.
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", "mpeg1video", "-f", "mpeg1video"]
# a non-default intra matrix (steeper) and inter matrix (rising), 64 values in natural order
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, rate, t):
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
# name: (ffmpeg input + encoder args, size patched into the sequence headers or None, rgba sample picks, yuv picks)
CASES = {
"qcif_200k": (src("testsrc2", 176, 144, 25, 1.2) + ["-b:v", "200k", "-bf", "0", "-g", "50"], None),
"main_450k": (src("testsrc2", 320, 180, 24, 1.5) + ["-b:v", "450k", "-bf", "0", "-g", "48"], None),
"zoom_150k": (src("mandelbrot", 320, 180, 24, 1.5) + ["-b:v", "150k", "-bf", "0", "-g", "48"], None),
"zoom_1500k": (src("mandelbrot", 320, 180, 24, 1) + ["-b:v", "1500k", "-bf", "0", "-g", "48"], None),
"big_1000k": (src("testsrc2", 640, 360, 24, 0.5) + ["-b:v", "1000k", "-bf", "0", "-g", "36"], None),
# odd sizes: ffmpeg's encoder only writes even ones, so the size in the sequence headers is patched; the
# reference is ffmpeg's decode of the unpatched stream, cropped (swscale's odd-size RGBA path interpolates
# chroma differently from its even-size one, which is what the decoder matches)
"odd_173x95": (src("mandelbrot", 174, 96, 24, 1) + ["-b:v", "300k", "-bf", "0", "-g", "24"], (173, 95)),
"bframes": (src("testsrc2", 320, 180, 24, 1) + ["-b:v", "600k", "-bf", "2", "-g", "24"], None),
"bframes_zoom": (src("mandelbrot", 176, 144, 24, 1.5) + ["-b:v", "250k", "-bf", "3", "-g", "16"], None),
"matrix": (src("testsrc2", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "12",
"-intra_matrix", INTRA, "-inter_matrix", INTER], None),
"q1": (src("mandelbrot", 176, 144, 25, 0.6) + ["-q:v", "1", "-bf", "0", "-g", "8"], None),
"q31": (src("testsrc2", 176, 144, 25, 1) + ["-q:v", "31", "-bf", "0", "-g", "25"], None),
"zeromv": (src("mandelbrot", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "25", "-me_method", "zero"], None),
}
def patch_size(es, w, h):
# every sequence header (00 00 01 B3): 12-bit width, 12-bit height
b = bytearray(es)
i = 0
while True:
i = b.find(b"\x00\x00\x01\xb3", i)
if i < 0:
return bytes(b)
b[i + 4] = w >> 4
b[i + 5] = ((w & 15) << 4) | (h >> 8)
b[i + 6] = h & 255
i += 4
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 crop(frames, w, h, cw, ch, bpp):
fs = w * h * bpp
out = bytearray()
for k in range(len(frames) // fs):
for y in range(ch):
o = k * fs + y * w * bpp
out += frames[o:o + cw * bpp]
return bytes(out)
def crop_yuv(frames, w, h, cw, ch):
fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
out = bytearray()
for k in range(len(frames) // fs):
f = frames[k * fs:(k + 1) * fs]
out += crop(f[:w * h], w, h, cw, ch, 1)
c = ((w + 1) // 2) * ((h + 1) // 2)
for pl in range(2):
out += crop(f[w * h + pl * c:w * h + (pl + 1) * c], (w + 1) // 2, (h + 1) // 2, (cw + 1) // 2, (ch + 1) // 2, 1)
return bytes(out)
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)
with tempfile.TemporaryDirectory(prefix="formats-mpeg1-") as tmp:
def encode(name, args, size):
path = os.path.join(tmp, name + ".m1v")
ff(args + ENC + [path])
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])
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])
return open(out, "rb").read(), w, h
for name, (args, size) in CASES.items():
es, path = encode(name, args, size)
rgba, w, h = reference(path, "rgba")
yuv, _, _ = reference(path, "yuv420p")
if size:
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
w, h = size
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
n = len(rgba) // fs
means = []
for k in range(n):
fr = rgba[k * fs:(k + 1) * fs]
means.append([round(sum(fr[c::4]) / (w * h), 4) for c in range(3)])
# whole frames: the first P-picture and the last one (the most drift) as RGBA, three as yuv420p
picks = sorted({1, n - 1}) if n > 2 else list(range(n))
ypicks = sorted({0, n // 2, n - 1})
ctx.emit("mpeg1_" + name, {
"name": name, "width": w, "height": h, "frames": n, "file": b64(es), "units": access_units(es),
"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],
})
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
a, pa = encode("sc_a", src("testsrc2", 176, 144, 24, 0.5) + ["-b:v", "200k", "-bf", "0", "-g", "6"], None)
b, pb = encode("sc_b", src("mandelbrot", 320, 180, 24, 0.5) + ["-b:v", "400k", "-bf", "0", "-g", "6"], None)
parts = []
for path in (pa, pb):
rg, w, h = reference(path, "rgba")
n = len(rg) // (w * h * 4)
parts.append({"width": w, "height": h, "frames": n, "last": z64(rg[(n - 1) * w * h * 4:])})
ctx.emit("mpeg1_sizechange", {"file": b64(a + b), "parts": parts})
bench = []
for w, h, rate in ((320, 240, "600k"), (640, 480, "1500k")):
es, _ = encode("bench", src("testsrc2", w, h, 25, 2) + ["-b:v", rate, "-bf", "2", "-g", "25"], None)
bench.append({"width": w, "height": h, "file": b64(es), "units": access_units(es)})
ctx.emit("mpeg1_bench", bench)
+59
View File
@@ -0,0 +1,59 @@
# MPEG-TS / PS fixtures (tools/fixtures.py): transport streams (MPEG-1 + MP2 as bugtv plays them, with B-frames,
# H.264 + AAC, M2TS 192-byte packets, garbage before the first packet) and program streams (MPEG-1 system stream,
# MPEG-2 PS / VOB layout, B-frames, a raw .m1v elementary stream), made by ffmpeg. For each file: ffprobe's streams
# and packets, ffmpeg's frames (CRC-32 of yuv420p; the first frames raw) and audio (f32).
# tests/gen/mpegts_cases.luau, tests/gen/mpegps_cases.luau
import importlib.util, os, tempfile
_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"]
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"]
AUD = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100"]
def case(tmp, name, raw_frames=3, pcm_frames=8192, packets=True):
path = os.path.join(tmp, name)
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path)}
if packets:
c["packets"] = V.packets(path)
vs = [s for s in c["streams"] if s["kind"] == "video"]
if vs:
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"])
c["frames"] = [V.crc(f) for f in frames]
c["yuv"] = frames[:raw_frames]
if any(s["kind"] == "audio" for s in c["streams"]):
pcm = V.pcm_f32(path)
c["pcm"] = pcm[:pcm_frames * 4]
c["pcmBytes"] = len(pcm)
return c
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="mpegfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-b:a", "128k",
"-f", "mpegts", "mpeg1_mp2.ts")
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpegts",
"bframes.ts")
ff(*SRC, *AUD, "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-g", "10", "-c:a", "aac", "-b:a", "96k",
"-f", "mpegts", "h264_aac.ts")
ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-f", "mpegts", "-mpegts_m2ts_mode", "1", "m2ts.m2ts")
open(os.path.join(tmp, "garbage.ts"), "wb").write(bytes(ctx.rng(3).randrange(256) for _ in range(333)).replace(b"G", b"g") +
open(os.path.join(tmp, "mpeg1_mp2.ts"), "rb").read())
ts = [case(tmp, "mpeg1_mp2.ts"), case(tmp, "bframes.ts"), case(tmp, "h264_aac.ts"), case(tmp, "m2ts.m2ts"),
case(tmp, "garbage.ts", packets=False)]
full = ts[0]["data"]
ts.append({"name": "truncated.ts", "data": full[: len(full) // 2 + 77], "truncated": True})
ctx.emit("mpegts_cases", ts)
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-f", "mpeg", "system.mpg")
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpeg",
"bframes.mpg")
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-c:a", "mp2", "-f", "vob", "mpeg2ps.vob")
ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-f", "mpeg1video", "es.m1v")
ps = [case(tmp, n, packets=False) for n in ("system.mpg", "bframes.mpg", "mpeg2ps.vob", "es.m1v")]
ctx.emit("mpegps_cases", ps)
+27
View File
@@ -0,0 +1,27 @@
# Video bench inputs (tools/fixtures.py, for tools/bench.luau): 1 s of testsrc2 at 320x240 and 640x480, 25 fps, as
# MJPEG AVI, MPEG-1 TS, VP8 WebM (libvpx) and 8 frames of 320x240 Y4M.
# tests/gen/videobench.luau { { name, size, data } }
import importlib.util, os, tempfile
_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 generate(ctx):
tmp = tempfile.mkdtemp(prefix="videobench_")
out = []
for size in ("320x240", "640x480"):
src = ["-f", "lavfi", "-i", "testsrc2=size=%s:rate=25" % size, "-t", "1"]
for name, args in (("mjpeg.avi", ["-c:v", "mjpeg", "-q:v", "4"]),
("mpeg1.ts", ["-c:v", "mpeg1video", "-b:v", "2M", "-bf", "2", "-f", "mpegts"]),
("vp8.webm", ["-c:v", "libvpx", "-b:v", "1M", "-g", "50"]),
("raw.y4m", ["-pix_fmt", "yuv420p", "-frames:v", "8"])):
if name == "raw.y4m" and size == "640x480":
continue
path = os.path.join(tmp, size + "_" + name)
V.ffmpeg(src + args + [path])
out.append({"name": name, "size": size, "data": open(path, "rb").read()})
ctx.emit("videobench", out)
+63
View File
@@ -0,0 +1,63 @@
# Our video writers checked by ffprobe / ffmpeg (tools/fixtures.py): tools/fixtures/_video_encode.luau remuxes /
# re-encodes the container fixtures (WebM remux, MJPEG Matroska / AVI / MP4 from VP8 and MPEG-1, MJPEG copies, H.264 +
# AAC MP4 to MOV / Matroska, PCM MOV, FLAC MP4, an animated GIF with uneven delays to AVI / Matroska / Y4M / MP4, WebM
# to Y4M); each output must probe in ffprobe and decode in
# ffmpeg. Emitted per file: our bytes, ffprobe's streams and packets, ffmpeg's frames (CRC-32; the first raw) and
# audio, so the test can decode our file with our decoders and compare.
# tests/gen/videoenc_src.luau { gif = <animated GIF made by Pillow: 4 frames, 100 / 50 / 200 / 100 ms> }
# tests/gen/videoenc_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } | { name, err } }
import importlib.util, os, shutil, subprocess, tempfile
_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", "tools/fixtures/_video_encode.luau", "tools/fixtures/mkv.py", "tools/fixtures/avi.py", "tools/fixtures/mp4.py",
"src/Formats/video", "src/Formats/codecs/Video", "src/Formats/containers/Ebml", "src/Formats/containers/Avi", "src/Formats/containers/IsoBmff",
"src/Formats/codecs/Jpeg", "src/Formats/codecs/Vp8"]
GIF = r"""
import io, sys
from PIL import Image, ImageDraw
frames = []
for i, c in enumerate([(255, 0, 0), (0, 160, 0), (0, 0, 255), (240, 200, 0)]):
im = Image.new("RGB", (64, 48), (20, 20, 20))
d = ImageDraw.Draw(im)
d.rectangle([4 + i * 10, 8, 24 + i * 10, 40], fill=c)
d.ellipse([40, 4 + i * 6, 60, 20 + i * 6], fill=(255, 255, 255))
frames.append(im)
b = io.BytesIO()
frames[0].save(b, "GIF", save_all=True, append_images=frames[1:], duration=[100, 50, 200, 100], loop=0)
sys.stdout.buffer.write(b.getvalue())
"""
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="videoenc_")
gif = ctx.python(["pillow"], GIF)
ctx.emit("videoenc_src", {"gif": gif})
luau = os.environ.get("LUAU") or shutil.which("luau")
cmd = [luau, "tools/fixtures/_video_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_video_encode.luau"]
out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode()
cases = []
for line in out.split("\n"):
if not line.strip():
continue
name, rest = line.split(" ", 1)
if rest.startswith("ERR "):
cases.append({"name": name, "err": rest[4:]})
continue
path = os.path.join(tmp, name)
open(path, "wb").write(bytes.fromhex(rest))
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
vs = [s for s in c["streams"] if s["kind"] == "video"]
if vs:
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
c["frames"] = [V.crc(f) for f in frames]
c["yuv"] = frames[:3]
if any(s["kind"] == "audio" for s in c["streams"]):
pcm = V.pcm_f32(path)
c["pcm"] = pcm[:8192 * 4]
c["pcmBytes"] = len(pcm)
cases.append(c)
ctx.emit("videoenc_cases", cases)
+133
View File
@@ -0,0 +1,133 @@
# VP8 video fixtures (tools/fixtures.py) for tests/codecs/vp8video.luau and tools/bench.luau. Clips are encoded by
# ffmpeg's libvpx into IVF (many encoder settings: alt-ref / hidden frames, golden refreshes, token partitions, error
# resilience, profiles 1-3, sharpness, segmentation, q extremes, short key frame intervals, motion off the frame edges),
# plus the official VP8 test vectors (tests/fixtures/vp8video/vp80-*.ivf, from the libvpx test data, BSD:
# licenses/libvpx-LICENSE.txt). The reference output is ffmpeg's native vp8 decoder (bit-exact with libvpx):
# `ffmpeg -c:v vp8 -i x.ivf -noautoscale -fps_mode passthrough -f framehash -hash crc32 -`: the CRC32 of every
# shown yuv420p frame (and its size: key frames may change it).
# tests/gen/vp8video_cases.luau { name, ivf, width, height (of the first frame), crcs, sizes (bytes) }
# tests/gen/vp8video_bench.luau { { name, ivf, width, height, frames, crcs, sizes } } for tools/bench.luau
import os, shutil, subprocess, tempfile, zlib
INPUTS = ["tests/fixtures/vp8video"]
VECTORS = "tests/fixtures/vp8video"
def ffmpeg(ctx, args):
"""runs ffmpeg (the one on PATH when it has libvpx, else nixpkgs#ffmpeg) and returns stdout"""
exe = shutil.which("ffmpeg")
if exe:
enc = subprocess.run([exe, "-hide_banner", "-encoders"], capture_output=True).stdout
if b"libvpx " in enc:
return subprocess.run([exe, "-hide_banner", "-loglevel", "error"] + args, capture_output=True, check=True).stdout
return ctx.nix("ffmpeg", ["ffmpeg", "-hide_banner", "-loglevel", "error"] + args)
def ivf_size(data):
return data[12] | data[13] << 8, data[14] | data[15] << 8
def reference(ctx, path):
"""ffmpeg's decode: (crc32, byte size) of each shown yuv420p frame (sizes may change at key frames)"""
out = ffmpeg(ctx, ["-c:v", "vp8", "-i", path, "-noautoscale", "-fps_mode", "passthrough", "-f", "framehash",
"-hash", "crc32", "-"])
frames = []
for line in out.decode().splitlines():
if line and not line.startswith("#"):
f = [x.strip() for x in line.split(",")]
frames.append((int(f[5], 16), int(f[4])))
return frames
# (name, lavfi source, frames, encoder options)
SRC_320 = "testsrc2=s=320x240:r=25"
PAN = "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'"
CLIPS = [
("default_320x240", SRC_320, 20, ["-b:v", "400k"]),
("odd_173x95", "mandelbrot=s=173x95:r=25", 16, ["-b:v", "200k"]),
("pan_320x240", PAN, 24, ["-b:v", "300k", "-g", "100"]),
("altref_352x288", "testsrc2=s=352x288:r=25", 30,
["-b:v", "300k", "-auto-alt-ref", "1", "-lag-in-frames", "16", "-arnr-maxframes", "7", "-arnr-strength", "5",
"-arnr-type", "3", "2pass"]),
("altref_pan", PAN, 30, ["-b:v", "250k", "-auto-alt-ref", "1", "-lag-in-frames", "25", "-g", "200", "2pass"]),
("tokenparts3", SRC_320, 12, ["-b:v", "500k", "-slices", "8"]),
("tokenparts1_odd", "mandelbrot=s=201x77:r=25", 12, ["-b:v", "300k", "-slices", "2"]),
("error_resilient", PAN, 16, ["-b:v", "300k", "-error-resilient", "1"]),
("profile1", PAN, 16, ["-b:v", "300k", "-profile:v", "1"]),
("profile2", PAN, 16, ["-b:v", "300k", "-profile:v", "2"]),
("profile3", PAN, 16, ["-b:v", "300k", "-profile:v", "3"]),
("sharpness7", PAN, 12, ["-b:v", "200k", "-sharpness", "7"]),
("sharpness3", "mandelbrot=s=160x120:r=25", 12, ["-b:v", "150k", "-sharpness", "3"]),
("realtime_cyclic", PAN, 24,
["-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", "-static-thresh", "100", "-screen-content-mode", "1"]),
("realtime_noise", "testsrc2=s=320x240:r=25,noise=alls=30:allf=t", 16,
["-deadline", "realtime", "-cpu-used", "4", "-b:v", "400k"]),
("best_split", "testsrc2=s=176x144:r=25,rotate=a='t*0.4':c=black", 16, ["-deadline", "best", "-b:v", "250k"]),
("cellauto_split", "cellauto=s=176x144:rule=110:r=25,scale=176:144", 16, ["-b:v", "300k", "-cpu-used", "0"]),
("q_high", PAN, 10, ["-qmin", "0", "-qmax", "2", "-b:v", "20M"]),
("q_low", PAN, 16, ["-qmin", "60", "-qmax", "63", "-b:v", "20k"]),
("keyint5", PAN, 16, ["-b:v", "300k", "-g", "5"]),
("golden", "testsrc2=s=240x160:r=25", 40, ["-b:v", "150k", "-g", "300", "-auto-alt-ref", "0"]),
("big_motion", "testsrc2=s=640x480:r=25,crop=w=192:h=144:x='224+200*sin(t*9)':y='168+150*cos(t*7)'", 16,
["-b:v", "300k"]),
("tiny_24x18", "testsrc2=s=24x18:r=25", 12, ["-b:v", "50k"]),
("temporal_layers", PAN, 16,
["-deadline", "realtime", "-b:v", "300k", "-ts-parameters",
"ts_number_layers=2:ts_target_bitrate=150,300:ts_rate_decimator=2,1:ts_periodicity=2:ts_layer_id=0,1"]),
]
BENCH = [
("bench_320x240", "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'", 40,
["-b:v", "500k"]),
("bench_640x480", "testsrc2=s=960x720:r=25,crop=w=640:h=480:x='160+150*sin(t*3)':y='120+100*cos(t*2)'", 30,
["-b:v", "1200k"]),
]
def encode(ctx, tmp, name, src, frames, opts):
path = os.path.join(tmp, name + ".ivf")
base = ["-f", "lavfi", "-i", src, "-frames:v", str(frames), "-pix_fmt", "yuv420p", "-c:v", "libvpx"]
try:
if "2pass" in opts: # alt-ref frames need the two-pass encoder
opts = [o for o in opts if o != "2pass"]
log = os.path.join(tmp, name + "-pass")
ffmpeg(ctx, base + opts + ["-pass", "1", "-passlogfile", log, "-f", "null", "-"])
opts = opts + ["-pass", "2", "-passlogfile", log]
ffmpeg(ctx, base + opts + ["-f", "ivf", "-y", path])
except subprocess.CalledProcessError as e:
if name == "temporal_layers": # optional: depends on the libvpx wrapper's options
return None
raise RuntimeError("vp8video: %s: %s" % (name, e.stderr.decode(errors="replace")))
return path
def case(ctx, name, path):
with open(path, "rb") as f:
data = f.read()
w, h = ivf_size(data)
ref = reference(ctx, path)
return {"name": name, "ivf": data, "width": w, "height": h, "crcs": [r[0] for r in ref], "sizes": [r[1] for r in ref]}
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="vp8video")
try:
cases = []
vec = os.path.join(ctx.root, VECTORS)
for f in sorted(os.listdir(vec)):
if f.endswith(".ivf"):
cases.append(case(ctx, f[:-4], os.path.join(vec, f)))
for name, src, frames, opts in CLIPS:
path = encode(ctx, tmp, name, src, frames, opts)
if path:
cases.append(case(ctx, name, path))
ctx.emit("vp8video_cases", cases)
bench = []
for name, src, frames, opts in BENCH:
c = case(ctx, name, encode(ctx, tmp, name, src, frames, opts))
c["frames"] = len(c["crcs"])
bench.append(c)
ctx.emit("vp8video_bench", bench)
finally:
shutil.rmtree(tmp)
+34
View File
@@ -0,0 +1,34 @@
# YUV4MPEG2 fixtures (tools/fixtures.py): streams written by ffmpeg in C420jpeg (odd size 173x95), C420mpeg2, C422,
# C444, Cmono and C420p10 (10-bit) with ffmpeg's yuv420p decode of each (CRC-32 per frame; the first frames raw for
# the converted layouts, which are compared by PSNR).
# tests/gen/y4m_cases.luau { { name, data, width, height, rate = { num, den }, frames = { crc }, yuv = { raw } } }
import importlib.util, os, tempfile
_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 generate(ctx):
tmp = tempfile.mkdtemp(prefix="y4mfx_")
cases = []
for name, size, rate, pix, extra in [
("c420jpeg.y4m", "173x95", "30000/1001", "yuv420p", []),
("c420mpeg2.y4m", "160x120", "25", "yuv420p", ["-chroma_sample_location", "left"]),
("c422.y4m", "160x120", "24", "yuv422p", []),
("c444.y4m", "160x120", "10", "yuv444p", []),
("cmono.y4m", "160x120", "10", "gray", []),
("c420p10.y4m", "96x64", "10", "yuv420p10le", ["-strict", "-1"]),
]:
path = os.path.join(tmp, name)
w, h = (int(x) for x in size.split("x"))
V.ffmpeg(["-f", "lavfi", "-i", "testsrc2=size=%s:rate=%s" % (size, rate), "-frames:v", "6", "-vf",
"pad=%d:%d" % (w + 1, h + 1) if w % 2 else "null", "-s", size, "-pix_fmt", pix] + extra + [path])
frames = V.yuv_frames(path, w, h)
num, den = (rate.split("/") + ["1"])[:2]
cases.append({"name": name, "data": open(path, "rb").read(), "width": w, "height": h,
"rate": [int(num), int(den)], "frames": [V.crc(f) for f in frames], "yuv": frames[:2],
"exact": pix == "yuv420p"})
ctx.emit("y4m_cases", cases)