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: eval-7 follow-ups -- export --normalize, render frame from the export preset, report language and labels on failures (#200)

claude[bot]58838fe0181f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index edd57cf..51148c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@
## Unreleased
-(nothing yet)
+- Eval iteration 7 follow-ups. `export.py --normalize` runs `loudness.py` on the written file when a platform preset's loudness spec is missed (audio re-encoded, video copied), so a platform export is one call instead of export, loudness, export again. `render.py` fills `frame.width/height` from the export preset when the project gives only an aspect of the same shape, so captions and overlays are burned at the delivery size instead of the source's short side (406x720 before a 1080x1920 reels export). SKILL.md: the report language is the language the request is written in, not a language it talks about or the language of an error (six English refusals came back in Spanish or Portuguese); the five report labels hold for the shortest failure too.
## 1.7.0
diff --git a/SKILL.md b/SKILL.md
index e8291cb..96ef77c 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -160,7 +160,7 @@ If a request needs an FFmpeg feature none of the 42 scripts expose, say so and n
| "remove the green screen", "chroma key this" | `overlay.py bg.mp4 --video greenscreen.mp4 --chromakey 0x00ff00` |
| "sync the lav mic to the camera", "line up the two cameras" | `sync.py camera.mp4 mic.wav --replace-audio` / `sync.py camA.mp4 camB.mp4 --trim-second` |
| "fix the audio levels", "normalise to -14 LUFS" | `loudness.py input.mp4` (`-I -16 --tp -1.5` for podcasts, `-I -23` for broadcast) |
-| "export for YouTube / Reels / X", "give me a ProRes master", "make it HEVC" | `export.py input.mp4 --preset youtube|reels|x|prores|h265` |
+| "export for YouTube / Reels / X", "give me a ProRes master", "make it HEVC" | `export.py input.mp4 --preset youtube|reels|x|prores|h265` (`--normalize` meets the platform's loudness spec in the same call, no separate `loudness.py` pass) |
| "make a GIF preview" | `export.py input.mp4 --preset gif` |
| "make a small/low-res proxy for an analysis pass", "a cheap preview file" | `proxy.py input.mp4 [--width 640 --no-audio]` — not a delivery preset, see `export.py` for those |
| "cut out the pauses / dead air", "tighten it up", "jump cuts" | `silence.py input.mp4 [--threshold -40 --min-silence 0.8]` |
@@ -239,7 +239,7 @@ commands work with `talk.wav` in place of `talk.mp4`. What changes:
## Report format
-Reply in the language the user wrote their request in — a Japanese request gets a Japanese report, English gets English, Chinese gets Chinese, and so on for any other language. Keep the shape below and the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English (they read like log fields, not prose, and stay recognisable across languages); the sentences around them, any question asked, and any explanation of a judgement call are in the user's language. Never default to English because the tool names and flags happen to be English. A mid-conversation language switch follows the user's latest message, not the first one. This holds for a one-command job too: a three-second audio trim answered with English labels, numbers and one Japanese word in `Notes:` is an English report; the `Done:` line's own description (what was cut, from where) and `Steps:` are written in the user's language even when the values are technical.
+Reply in the language the request itself is written in: the language of the user's own sentences, not a language the request talks about (an English request for Spanish subtitles gets an English report) and not the language of a tool's error text or of the file names. Keep the shape below and the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English (they read like log fields, not prose, and stay recognisable across languages); the sentences around them, any question asked, and any explanation of a judgement call are in the user's language. Never default to English because the tool names and flags happen to be English, and never drift into another language because the job is short or the report is a failure: a one-line "file does not exist" is written in the request's language too. A mid-conversation language switch follows the user's latest message, not the first one. This holds for a one-command job too: a three-second audio trim answered with English labels, numbers and one Japanese word in `Notes:` is an English report; the `Done:` line's own description (what was cut, from where) and `Steps:` are written in the user's language even when the values are technical.
Finish every job with this shape (numbers from `probe.py`/`check.py`, not memory):
@@ -263,7 +263,7 @@ Look: not needed (nothing written)
Notes: send a valid .cube, or say if you want the clip left as is
```
-A refusal (the request asks for a judgement this skill does not make, or for something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run (usually only probe), `Look: not needed`. Both keep the five labels so a reader can scan a failed report the way they scan a successful one. When a tool's failure JSON carries `error.hint`, quote it in `Notes:` — it is the flag change that would make the retry meaningful.
+A refusal (the request asks for a judgement this skill does not make, or for something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run (usually only probe), `Look: not needed`. Both keep the five labels so a reader can scan a failed report the way they scan a successful one. That includes the shortest failure: a missing input or an invalid LUT still gets `Failed:`, `Steps:`, `Check:`, `Look:` and `Notes:` lines, never prose headings in their place. When a tool's failure JSON carries `error.hint`, quote it in `Notes:` — it is the flag change that would make the retry meaningful.
Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification | interrupted, "message": ...}}` with `--json` and exits non-zero; quote the message, do not paraphrase it into a success.
diff --git a/references/scripts.md b/references/scripts.md
index 8e677ca..1cd24a5 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -640,7 +640,7 @@ integrated loudness ended more than 1 LU from the target because of it.
### export.py — delivery presets
```
-export.py INPUT --preset youtube|youtube4k|reels|x|prores|h265|gif [--fit pad|crop] [--no-scale] [--allow-long] [--crf N] [-o OUT]
+export.py INPUT --preset youtube|youtube4k|reels|x|prores|h265|gif [--fit pad|crop] [--no-scale] [--allow-long] [--crf N] [--normalize] [-o OUT]
export.py --list
```
Scales into the preset frame (pad by default), tags BT.709, sets `+faststart`,
@@ -648,7 +648,9 @@ trims to platform maximums (Reels 90 s, X 140 s) unless `--allow-long`. It
does not touch levels: for youtube / youtube4k / reels / x the written file is
measured and the result's `loudness` (and a `notes` line) says when it is
outside the platform's LUFS / true-peak spec, naming the `loudness.py` call
-that fixes it -- plan that pass instead of discovering it from `check.py`.
+that fixes it -- or pass `--normalize`, which runs that call on the written
+file itself (audio re-encoded, video copied; `loudness.normalized: true`) so a
+platform export is one command instead of export, loudness, export again.
### proxy.py — low-bitrate proxy for analysis/preview
```
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 304634c..0e40890 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -400,7 +400,7 @@ def output_schema(name: str, meta: Dict[str, Any]) -> Dict[str, Any]:
elif name == "report":
extra = {"report": {"type": "string"}, "check": {"type": ["object", "null"]}}
elif name == "export":
- extra = {"loudness": {"type": "object", "description": "platform presets with audio: the written file's lufs/tp against the platform's target_lufs/target_tp, ok true when inside the spec"},
+ extra = {"loudness": {"type": "object", "description": "platform presets with audio: the written file's lufs/tp against the platform's target_lufs/target_tp, ok true when inside the spec; normalized true when --normalize ran loudness.py on the file"},
"notes": {"type": "array", "items": {"type": "string"}}}
elif name == "loudness":
extra = {"measured": {"type": "object", "description": "--measure-only prints the loudnorm measurement instead (input_i, input_tp, input_lra, input_thresh, target_offset)"}}
diff --git a/scripts/export.py b/scripts/export.py
index 17a8d40..06a19f0 100755
--- a/scripts/export.py
+++ b/scripts/export.py
@@ -17,16 +17,19 @@ Presets:
Examples:
python3 export.py final.mp4 --preset youtube
python3 export.py final.mp4 --preset reels --fit crop
+ python3 export.py final.mp4 --preset reels --normalize # meet the platform's loudness in the same call
python3 export.py final.mp4 --preset prores -o master.mov
python3 export.py final.mp4 --preset copy -o delivered.mp4
python3 export.py --list
"""
import argparse
+import json
+import os
import sys
from pathlib import Path
from typing import Dict, List
-from _common import STATE, add_common, apply_common, bt709_tag_args, emit, cfr_args, default_output, die, ffmpeg_base, info, probe, run, validate_color, pad_filters, add_pad_fill_args, fmt_secs
+from _common import STATE, add_common, apply_common, bt709_tag_args, child_args, emit, cfr_args, default_output, die, ffmpeg_base, info, probe, run, run_tool, validate_color, pad_filters, add_pad_fill_args, fmt_secs
from check import SPECS as PLATFORMS, measure_loudness
PRESETS: Dict[str, Dict] = {
"youtube": {"w": 1920, "h": 1080, "ext": "mp4", "video": ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-profile:v", "high", "-pix_fmt", "yuv420p"], "audio": ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"], "max": None, "desc": "1080p H.264, AAC 192k"},
@@ -42,6 +45,7 @@ PRESETS: Dict[str, Dict] = {
# which check.py platform a preset targets (its loudness spec is measured after the write)
+HERE = Path(__file__).resolve().parent
PLATFORM_OF = {"youtube": "youtube", "youtube4k": "youtube", "reels": "reels", "x": "x"}
@@ -56,6 +60,7 @@ def main() -> int:
ap.add_argument("--no-scale", action="store_true", help="keep source resolution even for platform presets")
ap.add_argument("--allow-long", action="store_true", help="do not trim to the platform's max duration")
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)
args = ap.parse_args()
@@ -140,9 +145,34 @@ def main() -> int:
ok = abs(m["lufs"] - spec["lufs"]) <= spec["lufs_tol"] and m["tp"] <= spec["tp"]
extra["loudness"] = {"lufs": m["lufs"], "tp": m["tp"], "target_lufs": spec["lufs"], "target_tp": spec["tp"], "ok": ok}
extra["verification"] = [{"step": "loudness", "ok": ok, "platform": platform}]
- if not ok:
+ if not ok and args.normalize:
+ # Eval 7: every platform job ran export -> loudness.py -> export again (two video
+ # 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())
+ try:
+ child = json.loads(proc.stdout)
+ except ValueError:
+ child = {}
+ if proc.returncode != 0 or child.get("status") != "completed":
+ err = child.get("error") or {}
+ if os.path.exists(tmp):
+ os.remove(tmp)
+ die(f"--normalize: loudness.py failed: {err.get('message') or proc.stderr.strip()[-300:]}",
+ kind=err.get("kind") or "ffmpeg", output=output, hint=err.get("hint"))
+ os.replace(tmp, output)
+ m = measure_loudness(output) or m
+ ok = abs(m["lufs"] - spec["lufs"]) <= spec["lufs_tol"] and m["tp"] <= spec["tp"]
+ extra["loudness"] = {"lufs": m["lufs"], "tp": m["tp"], "target_lufs": spec["lufs"], "target_tp": spec["tp"], "ok": ok, "normalized": True}
+ extra["verification"] = [{"step": "loudness", "ok": ok, "platform": platform}]
+ if not ok:
+ notes.append(f"loudness is still {m['lufs']:.1f} LUFS / {m['tp']:+.1f} dBTP after loudness.py (target {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP): {child.get('result', {}).get('note') or 'the encoder overshoots the ceiling'}")
+ info("warning: " + notes[-1])
+ elif not ok:
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 before export)")
+ f"run loudness.py -I {spec['lufs']:g} --tp {spec['tp']:g} on this file, or export with --normalize")
info("warning: " + notes[-1])
if notes:
extra["notes"] = notes
diff --git a/scripts/render.py b/scripts/render.py
index cc2fd20..c814915 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -56,6 +56,7 @@ import sys
from pathlib import Path
from typing import Any, Dict, List
+from export import PRESETS
from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool, place_output, refuse_output_is_input, fingerprint, PLAN_VERSION
HERE = Path(__file__).resolve().parent
@@ -178,6 +179,25 @@ def execute_plan(plan: Dict[str, Any], path: str) -> int:
return 0
+def frame_from_preset(frame: Dict[str, Any], export: Dict[str, Any]) -> None:
+ """Fill frame.width/height from the export preset when the project gave only an aspect.
+ Eval 7 (j08 twice, e01 by hand): "frame": {"aspect": "9:16"} with a reels export fitted a
+ 1280x720 source to 406x720, captions were burned at that size, and export.py upscaled them
+ soft. A preset that names a delivery frame of the same aspect is that frame."""
+ if not frame.get("aspect") or frame.get("width") or frame.get("height"):
+ return
+ preset = PRESETS.get(str(export.get("preset") or ""), {})
+ if not (preset.get("w") and preset.get("h")):
+ return
+ m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*[:/]\s*(\d+(?:\.\d+)?)\s*", str(frame["aspect"]))
+ if not m or float(m.group(2)) == 0:
+ return
+ if abs(float(m.group(1)) / float(m.group(2)) - preset["w"] / preset["h"]) > 0.01:
+ return
+ frame["width"], frame["height"] = preset["w"], preset["h"]
+ info(f"frame: {preset['w']}x{preset['h']} from the {export['preset']} export preset (captions and overlays are sized for delivery)")
+
+
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("project", nargs="?", help="project.json, or a plan.json written by <tool> --plan")
@@ -236,8 +256,9 @@ def main() -> int:
import atexit
import shutil
atexit.register(lambda: shutil.rmtree(work, ignore_errors=True))
- frame = proj.get("frame") or {}
+ frame = dict(proj.get("frame") or {})
trans = proj.get("transition") or {}
+ frame_from_preset(frame, proj.get("export") or {})
brand_args: List[str] = ["--brand", rel(proj["brand"])] if proj.get("brand") else []
stages_done: List[str] = []
diff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.json
index 758510e..f2e6d8a 100644
--- a/tests/fixtures/mcp_tools.json
+++ b/tests/fixtures/mcp_tools.json
@@ -356,6 +356,7 @@
"json",
"list",
"no_scale",
+ "normalize",
"output",
"overwrite",
"pad_blur",
diff --git a/tests/test_all.py b/tests/test_all.py
index 3253e7f..dc51077 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -2488,6 +2488,53 @@ class FFmpegSkillTests(unittest.TestCase):
m = probe(str(OUT / "render_height.mp4"))
self.assertEqual(m["video"]["height"], 480)
+ def test_render_frame_aspect_takes_the_export_presets_size(self):
+ """Eval 7 (j08 twice, e01 by hand): "frame": {"aspect": "9:16"} with a reels export fitted
+ a 1280x720 source to 406x720, captions were burned there and export.py upscaled them
+ soft. When the export preset names a delivery frame of the same aspect, the fit stage
+ uses it; a preset of another shape (or an explicit width/height) is left alone."""
+ proj = OUT / "project_aspect.json"
+ work = OUT / "render_aspect_work"
+ proj.write_text(json.dumps({
+ "output": "render_aspect.mp4",
+ "clips": [{"src": "source.mp4", "in": "0:01", "out": "0:03"}],
+ "frame": {"aspect": "9:16"},
+ "export": {"preset": "reels"},
+ }), encoding="utf-8")
+ script("render.py", proj, "--fast", "--json", "--work", work, "--keep")
+ m = probe(str(work / "fit.mp4"))
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (1080, 1920))
+ sys.path.insert(0, str(SCRIPTS))
+ try:
+ import render
+ finally:
+ sys.path.pop(0)
+ frame = {"aspect": "1:1"}
+ render.frame_from_preset(frame, {"preset": "reels"})
+ self.assertEqual(frame, {"aspect": "1:1"})
+ frame = {"aspect": "9:16", "width": 540}
+ render.frame_from_preset(frame, {"preset": "reels"})
+ self.assertEqual(frame, {"aspect": "9:16", "width": 540})
+
+ def test_export_normalize_meets_the_platform_loudness_in_one_call(self):
+ """Eval 7: every platform job ran export -> loudness.py -> export again. --normalize runs
+ the levels pass on the written file (audio only) so one export delivers the spec."""
+ out = OUT / "export_normalize.mp4"
+ proc = script("export.py", OUT / "source.mp4", "--preset", "x", "--normalize", "-o", out, "--fast", "--json", "--overwrite")
+ d = json.loads(proc.stdout)
+ self.assertEqual(d["status"], "completed")
+ self.assertTrue(d["loudness"]["ok"], d["loudness"])
+ self.assertTrue(d["loudness"]["normalized"])
+ self.assertTrue(d["verified"])
+ self.assertAlmostEqual(d["loudness"]["lufs"], -14.0, delta=1.0)
+ self.assertFalse((OUT / "export_normalize_loudnorm.mp4").exists())
+ # 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)
+ self.assertFalse(d["loudness"]["ok"])
+ self.assertNotIn("normalized", d["loudness"])
+ self.assertIn("--normalize", " ".join(d["notes"]))
+
def test_render_exits_nonzero_when_the_check_stage_fails(self):
"""A render whose deliverable fails its own check stage must not report success."""
proj = OUT / "project_bad_check.json"