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: boundary sweep -- output lock, even-dimension retry, subtitle drops in cut/pad, unwritable dirs, dry-run source check, verify single JSON, redact radius, HDR refusal in color, and the P3s (#190)

claude[bot]8e0cee1143e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0ea7548..9b7ea3a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,12 @@
## Unreleased
-(nothing yet)
+- Boundary sweep (561 runs, 42 tools × 23 inputs). Two runs writing the same output at once both reported `completed` while one of them described the other's file: `run()` now holds a lock file (`.<name>.ffskill-lock`, pid inside) next to the output and the second run is refused as `kind: input`; a lock whose pid is dead or older than an hour is taken over.
+- Odd source dimensions (641x359 screen captures, 4:4:4 masters) failed 15 tools with "width not divisible by 2": `run()` retries the encode with an even-dimension scale in front of the filter chain; a `-filter_complex` graph that cannot take it is refused as `kind: input` with the fix named.
+- `cut.py`'s re-encode path and `pad.py --start` stream-copied a subtitle track whose cues then fired early (cut's container grew to 2 s for a 1 s cut): both drop it and report `dropped_non_av_streams`, as `fit`/`freeze` already did. `cut.py` counts a keyframe snap of exactly the tolerance as outside it.
+- `render.py --dry-run` planned ten commands for a clip whose source does not exist; the source is checked first. `render.py` and `report.py` answered an unwritable output directory with a traceback; an unwritable directory is now refused as `kind: input` by every writing tool before ffmpeg runs. `verify.py --json` printed two JSON documents for a non-media input.
+- `color.py --correct` / `--lut` on an HDR source tagged PQ/HLG pixels as BT.709 without a tone map: refused as `kind: input` naming `--to-sdr` (`--force` grades the raw values anyway). `redact.py --mode blur` failed on regions under 40 px with the default radius (clamped, chroma planes get their own). `loudness.py --measure-only --json` prints the contract's document shape.
+- Sweep P3s: `export.py`'s HDR warning is in the JSON (`notes`); `graphics.py` refuses a frame under 64 px instead of building a 0-height bar; `insert.py` refuses a video where it wants a still; `look.py` builds a sheet from a one-frame clip instead of printing "wrote" and then failing; `batch.py --dry-run` leaves no directories behind and `render.py` removes its auto-named work directory on every exit path.
## 1.4.13
diff --git a/scripts/_common.py b/scripts/_common.py
index f6ae1ab..e122864 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -461,6 +461,112 @@ def _check_output_path(cmd: Sequence[str]) -> None:
parent = os.path.dirname(os.path.abspath(output))
if not os.path.isdir(parent):
die(f"output directory {parent!r} does not exist; create it first (this tool never creates directories)")
+ if not os.access(parent, os.W_OK):
+ die(f"output directory {parent!r} is not writable")
+
+
+EVEN_SCALE = "scale=trunc(iw/2)*2:trunc(ih/2)*2"
+
+
+def _pid_dead(pid: int) -> bool:
+ """True only when the process is known not to exist. POSIX: signal 0. Windows: OpenProcess
+ fails with ERROR_INVALID_PARAMETER (87) for a pid that is not in use; any other outcome
+ (a handle, or access denied) means it is live. Unknown is treated as live."""
+ if os.name != "nt":
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return True
+ except OSError:
+ pass
+ return False
+ try:
+ import ctypes
+ k32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
+ handle = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
+ if handle:
+ k32.CloseHandle(handle)
+ return False
+ return k32.GetLastError() == 87
+ except Exception:
+ return False
+
+
+class _OutputLock:
+ """Two runs writing the same output at once used to both report `completed` while one of
+ them described the other's file (sweep F1). A lock file next to the output, created with
+ O_EXCL and holding the writer's pid, makes the second run refuse as `kind: input`. A lock
+ whose pid is dead (POSIX) or older than an hour is stale and taken over."""
+ def __init__(self, output: str) -> None:
+ self.path: Optional[str] = None
+ self.fd: Optional[int] = None
+ if output == "-" or output.startswith("pipe:") or output.startswith("-"):
+ return
+ d, base = os.path.split(os.path.abspath(output))
+ self.path = os.path.join(d, f".{base}.ffskill-lock")
+
+ def __enter__(self) -> "_OutputLock":
+ if not self.path:
+ return self
+ for attempt in (0, 1):
+ try:
+ self.fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
+ os.write(self.fd, str(os.getpid()).encode())
+ return self
+ except FileExistsError:
+ if attempt == 0 and self._stale():
+ try:
+ os.remove(self.path)
+ except OSError:
+ pass
+ continue
+ die(f"another run is writing {os.path.basename(self.path)[1:-len('.ffskill-lock')]!r} right now "
+ f"(lock {self.path}); wait for it or choose a different --output/-o path")
+ except OSError:
+ return self # unlockable location (read-only dir surfaces elsewhere): proceed without a lock
+ return self
+
+ def _stale(self) -> bool:
+ try:
+ pid = int(open(self.path).read().strip() or "0")
+ if pid > 0 and _pid_dead(pid):
+ return True
+ import time
+ return time.time() - os.path.getmtime(self.path) > 3600
+ except (OSError, ValueError):
+ return True
+
+ def __exit__(self, *exc: Any) -> None:
+ if self.fd is not None:
+ try:
+ os.close(self.fd)
+ except OSError:
+ pass
+ if self.path:
+ try:
+ os.remove(self.path)
+ except OSError:
+ pass
+
+
+def _odd_dimension_retry(cmd: List[str], stderr: str) -> Optional[List[str]]:
+ """An odd-sized source (641x359 screen captures, some 4:4:4 masters) fails every yuv420p
+ encode with "width/height not divisible by 2" (sweep F8, 15 tools). Return the same command
+ with an even-dimension scale prepended to its -vf chain (or a new -vf when the command had
+ none); None when the failure is something else or the graph is a -filter_complex the
+ caller has to fix itself."""
+ if "not divisible by 2" not in stderr or EVEN_SCALE in cmd or any(EVEN_SCALE in a for a in cmd):
+ return None
+ if "-filter_complex" in cmd:
+ return None
+ new = list(cmd)
+ if "-vf" in new:
+ i = new.index("-vf") + 1
+ new[i] = EVEN_SCALE + "," + new[i]
+ return new
+ if "-c:v" in new and new[new.index("-c:v") + 1] == "copy":
+ return None
+ return new[:-1] + ["-vf", EVEN_SCALE, new[-1]]
def _check_existing_output(cmd: Sequence[str]) -> None:
@@ -555,24 +661,41 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subpr
info(("[dry-run] $ " if STATE.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd))
if STATE.dry_run and is_ffmpeg:
return subprocess.CompletedProcess(list(cmd), 0, "", "")
- exec_cmd, final, tmp = _stage_existing_output(cmd) if is_ffmpeg else (list(cmd), None, None)
- if STATE.progress and is_ffmpeg and exec_cmd[-1] != "-":
- proc = _run_with_progress(exec_cmd, check)
- else:
- proc = _run_captured(exec_cmd, check)
- if final and tmp:
- if proc.returncode == 0:
- try:
- os.replace(tmp, final)
- except OSError as e:
+ with _OutputLock(cmd[-1] if is_ffmpeg else "-"):
+ exec_cmd, final, tmp = _stage_existing_output(cmd) if is_ffmpeg else (list(cmd), None, None)
+ proc = _execute(exec_cmd)
+ if proc.returncode != 0 and is_ffmpeg:
+ retry = _odd_dimension_retry(exec_cmd, proc.stderr or "")
+ if retry is not None:
+ info("source has odd dimensions; scaling to even before encoding (yuv420p needs it)")
+ STATE.commands[-1] = _cmdline(retry[:-1] + [cmd[-1]])
+ proc = _execute(retry)
+ elif "not divisible by 2" in (proc.stderr or ""):
+ die("the source has odd dimensions (width or height not divisible by 2) and this tool's filter graph "
+ "cannot pad them itself; make them even first, e.g. fit.py --width/--height, then retry",
+ kind="input")
+ if proc.returncode != 0 and check:
+ _fail(exec_cmd, proc.returncode, proc.stderr or "")
+ if final and tmp:
+ if proc.returncode == 0:
+ try:
+ os.replace(tmp, final)
+ except OSError as e:
+ _cleanup_partial_output(exec_cmd)
+ die(f"could not replace {final} with the new output: {e}", kind="output")
+ _remember_output(cmd)
+ else:
_cleanup_partial_output(exec_cmd)
- die(f"could not replace {final} with the new output: {e}", kind="output")
- _remember_output(cmd)
- else:
- _cleanup_partial_output(exec_cmd)
return proc
+def _execute(exec_cmd: List[str]) -> subprocess.CompletedProcess:
+ """One attempt, never exiting on failure (run() decides after its retries)."""
+ if STATE.progress and _is_ffmpeg(exec_cmd) and exec_cmd[-1] != "-":
+ return _run_with_progress(exec_cmd, False)
+ return _run_captured(exec_cmd, False)
+
+
def run_analysis(cmd: Sequence[str], *, check: bool = True, text: bool = True, record: bool = False) -> subprocess.CompletedProcess:
"""Run an ffmpeg *measurement* (scene scores, crop rectangles, decoded PCM, signal stats,
silence detection, loudness, stabilisation pass 1): output to `-f null`, a pipe or a temp
diff --git a/scripts/batch.py b/scripts/batch.py
index 060652c..d037def 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -156,8 +156,23 @@ def main() -> int:
if not outdir.is_absolute():
outdir = folder / outdir
work = Path(args.work) if args.work else outdir / ".work"
+ # the children refuse an output whose directory does not exist, under --dry-run too, so the
+ # directories are created for the plan as well -- and removed again afterwards when a dry
+ # run created them and left them empty (a plan leaves nothing behind, sweep F15)
+ created = [d for d in (outdir, work) if not d.exists()]
outdir.mkdir(parents=True, exist_ok=True)
work.mkdir(parents=True, exist_ok=True)
+ if STATE.dry_run and created:
+ import atexit
+
+ def _remove_empty_dirs() -> None:
+ for d in sorted(created, key=lambda p: len(str(p)), reverse=True):
+ try:
+ if not any(d.iterdir()):
+ d.rmdir()
+ except OSError:
+ pass
+ atexit.register(_remove_empty_dirs)
cache_path = outdir / ".ffskill_cache.json"
cache: Dict[str, Any] = {}
if cache_path.exists() and not args.force:
diff --git a/scripts/color.py b/scripts/color.py
index 68e1540..39226a4 100755
--- a/scripts/color.py
+++ b/scripts/color.py
@@ -285,6 +285,9 @@ def main() -> int:
output = args.output or default_output(args.input, "sdr")
tag = "sdr"
elif args.correct:
+ if v.get("hdr") and not args.force:
+ die(f"{args.input} is HDR ({v.get('hdr_format')}); --correct works on SDR pixels and would tag PQ/HLG data as BT.709 "
+ f"without a tone map (sweep F10). Run --to-sdr first, or --force to grade the raw values anyway")
vf = correction_chain(args)
output = args.output or default_output(args.input, "correct")
tag = "correct"
@@ -292,6 +295,9 @@ def main() -> int:
# "looks better" judgement -- the same primitive probe.py --analyze uses for Log detection.
measurements = {"input": analyze_levels(args.input)}
else:
+ if v.get("hdr") and not args.force:
+ die(f"{args.input} is HDR ({v.get('hdr_format')}); a LUT made for SDR applied to PQ/HLG pixels gives a wrong picture "
+ f"tagged BT.709 (sweep F10). Run --to-sdr first (or chain it), or --force if the LUT expects HDR input")
if not os.path.exists(args.lut):
die(f"LUT not found: {args.lut}")
if not (0.0 <= args.lut_strength <= 1.0):
diff --git a/scripts/cut.py b/scripts/cut.py
index 959cd80..39860ad 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -32,6 +32,8 @@ 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, X264_PRESETS, keyframes_near, MissingFpsError, concat_list_line, refuse_output_is_input, fmt_secs
+# outputs whose re-encode dropped a subtitle/data stream (reported as dropped_non_av_streams)
+DROPPED_STREAMS: List[str] = []
# 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 = []
@@ -115,6 +117,12 @@ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: i
cmd = ffmpeg_base() + ["-ss", f"{start:.6f}", "-i", src, "-t", f"{dur:.6f}"]
if is_audio_output(dst) or not meta.get("video"):
cmd += ["-af", f"atrim=end={dur:.6f},asetpts=PTS-STARTPTS"]
+ # ffmpeg's default stream selection also picks one subtitle stream; a re-encode cannot
+ # trim it (the cues kept their timestamps and the container grew to 2 s for a 1 s cut,
+ # sweep F2), so the re-encode carries video/audio only and the result says so
+ cmd += ["-sn", "-dn"]
+ if meta.get("subtitle_streams") or meta.get("data_streams"):
+ DROPPED_STREAMS.append(dst)
cmd += encode_args(meta, dst, crf, preset) + ["-avoid_negative_ts", "make_zero", dst]
elif audio_only:
# output-side seek: an input seek on a video file lands on the previous video keyframe and on
@@ -130,7 +138,7 @@ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: i
die(f"ffmpeg failed:\n{proc.stderr.strip()}", kind="ffmpeg")
if not reencode and tolerance >= 0 and not STATE.dry_run:
got = probe(dst).get("duration") or 0.0
- if abs(got - dur) > tolerance:
+ if abs(got - dur) >= tolerance: # a snap of exactly the tolerance is not "within" it (sweep F20)
near = keyframes_near(src, start)
alt = ""
if near:
@@ -230,6 +238,7 @@ def main() -> int:
info(f"wrote {output} ({fmt_secs(got)}, expected ~{expected:.3f}s, "
+ ("re-encoded" if reencoded else "lossless stream copy") + f", {precision} precision)")
emit(output, expected_duration=round(expected, 6), duration_error_ms=error_ms, precision=precision, reencoded=reencoded,
+ dropped_non_av_streams=bool(DROPPED_STREAMS),
requested_start=round(segments[0][0], 6) if len(segments) == 1 else None,
requested_end=round(segments[0][1], 6) if len(segments) == 1 else None,
requested_segments=[[round(s, 6), round(e, 6)] for s, e in segments] if len(segments) > 1 else None,
diff --git a/scripts/export.py b/scripts/export.py
index f990d6c..005dddb 100755
--- a/scripts/export.py
+++ b/scripts/export.py
@@ -68,8 +68,10 @@ def main() -> int:
meta = probe(args.input)
if not meta.get("video"):
die("input has no video stream")
+ notes: List[str] = []
if meta["video"].get("hdr") and args.preset not in ("prores", "copy"):
- info("warning: source is HDR (%s). This preset outputs SDR BT.709 tags without tone mapping; run color.py --to-sdr first for correct colours." % meta["video"].get("hdr_format"))
+ notes.append("source is HDR (%s). This preset outputs SDR BT.709 tags without tone mapping; run color.py --to-sdr first for correct colours." % meta["video"].get("hdr_format"))
+ info("warning: " + notes[-1])
has_audio = bool(meta.get("audio"))
output = args.output or default_output(args.input, args.preset, p["ext"])
out_ext = Path(output).suffix.lstrip(".").lower()
@@ -92,7 +94,7 @@ def main() -> int:
cmd += ["-filter_complex", fc, "-loop", "0", output]
run(cmd)
info(f"wrote {output}")
- emit(output)
+ emit(output, **({"notes": notes} if notes else {}))
return 0
if vf:
@@ -121,7 +123,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['codec']})")
- emit(output)
+ emit(output, **({"notes": notes} if notes else {}))
return 0
diff --git a/scripts/graphics.py b/scripts/graphics.py
index e46ba54..443b558 100755
--- a/scripts/graphics.py
+++ b/scripts/graphics.py
@@ -98,6 +98,8 @@ def main() -> int:
extra_inputs: List[str] = []
fc: List[str] = [] # filter_complex chains (used by templates that need animated boxes)
+ if 0 < min(W, H) < 64: # 0x0 is a dry-run probe of an intermediate that does not exist yet
+ die(f"the frame is {W}x{H}; the templates are sized from it and need at least 64 px on the short side")
if args.template == "lower-third":
if not args.name:
die("lower-third needs --name")
diff --git a/scripts/insert.py b/scripts/insert.py
index 194fb8c..ab14829 100644
--- a/scripts/insert.py
+++ b/scripts/insert.py
@@ -65,6 +65,9 @@ def main() -> int:
meta = probe(args.input)
if not meta.get("video"):
die("input has no image/video stream")
+ if (meta.get("duration") or 0) > 0.5 or meta.get("audio"):
+ die(f"{args.input} is a video, not a still image; insert.py animates a still (Ken Burns). "
+ f"For a clip use broll.py (cutaway) or cut.py/join.py")
sw, sh = meta["video"]["width"], meta["video"]["height"]
ratio = sw / sh
diff --git a/scripts/look.py b/scripts/look.py
index 4ef163f..84a65be 100755
--- a/scripts/look.py
+++ b/scripts/look.py
@@ -15,7 +15,7 @@ import sys
from pathlib import Path
from typing import List
-from _common import add_common, apply_common, default_font_file, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, time_arg
+from _common import STATE, add_common, apply_common, default_font_file, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, time_arg
FONT = "fontcolor=white:fontsize=h/18:box=1:[email protected]:boxborderw=6:x=8:y=8"
@@ -102,19 +102,28 @@ def main() -> int:
n = cols * rows
if not dur:
die("cannot build a contact sheet without a known duration")
+ frames_avail = int((meta["video"].get("fps") or 0) * dur) or 1
+ if n > frames_avail:
+ # a 2x2 sheet from a one-frame clip: tile waits for frames that never come and writes nothing
+ cols, rows = min(cols, frames_avail), 1
+ n = cols * rows
+ info(f"only {frames_avail} frame(s) available; sheet reduced to {cols}x{rows}")
step = dur / n
tile_w = max(2, (args.width // cols) // 2 * 2)
out = args.output or os.path.join(outdir, f"{stem}_sheet.png")
# sample at the middle of each slice so the first/last tiles are not black lead-in/out frames
vf = (f"select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,{step * 0.98:.6f})',scale={tile_w}:-2{tc},"
f"tile={cols}x{rows}:padding=2:margin=2:color=0x202020")
- cmd = ffmpeg_base() + ["-ss", f"{step / 2:.6f}", "-i", args.input, "-vf", vf, "-frames:v", "1", out]
+ # with only a handful of frames a mid-slice seek skips past them all: start at 0 instead
+ seek = 0.0 if frames_avail < 4 else step / 2
+ cmd = ffmpeg_base() + ["-ss", f"{seek:.6f}", "-i", args.input, "-vf", vf, "-frames:v", "1", out]
run(cmd)
outputs.append(out)
info(f"contact sheet: {n} frames every {step:.2f}s")
for o in outputs:
- info(f"wrote {o}")
+ if STATE.dry_run or os.path.exists(o):
+ info(f"wrote {o}")
emit(outputs[0] if len(outputs) == 1 else None, outputs=outputs)
if len(outputs) > 1 and not args.json:
for o in outputs:
diff --git a/scripts/loudness.py b/scripts/loudness.py
index 2110824..f79dd0f 100755
--- a/scripts/loudness.py
+++ b/scripts/loudness.py
@@ -64,12 +64,19 @@ def main() -> int:
if stats.get("silent"):
info("audio is silent (integrated loudness -inf); nothing to normalise")
if args.measure_only:
- print(json.dumps({"silent": True, "input_i": "-inf"}, indent=2))
+ if STATE.json:
+ emit(None, measured={"silent": True, "input_i": "-inf"})
+ else:
+ print(json.dumps({"silent": True, "input_i": "-inf"}, indent=2))
return 0
die("input audio is silent; loudness normalisation is meaningless (use audio.py --replace to add a track)")
info(f"measured: {float(stats['input_i']):.1f} LUFS, TP {float(stats['input_tp']):.1f} dBTP, LRA {float(stats['input_lra']):.1f} LU")
if args.measure_only:
- print(json.dumps({k: stats[k] for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset")}, indent=2))
+ measured = {k: stats[k] for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset")}
+ if STATE.json:
+ emit(None, measured=measured) # the contract's document shape (status, commands), not a bare dict
+ else:
+ print(json.dumps(measured, indent=2))
return 0
output = args.output or default_output(args.input, "loudnorm")
diff --git a/scripts/pad.py b/scripts/pad.py
index 37ed0ee..7d22682 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, X264_PRESETS, time_arg, fmt_secs
+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, time_arg, fmt_secs, run
def main() -> int:
@@ -57,7 +57,13 @@ def main() -> int:
cmd += aac_args()
else:
cmd += ["-an"]
- dropped_streams = run_keeping_subtitles(cmd, output)
+ if args.start > 0:
+ # a stream-copied subtitle track keeps its timestamps and would fire --start seconds early
+ # (sweep F3); drop it and say so, as freeze --mode insert and fit --method speed do
+ run(cmd + [output])
+ dropped_streams = bool(meta.get("subtitle_streams") or meta.get("data_streams"))
+ else:
+ dropped_streams = run_keeping_subtitles(cmd, output)
result = probe(output, role="output")
v = result["video"]
diff --git a/scripts/redact.py b/scripts/redact.py
index f6331e3..33a49be 100644
--- a/scripts/redact.py
+++ b/scripts/redact.py
@@ -74,7 +74,11 @@ def main() -> int:
output = args.output or default_output(args.input, "redact")
crop = f"crop={args.width}:{args.height}:{args.x}:{args.y}"
if args.mode == "blur":
- region = f"{crop},boxblur={args.blur_strength}:{args.blur_strength}"
+ # boxblur refuses a radius above half the plane: the chroma planes of 4:2:0 are half-size,
+ # so they get their own (halved) radius; a 30 px region with the default 20 used to fail
+ radius = max(1, min(args.blur_strength, min(args.width, args.height) // 2 - 1))
+ chroma = max(1, min(radius // 2, min(args.width, args.height) // 4 - 1))
+ region = f"{crop},boxblur={radius}:{radius}:{chroma}:{radius}"
else:
region = f"{crop},scale={max(1, args.width // args.block_size)}:{max(1, args.height // args.block_size)}:flags=neighbor,scale={args.width}:{args.height}:flags=neighbor"
fc = f"[0:v]split=2[base][region];[region]{region}[patched];[base][patched]overlay={args.x}:{args.y}[out]"
diff --git a/scripts/render.py b/scripts/render.py
index 3050b5a..f804595 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -141,7 +141,16 @@ def main() -> int:
# shared path, e.g. to inspect intermediates across runs); only the auto-derived default is
# made unique per process, since it's the one that's also auto-deleted at the end.
work = Path(args.work) if args.work else Path(f"{Path(output).with_suffix('')}_work_{os.getpid()}")
- work.mkdir(parents=True, exist_ok=True)
+ try:
+ work.mkdir(parents=True, exist_ok=True)
+ except OSError as e:
+ die(f"cannot create the work directory {work}: {e}")
+ if not args.keep and not args.work:
+ # a failed or dry run used to leave <output>_work_<pid>/ behind (sweep F15): the
+ # auto-named directory is ours alone, so remove it on every exit path
+ import atexit
+ import shutil
+ atexit.register(lambda: shutil.rmtree(work, ignore_errors=True))
frame = proj.get("frame") or {}
trans = proj.get("transition") or {}
brand_args: List[str] = ["--brand", rel(proj["brand"])] if proj.get("brand") else []
@@ -151,6 +160,8 @@ def main() -> int:
parts: List[str] = []
for i, c in enumerate(clips):
src = rel(c["src"])
+ if not os.path.exists(src):
+ die(f"clip {i}: source not found: {src}") # under --dry-run too: a plan for a missing file is no plan
if not STATE.dry_run:
probe(src)
needs_cut = c.get("in") is not None or c.get("out") is not None
diff --git a/scripts/report.py b/scripts/report.py
index 920e263..8419063 100755
--- a/scripts/report.py
+++ b/scripts/report.py
@@ -158,7 +158,10 @@ def main() -> int:
if STATE.dry_run:
info(f"wrote {output}") # printed as "[dry-run] would write"; nothing is written
else:
- Path(output).write_text(doc, encoding="utf-8")
+ try:
+ Path(output).write_text(doc, encoding="utf-8")
+ except OSError as e:
+ die(f"cannot write {output}: {e}", kind="output")
info(f"wrote {output} ({os.path.getsize(output) / 1024:.0f} KB)")
emit(None, report=output, check=chk)
if not args.json:
diff --git a/scripts/verify.py b/scripts/verify.py
index 945193b..44eef36 100755
--- a/scripts/verify.py
+++ b/scripts/verify.py
@@ -70,12 +70,15 @@ def collect(paths: List[str]) -> List[Path]:
def step(name: str, argv: List[str], timeout: float) -> Dict:
t0 = time.time()
if argv[0] == "__check_hdr__":
+ was_json, STATE.json = STATE.json, False # probe()'s die() would print a JSON document of its own
try:
v = probe(argv[1]).get("video") or {}
ok = bool(v.get("hdr")) and v.get("bit_depth", 8) >= 10
err = "" if ok else f"re-encode lost HDR: {v.get('color_transfer')}/{v.get('pix_fmt')}"
except SystemExit:
ok, err = False, "output missing"
+ finally:
+ STATE.json = was_json
return {"step": name, "ok": ok, "seconds": round(time.time() - t0, 1), "error": err}
try:
proc = subprocess.run([sys.executable, str(HERE / argv[0])] + argv[1:], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=timeout)
@@ -113,12 +116,15 @@ def main() -> int:
for f in files:
info(f"=== {f}")
entry: Dict = {"file": str(f), "steps": []}
+ was_json, STATE.json = STATE.json, False # same: one JSON document per run, printed at the end
try:
meta = probe(str(f))
except SystemExit:
entry["steps"].append({"step": "probe", "ok": False, "seconds": 0, "error": "ffprobe failed"})
results.append(entry)
continue
+ finally:
+ STATE.json = was_json
entry["probe"] = {k: meta.get(k) for k in ("duration", "format")}
entry["probe"]["video"] = {k: (meta.get("video") or {}).get(k) for k in ("codec", "width", "height", "fps", "pix_fmt", "hdr_format", "rotation", "variable_frame_rate_suspected")}
entry["probe"]["audio"] = {k: (meta.get("audio") or {}).get(k) for k in ("codec", "channels", "sample_rate")}
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 389cde5..c82de26 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1515,7 +1515,9 @@ class ContractTests(unittest.TestCase):
shutil.copyfile(self.src, bdir / "clip.mp4")
recipe = self.out("batch_recipe.json")
recipe.write_text(json.dumps({"glob": "*.mp4", "steps": [["fit.py", "{in}", "--aspect", "1:1", "-o", "{out}"]]}), encoding="utf-8")
- proc = subprocess.run([sys.executable, str(SCRIPTS / "batch.py"), "bdir", "--recipe", str(recipe), "--dry-run", "--json"],
+ # a real (fast) run: since the sweep fixes a --dry-run leaves no directory behind, so the
+ # placement of the default outdir is only visible after a write
+ proc = subprocess.run([sys.executable, str(SCRIPTS / "batch.py"), "bdir", "--recipe", str(recipe), "--fast", "--json"],
cwd=str(self.work), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
self.assertEqual(proc.returncode, 0, proc.stderr[-400:])
self.assertFalse((bdir / "bdir").exists(), "outdir was doubled")
@@ -1622,6 +1624,105 @@ class ContractTests(unittest.TestCase):
proc = tool("sync", self.src, self.src, "--analyze-seconds", "5000", "--json", check=False)
self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ def test_boundary_sweep_regressions(self):
+ """Pins from the 561-run boundary sweep (2026-09-12). F1: two runs on one -o both said
+ completed while one described the other's file -- a lock file next to the output refuses
+ the second (a dead-pid lock is taken over). F2/F3: cut's re-encode and pad --start copied a
+ subtitle track with stale timestamps -- dropped and reported. F7: render --dry-run planned
+ a missing clip. F6: verify printed two JSON documents for a non-media input. F8: odd
+ source dimensions failed 15 tools with "not divisible by 2" -- run() retries with an even
+ scale. F9: redact's default blur radius failed on regions under 40 px. F10: color
+ --correct/--lut tagged PQ pixels as BT.709 without a tone map. F19: loudness
+ --measure-only --json was a bare dict. F12: an unwritable output directory is kind input."""
+ # F1
+ lock = self.out(".lock_victim.mp4.ffskill-lock"); lock.write_text(str(os.getpid()))
+ proc = tool("cut", self.src, "--start", "0", "--end", "1", "--json", "-o", self.out("lock_victim.mp4"), check=False)
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"]), ("failed", "input"))
+ self.assertIn("another run is writing", doc["error"]["message"])
+ lock.write_text("999999")
+ doc = json.loads(tool("cut", self.src, "--start", "0", "--end", "1", "--json", "-o", self.out("lock_victim.mp4")).stdout)
+ self.assertEqual(doc["status"], "completed")
+ self.assertFalse(lock.exists(), "the lock must be released after the run")
+ # F2 / F3
+ srt = self.out("sw.srt"); srt.write_text("1\n00:00:00,500 --> 00:00:01,000\na\n\n2\n00:00:02,000 --> 00:00:02,500\nb\n\n", encoding="utf-8")
+ mkv = self.out("sw_in.mkv")
+ ffmpeg("-i", self.src, "-i", srt, "-map", "0", "-map", "1", "-c", "copy", "-c:s", "srt", mkv)
+ doc = json.loads(tool("cut", mkv, "--start", "0.5", "--end", "1.5", "--accurate", "--fast", "--json", "-o", self.out("sw_cut.mkv")).stdout)
+ self.assertTrue(doc["dropped_non_av_streams"])
+ self.assertAlmostEqual(doc["probe"]["duration"], 1.0, delta=0.15)
+ doc = json.loads(tool("pad", mkv, "--start", "1", "--fast", "--json", "-o", self.out("sw_pad.mkv")).stdout)
+ self.assertTrue(doc["dropped_non_av_streams"])
+ self.assertEqual(doc["probe"].get("subtitle_streams") or 0, 0)
+ # F7
+ proj = self.out("sw_missing.json"); proj.write_text(json.dumps({"output": str(self.out("sw_r.mp4")), "clips": [{"src": str(self.out("nope.mp4"))}]}))
+ proc = tool("render", proj, "--dry-run", "--json", check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ # F6
+ txt = self.out("notmedia.txt"); txt.write_text("x")
+ proc = tool("verify", txt, "--quick", "--out", self.out("sw_v"), "--json", check=False)
+ self.assertEqual(proc.stdout.count('"status"'), 1, proc.stdout[:300])
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "verification")
+ # F8
+ odd = self.out("odd.mp4")
+ ffmpeg("-f", "lavfi", "-i", "testsrc2=size=641x359:rate=30", "-f", "lavfi", "-i", "sine=f=440:r=48000", "-t", "2", "-pix_fmt", "yuv444p", "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac", odd)
+ for name, extra in (("cut", ["--start", "0.5", "--end", "1.5", "--accurate"]), ("fit", ["--duration", "1"]), ("color", ["--correct", "--exposure", "0.2"]), ("overlay", ["--text", "hi"])):
+ doc = json.loads(tool(name, odd, *extra, "--fast", "--json", "-o", self.out(f"odd_{name}.mp4")).stdout)
+ self.assertEqual(doc["status"], "completed", name)
+ self.assertEqual((doc["probe"]["video"]["width"] % 2, doc["probe"]["video"]["height"] % 2), (0, 0), name)
+ # F9
+ doc = json.loads(tool("redact", self.src, "--x", "10", "--y", "10", "--width", "30", "--height", "30", "--mode", "blur", "--fast", "--json", "-o", self.out("sw_red.mp4")).stdout)
+ self.assertEqual(doc["status"], "completed")
+ # F10
+ hdr = self.out("sw_hdr.mp4")
+ # the VUI colour tags must go through x265-params: newer builds (7.1 apt, 8.x brew/choco)
+ # do not carry -color_trc & co. into the libx265 encoder, and the fixture came out SDR
+ ffmpeg("-f", "lavfi", "-i", "testsrc2=size=64x64:rate=30", "-t", "1", "-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-preset", "ultrafast", "-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc", "-tag:v", "hvc1", hdr)
+ proc = tool("color", hdr, "--correct", "--exposure", "0.2", "--fast", "--json", "-o", self.out("sw_col.mp4"), check=False)
+ doc = json.loads(proc.stdout)
+ self.assertEqual(doc["error"]["kind"], "input")
+ self.assertIn("--to-sdr", doc["error"]["message"])
+ # F19
+ doc = json.loads(tool("loudness", self.src, "--measure-only", "--json").stdout)
+ self.assertEqual(doc["status"], "completed")
+ self.assertIn("input_i", doc["measured"])
+ # F12 (permissions do not bind root)
+ if hasattr(os, "geteuid") and os.geteuid() != 0:
+ ro = self.out("ro_dir"); ro.mkdir(exist_ok=True); ro.chmod(0o555)
+ proc = tool("fit", self.src, "--aspect", "1:1", "--dry-run", "--json", "-o", ro / "x.mp4", check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+
+ def test_boundary_sweep_p3_regressions(self):
+ """Sweep P3s: export's HDR warning reaches --json (F11); graphics refuses a frame too small
+ for its templates (F16); insert refuses a video where it wants a still (F17); look builds
+ a sheet from a one-frame clip instead of printing "wrote" and then failing (F18); batch
+ --dry-run leaves no directories behind and render removes its auto work dir on failure (F15)."""
+ one = self.out("one_frame.mp4")
+ ffmpeg("-f", "lavfi", "-i", "testsrc2=size=64x64:rate=30", "-frames:v", "1", "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", one)
+ doc = json.loads(tool("look", one, "--tiles", "2x2", "--width", "200", "--json", "-o", self.out("one_sheet.png")).stdout)
+ self.assertEqual(doc["status"], "completed")
+ self.assertTrue(self.out("one_sheet.png").exists())
+ tiny = self.out("tiny16.mp4")
+ ffmpeg("-f", "lavfi", "-i", "testsrc2=size=16x16:rate=30", "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", tiny)
+ proc = tool("graphics", tiny, "--template", "lower-third", "--name", "x", "--fast", "--json", "-o", self.out("tiny_g.mp4"), check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ proc = tool("insert", self.src, "--duration", "1", "--width", "64", "--height", "64", "--fast", "--json", "-o", self.out("ins_vid.mp4"), check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ hdr = self.out("p3_hdr.mp4")
+ # the VUI colour tags must go through x265-params: newer builds (7.1 apt, 8.x brew/choco)
+ # do not carry -color_trc & co. into the libx265 encoder, and the fixture came out SDR
+ ffmpeg("-f", "lavfi", "-i", "testsrc2=size=64x64:rate=30", "-t", "1", "-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-preset", "ultrafast", "-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc", "-tag:v", "hvc1", hdr)
+ doc = json.loads(tool("export", hdr, "--preset", "youtube", "--fast", "--json", "-o", self.out("p3_ex.mp4")).stdout)
+ self.assertTrue(any("HDR" in n for n in doc.get("notes", [])), doc.keys())
+ bdir = self.out("p3_batch"); bdir.mkdir(exist_ok=True); shutil.copyfile(self.src, bdir / "clip.mp4")
+ recipe = self.out("p3_recipe.json"); recipe.write_text(json.dumps({"glob": "*.mp4", "steps": [["fit.py", "{in}", "--aspect", "1:1", "-o", "{out}"]]}))
+ doc = json.loads(tool("batch", bdir, "--recipe", recipe, "--dry-run", "--json").stdout)
+ self.assertEqual(doc["status"], "completed")
+ self.assertFalse((bdir / "out").exists(), "batch --dry-run left its output directory behind")
+ proj = self.out("p3_missing.json"); proj.write_text(json.dumps({"output": str(self.out("p3_r.mp4")), "clips": [{"src": str(self.out("nope.mp4"))}]}))
+ tool("render", proj, "--json", check=False)
+ self.assertEqual([p.name for p in self.work.glob("p3_r_work_*")], [], "render left its work dir after a failure")
+
def test_cut_segments_refuses_output_equal_to_input(self):
"""Fourth review, P0: `cut.py in.mp4 --segments 0-1,2-3 -o in.mp4` replaced the source
with the 2 s join. The run() guard compares the ffmpeg command's -i paths with its output,