ws-video: video/mkv tests (ffprobe packets, ffmpeg audio, lacing / zlib / unknown clusters / subtitles, WebM remux), zlib content compression, codec-delay trimming of non-Opus audio (AudioWrap.trim), video/y4m, containers/Avi + video/avi (WIP tests)

This commit is contained in:
4DBug committed 2026-10-31 09:41:22 -05:00
1 parent 8a905a4510
commit 9411cd97c6
14 files changed
+1862 -20

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
# 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):
"""the first video stream decoded by ffmpeg to yuv420p: a list of frame bytes"""
raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
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)
+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"])
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)