Skip to content

Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.

fix: seventh review (--normalize temp name, --codec edges, contract) and eval-8 follow-ups (#204)

claude[bot]d69bc5af5716
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3c13a22..4389ac0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,8 @@
## Unreleased
-(nothing yet)
+- Seventh review (the 1.8.0 encoder flags and `--normalize`). `export.py --normalize` wrote its temporary file under `loudness.py`'s own default output name and destroyed a pre-existing `<output>_loudnorm.<ext>` (P0; now a private per-process name, no forced overwrite, and the normalising encode is in `commands`); `--normalize` on a preset without a loudness spec is `kind: input` and under `--dry-run` says what it would do; `--codec prores` without `-o` failed inside ffmpeg (refused with the `.mov` hint); `waveform.py` ignored `--codec`; `cut.py --codec` on the lossless path kept the source codec (switches to `--accurate`, said so); `export.py` no longer advertises `--codec` in the contract; duplicated `encoder:libx265` optional capabilities merged; `x264_args(keep_bt709=False)` honoured under `--codec`; HDR HEVC `--quality 50/51` no longer overflows CRF; the `--crf` range message names the av1 bound; `check.py` tags `true peak` as a judgement row.
+- Eval 8 follow-ups. SKILL.md says how to run doctor (`python3 scripts/_contract.py doctor --json`; two runs looked for a doctor.py); `render.py --init` writes `"normalize": true` on the export stage; the ProRes rule says `-o NAME.mov` explicitly.
## 1.8.0
diff --git a/SKILL.md b/SKILL.md
index 5659a16..82747e1 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -5,12 +5,14 @@ description: 'Edit video and audio with local FFmpeg from natural-language reque
# ffmpeg-skill
-Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. Every script has `--help`, and all of them accept `--dry-run`, `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress`, `--timeout SECONDS` (a single ffmpeg run is killed past this and reported as `kind: timeout`; default 1800) and `--overwrite` (consent to replace an output that already exists; without it the tool warns today and refuses from 2.0) and `--plan FILE` (a dry run written as a plan: fingerprinted inputs, commands, expected output, verify steps; `render.py FILE` executes it later and refuses if an input changed, so "plan → user confirms → execute" is one round trip). Writing tools run nothing under `--dry-run`; `probe`/`check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact (nor side files such as `--edl`, `--sheet` or a generated `.ass`); `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`). Every tool that re-encodes also takes `--codec h264|hevc|av1|prores` and `--quality N` (CRF scale; overrides `--crf`): without them SDR is x264 and HDR is x265 Main10, as before; `--codec prores` needs a `.mov` output, `--codec h264` refuses an HDR source (run `color.py --to-sdr` first). Details for every flag: `references/scripts.md`. Device-specific behaviour (iPhone HDR, GoPro, DJI, screen recordings, Zoom): `references/devices.md`.
+Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. Every script has `--help`, and all of them accept `--dry-run`, `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress`, `--timeout SECONDS` (a single ffmpeg run is killed past this and reported as `kind: timeout`; default 1800) and `--overwrite` (consent to replace an output that already exists; without it the tool warns today and refuses from 2.0) and `--plan FILE` (a dry run written as a plan: fingerprinted inputs, commands, expected output, verify steps; `render.py FILE` executes it later and refuses if an input changed, so "plan → user confirms → execute" is one round trip). Writing tools run nothing under `--dry-run`; `probe`/`check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact (nor side files such as `--edl`, `--sheet` or a generated `.ass`); `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`). Every tool that re-encodes also takes `--codec h264|hevc|av1|prores` and `--quality N` (CRF scale; overrides `--crf`): without them SDR is x264 and HDR is x265 Main10, as before; `--codec prores` needs an explicit `-o NAME.mov` (or `.mkv`), `--codec h264` refuses an HDR source (run `color.py --to-sdr` first). Details for every flag: `references/scripts.md`. Device-specific behaviour (iPhone HDR, GoPro, DJI, screen recordings, Zoom): `references/devices.md`.
## Workflow (always follow this order)
0. **Check the environment once per session, if unfamiliar.** On a machine
- you haven't confirmed capability on this session, run `doctor --json`
+ you haven't confirmed capability on this session, run
+ `python3 <skill-dir>/scripts/_contract.py doctor --json` (the npm install
+ also exposes it as `npx ffmpeg-skill doctor --json`; there is no doctor.py)
once: check `ok` and the target tool's `usable` before relying on it. If
`usable` isn't `yes`, don't run that tool — report the missing capability
instead of discovering it via a runtime failure (a missing `libass`,
diff --git a/evals/agent_prompts_24.json b/evals/agent_prompts_24.json
index 0bb6e68..a2ba476 100644
--- a/evals/agent_prompts_24.json
+++ b/evals/agent_prompts_24.json
@@ -17,7 +17,6 @@
"lang": "en",
"prompt": "Trim /home/user/ffmpeg-skill/tests/out/source.mp4 to 0:02-0:08 without losing quality, save in OUTDIR.",
"expect": [
- "probe",
"cut"
],
"refuse": false
@@ -163,7 +162,7 @@
"prompt": "/home/user/ffmpeg-skill/tests/out/gappy.mp4 の間(無音)を詰めて、YouTube 向けに音量も整えて。OUTDIR。",
"expect": [
"silence",
- "loudness"
+ "loudness|export"
],
"refuse": false
},
diff --git a/references/scripts.md b/references/scripts.md
index eed5b1f..9c24d1d 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -1,6 +1,6 @@
# Script reference
-Every script prints the same information with `--help`; this file exists so the agent can read several at once. All scripts accept `--dry-run`, `--json`, `--fast`, `--progress`, `--timeout SECONDS`, `--overwrite`, `--plan FILE` (the dry run written as a plan document that `render.py FILE` executes later; see render.py), `-o OUT`; every tool that re-encodes (the ones with `--crf`) also takes `--codec h264|hevc|av1|prores` (the encoder for the re-encode; default x264 for SDR, x265 Main10 for HDR, unchanged) and `--quality N` (CRF scale, overrides `--crf`; up to 63 for av1; ignored by prores). `--codec hevc` on SDR writes 8-bit BT.709 HEVC (`hvc1`), `av1` uses SVT-AV1 (libaom fallback), `prores` is 422 HQ and needs a `.mov`/`.mkv` output, `h264` refuses an HDR source (`kind: input`, run `color.py --to-sdr` first). `export.py` keeps choosing the codec from its preset and refuses `--codec` -- but `--dry-run` only guarantees nothing is written for writing tools: `probe` (read-only, `--dry-run` changes nothing) still runs ffprobe, `check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` still run their ffmpeg/ffprobe measurements (a dry-run plan rests on real numbers; they just don't write the final artifact), and `verify` accepts the flag but ignores it entirely. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).
+Every script prints the same information with `--help`; this file exists so the agent can read several at once. All scripts accept `--dry-run`, `--json`, `--fast`, `--progress`, `--timeout SECONDS`, `--overwrite`, `--plan FILE` (the dry run written as a plan document that `render.py FILE` executes later; see render.py), `-o OUT`; every editing tool that re-encodes (not `export.py`, whose preset decides the codec) also takes `--codec h264|hevc|av1|prores` (the encoder for the re-encode; default x264 for SDR, x265 Main10 for HDR, unchanged) and `--quality N` (CRF scale, overrides `--crf`; up to 63 for av1; ignored by prores). `--codec hevc` on SDR writes 8-bit BT.709 HEVC (`hvc1`), `av1` uses SVT-AV1 (libaom fallback), `prores` is 422 HQ and needs an explicit `-o NAME.mov` (or `.mkv`), `h264` refuses an HDR source (`kind: input`, run `color.py --to-sdr` first). `export.py` keeps choosing the codec from its preset and has neither flag; a `render.py` project cannot choose a codec either -- but `--dry-run` only guarantees nothing is written for writing tools: `probe` (read-only, `--dry-run` changes nothing) still runs ffprobe, `check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` still run their ffmpeg/ffprobe measurements (a dry-run plan rests on real numbers; they just don't write the final artifact), and `verify` accepts the flag but ignores it entirely. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).
## Contents
- probe.py — inspect
diff --git a/scripts/_common.py b/scripts/_common.py
index a8b79a4..95998c6 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -258,8 +258,9 @@ class Context:
STATE = Context()
-def add_common(ap: "argparse.ArgumentParser") -> None:
- """Add the flags every script shares."""
+def add_common(ap: "argparse.ArgumentParser", codec: bool = True) -> None:
+ """Add the flags every script shares. `codec=False` is for a tool that re-encodes but whose
+ preset decides the encoder (export.py): it must not advertise --codec/--quality in its schema."""
g = ap.add_argument_group("agent options")
g.add_argument("--dry-run", action="store_true", help="print the ffmpeg commands that would run, run nothing")
g.add_argument("--json", action="store_true", help="print a JSON result (output, probe, commands) on stdout instead of the path")
@@ -272,7 +273,7 @@ def add_common(ap: "argparse.ArgumentParser") -> None:
help="allow replacing an existing output (warned today, refused from 2.0)")
g.add_argument("--plan", metavar="FILE",
help="write the dry run as a plan (inputs fingerprinted, commands, expected output, verify steps) that render.py FILE executes later; implies --dry-run")
- if "--crf" in ap._option_string_actions:
+ if codec and "--crf" in ap._option_string_actions:
# only the tools that re-encode (they declare --crf before add_common): one encoder choice
# resolved in video_args(), the 2.0 encoder abstraction pre-shipped in 1.8 (docs/roadmap.md)
g.add_argument("--codec", choices=CODECS, default=None,
@@ -304,14 +305,20 @@ def apply_common(args: "argparse.Namespace") -> None:
if not 0 <= int(quality) <= top:
die(f"--quality must be between 0 and {top} for {STATE.codec or 'h264'} (CRF scale; 18 is visually lossless), got {quality}")
args.crf = int(quality) # every tool reads args.crf; --quality is the codec-neutral spelling of it
- if STATE.codec == "prores":
+ if STATE.codec == "prores" and hasattr(args, "output"):
out = getattr(args, "output", None)
- if out and os.path.splitext(str(out))[1].lower() not in (".mov", ".mkv"):
+ if not out:
+ # every tool defaults its output to the source's extension (or .mp4): ProRes in an .mp4
+ # fails inside ffmpeg with "codec not currently supported in container" (review 7)
+ die("--codec prores needs an explicit -o NAME.mov (or .mkv): the default output name keeps the source's container, which cannot hold ProRes",
+ hint="give -o NAME.mov")
+ if os.path.splitext(str(out))[1].lower() not in (".mov", ".mkv"):
die(f"--codec prores needs a .mov (or .mkv) output; {os.path.basename(str(out))} cannot hold ProRes",
hint="give -o NAME.mov")
crf = getattr(args, "crf", None)
- if crf is not None and not 0 <= int(crf) <= (63 if STATE.codec == "av1" else 51):
- die(f"--crf must be between 0 and 51 (x264/x265 scale; 18 is visually lossless, 23 the encoder default), got {crf}")
+ top = 63 if STATE.codec == "av1" else 51
+ if crf is not None and not 0 <= int(crf) <= top:
+ die(f"--crf must be between 0 and {top} ({'SVT-AV1' if STATE.codec == 'av1' else 'x264/x265'} scale; 18 is visually lossless), got {crf}")
install_signal_handlers()
@@ -1671,7 +1678,7 @@ def _sdr_bt709(encoder: str) -> "Tuple[str, List[str]]":
return "colorprim=bt709:transfer=bt709:colormatrix=bt709", []
-def encoder_args(codec: str, crf: int, preset: str, meta: Optional[Dict[str, Any]] = None) -> List[str]:
+def encoder_args(codec: str, crf: int, preset: str, meta: Optional[Dict[str, Any]] = None, keep_bt709: bool = True) -> List[str]:
"""The one place that turns (--codec, --quality, --preset, source) into encoder options.
h264 -> x264 8-bit BT.709 (refuses HDR: 8-bit H.264 cannot carry it); hevc -> x265, Main10
@@ -1689,13 +1696,13 @@ def encoder_args(codec: str, crf: int, preset: str, meta: Optional[Dict[str, Any
if hdr:
die(f"--codec h264 cannot carry HDR ({v.get('hdr_format') or 'BT.2020'}): 8-bit H.264 is SDR only",
hint="run color.py --to-sdr first, or use --codec hevc / av1 / prores, which keep the source's HDR")
- return _x264_raw(crf, preset)
+ return _x264_raw(crf, preset, keep_bt709)
if codec == "hevc":
if hdr:
x265 = f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}:range=limited:hdr10-opt=1" if trc == "smpte2084" else f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}"
- return ["-c:v", "libx265", "-preset", preset, "-crf", str(crf + 2), "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1",
+ return ["-c:v", "libx265", "-preset", preset, "-crf", str(min(51, crf + 2)), "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1",
"-x265-params", x265] + hdr_tags + ["-movflags", "+faststart"]
- params, extra = _sdr_bt709("libx265")
+ params, extra = _sdr_bt709("libx265") if keep_bt709 else ("", [])
return ["-c:v", "libx265", "-preset", preset, "-crf", str(crf), "-pix_fmt", "yuv420p", "-tag:v", "hvc1",
"-x265-params", "log-level=error" + (":" + params if params else "")] + extra + ["-movflags", "+faststart"]
if codec == "av1":
@@ -1704,12 +1711,12 @@ def encoder_args(codec: str, crf: int, preset: str, meta: Optional[Dict[str, Any
args = ["-c:v", "libsvtav1", "-preset", str(SVT_PRESET.get(preset, 6)), "-crf", str(min(63, crf)), "-pix_fmt", pix]
if hdr:
args += hdr_tags
- else:
+ elif keep_bt709:
params, extra = _sdr_bt709("libsvtav1")
args += (["-svtav1-params", params] if params else []) + extra
elif "libaom-av1" in ffmpeg_encoders():
args = ["-c:v", "libaom-av1", "-crf", str(min(63, crf)), "-b:v", "0", "-cpu-used", "6", "-row-mt", "1", "-pix_fmt", pix]
- args += hdr_tags if hdr else _sdr_bt709("libaom-av1")[1]
+ args += hdr_tags if hdr else (_sdr_bt709("libaom-av1")[1] if keep_bt709 else [])
else:
die("--codec av1 needs an AV1 encoder (libsvtav1 or libaom-av1) and this ffmpeg build has neither", kind="missing_tool",
hint="install an ffmpeg built with SVT-AV1 (most distribution builds are), or use --codec hevc")
@@ -1733,7 +1740,7 @@ def x264_args(crf: int = 18, preset: str = "medium", keep_bt709: bool = True) ->
"""SDR H.264 encoder args -- or, when --codec named another encoder, that encoder's SDR args
(color.py's --to-sdr path builds its own H.264 line; the flag still has to reach it)."""
if STATE.codec and STATE.codec != "h264":
- return encoder_args(STATE.codec, crf, preset, None)
+ return encoder_args(STATE.codec, crf, preset, None, keep_bt709)
return _x264_raw(crf, preset, keep_bt709)
@@ -1754,7 +1761,7 @@ def video_args(meta: Optional[Dict[str, Any]], crf: int = 18, preset: str = "med
prim = v.get("color_primaries") or "bt2020"
trc = v.get("color_transfer") or "arib-std-b67"
x265 = f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}:range=limited:hdr10-opt=1" if trc == "smpte2084" else f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}"
- return ["-c:v", "libx265", "-preset", preset, "-crf", str(crf + 2), "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1",
+ return ["-c:v", "libx265", "-preset", preset, "-crf", str(min(51, crf + 2)), "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1",
"-x265-params", x265, "-colorspace", cs, "-color_primaries", prim, "-color_trc", trc, "-movflags", "+faststart"]
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 07a0b16..4dddbda 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -876,6 +876,19 @@ def capability_map(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
# ----------------------------------------------------------------------------- contract
+def _merge_optional(base: List[Dict[str, Any]], extra: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """Optional capabilities de-duplicated by name: a tool that already lists encoder:libx265 for
+ HDR sources gets its `when` extended by the --codec condition instead of a second entry."""
+ out: List[Dict[str, Any]] = [dict(o) for o in base]
+ for o in extra:
+ hit = next((b for b in out if b["capability"] == o["capability"]), None)
+ if hit is None:
+ out.append(dict(o))
+ elif o["when"] not in hit["when"]:
+ hit["when"] = f"{hit['when']}; {o['when']}"
+ return out
+
+
def tool_spec(name: str, version: str) -> Dict[str, Any]:
if name not in TOOL_META:
# a public script without metadata is drift: fail loudly instead of guessing its role or capabilities
@@ -903,7 +916,7 @@ def tool_spec(name: str, version: str) -> Dict[str, Any]:
"description": (parser.description or "").strip().splitlines()[0] if parser.description else "",
"executable": f"scripts/{name}.py",
"role": meta["role"],
- "capabilities": {"required": list(meta["required"]), "optional": list(meta["optional"]) + (CODEC_CAPS if "codec" in schema["properties"] else [])},
+ "capabilities": {"required": list(meta["required"]), "optional": _merge_optional(meta["optional"], CODEC_CAPS if "codec" in schema["properties"] else [])},
"inputs": list(meta["inputs"]),
"outputs": list(meta["outputs"]),
"input_schema": schema,
diff --git a/scripts/check.py b/scripts/check.py
index 34f8b02..6e0de05 100755
--- a/scripts/check.py
+++ b/scripts/check.py
@@ -98,14 +98,14 @@ def main() -> int:
v, a = meta.get("video") or {}, meta.get("audio") or {}
rows: List[Dict[str, Any]] = []
- JUDGEMENT = {"duration", "aspect", "loudness", "fps", "resolution"}
+ JUDGEMENT = {"duration", "aspect", "loudness", "true peak", "fps", "resolution"}
def row(name: str, status: str, value: Any, expect: Any, fix: str = "", reason: str = "") -> None:
# "format" rows are safe to fix mechanically; "judgement" rows change the content
# (what is cut, what is cropped, how loud ambience gets) and need a decision.
# "fix" is the command that resolves it; "reason" (only on the FAILs a non-technical
# person would ask "so what?" about) is why it matters in plain terms, not the spec clause.
- if status == "FAIL" and not named and (name in JUDGEMENT or name == "true peak"):
+ if status == "FAIL" and not named and name in JUDGEMENT:
status = "WARN"
rows.append({"check": name, "status": status, "value": value, "expected": expect, "fix": fix,
"reason": reason if status != "PASS" else "",
diff --git a/scripts/cut.py b/scripts/cut.py
index 6e100d6..e41a6a6 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -174,6 +174,10 @@ def main() -> int:
if meta.get("video", {}) and meta["video"].get("variable_frame_rate_suspected") and not args.accurate:
info("source looks variable-frame-rate; lossless cuts on VFR are unreliable, switching to --accurate")
args.accurate = True
+ if STATE.codec and not args.accurate:
+ # "cut this and make it HEVC": a stream copy keeps the source codec, so the request is a re-encode
+ info(f"--codec {STATE.codec} asks for a re-encode; the lossless copy path keeps the source codec, switching to --accurate")
+ args.accurate = True
fps = (meta.get("video") or {}).get("fps")
if args.segments:
diff --git a/scripts/export.py b/scripts/export.py
index 10e7cc4..53edab6 100755
--- a/scripts/export.py
+++ b/scripts/export.py
@@ -62,7 +62,7 @@ def main() -> int:
ap.add_argument("--crf", type=int, help="override CRF")
ap.add_argument("--normalize", action="store_true", help="youtube/youtube4k/reels/x: when the written file misses the platform's loudness spec, run loudness.py on it (audio re-encoded, video copied) so one export delivers")
ap.add_argument("--list", action="store_true", help="list presets and exit")
- add_common(ap)
+ add_common(ap, codec=False) # the preset decides the codec; --codec would only be refused
args = ap.parse_args()
apply_common(args)
@@ -73,9 +73,9 @@ def main() -> int:
if not args.input or not args.preset:
die("input and --preset are required (or use --list)")
validate_color(args.pad_color, "--pad-color")
- if args.codec:
- die(f"export.py's presets decide the codec (--preset h265 for HEVC, prores for ProRes); --codec {args.codec} is for the editing tools",
- hint="drop --codec here, or run the edit with --codec and export with --preset copy")
+ if args.normalize and args.preset not in PLATFORM_OF:
+ die(f"--normalize applies to the platform presets ({', '.join(sorted(PLATFORM_OF))}); --preset {args.preset} has no loudness spec to meet",
+ hint="drop --normalize, or run loudness.py with your own target")
p = PRESETS[args.preset]
meta = probe(args.input)
@@ -153,12 +153,15 @@ def main() -> int:
# encodes). The levels pass only re-encodes audio, so do it here on the written
# file and the caller gets one export that meets the spec.
info(f"loudness {m['lufs']:.1f} LUFS / {m['tp']:+.1f} dBTP is outside {platform}'s spec; normalising to {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP")
- tmp = str(Path(output).with_name(Path(output).stem + "_loudnorm" + Path(output).suffix))
- proc = run_tool([str(HERE / "loudness.py"), output, "-I", f"{spec['lufs']:g}", "--tp", f"{spec['tp']:g}", "-o", tmp, "--json", "--overwrite"] + child_args())
+ # a private name: <stem>_loudnorm.<ext> is loudness.py's own default output, so a
+ # real file of that name next to the export was overwritten and renamed away (review 7)
+ tmp = str(Path(output).with_name(f".{Path(output).stem}.normalize-{os.getpid()}{Path(output).suffix}"))
+ proc = run_tool([str(HERE / "loudness.py"), output, "-I", f"{spec['lufs']:g}", "--tp", f"{spec['tp']:g}", "-o", tmp, "--json"] + child_args())
try:
child = json.loads(proc.stdout)
except ValueError:
child = {}
+ STATE.commands.extend(child.get("commands") or []) # the encode that changed the audio belongs in this run's log
if proc.returncode != 0 or child.get("status") != "completed":
err = child.get("error") or {}
if os.path.exists(tmp):
@@ -177,6 +180,9 @@ def main() -> int:
notes.append(f"loudness {m['lufs']:.1f} LUFS / {m['tp']:+.1f} dBTP is outside {platform}'s {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP; "
f"run loudness.py -I {spec['lufs']:g} --tp {spec['tp']:g} on this file, or export with --normalize")
info("warning: " + notes[-1])
+ elif platform and has_audio and args.normalize:
+ spec = PLATFORMS[platform]
+ notes.append(f"[dry-run] --normalize: loudness.py -I {spec['lufs']:g} --tp {spec['tp']:g} would run on the written file if it misses {platform}'s spec")
if notes:
extra["notes"] = notes
emit(output, **extra)
diff --git a/scripts/render.py b/scripts/render.py
index dd055d0..9badffa 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -74,7 +74,7 @@ TEMPLATE = {
"audio": None,
"loudness": {"lufs": -14, "tp": -1},
"fit": None,
- "export": {"preset": "youtube"},
+ "export": {"preset": "youtube", "normalize": True},
"check": {"platform": "youtube"},
}
diff --git a/scripts/waveform.py b/scripts/waveform.py
index e2bb158..0bcc19d 100644
--- a/scripts/waveform.py
+++ b/scripts/waveform.py
@@ -22,7 +22,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, validate_color, X264_PRESETS, fmt_secs
+from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, validate_color, video_args, X264_PRESETS, fmt_secs
WAVEFORM_MODES = ["point", "line", "p2p", "cline"]
@@ -76,7 +76,7 @@ def main() -> int:
vf = f"color=c={args.background}:s={args.width}x{args.height}:r={args.fps:g}[bg];[0:a:{args.audio_stream}]{vf}[vis];[bg][vis]overlay=format=auto"
cmd = ffmpeg_base() + ["-i", args.input, "-filter_complex", vf, "-map", f"0:a:{args.audio_stream}"]
- cmd += ["-c:v", "libx264", "-preset", args.preset, "-crf", str(args.crf), "-pix_fmt", "yuv420p", "-movflags", "+faststart"]
+ cmd += video_args(None, args.crf, args.preset) # the one encoder line, so --codec / --quality reach it (review 7)
cmd += aac_args()
# -shortest alone is not enough on FFmpeg 5.x: showwaves keeps emitting frames after the
# audio ends (a 12 s source came out 14.08 s on 5.1.1, #146), so the output is also capped
diff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.json
index 8a27084..7aca5d2 100644
--- a/tests/fixtures/mcp_tools.json
+++ b/tests/fixtures/mcp_tools.json
@@ -364,7 +364,6 @@
"properties": [
"allow_long",
"argv",
- "codec",
"crf",
"dry_run",
"fast",
@@ -382,7 +381,6 @@
"plan",
"preset",
"progress",
- "quality",
"timeout"
],
"required": []
diff --git a/tests/test_all.py b/tests/test_all.py
index 4e467c4..faf6990 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -2271,8 +2271,37 @@ class FFmpegSkillTests(unittest.TestCase):
# --quality bounds follow the codec; export refuses --codec
d = json.loads(script("fit.py", self.src, "--width", "320", "--quality", "60", "-o", out, "--json", expect_fail=True).stdout)
self.assertEqual(d["error"]["kind"], "input")
- d = json.loads(script("export.py", self.src, "--preset", "x", "--codec", "hevc", "-o", OUT / "codec_export.mp4", "--json", expect_fail=True).stdout)
+ proc = script("export.py", self.src, "--preset", "x", "--codec", "hevc", "-o", OUT / "codec_export.mp4", "--json", expect_fail=True)
+ self.assertIn("--codec", proc.stderr) # argparse: the preset decides, the flag is not offered (review 7)
+ self.assertNotIn("--codec", script("export.py", "--help").stdout)
+ # review 7: prores without -o would have failed inside ffmpeg (mp4 cannot hold it)
+ d = json.loads(script("fit.py", self.src, "--width", "320", "--codec", "prores", "--json", expect_fail=True).stdout)
self.assertEqual(d["error"]["kind"], "input")
+ self.assertIn("-o NAME.mov", d["error"]["hint"])
+ # review 7: cut's lossless path used to keep the source codec under --codec
+ cutout = OUT / "codec_cut.mp4"
+ script("cut.py", self.src, "--start", "0", "--end", "2", "--codec", "hevc", "-o", cutout, "--fast", "--json", "--overwrite")
+ self.assertEqual(probe(str(cutout))["video"]["codec"], "hevc")
+ # review 7: waveform.py built its own x264 line and ignored the flag
+ wf = OUT / "codec_wave.mp4"
+ script("waveform.py", self.src, "--codec", "hevc", "-o", wf, "--fast", "--json", "--overwrite") # source.mp4: c_tone.wav is a test_contract fixture
+ self.assertEqual(probe(str(wf))["video"]["codec"], "hevc")
+ # review 7: the av1 bound is named in the --crf message, and HDR hevc --quality 51 does not overflow
+ d = json.loads(script("fit.py", self.src, "--width", "320", "--codec", "av1", "--crf", "70", "-o", out, "--json", expect_fail=True).stdout)
+ self.assertIn("63", d["error"]["message"])
+ sys.path.insert(0, str(SCRIPTS))
+ try:
+ import _common as c
+ finally:
+ sys.path.pop(0)
+ args = c.encoder_args("hevc", 51, "medium", {"video": {"hdr": True, "color_transfer": "smpte2084"}})
+ self.assertEqual(args[args.index("-crf") + 1], "51")
+ self.assertNotIn("-colorspace", c.encoder_args("hevc", 18, "medium", None, keep_bt709=False))
+ # the contract lists each --codec encoder once per tool
+ spec = json.loads(script("_contract.py", "--json").stdout)
+ fit_caps = [o["capability"] for o in next(t for t in spec["tools"] if t["name"] == "fit")["capabilities"]["optional"]]
+ self.assertEqual(len(fit_caps), len(set(fit_caps)), fit_caps)
+ self.assertNotIn("codec", next(t for t in spec["tools"] if t["name"] == "export")["input_schema"]["properties"])
# no --codec: the old default line, byte for byte
d = json.loads(script("fit.py", self.src, "--width", "320", "-o", out, "--fast", "--json", "--overwrite").stdout)
self.assertTrue(any("libx264" in c for c in d["commands"]))
@@ -2332,6 +2361,7 @@ class FFmpegSkillTests(unittest.TestCase):
rows = {r["check"]: r for r in data["checks"]}
self.assertEqual(rows["true peak"]["status"], "WARN")
self.assertEqual(rows["loudness"]["kind"], "judgement")
+ self.assertEqual(rows["true peak"]["kind"], "judgement")
self.assertTrue(any("no --platform" in n for n in data["notes"]))
# the same file with the platform named is the same FAIL as before
data = json.loads(script("check.py", self.src, "--platform", "youtube", "--json", expect_fail=True).stdout)
@@ -2610,6 +2640,20 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertTrue(d["verified"])
self.assertAlmostEqual(d["loudness"]["lufs"], -14.0, delta=1.0)
self.assertFalse((OUT / "export_normalize_loudnorm.mp4").exists())
+ self.assertTrue(any("linear=true" in c for c in d["commands"]), "the normalising encode is in the command log (review 7)")
+ # review 7 P0: a real <output>_loudnorm.<ext> next to the export survives --normalize
+ precious = OUT / "export_normalize_loudnorm.mp4"
+ precious.write_bytes(b"PRECIOUS")
+ try:
+ script("export.py", OUT / "source.mp4", "--preset", "x", "--normalize", "-o", out, "--fast", "--json", "--overwrite")
+ self.assertEqual(precious.read_bytes(), b"PRECIOUS")
+ finally:
+ precious.unlink()
+ # --normalize on a preset without a loudness spec is refused; under --dry-run it says what it would do
+ d = json.loads(script("export.py", OUT / "source.mp4", "--preset", "h265", "--normalize", "-o", OUT / "export_norm_h265.mp4", "--json", expect_fail=True).stdout)
+ self.assertEqual(d["error"]["kind"], "input")
+ d = json.loads(script("export.py", OUT / "source.mp4", "--preset", "x", "--normalize", "-o", out, "--dry-run", "--json").stdout)
+ self.assertTrue(any("--normalize" in n for n in d.get("notes", [])), d)
# without the flag the same file is reported, not fixed
proc = script("export.py", OUT / "source.mp4", "--preset", "x", "-o", out, "--fast", "--json", "--overwrite")
d = json.loads(proc.stdout)