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.

0.4.1: fixes from a real iPhone Dolby Vision clip (#5)

kajisho5efb2f8d6888f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c29ce0d..6bf5ae7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## 0.4.1
+
+Fixes found by running `verify.py` on a real iPhone clip (Dolby Vision 8.4 / HLG, 10-bit HEVC, 60 fps VFR, portrait rotation, extra metadata tracks):
+
+- HDR sources now stay HDR through every re-encode (`cut`, `fit`, `caption`, `overlay`, `silence`, `join`, `multicam`, `sync`): HEVC Main10 with the source's HLG/PQ tags instead of an 8-bit H.264 file mislabelled BT.709. Use `color.py --to-sdr` when you want SDR.
+- Audio mapping uses the first audio stream only (`0:a:0?`); iPhone `.mov` files carry timecode/metadata tracks that broke `-map 0:a?`.
+- `probe.py --analyze` normalises 10-/12-bit levels to an 8-bit scale before the Log heuristic.
+- `look.py` tone-maps HDR frames for display so the agent judges representative colours.
+- `verify.py` runs `color --to-sdr` on the original file and adds an "hdr preserved" check on the accurate cut.
+
## 0.4.0
- `verify.py` (new): real-footage verification kit — runs the toolchain over the user's own files and reports PASS/FAIL per step, Markdown and JSON.
diff --git a/SKILL.md b/SKILL.md
index eced77c..f6a0de7 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -263,10 +263,14 @@ trims to platform maximums (Reels 90 s, X 140 s) unless `--allow-long`.
After `sync.py`, verify by running it again on the output: offset (and drift
ppm with `--fix-drift`) should be ~0. Recordings longer than ~10 minutes from
separate devices: always use `--fix-drift`.
-- **Colour.** All H.264/H.265 outputs are tagged BT.709 and `yuv420p`. When
- `probe.py` reports `hdr: true` (`hdr_format` HDR10/PQ, HLG or BT.2020), run
- `color.py --to-sdr` **first**; other scripts would tag the HDR picture as
- BT.709 and it would look flat and desaturated (`export.py` warns about this).
+- **Colour.** SDR outputs are H.264 tagged BT.709 `yuv420p`. When `probe.py`
+ reports `hdr: true` (HDR10/PQ, HLG, Dolby Vision, BT.2020), every editing
+ script keeps the output HDR (HEVC Main10, source colour tags) so nothing is
+ silently flattened. Decide with the user: keep HDR (fine for YouTube/phones)
+ or run `color.py --to-sdr` first for SDR-only destinations, LUT work or
+ H.264 deliverables. `export.py` platform presets are SDR and warn on HDR
+ input. iPhone `.mov` files also carry timecode/metadata tracks; scripts map
+ only the first audio track, so extra tracks are dropped on re-encode.
For Log footage (S-Log, V-Log, C-Log: looks grey and low-contrast but is
tagged SDR) run `probe.py --analyze`; `looks_like_log: true` means apply the
manufacturer's `.cube` with `color.py --lut` before anything else. Keep
diff --git a/package.json b/package.json
index 1f90a44..716dedd 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "ffmpeg-skill",
- "version": "0.4.0",
+ "version": "0.4.1",
"description": "Agent Skill that lets coding agents (Claude Code, Cursor, Codex) do professional video editing with local FFmpeg: cut, silence removal, transitions, multicam, captions, sync with drift correction, HDR to SDR, LUTs, audio clean-up and ducking, loudness, platform exports. No API keys, no cloud, no dependencies.",
"keywords": ["ffmpeg", "video", "agent-skill", "claude-code", "cursor", "codex", "skill", "video-editing"],
"license": "MIT",
diff --git a/scripts/_common.py b/scripts/_common.py
index 44d0dbf..bc93054 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -331,6 +331,25 @@ def x264_args(crf: int = 18, preset: str = "medium", keep_bt709: bool = True) ->
return args
+def video_args(meta: Optional[Dict[str, Any]], crf: int = 18, preset: str = "medium") -> List[str]:
+ """Encoder args that preserve what the source is.
+
+ SDR sources -> H.264 8-bit tagged BT.709 (x264_args). HDR sources (HDR10/PQ, HLG,
+ Dolby Vision base layer, BT.2020) -> HEVC Main10 with the source's own colour tags,
+ so cutting/captioning/fitting an iPhone HDR clip stays HDR instead of becoming a
+ washed-out file mislabelled as BT.709. Use color.py --to-sdr when SDR is wanted.
+ """
+ v = (meta or {}).get("video") or {}
+ if not v.get("hdr"):
+ return x264_args(crf, preset)
+ cs = v.get("color_space") or "bt2020nc"
+ prim = v.get("color_primaries") or "bt2020"
+ trc = v.get("color_transfer") or "arib-std-b67"
+ x265 = f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}:range=limited:hdr10-opt=1" if trc == "smpte2084" else f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}"
+ return ["-c:v", "libx265", "-preset", preset, "-crf", str(crf + 2), "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1",
+ "-x265-params", x265, "-colorspace", cs, "-color_primaries", prim, "-color_trc", trc, "-movflags", "+faststart"]
+
+
def aac_args(bitrate: str = "192k") -> List[str]:
return ["-c:a", "aac", "-b:a", bitrate]
@@ -376,14 +395,20 @@ def analyze_levels(path: str, seconds: float = 20.0) -> Dict[str, Any]:
v = vals.get(k) or [0.0]
return sum(v) / len(v)
ymin, ymax, yavg, sat = min(vals.get("YMIN") or [0]), max(vals.get("YMAX") or [255]), mean("YAVG"), mean("SATAVG")
+ # signalstats reports in the source bit depth; normalise everything to an 8-bit scale
+ scale = 1.0
+ if ymax > 255 or yavg > 255:
+ scale = 1 / 4.0 if ymax <= 1023 else 1 / 16.0
+ ymin, ymax, yavg, sat = ymin * scale, ymax * scale, yavg * scale, sat * scale
# 5th/95th percentile of per-frame lows/highs is more robust than the absolute min/max
- lows = sorted(vals.get("YLOW") or vals.get("YMIN") or [0])
- highs = sorted(vals.get("YHIGH") or vals.get("YMAX") or [255])
+ lows = sorted(x * scale for x in (vals.get("YLOW") or vals.get("YMIN") or [0]))
+ highs = sorted(x * scale for x in (vals.get("YHIGH") or vals.get("YMAX") or [255]))
p_low = lows[len(lows) // 20]
p_high = highs[-1 - len(highs) // 20]
looks_log = p_low >= 64 and p_high <= 235 and sat < 40
return {
- "y_min": ymin, "y_max": ymax, "y_avg": round(yavg, 1), "y_low_p5": p_low, "y_high_p95": p_high,
+ "scale": "8-bit equivalent",
+ "y_min": round(ymin, 1), "y_max": round(ymax, 1), "y_avg": round(yavg, 1), "y_low_p5": round(p_low, 1), "y_high_p95": round(p_high, 1),
"saturation_avg": round(sat, 1),
"looks_like_log": looks_log,
"note": ("flat, low-contrast, desaturated picture tagged as SDR: probably a Log profile (S-Log/V-Log/C-Log). "
diff --git a/scripts/caption.py b/scripts/caption.py
index 1d0184b..f6bd9cf 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -22,7 +22,7 @@ import re
import sys
from typing import List, Tuple
-from _common import add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, info, parse_time, probe, run, x264_args
+from _common import video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, info, parse_time, probe, run, x264_args
ALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}
@@ -302,7 +302,7 @@ def main() -> int:
if args.fonts_dir:
vf += f":fontsdir={escape_filter_path(args.fonts_dir)}"
- cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf] + x264_args(args.crf, args.preset) + cfr_args(meta)
+ cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf] + video_args(meta, args.crf, args.preset) + cfr_args(meta)
cmd += (aac_args() if meta.get("audio") else ["-an"]) + [output]
run(cmd)
result = probe(output)
diff --git a/scripts/color.py b/scripts/color.py
index 95bc679..5e8de19 100755
--- a/scripts/color.py
+++ b/scripts/color.py
@@ -99,7 +99,7 @@ def main() -> int:
if proc.returncode != 0:
# some codecs cannot carry retagged colour info without a bitstream filter; fall back to re-encode
info("stream copy could not rewrite tags, re-encoding")
- cmd = ffmpeg_base() + ["-i", args.input, "-map", "0:v:0", "-map", "0:a?"] + x264_args(args.crf, args.preset, keep_bt709=False)
+ cmd = ffmpeg_base() + ["-i", args.input, "-map", "0:v:0", "-map", "0:a:0?"] + x264_args(args.crf, args.preset, keep_bt709=False)
cmd += ["-colorspace", tags[0], "-color_primaries", tags[1], "-color_trc", tags[2]] + (aac_args() if has_audio else []) + [output]
run(cmd)
info(f"wrote {output} (tags -> {args.retag})")
@@ -124,7 +124,7 @@ def main() -> int:
output = args.output or default_output(args.input, "lut")
tag = "lut"
- cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf, "-map", "0:v:0", "-map", "0:a?"]
+ cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf, "-map", "0:v:0", "-map", "0:a:0?"]
cmd += x264_args(args.crf, args.preset) + cfr_args(meta) + (aac_args() if has_audio else []) + [output]
run(cmd)
r = probe(output)
diff --git a/scripts/cut.py b/scripts/cut.py
index 6d5d236..8587440 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -16,7 +16,7 @@ import sys
import tempfile
from typing import List, Tuple
-from _common import STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, x264_args
+from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, x264_args
def parse_segments(spec: str) -> List[Tuple[float, float]]:
@@ -43,7 +43,7 @@ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: i
meta = meta or probe(src)
if reencode:
cmd = ffmpeg_base() + ["-ss", f"{start:.3f}", "-i", src, "-t", f"{dur:.3f}"]
- cmd += x264_args(crf, preset) + cfr_args(meta) + aac_args() + ["-avoid_negative_ts", "make_zero", dst]
+ cmd += video_args(meta, crf, preset) + cfr_args(meta) + aac_args() + ["-avoid_negative_ts", "make_zero", dst]
else:
cmd = ffmpeg_base() + ["-ss", f"{start:.3f}", "-i", src, "-t", f"{dur:.3f}", "-c", "copy", "-avoid_negative_ts", "make_zero", dst]
proc = run(cmd, check=False)
@@ -126,7 +126,7 @@ def main() -> int:
proc = run(cmd, check=False)
if proc.returncode != 0:
info("concat with stream copy failed, re-encoding the join")
- cmd = ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile] + x264_args(args.crf, args.preset) + cfr_args(meta) + aac_args() + [output]
+ cmd = ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile] + video_args(meta, args.crf, args.preset) + cfr_args(meta) + aac_args() + [output]
run(cmd)
result = probe(output)
diff --git a/scripts/fit.py b/scripts/fit.py
index aee8a55..5672348 100755
--- a/scripts/fit.py
+++ b/scripts/fit.py
@@ -19,7 +19,7 @@ import sys
from fractions import Fraction
from typing import List
-from _common import STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, x264_args
+from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, x264_args
ASPECT_PRESETS = {"16:9": Fraction(16, 9), "9:16": Fraction(9, 16), "1:1": Fraction(1, 1), "4:5": Fraction(4, 5), "4:3": Fraction(4, 3), "21:9": Fraction(21, 9)}
@@ -153,7 +153,7 @@ def main() -> int:
cmd += ["-vf", ",".join(vf)]
if af:
cmd += ["-af", ",".join(af)]
- cmd += x264_args(args.crf, args.preset)
+ cmd += video_args(meta, args.crf, args.preset)
cmd += cfr_args(meta, args.fps) if not args.fps else []
if has_audio:
cmd += aac_args()
diff --git a/scripts/join.py b/scripts/join.py
index 1998672..96595fd 100755
--- a/scripts/join.py
+++ b/scripts/join.py
@@ -14,7 +14,7 @@ import argparse
import sys
from typing import List
-from _common import aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, x264_args
+from _common import video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, x264_args
TRANSITIONS = ["fade", "dissolve", "wipeleft", "wiperight", "wipeup", "wipedown", "slideleft", "slideright",
"circleopen", "circleclose", "fadeblack", "fadewhite", "smoothleft", "smoothright", "radial", "none"]
@@ -78,8 +78,9 @@ def main() -> int:
geo = f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}"
else:
geo = f"scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={args.pad_color}"
+ pixfmt = "yuv420p10le" if (metas[0].get("video") or {}).get("hdr") else "yuv420p"
for i in range(n):
- parts.append(f"[{i}:v]{geo},setsar=1,fps={fps:g},format=yuv420p,settb=AVTB[v{i}]")
+ parts.append(f"[{i}:v]{geo},setsar=1,fps={fps:g},format={pixfmt},settb=AVTB[v{i}]")
parts.append(f"[{audio_src[i]}]aformat=sample_rates=48000:channel_layouts=stereo,asetpts=PTS-STARTPTS[a{i}]")
if args.transition == "none":
@@ -98,7 +99,7 @@ def main() -> int:
output = args.output or default_output(args.inputs[0], "joined", "mp4")
cmd += ["-filter_complex", ";".join(parts), "-map", "[vout]", "-map", "[aout]"]
- cmd += x264_args(args.crf, args.preset) + aac_args() + [output]
+ cmd += video_args(metas[0], args.crf, args.preset) + aac_args() + [output]
run(cmd)
expected = sum(durs) - d * (n - 1)
r = probe(output)
diff --git a/scripts/look.py b/scripts/look.py
index 844513a..a7e49a5 100755
--- a/scripts/look.py
+++ b/scripts/look.py
@@ -44,6 +44,13 @@ def main() -> int:
stem = Path(args.input).stem
outdir = str(Path(args.output).parent) if args.output else str(Path(args.input).parent)
tc = "" if args.no_timecode else "," + timecode_filter()
+ # HDR sources: tone-map for the PNG so the agent judges representative colours, not raw HLG/PQ
+ if meta["video"].get("hdr"):
+ v = meta["video"]
+ tm = (f"zscale=tin={v.get('color_transfer') or 'arib-std-b67'}:pin={v.get('color_primaries') or 'bt2020'}:min={v.get('color_space') or 'bt2020nc'}:rin=tv:t=linear:npl=1000,"
+ "format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable,zscale=t=bt709:m=bt709:r=tv,format=yuv420p,")
+ tc = "," + tm.rstrip(",") + tc
+ info("HDR source: frames are tone-mapped to SDR for display")
outputs: List[str] = []
if args.compare:
diff --git a/scripts/multicam.py b/scripts/multicam.py
index 84b14eb..0158bf9 100755
--- a/scripts/multicam.py
+++ b/scripts/multicam.py
@@ -21,7 +21,7 @@ import argparse
import sys
from typing import List, Tuple
-from _common import aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, x264_args
+from _common import video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, x264_args
from sync import measure_offset
@@ -154,7 +154,8 @@ def main() -> int:
w, h = h, w
fps = args.fps or v0.get("fps") or 30.0
fps = round(fps) if abs(fps - round(fps)) < 0.02 else fps
- geo = f"scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps:g},format=yuv420p"
+ pixfmt = "yuv420p10le" if v0.get("hdr") else "yuv420p"
+ geo = f"scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps:g},format={pixfmt}"
cmd = ffmpeg_base()
for p in args.inputs:
@@ -184,7 +185,7 @@ def main() -> int:
output = args.output or default_output(args.inputs[0], "multicam", "mp4")
cmd += ["-filter_complex", ";".join(parts), "-map", "[vout]", "-map", "[aout]"]
- cmd += x264_args(args.crf, args.preset) + aac_args() + ["-shortest", output]
+ cmd += video_args(metas[0], args.crf, args.preset) + aac_args() + ["-shortest", output]
run(cmd)
r = probe(output)
info(f"wrote {output} ({r['duration']:.3f}s, {len(filled)} cuts, audio from input {a})")
diff --git a/scripts/overlay.py b/scripts/overlay.py
index f68b245..7c53d52 100755
--- a/scripts/overlay.py
+++ b/scripts/overlay.py
@@ -15,7 +15,7 @@ import argparse
import sys
from typing import List, Optional
-from _common import add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, x264_args
+from _common import video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, x264_args
POS = {
"top-left": ("{m}", "{m}"),
@@ -140,7 +140,7 @@ def main() -> int:
# -loop 1 turns the still into a timed stream so fade/enable expressions see real timestamps
cmd = ffmpeg_base() + ["-i", args.input, "-loop", "1", "-i", args.image]
fc = f"[1:v]{','.join(chain)},setpts=PTS-STARTPTS[ov];[0:v][ov]{ov}[out]"
- cmd += ["-filter_complex", fc, "-map", "[out]", "-map", "0:a?", "-shortest"]
+ cmd += ["-filter_complex", fc, "-map", "[out]", "-map", "0:a:0?", "-shortest"]
else:
x, y = position_exprs(args.position, args.margin, text_mode=True)
opts = [f"text='{escape_drawtext(args.text)}'", f"fontsize={args.font_size}", f"x={x}", f"y={y}",
@@ -159,7 +159,7 @@ def main() -> int:
opts.append(f"enable='{enable}'")
cmd += ["-vf", "drawtext=" + ":".join(opts)]
- cmd += x264_args(args.crf, args.preset) + cfr_args(meta)
+ cmd += video_args(meta, args.crf, args.preset) + cfr_args(meta)
cmd += aac_args() if meta.get("audio") else ["-an"]
cmd.append(output)
run(cmd)
diff --git a/scripts/silence.py b/scripts/silence.py
index 6bf118f..9e5b95c 100755
--- a/scripts/silence.py
+++ b/scripts/silence.py
@@ -16,7 +16,7 @@ import re
import sys
from typing import List, Tuple
-from _common import aac_args, add_common, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, print_json, probe, require_tool, run, x264_args
+from _common import video_args, aac_args, add_common, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, print_json, probe, require_tool, run, x264_args
SIL_RE = re.compile(r"silence_(start|end): ([0-9.]+)")
@@ -110,7 +110,7 @@ def main() -> int:
af = f"aselect='{expr}',asetpts=N/SR/TB"
cmd = ffmpeg_base() + ["-i", args.input]
if meta.get("video"):
- cmd += ["-vf", vf] + x264_args(args.crf, args.preset) + cfr_args(meta)
+ cmd += ["-vf", vf] + video_args(meta, args.crf, args.preset) + cfr_args(meta)
cmd += ["-af", af] + aac_args() + [output]
run(cmd)
r = probe(output)
diff --git a/scripts/sync.py b/scripts/sync.py
index a158d28..e7fd177 100755
--- a/scripts/sync.py
+++ b/scripts/sync.py
@@ -26,7 +26,7 @@ import subprocess
import sys
from typing import List
-from _common import add_common, apply_common, emit, aac_args, audio_codec_for, default_output, die, ffmpeg_base, info, probe, require_tool, run, x264_args
+from _common import video_args, add_common, apply_common, emit, aac_args, audio_codec_for, default_output, die, ffmpeg_base, info, probe, require_tool, run, x264_args
SR = 8000 # decode sample rate
@@ -253,14 +253,14 @@ def main() -> int:
if proc.returncode != 0:
cmd = [c for c in cmd if c != "copy"]
idx = cmd.index("-c:v"); del cmd[idx]
- cmd = cmd[:-1] + x264_args(args.crf) + [output]
+ cmd = cmd[:-1] + video_args(probe(args.reference) if args.replace_audio else probe(args.second), args.crf) + [output]
run(cmd)
else:
if head_trim > 0 and not drift_af:
cmd = ffmpeg_base() + ["-ss", f"{head_trim:.4f}", "-i", args.second, "-c", "copy", "-avoid_negative_ts", "make_zero", output]
proc = run(cmd, check=False)
if proc.returncode != 0:
- cmd = ffmpeg_base() + ["-ss", f"{head_trim:.4f}", "-i", args.second] + (x264_args(args.crf) if has_video else []) + audio_codec_for(output) + [output]
+ cmd = ffmpeg_base() + ["-ss", f"{head_trim:.4f}", "-i", args.second] + (video_args(probe(args.reference) if args.replace_audio else probe(args.second), args.crf) if has_video else []) + audio_codec_for(output) + [output]
run(cmd)
else:
cmd = ffmpeg_base()
@@ -278,7 +278,7 @@ def main() -> int:
vf.append(f"setpts=PTS/{drift_ratio:.9f}")
if vf:
cmd += ["-vf", ",".join(vf)]
- cmd += x264_args(args.crf)
+ cmd += video_args(probe(args.reference) if args.replace_audio else probe(args.second), args.crf)
if af_parts:
cmd += ["-af", ",".join(af_parts)]
cmd += audio_codec_for(output) + [output]
diff --git a/scripts/verify.py b/scripts/verify.py
index 0db1c61..4675e01 100755
--- a/scripts/verify.py
+++ b/scripts/verify.py
@@ -47,6 +47,14 @@ 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__":
+ 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"
+ 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)
ok = proc.returncode == 0
@@ -110,7 +118,8 @@ def main() -> int:
plan.append(("overlay text", ["overlay.py", cut, "--text", "verify", "--position", "top-left", "-o", f"{stem}_ovl.mp4"] + fast))
plan.append(("look sheet", ["look.py", cut, "-o", f"{stem}_sheet.png"]))
if (meta.get("video") or {}).get("hdr"):
- plan.append(("color to-sdr", ["color.py", cut, "--to-sdr", "-o", f"{stem}_sdr.mp4"] + fast))
+ plan.append(("color to-sdr", ["color.py", str(f), "--to-sdr", "-o", f"{stem}_sdr.mp4"] + fast))
+ plan.append(("hdr preserved", ["__check_hdr__", f"{stem}_acc.mp4"]))
plan.append(("probe analyze", ["probe.py", cut, "--analyze"]))
plan.append(("export x", ["export.py", cut, "--preset", "x", "-o", f"{stem}_x.mp4"]))
if has_a and not args.quick:
diff --git a/tests/test_all.py b/tests/test_all.py
index 7ae2ed6..331ad10 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -513,6 +513,42 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertIn("-preset veryfast", proc.stderr, "--fast overrides the preset")
self.assertClose(probe(str(out))["duration"], 6.0, 0.2)
+ # ---------------------------------------------------------------- real iPhone regressions (Dolby Vision 8.4 / HLG, VFR, extra tracks)
+ def test_hdr_source_stays_hdr_through_reencodes(self):
+ # HLG 10-bit HEVC with audio AND a timecode data track, like an iPhone .mov
+ hlg = OUT / "hlg_tc.mov"
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
+ "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=30", "-f", "lavfi", "-i", f"aevalsrc='{TONES}':s=48000",
+ "-t", "5", "-vf", "format=yuv420p10le", "-c:v", "libx265", "-preset", "ultrafast",
+ "-x265-params", "colorprim=bt2020:transfer=arib-std-b67:colormatrix=bt2020nc:log-level=error", "-tag:v", "hvc1",
+ "-c:a", "aac", "-timecode", "01:00:00:00", hlg)
+ streams = json.loads(sh("ffprobe", "-v", "error", "-print_format", "json", "-show_streams", hlg).stdout)["streams"]
+ self.assertEqual(len(streams), 3, "video + audio + tmcd data track")
+ for name, argv in [
+ ("cut.py", [hlg, "--start", "1", "--end", "3", "--accurate"]),
+ ("fit.py", [hlg, "--aspect", "1:1", "--width", "480"]),
+ ("caption.py", [hlg, "--text", self.cues]),
+ ("overlay.py", [hlg, "--text", "hdr"]),
+ ("silence.py", [hlg]),
+ ("join.py", [hlg, hlg, "--transition", "none"]),
+ ]:
+ out = OUT / f"hdrkeep_{name}.mp4"
+ script(name, *argv, "--fast", "-o", out)
+ v = probe(str(out))["video"]
+ self.assertTrue(v["hdr"], name)
+ self.assertEqual((v["codec"], v["pix_fmt"], v["color_transfer"]), ("hevc", "yuv420p10le", "arib-std-b67"), name)
+ # tone-mapping and the display path still work on the multi-track file
+ sdr = OUT / "hlg_tc_sdr.mp4"
+ script("color.py", hlg, "--to-sdr", "--fast", "-o", sdr)
+ self.assertFalse(probe(str(sdr))["video"]["hdr"])
+ proc = script("look.py", hlg, "--at", "1", "-o", OUT / "hlgframe")
+ self.assertIn("tone-mapped", proc.stderr)
+ self.assertTrue((OUT / "hlgframe_1.000s.png").exists())
+ # 10-bit levels are reported on an 8-bit scale, so a normal HDR clip is not called Log
+ data = json.loads(script("probe.py", hlg, "--analyze").stdout)
+ self.assertLessEqual(data["levels"]["y_max"], 255)
+ self.assertFalse(data["levels"]["looks_like_log"])
+
# ---------------------------------------------------------------- help
def test_every_script_has_help(self):
for name in sorted(p.name for p in SCRIPTS.glob("*.py") if not p.name.startswith("_")):