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: validate --preset/--crf before ffmpeg; silence.py and cut.py say what to change next; failure JSON may carry a hint (#175)

Shogo Kajiyama190c1b39cae3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c31d76..e62942c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,12 @@
## Unreleased
-(nothing yet)
+- `--preset` is an argparse choice of the x264 presets in every encoding tool (the contract and MCP schema carry the enum) and `--crf` is range-checked (0-51) before ffmpeg runs; a typo is a `kind: input` refusal, not an encoder error.
+- `silence.py` says why nothing was found: with zero silences the result carries a `hint` with the track's measured mean/peak level and a threshold to try. `cut.py` names the nearest keyframes (`nearest_keyframes`) when a lossless cut had to re-encode, so the caller can move the cut instead. Failure JSON may carry `error.hint`.
+- `broll.py --pad-color` is validated like every other colour flag (it was spliced into the filter graph unchecked; a value containing `,` could append a filter).
+- The MCP server attaches the tool's own failure document as `structuredContent` on a failed call, so a caller reads `error.kind`/`code` instead of parsing prose.
+- `render.py` re-raises a stage's own failure (kind, exit code, hint, `stage`) instead of reporting every child failure as `kind: input`; `report.py` shows "check could not run" instead of crashing when `check.py` fails to run; `--commands`/`--notes`/`--chapters` files that are missing or not UTF-8 are a `kind: input` refusal, not a traceback.
+- SKILL.md: a failed or refused report keeps the five labels (`Look: not needed (nothing written)`), quotes `error.hint` in `Notes:`, and several open questions are asked as one bundled proposal instead of one per turn.
## 1.4.4
diff --git a/SKILL.md b/SKILL.md
index a8051b2..c49298e 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -95,7 +95,7 @@ Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>
## Before you run anything: what to ask, what to assume
-Ask one short question only when the answer changes the output materially and the request does not imply it:
+Ask one short question only when the answer changes the output materially and the request does not imply it. When several things are open at once (a vague "make it for social media" leaves destination, aspect method, length and captions unresolved), do not ask them one per turn: propose one bundle with your defaults and let the user change any part ("Reels: 9:16 with padding, trimmed to 60 s, -14 LUFS, no captions — OK, or change something?"). One question, one answer, then the run.
- **Destination** decides aspect, length limit, loudness and codec. "For Reels" answers all four. If no destination is named and the edit is a plain cut/caption, keep the source format and say so; if the user asks to "export", "post" or "deliver", ask where.
- **Duration** ("make it 60 s") without a method: speed up for ≤1.5× changes, trim otherwise, and state which you chose. Ask if the content is a talk (trimming loses words) and the change is large.
@@ -262,9 +262,13 @@ When a step fails, replace `Done:` with `Failed:` and keep the rest honest:
```
Failed: color.py --lut grade.cube exited 1 — ffmpeg: "Unable to parse LUT file" (the .cube is not a valid LUT)
Steps: probe -> color (failed); nothing written
+Check: nothing to verify
+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.
+
Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification, "message": ...}}` with `--json` and exits non-zero; quote the message, do not paraphrase it into a success.
## Things that look right but are wrong
diff --git a/docs/contract.md b/docs/contract.md
index 024f3d2..d3c34c7 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -312,7 +312,8 @@ before, and, when `--json` was given, on stdout:
```
`message` carries the script's own reason (missing input, ffprobe failure, the last
-stderr lines of ffmpeg, the verification that failed); `commands` lists what was planned
+stderr lines of ffmpeg, the verification that failed); an optional `error.hint` names the
+flag change that would make a retry meaningful (never a diagnosis of the media); `commands` lists what was planned
or run so the caller can retry or report without re-deriving the command. `code` is a
purely additive, statically-mapped relabelling of `kind` (never a new distinction `kind`
doesn't already make) for a caller that wants a stable enum instead of matching `kind`
diff --git a/mcp/server.py b/mcp/server.py
index d819609..89a9c78 100755
--- a/mcp/server.py
+++ b/mcp/server.py
@@ -102,7 +102,13 @@ def call_tool(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
if proc.returncode != 0:
err = proc.stderr.strip().splitlines()
tail = "\n".join(err[-12:])
- return {"isError": True, "content": [{"type": "text", "text": f"{name} failed (exit {proc.returncode})\n{tail}"}]}
+ failed: Dict[str, Any] = {"isError": True, "content": [{"type": "text", "text": f"{name} failed (exit {proc.returncode})\n{tail}"}]}
+ # The child's own failure document (status, error.kind/code/hint, commands) is the
+ # machine-readable half of the contract; dropping it here left an MCP caller regex-
+ # parsing prose to tell a timeout from a missing binary.
+ if isinstance(structured, dict):
+ failed["structuredContent"] = structured
+ return failed
if structured is None:
text = stdout or "\n".join(proc.stderr.strip().splitlines()[-5:])
result: Dict[str, Any] = {"content": [{"type": "text", "text": text}]}
diff --git a/scripts/_common.py b/scripts/_common.py
index 361c536..64f4f3e 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -159,7 +159,8 @@ def die(msg: str, code: int = 1, kind: str = "input", **extra: Any) -> "None":
reporting that detail while the top-level status says failed. Before 1.4.3 those four printed
`status: "completed"` next to a non-zero exit code, so a caller keying on the status alone
read a failed delivery as a success."""
- sys.stderr.write(f"error: {msg}\n")
+ hint = extra.pop("hint", None)
+ sys.stderr.write(f"error: {msg}\n" + (f"hint: {hint}\n" if hint else ""))
if STATE.json:
doc: Dict[str, Any] = {
"status": "failed", "exit_code": code,
@@ -170,6 +171,8 @@ def die(msg: str, code: int = 1, kind: str = "input", **extra: Any) -> "None":
},
"commands": list(STATE.commands),
}
+ if hint:
+ doc["error"]["hint"] = hint
doc.update(extra)
print_json(doc)
sys.exit(code)
@@ -268,6 +271,9 @@ def apply_common(args: "argparse.Namespace") -> None:
STATE.timeout = max(0.0, float(args.timeout))
if STATE.fast and getattr(args, "preset", None) in X264_PRESETS:
args.preset = "veryfast"
+ crf = getattr(args, "crf", None)
+ if crf is not None and not 0 <= int(crf) <= 51:
+ die(f"--crf must be between 0 and 51 (x264/x265 scale; 18 is visually lossless, 23 the encoder default), got {crf}")
def emit(output: Optional[str], **extra: Any) -> None:
@@ -1078,6 +1084,55 @@ def db_to_linear(db: float) -> float:
return 10 ** (db / 20.0)
+def read_text_or_die(path: str, flag: str) -> str:
+ """Read a caller-supplied UTF-8 text file (a cue list, chapters, notes) or fail as kind input
+ with the flag named, instead of a FileNotFoundError / UnicodeDecodeError traceback."""
+ try:
+ with open(path, "r", encoding="utf-8") as fh:
+ return fh.read()
+ except FileNotFoundError:
+ die(f"{flag}: {path} does not exist")
+ except IsADirectoryError:
+ die(f"{flag}: {path} is a directory, not a text file")
+ except UnicodeDecodeError as e:
+ die(f"{flag}: {path} is not UTF-8 text ({e.reason} at byte {e.start}); save it as UTF-8")
+ except OSError as e:
+ die(f"{flag}: cannot read {path}: {e.strerror}")
+ return "" # unreachable
+
+
+def keyframes_near(path: str, t: float, window: float = 5.0) -> List[float]:
+ """Video keyframe timestamps within +-window seconds of t, ascending. Read with
+ -read_intervals so a long file is not scanned end to end; empty when ffprobe cannot say."""
+ ffprobe = require_tool("ffprobe")
+ lo = max(0.0, t - window)
+ proc = run([ffprobe, "-v", "error", "-select_streams", "v:0", "-skip_frame", "nokey",
+ "-read_intervals", f"{lo:.3f}%{t + window:.3f}", "-show_entries", "frame=pts_time",
+ "-of", "csv=p=0", path], quiet=True, check=False)
+ if proc.returncode != 0:
+ return []
+ out: List[float] = []
+ for line in proc.stdout.splitlines():
+ try:
+ out.append(round(float(line.strip().rstrip(",")), 3))
+ except ValueError:
+ continue
+ return sorted(set(out))
+
+
+def measured_level_dbfs(path: str, seconds: float = 120.0) -> Optional[Dict[str, float]]:
+ """Mean and peak level of the first `seconds` of audio (volumedetect), in dBFS; None if unmeasurable.
+ Cheap enough to run once as a hint when a threshold-based tool found nothing."""
+ ffmpeg = require_tool("ffmpeg")
+ proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-t", f"{seconds:.0f}", "-i", path, "-vn",
+ "-af", "volumedetect", "-f", "null", "-"], check=False)
+ m_mean = re.search(r"mean_volume:\s*(-?[0-9.]+) dB", proc.stderr)
+ m_max = re.search(r"max_volume:\s*(-?[0-9.]+) dB", proc.stderr)
+ if not (m_mean and m_max):
+ return None
+ return {"mean_dbfs": float(m_mean.group(1)), "peak_dbfs": float(m_max.group(1))}
+
+
def analyze_levels(path: str, seconds: float = 20.0) -> Dict[str, Any]:
"""Sample luma/saturation statistics (signalstats) and guess whether the picture is Log-encoded.
diff --git a/scripts/background.py b/scripts/background.py
index a2d4b8d..5632e40 100644
--- a/scripts/background.py
+++ b/scripts/background.py
@@ -14,7 +14,7 @@ import argparse
import math
import sys
-from _common import add_common, apply_common, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args
+from _common import add_common, apply_common, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS
def main() -> int:
@@ -29,7 +29,7 @@ def main() -> int:
src.add_argument("--gradient", help="two colours as C1:C2 for a linear gradient, e.g. 0xff6a00:0x0057ff")
ap.add_argument("--angle", type=float, default=0.0, help="gradient angle in degrees (with --gradient, default 0 = left to right)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/broll.py b/scripts/broll.py
index db374ac..6fb4bfb 100755
--- a/scripts/broll.py
+++ b/scripts/broll.py
@@ -21,7 +21,7 @@ import argparse
import sys
from typing import Any, Dict, List
-from _common import STATE, add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args
+from _common import STATE, add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS
def main() -> int:
@@ -36,10 +36,11 @@ def main() -> int:
ap.add_argument("--audio", choices=["a", "b", "mix"], default="a", help="under a cutaway: A's audio (default), B's audio, or both mixed")
ap.add_argument("--pad-color", default="black", help="pad colour when B's aspect differs from A's (default black)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
+ validate_color(args.pad_color, "--pad-color")
n = len(args.insert)
if len(args.at) != n:
diff --git a/scripts/caption.py b/scripts/caption.py
index f8d57b8..45c64a4 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -36,7 +36,7 @@ import sys
from pathlib import Path
from typing import List, Optional, Tuple
-from _common import STATE, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args
+from _common import STATE, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args, X264_PRESETS
ALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}
@@ -406,7 +406,7 @@ def main() -> int:
anim.add_argument("--write-ass", help="where to save the generated ASS (default: next to the output)")
enc = ap.add_argument_group("encoding")
enc.add_argument("--crf", type=int, default=18)
- enc.add_argument("--preset", default="medium")
+ enc.add_argument("--preset", default="medium", choices=X264_PRESETS)
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/color.py b/scripts/color.py
index 8d6b0b6..33507d9 100755
--- a/scripts/color.py
+++ b/scripts/color.py
@@ -22,7 +22,7 @@ import os
import sys
from typing import List
-from _common import add_common, analyze_levels, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, info, probe, run, run_keeping_subtitles, x264_args
+from _common import add_common, analyze_levels, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, info, probe, run, run_keeping_subtitles, x264_args, X264_PRESETS
TONEMAPS = ["hable", "mobius", "reinhard", "bt2390", "clip", "linear", "gamma"]
@@ -204,7 +204,7 @@ def main() -> int:
"audio (--to-sdr, --lut, --correct, and --retag's re-encode fallback) -- --strip-dovi and "
"a successful --retag stream-copy all streams untouched, so the flag has nothing to select there.")
ap.add_argument("--crf", type=int, default=18)
- ap.add_argument("--preset", default="medium")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS)
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/crop.py b/scripts/crop.py
index 3b40e41..56cdbb9 100644
--- a/scripts/crop.py
+++ b/scripts/crop.py
@@ -21,7 +21,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
def main() -> int:
@@ -33,7 +33,7 @@ def main() -> int:
ap.add_argument("--width", type=int, required=True, help="crop width in px (must be even)")
ap.add_argument("--height", type=int, required=True, help="crop height in px (must be even)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
ap.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
add_common(ap)
args = ap.parse_args()
diff --git a/scripts/cut.py b/scripts/cut.py
index ed2f388..72b0896 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -30,7 +30,11 @@ import sys
import tempfile
from typing import List, Tuple
-from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run
+from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run, X264_PRESETS, keyframes_near
+
+# keyframe timestamps found next to a requested cut that the tolerance turned into a re-encode
+# (reported so the caller can choose a lossless cut at one of them next time)
+NEAREST_KEYFRAMES: list = []
def parse_segments(spec: str) -> List[Tuple[float, float]]:
@@ -116,8 +120,15 @@ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: i
if not reencode and tolerance >= 0 and not STATE["dry_run"]:
got = probe(dst).get("duration") or 0.0
if abs(got - dur) > tolerance:
+ near = keyframes_near(src, start)
+ alt = ""
+ if near:
+ closest = min(near, key=lambda k: abs(k - start))
+ alt = (f"; for a lossless cut move --start to a keyframe (nearest: {closest:.3f}s"
+ + (f", others within 5 s: {', '.join(f'{k:.3f}' for k in near if k != closest)}" if len(near) > 1 else "") + ")")
+ NEAREST_KEYFRAMES.extend(k for k in near if k not in NEAREST_KEYFRAMES)
info(f"stream copy landed on a keyframe {abs(got - dur):.2f}s away from the requested cut "
- f"(> {tolerance:.2f}s tolerance); re-encoding this segment for accuracy")
+ f"(> {tolerance:.2f}s tolerance); re-encoding this segment for accuracy{alt}")
return cut_one(src, start, end, dst, True, crf, preset, tolerance, meta)
return reencode
@@ -134,7 +145,7 @@ def main() -> int:
ap.add_argument("--accurate", action="store_true", help="always re-encode for frame-accurate (video) / sample-accurate (audio) cuts (default: lossless -c copy, re-encoding only when the keyframe snap exceeds --tolerance)")
ap.add_argument("--tolerance", type=float, default=0.5, help="max seconds a lossless cut may deviate before re-encoding kicks in (default 0.5, -1 = never)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF when re-encoding (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset when re-encoding")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset when re-encoding")
add_common(ap)
args = ap.parse_args()
apply_common(args)
@@ -211,7 +222,8 @@ def main() -> int:
requested_segments=[[round(s, 6), round(e, 6)] for s, e in segments] if len(segments) > 1 else None,
requested_duration=round(expected, 6), output_duration=round(got, 6) if got is not None else None,
duration_delta_seconds=round(error_ms / 1000, 6) if error_ms is not None else None,
- mode=mode, keyframe_snapped=keyframe_snapped)
+ mode=mode, keyframe_snapped=keyframe_snapped,
+ nearest_keyframes=sorted(NEAREST_KEYFRAMES) if NEAREST_KEYFRAMES else None)
return 0
diff --git a/scripts/deinterlace.py b/scripts/deinterlace.py
index 812547b..15c1794 100644
--- a/scripts/deinterlace.py
+++ b/scripts/deinterlace.py
@@ -22,7 +22,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
MODES = {"frame": 0, "field": 1}
PARITIES = {"auto": -1, "tff": 0, "bff": 1}
@@ -41,7 +41,7 @@ def main() -> int:
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to keep, 0-based in file order (default 0)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/denoise.py b/scripts/denoise.py
index 8c61b4b..74a1f45 100644
--- a/scripts/denoise.py
+++ b/scripts/denoise.py
@@ -18,7 +18,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
# hqdn3d's own AVOptions default to 0 (off); these tested presets are the light/medium/heavy
# starting points its own documentation and common usage recommend (spatial then temporal,
@@ -43,7 +43,7 @@ def main() -> int:
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to keep, 0-based in file order (default 0)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
ap.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
add_common(ap)
args = ap.parse_args()
diff --git a/scripts/fit.py b/scripts/fit.py
index 91d302f..2e474d1 100755
--- a/scripts/fit.py
+++ b/scripts/fit.py
@@ -38,7 +38,7 @@ import sys
from fractions import Fraction
from typing import List
-from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, pad_filters, add_pad_fill_args
+from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, pad_filters, add_pad_fill_args, X264_PRESETS
ASPECT_PRESETS = {"16:9": Fraction(16, 9), "9:16": Fraction(9, 16), "1:1": Fraction(1, 1), "4:5": Fraction(4, 5), "4:3": Fraction(4, 3), "21:9": Fraction(21, 9)}
@@ -101,7 +101,7 @@ def main() -> int:
r.add_argument("--flip", choices=["h", "v"], help="mirror the picture horizontally (h) or vertically (v)")
e = ap.add_argument_group("encoding")
e.add_argument("--crf", type=int, default=18)
- e.add_argument("--preset", default="medium")
+ e.add_argument("--preset", default="medium", choices=X264_PRESETS)
e.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
add_common(ap)
args = ap.parse_args()
diff --git a/scripts/freeze.py b/scripts/freeze.py
index 1a25c14..c2e11d9 100644
--- a/scripts/freeze.py
+++ b/scripts/freeze.py
@@ -19,7 +19,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
def main() -> int:
@@ -31,7 +31,7 @@ def main() -> int:
ap.add_argument("--mode", choices=["insert", "extend"], default="insert",
help="insert (default): hold pushes the rest of the clip later; extend: only valid at/after the clip's end, makes the last frame last longer with nothing pushed")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/graphics.py b/scripts/graphics.py
index d24b43a..c16f99e 100755
--- a/scripts/graphics.py
+++ b/scripts/graphics.py
@@ -21,7 +21,7 @@ import argparse
import sys
from typing import List, Optional
-from _common import aac_args, add_common, apply_common, cfr_args, color_hex, default_font_file, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, run_keeping_subtitles, video_args, drawtext_boxborderw
+from _common import aac_args, add_common, apply_common, cfr_args, color_hex, default_font_file, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, run_keeping_subtitles, video_args, drawtext_boxborderw, X264_PRESETS
TEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug"]
@@ -62,7 +62,7 @@ def main() -> int:
ap.add_argument("--font-file")
ap.add_argument("--scale", type=float, default=1.0, help="size multiplier (default 1)")
ap.add_argument("--crf", type=int, default=18)
- ap.add_argument("--preset", default="medium")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS)
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/grid.py b/scripts/grid.py
index 677126a..c49fe56 100644
--- a/scripts/grid.py
+++ b/scripts/grid.py
@@ -25,7 +25,7 @@ import argparse
import os
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_font_file, default_output, die, emit, \
+from _common import add_common, apply_common, aac_args, cfr_args, default_font_file, default_output, die, emit, X264_PRESETS, \
escape_drawtext, escape_filter_path, ffmpeg_base, info, probe, run, validate_color, video_args
LABEL_MARGIN = 10
@@ -50,7 +50,7 @@ def main() -> int:
ap.add_argument("--gap", type=int, default=0, help="gap between cells in px, must be even (default 0, cells touch)")
ap.add_argument("--background", default="black", help="colour of the gap/pad borders (default black)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/insert.py b/scripts/insert.py
index 143cc80..fdf34f3 100644
--- a/scripts/insert.py
+++ b/scripts/insert.py
@@ -27,7 +27,7 @@ import argparse
import math
import sys
-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args
+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS
def even(n: float) -> int:
@@ -47,7 +47,7 @@ def main() -> int:
ap.add_argument("--zoom-amount", type=float, default=1.3, help="end (zoom in) or start (zoom out) zoom factor, > 1.0 (default 1.3)")
ap.add_argument("--pan", choices=["left", "right", "up", "down"], help="drift the visible window this direction while zoomed (needs --zoom)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/join.py b/scripts/join.py
index 948242e..657b8b7 100755
--- a/scripts/join.py
+++ b/scripts/join.py
@@ -23,7 +23,7 @@ import argparse
import sys
from typing import List
-from _common import STATE, video_args, aac_args, add_common, apply_common, audio_codec_for, default_output, die, emit, ffmpeg_base, info, is_audio_output, probe, run, validate_color
+from _common import STATE, video_args, aac_args, add_common, apply_common, audio_codec_for, default_output, die, emit, ffmpeg_base, info, is_audio_output, probe, run, validate_color, X264_PRESETS
TRANSITIONS = ["fade", "dissolve", "wipeleft", "wiperight", "wipeup", "wipedown", "slideleft", "slideright",
"circleopen", "circleclose", "fadeblack", "fadewhite", "smoothleft", "smoothright", "radial", "none"]
@@ -94,7 +94,7 @@ def main() -> int:
ap.add_argument("--fit", choices=["pad", "crop"], default="pad", help="how clips of another aspect reach the frame (default pad)")
ap.add_argument("--pad-color", default="black")
ap.add_argument("--crf", type=int, default=18)
- ap.add_argument("--preset", default="medium")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS)
aud = ap.add_argument_group("audio-only inputs")
aud.add_argument("--sample-rate", type=int, help="output sample rate in Hz (default: first clip's)")
aud.add_argument("--channels", type=int, choices=[1, 2, 6, 8], help="output channel count (default: the widest clip)")
diff --git a/scripts/loop.py b/scripts/loop.py
index 95fdd51..29acb18 100644
--- a/scripts/loop.py
+++ b/scripts/loop.py
@@ -18,7 +18,7 @@ import argparse
import math
import sys
-from _common import add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args
+from _common import add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS
def main() -> int:
@@ -29,7 +29,7 @@ def main() -> int:
group.add_argument("--times", type=int, help="repeat the whole clip this many times (2 = original + 1 repeat)")
group.add_argument("--duration", help="loop (and trim the last repeat) to hit exactly this target duration (seconds or mm:ss)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/metadata.py b/scripts/metadata.py
index dca1c3d..fa55de9 100755
--- a/scripts/metadata.py
+++ b/scripts/metadata.py
@@ -30,7 +30,7 @@ import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional
-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, STATE
+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, STATE, read_text_or_die
CHAPTER_CONTAINERS = {".mp4", ".m4v", ".m4a", ".mov", ".mkv", ".mka", ".webm"}
TAG_KEYS = ("title", "artist", "album", "comment", "date", "genre")
@@ -39,7 +39,7 @@ TAG_KEYS = ("title", "artist", "album", "comment", "date", "genre")
def parse_chapters(path: str, duration: float) -> List[Dict[str, Any]]:
"""`TIME TITLE` per line -> [{"start", "end", "title"}], validated: ascending starts, every
start inside the file, the last chapter running to the file's end."""
- text = Path(path).read_text(encoding="utf-8")
+ text = read_text_or_die(path, "--chapters")
entries: List[Dict[str, Any]] = []
for n, raw in enumerate(text.splitlines(), start=1):
line = raw.strip()
diff --git a/scripts/multicam.py b/scripts/multicam.py
index e8de298..f9c10f6 100755
--- a/scripts/multicam.py
+++ b/scripts/multicam.py
@@ -29,7 +29,7 @@ import argparse
import sys
from typing import List, Tuple
-from _common import video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, x264_args
+from _common import video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, x264_args, X264_PRESETS
from sync import measure_offset
@@ -69,7 +69,7 @@ def main() -> int:
ap.add_argument("--height", type=int, help="output height (default: reference)")
ap.add_argument("--fps", type=float, help="output fps (default: reference)")
ap.add_argument("--crf", type=int, default=18)
- ap.add_argument("--preset", default="medium")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS)
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/overlay.py b/scripts/overlay.py
index 352cc68..f749274 100755
--- a/scripts/overlay.py
+++ b/scripts/overlay.py
@@ -24,7 +24,7 @@ import argparse
import sys
from typing import List, Optional
-from _common import STATE, load_brand, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args
+from _common import STATE, load_brand, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, X264_PRESETS
POS = {
"top-left": ("{m}", "{m}"),
@@ -119,7 +119,7 @@ def main() -> int:
txt.add_argument("--box-color", default="[email protected]")
enc = ap.add_argument_group("encoding")
enc.add_argument("--crf", type=int, default=18)
- enc.add_argument("--preset", default="medium")
+ enc.add_argument("--preset", default="medium", choices=X264_PRESETS)
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/pad.py b/scripts/pad.py
index 28c648b..f27ff0a 100644
--- a/scripts/pad.py
+++ b/scripts/pad.py
@@ -16,7 +16,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS
def main() -> int:
@@ -27,7 +27,7 @@ def main() -> int:
ap.add_argument("--end", type=float, default=0.0, help="seconds of padding to add after the clip (default 0)")
ap.add_argument("--color", default="black", help="padding colour (default black)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/redact.py b/scripts/redact.py
index 28a3036..01dd72c 100644
--- a/scripts/redact.py
+++ b/scripts/redact.py
@@ -20,7 +20,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
def main() -> int:
@@ -37,7 +37,7 @@ def main() -> int:
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to keep, 0-based in file order (default 0)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
ap.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
add_common(ap)
args = ap.parse_args()
diff --git a/scripts/render.py b/scripts/render.py
index 03722c8..aeea2cd 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -80,18 +80,26 @@ TEMPLATE = {
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 = [sys.executable, str(HERE / script)] + [str(a) for a in argv] + (extra or []) + child_args()
- info("→ " + " ".join(os.path.basename(c) if i < 2 else c for i, c in enumerate(cmd)))
+ cmd = [sys.executable, str(HERE / script)] + [str(a) for a in argv] + (extra or []) + child_args() + ["--json"]
+ info("→ " + " ".join(os.path.basename(c) if i < 2 else c for i, c in enumerate(cmd[:-1])))
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for line in proc.stderr.splitlines():
if line.startswith("$ ") or line.startswith("[dry-run]"):
STATE["commands"].append(line[2:] if line.startswith("$ ") else line)
elif line.strip():
info(" " + line)
+ try:
+ doc = json.loads(proc.stdout.strip() or "{}")
+ except ValueError:
+ doc = {}
if proc.returncode != 0:
- die(f"{script} failed")
- out = proc.stdout.strip().splitlines()
- return out[-1] if out else ""
+ # Re-raise the stage's own failure: its kind, exit code and hint are what the caller
+ # needs (a timeout inside audio.py is a timeout, not an "input" error of render.py).
+ err = doc.get("error") or {}
+ extra_fields = {"hint": err["hint"]} if err.get("hint") else {}
+ die(f"{script} failed: {err.get('message') or (proc.stderr.strip().splitlines() or ['?'])[-1][:300]}",
+ code=int(doc.get("exit_code") or 1), kind=err.get("kind") or "input", stage=script, **extra_fields)
+ return str(doc.get("output") or "")
def main() -> int:
diff --git a/scripts/report.py b/scripts/report.py
index 509d298..3d5279f 100755
--- a/scripts/report.py
+++ b/scripts/report.py
@@ -19,7 +19,7 @@ import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional
-from _common import STATE, add_common, apply_common, die, emit, info, probe
+from _common import STATE, add_common, apply_common, die, emit, info, probe, read_text_or_die
HERE = Path(__file__).resolve().parent
@@ -46,9 +46,16 @@ def loudness(path: str) -> Dict[str, Any]:
def check(path: str, platform: str) -> Optional[Dict[str, Any]]:
proc = subprocess.run([sys.executable, str(HERE / "check.py"), path, "--platform", platform, "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
- return json.loads(proc.stdout)
+ doc = json.loads(proc.stdout)
except ValueError:
+ doc = None
+ if not isinstance(doc, dict) or "checks" not in doc:
+ # check.py could not run at all (missing ffmpeg, unreadable file): its failure document
+ # has no rows to render. A failed *verification* still carries its rows and is shown.
+ reason = ((doc or {}).get("error") or {}).get("message") or (proc.stderr.strip().splitlines() or ["?"])[-1]
+ info(f"check.py could not run: {reason[:200]}")
return None
+ return doc
def fmt_dur(sec: Optional[float]) -> str:
@@ -99,8 +106,8 @@ def main() -> int:
sheets["before"] = sheet_b64(args.before)
if after.get("video"):
sheets["after"] = sheet_b64(args.after)
- commands = Path(args.commands).read_text(encoding="utf-8").splitlines() if args.commands else []
- notes = Path(args.notes).read_text(encoding="utf-8") if args.notes else ""
+ commands = read_text_or_die(args.commands, "--commands").splitlines() if args.commands else []
+ notes = read_text_or_die(args.notes, "--notes") if args.notes else ""
title = args.title or f"Delivery report — {Path(args.after).name}"
output = args.output or str(Path(args.after).with_name(Path(args.after).stem + "_report.html"))
diff --git a/scripts/reverse.py b/scripts/reverse.py
index 92132e5..1cca0dc 100644
--- a/scripts/reverse.py
+++ b/scripts/reverse.py
@@ -14,7 +14,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
def main() -> int:
@@ -23,7 +23,7 @@ def main() -> int:
ap.add_argument("-o", "--output", help="output file (default: <name>_reverse.<ext>)")
ap.add_argument("--no-audio", action="store_true", help="drop audio instead of reversing it")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/sequence.py b/scripts/sequence.py
index 7e0d41b..05dd7f8 100644
--- a/scripts/sequence.py
+++ b/scripts/sequence.py
@@ -19,7 +19,7 @@ import sys
import tempfile
from pathlib import Path
-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, video_args
+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
def even(n: float) -> int:
@@ -43,7 +43,7 @@ def main() -> int:
ap.add_argument("--width", type=int, help="output width in px; with --height also given, both are used directly")
ap.add_argument("--height", type=int, help="output height in px; with --width also given, both are used directly")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/silence.py b/scripts/silence.py
index bd5bdca..572aa17 100755
--- a/scripts/silence.py
+++ b/scripts/silence.py
@@ -16,7 +16,7 @@ import re
import sys
from typing import List, Tuple
-from _common import video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, require_tool, run, x264_args
+from _common import STATE, video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, require_tool, run, x264_args, X264_PRESETS, measured_level_dbfs
SIL_RE = re.compile(r"silence_(start|end): ([0-9.]+)")
@@ -65,7 +65,7 @@ def main() -> int:
ap.add_argument("--list", action="store_true", help="only print silences and the kept ranges")
ap.add_argument("--edl", help="write the kept ranges to this file, one START-END per line")
ap.add_argument("--crf", type=int, default=18)
- ap.add_argument("--preset", default="medium")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS)
add_common(ap)
args = ap.parse_args()
apply_common(args)
@@ -86,6 +86,19 @@ def main() -> int:
"removed_seconds": round(removed, 3),
}
info(f"{len(silences)} silences, keeping {len(keeps)} ranges: {kept:.2f}s of {duration:.2f}s (removing {removed:.2f}s)")
+ if not silences and not STATE.dry_run:
+ # Nothing under the threshold is a valid result, not a failure -- but an agent that only
+ # sees "0 silences" tends to reach for raw ffmpeg next. Say what the floor actually is and
+ # what threshold would bite, so the retry is a flag change, not a workaround.
+ level = measured_level_dbfs(args.input)
+ if level:
+ suggested = min(-5.0, round(level["mean_dbfs"] + 6.0))
+ summary["hint"] = (f"no passage sits below {args.threshold:g} dBFS for {args.min_silence:g}s; the track's mean level is "
+ f"{level['mean_dbfs']:.1f} dBFS (peak {level['peak_dbfs']:.1f}). For a quiet-room recording try "
+ f"--threshold {suggested:g}, or a shorter --min-silence")
+ else:
+ summary["hint"] = f"no passage sits below {args.threshold:g} dBFS for {args.min_silence:g}s; try a higher --threshold (e.g. -25) or a shorter --min-silence"
+ info("hint: " + summary["hint"])
if args.edl:
with open(args.edl, "w", encoding="utf-8") as fh:
diff --git a/scripts/speedramp.py b/scripts/speedramp.py
index 63367a4..5a68745 100644
--- a/scripts/speedramp.py
+++ b/scripts/speedramp.py
@@ -19,7 +19,7 @@ import argparse
import sys
from typing import List, Tuple
-from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args
+from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
MAX_SPEED = 20.0
MIN_SPEED = 0.05
@@ -60,7 +60,7 @@ def main() -> int:
ap.add_argument("--segment", action="append", required=True, dest="segments",
help=f"START-END:FACTOR, repeatable; segments must cover 0..duration with no gaps or overlaps, in order. FACTOR is {MIN_SPEED}..{MAX_SPEED} (2.0 = twice as fast, 0.5 = half speed)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/sphere.py b/scripts/sphere.py
index 4b71981..97a1548 100644
--- a/scripts/sphere.py
+++ b/scripts/sphere.py
@@ -31,7 +31,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
# v360's own AVOption names for the input projections real 360 cameras/exports actually
# produce (ffmpeg -h filter=v360 documents 24 total; this is the subset a caller is likely
@@ -65,7 +65,7 @@ def main() -> int:
out.add_argument("--height", type=int, default=1080, help="output height in px, must be even (default 1080)")
out.add_argument("--interp", choices=INTERP_METHODS, default="lanczos", help="resampling method (default lanczos)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
ap.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
add_common(ap)
args = ap.parse_args()
diff --git a/scripts/stabilize.py b/scripts/stabilize.py
index 5a40d70..4fbbc9d 100644
--- a/scripts/stabilize.py
+++ b/scripts/stabilize.py
@@ -27,7 +27,7 @@ import sys
import tempfile
from pathlib import Path
-from _common import STATE, add_common, apply_common, aac_args, cfr_args, default_output, die, emit, escape_filter_path, ffmpeg_base, info, probe, require_tool, run, video_args
+from _common import STATE, add_common, apply_common, aac_args, cfr_args, default_output, die, emit, escape_filter_path, ffmpeg_base, info, probe, require_tool, run, video_args, X264_PRESETS
def main() -> int:
@@ -40,7 +40,7 @@ def main() -> int:
ap.add_argument("--crop", choices=["keep", "black"], default="keep", help="edges --zoom doesn't crop away: keep (stretch border pixels, default) or black (fill solid black)")
ap.add_argument("--tripod", action="store_true", help="lock the frame fully still against a single reference frame instead of smoothing the camera's motion")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/scripts/straighten.py b/scripts/straighten.py
index e1b3bef..580ce1c 100644
--- a/scripts/straighten.py
+++ b/scripts/straighten.py
@@ -22,7 +22,7 @@ import argparse
import math
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS
def main() -> int:
@@ -36,7 +36,7 @@ def main() -> int:
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to keep, 0-based in file order (default 0)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
ap.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
add_common(ap)
args = ap.parse_args()
diff --git a/scripts/waveform.py b/scripts/waveform.py
index 61009a5..09aeca7 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
+from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, validate_color, X264_PRESETS
WAVEFORM_MODES = ["point", "line", "p2p", "cline"]
@@ -42,7 +42,7 @@ def main() -> int:
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to render, 0-based in file order (default 0)")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
- ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
diff --git a/tests/test_all.py b/tests/test_all.py
index 2990ae2..95dd6d7 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -168,6 +168,11 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertTrue(data3["reencoded"])
self.assertEqual(data3["mode"], "hybrid")
self.assertFalse(data3["keyframe_snapped"])
+ # ...and name the keyframes a lossless cut could have used instead (x264's default GOP on the
+ # fixture puts the only one within 5 s of 1.13 at 0.0)
+ self.assertTrue(data3["nearest_keyframes"], data3)
+ self.assertIn(0.0, data3["nearest_keyframes"])
+ self.assertIsNone(data["nearest_keyframes"], "a clean copy has no alternative to offer")
# multi-segment: requested_start/end are None, requested_segments lists each range
out4 = OUT / "cut_honest_segments.mp4"
@@ -229,6 +234,11 @@ class FFmpegSkillTests(unittest.TestCase):
"-f", "lavfi", "-i", "sine=frequency=880:sample_rate=48000:duration=8", "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac", b)
out = OUT / "broll_out.mp4"
data = json.loads(script("broll.py", self.src, "--insert", b, "--at", "4", "--end", "7", "--from", "1", "--fast", "--json", "-o", out).stdout)
+ # --pad-color is spliced into the filter graph like every other colour flag, so it is validated like them
+ inj = script("broll.py", self.src, "--insert", b, "--at", "4", "--end", "7", "--pad-color", "black,drawtext=text=INJECTED",
+ "--json", "-o", OUT / "broll_inj.mp4", expect_fail=True)
+ self.assertIn("plain colour", json.loads(inj.stdout)["error"]["message"])
+ self.assertEqual(json.loads(inj.stdout)["commands"], [], "refused before ffmpeg ran")
self.assertEqual(data["cutaways"], [{"insert": str(b), "at": 4.0, "end": 7.0, "from": 1.0}])
m = probe(str(out))
self.assertClose(m["duration"], probe(str(self.src))["duration"], 0.1)
@@ -1710,6 +1720,16 @@ class FFmpegSkillTests(unittest.TestCase):
"-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-t", "12", "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac", gappy)
data = json.loads(script("silence.py", gappy, "--list", "--json").stdout)
self.assertEqual(len(data["silences"]), 3)
+ self.assertNotIn("hint", data, "a hit needs no hint")
+ # a track with nothing under the threshold says what the floor is and which flag to change,
+ # instead of a bare "0 silences" that sends an agent off to raw ffmpeg (evals iteration 5, finding 1)
+ tone = OUT / "tone.mp4"
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000",
+ "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30", "-t", "4", "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac", tone)
+ none = json.loads(script("silence.py", tone, "--list", "--json").stdout)
+ self.assertEqual(none["silences"], [])
+ self.assertIn("--threshold", none["hint"])
+ self.assertIn("mean level", none["hint"])
self.assertClose(data["removed_seconds"], 5.25, 0.3)
out = OUT / "tight.mp4"
edl = OUT / "keep.txt"
@@ -2486,6 +2506,9 @@ class FFmpegSkillTests(unittest.TestCase):
proc = script("render.py", proj, "--fast", "--timeout", "0.05", "--json", expect_fail=True)
self.assertIn("time limit", proc.stderr)
self.assertIn("--timeout 0.05", proc.stderr, "the flag must be forwarded to the child command line")
+ # ...and the stage's own failure is what render reports: kind timeout, exit 124, the stage named
+ tdoc = json.loads(proc.stdout)
+ self.assertEqual((tdoc["status"], tdoc["error"]["kind"], tdoc["exit_code"], tdoc["stage"]), ("failed", "timeout", 124, "cut.py"))
def test_join_width_keeps_aspect(self):
out = OUT / "join_w.mp4"
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 73e0ad4..b27aa4a 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -930,6 +930,10 @@ class ContractTests(unittest.TestCase):
self.assertEqual(resps[3]["error"]["code"], -32000)
self.assertTrue(resps[4]["result"]["isError"])
self.assertIn("cut failed (exit", resps[4]["result"]["content"][0]["text"])
+ # the child's failure document rides along: kind/code are what an MCP caller keys on
+ failed_doc = resps[4]["result"]["structuredContent"]
+ self.assertEqual((failed_doc["status"], failed_doc["error"]["kind"]), ("failed", "input"))
+ self.assertIn("code", failed_doc["error"])
self.assertEqual(resps[5]["result"]["structuredContent"]["audio"]["codec"], "pcm_s16le")
self.assertIn("structuredContent", resps[6]["result"], "--json appended for a JSON tool in raw argv form")
# the raw form appends --json exactly for the tools that need it to speak JSON
@@ -1207,6 +1211,25 @@ class ContractTests(unittest.TestCase):
self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "timeout", "the env default applies without the flag")
self.assertIn("timeout", self.contract["json_output"]["error_kinds"])
+ def test_encoder_flags_are_validated_before_ffmpeg_sees_them(self):
+ """--preset took any string and --crf any integer; an agent's typo ("--preset fastest",
+ "--crf 99") reached ffmpeg and came back as kind ffmpeg with x264's stderr, which reads as
+ an encoder failure rather than a bad argument. Every x264 --preset is now an argparse
+ choice (so the contract and MCP schema carry the enum) and --crf is range-checked once
+ in apply_common for all 31 tools that take it."""
+ proc = tool("cut", self.src, "--start", "0", "--end", "1", "--preset", "fastest", "--json", "-o", self.out("p.mp4"), check=False)
+ self.assertEqual(proc.returncode, 2, "argparse rejects an unknown preset")
+ self.assertIn("invalid choice", proc.stderr)
+ proc = tool("cut", self.src, "--start", "0", "--end", "1", "--crf", "99", "--json", "-o", self.out("c.mp4"), check=False)
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"]), ("failed", "input"))
+ self.assertIn("--crf must be between 0 and 51", doc["error"]["message"])
+ self.assertEqual(doc["commands"], [], "refused before any ffmpeg ran")
+ for name, spec in self.tools.items():
+ preset = spec["input_schema"]["properties"].get("preset")
+ if preset and name != "export":
+ self.assertEqual(set(preset["enum"]), set(_common.X264_PRESETS), name)
+
def test_failed_run_never_deletes_an_output_that_predates_it(self):
"""The partial-output cleanup (#78) removed the output path after every failed ffmpeg run
without asking whether the file had been there before: a bad filter argument aimed at an