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: loudness holds --tp in the written file; SIGINT/SIGTERM stop ffmpeg cleanly; apostrophes in filter paths (#184)

claude[bot]66739b585000
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6cc0b4a..d96cbdd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,9 @@
## Unreleased
-(nothing yet)
+- `loudness.py` holds its `--tp` ceiling in the file it writes, not just in loudnorm's float output: the written file is measured and, when a lossy encoder overshot (ffmpeg's AAC at 192k turned one transient of a 12-minute film from -2.4 to +3.7 dBFS, so `--tp -1` delivered +1.2 dBTP and `check.py`'s fix hint looped back), it re-encodes at 256k then 320k when `--audio-bitrate` was not pinned, then with the ceiling lowered by the overshoot. `result` carries `tp_ceiling_used`, `audio_bitrate_used`, `encodes` and a `note` when the loudness moved more than 1 LU.
+- SIGINT/SIGTERM stop the running ffmpeg (or sibling script), remove its partial output and exit with a failure document (`kind: interrupted`, exit 130/143). Before, SIGTERM killed only the Python parent and ffmpeg carried on as an orphan finishing a file nobody verified; SIGINT was a traceback with the partial left on disk.
+- A path with an apostrophe (`Ryo's Mac/cues.srt`, `lu't.cube`) reaches `subtitles=`, `ass=`, `lut3d=` and `fontsdir=` intact: `escape_filter_path` now writes the three backslashes the two-level filter parser needs for `'` (one was consumed as a quote, so ffmpeg opened `Ryos Mac/cues.srt`).
## 1.4.9
diff --git a/README.md b/README.md
index c3b8318..18a6a3b 100644
--- a/README.md
+++ b/README.md
@@ -293,7 +293,7 @@ The contract is generated from the code that runs, not maintained beside it. For
| `mutates_input` | always `false` |
| `idempotency_hint` | `bit_exact`, `content_equivalent`, `cached` or `environment_dependent` |
-`contract_version` (1.0) is separate from the skill version, so a consumer can pin the shape and read the version for provenance. The document also states the invocation mapping (structured arguments → argv), the JSON shapes for success and failure (`{"status": "failed", "error": {"kind": "input | ffmpeg | output | missing_tool | timeout | verification", "message": …}}`), and that no tool runs a shell or executes anything other than the named script, `ffmpeg` and `ffprobe`. Field-by-field reference: [docs/contract.md](docs/contract.md).
+`contract_version` (1.0) is separate from the skill version, so a consumer can pin the shape and read the version for provenance. The document also states the invocation mapping (structured arguments → argv), the JSON shapes for success and failure (`{"status": "failed", "error": {"kind": "input | ffmpeg | output | missing_tool | timeout | verification | interrupted", "message": …}}`), and that no tool runs a shell or executes anything other than the named script, `ffmpeg` and `ffprobe`. Field-by-field reference: [docs/contract.md](docs/contract.md).
### MCP
diff --git a/SKILL.md b/SKILL.md
index 87bb69a..603b365 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -265,7 +265,7 @@ 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.
+Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification | interrupted, "message": ...}}` with `--json` and exits non-zero; quote the message, do not paraphrase it into a success.
## Things that look right but are wrong
diff --git a/docs/contract.md b/docs/contract.md
index 5094acf..316da7c 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -309,7 +309,7 @@ before, and, when `--json` was given, on stdout:
```json
{"status": "failed", "exit_code": 1,
- "error": {"kind": "input | ffmpeg | output | missing_tool | timeout | verification", "message": "...",
+ "error": {"kind": "input | ffmpeg | output | missing_tool | timeout | verification | interrupted", "message": "...",
"code": "INPUT_INVALID | DEPENDENCY_MISSING | FFMPEG_EXECUTION_FAILED | OUTPUT_INVALID | TIMEOUT | VERIFICATION_FAILED | INTERNAL_ERROR",
"retryable": false},
"commands": ["ffmpeg ..."]}
diff --git a/references/scripts.md b/references/scripts.md
index e3feb09..ba31a16 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -596,6 +596,13 @@ loudness.py INPUT [-I -14] [--tp -1] [--lra 11] [--measure-only] [-o OUT]
Two-pass `loudnorm`: measure, then apply with measured values (linear mode when
the true-peak ceiling allows). Video is stream-copied; audio becomes AAC in
video containers or the codec matching the extension (.wav → PCM, .flac, .mp3).
+The written file is measured again: a lossy encoder can push peaks past the
+ceiling loudnorm held (ffmpeg's AAC at 192k turned one transient from -2.4 to
++3.7 dBFS). When it does, the tool re-encodes -- first at 256k then 320k if you
+did not pass `--audio-bitrate`, then with the loudnorm ceiling lowered by the
+overshoot -- until the file itself meets `--tp`. `result` reports
+`tp_ceiling_used`, `audio_bitrate_used`, `encodes`, and a `note` when the
+integrated loudness ended more than 1 LU from the target because of it.
### export.py — delivery presets
```
diff --git a/scripts/_common.py b/scripts/_common.py
index a1b2076..03048a6 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -64,6 +64,7 @@ ERROR_CODE = {
"output": "OUTPUT_INVALID",
"timeout": "TIMEOUT",
"verification": "VERIFICATION_FAILED",
+ "interrupted": "INTERRUPTED",
}
# Wall-clock ceiling for one ffmpeg/ffprobe invocation, in seconds. A hung ffmpeg (a build
@@ -263,6 +264,66 @@ def apply_common(args: "argparse.Namespace") -> None:
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}")
+ install_signal_handlers()
+
+
+# The child processes this tool is waiting on right now (an ffmpeg, or a sibling script under
+# run_tool), with the command whose partial output would need removing. A signal handler
+# reads it; the runners keep it current. Before 1.4.9 a SIGTERM to the tool (a cancelled MCP
+# call, a supervisor's stop, a closed terminal) killed only the Python parent: ffmpeg carried on
+# as an orphan, finished a file nobody verified, and the caller got no JSON at all; SIGINT was a
+# KeyboardInterrupt traceback with the partial left on disk.
+_CHILDREN: List[Tuple[subprocess.Popen, Sequence[str]]] = []
+_SIGNALS_INSTALLED = False
+
+
+def _on_signal(signum: int, frame: Any) -> None:
+ import signal as _signal
+ name = {getattr(_signal, "SIGINT", None): "SIGINT", getattr(_signal, "SIGTERM", None): "SIGTERM"}.get(signum, str(signum))
+ for proc, cmd in list(_CHILDREN):
+ try:
+ proc.terminate() # ffmpeg exits promptly on SIGTERM; a sibling script runs this same handler
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ except OSError:
+ pass
+ if cmd:
+ _cleanup_partial_output(cmd)
+ _CHILDREN.clear()
+ die(f"interrupted by {name}: the running command was stopped and its partial output removed; nothing was written",
+ code=128 + signum, kind="interrupted")
+
+
+def install_signal_handlers() -> None:
+ """SIGINT/SIGTERM stop the child, remove its partial output and exit with a failure document
+ (kind: interrupted, exit 130/143). Main thread only; on Windows SIGTERM is never delivered,
+ SIGINT (Ctrl-C) is."""
+ global _SIGNALS_INSTALLED
+ if _SIGNALS_INSTALLED:
+ return
+ import signal as _signal
+ import threading
+ if threading.current_thread() is not threading.main_thread():
+ return
+ for sig in (getattr(_signal, "SIGINT", None), getattr(_signal, "SIGTERM", None)):
+ if sig is None:
+ continue
+ try:
+ _signal.signal(sig, _on_signal)
+ except (ValueError, OSError):
+ pass
+ _SIGNALS_INSTALLED = True
+
+
+def _watch(proc: subprocess.Popen, cmd: Sequence[str]) -> None:
+ _CHILDREN.append((proc, cmd))
+
+
+def _unwatch(proc: subprocess.Popen) -> None:
+ _CHILDREN[:] = [(p, c) for p, c in _CHILDREN if p is not proc]
def emit(output: Optional[str], **extra: Any) -> None:
@@ -534,9 +595,16 @@ def run_tool(argv: Sequence[str], *, per_call: Optional[float] = None) -> subpro
document (kind timeout, exit 124), so callers that parse the child's --json see a timeout
exactly as they would from the child itself."""
limit = child_limit(per_call)
+ child = subprocess.Popen([sys.executable] + list(argv), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ _watch(child, []) # a sibling script removes its own partial output; there is none of ours to clean
try:
- return subprocess.run([sys.executable] + list(argv), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=limit)
+ out, err = child.communicate(timeout=limit)
+ _unwatch(child)
+ return subprocess.CompletedProcess(child.args, child.returncode, out, err)
except subprocess.TimeoutExpired as e:
+ child.kill()
+ child.communicate()
+ _unwatch(child)
name = os.path.basename(str(argv[0]))
msg = f"{name} did not finish within {limit:.0f} s (4x the per-ffmpeg --timeout plus 60 s) and was killed"
doc = {"status": "failed", "exit_code": 124,
@@ -628,10 +696,18 @@ def _limit_for(cmd: Sequence[str]) -> Optional[float]:
def _run_captured(cmd: List[str], check: bool) -> subprocess.CompletedProcess:
"""Plain run with stdout/stderr captured."""
limit = _limit_for(cmd)
+ child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ _watch(child, cmd)
try:
- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=limit)
+ out, err = child.communicate(timeout=limit)
except subprocess.TimeoutExpired:
+ child.kill()
+ child.communicate()
+ _unwatch(child)
_timed_out(cmd, limit or 0)
+ finally:
+ _unwatch(child)
+ proc = subprocess.CompletedProcess(list(cmd), child.returncode, out, err)
if proc.returncode == 0 and _is_ffmpeg(cmd):
_remember_output(cmd)
if proc.returncode != 0:
@@ -671,6 +747,7 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
t0 = time.time()
limit = _limit_for(cmd)
proc = subprocess.Popen(full, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ _watch(proc, cmd)
assert proc.stdout is not None and proc.stderr is not None
lines: "queue.Queue[Optional[str]]" = queue.Queue()
err_chunks: List[str] = []
@@ -722,6 +799,7 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
proc.wait(timeout=(max(5.0, limit - (time.time() - t0)) if limit else None))
except subprocess.TimeoutExpired:
timed_out()
+ _unwatch(proc)
err_thread.join()
err = "".join(err_chunks)
clear_line()
@@ -1020,12 +1098,17 @@ def escape_filter_path(path: str) -> str:
written `D\\\\:/x.srt`; with a single backslash the second pass still splits at the colon and
ffmpeg reads `/x.srt` as the next option (`Unable to parse "original_size" option value`).
Backslashes are turned into forward slashes first (ffmpeg accepts them on Windows), so a backslash
- never has to be escaped itself; `'`, `,`, `;`, `[` and `]` are graph-level characters.
+ never has to be escaped itself; `,`, `;`, `[` and `]` are graph-level characters and survive with
+ one backslash. `'` is special: the graph parser also treats a quote as the start of a quoted
+ token, so a single `\\'` is consumed by the first pass and "Ryo's Mac/cues.srt" reaches the
+ filter as "Ryos Mac/cues.srt" (Unable to open ...). Three backslashes survive both passes
+ (measured on 6.1 and 7.1 with subtitles=, ass= and lut3d=file=).
"""
p = str(Path(path))
p = p.replace("\\", "/")
p = p.replace(":", "\\\\:")
- for ch in ("'", ",", ";", "[", "]"):
+ p = p.replace("'", "\\\\\\'")
+ for ch in (",", ";", "[", "]"):
p = p.replace(ch, "\\" + ch)
return p
diff --git a/scripts/_contract.py b/scripts/_contract.py
index f437a38..92dc44e 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -1040,7 +1040,7 @@ def build(detect: bool = True) -> Dict[str, Any]:
"json_output": {
"success": {"status": "completed", "exit_code": 0, "stdout": "one JSON document (output_schema)"},
"failure": {"status": "failed", "exit_code": "non-zero (127 when ffmpeg/ffprobe is missing)", "stdout": "{\"status\": \"failed\", \"exit_code\": N, \"error\": {\"kind\": ..., \"message\": ...}, \"commands\": [...]} when --json was given", "stderr": "human-readable message"},
- "error_kinds": {"input": "missing or unsuitable input, bad arguments", "ffmpeg": "ffmpeg/ffprobe returned an error (message carries the last stderr lines)", "output": "ffmpeg exited 0 but the artifact is missing, empty or unreadable (an empty file is removed)", "missing_tool": "ffmpeg or ffprobe not on PATH", "timeout": "one ffmpeg/ffprobe run exceeded --timeout (default 1800 s, FFMPEG_SKILL_TIMEOUT) and was killed; partial output removed; exit 124", "verification": "the tool ran but its result failed the requested check: check.py platform rows (checks attached), render.py's check stage (output written, check attached), batch.py items (results attached), verify.py steps (files attached); exit 1"},
+ "error_kinds": {"input": "missing or unsuitable input, bad arguments", "ffmpeg": "ffmpeg/ffprobe returned an error (message carries the last stderr lines)", "output": "ffmpeg exited 0 but the artifact is missing, empty or unreadable (an empty file is removed)", "missing_tool": "ffmpeg or ffprobe not on PATH", "timeout": "one ffmpeg/ffprobe run exceeded --timeout (default 1800 s, FFMPEG_SKILL_TIMEOUT) and was killed; partial output removed; exit 124", "verification": "the tool ran but its result failed the requested check: check.py platform rows (checks attached), render.py's check stage (output written, check attached), batch.py items (results attached), verify.py steps (files attached); exit 1", "interrupted": "the tool received SIGINT or SIGTERM: the running ffmpeg (or sibling script) was stopped and its partial output removed; exit 130 or 143"},
"success_criterion": "exit 0 AND the output exists AND is non-empty AND ffprobe reads a stream from it; only then is status completed printed and the output probe attached",
},
"capabilities": caps,
diff --git a/scripts/loudness.py b/scripts/loudness.py
index e1dcb14..2110824 100755
--- a/scripts/loudness.py
+++ b/scripts/loudness.py
@@ -50,7 +50,7 @@ def main() -> int:
ap.add_argument("--tp", type=float, default=-1.0, help="true peak ceiling in dBTP (default -1)")
ap.add_argument("--lra", type=float, default=11.0, help="loudness range target in LU (default 11)")
ap.add_argument("--measure-only", action="store_true", help="print the measured stats as JSON and exit")
- ap.add_argument("--audio-bitrate", default="192k", help="AAC bitrate when the container is video (default 192k)")
+ ap.add_argument("--audio-bitrate", default=None, help="AAC bitrate when the container is video (default 192k; raised to 256k/320k only when the encoder overshoots the true-peak ceiling and you did not pin it)")
ap.add_argument("--sample-rate", type=int, help="output sample rate (default: 48000; loudnorm upsamples internally to 192k)")
add_common(ap)
args = ap.parse_args()
@@ -80,24 +80,79 @@ def main() -> int:
)
sr = args.sample_rate or meta["audio"].get("sample_rate") or 48000
ext = os.path.splitext(output)[1].lower()
- cmd = ffmpeg_base() + ["-i", args.input, "-af", af, "-ar", str(sr)]
- if ext in AUDIO_CODECS or not meta.get("video"):
- cmd += ["-vn"] + audio_codec_for(output, args.audio_bitrate)
- else:
- cmd += ["-map", "0:v:0", "-map", "0:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", args.audio_bitrate]
- cmd.append(output)
- run(cmd)
+ bitrate_pinned = args.audio_bitrate is not None
+ bitrate = args.audio_bitrate or "192k"
+ def encode(tp: float, bitrate: str) -> None:
+ af = (
+ f"loudnorm=I={args.lufs}:TP={tp}:LRA={args.lra}"
+ f":measured_I={stats['input_i']}:measured_TP={stats['input_tp']}:measured_LRA={stats['input_lra']}"
+ f":measured_thresh={stats['input_thresh']}:offset={stats['target_offset']}:linear=true:print_format=summary"
+ )
+ cmd = ffmpeg_base() + ["-i", args.input, "-af", af, "-ar", str(sr)]
+ if ext in AUDIO_CODECS or not meta.get("video"):
+ cmd += ["-vn"] + audio_codec_for(output, bitrate)
+ else:
+ cmd += ["-map", "0:v:0", "-map", "0:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", bitrate]
+ cmd.append(output)
+ run(cmd)
+
+ encode(args.tp, bitrate)
if STATE.dry_run:
# pass 1 measured the input for real; there is no output to measure
emit(output, measured={k: stats[k] for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset", "silent")})
return 0
after = measure(output, args.lufs, args.tp, args.lra)
+ # loudnorm holds the ceiling on the float samples it outputs; the lossy encoder then adds
+ # its own overshoot. ffmpeg's native AAC at 192k turned one transient of a 12-minute film
+ # from -2.4 dBFS into +3.7 dBFS, so the file measured +1.2 dBTP after "--tp -1" and
+ # check.py's fix hint pointed straight back here. Two remedies, in this order: more bits
+ # (256k, then 320k: the overshoot is quantisation noise and shrinks with bitrate, and the
+ # loudness target is untouched) when the caller did not pin the bitrate; then a lower
+ # loudnorm ceiling by the measured overshoot, which in linear mode also lowers the
+ # integrated loudness -- reported, never hidden.
+ ceiling, rounds = args.tp, 0
+ steps = [] if bitrate_pinned or ext in AUDIO_CODECS and "aac" not in AUDIO_CODECS[ext] else [b for b in ("256k", "320k") if _kbps(b) > _kbps(bitrate)]
+ while not after.get("silent") and float(after["input_tp"]) > args.tp + 0.1 and rounds < 5:
+ rounds += 1
+ overshoot = float(after["input_tp"]) - args.tp
+ if steps:
+ bitrate = steps.pop(0)
+ info(f"true peak {float(after['input_tp']):.2f} dBTP exceeds the requested {args.tp:g} dBTP after encoding "
+ f"(codec overshoot); re-encoding at {bitrate}")
+ else:
+ ceiling -= overshoot + 0.2
+ info(f"true peak {float(after['input_tp']):.2f} dBTP exceeds the requested {args.tp:g} dBTP after encoding "
+ f"(codec overshoot); re-encoding with the loudnorm ceiling at {ceiling:.2f} dBTP")
+ encode(ceiling, bitrate)
+ after = measure(output, args.lufs, args.tp, args.lra)
if not after.get("silent"):
- info(f"result: {float(after['input_i']):.1f} LUFS, TP {float(after['input_tp']):.1f} dBTP (target {args.lufs} LUFS)")
- emit(output, result={k: after[k] for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset", "silent")})
+ info(f"result: {float(after['input_i']):.1f} LUFS, TP {float(after['input_tp']):.1f} dBTP (target {args.lufs} LUFS, TP <= {args.tp:g})")
+ result = {k: after[k] for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset", "silent")}
+ result["tp_ceiling_used"] = round(ceiling, 2)
+ if ext not in AUDIO_CODECS or "aac" in AUDIO_CODECS[ext]:
+ result["audio_bitrate_used"] = bitrate
+ result["encodes"] = rounds + 1
+ if not after.get("silent") and abs(float(after["input_i"]) - args.lufs) > 1.0:
+ result["note"] = (f"integrated loudness is {float(after['input_i']) - args.lufs:+.1f} LU from the target because the "
+ f"true-peak ceiling had to absorb the encoder's overshoot; a lossless delivery (wav/flac) or a pinned "
+ f"higher --audio-bitrate keeps both")
+ if not after.get("silent") and float(after["input_tp"]) > args.tp + 0.1:
+ die(f"true peak is still {float(after['input_tp']):.2f} dBTP after {rounds + 1} encodes (requested <= {args.tp:g}); "
+ f"the encoder overshoots more than the loudnorm ceiling can absorb at this bitrate",
+ kind="verification", output=output, result=result,
+ hint="raise --audio-bitrate (e.g. 256k) or deliver a lossless format (wav/flac) and let the platform encode")
+ emit(output, result=result)
return 0
+def _kbps(value: str) -> int:
+ v = value.lower().rstrip("k")
+ try:
+ return int(float(v)) if value.lower().endswith("k") else int(float(v)) // 1000
+ except ValueError:
+ return 0
+
+
if __name__ == "__main__":
sys.exit(main())
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 2ba1796..a3ef3c4 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1424,6 +1424,76 @@ class ContractTests(unittest.TestCase):
proc = tool("pad", self.src, "--start", "abc", "--json", "-o", self.out("pad_bad.mp4"), check=False)
self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ def test_filter_paths_with_apostrophes_open(self):
+ """Fourth review, P1: escape_filter_path wrote `\\'`, which the graph parser consumed as a
+ quote, so "Ryo's Mac/cues.srt" reached the subtitles filter as "Ryos Mac/cues.srt". Pin
+ the escaping and a real burn-in plus LUT through directories and names with apostrophes."""
+ self.assertEqual(_common.escape_filter_path("/a/Ryo's Mac/c.srt"), "/a/Ryo\\\\\\'s Mac/c.srt")
+ d = self.out("Ryo's Mac"); d.mkdir(exist_ok=True)
+ srt = d / "cu'es.srt"
+ srt.write_text("1\n00:00:00,000 --> 00:00:02,000\nhi\n\n", encoding="utf-8")
+ proc = tool("caption", self.src, "--srt", srt, "--fast", "--json", "-o", d / "ap'os.mp4")
+ self.assertEqual(proc.returncode, 0, proc.stderr[-400:])
+ cube = d / "id'ent.cube"
+ with open(cube, "w") as fh:
+ fh.write("LUT_3D_SIZE 2\n")
+ for b in (0, 1):
+ for g in (0, 1):
+ for r in (0, 1):
+ fh.write(f"{r:.1f} {g:.1f} {b:.1f}\n")
+ proc = tool("color", self.src, "--lut", cube, "--fast", "--json", "-o", d / "lu't.mp4")
+ self.assertEqual(proc.returncode, 0, proc.stderr[-400:])
+
+ def test_loudness_holds_true_peak_in_the_written_file(self):
+ """Fourth review, P1: loudnorm held -1 dBTP on its float output and the AAC encoder then
+ overshot (+1.2 dBTP on a real film, +3.4 on this square wave), so the file failed the
+ ceiling it was made to meet and check.py's fix hint pointed back at loudness.py. The
+ tool now measures the written file and re-encodes (more bits, then a lower ceiling)
+ until it meets --tp. A lossless output needs one encode."""
+ # 50 ms square-wave bursts once a second: quiet on average (so -14 LUFS leaves the peaks
+ # at the ceiling) with the hard edges the AAC encoder overshoots on
+ sq = self.out("square.wav")
+ ffmpeg("-f", "lavfi", "-i", "sine=f=1000:r=48000:d=6,aeval='sgn(val(0))*0.9*lt(mod(t\\,1)\\,0.05)'", "-c:a", "pcm_s16le", sq)
+ doc = json.loads(tool("loudness", sq, "-I", "-14", "--tp", "-1", "--json", "-o", self.out("square_norm.m4a")).stdout)
+ self.assertEqual(doc["status"], "completed")
+ r = doc["result"]
+ self.assertLessEqual(float(r["input_tp"]), -0.9, r)
+ self.assertGreater(r["encodes"], 1, "the first AAC encode was expected to overshoot")
+ doc = json.loads(tool("loudness", sq, "-I", "-14", "--tp", "-1", "--json", "-o", self.out("square_norm.wav")).stdout)
+ self.assertEqual(doc["result"]["encodes"], 1)
+ self.assertLessEqual(float(doc["result"]["input_tp"]), -0.9)
+
+ @unittest.skipIf(platform.system() == "Windows", "SIGTERM is not deliverable to a process on Windows; the handler is registered there for Ctrl-C only")
+ def test_sigterm_and_sigint_stop_ffmpeg_and_report_interrupted(self):
+ """Fourth review, P1: SIGTERM killed only the Python parent -- ffmpeg carried on as an
+ orphan and finished a file nobody verified, with no JSON; SIGINT was a KeyboardInterrupt
+ traceback with the partial left on disk. Now both stop the child, remove the partial and
+ print a kind: interrupted failure document (exit 130/143)."""
+ import signal
+ import time
+ long_src = self.out("long_src.mp4")
+ ffmpeg("-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-t", "40", "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", long_src)
+ for sig, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130)):
+ out = self.out(f"sig{code}.mp4")
+ p = subprocess.Popen([sys.executable, str(SCRIPTS / "fit.py"), str(long_src), "--aspect", "9:16", "--preset", "placebo", "--json", "-o", str(out)],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ deadline = time.time() + 30
+ while time.time() < deadline and not out.exists():
+ time.sleep(0.2)
+ self.assertTrue(out.exists(), "ffmpeg never opened the output")
+ time.sleep(1.0)
+ p.send_signal(sig)
+ stdout, stderr = p.communicate(timeout=60)
+ self.assertEqual(p.returncode, code, stderr[-400:])
+ self.assertNotIn("Traceback", stderr)
+ doc = json.loads(stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"], doc["exit_code"]), ("failed", "interrupted", code))
+ self.assertFalse(out.exists(), "partial output left behind")
+ # no orphaned ffmpeg writing that path
+ ps = subprocess.run(["pgrep", "-f", str(out)], stdout=subprocess.PIPE, text=True) if shutil.which("pgrep") else None
+ if ps is not None:
+ self.assertEqual(ps.stdout.strip(), "", "an ffmpeg is still running on the output")
+
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,