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: render.py refuses unknown project keys, ctx= reaches write_plan and the exit hook, --crf mark on every tool with --quality, time refusals say not a time (#211)

claude[bot]7834cdf0828d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 102cc51..6cacc94 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,16 @@
## Unreleased
-(nothing yet)
+### Fixed
+
+- `render.py` now refuses an unrecognised key in a project — top level or in any stage/clip object — naming the object, the key and the nearest valid key, instead of silently ignoring it (a clip `start`/`end` typo rendered the clip untrimmed; a stage typo dropped the stage, both reported as success).
+- `write_plan()` and the at-exit plan hook use the `Context` `emit()`/`die()` were given: `emit(ctx=…)` no longer writes an empty plan, and `die(ctx=…)` no longer leaves a plan behind for a failed run.
+- The nine tools that declared `--crf` without a help string now show the `(deprecated: use --quality)` mark in `--help` (and in their MCP `crf` description).
+- The `--crf` deprecation warning fires for the abbreviations argparse accepts (`--cr`, `--c`) as well, and `batch.py` no longer swallows a recipe step's warning; `export.py` stays exempt.
+- A non-numeric time says `'zz': not a time` instead of leaking the interpreter's `could not convert string to float`.
+- docs/contract.md: `tools/list` under `FFMPEG_SKILL_MCP_LEAN` is stable in tool and argument names and `required` lists — what the frozen snapshot pins — not byte-identical (descriptions may change).
+- SKILL.md: the time-grammar sentence is scoped to the timestamp flags (`--start`/`--end`/`--at`/`--from`/`--duration`/`--offset` and cue/chapter files); `doctor`'s tool list is `doctor --json`'s `tools`.
+- references/scripts.md notes the `--crf` deprecation and `FFMPEG_SKILL_NO_OVERWRITE`; README marks `proxy.py --crf` as the deprecated alias.
## 1.10.0
diff --git a/README.md b/README.md
index 1aa6b81..c68c8bd 100644
--- a/README.md
+++ b/README.md
@@ -214,7 +214,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
| Tool | What it does |
|---|---|
| `export.py` | Presets `youtube`, `youtube4k`, `reels`, `x`, `prores`, `h265`, `gif`, all tagged BT.709; `--normalize` meets the platform's loudness in the same call (`render.py` turns it on by default for platform presets) |
-| `proxy.py` | Small, low-bitrate proxy for downstream AI analysis/preview/editing decisions — resize by `--width`/`--scale`, proxy-grade `--crf`, `--fps`, `--no-audio`; not a delivery preset |
+| `proxy.py` | Small, low-bitrate proxy for downstream AI analysis/preview/editing decisions — resize by `--width`/`--scale`, proxy-grade `--crf` (deprecated alias of `--quality`), `--fps`, `--no-audio`; not a delivery preset |
| `check.py` | PASS / WARN / FAIL against YouTube, Shorts, Reels, TikTok, X, LinkedIn, broadcast and podcast specs, with the fix for each failure and a `format` / `judgement` kind per row |
| `report.py` | Single-file HTML delivery report: before/after sheets, media facts, loudness, compliance, the commands run |
diff --git a/SKILL.md b/SKILL.md
index 1f0eda5..c579ffe 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -130,9 +130,9 @@ If a request needs an FFmpeg feature none of the 42 scripts expose, say so and n
## Request → script
-This table and `doctor`'s tool list are the source of truth for what exists: name only a script you have seen in one of them, never a plausible-sounding one (there is no `doctor.py`, no `trim.py`, no `subtitle.py`).
+This table and `doctor --json`'s `tools` list are the source of truth for what exists: name only a script you have seen in one of them, never a plausible-sounding one (there is no `doctor.py`, no `trim.py`, no `subtitle.py`).
-Times take seconds, `mm:ss(.fff)`, `hh:mm:ss(.fff)` or four-part SMPTE `hh:mm:ss:ff` everywhere, with `@fps` naming the rate (`00:01:02:[email protected]`): use the timecode forms when the user pastes an editor's timecode list or an NLE cue sheet, so nothing is converted by hand on the way in.
+Timestamp flags -- `--start`, `--end`, `--at`, `--from`, `--duration`, `--offset`, and the times in cue and chapter files -- take seconds, `mm:ss(.fff)`, `hh:mm:ss(.fff)` or four-part SMPTE `hh:mm:ss:ff`, with `@fps` naming the rate (`00:01:02:[email protected]`); tolerance-style flags that are a length rather than a point in time (`--min-silence`, `--margin`, `--min-keep`, `--fade`) are plain seconds. Use the timecode forms when the user pastes an editor's timecode list or an NLE cue sheet, so nothing is converted by hand on the way in.
| User says | Do |
|-----------|----|
diff --git a/docs/contract.md b/docs/contract.md
index f73f389..ed6ba44 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -426,8 +426,9 @@ identical to the translation of `contract --json`), which the tests check.
them required). They are transport flags `mcp/server.py` sets itself -- it appends `--json` for
every tool but `look` and `probe` -- rather than arguments a caller chooses, and 2.0 drops them
for good (see "What 2.0 changes"). The flag is opt-in and changes nothing else: without it
-`tools/list` is byte-identical to what it has always been, which is what the frozen 1.x snapshot
-pins, so a lean client and a default client see the same tools with the same names.
+`tools/list` carries the tool names, argument names and `required` lists the frozen 1.x snapshot
+pins -- descriptions may change between releases (the `--crf` deprecation mark did) -- so a lean
+client and a default client see the same tools with the same names.
## Consuming the contract from an agent
diff --git a/references/scripts.md b/references/scripts.md
index b0bf3e9..be94ad8 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 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`).
+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). `--crf` is deprecated since 1.10.0 (it warns on stderr and is removed in 2.0): use `--quality`, except on `export.py`, whose `--crf` is not an alias and stays. With `FFMPEG_SKILL_NO_OVERWRITE=1` in the environment, any tool refuses (`kind: input`) to replace an existing output unless `--overwrite` is given. `--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`).
## Time grammar (every time-taking flag, 1.9)
@@ -406,7 +406,9 @@ and the project has no `loudness` stage; `"normalize": false` opts out.
Stages: clips (cut, optional speed) → join (transition) → silence → fit →
captions → graphics → overlays → audio → loudness → export → check. Keys mirror the
-CLI flags of each script (see the docstring). Use it whenever an edit has
+CLI flags of each script (see the docstring); a key `render.py` does not read -- at
+the top level or in any stage/clip object -- is refused (`kind: input`) naming the
+key and the nearest valid one, never silently ignored. Use it whenever an edit has
more than two steps or the user is likely to ask for changes: edit the JSON,
re-render, and the result is reproducible. `--dry-run --json` prints the
complete command plan for review.
diff --git a/scripts/_common.py b/scripts/_common.py
index c525d1b..3eb20b5 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -177,7 +177,9 @@ def die(msg: str, code: int = 1, kind: str = "input", *, ctx: "Optional[Context]
read a failed delivery as a success."""
hint = extra.pop("hint", None)
ctx = ctx or STATE # 1.10: the optional per-request Context (2.0 makes it required); STATE is the default instance
+ _set_current_ctx(ctx) # the atexit hook has no argument: it reads the ctx emit()/die() last used
ctx.plan = None # a failed run plans nothing (the exit hook must not write a plan for it)
+ STATE.plan = None # the hook falls back to STATE when nothing passed a ctx; a failed run plans nothing there either
sys.stderr.write(f"error: {msg}\n" + (f"hint: {hint}\n" if hint else ""))
if ctx.json:
doc: Dict[str, Any] = {
@@ -259,6 +261,15 @@ class Context:
STATE = Context()
+# The atexit plan hook takes no arguments, so emit()/die() record the Context they were given
+# here; nothing passed a ctx = it stays None and the hook falls back to STATE, as before (1.10).
+_CURRENT_CTX: "Optional[Context]" = None
+
+
+def _set_current_ctx(ctx: "Context") -> None:
+ global _CURRENT_CTX
+ _CURRENT_CTX = ctx
+
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
@@ -280,8 +291,17 @@ def add_common(ap: "argparse.ArgumentParser", codec: bool = True) -> None:
# `deprecated` list in `contract --json` and docs/contract.md "What 2.0 changes"). Marked
# here, once, rather than in each re-encoding tool's own parser.
crf = ap._option_string_actions["--crf"]
- if crf.help and "deprecated" not in crf.help:
- crf.help += " (deprecated: use --quality)"
+ # The flag's own default moves aside so apply_common() can tell an explicit --crf (in any
+ # spelling argparse accepts, including the --cr / --c abbreviations) from the default;
+ # apply_common() puts _CRF_DEFAULT back when the flag was absent.
+ global _CRF_DEFAULT
+ _CRF_DEFAULT = crf.default
+ crf.deprecated_default = crf.default # the schema still advertises it (_contract._json_type)
+ crf.default = None
+ if "deprecated" not in (crf.help or ""):
+ # the nine tools that declare --crf with no help string used to fall through this and
+ # never show the mark at all (review 9)
+ crf.help = (crf.help or "x264 CRF when re-encoding (default 18)") + " (deprecated: use --quality)"
# 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,
@@ -290,13 +310,18 @@ def add_common(ap: "argparse.ArgumentParser", codec: bool = True) -> None:
help="encoder quality on the CRF scale (lower = better; 18 visually lossless for x264/x265, up to 63 for av1); overrides --crf, ignored by prores")
-def _passed_explicitly(flag: str) -> bool:
- """True when this process was given `flag` on the command line (`--flag` or `--flag=V`),
- as opposed to argparse filling in its default. Used for the deprecation warnings."""
- return any(a == flag or a.startswith(flag + "=") for a in sys.argv[1:])
+# The declared default of a deprecated --crf, parked by add_common() (one parser per process).
+_CRF_DEFAULT: Optional[int] = None
def apply_common(args: "argparse.Namespace") -> None:
+ # Was --crf typed? add_common() parked the flag's default (None in its place) on every tool
+ # whose --crf is deprecated, i.e. the ones that also have --quality; export.py's --crf is not
+ # an alias and keeps its own default. Scanning sys.argv for "--crf" instead missed the unique
+ # prefixes argparse accepts (--cr, --c) and never ran for batch.py's recipe steps (review 9).
+ crf_explicit = hasattr(args, "quality") and getattr(args, "crf", None) is not None
+ if hasattr(args, "quality") and hasattr(args, "crf") and args.crf is None:
+ args.crf = _CRF_DEFAULT
STATE.plan = getattr(args, "plan", None) or None
STATE.dry_run = bool(getattr(args, "dry_run", False)) or bool(STATE.plan)
if STATE.plan:
@@ -330,12 +355,10 @@ def apply_common(args: "argparse.Namespace") -> None:
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)
- # The warning the deprecation policy asks for, only when the user typed the flag: argparse's
- # own default for --crf is 18 on every re-encoding tool, so `args.crf is not None` cannot tell
- # an explicit --crf from the default (sys.argv can).
- # export.py has no --quality (its preset chooses the encoder), so its --crf is not an alias and
- # is not deprecated: warn only where --quality exists.
- if crf is not None and hasattr(args, "quality") and _passed_explicitly("--crf"):
+ # The warning the deprecation policy asks for, only when the caller typed the flag (see
+ # crf_explicit above). export.py has no --quality (its preset chooses the encoder), so its
+ # --crf is not an alias and is not deprecated: warn only where --quality exists.
+ if crf is not None and crf_explicit:
info("warning: --crf is deprecated since 1.10.0; use --quality N (the same CRF scale, codec-neutral). --crf is removed in 2.0.")
top = 63 if STATE.codec == "av1" else 51
if crf is not None and not 0 <= int(crf) <= top:
@@ -408,6 +431,7 @@ def emit(output: Optional[str], *, ctx: "Optional[Context]" = None, **extra: Any
`ctx` is the optional per-request Context added in 1.10 (2.0 makes it required, issue #189 B);
omitted, every read falls back to the process-global STATE as before."""
ctx = ctx or STATE
+ _set_current_ctx(ctx) # so the atexit hook writes (or skips) this ctx's plan, not STATE's
meta: Dict[str, Any] = {}
if output and not ctx.dry_run:
meta = verify_output(output) # dies (status: failed, kind: output) if the artifact is unusable
@@ -430,10 +454,10 @@ def emit(output: Optional[str], *, ctx: "Optional[Context]" = None, **extra: Any
if os.environ.get("FFMPEG_SKILL_RESULT_V2", "") not in ("", "0"):
doc["result_v2"] = _result_v2(output, meta, dict(extra, verified=doc["verified"], verification=steps))
if ctx.plan:
- doc["plan"] = write_plan(ctx.plan, output, extra)
+ doc["plan"] = write_plan(ctx.plan, output, extra, ctx=ctx)
print_json(doc)
elif ctx.plan:
- print(write_plan(ctx.plan, output, extra))
+ print(write_plan(ctx.plan, output, extra, ctx=ctx))
elif output:
print(output)
@@ -443,9 +467,10 @@ _PLAN_STRIP = ("--plan", "--dry-run", "--json")
def _plan_at_exit() -> None:
- if STATE.plan and not STATE.plan_written:
+ ctx = _CURRENT_CTX or STATE
+ if ctx.plan and not ctx.plan_written:
try:
- write_plan(STATE.plan, None, {})
+ write_plan(ctx.plan, None, {}, ctx=ctx)
except SystemExit:
pass
@@ -468,13 +493,13 @@ def fingerprint(path: str) -> Dict[str, Any]:
return {"path": os.path.abspath(path), "size": st.st_size, "sha256_head_tail": h.hexdigest()}
-def _plan_inputs(commands: Sequence[str], argv: Sequence[str] = ()) -> List[str]:
+def _plan_inputs(commands: Sequence[str], argv: Sequence[str] = (), ctx: "Optional[Context]" = None) -> List[str]:
"""Every existing file the plan depends on: the `-i` inputs of the planned commands, any
existing file named in argv (a recipe, a project, an SRT, a LUT, a still), and the side
inputs tools register through escape_filter_path() (review 6: only `-i` files were bound)."""
import shlex
seen: List[str] = []
- for a in list(argv) + list(STATE.plan_inputs):
+ for a in list(argv) + list((ctx or STATE).plan_inputs):
if a and not a.startswith("-") and os.path.isfile(a) and a not in seen:
seen.append(a)
for line in commands:
@@ -488,10 +513,14 @@ def _plan_inputs(commands: Sequence[str], argv: Sequence[str] = ()) -> List[str]
return seen
-def write_plan(path: str, output: Optional[str], extra: Dict[str, Any]) -> str:
+def write_plan(path: str, output: Optional[str], extra: Dict[str, Any], ctx: "Optional[Context]" = None) -> str:
"""The dry run as an artifact: what will run, on which exact inputs, producing what, checked
- how. `render.py PLAN` executes it after re-fingerprinting the inputs (issue #189 C)."""
+ how. `render.py PLAN` executes it after re-fingerprinting the inputs (issue #189 C).
+
+ `ctx` is the Context whose commands and inputs the plan describes (emit()/die() pass the one
+ they were given); omitted, it is the process-global STATE as before."""
import datetime
+ ctx = ctx or STATE
argv = [a for a in sys.argv[1:]]
cleaned: List[str] = []
skip = False
@@ -520,8 +549,8 @@ def write_plan(path: str, output: Optional[str], extra: Dict[str, Any]) -> str:
"tool": tool,
"argv": cleaned,
"cwd": os.getcwd(),
- "inputs": [fingerprint(p) for p in _plan_inputs(STATE.commands, cleaned)],
- "commands": list(STATE.commands),
+ "inputs": [fingerprint(p) for p in _plan_inputs(ctx.commands, cleaned, ctx)],
+ "commands": list(ctx.commands),
"output": os.path.abspath(output) if output else None,
"verify": verify,
"notes": list(extra.get("notes") or []),
@@ -534,8 +563,8 @@ def write_plan(path: str, output: Optional[str], extra: Dict[str, Any]) -> str:
os.replace(tmp, path)
except OSError as exc:
die(f"cannot write plan {path}: {exc}", kind="output")
- STATE.plan_written = True
- info(f"plan written: {path} ({len(doc['commands'])} command(s), {len(doc['inputs'])} input(s)); run it with render.py {path}")
+ ctx.plan_written = True
+ info(f"plan written: {path} ({len(doc['commands'])} command(s), {len(doc['inputs'])} input(s)); run it with render.py {path}", ctx)
return path
@@ -1497,7 +1526,11 @@ def parse_time(value: str, fps: Optional[float] = None) -> float:
raise ValueError(f"bad time: {value}")
total = 0.0
for part in parts:
- total = total * 60 + float(part)
+ try:
+ total = total * 60 + float(part)
+ except ValueError:
+ # not the interpreter's "could not convert string to float: 'zz'" (review 9)
+ raise ValueError(f"'{value}': not a time")
return total
diff --git a/scripts/_contract.py b/scripts/_contract.py
index c81b6d6..2f69f7b 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -342,12 +342,15 @@ def input_schema(parser: argparse.ArgumentParser) -> Dict[str, Any]:
if isinstance(action, argparse._HelpAction):
continue
prop: Dict[str, Any] = _json_type(action)
+ # add_common() parks a deprecated --crf's default aside (so an explicit flag is
+ # distinguishable from the default); the schema still advertises the real one
+ default = getattr(action, "deprecated_default", action.default)
if action.help and action.help != argparse.SUPPRESS:
- prop["description"] = action.help % {"default": action.default} if "%(default)" in action.help else action.help
+ prop["description"] = action.help % {"default": default} if "%(default)" in action.help else action.help
if action.choices:
prop["enum"] = list(action.choices)
- if action.default not in (None, False, argparse.SUPPRESS):
- prop["default"] = action.default
+ if default not in (None, False, argparse.SUPPRESS):
+ prop["default"] = default
if action.option_strings:
prop["cli"] = list(action.option_strings)
if action.required:
diff --git a/scripts/batch.py b/scripts/batch.py
index 2233d9e..41b6646 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -83,6 +83,9 @@ def run_step(argv: List[str]) -> bool:
if proc.returncode != 0:
info(" " + "\n ".join(proc.stderr.strip().splitlines()[-4:]))
return False
+ for line in proc.stderr.splitlines():
+ if line.startswith("warning:"): # a step's deprecation notice is not swallowed by a success (review 9)
+ info(" " + line)
return True
diff --git a/scripts/render.py b/scripts/render.py
index dd36283..45de4a9 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -49,6 +49,7 @@ Examples:
python3 render.py project.json --fast # preview quality
"""
import argparse
+import difflib
import re
import json
import os
@@ -79,6 +80,58 @@ TEMPLATE = {
}
+# Every key render.py reads, per object. Anything else is a refusal rather than a silent no-op:
+# a clip "start"/"end" (the spelling titles, graphics and overlays use) rendered the whole clip
+# untrimmed, and a mistyped stage name dropped the stage -- both reported as a success (review 9).
+OBJECT_KEYS: Dict[str, frozenset] = {
+ "project": frozenset({"output", "frame", "clips", "transition", "silence", "brand", "captions",
+ "graphics", "overlays", "audio", "loudness", "fit", "export", "check"}),
+ "clips[]": frozenset({"src", "in", "out", "speed"}),
+ "frame": frozenset({"aspect", "width", "height", "fps"}),
+ "transition": frozenset({"type", "duration"}),
+ "silence": frozenset({"threshold", "min_silence", "margin"}),
+ "captions": frozenset({"text", "srt", "ass", "font", "size", "color", "position", "margin",
+ "animate", "highlight_color", "outline", "karaoke", "bold", "box"}),
+ "graphics[]": frozenset({"template", "name", "title", "subtitle", "start", "end", "position",
+ "from", "scale", "primary", "text_color"}),
+ "overlays[]": frozenset({"logo", "image", "text", "position", "start", "end", "fade", "opacity",
+ "scale", "font_size", "font", "font_file", "margin", "box"}),
+ "audio": frozenset({"music", "replace", "music_volume", "fade_in", "fade_out", "music_fade_out",
+ "gain", "duck_amount", "voice", "denoise", "duck", "music_loop", "stereo",
+ "mono", "downmix"}),
+ "loudness": frozenset({"lufs", "tp"}),
+ "fit": frozenset({"duration", "method", "aspect", "fit", "width", "height", "fps", "smooth"}),
+ "export": frozenset({"preset", "fit", "crf", "normalize"}),
+ "check": frozenset({"platform"}),
+}
+# Typos difflib cannot see: a clip is trimmed with in/out, not the start/end that time a title.
+NEAR_KEYS: Dict[str, Dict[str, str]] = {"clips[]": {"start": "in", "end": "out", "from": "in", "to": "out"}}
+
+
+def check_keys(obj: Any, schema: str, label: str) -> None:
+ """Refuse an unrecognised key, naming the object, the key and the nearest valid one."""
+ if not isinstance(obj, dict):
+ return
+ valid = OBJECT_KEYS[schema]
+ for key in obj:
+ if key in valid:
+ continue
+ near = NEAR_KEYS.get(schema, {}).get(str(key)) or next(iter(difflib.get_close_matches(str(key), sorted(valid), n=1, cutoff=0.6)), None)
+ die(f"{label}: unknown key {key!r}" + (f" (did you mean {near!r}?)" if near
+ else f" (valid keys: {', '.join(sorted(valid))})"))
+
+
+def validate_project(proj: Dict[str, Any]) -> None:
+ check_keys(proj, "project", "project")
+ for name in ("frame", "transition", "silence", "captions", "audio", "loudness", "fit", "export", "check"):
+ check_keys(proj.get(name), name, name)
+ for name in ("clips", "graphics", "overlays"):
+ items = proj.get(name)
+ if isinstance(items, list):
+ for i, item in enumerate(items):
+ check_keys(item, f"{name}[]", f"{name}[{i}]")
+
+
def sh(script: str, *argv: Any, extra: List[str] = None) -> str:
"""Run a sibling script, forwarding --fast / --dry-run, returning its printed output path."""
cmd = [str(HERE / script)] + [str(a) for a in argv] + (extra or []) + child_args() + ["--json"]
@@ -226,6 +279,7 @@ def main() -> int:
die(f"{args.project}: not a project or plan object (top level is {type(proj).__name__})")
if "plan_version" in proj:
return execute_plan(proj, os.path.abspath(args.project))
+ validate_project(proj)
base = Path(args.project).resolve().parent
def rel(p: Any) -> str:
diff --git a/tests/test_all.py b/tests/test_all.py
index 7ddf387..ab6e71f 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -2643,6 +2643,62 @@ class FFmpegSkillTests(unittest.TestCase):
p.write_text(json.dumps(dict({"output": name.replace(".json", ".mp4")}, **body)), encoding="utf-8")
return p
+ def test_render_refuses_an_unknown_project_key_naming_the_nearest_valid_one(self):
+ """Review 9: a project was read with dict.get only, so a mistyped key was silently
+ ignored -- a clip "start"/"end" (the spelling graphics and overlays use for their own
+ times) rendered the whole clip untrimmed, and "exports" dropped the export stage, both
+ reported as a successful render. Every key of the project and of each stage/clip object
+ is now checked, and the template still validates."""
+ cases = {
+ "clip_key": ({"clips": [{"src": "source.mp4", "start": 0, "end": 2}], "export": {"preset": "reels"}},
+ "clips[0]: unknown key 'start' (did you mean 'in'?)"),
+ "stage_key": ({"clips": [{"src": "source.mp4", "in": 0, "out": 2}], "exports": {"preset": "reels"}},
+ "project: unknown key 'exports' (did you mean 'export'?)"),
+ "nested_key": ({"clips": [{"src": "source.mp4"}], "export": {"preset": "reels", "quality": 20}},
+ "export: unknown key 'quality'"),
+ }
+ for name, (body, message) in cases.items():
+ proc = script("render.py", self._proj(f"render_key_{name}.json", body), "--dry-run", "--json", expect_fail=True)
+ self.assertIn(message, proc.stderr, f"{name}: {proc.stderr[-400:]}")
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"]), ("failed", "input"))
+ tmpl = OUT / "render_template_valid.json"
+ script("render.py", "--init", tmpl)
+ proc = script("render.py", tmpl, "--dry-run", expect_fail=True) # only REPLACE_ME.mp4 is missing
+ self.assertIn("source not found", proc.stderr)
+ self.assertNotIn("unknown key", proc.stderr)
+
+ def test_emit_and_die_use_the_ctx_they_were_given_for_the_plan(self):
+ """Review 9: run()/emit()/die() took ctx= but write_plan() and the atexit hook still read
+ STATE -- emit(ctx=...) wrote an empty plan while reporting one, and die(ctx=...) let the
+ hook write a plan for a failed run."""
+ code = (
+ "import sys, atexit, json\n"
+ f"sys.path.insert(0, {str(SCRIPTS)!r})\n"
+ "import _common as c\n"
+ "atexit.register(c._plan_at_exit)\n"
+ "mode, src, plan = sys.argv[1], sys.argv[2], sys.argv[3]\n"
+ "ctx = c.Context(); ctx.json = True; ctx.dry_run = True; ctx.plan = plan\n"
+ "c.STATE.plan = plan\n"
+ "c.run(['/usr/bin/ffmpeg', '-i', src, '-t', '1', src + '.out.mp4'], ctx=ctx)\n"
+ "if mode == 'emit':\n"
+ " c.emit(None, ctx=ctx)\n"
+ "else:\n"
+ " c.die('boom', ctx=ctx)\n"
+ )
+ src = str(OUT / "source.mp4")
+ plan = OUT / "ctx_plan.json"
+ sh(sys.executable, "-c", code, "emit", src, plan)
+ doc = json.loads(plan.read_text(encoding="utf-8"))
+ self.assertEqual(len(doc["commands"]), 1, doc)
+ self.assertIn("ffmpeg", doc["commands"][0])
+ plan2 = OUT / "ctx_plan_die.json"
+ if plan2.exists():
+ plan2.unlink()
+ proc = sh(sys.executable, "-c", code, "die", src, plan2, expect_fail=True)
+ self.assertIn("boom", proc.stderr)
+ self.assertFalse(plan2.exists(), "die() left a plan behind for a failed run")
+
def test_render_default_work_dir_is_unique_per_process(self):
"""The default work dir name came only from the output path (e.g. "out_work"), no PID or
timestamp -- two concurrent render.py runs targeting the same output (a batch.py "project"