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: color --to-sdr keeps BT.2020 SDR bright; crossfaded joins keep sound with picture (#291)

Shogo Kajiyama1afbcbc15893
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b1acd44..fc071a1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,22 @@
## Unreleased
-(nothing yet)
+- `color.py --to-sdr` no longer tone-maps BT.2020 SDR input. A file with BT.2020 primaries on
+ an SDR transfer (bt709, bt2020-10) went through the PQ tone map, which took white from Y 235
+ to 151 and mid-grey from 126 to 90 and still reported `verified: true` -- and export, check,
+ verify and the gotchas all send wide-gamut SDR files there. It now gets a gamut conversion
+ only (its own transfer to linear, BT.2020 to BT.709 primaries, back to the BT.709 transfer);
+ PQ, HLG, Dolby Vision and `--force` on an untagged file are tone-mapped as before. The result
+ says which path ran in the new `sdr_path` key (`tonemap` / `gamut`) and in `notes`.
+- **join.py: a crossfaded join keeps each clip's sound with its picture.** Every clip now has one
+ length for both streams -- its video stream's, or its audio's when the sound runs more than a
+ frame past the picture -- and the shorter stream is padded to it (silence, or the last frame
+ held) before `xfade`/`acrossfade`, whose offsets both come from it. Clips with 5 s of picture
+ and 3 s of narration used to speak clip 2 at ~2.6 s instead of 4.5 s; audio longer than the
+ picture could lose a clip's picture; parts gained a frame or two per join from the container's
+ AAC tail. `verified` now includes a `duration` step comparing the output's video-stream length
+ with `expected_duration`, and `probe` reports each stream's own `duration`. The audio-only
+ join and `--transition none` build the same commands as before.
## 2.2.2
diff --git a/docs/contract.md b/docs/contract.md
index 3500095..b8d603c 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -492,6 +492,12 @@ Per-tool keys added in 1.18.0, all additive:
| `sources` | `sync.py` | `[{path, offset_s, confidence, drift_ppm}]`, one entry per SOURCE. Present for every run, including the original single-SOURCE shape (where it mirrors the top-level `second`/`offset_seconds`/`confidence` additively). With 2+ SOURCEs it is the *only* per-source shape: there is no top-level `second`/`offset_seconds` because there is no single pair to put there |
| `switch_mode`, `min_shot` | `multicam.py --switch energy` | `"energy"` and the `--min-shot` value used (default 1.5s), alongside the existing `cuts` (`[[start, end, camera], ...]`) which already carries the camera index for `--edl`'s companion cut list |
+Per-tool keys added after 2.2.2, all additive:
+
+| key | tool | what it holds |
+|---|---|---|
+| `sdr_path`, `notes` | `color.py --to-sdr` | `sdr_path` is `"tonemap"` for PQ / HLG / Dolby Vision input (and `--force` on an untagged file) or `"gamut"` for BT.2020 primaries on an SDR transfer, which is converted to BT.709 without a tone map (`--tonemap`/`--peak`/`--desat` do not apply); `notes` says which path was taken and why |
+
`check.py` also gains an informational `subtitles` row on **every** platform:
`PASS` when every soft subtitle stream carries a language tag, `WARN` when one
does not (or when there are none). Like `channels` and `chapters` it is never
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index ba8e466..43d546c 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -64,10 +64,16 @@ exists. When a decision changes, edit the entry in the same PR.
## Colour
- **A BT.2020-primaries stream is routed through the HDR (10-bit HEVC, tags preserved) path even
- when its transfer is SDR.** `probe` reports `hdr: true` with `hdr_format: "BT.2020 SDR"` for
- it. The alternative -- 8-bit BT.709 x264 -- would clip the wide gamut without a conversion.
- Changing the meaning of `hdr` is a 1.x contract change and waits for 2.0. Code:
- `_common.probe()` (`hdr = ...`), `_common.video_args()` docstring.
+ when its transfer is SDR.** `probe` reports it as `hdr: false`, `bt2020_or_hdr: true`,
+ `hdr_format: "BT.2020 SDR"` (see "`hdr` is a real HDR signal" below); the editing tools route
+ on `bt2020_or_hdr`. The alternative -- 8-bit BT.709 x264 -- would clip the wide gamut without a
+ conversion. Code: `_common.probe()`, `_common.video_args()` docstring.
+- **`color.py --to-sdr` converts such a stream's gamut without a tone map.** It is already SDR:
+ linearised with its own transfer, mapped to BT.709 primaries and re-encoded with the BT.709
+ transfer, white and grey stay where they were. The tone map is kept for PQ, HLG, Dolby Vision
+ 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`.
- **`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`.
@@ -596,11 +602,13 @@ not a new file format this tool would have to maintain.
`render.export_timeline()`, `_common/timeline.py`.
- **The timeline matches the project's numbers, not a render's.** A dissolve is centred on
each cut and trimmed `trim_head`/`trim_tail` frames either side, so the total is the sum of the
- clip lengths minus one transition per join -- what `join.py`'s xfade renders by design. A real
- render can come out a few frames longer, because `join.py` offsets each crossfade by the
- part's *container* duration (audio priming included); that is render's drift, recorded as a
- follow-up, and copying it into the timeline would hand an editor a cut nobody asked for.
- Test: `test_build_centres_each_dissolve_and_keeps_the_rendered_length`.
+ clip lengths minus one transition per join -- what `join.py`'s xfade renders by design. Since
+ the Unreleased fix after 2.2.2, `join.py` offsets each crossfade by the part's video-stream
+ length (its audio's only when the sound runs more than a frame past the picture), no longer
+ the *container* duration with its audio priming, so a render matches this total to the frame.
+ Tests: `test_build_centres_each_dissolve_and_keeps_the_rendered_length`,
+ `test_join_dissolve_of_short_parts_keeps_the_frame_count`,
+ `test_join_transition_keeps_each_clips_sound_with_its_picture`.
- **What a timeline cannot carry is reported, never dropped.** Captions, graphics, overlays,
the silence cut, fit, audio processing, loudness and the export preset go to
`timeline.not_exported` and stderr. A caption track or a title in FCPXML would be a second
diff --git a/references/scripts.md b/references/scripts.md
index 318da87..7fd1ac9 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -573,7 +573,11 @@ frame, rate or xfade offsets that rest on a pending input's unmeasured placehold
Normalises every clip to one frame size, fps, `yuv420p`, 48 kHz and one
channel layout (the widest clip's -- a 5.1 clip keeps 5.1 -- or `--channels`;
silent track generated for clips without audio), then chains `xfade` +
-`acrossfade`. Output length = sum of clips − transition × (n−1). Clips must be
+`acrossfade`. With a transition each clip has one length for picture and sound
+-- the video stream's, or the audio's when it runs more than a frame longer --
+and the shorter stream is padded (silence / last frame held), so every clip's
+sound stays with its picture. Output length = sum of clip lengths −
+transition × (n−1); `verified` checks the output's video-stream length against it. Clips must be
longer than 2 × the transition. Use `--transition none` for a plain cut.
A subtitle/data track in the source is not carried into the retimed/concatenated
output; the result says so with `dropped_non_av_streams: true`.
diff --git a/scripts/_common/probe.py b/scripts/_common/probe.py
index 7313cea..fb61d07 100644
--- a/scripts/_common/probe.py
+++ b/scripts/_common/probe.py
@@ -283,6 +283,8 @@ def probe(path: str, role: str = "input") -> Dict[str, Any]:
"color_range": video.get("color_range"),
"rotation": rotation,
"nb_frames": _to_int(video.get("nb_frames")),
+ # the stream's own length (a container's also counts audio priming and a longer track)
+ "duration": _to_float(video.get("duration")),
"bitrate": _to_int(video.get("bit_rate")),
}
if audio:
@@ -292,6 +294,7 @@ def probe(path: str, role: str = "input") -> Dict[str, Any]:
"channel_layout": audio.get("channel_layout"),
"sample_rate": _to_int(audio.get("sample_rate")),
"bitrate": _to_int(audio.get("bit_rate")),
+ "duration": _to_float(audio.get("duration")),
}
# every audio stream in file order: index n here is `-map 0:a:n` (audio.py --audio-stream n)
out["audio_streams"] = [{
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 5d91432..5d6dd5e 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -443,6 +443,11 @@ def output_schema(name: str, meta: Dict[str, Any]) -> Dict[str, Any]:
extra = {"measured": {"type": "object", "description": "the loudnorm measurement of the input (input_i, input_tp, input_lra, input_thresh, target_offset); with --measure-only it is the whole result"},
"targets": {"type": "object", "description": "the requested lufs / tp / lra"},
"result": {"type": "object", "description": "the written file measured again (input_i, input_tp, input_lra, ...), plus tp_ceiling_used, audio_bitrate_used and encodes"}}
+ elif name == "color":
+ extra = {"dropped_non_av_streams": {"type": "boolean"},
+ "sdr_path": {"enum": ["tonemap", "gamut"], "description": "--to-sdr only: tonemap for PQ / HLG / Dolby Vision (and --force on an untagged file); gamut for BT.2020 primaries on an SDR transfer, converted to BT.709 without a tone map"},
+ "notes": {"type": "array", "items": {"type": "string"}, "description": "--to-sdr only: which path was taken and why"},
+ "measurements": {"type": "object", "description": "--correct only: signalstats levels of input and output"}}
elif name == "cut":
extra = {"expected_duration": {"type": "number", "description": "seconds requested"},
"duration_error_ms": {"type": ["number", "null"], "description": "written minus requested, measured by ffprobe (null under --dry-run)"},
diff --git a/scripts/color.py b/scripts/color.py
index 1df79e6..e61acc3 100755
--- a/scripts/color.py
+++ b/scripts/color.py
@@ -169,12 +169,36 @@ def hdr_to_sdr_chain(meta: dict, tonemap: str, peak: float, desat: float) -> str
return ",".join(chain)
+def bt2020_sdr_to_bt709_chain(meta: dict) -> str:
+ """Gamut conversion only, for BT.2020 primaries on an SDR transfer (probe: `bt2020_or_hdr`
+ true, `hdr_signal` false). Such a file is already display-referred SDR: linearising it with
+ its own transfer, mapping the primaries to BT.709 and re-applying the BT.709 transfer keeps
+ white at white and grey at grey. The tone map the HDR chain adds would treat 100 % SDR white
+ as a fraction of a 1000-nit peak and darken the picture (white Y 235 -> 151, grey 126 -> 90)."""
+ v = meta["video"]
+ trc = v.get("color_transfer") or "bt709"
+ space = v.get("color_space") or "bt2020nc"
+ return ",".join([
+ f"zscale=tin={trc}:pin=bt2020:min={space}:rin={v.get('color_range') or 'tv'}:t=linear",
+ "format=gbrpf32le",
+ "zscale=p=bt709",
+ "zscale=t=bt709:m=bt709:r=tv",
+ "format=yuv420p",
+ ])
+
+
+def is_bt2020_sdr(v: dict) -> bool:
+ """BT.2020 primaries on a non-HDR transfer and no Dolby Vision: gamut-only --to-sdr."""
+ return bool(v.get("bt2020_or_hdr")) and not v.get("hdr_signal") and not v.get("dolby_vision") \
+ and v.get("color_transfer") not in ("smpte2084", "arib-std-b67")
+
+
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input")
ap.add_argument("-o", "--output", help="output file (default: <name>_sdr / _lut / _retag)")
mode = ap.add_mutually_exclusive_group(required=True)
- mode.add_argument("--to-sdr", action="store_true", help="tone-map HDR (PQ/HLG/BT.2020) to SDR BT.709")
+ mode.add_argument("--to-sdr", action="store_true", help="convert to SDR BT.709: tone-map HDR (PQ/HLG/Dolby Vision); BT.2020 primaries on an SDR transfer get a gamut conversion only, no tone map")
mode.add_argument("--lut", help=".cube LUT to apply (3D)")
mode.add_argument("--retag", choices=["bt709", "bt2020-pq", "bt2020-hlg", "bt601"], help="rewrite colour tags only (no re-encode)")
mode.add_argument("--strip-dovi", action="store_true", help="remove the Dolby Vision RPU (profile 8.4 iPhone clips) so players use the plain HLG/HDR10 base layer; stream copy")
@@ -183,7 +207,7 @@ def main() -> int:
ap.add_argument("--peak", type=float, default=1000.0, help="source peak brightness in nits used for PQ (default 1000)")
ap.add_argument("--desat", type=float, default=0.0, help="tonemap desaturation strength (default 0)")
ap.add_argument("--lut-strength", type=float, default=1.0, help="blend LUT result with the original, 0..1 (default 1)")
- ap.add_argument("--force", action="store_true", help="run --to-sdr even if the file is not tagged as HDR (treat as PQ)")
+ ap.add_argument("--force", action="store_true", help="run --to-sdr even if the file is tagged neither HDR nor BT.2020 (tone-mapped as PQ; a BT.2020 SDR file never needs it)")
ap.add_argument("--exposure", type=float, default=CORRECTION["exposure"][0], help="--correct: exposure in stops, -3..3 (default 0)")
ap.add_argument("--contrast", type=float, default=CORRECTION["contrast"][0], help="--correct: contrast, 0..2, 1=unchanged (default 1)")
ap.add_argument("--saturation", type=float, default=CORRECTION["saturation"][0], help="--correct: saturation, 0..2, 1=unchanged (default 1)")
@@ -278,10 +302,21 @@ def main() -> int:
return 0
measurements = None
+ sdr_extra: dict = {}
if args.to_sdr:
if not v.get("bt2020_or_hdr") and not args.force:
die(f"{args.input} is not tagged as HDR (transfer={v.get('color_transfer')}, primaries={v.get('color_primaries')}). Use --force to tone-map anyway.")
- vf = hdr_to_sdr_chain(meta, args.tonemap, args.peak, args.desat)
+ if is_bt2020_sdr(v):
+ vf = bt2020_sdr_to_bt709_chain(meta)
+ sdr_path = "gamut"
+ note = (f"BT.2020 primaries on an SDR transfer ({v.get('color_transfer')}): converted the gamut to BT.709 "
+ f"without a tone map (--tonemap/--peak/--desat do not apply)")
+ else:
+ vf = hdr_to_sdr_chain(meta, args.tonemap, args.peak, args.desat)
+ sdr_path = "tonemap"
+ note = f"tone-mapped {v.get('hdr_format') or 'untagged input as PQ (--force)'} to SDR BT.709 with {args.tonemap}"
+ info(f"note: {note}")
+ sdr_extra = {"sdr_path": sdr_path, "notes": [note]}
output = args.output or default_output(args.input, "sdr")
tag = "sdr"
elif args.correct:
@@ -323,7 +358,7 @@ def main() -> int:
r = probe(output, role="output")
info(f"wrote {output} ({fmt_secs(r['duration'])}, {r['video']['width']}x{r['video']['height']}, "
f"{r['video']['color_transfer']}/{r['video']['color_primaries']}, {tag})")
- extra = {"dropped_non_av_streams": dropped_streams}
+ extra = {"dropped_non_av_streams": dropped_streams, **sdr_extra}
if measurements is not None:
measurements["output"] = analyze_levels(output)
extra["measurements"] = measurements
diff --git a/scripts/join.py b/scripts/join.py
index cd93fbd..95b7374 100755
--- a/scripts/join.py
+++ b/scripts/join.py
@@ -63,6 +63,20 @@ def unpending_length(durs: List[float], d: float) -> Optional[float]:
return round(sum(durs) - d * (len(durs) - 1), 3)
+def clip_length(meta: Dict[str, Any], fps: float) -> float:
+ """The one length a clip holds in a crossfaded join, for its picture and its sound alike: the
+ video stream's, or the audio stream's when the sound runs more than a frame past the picture
+ (narration is never cut; an AAC tail adds no frame). The container duration (audio priming,
+ a longer track) is only the fallback when a stream length is unknown (a pending input)."""
+ v = (meta.get("video") or {}).get("duration")
+ a = (meta.get("audio") or {}).get("duration")
+ if not v:
+ return meta.get("duration") or 0.0
+ if a and fps and a > v + 1.0 / fps:
+ return a
+ return v
+
+
def expected_text(expected: Optional[float]) -> str:
"""unpending_length() as the stderr summary line puts it."""
return f"expected ~{expected:.3f}s" if expected is not None else "expected length unknown until the pending inputs exist"
@@ -293,7 +307,10 @@ def main() -> int:
w, h = w - (w % 2), h - (h % 2)
durs = [m.get("duration") or 0.0 for m in metas]
d = args.duration if args.transition != "none" else 0.0
- for p, dur in zip(args.inputs, durs):
+ # a crossfaded join gives each clip one length for both streams, so the offsets that place
+ # every picture also place its sound; the plain cut (concat) keeps the streams paired itself
+ lens = [clip_length(m, fps) for m in metas] if d else durs
+ for p, dur in zip(args.inputs, lens):
if d and dur <= d * 2 and not STATE.dry_run:
die(f"{p} is only {dur:.2f}s, too short for a {d:.2f}s transition; shorten --duration")
@@ -347,14 +364,22 @@ def main() -> int:
chain = "".join(f"[v{i}][a{i}]" for i in range(n))
parts.append(f"{chain}concat=n={n}:v=1:a=1[vout][aout]")
else:
- vprev, aprev = "v0", "a0"
+ # pad the shorter stream to the clip's length: the audio with silence, the picture by
+ # holding its last frame, then cut both there -- each xfade and acrossfade then starts
+ # at the same clip boundary instead of the audio chain drifting by every clip's gap
+ for i in range(n):
+ vlen = (metas[i].get("video") or {}).get("duration") or lens[i]
+ hold = f"tpad=stop_mode=clone:stop_duration={lens[i] - vlen:.3f}," if lens[i] > vlen else ""
+ parts.append(f"[v{i}]{hold}trim=duration={lens[i]:.3f}[vp{i}]")
+ parts.append(f"[a{i}]apad=whole_dur={lens[i]:.3f},atrim=duration={lens[i]:.3f}[ap{i}]")
+ vprev, aprev = "vp0", "ap0"
offset = 0.0
for i in range(1, n):
- offset += durs[i - 1] - d
+ offset += lens[i - 1] - d
vout = f"vx{i}" if i < n - 1 else "vout"
aout = f"ax{i}" if i < n - 1 else "aout"
- parts.append(f"[{vprev}][v{i}]xfade=transition={args.transition}:duration={d:g}:offset={offset:.3f}[{vout}]")
- parts.append(f"[{aprev}][a{i}]acrossfade=d={d:g}:c1=tri:c2=tri[{aout}]")
+ parts.append(f"[{vprev}][vp{i}]xfade=transition={args.transition}:duration={d:g}:offset={offset:.3f}[{vout}]")
+ parts.append(f"[{aprev}][ap{i}]acrossfade=d={d:g}:c1=tri:c2=tri[{aout}]")
vprev, aprev = vout, aout
# A pending input's stub is unmeasured (0x0, 0 fps, 0 s -- #77 keeps it honest rather than
@@ -367,12 +392,26 @@ def main() -> int:
"by its measured length")
output = args.output or default_output(args.inputs[0], "joined", "mp4")
cmd += ["-filter_complex", ";".join(parts), "-map", "[vout]", "-map", "[aout]"]
+ if d:
+ # the fps filter already made the picture constant-rate and xfade places every frame: FFmpeg
+ # 5.1's default cfr output mode still duplicated the last one to meet the AAC tail (a 51-frame
+ # dissolve came out 52), which newer builds no longer do -- pass the frames through as built
+ cmd += ["-fps_mode", "passthrough"]
cmd += video_args(hdr_meta or metas[0], args.crf, args.preset) + aac_args() + [output]
run(cmd)
- expected = unpending_length(durs, d)
+ expected = unpending_length(lens, d)
r = probe(output, role="output")
- info(f"wrote {output} ({fmt_secs(r['duration'])}, {expected_text(expected)}, {w}x{h} @ {fps:g}fps, {n} clips, {args.transition})")
+ # the picture is what the offsets place: measure the video stream, not the container (whose
+ # length also counts the AAC tail), against the length the clips add up to
+ measured = (r.get("video") or {}).get("duration") or r.get("duration")
+ verification = []
+ if expected is not None and measured is not None and not STATE.dry_run:
+ tol = max(1.5 / fps, 0.05)
+ verification.append({"step": "duration", "ok": abs(measured - expected) <= tol,
+ "measured": round(measured, 3), "expected": expected, "tolerance": round(tol, 3)})
+ info(f"wrote {output} ({fmt_secs(measured)}, {expected_text(expected)}, {w}x{h} @ {fps:g}fps, {n} clips, {args.transition})")
emit(output, mode="video", **reported(), clips=n, transition=args.transition, expected_duration=expected,
+ verification=verification,
dropped_non_av_streams=any(m.get("subtitle_streams") or m.get("data_streams") for m in metas))
return 0
diff --git a/tests/test_editing.py b/tests/test_editing.py
index 44e65e8..2967c6c 100644
--- a/tests/test_editing.py
+++ b/tests/test_editing.py
@@ -815,6 +815,64 @@ class EditingTests(MediaFixtures):
self.assertClose(probe(str(out2))["duration"], 16.0, 0.3)
script("join.py", self.src, expect_fail=True)
+ def _av_clip(self, out, picture, tone, freq, fps=30):
+ """A tiny clip: `picture` s of colour at `fps`, `tone` s of a sine at `freq` Hz, AAC audio."""
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", f"color=c=gray:s=64x48:r={fps}:d={picture}",
+ "-f", "lavfi", "-i", f"sine=f={freq}:d={tone}", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", out)
+ return out
+
+ @staticmethod
+ def _tone_onset(path, freq):
+ """When a tone at `freq` Hz is first heard: the end of the leading silence in a narrow band."""
+ proc = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", str(path), "-vn", "-af",
+ f"bandpass=f={freq}:width_type=q:w=8,bandpass=f={freq}:width_type=q:w=8,silencedetect=n=-35dB:d=0.1",
+ "-f", "null", "-"], capture_output=True, text=True)
+ ends = [float(x) for x in re.findall(r"silence_end: ([0-9.]+)", proc.stderr)]
+ return ends[0] if ends else 0.0
+
+ def test_join_transition_keeps_each_clips_sound_with_its_picture(self):
+ """Three clips of 5 s picture and 3 s of sound (a TTS line): each clip's sound must start
+ where its picture does, 4.5 s and 9.0 s with a 0.5 s fade. join.py used to chain the raw
+ audio lengths through acrossfade, so clip 2 spoke at ~2.5 s and clip 3 at ~5 s."""
+ d = OUT / "join_sync"
+ d.mkdir(exist_ok=True)
+ freqs = (500, 1300, 2900)
+ clips = [self._av_clip(d / f"c{f}.mp4", 5, 3, f) for f in freqs]
+ out = d / "synced.mp4"
+ doc = json.loads(script("join.py", *clips, "--transition", "fade", "--duration", "0.5", "--preset", "ultrafast",
+ "--json", "-o", out).stdout)
+ self.assertTrue(doc["verified"], doc["verification"])
+ for f, start in zip(freqs[1:], (4.5, 9.0)):
+ self.assertClose(self._tone_onset(out, f), start, 0.1, f"the {f} Hz clip's sound starts with its picture")
+ self.assertClose(probe(str(out))["video"]["duration"], 14.0, 0.05)
+
+ def test_join_transition_keeps_a_picture_shorter_than_its_sound(self):
+ """Audio past the picture: the clip lasts as long as its sound (the last frame held), so
+ the next clip's picture is neither lost nor started early, and `verified` measures the
+ video stream against the expected length."""
+ d = OUT / "join_long_audio"
+ d.mkdir(exist_ok=True)
+ a = self._av_clip(d / "a.mp4", 2, 3, 700)
+ b = self._av_clip(d / "b.mp4", 2, 2, 1900)
+ out = d / "long.mp4"
+ doc = json.loads(script("join.py", a, b, "--duration", "0.5", "--preset", "ultrafast", "--json", "-o", out).stdout)
+ self.assertEqual(doc["expected_duration"], 4.5)
+ self.assertTrue(doc["verified"], doc["verification"])
+ self.assertClose(probe(str(out))["video"]["duration"], 4.5, 0.05)
+ self.assertClose(self._tone_onset(out, 1900), 2.5, 0.1)
+
+ def test_join_dissolve_of_short_parts_keeps_the_frame_count(self):
+ """Two 1 s parts at 30 fps whose AAC sound runs 20 ms past the picture (a cut part) dissolved
+ over 0.3 s: 30 + 30 - 9 = 51 frames. Offsetting by the container length added frames and
+ cut the dissolve short."""
+ d = OUT / "join_frames"
+ d.mkdir(exist_ok=True)
+ a = self._av_clip(d / "a.mp4", 1, 1.02, 440)
+ b = self._av_clip(d / "b.mp4", 1, 1.02, 880)
+ out = d / "parts.mp4"
+ script("join.py", a, b, "--transition", "dissolve", "--duration", "0.3", "--preset", "ultrafast", "-o", out)
+ self.assertEqual(probe(str(out))["video"]["nb_frames"], 51)
+
def test_join_two_or_more_audio_less_clips(self):
"""Every no-audio clip gets a synthetic silent audio track added as an extra ffmpeg input (join.py
builds this itself, not this test's fixtures) -- `idx` must be this ffmpeg input's actual position
diff --git a/tests/test_picture.py b/tests/test_picture.py
index 8ff51c0..dcc39eb 100644
--- a/tests/test_picture.py
+++ b/tests/test_picture.py
@@ -994,6 +994,33 @@ class PictureTests(MediaFixtures):
# refuses on SDR input unless forced
script("color.py", self.src, "--to-sdr", expect_fail=True)
+ def test_to_sdr_bt2020_sdr_converts_gamut_without_tonemap(self):
+ """BT.2020 primaries on an SDR transfer are not HDR: --to-sdr converts the gamut only.
+ It used to tone-map them as PQ, darkening white Y 235 -> 151 and grey 126 -> 90 while
+ still reporting verified: true. White and grey must come out where they went in."""
+ wide = OUT / "bt2020_sdr_levels.mp4"
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=white:size=320x120:rate=30",
+ "-f", "lavfi", "-i", "color=c=0x808080:size=320x120:rate=30", "-t", "1",
+ "-filter_complex", "[0][1]vstack,format=yuv420p10le", "-c:v", "libx265", "-preset", "ultrafast",
+ "-x265-params", "colorprim=bt2020:transfer=bt709:colormatrix=bt2020nc:log-level=error", "-tag:v", "hvc1", wide)
+
+ def luma(path, crop):
+ proc = sh("ffmpeg", "-hide_banner", "-i", str(path), "-frames:v", "1",
+ "-vf", f"crop={crop},format=yuv420p,signalstats,metadata=print:file=-", "-f", "null", "-")
+ return float(re.search(r"lavfi\.signalstats\.YAVG=([0-9.]+)", proc.stdout).group(1))
+
+ out = OUT / "bt2020_sdr_to_sdr.mp4"
+ proc = script("color.py", wide, "--to-sdr", "--fast", "--json", "-o", out)
+ doc = json.loads(proc.stdout)
+ self.assertTrue(doc["verified"])
+ v = probe(str(out))["video"]
+ self.assertEqual((v["color_transfer"], v["color_primaries"], v["color_space"]), ("bt709", "bt709", "bt709"))
+ for crop in ("iw:ih/2-8:0:4", "iw:ih/2-8:0:ih/2+4"): # white half, mid-grey half
+ self.assertLessEqual(abs(luma(out, crop) - luma(wide, crop)), 3, crop)
+ self.assertEqual(doc["sdr_path"], "gamut")
+ self.assertTrue(any("without a tone map" in n for n in doc["notes"]))
+ self.assertFalse(any("tonemap" in c for c in doc["commands"]), doc["commands"])
+
def test_color_retag_is_stream_copy(self):
out = OUT / "retag.mp4"
proc = script("color.py", self.src, "--retag", "bt601", "-o", out)