Files

123 lines
4.1 KiB
Python

# 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)