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(cut): -reinit_filter 0 on every --segments --accurate input (#322)

Shogo Kajiyama8375657b8e31
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac55ceb..f69941d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,9 @@
## Unreleased
-(nothing yet)
+### Fixed
+
+- **`cut.py --segments --accurate` no longer hangs when a later segment crosses a mid-stream colour-tag change.** The concat re-cut opens the source once per segment; on FFmpeg 8.1.2 a source whose tags change partway (untagged to bt470bg/tv on a new SPS) deadlocked at 0% CPU in the second input's graph rebuild and ended at `--timeout` with nothing written. Every segment input now carries `-reinit_filter 0`, so the graph keeps its first format; the output's colour tags were already written explicitly, so no pixels change. A source whose frame size changes mid-stream is no longer refused cleanly by the concat filter (see `docs/design-decisions.md`) (#316).
## 2.8.3
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 4f6f852..ede8fd6 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -85,6 +85,27 @@ exists. When a decision changes, edit the entry in the same PR.
and `--force` on an untagged file; through 2.2.2 it ran on BT.2020 SDR too and darkened white
from Y 235 to 151. The result says which path ran (`sdr_path`, `notes`). Code:
`color.is_bt2020_sdr()`. Test: `test_to_sdr_bt2020_sdr_converts_gamut_without_tonemap`.
+- **`cut.py --segments --accurate` reads every segment with `-reinit_filter 0`, so a colour-tag change
+ inside the source is a label, not a conversion.** The re-cut feeds one `-ss -t -i src` input per
+ segment into one concat graph. By default FFmpeg rebuilds the graph at an input's buffer source when
+ its frames change colour tags; on 8.1.2 that rebuild at a *later* input deadlocked at 0% CPU (an
+ in-band SPS going from untagged to bt470bg/tv, #316), so a 36-segment job sat until `--timeout`.
+ With the option the graph keeps the format it was configured with and the retagged frames pass as
+ decoded. That is acceptable because the tool never converts colour in a cut: an SDR output is
+ tagged BT.709 explicitly and tag-only (`bt709_tag_args`; "without touching its pixels"), and an
+ untagged source is relabelled the same way, so the BT.601-tagged later segment is no different from
+ an untagged one. The rebuild would have converted the retagged side toward the graph's first (unknown)
+ tag (the issue's debug log: `csp:bt470bg -> csp:unknown`), not toward BT.709, so it was no closer to
+ the output's label. A BT.2020/HDR source
+ still takes the HDR path chosen from the first video stream's probe. The cost: a source whose
+ frame *size* or pixel format changes mid-stream is no longer refused by concat's own "parameters do
+ not match" error; on 6.1 the first-format graph then crashes or stalls the encoder (the stall is
+ bounded by `--timeout`). No other tool builds this structure: `join.py`, `multicam.py` and
+ `broll.py` open different files without `-ss`; `speedramp.py`, `freeze.py` and `loop.py` split one
+ input. Code: `cut._join_chunk()`. Test:
+ `test_every_segment_input_of_an_accurate_join_keeps_the_graph_format` (the planned command, any
+ FFmpeg) and `test_an_accurate_join_across_a_colour_tag_change_completes` (the run; it only fails
+ where the deadlock reproduces).
- **`escape_drawtext()` drops `'` and `%` from burnt-in text** instead of escaping them. Both
characters have no reliable escape across the FFmpeg versions in CI; a missing apostrophe is a
known limitation, a broken filter graph is not. Test: `test_drawtext_semicolon_and_quote_render_as_inert_literal_text`.
diff --git a/scripts/cut.py b/scripts/cut.py
index 13fffd2..9017ee3 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -1025,8 +1025,13 @@ def _join_chunk(src: str, segments: List[Tuple[float, float]], dst: str, meta: d
# land on that keyframe and lose its leading frames -- measured: -ss 9.9 on a keyint-60
# HEVC file began at 10.0 (seek_keyframe measures where a copy lands). Likewise an input -t stops reading at s+d in decode order and would drop
# B-frames that display inside the segment, so it reads a second past the end.
+ # -reinit_filter 0: every input is the same file, so the graph keeps the format it was
+ # configured with. A later input that decodes across a mid-stream colour-tag change (an
+ # in-band SPS going from untagged to bt470bg, say) made FFmpeg 8.1 rebuild the graph at
+ # that input's buffer source and deadlock at 0% CPU (#316); the output's colour tags are
+ # written explicitly (video_args), so the retag is a label here, not a conversion.
m = min(SEEK_MARGIN, s)
- cmd += ["-ss", f"{s - m:.6f}", "-t", f"{m + d + 1.0:.6f}", "-i", src]
+ cmd += ["-ss", f"{s - m:.6f}", "-t", f"{m + d + 1.0:.6f}", "-reinit_filter", "0", "-i", src]
a, b, half = m, m + d, 0.0
if has_v and rate:
# Both streams are cut on the source's frame grid: from the first frame at or after the
diff --git a/tests/test_cut_copy.py b/tests/test_cut_copy.py
index 544901b..d0400d4 100644
--- a/tests/test_cut_copy.py
+++ b/tests/test_cut_copy.py
@@ -15,6 +15,7 @@ import json
import math
import os
import re
+import shlex
import subprocess
import sys
import tempfile
@@ -24,7 +25,7 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _fixtures import OUT, SCRIPTS, script, sh # noqa: E402
-from _common import decision, probe # noqa: E402
+from _common import decision, ffmpeg_encoders, probe # noqa: E402
probe_mod = sys.modules["_common.probe"] # the module (the package re-exports probe() under its name)
sys.path.insert(0, str(SCRIPTS))
@@ -623,6 +624,53 @@ class CutJoinTests(unittest.TestCase):
self.assertFrameIs(frames[59], 59, "last frame of segment 0")
self.assertFrameIs(frames[60], 120, "first frame of segment 1 (4.0 s)")
+ def _retagged(self):
+ """The #316 source: 10 s untagged, then 10 s tagged bt470bg/tv, with the SPS repeated in-band,
+ stream-copied together, so a later segment's decode crosses a colour-tag change at 10 s."""
+ out = DIR / "retagged.mp4"
+ if out.exists():
+ return out
+ if "libx264" not in ffmpeg_encoders():
+ self.skipTest("this ffmpeg has no libx264")
+ part = ("-c:v", "libx264", "-preset", "ultrafast", "-g", "60", "-x264-params", "repeat-headers=1",
+ "-pix_fmt", "yuv420p")
+ a, b, lst = DIR / "retag_a.mp4", DIR / "retag_b.mp4", DIR / "retag.txt"
+ sh("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=320x180:r=30:d=10",
+ "-f", "lavfi", "-i", "sine=f=440:d=10", *part, "-c:a", "aac", "-shortest", a)
+ sh("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=320x180:r=30:d=10",
+ "-f", "lavfi", "-i", "sine=f=660:d=10", *part, "-colorspace", "bt470bg", "-color_range", "tv",
+ "-c:a", "aac", "-shortest", b)
+ lst.write_text(decision.concat_list_line(str(a)) + "\n" + decision.concat_list_line(str(b)) + "\n", encoding="utf-8")
+ sh("ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", out)
+ return out
+
+ def test_an_accurate_join_across_a_colour_tag_change_completes(self):
+ """#316: a segment that is not the first input and starts before a mid-stream colour-tag
+ change made FFmpeg 8.1 rebuild the graph at that input and deadlock at 0% CPU until
+ --timeout. The run completes within a short limit and has the length asked for. Where this
+ FFmpeg does not hang, the second test below still pins the flag that prevents it."""
+ src = self._retagged()
+ out = DIR / "retagged_join.mp4"
+ data = cut_json(src, "--segments", "0-3,9.5-13", "--accurate", "--preset", "ultrafast", "--timeout", "60", "-o", out)
+ self.assertEqual(data["status"], "completed")
+ self.assertEqual(data["mode"], "accurate")
+ self.assertLess(abs(data["output_duration"] - 6.5), 1 / FPS + 1024 / 48000, data["output_duration"])
+ self.assertEqual(len(frame_pts(out)), 195)
+ self.assertEqual(stderr_of_decode(out), "")
+ # the output's tags are the tool's own (bt709), whatever the source's later segment said
+ self.assertEqual(probe(str(out))["video"].get("color_space"), "bt709")
+
+ def test_every_segment_input_of_an_accurate_join_keeps_the_graph_format(self):
+ """The planned command puts -reinit_filter 0 before every segment's -i (#316), so it holds
+ on an FFmpeg where the colour-tag change does not deadlock (6.1) as on the one where it does."""
+ src = self._retagged()
+ data = cut_json(src, "--segments", "0-3,9.5-13,5-6", "--accurate", "--dry-run", "-o", DIR / "retagged_plan.mp4")
+ cmd = shlex.split(data["commands"][0])
+ inputs = [i for i, tok in enumerate(cmd) if tok == "-i"]
+ self.assertEqual(len(inputs), 3, cmd)
+ for i in inputs:
+ self.assertEqual(cmd[i - 2:i], ["-reinit_filter", "0"], cmd)
+
def test_the_last_segment_past_the_video_end_is_left_alone(self):
"""No join follows the last segment, so its sound-only tail is what the source had: no hold,
no pre-check fallback."""