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.

cut.py --segments: fade the sound at every join the re-encode makes (#364)

Shogo Kajiyama6d8934b210fb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b8ea9c..5d76e07 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@
## Unreleased
+### Fixed
+
+- **`cut.py --segments` joins no longer click.** Every join the re-encode makes now fades the sound 20 ms on each side. Before, two cuts butted together left a step in the waveform that played as a click: on a 440 Hz tone the step was 14x the tone's own largest. `--declick-ms` sets the length, `--no-declick` restores the butt join, and the result reports `declick_ms`. A stream-copy join copies the sound and is not faded.
+
### Documentation
- **A project site on GitHub Pages.** `pages.yml` publishes https://kajisho5.github.io/ffmpeg-skill/ on every push to `main` that touches the docs. `.github/scripts/build_pages.py` assembles the site from the repository's own Markdown: the README, the demo gallery, the contract, the design decisions, the roadmap and this changelog. It rewrites relative links and copies the images they use, so nothing on the site is written by hand. A relative link to a file that does not exist fails the build, and `test_pages_site_builds_with_no_dead_links` runs the same build in CI.
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 3642313..583f3bc 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -47,6 +47,7 @@ exists. When a decision changes, edit the entry in the same PR.
- [2.15.0 — render.py's intermediate stages encode with veryfast](#2150--renderpys-intermediate-stages-encode-with-veryfast)
- [2.16.0 — intermediates at superfast, not ultrafast](#2160--intermediates-at-superfast-not-ultrafast)
- [2.17.0 — check.py --content's dropouts row](#2170--checkpy---contents-dropouts-row)
+- [2.17.2 — cut.py fades the sound at every --segments join it re-encodes](#2172--cutpy-fades-the-sound-at-every---segments-join-it-re-encodes)
<!-- contents:end -->
## Time limits
@@ -2109,3 +2110,18 @@ What was decided there:
a second silencedetect in the main pass logs under the same name as the silence row's, and
their lines could not be told apart. Code: `_common.probe._detect_dropouts()`. Test:
`test_check_content_dropouts_row`.
+
+## 2.17.2 — cut.py fades the sound at every --segments join it re-encodes
+
+- **A re-encoded `--segments` join fades the sound 20 ms on each side, by default.** Two cuts
+ butted together leave a step in the waveform wherever the sound was not at zero on both sides,
+ and a step plays as a click. Measured on a 440 Hz tone, the step at the join was 14x the tone's
+ own largest sample-to-sample change. 20 ms is too short to hear as a dip and long enough to
+ remove the step. Only the sides that meet another segment are faded: the file's own start and
+ end stay as cut. A stream-copy join copies the sound and cannot fade it without re-encoding the
+ sound, which would make a lossless join lossy, so it is left as it was. The result's
+ `declick_ms` reports the fade (null when no join was re-encoded), and `--no-declick` restores
+ the butt join. `silence.py` is not changed: it cuts inside silence, where the sound is already
+ near zero on both sides. Code: `cut._join_chunk()`, `DECLICK_S`. Test:
+ `test_cut_segments_join_is_faded_so_it_does_not_click`.
+
diff --git a/references/scripts.md b/references/scripts.md
index 28566a6..fba50ae 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -64,7 +64,7 @@ own clock, `null` when unknown). `--compact` gives one line per file.
### cut.py — cut / join segments
```
-cut.py INPUT [--start T] [--end T | --duration T] [--segments A-B,C-D,...] [--accurate] [--edit-list] [--keep-hevc] [--vfr-guard average|sampled|off] [-o OUT]
+cut.py INPUT [--start T] [--end T | --duration T] [--segments A-B,C-D,...] [--accurate] [--declick-ms 20 | --no-declick] [--edit-list] [--keep-hevc] [--vfr-guard average|sampled|off] [-o OUT]
cut.py INPUT --start T --end T --snap beats [--snap-tolerance 0.12] [--snap-source FILE] [--min-confidence 0.5]
```
Times accept `12.5`, `1:30`, `00:01:30.250`. Default is `-c copy` (snaps to
@@ -75,7 +75,7 @@ keyframes, instant, lossless); if the snapped result deviates more than
`--codec` overrides all of them). `--accurate` always re-encodes; `--tolerance -1` never does for a keyframe snap
(a `--segments` join of open-GOP video, one whose later B-frame `.mp4`/`.mov` segment starts
between keyframes, or one that fails its check, still re-cuts).
-Multiple segments are concatenated in the order given. stderr reports whether
+Multiple segments are concatenated in the order given. Since 2.17.2 every join the re-encode makes fades the sound for `--declick-ms` (20 ms) on each side, so butted cuts do not click; `--no-declick` butts them as before, and a stream-copy join (sound copied) is not faded. The result reports `declick_ms` (null when there was no re-encoded join). stderr reports whether
the result was "lossless stream copy" or "re-encoded"; when the snap forced a
re-encode, the result's `lossless_alternative` names the nearest keyframe
`--start` that would stream-copy instead, so the trade can be offered.
diff --git a/scripts/_contract.py b/scripts/_contract.py
index ac5602d..c7b10b4 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -637,6 +637,7 @@ def output_schema(name: str, meta: Dict[str, Any], hw: bool = False) -> Dict[str
"vfr_check": {"type": "object", "description": "the sampled frame timing of a video input that could still stream-copy: under --vfr-guard average (the default) only when its nominal and average frame rates differ, which re-encodes it (reason vfr) whatever the sample says; under sampled or off on every such input (absent for audio-only input or output, --accurate, --codec, or a --dry-run input a plan has not written yet): {heuristic: true, measured, method: \"sampled\", guard, windows, deltas}. measured is sampled_cfr (every packet interval in up to five 6 s windows within a tick, at least 1 ms and at most half a frame, of its window's median, and the windows agree; the file-start window's first interval is ignored), vfr (under sampled, forces a re-encode, reason vfr) or inconclusive (fewer than 20 intervals or ffprobe failed; under sampled, reason vfr_inconclusive). --vfr-guard off keeps the copy either way, with a note. Variable timing between the windows is not seen"},
"lossless_alternative": {"type": ["string", "null"], "description": "when a lossless cut re-encoded because of the keyframe snap: the --start that would stream-copy instead, and how far it is from the request"},
"join_check": {"type": ["object", "null"], "description": "--segments video stream-copy join: the written file measured by demuxing, {packets, expected_packets, max_step_seconds, audio_offset_ms, audio_parts_checked, ok}. expected_packets counts the source's video packets from each part's start keyframe to its end (or the end of the video); max_step_seconds is the largest presentation step (null when vfr_check measured anything but sampled_cfr, e.g. a --vfr-guard off join of variable timing, which checks the count only), and each step at a join must be the step its parts predict within 1 ms; audio_offset_ms is, per part, its sound's shift minus its picture's (+ = sound late) from audio packets matched by CRC32 to the source stream shaped like the joined audio (FFmpeg's default selection may copy one other than a:0; an MPEG-TS source's AAC is hashed without its ADTS headers) (null for a part with no unique match, e.g. digital silence; null as a whole when the source has no audio or the video check failed), and audio_parts_checked counts the measured parts; ok is the conjunction (counts, steps, every measured part within 5 ms), and false means the join was re-cut from the source (concat_fallback) and this is the failed measurement. null for a single segment, audio, --dry-run, --accurate/--codec/a forced re-encode, a segment that re-encoded, or a join that fell back before a copy join was attempted (open GOPs, a later B-frame segment starting between keyframes, parts that differ, a concat error)"},
+ "declick_ms": {"type": ["number", "null"], "description": "--segments joined by the re-encode (--accurate, a forced re-encode or concat_fallback): the fade in ms asked for on each side of every join, so butted cuts do not click (20 by default, --declick-ms; 0 under --no-declick; the file's own start and end are not faded). Each fade is capped at half its segment, so a segment shorter than twice this is faded for half its length. null when there is no join to fade: a single segment, a source with no audio, or a stream-copy join, whose sound is copied and not faded"},
"segment_end_snap_seconds": {"type": ["array", "null"], "items": {"type": ["number", "null"]}, "description": "--segments stream-copy join: per segment, the signed seconds its end moved to the keyframe the copied part stops at (the first keyframe at or after the requested end, never an earlier one; null for a part that runs to the end of the video, a part of a source with no B-frames, which is cut to its requested end as in every 2.x release, or a Matroska/MPEG-TS part, which is not snapped). null as a whole unless the output is those copied parts: a single segment, audio, --dry-run, or any re-encode or fallback"}}
elif name == "multicam":
extra = {"cuts": {"type": "array", "description": "[[start, end, camera], ...] on the reference timeline: the camera actually rendered. A range whose camera had not started yet plays camera 0, and diagnostics.fallbacks names the camera asked for (code camera_not_started)"},
diff --git a/scripts/cut.py b/scripts/cut.py
index 55cda87..a17d679 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -48,6 +48,7 @@ Examples:
import argparse
import contextlib
import json
+import math
import os
import sys
import tempfile
@@ -908,6 +909,11 @@ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: i
# The most segments one fallback ffmpeg call opens: every segment is its own input (a file handle,
# a demuxer and a decoder each), and macOS shells default to 256 open files.
JOIN_CHUNK = 32
+# Seconds of fade on each side of every --segments join the re-encode makes (--declick-ms / --no-declick).
+# Butting two cuts together leaves a step in the waveform wherever they were not both at zero, which
+# plays as a click: measured on a 440 Hz tone, the step at the join was 14x the tone's own largest
+# sample-to-sample change. A 20 ms fade is too short to hear as a dip and long enough to remove it.
+DECLICK_S = 0.02
# how far before a segment the fallback seeks, so a start inside the B-frame reorder delay before a
# keyframe still decodes from the keyframe BEFORE it
SEEK_MARGIN = 1.0
@@ -1017,7 +1023,8 @@ def _grid_at_or_after(t: float, v0: float, rate: float) -> float:
def _join_chunk(src: str, segments: List[Tuple[float, float]], dst: str, meta: dict, crf: int, preset: str,
- has_v: bool, intermediate: bool = False, vend=None, hold=frozenset(), first: int = 0) -> List[str]:
+ has_v: bool, intermediate: bool = False, vend=None, hold=frozenset(), first: int = 0,
+ total=None) -> List[str]:
"""Re-cut `segments` from the source into one file through the concat filter, returning the codec
arguments it encoded with. Each segment is
its own seeked input, so both of its streams start at the segment's origin (0); neither is
@@ -1072,8 +1079,16 @@ def _join_chunk(src: str, segments: List[Tuple[float, float]], dst: str, meta: d
graph.append(f"[{i}:v:0]{pad}trim=start={a - half:.6f}:end={b - half:.6f},setpts=PTS-{a:.6f}/TB[v{i}]")
pads += f"[v{i}]"
if has_a:
+ # fade only the sides that meet another segment: the file's own start and end stay as cut
+ n = first + i
+ fade = min(DECLICK_S, (b - a) / 2)
+ fades = ""
+ if fade > 0 and n > 0:
+ fades += f",afade=t=in:st=0:d={fade:.6f}"
+ if fade > 0 and n < (len(segments) if total is None else total) - 1:
+ fades += f",afade=t=out:st={b - a - fade:.6f}:d={fade:.6f}"
graph.append(f"[{i}:a:0]atrim=start={a:.6f}:end={b:.6f},asetpts=PTS-{a:.6f}/TB,"
- f"aresample=async=1:first_pts=0[a{i}]")
+ f"aresample=async=1:first_pts=0{fades}[a{i}]")
pads += f"[a{i}]"
outs = ("[v]" if has_v else "") + ("[a]" if has_a else "")
graph.append(f"{pads}concat=n={len(segments)}:v={int(has_v)}:a={int(has_a)}{outs}")
@@ -1120,7 +1135,7 @@ def join_from_source(src: str, segments: List[Tuple[float, float]], dst: str, me
for k in range(0, len(segments), JOIN_CHUNK):
chunk = os.path.join(tmp, f"chunk{k // JOIN_CHUNK:03d}.mkv")
args = _join_chunk(src, segments[k:k + JOIN_CHUNK], chunk, meta, crf, preset, has_v, intermediate=True,
- vend=vend, hold=hold, first=k) or []
+ vend=vend, hold=hold, first=k, total=len(segments)) or []
if "-tag:v" in args:
tag[:] = args[args.index("-tag:v"):args.index("-tag:v") + 2]
out.append(chunk)
@@ -1287,6 +1302,7 @@ def _join_workspace():
def main() -> int:
+ global DECLICK_S
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input")
ap.add_argument("-o", "--output", help="output file (default: <name>_cut.<ext>)")
@@ -1306,6 +1322,11 @@ def main() -> int:
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 for a "
"keyframe snap; a --segments join is still re-cut for open GOPs, a later B-frame .mp4/.mov "
"segment starting between keyframes, or a failed join check)")
+ dc = ap.add_mutually_exclusive_group()
+ dc.add_argument("--declick-ms", type=float, default=DECLICK_S * 1000,
+ help="--segments: fade the sound this many ms on each side of every join the re-encode makes, so "
+ "butted cuts do not click (default %(default)g; a stream-copy join is not faded)")
+ dc.add_argument("--no-declick", action="store_true", help="--segments: butt the joins with no fade")
snap = ap.add_argument_group("beat snapping")
snap.add_argument("--snap", choices=["none", "beats"], default="none",
help="move each in/out point to the nearest measured beat (default none)")
@@ -1456,6 +1477,9 @@ def main() -> int:
args.accurate = True
forced.append("vfr" if measured == "vfr" else "vfr_inconclusive")
+ if not math.isfinite(args.declick_ms) or args.declick_ms < 0:
+ die(f"--declick-ms must be a finite number of ms, 0 or more, got {args.declick_ms:g}")
+ DECLICK_S = 0.0 if args.no_declick else args.declick_ms / 1000
outcomes: List[dict] = []
join_reencoded = False
join_check = None
@@ -1665,6 +1689,9 @@ def main() -> int:
segment_precision=report["segment_precision"],
edit_list=bool(single.get("edit_list")), stored_preroll_seconds=stored, av_start_skew_seconds=skew,
join_check=join_check, segment_end_snap_seconds=end_snaps,
+ # the joins were faded only where the concat filter re-encoded them
+ declick_ms=(DECLICK_S * 1000 if len(segments) > 1 and (join_reencoded or args.accurate) and meta.get("audio")
+ else None),
notes=notes, **({"vfr_check": vfr_check} if vfr_check else {}),
nearest_keyframes=sorted(NEAREST_KEYFRAMES) if NEAREST_KEYFRAMES else None,
# the trade the caller can offer instead of a re-encode (eval e02: "without losing quality")
diff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.json
index 706735b..0fdfcf7 100644
--- a/tests/fixtures/mcp_tools.json
+++ b/tests/fixtures/mcp_tools.json
@@ -315,6 +315,7 @@
"accurate",
"argv",
"codec",
+ "declick_ms",
"dry_run",
"duration",
"edit_list",
@@ -325,6 +326,7 @@
"json_brief",
"keep_hevc",
"min_confidence",
+ "no_declick",
"no_hw",
"output",
"overwrite",
diff --git a/tests/test_editing.py b/tests/test_editing.py
index c18aeb6..f6e745e 100644
--- a/tests/test_editing.py
+++ b/tests/test_editing.py
@@ -50,6 +50,43 @@ class EditingTests(MediaFixtures):
script("cut.py", self.src, "--segments", "1-3,6-9", "--accurate", "-o", out)
self.assertClose(probe(str(out))["duration"], 5.0, 0.15)
+ def test_cut_segments_join_is_faded_so_it_does_not_click(self):
+ """Butting two cuts of a tone left a step in the waveform at the join 14x the tone's own
+ largest sample-to-sample change: an audible click. Every join the re-encode makes is now
+ faded (--declick-ms, 20 by default); --no-declick keeps the old butt join."""
+ tone = OUT / "declick_tone.wav"
+ if not tone.exists():
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i",
+ "sine=f=440:d=4:sample_rate=48000", "-c:a", "pcm_s16le", tone)
+
+ def largest_step(path):
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-f", "s16le", "-ac", "1", "-"],
+ stdout=subprocess.PIPE, check=True).stdout
+ pcm = memoryview(raw).cast("h")
+ return max(abs(pcm[i + 1] - pcm[i]) for i in range(len(pcm) - 1))
+
+ own = largest_step(tone)
+ runs = {}
+ for name, extra in (("faded", ()), ("butted", ("--no-declick",))):
+ out = OUT / f"declick_{name}.wav"
+ runs[name] = json.loads(script("cut.py", tone, "--segments", "0-1.0011,2-3", "--accurate", *extra,
+ "-o", out, "--json").stdout)
+ runs[name]["step"] = largest_step(out)
+ self.assertEqual((runs["faded"]["declick_ms"], runs["butted"]["declick_ms"]), (20.0, 0.0))
+ self.assertLessEqual(runs["faded"]["step"], own * 1.1, runs)
+ self.assertGreater(runs["butted"]["step"], own * 2, runs)
+ # nothing to fade without sound, and a fade length that is not a number is refused
+ silent = OUT / "declick_silent.mp4"
+ if not silent.exists():
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i",
+ "color=c=gray:s=160x120:r=30:d=4", "-c:v", "libx264", silent)
+ data = json.loads(script("cut.py", silent, "--segments", "0-1,2-3", "--accurate", "-o",
+ OUT / "declick_silent_out.mp4", "--json").stdout)
+ self.assertIsNone(data["declick_ms"])
+ refused = script("cut.py", tone, "--segments", "0-1,2-3", "--accurate", "--declick-ms=nan",
+ "-o", OUT / "declick_nan.wav", expect_fail=True)
+ self.assertIn("finite", refused.stderr)
+
def test_cut_json_reports_requested_vs_actual_and_mode(self):
# exact-second cut on a keyframe-aligned GOP: expect a clean lossless copy
out = OUT / "cut_honest_copy.mp4"