"""Pre-delivery compliance check: does this file meet the platform's spec?
Checks duration, frame size / aspect, fps, codec, pixel format, colour tags,
file size, integrated loudness and true peak against the chosen platform
and prints a PASS/WARN/FAIL table. Exit code 1 when anything FAILs. A length
or file size over the platform table's limit is WARN (`basis: guidance`): upload
limits change and the uploader checks the current one; --max-duration / --max-mb
state the caller's own limit, which FAILs when a --platform is named (with none,
an over-length is WARN, as every judgement row is). Each
row's `fix` is the command that resolves it; a few of the less obvious FAILs
(video codec, pixel format, HDR colour, loudness) also carry a plain-language
`reason` -- "QuickTime and iOS commonly reject video that isn't 8-bit 4:2:0",
not a restatement of the spec value -- for a caller reporting this to someone
who doesn't already know why the spec says what it says.
Platforms: youtube, shorts, reels, tiktok, x, linkedin, facebook, broadcast (EBU R128),
podcast, custom -- one table, shared with export.py and the render.py templates
Examples:
python3 check.py final.mp4 --platform youtube
python3 check.py reel.mp4 --platform reels --json
python3 check.py spot.mov --platform broadcast
python3 check.py clip.mp4 --platform custom --max-duration 30 --aspect 1:1 --lufs -16
python3 check.py final.mp4 --platform reels --content
--content (opt-in) adds content rows from one decode pass: black (share of the
duration that is black: WARN > 10%, FAIL >= 95%), frozen (longest frozen span: WARN >
max(3 s, 30% of the duration), FAIL when the whole video is frozen) and silence (share
below -50 dBFS: WARN > 50%, FAIL >= 95%); and, from one more audio-only pass (2.17),
dropouts (gaps of digital silence, <= -80 dBFS for 20 ms to 1 s with sound on both sides:
WARN when there is any); and, from one more video pass and a one-frame decode (2.23), flashes
(single frames that differ from both neighbours while they match each other: WARN when there is
any) and first frame (one flat colour, the frame a feed's autoplay shows first: WARN). Without it
the row set is unchanged.
--levels bt709|ebu-r103 (opt-in) decodes every frame once more and adds a legal levels row: the share
of luma and of chroma samples outside the standard's legal range, counted exactly per frame, with
min/max Y/U/V (FAIL when any frame's share passes --levels-tolerance, 1 % by default). The JSON
`levels` document repeats it per clip and per --levels-window seconds (10 by default).
"""
import argparse
import json
import os
import re
import sys
from fractions import Fraction
from typing import Any, Dict, List, Optional, Tuple
from _platforms import PLATFORMS, PLATFORM_CHOICES, TP_TOLERANCE_DB, spec_of, upload_limit_note, resolve as resolve_platform
from _common.probe import (CHANGE_FLOOR, CHANGE_GRID, change_mask_tiles, change_tiles, LEGAL_RANGE_CHOICES, measure_signal_range, COMPARE_SSIM_WARN, CONTENT_FLAT_STD, SILENT_PEAK_DBFS, compare_pictures, detect_content,
detect_flashes, first_frame_stats, presentation_times, measured_level_dbfs)
from _common.emit import file_identity, own_length
from _common.probe import PROBED_AUDIO
from _common.probe import display_size as shown_size, shorter_than_a_loudness_block
from _common import STATE, add_common, apply_common, die, emit, probe, require_tool, run_analysis, dry_run_input_pending
SPECS: Dict[str, Dict[str, Any]] = {name: spec_of(name) for name in sorted(PLATFORMS)
if PLATFORMS[name]["check"] == name}
def measure_loudness(path: str) -> Dict[str, float]:
if dry_run_input_pending(path):
return {}
ffmpeg = require_tool("ffmpeg")
proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-map", f"0:{PROBED_AUDIO}", "-vn",
"-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], check=False, record=True)
m = re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", proc.stderr, re.S)
if not m:
return {}
d = json.loads(m.group(0))
try:
return {"lufs": float(d["input_i"]), "tp": float(d["input_tp"]), "lra": float(d["input_lra"])}
except (KeyError, ValueError):
return {}
BLACK_WARN, BLACK_FAIL = 0.10, 0.95
FROZEN_WARN_S, FROZEN_WARN_SHARE = 3.0, 0.30
FROZEN_FAIL = 0.95
SILENCE_WARN, SILENCE_FAIL = 0.50, 0.95
LEVELS_TOLERANCE_PCT = 1.0
_YUV_PREFIXES = ("yuv", "yuvj", "nv", "p01", "p21", "p41", "y21", "uyvy", "yuyv", "ayuv", "vuya", "xv")
STATE_NOTES: List[str] = []
def flash_times(flashes: List[int], v: Dict[str, Any], meta: Dict[str, Any], pts: "Optional[List[float]]" = None) -> str:
"""The flashes row's first five times on look.py's timeline (seconds from the container
start). A flash frame's own presentation time when `pts` has it (presentation_times(): exact,
gaps in the timestamps included); otherwise index / average rate plus the video's lead over
the container, marked "~" (approximate), and `frame N` when there is no frame rate either."""
return ", ".join(frame_time(n, v, meta, pts) for n in flashes[:5]) + (" ..." if len(flashes) > 5 else "")
def frame_time(n: int, v: Dict[str, Any], meta: Dict[str, Any], pts: "Optional[List[float]]" = None) -> str:
"""Frame `n` (decode order) on look.py's timeline, as flash_times() describes: exact from
`pts`, else "~" index / average rate plus the video's lead, else `frame N`."""
origin = float(meta.get("start_time") or 0.0)
if pts and n < len(pts):
return f"{max(0.0, pts[n] - origin):.2f}s"
fps = float(v.get("fps") or 0.0)
lead = max(0.0, float(v.get("start_time") or 0.0) - origin)
return f"~{lead + n / fps:.2f}s" if fps else f"frame {n}"
def display_size(v: Dict[str, Any]) -> "Tuple[int, int]":
"""The frame size as decoded and auto-rotated, which is what --compare's ffmpeg pass sees."""
w, h = int(v.get("width") or 0), int(v.get("height") or 0)
return (h, w) if int(v.get("rotation") or 0) % 180 == 90 else (w, h)
def parse_expect_changed(values: "List[str]") -> "List[Dict[str, Any]]":
"""--expect-changed values -> [{start, end, rect}] (rect [x, y, w, h] in displayed pixels, or
None for the whole frame); [] for `none`. Refuses anything it cannot read: a declaration that
was silently dropped would turn into a FAIL the caller cannot explain, or a PASS it did not earn."""
from _common.decision import parse_time
import math
if any(v.strip().lower() == "none" for v in values):
if len(values) > 1:
die("--expect-changed none says the picture must not change at all; it cannot be combined with a span")
return []
spans = []
for raw in values:
span, _, rect_text = raw.strip().partition("@")
start_text, sep, end_text = span.partition("-")
try:
if not sep or not start_text or not end_text:
raise ValueError(raw)
start, end = parse_time(start_text), parse_time(end_text)
except (ValueError, SystemExit):
die(f"--expect-changed takes START-END (seconds or H:MM:SS), optionally @X,Y,W,H, or none; got {raw!r}")
if not (math.isfinite(start) and math.isfinite(end)) or start < 0 or end < start:
die(f"--expect-changed {raw!r}: a span starts at 0 or later and ends at or after its start")
rect = None
if "@" in raw:
try:
rect = [int(n) for n in rect_text.split(",")]
except ValueError:
rect = []
if len(rect) != 4 or rect[0] < 0 or rect[1] < 0 or rect[2] <= 0 or rect[3] <= 0:
die(f"--expect-changed {raw!r}: the rectangle is X,Y,W,H in displayed pixels, whole numbers, W and H above 0")
spans.append({"start": start, "end": end, "rect": rect})
return spans
def _runs(frames: "List[int]") -> "List[Tuple[int, int]]":
"""Sorted frame indices -> [(first, last)] of consecutive runs."""
out: "List[Tuple[int, int]]" = []
for n in frames:
if out and n == out[-1][1] + 1:
out[-1] = (out[-1][0], n)
else:
out.append((n, n))
return out
def change_scope(tiles: "Dict[str, Any]", declared: "List[Dict[str, Any]]", times: "List[float]",
size: "Tuple[int, int]", floor: int) -> "Dict[str, Any]":
"""The measured tiles against the declaration. `times` has one more entry than there are
frames (frame n is shown from times[n] until times[n+1]). A declared span is closed at both
ends and widened to whole frames: frame n is inside when its interval touches the span.
Inside a span with a rectangle, only the tiles the rectangle touches may change."""
gw, gh = CHANGE_GRID
w, h = size
tw, th = w / gw, h / gh
def allowed_mask(rect: "Optional[List[int]]") -> int:
if rect is None:
return (1 << gw * gh) - 1
x, y, rw, rh = rect
return sum(1 << (c + r * gw) for c in range(gw) for r in range(gh)
if c * tw < x + rw and (c + 1) * tw > x and r * th < y + rh and (r + 1) * th > y)
spans = [dict(d, mask=allowed_mask(d["rect"]), seen=False) for d in declared]
def describe(frames: "Dict[int, int]") -> "List[Dict[str, Any]]":
out = []
for first, last in _runs(sorted(frames)):
union = 0
for n in range(first, last + 1):
union |= frames[n]
hit = change_mask_tiles(union)
c0, c1 = min(c for c, _ in hit), max(c for c, _ in hit)
r0, r1 = min(r for _, r in hit), max(r for _, r in hit)
x0, y0, x1, y1 = int(c0 * tw), int(r0 * th), int(round((c1 + 1) * tw)), int(round((r1 + 1) * th))
out.append({"start": round(times[first], 3), "end": round(times[last + 1], 3), "frames": last - first + 1,
"rect": [x0, y0, x1 - x0, y1 - y0], "peak": max(tiles["peaks"][n] for n in range(first, last + 1))})
return out
outside: "Dict[int, int]" = {}
for n, changed in tiles["changed"].items():
left = changed
for d in spans:
if times[n] <= d["end"] and times[n + 1] > d["start"]:
if changed & d["mask"]:
d["seen"] = True
left &= ~d["mask"]
if left:
outside[n] = left
return {"declared": [{"start": d["start"], "end": d["end"], "rect": d["rect"]} for d in declared],
"observed": describe(tiles["changed"]), "undeclared": describe(outside),
"declared_unchanged": [{"start": d["start"], "end": d["end"], "rect": d["rect"]} for d in spans if not d["seen"]],
"floor": floor, "tile": [gw, gh], "frames": tiles["frames"], "quiet_peak": tiles["quiet_peak"]}
def _span_total(spans: Any) -> float:
return sum(max(0.0, e - s) for s, e in spans)
def aspect_name(w: int, h: int) -> str:
f = Fraction(w, h)
for name, target in (("16:9", Fraction(16, 9)), ("9:16", Fraction(9, 16)), ("1:1", Fraction(1)), ("4:5", Fraction(4, 5)), ("4:3", Fraction(4, 3)), ("21:9", Fraction(21, 9))):
if abs(float(f) - float(target)) < 0.02:
return name
return f"{f.numerator}:{f.denominator}"
def levels_row(args: argparse.Namespace, v: Dict[str, Any], row: Any) -> "Optional[Dict[str, Any]]":
"""--levels: measure the signal range (measure_signal_range) and add the legal levels row.
Returns the JSON `levels` document, or None when nothing was measured."""
expect = f"every frame <= {args.levels_tolerance:g}% of luma and of chroma samples outside {args.levels}"
pix = str(v.get("pix_fmt") or "")
if not v:
return None
if not pix.startswith(_YUV_PREFIXES):
row("legal levels", "WARN", f"not measured: {pix or 'unknown'} is not a Y'CbCr picture", expect,
"legal levels are measured on the Y'CbCr file a broadcaster receives: check the encoded delivery, not an RGB master",
reason="an RGB or grey picture has no luma and chroma codes to count")
return None
doc = measure_signal_range(args.input, args.levels, args.levels_window, pix_fmt=pix)
if doc is None:
row("legal levels", "WARN", "could not measure", expect, "re-run check.py --levels, or look.py the picture",
reason="the decode failed or stopped part-way, so the signal range of the whole file is unknown")
return None
pct, worst = doc["out_of_range_pct"], doc["worst_frame"]
over = worst["y_pct"] > args.levels_tolerance or worst["chroma_pct"] > args.levels_tolerance
at = "" if worst["time"] is None else f" at {worst['time']:.2f}s"
lo, hi = doc["min"], doc["max"]
value = (f"luma {pct['y']:.3f}%, chroma {pct['chroma']:.3f}% out of range (worst frame{at}: luma {worst['y_pct']:.3f}%, "
f"chroma {worst['chroma_pct']:.3f}%); Y {lo['y']}-{hi['y']}, U {lo['u']}-{hi['u']}, V {lo['v']}-{hi['v']}")
full = v.get("color_range") == "pc" or pix.startswith("yuvj")
if full:
STATE_NOTES.append("--levels: the picture is tagged full range (0-255 codes by design), so it was counted against "
"the limited-range limits a broadcast file uses; convert it to limited range before judging the row")
row("legal levels", "FAIL" if over else "PASS", value, expect,
f"color.py {args.input} --legalize {args.levels} (clamps after the 4:2:0 conversion and measures the result), or "
"pull the highlights and shadows in with a soft clip in the grade and check again" if over else "",
reason="a broadcaster's QC rejects or clips a picture whose levels leave the legal range" if over else "")
return doc
def encoding_differences(v: Dict[str, Any], rv: Dict[str, Any]) -> "List[str]":
"""What makes two video streams "not encoded alike" for --expect-changed: part of a measured
difference is then the encoder's. The stored size is the file's own width and height, before
rotation: 1080x1920 turned to 1920x1080 against a stored 1920x1080 is the same displayed
picture stored another way (as is 1440x1080 at 4:3), compared and said."""
def stored(x: Dict[str, Any]) -> str:
return f"{x.get('width')}x{x.get('height')}"
pairs = (("codec", v.get("codec"), rv.get("codec")), ("pix_fmt", v.get("pix_fmt"), rv.get("pix_fmt")),
("fps", v.get("fps"), rv.get("fps")), ("stored size", stored(v), stored(rv)))
return [f"{k} {a} against {b}" for k, a, b in pairs if a != b]
def change_scope_row(args: Any, declared: "List[Dict[str, Any]]", meta: Dict[str, Any], v: Dict[str, Any], row: Any) -> "Optional[Dict[str, Any]]":
"""--expect-changed: measure where the picture differs from the reference and grade it against
the declaration. A comparison that could not be made is a FAIL, never a WARN or a PASS: the
flag exists to stop a false "nothing else changed", and a check that did not run would be one."""
want = "a change only where declared" if declared else "no change in the picture"
look = f"look.py --compare {args.compare} --at "
def not_compared(why: str, fix: str) -> None:
row("change_scope", "FAIL", f"not compared: {why}", want, fix,
reason="nothing was measured, so this does not say the rest of the picture is unchanged")
ref = probe(args.compare)
rv = ref.get("video") or {}
if not v or not rv:
return not_compared("one of the files has no picture", "--expect-changed needs a video stream in both files")
from _common.probe import display_size as shown_size, square_pixels
size = shown_size(v)
if size != shown_size(rv):
return not_compared("%dx%d against %dx%d (as displayed)" % (size + shown_size(rv)),
"compare two renders of the same frame size")
for d in declared:
if d["rect"] and (d["rect"][0] + d["rect"][2] > size[0] or d["rect"][1] + d["rect"][3] > size[1]):
die(f"--expect-changed: the rectangle {','.join(map(str, d['rect']))} does not fit inside the {size[0]}x{size[1]} picture")
origin = float(meta.get("start_time") or 0.0)
pts = presentation_times(args.input, float(v.get("start_time") or 0.0))
ref_pts = presentation_times(args.compare, float(rv.get("start_time") or 0.0))
nout, nref = v.get("nb_frames") or len(pts) or None, rv.get("nb_frames") or len(ref_pts) or None
if not nout or not nref:
return not_compared("a frame count could not be read", "remux the file that has no readable frame count (export.py --preset copy)")
if int(nout) != int(nref):
return not_compared(f"{nout} frames against the reference's {nref}",
"an edit that changes the length cannot be paired frame by frame; compare the parts separately")
tiles = change_tiles(args.input, args.compare, args.change_floor, squares=(square_pixels(v), square_pixels(rv)))
if tiles is None:
return not_compared("the comparison pass failed", look + "0")
n = tiles["frames"]
fps = float(v.get("fps") or 0.0)
if pts and len(pts) >= n:
times = [max(0.0, t - origin) for t in pts[:n]]
times.append(times[-1] + ((times[-1] - times[-2]) if n > 1 else (1.0 / fps if fps else 0.0)))
else:
return not_compared("the frame times could not be read", "remux the file (export.py --preset copy) and check it again")
doc = change_scope(tiles, declared, times, size, args.change_floor)
def span(d: "Dict[str, Any]") -> str:
return f"{d['start']:.2f}-{d['end']:.2f}"
def place(d: "Dict[str, Any]") -> str:
x, y, w, h = d["rect"]
return f"{span(d)} ({d['frames']} frame{'s' if d['frames'] != 1 else ''}, around x {x}-{x + w}, y {y}-{y + h})"
idle = "; ".join(f"declared {span(d)} but nothing changed there" for d in doc["declared_unchanged"])
differ = encoding_differences(v, rv)
if differ:
STATE_NOTES.append("--expect-changed: the two files are not encoded alike (" + ", ".join(differ) + "), so part of "
"what was measured is the encoder's difference, not the edit")
floor_note = f"floor {doc['floor']}, largest unchanged tile {doc['quiet_peak']}"
if doc["undeclared"]:
first = doc["undeclared"][0]
more = len(doc["undeclared"]) - 1
value = "changed " + place(first) + (f" and {more} more span{'s' if more != 1 else ''}" if more else "") + ": not declared"
row("change_scope", "FAIL", value + (f"; {idle}" if idle else "") + f" ({floor_note})", want,
look + f"{first['start']:g}", reason="the picture changed where the edit was not meant to reach")
elif idle:
row("change_scope", "WARN", idle + f" ({floor_note})", want, "look at that span: the edit probably did not apply",
reason="a declared change was not found")
else:
seen = ", ".join(span(d) for d in doc["observed"]) or "nothing"
value = (f"changed {seen} inside the declared span{'s' if len(declared) != 1 else ''}; nothing else above the floor"
if declared else "no tile above the floor in any frame") + f" ({floor_note}, {n} frames)"
row("change_scope", "WARN" if differ else "PASS", value, want,
"compare two renders made with the same encoder settings" if differ else "",
reason="the two files are not encoded alike: " + ", ".join(differ) if differ else "")
return doc
def main() -> int:
STATE_NOTES.clear()
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input")
ap.add_argument("--platform", choices=PLATFORM_CHOICES, default=None, help="delivery spec to check against (default: youtube, with judgement rows reported as WARN because no platform was named)")
ap.add_argument("--max-duration", type=float, help="the caller's own maximum length in seconds: over it FAILs when a --platform is named, WARNs with none (the platform table's limit is guidance, WARN)")
ap.add_argument("--aspect", help="override allowed aspect (e.g. 9:16 or 16:9,1:1)")
ap.add_argument("--lufs", type=float, help="override loudness target")
ap.add_argument("--tp", type=float, help="override true-peak ceiling")
ap.add_argument("--max-mb", type=float, help="the caller's own maximum file size in MB: over it FAILs (the platform table's limit is guidance, WARN)")
ap.add_argument("--no-loudness", action="store_true", help="skip the loudness measurement (faster)")
ap.add_argument("--content", action="store_true",
help="also check the content (one decode pass, plus an audio-only and a video-only one): black, frozen, silence, dropouts, flashes and first frame rows")
ap.add_argument("--levels", choices=LEGAL_RANGE_CHOICES, default=None,
help="also measure the broadcast signal range (one more decode of every frame): a legal levels row with "
"the share of luma and chroma samples outside bt709 (16-235 / 16-240) or ebu-r103 (luma -1..103 %%), "
"and min/max Y/U/V; the JSON levels document has it per clip and per --levels-window")
ap.add_argument("--levels-window", type=float, default=10.0, metavar="SECONDS",
help="--levels: report the shares for every window of this many seconds too (default 10; 0 = the whole clip only)")
ap.add_argument("--levels-tolerance", type=float, default=LEVELS_TOLERANCE_PCT, metavar="PCT",
help="--levels: the legal levels row FAILs when one frame has more than this percentage of its luma or of "
"its chroma samples out of range (default %(default)g; 0 = any sample)")
ap.add_argument("--compare", metavar="REFERENCE",
help="also measure the picture against REFERENCE, frame by frame (SSIM and PSNR, one pass): a "
"similarity row, WARN when the mean SSIM is under 0.98, with the worst frame's time")
ap.add_argument("--expect-changed", action="append", metavar="SPAN[@X,Y,W,H]|none",
help="with --compare: where the picture is allowed to differ from REFERENCE, as START-END in this "
"file's time (repeatable), optionally only inside a rectangle of displayed pixels, or `none`. A "
"change_scope row FAILs on a change anywhere else (with its time and place) or when the two "
"could not be compared, and WARNs when a declared span did not change")
ap.add_argument("--change-floor", type=int, default=CHANGE_FLOOR, metavar="N",
help="--expect-changed: a 60x60-ish tile (the frame in %dx%d) counts as changed when its largest "
"channel difference is above N of 255 (default %%(default)d)" % CHANGE_GRID)
ap.add_argument("--expect-identity", metavar="SIZE:MTIME_NS",
help="the output_identity a writing tool reported ({size}:{mtime_ns}): an identity row FAILs when "
"the file at INPUT is not that file (a later run replaced it, or a failed run left an older one)")
add_common(ap)
args = ap.parse_args()
apply_common(args)
named = args.platform is not None
args.platform = resolve_platform(args.platform) or "youtube"
spec = dict(SPECS[args.platform])
if args.max_duration is not None:
spec["max_duration"] = args.max_duration
if args.aspect:
spec["aspects"] = [a.strip() for a in args.aspect.split(",")]
if args.lufs is not None:
spec["lufs"] = args.lufs
if args.tp is not None:
spec["tp"] = args.tp
if args.max_mb is not None:
spec["max_bytes"] = int(args.max_mb * 1024 * 1024)
if args.levels_window < 0:
die(f"--levels-window {args.levels_window:g}: a window is 0 (the whole clip only) or a number of seconds")
if not 0 <= args.levels_tolerance <= 100:
die(f"--levels-tolerance {args.levels_tolerance:g} is outside 0..100 (percent of a frame's samples)")
declared_changes = None
if args.expect_changed:
if not args.compare:
die("--expect-changed says where the picture may differ from a reference, so it needs --compare REFERENCE")
declared_changes = parse_expect_changed(args.expect_changed)
if not 1 <= args.change_floor <= 254:
die(f"--change-floor {args.change_floor} is outside 1..254 (a difference of 0-255 per channel)")
expected_identity = None
if args.expect_identity is not None:
try:
size, mtime_ns = (int(x) for x in args.expect_identity.split(":"))
except ValueError:
die(f"--expect-identity takes SIZE:MTIME_NS from a tool's output_identity, got {args.expect_identity!r}")
expected_identity = {"size": size, "mtime_ns": mtime_ns}
identity_before = None if dry_run_input_pending(args.input) else file_identity(args.input)
if identity_before is None and STATE.dry_run and not os.path.exists(args.input):
emit(None, platform=args.platform, checks=[], failed=0, warnings=0, ok=False,
notes=[f"[dry-run] {args.input} does not exist yet, so nothing was checked"])
return 0
meta = probe(args.input)
v, a = meta.get("video") or {}, meta.get("audio") or {}
rows: List[Dict[str, Any]] = []
JUDGEMENT = {"duration", "aspect", "loudness", "true peak", "fps", "resolution", "first frame", "flashes"}
guidance = {name for name, stated, limit in (("duration", args.max_duration, spec["max_duration"]),
("file size", args.max_mb, spec["max_bytes"]))
if stated is None and limit}
def row(name: str, status: str, value: Any, expect: Any, fix: str = "", reason: str = "") -> None:
if status == "FAIL" and not named and name in JUDGEMENT:
status = "WARN"
basis = "guidance" if name in guidance else "requirement"
if basis == "guidance" and status != "PASS":
status = "WARN"
reason = (reason + "; " if reason else "") + upload_limit_note(args.platform)
rows.append({"check": name, "status": status, "value": value, "expected": expect, "fix": fix,
"reason": reason if status != "PASS" else "",
"kind": "judgement" if name in JUDGEMENT else "format", "basis": basis})
dur_read = meta.get("duration")
dur = dur_read or 0.0
if dur_read is None:
row("duration", "FAIL" if spec["max_duration"] else "WARN", "could not measure",
f"<= {spec['max_duration']:g}s" if spec["max_duration"] else "any",
"remux the file (export.py --preset copy) so the container states its length, then check again",
reason="the file does not state its length, so whether it is within the limit is unknown")
elif spec["max_duration"]:
row("duration", "PASS" if dur <= spec["max_duration"] else "FAIL", f"{dur:.2f}s", f"<= {spec['max_duration']:g}s", "decide with the user: cut.py keeps quality but drops content; fit.py --duration speeds up (audio pitch-preserved, motion faster)")
else:
row("duration", "PASS", f"{dur:.2f}s", "any")
if v:
w, h = v["width"], v["height"]
if v.get("rotation") in (90, -90, 270, -270):
w, h = h, w
asp = aspect_name(*shown_size(v)) if all(shown_size(v)) else aspect_name(w, h)
if spec["aspects"]:
row("aspect", "PASS" if asp in spec["aspects"] else "FAIL", asp, "/".join(spec["aspects"]), f"fit.py --aspect {spec['aspects'][0]} --fit pad (keeps everything, adds bars) or crop (fills the frame, loses the edges: check the subject with look.py)")
else:
row("aspect", "PASS", asp, "any")
short = min(w, h)
if spec["min_height"]:
row("resolution", "PASS" if short >= spec["min_height"] else "WARN", f"{w}x{h}", f"short side >= {spec['min_height']}", "upscaling will not add detail; re-export from the master")
fps = v.get("fps") or 0
if spec["fps_max"] and not fps:
row("fps", "WARN", "could not measure", f"<= {spec['fps_max']}", "re-encode at a fixed rate (fit.py --fps N)",
reason="the stream states no frame rate, so whether it is within the limit is unknown")
elif spec["fps_max"]:
row("fps", "PASS" if fps <= spec["fps_max"] + 0.01 else "FAIL", f"{fps:g}", f"<= {spec['fps_max']}", "fit.py --fps 30 (drops half the frames of 60 fps motion; fine for talking heads, visible on sports/gaming)")
row("vfr", "PASS" if not v.get("variable_frame_rate_suspected") else "WARN", "variable" if v.get("variable_frame_rate_suspected") else "constant", "constant", "fit.py --fps N (any re-encode conforms it)")
if spec["codecs"]:
row("video codec", "PASS" if v.get("codec") in spec["codecs"] else "FAIL", v.get("codec"), "/".join(spec["codecs"]), "export.py --preset " + (PLATFORMS[args.platform].get("preset") or "youtube"),
reason="the platform's player may refuse to decode this codec at all, not just look worse")
pf = v.get("pix_fmt") or ""
if args.platform in ("reels", "tiktok", "x", "linkedin", "facebook"):
row("pixel format", "PASS" if pf == "yuv420p" else "FAIL", pf, "yuv420p (8-bit 4:2:0)", "export.py preset re-encodes to yuv420p",
reason="QuickTime and iOS commonly reject video that isn't 8-bit 4:2:0")
if spec["sdr_only"] and v.get("bt2020_or_hdr"):
row("colour", "FAIL", v.get("hdr_format"), "SDR BT.709", "color.py --to-sdr",
reason="a platform or player without HDR support will show this washed-out, too dark, or with wrong colours -- not a rendering glitch, a colour space mismatch")
else:
tags = (v.get("color_primaries"), v.get("color_transfer"))
untagged = not tags[0] and not tags[1]
matrix = v.get("color_space")
matrix_709 = matrix in (None, "bt709")
shown = (f"{matrix} matrix, primaries/transfer untagged" if untagged and matrix else
f"{tags[0]}/{tags[1]}" + ("" if matrix in (None, tags[0]) else f", {matrix} matrix"))
if v.get("bt2020_or_hdr") or (tags == ("bt709", "bt709") and matrix_709) or args.platform in ("podcast", "custom"):
row("colour", "PASS", f"{tags[0]}/{tags[1]}" + (f" ({v.get('hdr_format')})" if v.get("bt2020_or_hdr") else ""), "bt709/bt709 tagged (or HDR)")
elif untagged and matrix_709 and (v.get("bit_depth") or 8) == 8:
row("colour", "PASS", shown + " (players assume bt709)" if matrix else "untagged (players assume bt709)", "bt709/bt709 tagged (or HDR)")
elif matrix in ("smpte170m", "bt470bg"):
row("colour", "WARN", shown, "bt709/bt709 tagged (or HDR)",
"export.py (any re-encode here converts the BT.601 matrix to BT.709); color.py --retag bt709 only relabels it: right only if the pixels really are BT.709",
reason="a player that honours the BT.601 tag and one that ignores it on HD video (decoding it as BT.709) show different colours")
else:
row("colour", "WARN", shown, "bt709/bt709 tagged (or HDR)", "color.py --retag bt709 when the picture really is 709; color.py --to-sdr when it is HDR")
elif args.platform not in ("podcast", "custom"):
row("video", "FAIL", "none", "video stream", "")
size = meta.get("size_bytes") or 0
if spec["max_bytes"] and meta.get("size_bytes") is None:
row("file size", "FAIL", "could not measure", f"<= {spec['max_bytes'] / 1024 / 1024:.0f} MB", "",
reason="the file's size could not be read, so whether it is within the limit is unknown")
elif spec["max_bytes"]:
row("file size", "PASS" if size <= spec["max_bytes"] else "FAIL", f"{size / 1024 / 1024:.1f} MB", f"<= {spec['max_bytes'] / 1024 / 1024:.0f} MB", "export.py --crf 24 or lower resolution")
if a:
row("audio", "PASS", f"{a.get('codec')} {a.get('channels')}ch {a.get('sample_rate')}Hz", "present")
if args.platform == "podcast":
ch = a.get("channels") or 0
row("channels", "PASS" if ch in (1, 2) else "WARN", f"{ch}ch", "1 (mono) or 2 (stereo)",
"audio.py --downmix (5.1/7.1 to stereo with the ITU-R BS.775 weights) or audio.py --mono",
reason="podcast players downmix 5.1 unpredictably")
if args.platform == "podcast":
chapters = meta.get("chapters") or []
row("chapters", "PASS" if chapters else "WARN", f"{len(chapters)}" if chapters else "none", ">= 1 chapter marker",
"metadata.py episode.m4a --chapters chapters.txt (`TIME TITLE` per line; streams copied)",
reason="chapter markers are optional, but a podcast app shows them as the episode's seekable table of contents")
subs = meta.get("subtitle_stream_details") or []
if not subs:
row("subtitles", "WARN", "none", ">= 1 language-tagged subtitle track",
"caption.py video.mp4 --mode mux --srt subs.srt:en -o video_subs.mkv (streams are copied)",
reason="subtitles are optional, but they are the cheapest accessibility win a delivery has")
else:
untagged = [str(s["index"]) for s in subs if not s.get("language")]
listed = ", ".join((s.get("language") or "untagged") for s in subs)
row("subtitles", "WARN" if untagged else "PASS", f"{len(subs)} ({listed})",
"every track tagged with its language",
"caption.py video.mp4 --mode mux --srt subs.srt:en -o video_subs.mkv, or re-mux with `--srt file:lang` per track"
if untagged else "",
reason=("stream(s) " + ", ".join(untagged) + " carry no language tag: a player lists them "
"by number and the viewer has to guess") if untagged else "")
if a:
audio_row = next(r for r in rows if r["check"] == "audio")
def silent_audio(peak: float) -> None:
audio_row.update(status="FAIL" if spec["lufs"] is not None else "WARN", value=audio_row["value"] + f", silent (peak {peak:.1f} dB)",
expected=f"present, peak above {SILENT_PEAK_DBFS:g} dBFS",
fix="audio.py --replace with the real track, or re-export from the master",
reason="the audio track exists but carries no sound: viewers hear nothing")
loudness_ran = False
if a.get("sample_rate") and a["sample_rate"] not in (44100, 48000):
row("sample rate", "WARN", a["sample_rate"], "44100 or 48000", "loudness.py --sample-rate 48000")
tp_only = spec["lufs"] is None and args.tp is not None
if not args.no_loudness and (spec["lufs"] is not None or tp_only):
lm = measure_loudness(args.input)
loudness_ran = bool(lm)
if lm and lm["tp"] <= SILENT_PEAK_DBFS:
silent_audio(lm["tp"])
if lm and tp_only:
row("true peak", "PASS" if lm["tp"] <= spec["tp"] + TP_TOLERANCE_DB else "FAIL", f"{lm['tp']:.1f} dBTP", f"<= {spec['tp']:g} dBTP (+{TP_TOLERANCE_DB:g} dB tolerance)", f"loudness.py --tp {spec['tp']:g}")
elif not lm and tp_only:
row("true peak", "WARN", "could not measure", f"<= {spec['tp']:g} dBTP", "re-run check.py, or verify true peak manually",
reason="ffmpeg's loudness measurement didn't produce a readable result -- this was not actually checked")
elif (lm and lm["lufs"] == float("-inf") and lm["tp"] > SILENT_PEAK_DBFS
and shorter_than_a_loudness_block(own_length(a) or dur_read)):
row("loudness", "WARN", "could not measure (shorter than one 400 ms loudness block)",
f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", "",
reason="integrated loudness is gated over 400 ms blocks; a clip this short has none")
row("true peak", "PASS" if lm["tp"] <= spec["tp"] + TP_TOLERANCE_DB else "FAIL", f"{lm['tp']:.1f} dBTP", f"<= {spec['tp']:g} dBTP (+{TP_TOLERANCE_DB:g} dB tolerance)", f"loudness.py --tp {spec['tp']:g}")
elif lm:
diff = abs(lm["lufs"] - spec["lufs"])
row("loudness", "PASS" if diff <= spec["lufs_tol"] else "FAIL", f"{lm['lufs']:.1f} LUFS", f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", f"loudness.py -I {spec['lufs']:g} for speech or music; leave ambience/near-silence (<= -40 LUFS) alone and say so",
reason="the platform will auto-normalise it to its own target anyway, which can pump or duck the mix in ways you did not choose")
row("true peak", "PASS" if lm["tp"] <= spec["tp"] + TP_TOLERANCE_DB else "FAIL", f"{lm['tp']:.1f} dBTP", f"<= {spec['tp']:g} dBTP (+{TP_TOLERANCE_DB:g} dB tolerance)", f"loudness.py --tp {spec['tp']:g}")
else:
row("loudness", "WARN", "could not measure", f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", "re-run check.py, or verify loudness manually",
reason="ffmpeg's loudness measurement didn't produce a readable result -- this was not actually checked")
row("true peak", "WARN", "could not measure", f"<= {spec['tp']:g} dBTP", "re-run check.py, or verify true peak manually")
if not loudness_ran and not dry_run_input_pending(args.input):
lv = measured_level_dbfs(args.input, seconds=None)
if lv and lv["peak_dbfs"] <= SILENT_PEAK_DBFS:
silent_audio(lv["peak_dbfs"])
elif args.platform in ("podcast",):
row("audio", "FAIL", "none", "audio stream", "audio.py --replace")
else:
row("audio", "WARN", "none", "audio stream", "audio.py --replace (silent uploads are often rejected)")
if args.content:
cd = detect_content(args.input, dur, video=bool(v), audio=bool(a))
span = dur if dur > 0 else 0.0
if not span and not dry_run_input_pending(args.input):
for name, stream in (("black", v), ("frozen", v), ("silence", a)):
if stream:
row(name, "WARN", "could not measure", "a share of the running time",
"remux the file (export.py --preset copy) so the container states its length, then check again",
reason="the file does not state its length, so this share of it could not be worked out")
if "black" in cd and span:
share = _span_total(cd["black"]) / span
row("black", "FAIL" if share >= BLACK_FAIL else ("WARN" if share > BLACK_WARN else "PASS"),
f"{share * 100:.0f}% black", f"<= {BLACK_WARN * 100:.0f}% black",
"look.py the black spans; trim them with cut.py or re-export from the master",
reason="an all-black or mostly black picture is usually a failed render or a missing clip")
if "frozen" in cd and span:
longest = max((e - s for s, e in cd["frozen"]), default=0.0)
limit = max(FROZEN_WARN_S, FROZEN_WARN_SHARE * span)
row("frozen", "FAIL" if longest >= FROZEN_FAIL * span else ("WARN" if longest > limit else "PASS"),
f"longest {longest:.1f}s", f"<= {limit:.1f}s frozen",
"look.py the frozen span: a still title card is fine, a stuck decode is not",
reason="a picture that never changes is usually a stuck frame, not the edit")
if v and not dry_run_input_pending(args.input):
first = first_frame_stats(args.input)
if first is None:
row("first frame", "WARN", "could not measure", f"spread >= {CONTENT_FLAT_STD:g} (not one flat colour)",
"look.py the first frame", reason="the first frame did not decode, so whether it is flat is unknown")
else:
mean, spread = first
flat = spread < CONTENT_FLAT_STD
row("first frame", "WARN" if flat else "PASS", f"luma {mean:.0f}, spread {spread:.1f}",
f"spread >= {CONTENT_FLAT_STD:g} (not one flat colour)",
"a fade from black is a choice; where autoplay or the preview shows the first frame, start on "
"a picture (cut.py --start a few frames in, or move a title card to frame 0)" if flat else "",
reason="a feed shows the first frame before anything plays, and a flat one reads as a broken upload" if flat else "")
flashes = detect_flashes(args.input)
pts = presentation_times(args.input, float(v.get("start_time") or 0.0)) if flashes else None
at = flash_times(flashes or [], v, meta, pts)
if flashes is None:
row("flashes", "WARN", "could not measure", "no single frame unlike both its neighbours",
"look.py the video: no frame decoded, so nothing was compared",
reason="the video did not decode, so whether it has flashes is unknown")
else:
row("flashes", "WARN" if flashes else "PASS", f"{len(flashes)}" + (f": {at}" if flashes else ""),
"no single frame unlike both its neighbours",
"look.py at those times: a stray frame at a cut or join is an edit error (re-cut with cut.py "
"--accurate, or join.py again); a camera flash or a strobe in the footage is fine" if flashes else "",
reason="one frame that matches neither neighbour is usually a frame left over at a cut, or a decode glitch" if flashes else "")
if "silence" in cd and span:
share = _span_total(cd["silence"]) / span
row("silence", "FAIL" if share >= SILENCE_FAIL else ("WARN" if share > SILENCE_WARN else "PASS"),
f"{share * 100:.0f}% silent", f"<= {SILENCE_WARN * 100:.0f}% below {SILENT_PEAK_DBFS:g} dBFS",
"silence.py to cut the gaps, or audio.py --replace when the track is empty",
reason="most of the running time has no audible sound")
if "dropouts" in cd:
gaps = cd["dropouts"]
at = ", ".join(f"{s:.2f}s ({(e - s) * 1000:.0f} ms)" for s, e in gaps[:5]) + (" ..." if len(gaps) > 5 else "")
row("dropouts", "WARN" if gaps else "PASS", f"{len(gaps)}" + (f": {at}" if gaps else ""),
"no digital-silence gap under 1 s with sound on both sides",
"listen at those times: a gap at a cut or join is lost audio (re-cut with cut.py --accurate, or join.py "
"again); a noise gate makes these on purpose" if gaps else "",
reason="a short stretch of digital silence in the middle of the sound is usually lost audio at a join or a glitched decode" if gaps else "")
levels_doc = None
if args.levels and not dry_run_input_pending(args.input):
levels_doc = levels_row(args, v, row)
if args.compare and not dry_run_input_pending(args.input) and not dry_run_input_pending(args.compare):
ref = probe(args.compare)
rv = ref.get("video") or {}
if not v or not rv:
row("similarity", "WARN", "not compared", "two pictures", "--compare needs a video stream in both files",
reason="one of the files has no picture")
elif display_size(v) != display_size(rv):
row("similarity", "WARN", "not compared: %dx%d vs %dx%d (as displayed)" % (display_size(v) + display_size(rv)),
"the same frame size", "compare against a reference at the delivery size (fit.py or export.py it first)",
reason="SSIM and PSNR compare pixels, so the two frames must be the same size")
else:
cmp_ = compare_pictures(args.input, args.compare)
if cmp_ is None:
row("similarity", "WARN", "could not measure", f"mean SSIM >= {COMPARE_SSIM_WARN:g}",
"look.py --compare at a few times", reason="the comparison pass failed")
else:
pts = presentation_times(args.input, float(v.get("start_time") or 0.0))
at = frame_time(cmp_["worst_frame"], v, meta, pts)
seek = "0" if at.startswith("frame") else at.lstrip("~").rstrip("s")
psnr = "identical" if cmp_["psnr"] == float("inf") else (f"{cmp_['psnr']:.1f} dB" if cmp_["psnr"] is not None else "?")
low = cmp_["ssim"] < COMPARE_SSIM_WARN
row("similarity", "WARN" if low else "PASS",
f"SSIM {cmp_['ssim']:.4f} (worst {cmp_['worst_ssim']:.4f} at {at}), PSNR {psnr}, {cmp_['frames']} frames",
f"mean SSIM >= {COMPARE_SSIM_WARN:g}",
f"look.py --compare {args.compare} --at {seek}" if low else "",
reason="the picture differs visibly from the reference somewhere" if low else "")
nout = v.get("nb_frames") or len(pts) or None
nref = rv.get("nb_frames") or len(presentation_times(args.compare, float(rv.get("start_time") or 0.0))) or None
if nref and nout and int(nref) != int(nout):
STATE_NOTES.append(f"--compare: {nout} frames against the reference's {nref}; frames were paired in "
f"order, so an added or dropped frame shifts every later pair, and only the "
f"first {min(int(nref), int(nout))} were compared")
scope_doc = None
if declared_changes is not None and not dry_run_input_pending(args.input) and not dry_run_input_pending(args.compare):
scope_doc = change_scope_row(args, declared_changes, meta, v, row)
identity = None if dry_run_input_pending(args.input) else file_identity(args.input)
if identity is not None and identity != identity_before and expected_identity is None:
STATE_NOTES.append("the file changed while it was being checked: input_identity is the file as it was "
"at the end, and the rows may describe an earlier one; check it again")
if expected_identity is not None:
size, mtime_ns = expected_identity["size"], expected_identity["mtime_ns"]
if identity is not None:
changed = identity != identity_before
same = identity == {"size": size, "mtime_ns": mtime_ns} and not changed
row("identity", "PASS" if same else "FAIL", f"{identity['size']}:{identity['mtime_ns']}", f"{size}:{mtime_ns}",
"" if same else "re-run the tool that writes this file and check what it reports, not what the path holds",
reason="" if same else ("the file changed while it was being checked" if changed
else "the file at this path is not the one the run being checked wrote"))
elif not dry_run_input_pending(args.input):
row("identity", "FAIL", "no regular file at this path", f"{size}:{mtime_ns}",
"re-run the tool that writes this file and check what it reports, not what the path holds",
reason="the file at this path is not the one the run being checked wrote")
failed = [r for r in rows if r["status"] == "FAIL"]
warned = [r for r in rows if r["status"] == "WARN"]
notes: List[str] = []
if not named:
notes.append("no --platform given: youtube's spec was assumed, so judgement rows (duration, aspect, fps, resolution, loudness, true peak) are WARN, not FAIL; name a platform to enforce them")
notes += STATE_NOTES
if not args.json:
width = max(len(r["check"]) for r in rows)
print(f"{args.input} — {args.platform}" + ("" if named else " (assumed)"))
for r in rows:
line = f" {r['status']:4s} {r['check']:{width}s} {r['value']} (expected {r['expected']})"
if r["status"] != "PASS" and r["kind"] == "judgement":
line += " [judgement]"
if r["status"] != "PASS" and r["basis"] == "guidance":
line += " [guidance]"
if r["status"] != "PASS" and r["reason"]:
line += f" ({r['reason']})"
if r["status"] != "PASS" and r["fix"]:
line += f" -> {r['fix']}"
print(line)
print(f" {len(rows)} checks, {len(failed)} failed, {len(warned)} warnings")
for n in notes:
print(f" note: {n}")
extra: Dict[str, Any] = {"notes": notes} if notes else {}
if levels_doc is not None:
extra["levels"] = levels_doc
if scope_doc is not None:
extra["change_scope"] = scope_doc
if identity is not None:
extra["input_identity"] = identity
if failed:
die(f"{len(failed)} of {len(rows)} {args.platform} checks failed: {', '.join(r['check'] for r in failed)}",
kind="verification", output=None, dry_run=STATE.dry_run,
platform=args.platform, checks=rows, failed=len(failed), warnings=len(warned), ok=False, **extra)
emit(None, platform=args.platform, checks=rows, failed=len(failed), warnings=len(warned), ok=True, **extra)
return 0
if __name__ == "__main__":
sys.exit(main())