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.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
fix(color): convert a BT.601 source to the BT.709 its re-encode is tagged with (#332)
Shogo Kajiyama57daa49c4136
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bfb061a..50c4877 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,9 @@## Unreleased-(nothing yet)+### Fixed++- **A BT.601 source is converted to the BT.709 its re-encode is tagged with, not just relabelled.** Every SDR re-encode (`export.py`'s presets, and `fit`, `cut --accurate`, `crop`, `caption`, `overlay`, `graphics`, `color --lut/--correct` and the other tools that re-encode a video source) tags its output BT.709, and those tags never touch the pixels; through 2.10.0 nothing else did either, so a source tagged `smpte170m` or `bt470bg` (fully, or with only the matrix tag) came out `bt709/bt709/bt709` over unconverted BT.601 pixels (48.5 dB YUV PSNR against the source on FFmpeg 6.1), and every player that honours the tags showed shifted colours. The matrix is now converted with FFmpeg's `colorspace` filter as the first step of the tool's own graph (`_common.bt709_matrix_filter()`; `fcc` and `smpte240m` matrices too); primaries, transfer and range pass through. `join`, `multicam`, `broll` and `overlay --video` convert each input by its own tags. An untagged or BT.709 source, an HDR/BT.2020 source, a stream copy and the `prores` master are unchanged: their commands are what they were. `check.py`'s colour row for a BT.601 matrix now names `export.py` as the fix (any re-encode converts) and says `color.py --retag bt709` only relabels.## 2.10.0diff --git a/README.md b/README.mdindex 462908f..944b5aa 100644--- a/README.md+++ b/README.md@@ -248,7 +248,7 @@ These are the rules the skill file gives the agent and the code enforces.| Tool | What it does ||---|---|-| `export.py` | Presets `youtube`, `youtube4k`, `reels`, `tiktok`, `shorts`, `linkedin`, `facebook`, `x`, `youtube-hdr` (HEVC Main10, source HDR tags kept), `youtube-av1`, `prores`, `h265`, `gif`, `copy`, all tagged BT.709 unless they carry HDR; `--normalize` meets the platform's loudness in the same call (`render.py` turns it on by default for platform presets) |+| `export.py` | Presets `youtube`, `youtube4k`, `reels`, `tiktok`, `shorts`, `linkedin`, `facebook`, `x`, `youtube-hdr` (HEVC Main10, source HDR tags kept), `youtube-av1`, `prores`, `h265`, `gif`, `copy`, all tagged BT.709 unless they carry HDR (a BT.601-matrix source is converted to BT.709, not relabelled); `--normalize` meets the platform's loudness in the same call (`render.py` turns it on by default for platform presets) || `proxy.py` | Small, low-bitrate proxy for downstream AI analysis/preview/editing decisions — resize by `--width`/`--scale`, proxy-grade `--quality` (default 30), `--fps`, `--no-audio`; not a delivery preset || `check.py` | PASS / WARN / FAIL against YouTube, Shorts, Reels, TikTok, X, LinkedIn, Facebook, broadcast and podcast specs, from the same delivery table the export presets and templates read (podcast also reports chapter markers and channel count), with the fix for each failure and a `format` / `judgement` kind per row || `report.py` | Single-file HTML delivery report: before/after sheets, media facts, loudness, compliance, the commands run; `--pack` renders a social pack table |diff --git a/docs/contract.md b/docs/contract.mdindex 9bfb747..5a84832 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -217,6 +217,10 @@ BT.709 for SDR; av1 is SVT-AV1 with libaom as the fallback; prores is 422 HQ andits default is the tool's own (18, `proxy.py` 30). 1.x also accepted `--crf` as an alias; 2.0removed it (`export.py` keeps its own `--crf`). Without `--codec` the encoder is what it always was (x264 for SDR, x265Main10 for HDR), so the flags add no behaviour to a caller that does not pass them.+Every SDR line except prores is tagged BT.709; a source whose matrix is BT.601 (`smpte170m`,+`bt470bg`, or `fcc`/`smpte240m`) is converted to it in the filter graph (`colorspace`, matrix+only; `_common.bt709_matrix_filter()`), so the label and the pixels agree. An untagged or BT.709+source adds no filter, and the tags themselves never convert (`bt709_tag_args()`).`cut.py --keep-hevc` (opt-in) re-encodes an SDR HEVC source as x265 8-bit BT.709 instead of x264; an HDR orBT.2020 source keeps the Main10 line with its own colour tags, with or without the flag. Theencoder each value needs is listed under the tool's optional capabilities (`--codec hevc` anddiff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex 456c5b2..1f527aa 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -91,10 +91,12 @@ exists. When a decision changes, edit the entry in the same PR.its frames change colour tags; on 8.1.2 that rebuild at a *later* input deadlocked at 0% CPU (anin-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)+ decoded. That is acceptable because no colour conversion in a cut follows the frames' own tags: an+ SDR output is tagged BT.709 explicitly and tag-only (`bt709_tag_args`), and the one conversion a cut+ can carry (a source whose *probed* matrix is BT.601, `bt709_matrix_filter`) takes the source's+ matrix as an explicit input property, so every segment of one source goes through the same one. An+ untagged source (#316's starts untagged) is relabelled, as before, 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 tothe output's label. A BT.2020/HDR sourcestill takes the HDR path chosen from the first video stream's probe. The cost: a source whose@@ -115,12 +117,40 @@ exists. When a decision changes, edit the entry in the same PR.is a deliverable, keep the HDR (10-bit HEVC) path. Test: `test_grid_composites_cols_rows_with_labels`.- **`look.py -o` is used verbatim only for a single `--at` with an image extension**; several frames,or `-o` given as a stem, produce `<stem>_<t>s.png` names. Test: `test_hdr_source_stays_hdr_through_reencodes`.-- **`check.py`'s colour row WARNs on a BT.601 matrix without naming a command.** The matrix is a- tag (#325): a file tagged only `smpte170m`/`bt470bg` is BT.601, not "untagged". No tool here- converts the matrix -- `color.py --retag bt709`, and every SDR re-encode (`bt709_tag_args`), only- relabels it, which shifts the colours of BT.601 pixels -- so the fix says to re-export from the- master as BT.709. Untagged 8-bit video, or a BT.709 matrix alone, still passes: players assume- BT.709. Code: `check.py`, the colour row. Test: `test_check_colour_row_reads_the_matrix_tag`.+- **`check.py`'s colour row WARNs on a BT.601 matrix and names `export.py`, not `--retag`.** The+ matrix is a tag (#325): a file tagged only `smpte170m`/`bt470bg` is BT.601, not "untagged". Every+ re-encode here converts it to the BT.709 it tags (the entry below; through 2.10.0 nothing did, and+ this fix said to re-export from the master); `color.py --retag bt709` is a stream copy that only+ relabels it, which shifts the colours of BT.601 pixels, so the fix says that too. Untagged 8-bit+ video, or a BT.709 matrix alone, still passes: players assume BT.709. Code: `check.py`, the colour+ row. Test: `test_check_colour_row_reads_the_matrix_tag`.+- **A source with a BT.601 matrix is converted to BT.709 when it is re-encoded; an untagged one is+ not.** Every SDR line but prores is tagged BT.709, and the tags are labels (`bt709_tag_args`), so+ a `smpte170m`/`bt470bg` (or `fcc`/`smpte240m`) source used to come out labelled BT.709 over+ BT.601 pixels: 48.5 dB YUV PSNR against its source on 6.1, every tag-honouring player showing+ shifted colours. `bt709_matrix_filter()` now converts it with the `colorspace` filter (in every+ FFmpeg build, explicit input properties, so no build's tag negotiation decides it). Untagged+ stays a relabel on purpose: players take untagged SDR as BT.709, and converting it is exactly the+ 7.1 auto-conversion `bt709_tag_args` avoids. Only the **matrix** is converted; primaries and+ transfer pass through: the matrix is what every decoder applies, SMPTE-C/EBU primaries are+ shown as BT.709 by every player that does not colour-manage, a full conversion moved testsrc2 to+ 22.5 dB RGB PSNR from what such a player shows, and a `bt470bg` (gamma 2.8) transfer tag on SD+ material is usually a label, not the camera's curve. The range is left as it is. The filter+ rides on the encoder line as a `-vf` (`video_args()`, `x264_args(source=...)`, export's preset+ line) and `run()` folds it into the+ tool's own graph as its first step (`fold_bt709_matrix()`), so the tools that re-encode one+ source needed no edit of their own; `join`, `multicam`, `broll` and `overlay --video` convert each+ input by its own tags in its own chain (`matrix_chain()`), since one source's tags say nothing+ about another's. Not converted: a stream copy, a prores master, an HDR/BT.2020 source, `grid.py`+ (an inspection sheet), stills, and the second input of a tool that composites a still over the+ source. Measured on 5.1.1, 6.1 and a 7.1 development snapshot that predates 7.1's colour+ negotiation (CI runs 8.x): 42.2 dB RGB PSNR between the source decoded+ as BT.601 and the output decoded as BT.709 (24.8 dB for the old relabel), untagged and BT.709+ sources unchanged. Code: `_common/color.py`. Tests:+ `test_a_bt601_source_is_converted_to_the_bt709_it_is_tagged_with`,+ `test_an_untagged_or_bt709_source_is_not_converted`,+ `test_every_reencoding_tool_plans_the_bt601_conversion`,+ `test_fold_bt709_matrix_into_the_tools_graph`.- **`--correct` converts through bt601 on both legs** (not bt709), because on every testedFFmpeg the 709 round trip through 8-bit 4:2:0 loses ~5 dB more than 601. Code:`color.py _rgb_stage()`. Test: `test_color_correct_identity_holds_on_a_bt709_tagged_source`.diff --git a/references/gotchas.md b/references/gotchas.mdindex 4515354..9d5677a 100644--- a/references/gotchas.md+++ b/references/gotchas.md@@ -8,7 +8,10 @@ detail, not an aside.## Colour, HDR and Log### HDR and colour-SDR outputs are H.264 tagged BT.709 `yuv420p`. When `probe.py` reports+SDR outputs are H.264 tagged BT.709 `yuv420p`. A source tagged with a BT.601 matrix+(`smpte170m`, `bt470bg`; also `fcc`, `smpte240m`) has its pixels converted to that BT.709 matrix+by every re-encode (through 2.10.0 only the label changed); `color.py --retag bt709` is a+stream copy and still only relabels. Untagged sources are taken as BT.709 and left alone. When `probe.py` reports`bt2020_or_hdr: true` (HDR10/PQ, HLG, Dolby Vision, or BT.2020 SDR), every editing script keepsthe output on the 10-bit path (HEVC Main10, source colour tags) so nothing is silentlyflattened. Decide with the user: keep HDR (fine for YouTube/phones) or rundiff --git a/references/scripts.md b/references/scripts.mdindex ec7892f..f726563 100644--- a/references/scripts.md+++ b/references/scripts.md@@ -1615,7 +1615,7 @@ export.py INPUT --preset youtube|youtube4k|reels|tiktok|shorts|linkedin|facebook[--fit pad|crop] [--no-scale] [--allow-long] [--crf N] [--normalize] [-o OUT]export.py --list```-Scales into the preset frame (pad by default), tags BT.709, sets `+faststart`,+Scales into the preset frame (pad by default), tags BT.709 (a BT.601-matrix source is converted to it, as by every re-encode), sets `+faststart`,trims to platform maximums (Reels 90 s, X 140 s) unless `--allow-long`. Itdoes not touch levels: for youtube / youtube4k / reels / x the written file ismeasured and the result's `loudness` (and a `notes` line) says when it isdiff --git a/scripts/_common/__init__.py b/scripts/_common/__init__.pyindex c044898..ce1f9bf 100644--- a/scripts/_common/__init__.py+++ b/scripts/_common/__init__.py@@ -83,7 +83,7 @@ from _common.decision import (_onset_strength, _pick_onsets, _autocorrelation_peak, _grid_score,brand_states_font, cfr_args, concat_list_line, db_to_linear, default_output, encoder_args, escape_filter_path,fmt_secs, fmt_smpte_time, fmt_srt_time, frame_size, is_audio_output, load_brand, MissingFpsError, pad_filters, parse_time,- signed_time_arg, source_codec_video_args, SVT_PRESET, time_arg, video_args, x264_args, _x264_raw+ signed_time_arg, source_codec_video_args, matrix_chain, SVT_PRESET, time_arg, video_args, x264_args, _x264_raw)from _common.asr import (ASR_ENGINES, ASR_INSTALL_HINT, _asr_run, die_no_engine, parse_srt, transcribe, _transcribe_in,@@ -91,7 +91,8 @@ from _common.asr import (whisper_word_timings, write_srt)from _common.color import (- bt709_tag_args, color_hex, _COLOR_TOKEN_RE, _sdr_bt709, validate_color+ bt709_matrix_args, bt709_matrix_filter, bt709_tag_args, color_hex, _COLOR_TOKEN_RE, fold_bt709_matrix,+ NON_BT709_MATRICES, _sdr_bt709, validate_color)from _common.text import (ADVANCE_EM, BIDI_SCRIPTS, _char_em, char_script, default_font_file, detect_script, drawtext_boxborderw, drawtext_center_align,@@ -178,7 +179,7 @@ __all__ = ["platform", "re", "shutil", "subprocess", "sys", "unicodedata","aac_args", "add_common", "add_pad_fill_args", "ADVANCE_EM", "analyze_levels", "apply_common", "detect_scenes", "detect_silences", "SCORE_RE", "SIL_RE", "_aspect_string","audio_codec_for", "AUDIO_CODECS", "BIDI_SCRIPTS", "_bit_depth", "brand_caption_style", "BRAND_DEFAULTS",- "brand_states_font", "_brief", "_BRIEF_DROP", "_brief_summary", "bt709_tag_args", "cfr_args", "_char_em",+ "brand_states_font", "_brief", "_BRIEF_DROP", "_brief_summary", "bt709_matrix_args", "bt709_matrix_filter", "bt709_tag_args", "cfr_args", "_char_em","char_script", "_check_existing_output", "refuse_existing_outputs", "_check_no_overwrite_input", "_check_output_path", "child_args","child_limit", "_CHILDREN", "_cleanup_partial_output", "_cmdline", "CODECS", "color_hex", "_COLOR_TOKEN_RE","concat_list_line", "Context", "_CURRENT_CTX", "db_to_linear", "decode_pcm_mono", "description_block", "_evidence_rank", "fmt_chapter_time", "propose_chapters",@@ -196,12 +197,12 @@ __all__ = ["_EMOJI_TAIL", "encoder_args", "_ENCODERS", "_env_timeout", "ERROR_CODE", "ERROR_RETRYABLE", "escape_drawtext","escape_filter_path", "EVEN_SCALE", "_execute", "_fail", "_family_rank", "FC_LANG", "_fc_list_fonts","FC_UNKNOWN", "ffmpeg_base", "ffmpeg_encoders", "ffmpeg_exe", "_FFMPEG_VERSION", "ffmpeg_version", "fingerprint",- "flush_drawtext_textfiles", "fmt_secs", "fmt_smpte_time", "fmt_srt_time", "font_covers_script",+ "flush_drawtext_textfiles", "fold_bt709_matrix", "fmt_secs", "fmt_smpte_time", "fmt_srt_time", "font_covers_script","font_family_for_script", "font_family_of_file", "FONT_FLAG_HINT", "font_for_script", "FONT_INSTALL_HINT","fonts_dir_covers_script", "_fraction", "has_emoji", "info", "INSTALL_HINTS", "install_signal_handlers","is_audio_output", "_is_emoji_base", "_is_emoji_char", "_is_ffmpeg", "_is_mark", "_KEYCAP", "_KEYCAP_BASES","keyframes_near", "classify_frame_timing", "measure_frame_timing", "LANGUAGE_NAMES", "LATIN_EM", "LEADING_VOWELS", "_libass_color_probe", "_limit_for",- "load_brand", "measured_level_dbfs", "AUDIO_MEDIA_EXT", "MEDIA_EXT", "MissingFpsError", "needs_shaping", "NO_SPACE_SCRIPTS",+ "load_brand", "measured_level_dbfs", "AUDIO_MEDIA_EXT", "MEDIA_EXT", "MissingFpsError", "needs_shaping", "NO_SPACE_SCRIPTS", "NON_BT709_MATRICES","_odd_dimension_retry", "_on_signal", "_output_failed", "_OutputLock", "pad_filters", "parse_time", "_pid_dead","place_output", "_plan_at_exit", "_plan_inputs", "_PLAN_STRIP", "PLAN_VERSION", "PREFERRED_FAMILIES","print_json", "probe", "PROBE_TIMEOUT", "_progress_line", "read_text_or_die", "refuse_output_is_input",@@ -212,7 +213,7 @@ __all__ = ["SCRIPTS", "_sdr_bt709", "_set_current_ctx", "_SHAPING_BUILD_CACHE", "SHAPING_SCRIPTS", "shell_quote", "sibling_temp","_SIGNALS_INSTALLED", "signed_time_arg", "_stage_existing_output", "STATE", "SVT_PRESET", "text_width_em","time_arg", "_timed_out", "_to_float", "_to_int", "_unwatch", "validate_color", "verify_output",- "source_codec_video_args", "video_args", "_VS15", "_VS16", "_watch", "WINDOWS_FONTS", "write_plan", "x264_args", "X264_PRESETS",+ "source_codec_video_args", "matrix_chain", "video_args", "_VS15", "_VS16", "_watch", "WINDOWS_FONTS", "write_plan", "x264_args", "X264_PRESETS","_x264_raw", "_ZWJ","ASR_ENGINES", "ASR_INSTALL_HINT", "_asr_run", "die_no_engine", "parse_srt", "transcribe","_transcribe_in", "transcribe_words", "_words_from_openai_whisper_json",diff --git a/scripts/_common/color.py b/scripts/_common/color.pyindex 7f408cd..8b1c42e 100644--- a/scripts/_common/color.py+++ b/scripts/_common/color.py@@ -4,7 +4,7 @@ validation for the tools that take a `--color`.from __future__ import annotationsimport re-from typing import List, Tuple+from typing import Any, Dict, List, Optional, Sequence, Tuplefrom _common.emit import diefrom _common.runner import ffmpeg_version@@ -18,9 +18,13 @@ def bt709_tag_args(encoder: str = "libx264") -> List[str]:screen recordings, many cameras) the CLI now auto-inserts a *real* matrix conversion (itsguess for "unknown" is bt601) into every SDR re-encode: a --lut-strength 0 no-op gradecame back ~24 dB PSNR from its source on 7.1. From 7.1 on, the tags therefore go through- the encoder's own VUI parameters instead, which libavfilter never sees; a source that is- genuinely tagged bt601/bt2020 is left alone either way (it keeps its own tags on the old- path, and the encoder VUI is a label, not a conversion, on the new one).+ the encoder's own VUI parameters instead, which libavfilter never sees.++ These tags are a label on every FFmpeg version: they never convert the pixels. A source+ whose matrix is not BT.709 (a BT.601 `smpte170m`/`bt470bg` file) gets its pixels converted+ separately, by bt709_matrix_filter() in the filter graph; through 2.10.0 nothing did, and+ such a source came out labelled BT.709 over BT.601 pixels (measured on 6.1: 48.5 dB YUV+ PSNR against the source, i.e. untouched, tagged bt709/bt709/bt709)."""if ffmpeg_version() < (7, 1):return ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"]@@ -42,6 +46,101 @@ def _sdr_bt709(encoder: str) -> "Tuple[str, List[str]]":return "colorprim=bt709:transfer=bt709:colormatrix=bt709", []+# The SDR matrices (ffprobe's names) whose pixels an output tagged BT.709 has to convert:+# BT.601 (`smpte170m` 525-line, `bt470bg` 625-line: the same coefficients) and the two rare+# pre-BT.709 ones the colorspace filter also reads. bt2020nc/c sources take the HDR/BT.2020 path.+NON_BT709_MATRICES = ("smpte170m", "bt470bg", "fcc", "smpte240m")++_MATRIX_FILTER_RE = re.compile(r"^colorspace=ispace=(?:%s):iprimaries=bt709:itrc=bt709:space=bt709:primaries=bt709:trc=bt709$"+ % "|".join(NON_BT709_MATRICES))+_INPUT_VIDEO_REF = re.compile(r"\[(\d+):v(?::0)?\]")+++def bt709_matrix_filter(meta: Optional[Dict[str, Any]]) -> Optional[str]:+ """The filter that turns the probed source's pixels into BT.709 ones before an output is+ tagged BT.709, or None when nothing needs converting: an SDR source tagged with a non-BT.709+ matrix (NON_BT709_MATRICES) only. An untagged or BT.709 source, an HDR/BT.2020 one (it keeps+ its own tags, or color.py --to-sdr converts it) and a missing probe get None, so their+ commands are what they were.++ The matrix is converted and nothing else: primaries and transfer are passed through+ (iprimaries/itrc = the output's), so the picture a player that decodes with the source's+ matrix showed is the picture the BT.709 output shows. The `colorspace` filter is in every+ FFmpeg build (no zscale needed) and takes explicit input properties, so the conversion does+ not depend on how a build reads or negotiates the frames' own tags. The range is left as it is."""+ v = (meta or {}).get("video") or {}+ matrix = v.get("color_space")+ if v.get("bt2020_or_hdr") or matrix not in NON_BT709_MATRICES:+ return None+ return f"colorspace=ispace={matrix}:iprimaries=bt709:itrc=bt709:space=bt709:primaries=bt709:trc=bt709"+++def bt709_matrix_args(meta: Optional[Dict[str, Any]]) -> List[str]:+ """["-vf", bt709_matrix_filter(meta)] for an encoder line that tags its output BT.709, or [].++ It rides on the encoder line (decision.video_args() and friends) so every tool that+ re-encodes through that line converts without building it into its own graph. That -vf is+ valid as it stands for a command with no other filter; run() folds it into the tool's own+ -vf or -filter_complex (fold_bt709_matrix()) before the command is recorded or run."""+ f = bt709_matrix_filter(meta)+ return ["-vf", f] if f else []+++def fold_bt709_matrix(cmd: Sequence[str]) -> List[str]:+ """`cmd` with the conversion bt709_matrix_args() appended to its encoder line moved into the+ tool's own filter graph, where it runs first, on the decoded source:++ - no other filter: unchanged (the -vf is the graph);+ - a -vf: the conversion is prepended to that chain;+ - a -filter_complex: every `[N:v]` / `[N:v:0]` reference to an input that reads the same file+ as input 0 (the file the encoder line was built for; cut.py's segment join opens it once+ per segment) reads that input through the conversion instead. Other inputs are untouched.++ A -filter_complex with no such reference is refused rather than run with two graphs (ffmpeg+ would refuse it anyway, less clearly). Every other command is returned as it is."""+ out: List[str] = []+ conv, at = None, -1+ i = 0+ while i < len(cmd):+ if cmd[i] == "-vf" and i + 1 < len(cmd) and _MATRIX_FILTER_RE.match(str(cmd[i + 1])):+ conv, at = conv or str(cmd[i + 1]), (at if at >= 0 else len(out))+ i += 2+ continue+ out.append(cmd[i])+ i += 1+ if conv is None:+ return list(cmd)+ graph_at = next((k for k, a in enumerate(out[:-1]) if a in ("-filter_complex", "-lavfi")), None)+ if graph_at is not None:+ inputs = [out[k + 1] for k in range(len(out) - 1) if out[k] == "-i"]+ source = {n for n, p in enumerate(inputs) if p == inputs[0]} if inputs else set()+ refs: Dict[int, List[str]] = {} # input index -> [its first reference, the labels standing in for it]++ def through(m: "re.Match[str]") -> str:+ n = int(m.group(1))+ if n not in source:+ return m.group(0)+ label = f"[bt709src{sum(len(v) - 1 for v in refs.values())}]"+ refs.setdefault(n, [m.group(0)]).append(label)+ return label++ graph = _INPUT_VIDEO_REF.sub(through, str(out[graph_at + 1]))+ if not refs:+ die("internal: a BT.709 matrix conversion was requested for a -filter_complex that never reads "+ "input 0's video as [0:v]", kind="ffmpeg")+ # one conversion per input, split when the graph reads that input more than once+ # (speedramp.py trims [0:v] once per segment)+ chains = [f"{ref}{conv}" + (f",split={len(labels)}" if len(labels) > 1 else "") + "".join(labels)+ for ref, *labels in refs.values()]+ out[graph_at + 1] = ";".join(chains + [graph])+ return out+ vf_at = next((k for k, a in enumerate(out[:-1]) if a == "-vf"), None)+ if vf_at is not None:+ out[vf_at + 1] = f"{conv},{out[vf_at + 1]}"+ return out+ return out[:at] + ["-vf", conv] + out[at:]++def color_hex(value: str) -> str:"""Normalise '#ffd200' / 'ffd200' / '0xFFD200' to 'FFD200'."""v = str(value).strip().lstrip("#")diff --git a/scripts/_common/decision.py b/scripts/_common/decision.pyindex 7f2e963..20bbc96 100644--- a/scripts/_common/decision.py+++ b/scripts/_common/decision.py@@ -14,7 +14,7 @@ import argparsefrom fractions import Fractionfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple-from _common.color import bt709_tag_args, _sdr_bt709+from _common.color import bt709_matrix_args, bt709_matrix_filter, bt709_tag_args, _sdr_bt709from _common.emit import diefrom _common.runner import CODECS, STATE, ffmpeg_encoders, ffmpeg_version, hw_platform_reason@@ -497,30 +497,55 @@ def _x264_raw(crf: int, preset: str, keep_bt709: bool = True) -> List[str]:return args-def x264_args(crf: int = 18, preset: str = "medium", keep_bt709: bool = True) -> List[str]:+def x264_args(crf: int = 18, preset: str = "medium", keep_bt709: bool = True,+ source: Optional[Dict[str, Any]] = None) -> List[str]:"""SDR H.264 encoder args -- or, when --codec named another encoder, that encoder's SDR args- (color.py's --to-sdr path builds its own H.264 line; the flag still has to reach it)."""+ (color.py's --to-sdr path builds its own H.264 line; the flag still has to reach it).++ `source`: the probe of the file being re-encoded, when the pixels reaching the encoder are+ still that file's. A BT.709-tagged line then carries the conversion of a non-BT.709 matrix+ (bt709_matrix_args); a caller whose graph already outputs BT.709 (--to-sdr) leaves it out."""if STATE.codec and STATE.codec != "h264":- return encoder_args(STATE.codec, crf, preset, None, keep_bt709)- return _maybe_hw("h264", crf, None, keep_bt709, _x264_raw(crf, preset, keep_bt709))+ args = encoder_args(STATE.codec, crf, preset, None, keep_bt709)+ else:+ args = _maybe_hw("h264", crf, None, keep_bt709, _x264_raw(crf, preset, keep_bt709))+ return args + (bt709_matrix_args(source) if keep_bt709 and STATE.codec != "prores" else [])-def video_args(meta: Optional[Dict[str, Any]], crf: int = 18, preset: str = "medium") -> List[str]:+def video_args(meta: Optional[Dict[str, Any]], crf: int = 18, preset: str = "medium", convert_matrix: bool = True) -> 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 awashed-out file mislabelled as BT.709. Use color.py --to-sdr when SDR is wanted.++ An SDR source tagged with a BT.601 (or another non-BT.709) matrix is converted to BT.709+ before it is tagged so: the line ends with the `-vf` of bt709_matrix_args(), which run()+ folds into the tool's own graph (color.fold_bt709_matrix). `convert_matrix=False` is for a+ tool that mixes several sources and converts each one in its own graph (join, multicam,+ broll, overlay --video). --codec prores keeps the source's tags, so it converts nothing."""- if STATE.codec:- return encoder_args(STATE.codec, crf, preset, meta)v = (meta or {}).get("video") or {}+ fix = bt709_matrix_args(meta) if convert_matrix and STATE.codec != "prores" else []+ if STATE.codec:+ return encoder_args(STATE.codec, crf, preset, meta) + fixif not v.get("bt2020_or_hdr"):- return x264_args(crf, preset)+ return x264_args(crf, preset) + fixreturn _maybe_hw("hevc", crf, meta, True, _x265_hdr_default(v, crf, preset))+def matrix_chain(meta: Optional[Dict[str, Any]], line_meta: Optional[Dict[str, Any]]) -> str:+ """For a tool that mixes several sources in one graph and encodes it through+ video_args(line_meta, convert_matrix=False): the conversion one source's own chain starts+ with ("<filter>," -- bt709_matrix_filter), or "" when that source needs none or the line does+ not tag BT.709 (an HDR/BT.2020 line keeps its tags, --codec prores keeps the source's)."""+ if STATE.codec == "prores" or ((line_meta or {}).get("video") or {}).get("bt2020_or_hdr"):+ return ""+ f = bt709_matrix_filter(meta)+ return f + "," if f else ""++def source_codec_video_args(meta: Optional[Dict[str, Any]], crf: int = 18, preset: str = "medium",keep_hevc: bool = False) -> List[str]:"""video_args(), except that with `keep_hevc` (cut.py --keep-hevc) an SDR HEVC source re-encodes@@ -530,7 +555,7 @@ def source_codec_video_args(meta: Optional[Dict[str, Any]], crf: int = 18, presesource always takes video_args()'s Main10 line, and --codec always wins."""v = (meta or {}).get("video") or {}if keep_hevc and not STATE.codec and v.get("codec") == "hevc" and not v.get("bt2020_or_hdr"):- return encoder_args("hevc", crf, preset, meta)+ return encoder_args("hevc", crf, preset, meta) + bt709_matrix_args(meta)return video_args(meta, crf, preset)diff --git a/scripts/_common/runner.py b/scripts/_common/runner.pyindex 0170482..bc346b1 100644--- a/scripts/_common/runner.py+++ b/scripts/_common/runner.py@@ -878,6 +878,11 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True, ctx: "Opctx = ctx or STATEis_ffmpeg = _is_ffmpeg(cmd)if is_ffmpeg:+ # an encoder line that converts a BT.601 source to the BT.709 it is tagged with carries+ # that conversion as a -vf; it joins the tool's own graph here, before anything records+ # or runs the command (color.py imports this module, hence the late import)+ from _common.color import fold_bt709_matrix+ cmd = fold_bt709_matrix(cmd)_check_no_overwrite_input(cmd)_check_output_path(cmd)_check_existing_output(cmd)diff --git a/scripts/broll.py b/scripts/broll.pyindex 23143d6..4fc366d 100755--- a/scripts/broll.py+++ b/scripts/broll.py@@ -21,7 +21,7 @@ import argparseimport sysfrom typing import Any, Dict, List-from _common import STATE, add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, time_arg, probe, run, validate_color, video_args, X264_PRESETS, fmt_secs+from _common import STATE, add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, time_arg, matrix_chain, probe, run, validate_color, video_args, X264_PRESETS, fmt_secsdef main() -> int:@@ -87,7 +87,7 @@ def main() -> int:die(f"cutaway {i + 1}: {path} has only {dur_b - start_b:.3f}s from {start_b:g}s, {length:g}s asked for")if cutaways and at < cutaways[-1]["at"] + cutaways[-1]["length"]:die(f"cutaway {i + 1} at {at:g}s overlaps the previous one (ends {cutaways[-1]['at'] + cutaways[-1]['length']:g}s)")- cutaways.append({"path": path, "at": at, "length": length, "from": start_b, "has_audio": bool(meta_b.get("audio"))})+ cutaways.append({"path": path, "at": at, "length": length, "from": start_b, "has_audio": bool(meta_b.get("audio")), "meta": meta_b})if args.audio != "a" and not all(c["has_audio"] for c in cutaways):die("--audio b/mix needs audio on every B-roll clip")@@ -101,10 +101,14 @@ def main() -> int:# A shows through unchanged, so A's timeline is never touched.parts: List[str] = []cur = "[0:v]"+ # every clip is converted by its own colour tags to the BT.709 the output is tagged with+ if matrix_chain(meta_a, meta_a):+ parts.append(f"[0:v]{matrix_chain(meta_a, meta_a)}null[a709]")+ cur = "[a709]"for i, c in enumerate(cutaways):geo = f"scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={args.pad_color}"parts.append(f"[{i + 1}:v]trim=start={c['from']:.3f}:duration={c['length']:.3f},setpts=PTS-STARTPTS+{c['at']:.3f}/TB,"- f"{geo},setsar=1,fps={fps:g},format={'yuv420p10le' if (meta_a.get('video') or {}).get('bt2020_or_hdr') else 'yuv420p'}[b{i}]")+ f"{matrix_chain(c['meta'], meta_a)}{geo},setsar=1,fps={fps:g},format={'yuv420p10le' if (meta_a.get('video') or {}).get('bt2020_or_hdr') else 'yuv420p'}[b{i}]")parts.append(f"{cur}[b{i}]overlay=0:0:eof_action=pass:enable='between(t,{c['at']:.3f},{c['at'] + c['length']:.3f})'[v{i}]")cur = f"[v{i}]"vout = cur@@ -131,7 +135,7 @@ def main() -> int:cmd += ["-filter_complex", ";".join(parts), "-map", vout]if aout:cmd += ["-map", aout]- cmd += video_args(meta_a, args.crf, args.preset) + cfr_args(meta_a, None)+ cmd += video_args(meta_a, args.crf, args.preset, convert_matrix=False) + cfr_args(meta_a, None)if aout == "0:a:0":cmd += ["-c:a", "copy"]elif aout:diff --git a/scripts/check.py b/scripts/check.pyindex 4f95c96..7bb2ce4 100755--- a/scripts/check.py+++ b/scripts/check.py@@ -175,10 +175,10 @@ def main() -> int:# untagged 8-bit video is treated as BT.709 by every player and platform; nothing to fixrow("colour", "PASS", shown + " (players assume bt709)" if matrix else "untagged (players assume bt709)", "bt709/bt709 tagged (or HDR)")elif matrix in ("smpte170m", "bt470bg"):- # The pixels are BT.601-encoded. Nothing here converts the matrix: --retag bt709 and- # every SDR re-encode (bt709_tag_args) only relabel it, which shifts the colours.+ # The pixels are BT.601-encoded. A re-encode here converts them to the BT.709 it tags+ # (bt709_matrix_filter); --retag bt709 is a stream copy and only relabels the matrix.row("colour", "WARN", shown, "bt709/bt709 tagged (or HDR)",- "re-export from the master as BT.709; color.py --retag bt709 (like any re-encode here) only relabels the matrix: right only if the pixels really are BT.709",+ "export.py (any re-encode here converts the BT.601 matrix to BT.709); color.py --retag bt709 only relabels it: right only if the pixels really are BT.709",reason="a player that honours the BT.601 tag and one that ignores it on HD video (decoding it as BT.709) show different colours")else:row("colour", "WARN", shown, "bt709/bt709 tagged (or HDR)", "color.py --retag bt709 when the picture really is 709; color.py --to-sdr when it is HDR")diff --git a/scripts/color.py b/scripts/color.pyindex e61acc3..feb64b2 100755--- a/scripts/color.py+++ b/scripts/color.py@@ -353,7 +353,9 @@ def main() -> int:tag = "lut"cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf, "-map", "0:v:0", "-map", f"0:a:{args.audio_stream}?"]- cmd += x264_args(args.crf, args.preset) + cfr_args(meta) + (aac_args() if has_audio else [])+ # --lut/--correct grade the source's own pixels, so a BT.601 source is converted to the BT.709+ # the line is tagged with; --to-sdr's zscale chain already writes BT.709 and converts nothing more+ cmd += x264_args(args.crf, args.preset, source=None if args.to_sdr else meta) + cfr_args(meta) + (aac_args() if has_audio else [])dropped_streams = run_keeping_subtitles(cmd, output)r = probe(output, role="output")info(f"wrote {output} ({fmt_secs(r['duration'])}, {r['video']['width']}x{r['video']['height']}, "diff --git a/scripts/export.py b/scripts/export.pyindex 364fc6d..ddf2446 100755--- a/scripts/export.py+++ b/scripts/export.py@@ -36,7 +36,7 @@ import sysfrom pathlib import Pathfrom typing import Dict, List-from _common import STATE, add_common, apply_common, bt709_tag_args, child_args, emit, cfr_args, default_output, die, encoder_args, ffmpeg_base, info, probe, run, run_tool, validate_color, pad_filters, add_pad_fill_args, fmt_secs+from _common import STATE, add_common, apply_common, bt709_matrix_args, bt709_tag_args, child_args, emit, cfr_args, default_output, die, encoder_args, ffmpeg_base, info, probe, run, run_tool, validate_color, pad_filters, add_pad_fill_args, fmt_secsfrom _common.decision import hw_preset_video, restate_last_swapfrom check import SPECS as PLATFORMS, measure_loudnessfrom _platforms import ALIASES as _ALIASES, PLATFORMS as PLATFORM_TABLE, resolve as resolve_platform@@ -216,6 +216,11 @@ def main() -> int:cmd += cfr_args(meta)if tag_bt709 and not video[video.index("-c:v") + 1].endswith("_videotoolbox"):cmd += bt709_tag_args(video[video.index("-c:v") + 1])+ if args.preset != "prores":+ # every line but the prores master's says BT.709 (the fixed presets' tags above, an+ # SDR hevc/av1 line's own): a BT.601 source's pixels are converted to match, in front+ # of the -vf above (run() folds the two); an untagged, BT.709 or HDR source adds nothing+ cmd += bt709_matrix_args(meta)if out_ext == "mp4":cmd += ["-movflags", "+faststart"]cmd += (p["audio"] if has_audio else ["-an"])diff --git a/scripts/join.py b/scripts/join.pyindex 6eef884..ea0433e 100755--- a/scripts/join.py+++ b/scripts/join.py@@ -39,7 +39,7 @@ import osimport sysfrom typing import Any, Dict, List, Optional, Tuple-from _common import STATE, AUDIO_MEDIA_EXT, video_args, aac_args, add_common, apply_common, audio_codec_for, default_output, die, dry_run_input_pending, emit, ffmpeg_base, info, measured_level_dbfs, is_audio_output, probe, require_tool, run, validate_color, X264_PRESETS, fmt_secs+from _common import STATE, AUDIO_MEDIA_EXT, matrix_chain, video_args, aac_args, add_common, apply_common, audio_codec_for, default_output, die, dry_run_input_pending, emit, ffmpeg_base, info, measured_level_dbfs, is_audio_output, probe, require_tool, run, validate_color, X264_PRESETS, fmt_secsTRANSITIONS = ["fade", "dissolve", "wipeleft", "wiperight", "wipeup", "wipedown", "slideleft", "slideright","circleopen", "circleclose", "fadeblack", "fadewhite", "smoothleft", "smoothright", "radial", "none"]@@ -497,7 +497,8 @@ def main() -> int:if len(set(chans)) > 1:info(f"channel counts differ ({', '.join(str(c) for c in chans)}); every clip becomes {layout}")for i in range(n):- parts.append(f"[{i}:v]{geo},setsar=1,fps={fps:g},format={pixfmt},settb=AVTB[v{i}]")+ # a BT.601 clip is converted to the BT.709 the join is tagged with, each clip by its own tags+ parts.append(f"[{i}:v]{matrix_chain(metas[i], hdr_meta or metas[0])}{geo},setsar=1,fps={fps:g},format={pixfmt},settb=AVTB[v{i}]")parts.append(f"[{audio_src[i]}]aformat=sample_rates=48000:channel_layouts={layout},asetpts=PTS-STARTPTS[a{i}]")# pad the shorter stream to the clip's length: the audio with silence, the picture by holding@@ -541,7 +542,7 @@ def main() -> int:# to meet the AAC tail (a 51-frame dissolve came out 52), which newer builds no longer do -- pass# the frames through as built, for a plain cut as much as for a transitioncmd += ["-fps_mode", "passthrough"]- cmd += video_args(hdr_meta or metas[0], args.crf, args.preset) + aac_args() + [output]+ cmd += video_args(hdr_meta or metas[0], args.crf, args.preset, convert_matrix=False) + aac_args() + [output]run(cmd)expected = unpending_length(lens, d)r = probe(output, role="output")diff --git a/scripts/multicam.py b/scripts/multicam.pyindex 0eeb3b1..13b8fde 100755--- a/scripts/multicam.py+++ b/scripts/multicam.py@@ -31,7 +31,7 @@ import mathimport sysfrom typing import Dict, List, Tuple-from _common import video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, time_arg, probe, run, x264_args, X264_PRESETS, fmt_secs, decode_pcm_mono, rms_envelope, STATE+from _common import matrix_chain, video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, time_arg, probe, run, x264_args, X264_PRESETS, fmt_secs, decode_pcm_mono, rms_envelope, STATEfrom sync import measure_offsetENERGY_WINDOW_S = 0.25 # --switch energy: loudness measured over this window on the reference timeline@@ -276,7 +276,8 @@ def main() -> int:if src_s < 0:info(f"warning: camera {c} has not started at reference {s:.2f}s; using camera 0 for that range")c, src_s, src_e = 0, s, e- parts.append(f"[{c}:v]trim=start={src_s:.4f}:end={src_e:.4f},setpts=PTS-STARTPTS,{geo}[v{i}]")+ # each camera converted by its own colour tags to the BT.709 the cut is tagged with+ parts.append(f"[{c}:v]trim=start={src_s:.4f}:end={src_e:.4f},setpts=PTS-STARTPTS,{matrix_chain(metas[c], metas[0])}{geo}[v{i}]")labels.append(f"[v{i}]")project_clips.append({"src": args.inputs[c], "in": round(src_s, 3), "out": round(src_e, 3)})parts.append("".join(labels) + f"concat=n={len(filled)}:v=1:a=0[vout]")@@ -297,7 +298,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 += video_args(metas[0], args.crf, args.preset) + aac_args() + ["-t", f"{ref_dur:.3f}", output]+ cmd += video_args(metas[0], args.crf, args.preset, convert_matrix=False) + aac_args() + ["-t", f"{ref_dur:.3f}", output]if args.write_project:# Same cut decision as the combined render above (project_clips was built alongside thediff --git a/scripts/overlay.py b/scripts/overlay.pyindex c0ef259..7222ac1 100755--- a/scripts/overlay.py+++ b/scripts/overlay.py@@ -25,7 +25,7 @@ import sysfrom typing import List, Optionalfrom _platforms import PLATFORMS, PLATFORM_CHOICES, safe_margins_px, resolve as resolve_platform-from _common import STATE, script_font_for_text, drawtext_text_opts, needs_shaping, LANGUAGE_NAMES, has_emoji, detect_script, emoji_clusters, load_brand, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, X264_PRESETS, time_arg, fmt_secs+from _common import STATE, script_font_for_text, drawtext_text_opts, needs_shaping, LANGUAGE_NAMES, has_emoji, detect_script, emoji_clusters, load_brand, matrix_chain, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, X264_PRESETS, time_arg, fmt_secs# Per-edge margins: a platform's UI does not cover the same fraction of every edge (TikTok's# like column is 14 % of the width, its description block 22 % of the height), so a position@@ -299,7 +299,10 @@ def main() -> int:if enable:ov += f":enable='{enable}'"cmd = ffmpeg_base() + ["-i", args.input, "-i", args.video]- fc = f"[1:v]{','.join(chain)}[ov];[0:v][ov]{ov}[out]"+ # both pictures converted by their own colour tags to the BT.709 the output is tagged with+ base = matrix_chain(meta, meta)+ fc = (f"[1:v]{matrix_chain(pip_meta, meta)}{','.join(chain)}[ov];"+ + (f"[0:v]{base}null[base];[base]" if base else "[0:v]") + f"[ov]{ov}[out]")cmd += ["-filter_complex", fc, "-map", "[out]", "-map", f"0:a:{args.audio_stream}?"]if meta.get("duration"):# See the --image branch above: -t (exact, bounds only the main input) instead of@@ -329,7 +332,7 @@ def main() -> int:if meta.get("audio"):cmd += ["-map", f"0:a:{args.audio_stream}"]- cmd += video_args(meta, args.crf, args.preset) + cfr_args(meta)+ cmd += video_args(meta, args.crf, args.preset, convert_matrix=not args.video) + cfr_args(meta)cmd += aac_args() if meta.get("audio") else ["-an"]dropped_streams = run_keeping_subtitles(cmd, output)if not STATE.dry_run:diff --git a/tests/test_analysis.py b/tests/test_analysis.pyindex 4311ce7..5192ae6 100644--- a/tests/test_analysis.py+++ b/tests/test_analysis.py@@ -312,9 +312,10 @@ class AnalysisTests(MediaFixtures):if status == "PASS":self.assertEqual((row["fix"], row["reason"]), ("", ""), row)else:- # every WARN here is a BT.601 matrix: nothing converts it, so --retag bt709 is not the fix- self.assertTrue(row["fix"].startswith("re-export from the master as BT.709"), row)- self.assertIn("only relabels", row["fix"])+ # every WARN here is a BT.601 matrix: a re-encode converts it (after 2.10.0), --retag bt709+ # only relabels it, so the fix names the conversion first+ self.assertTrue(row["fix"].startswith("export.py (any re-encode here converts the BT.601 matrix to BT.709)"), row)+ self.assertIn("--retag bt709 only relabels", row["fix"])self.assertIn("BT.601", row["reason"])def test_check_default_rows_unchanged_without_content(self):diff --git a/tests/test_contract.py b/tests/test_contract.pyindex 1429832..edc3ca0 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -1030,6 +1030,70 @@ class ContractTests(unittest.TestCase):finally:_common._FFMPEG_VERSION = saved+ def test_bt601_matrix_conversion_rides_on_the_encoder_line(self):+ """The BT.709 tags are a label (above); a source whose matrix is BT.601 also needs its pixels+ converted, or it comes out BT.709-labelled over BT.601 pixels. The encoder line carries that+ conversion as a -vf, from the source's probe only: an untagged, BT.709 or HDR source, prores+ (which keeps the source's tags) and a tool that converts per input get nothing."""+ def meta(**v):+ return {"file": "src.mp4", "video": dict({"bt2020_or_hdr": False}, **v)}+ conv = "colorspace=ispace={}:iprimaries=bt709:itrc=bt709:space=bt709:primaries=bt709:trc=bt709"+ for matrix in ("smpte170m", "bt470bg", "fcc", "smpte240m"):+ self.assertEqual(_common.bt709_matrix_filter(meta(color_space=matrix)), conv.format(matrix), matrix)+ for m in (None, {}, meta(), meta(color_space="bt709"), meta(color_space="unknown"), meta(color_space="gbr"),+ meta(color_space="bt2020nc", bt2020_or_hdr=True), meta(color_space="smpte170m", bt2020_or_hdr=True)):+ self.assertIsNone(_common.bt709_matrix_filter(m), m)+ saved = (_common.STATE.codec, _common.STATE.hw)+ try:+ _common.STATE.hw = False+ for codec in (None, "h264", "hevc"):+ _common.STATE.codec = codec+ line = _common.video_args(meta(color_space="smpte170m"))+ self.assertEqual(line[-2:], ["-vf", conv.format("smpte170m")], codec)+ self.assertNotIn("-vf", _common.video_args(meta(color_space="bt709")), codec)+ self.assertNotIn("-vf", _common.video_args(meta()), codec)+ self.assertNotIn("-vf", _common.video_args(meta(color_space="smpte170m"), convert_matrix=False), codec)+ self.assertEqual(_common.x264_args(source=meta(color_space="bt470bg"))[-2:], ["-vf", conv.format("bt470bg")], codec)+ self.assertNotIn("-vf", _common.x264_args(), codec)+ self.assertEqual(_common.matrix_chain(meta(color_space="smpte170m"), meta()), conv.format("smpte170m") + ",")+ self.assertEqual(_common.matrix_chain(meta(), meta()), "")+ # an HDR line keeps its own tags: a BT.601 clip joined into it is not "converted to BT.709"+ self.assertEqual(_common.matrix_chain(meta(color_space="smpte170m"), meta(bt2020_or_hdr=True)), "")+ _common.STATE.codec = "prores"+ self.assertNotIn("-vf", _common.video_args(meta(color_space="smpte170m")))+ self.assertEqual(_common.matrix_chain(meta(color_space="smpte170m"), meta()), "")+ finally:+ _common.STATE.codec, _common.STATE.hw = saved++ def test_fold_bt709_matrix_into_the_tools_graph(self):+ """run() moves the encoder line's conversion -vf into the tool's own graph, first: with no+ other filter it is the graph; a -vf gets it prepended; a -filter_complex reads every input+ that opens input 0's file through it (once per input, split when read twice), other inputs+ untouched. A command without it is returned as it was."""+ conv = _common.bt709_matrix_filter({"video": {"color_space": "smpte170m"}})+ fold = _common.fold_bt709_matrix+ enc = ["-c:v", "libx264", "-crf", "18", "-vf", conv, "out.mp4"]+ self.assertEqual(fold(["ffmpeg", "-i", "a.mp4"] + enc), ["ffmpeg", "-i", "a.mp4"] + enc)+ self.assertEqual(fold(["ffmpeg", "-i", "a.mp4", "-vf", "scale=2:2,setsar=1"] + enc),+ ["ffmpeg", "-i", "a.mp4", "-vf", f"{conv},scale=2:2,setsar=1", "-c:v", "libx264", "-crf", "18", "out.mp4"])+ # speedramp reads [0:v] once per segment; a logo (input 1) is not the source+ got = fold(["ffmpeg", "-i", "a.mp4", "-i", "logo.png", "-filter_complex",+ "[0:v]trim=0:1[x];[0:v]trim=1:2[y];[1:v]scale=9:9[l];[x][y]concat[c];[c][l]overlay[out]", "-map", "[out]"] + enc)+ self.assertEqual(got[got.index("-filter_complex") + 1],+ f"[0:v]{conv},split=2[bt709src0][bt709src1];"+ "[bt709src0]trim=0:1[x];[bt709src1]trim=1:2[y];[1:v]scale=9:9[l];[x][y]concat[c];[c][l]overlay[out]")+ self.assertNotIn(conv, got[got.index("-filter_complex") + 2:])+ # cut.py's segment join opens the source once per segment; join.py's second clip is another file+ got = fold(["ffmpeg", "-ss", "1", "-i", "a.mp4", "-ss", "5", "-i", "a.mp4", "-i", "b.mp4", "-filter_complex",+ "[0:v:0]trim=0:1[v0];[1:v:0]trim=0:1[v1];[2:v]null[v2];[v0][v1][v2]concat=n=3[v]", "-map", "[v]"] + enc)+ self.assertEqual(got[got.index("-filter_complex") + 1],+ f"[0:v:0]{conv}[bt709src0];[1:v:0]{conv}[bt709src1];"+ "[bt709src0]trim=0:1[v0];[bt709src1]trim=0:1[v1];[2:v]null[v2];[v0][v1][v2]concat=n=3[v]")+ plain = ["ffmpeg", "-i", "a.mp4", "-vf", "scale=2:2", "-c:v", "libx264", "out.mp4"]+ self.assertEqual(fold(plain), plain)+ with self.assertRaises(SystemExit):+ fold(["ffmpeg", "-i", "a.mp4", "-filter_complex", "color=red[v]", "-map", "[v]"] + enc)+# ------------------------------------------------------------------ consistency: MCP and installerdef test_mcp_tools_match_contract(self):"""FFMPEG_SKILL_MCP_FULL=1 is the escape hatch back to the pre-1.18.3 behaviour: every@@ -1711,6 +1775,51 @@ class ContractTests(unittest.TestCase):self.assertEqual(tool("probe", self.src, "--dry-run", env=env).returncode, 0)self.assertEqual(tool("check", self.src, "--platform", "x", "--no-loudness", "--dry-run", env=env).returncode, 0)+ def test_every_reencoding_tool_plans_the_bt601_conversion(self):+ """Through 2.10.0 a BT.601-matrix source came out of every SDR re-encode tagged BT.709 with its+ pixels untouched. The conversion rides on the shared encoder line and run() folds it into each+ tool's own graph, so this plans every tool that re-encodes one or several sources: on a+ BT.601 source each input read from that file is converted once (cut's segment join opens it+ once per segment), a mixed join/multicam/broll/overlay --video converts only the BT.601+ input, and copies, the prores master and an untagged source plan no conversion at all."""+ s601 = OUT / "c_source601.mp4"+ if not s601.exists():+ ffmpeg("-i", self.src, "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-x264-params",+ "colorprim=smpte170m:transfer=smpte170m:colormatrix=smpte170m", "-c:a", "copy", s601)+ self.assertEqual(json.loads(tool("probe", s601, "--json").stdout)["video"]["color_space"], "smpte170m")+ conv = "colorspace=ispace=smpte170m:"+ cases = [ # (tool, args after the input, conversions on a BT.601 input)+ ("export", ["--preset", "reels"], 1), ("export", ["--preset", "prores"], 0), ("export", ["--preset", "copy"], 0),+ ("export", ["--preset", "x", "--pad-fill", "blur"], 1),+ ("fit", ["--width", "320", "--height", "320"], 1), ("cut", ["--start", "1", "--end", "3", "--accurate"], 1),+ ("cut", ["--segments", "0.5-1.5,2-3", "--accurate"], 2), ("cut", ["--start", "1", "--end", "3"], 0),+ ("crop", ["--x", "0", "--y", "0", "--width", "100", "--height", "100"], 1), ("deinterlace", [], 1), ("denoise", [], 1),+ ("freeze", ["--at", "1", "--hold", "1"], 1), ("graphics", ["--template", "title", "--title", "T"], 1),+ ("loop", ["--times", "2"], 1), ("loop", ["--times", "2", "--boomerang"], 1),+ ("overlay", ["--image", self.logo], 1), ("overlay", ["--text", "hi"], 1), ("overlay", ["--video", self.camb], 1),+ ("pad", ["--start", "1"], 1), ("proxy", [], 1), ("redact", ["--x", "0", "--y", "0", "--width", "100", "--height", "100"], 1),+ ("reverse", [], 1), ("speedramp", ["--segment", "0-3:2", "--segment", "3-6:1"], 1), ("straighten", ["--degrees", "2"], 1),+ ("caption", ["--text", self.cues], 1), ("color", ["--correct", "--exposure", "0.2"], 1),+ ("join", [self.camb], 1), ("broll", ["--insert", self.camb, "--at", "1", "--duration", "1"], 1),+ ("multicam", [self.camb, "--switch", "0-2:0,2-4:1"], 2), # camera 0 also fills 4-6 s: one chain per window+ ]+ for n, (name, args, want) in enumerate(cases):+ for src, expected in ((s601, want), (self.src, 0)):+ with self.subTest(tool=name, args=args, source=src.name):+ ext = ".mov" if "prores" in args else ".mp4"+ proc = tool(name, src, *args, "-o", self.out(f"bt601_{n}{ext}"), "--dry-run", "--json", check=False)+ self.assertEqual(proc.returncode, 0, proc.stderr[-600:])+ commands = " ".join(json.loads(proc.stdout)["commands"])+ self.assertEqual(commands.count(conv), expected, commands)+ if src == self.src:+ self.assertNotIn("colorspace=", commands)+ # the other way round: the BT.601 file as the second input is converted in its own chain+ for name, args in (("join", [self.camb, s601]), ("broll", [self.camb, "--insert", s601, "--at", "1", "--duration", "1"]),+ ("overlay", [self.camb, "--video", s601])):+ with self.subTest(tool=name, second=True):+ commands = " ".join(json.loads(tool(name, *args, "-o", self.out(f"bt601_2nd_{name}.mp4"), "--dry-run", "--json").stdout)["commands"])+ self.assertEqual(commands.count(conv), 1, commands)+def test_json_success_and_failure_shapes_and_exit_codes(self):doc = json.loads(tool("cut", self.wav, "--start", "1", "--end", "3", "-o", self.out("shape.wav"), "--json").stdout)self.assertEqual(doc["status"], "completed")diff --git a/tests/test_picture.py b/tests/test_picture.pyindex 31ed262..5298817 100644--- a/tests/test_picture.py+++ b/tests/test_picture.py@@ -2223,6 +2223,93 @@ class PictureTests(MediaFixtures):self.assertEqual((OUT / "cap_mux_auto.srt").read_bytes(),(OUT / "cap_mux_off.srt").read_bytes())++class Bt601ConversionTests(unittest.TestCase):+ """A BT.601-matrix source re-encoded here comes out tagged BT.709 *and* converted to it. Through+ 2.10.0 only the label changed: export.py --preset reels on a smpte170m clip wrote+ bt709/bt709/bt709 over pixels 48.5 dB YUV PSNR from the source (untouched), so every player+ that honours the tag showed shifted colours.++ The pictures are compared in RGB, each decoded with the matrix it is tagged with (the source as+ BT.601, the output as BT.709): a converted output matches its source there, a relabelled one+ does not. Both sides' tags are pinned first, as in MediaFixtures._psnr, so no FFmpeg 7.1++ negotiation adds a conversion of its own."""++ @classmethod+ def setUpClass(cls):+ encoders = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], stdout=subprocess.PIPE, text=True).stdout+ if "libx264" not in encoders:+ raise unittest.SkipTest("this ffmpeg build has no libx264")+ OUT.mkdir(parents=True, exist_ok=True)+ cls.clips = {}+ for name, params, size in (("full601", "colorprim=smpte170m:transfer=smpte170m:colormatrix=smpte170m", "320x240"),+ ("bt470bg", "colormatrix=bt470bg", "320x240"),+ ("untagged", None, "320x240"),+ ("bt709", "colorprim=bt709:transfer=bt709:colormatrix=bt709", "320x240"),+ ("reels601", "colorprim=smpte170m:transfer=smpte170m:colormatrix=smpte170m", "1080x1920")):+ path = OUT / f"matrix_{name}.mp4"+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", f"testsrc2=s={size}:r=30:d={1 if size == '1080x1920' else 2}",+ "-f", "lavfi", "-i", "sine=sample_rate=48000:d=2", "-c:v", "libx264", "-preset", "ultrafast", "-crf", "8", "-pix_fmt", "yuv420p",+ *(["-x264-params", params] if params else []), "-c:a", "aac", "-shortest", path)+ cls.clips[name] = path++ @staticmethod+ def _rgb_psnr(a, a_matrix, b, b_matrix, seek=None):+ """PSNR in RGB of b (decoded with b_matrix) against a (decoded with a_matrix), over b's frames;+ `seek` = (start, length) of a that b holds."""+ def leg(i, m):+ tag = {"bt601": "smpte170m", "bt709": "bt709"}[m]+ return (f"[{i}:v]setpts=N/FRAME_RATE/TB,setparams=colorspace={tag}:color_primaries=bt709:color_trc=bt709:range=tv,"+ f"scale=in_color_matrix={m}:in_range=tv:out_range=pc,format=gbrp[{'ab'[i]}]")+ cut = ["-ss", str(seek[0]), "-t", str(seek[1])] if seek else []+ proc = subprocess.run(["ffmpeg", "-hide_banner", *cut, "-i", str(a), "-i", str(b), "-lavfi",+ f"{leg(0, a_matrix)};{leg(1, b_matrix)};[a][b]psnr", "-f", "null", "-"],+ stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")+ m = re.search(r"average:(inf|[\d.]+)", proc.stderr)+ assert m, proc.stderr[-400:]+ return float("inf") if m.group(1) == "inf" else float(m.group(1))++ def _runs(self, name):+ """(tool, output, seek, result document) for fit.py and cut.py --accurate on clip `name`."""+ src = self.clips[name]+ for tool, args, seek in (("fit.py", ["--width", "320", "--height", "240", "--quality", "8"], None),+ ("cut.py", ["--start", "0.5", "--end", "1.5", "--accurate", "--quality", "8"], (0.5, 1))):+ out = OUT / f"matrix_{name}_{tool[:-3]}.mp4"+ doc = json.loads(script(tool, src, *args, "--fast", "--json", "-o", out).stdout)+ yield tool, out, seek, doc++ def _assert_bt709_tags(self, out):+ v = probe(str(out))["video"]+ self.assertEqual((v["color_space"], v["color_primaries"], v["color_transfer"]), ("bt709", "bt709", "bt709"))++ def test_a_bt601_source_is_converted_to_the_bt709_it_is_tagged_with(self):+ # the issue's reproduction: export.py --preset reels on a 1080x1920 smpte170m clip+ src = self.clips["reels601"]+ out = OUT / "matrix_reels601_export.mp4"+ doc = json.loads(script("export.py", src, "--preset", "reels", "--fast", "--crf", "8", "--json", "-o", out).stdout)+ self.assertIn("colorspace=ispace=smpte170m", " ".join(doc["commands"]))+ cases = [("export.py", out, None, src)] + [(t, o, s, self.clips[n]) for n in ("full601", "bt470bg") for t, o, s, _ in self._runs(n)]+ for tool, out, seek, src in cases:+ with self.subTest(tool=tool, source=src.name):+ self._assert_bt709_tags(out)+ converted = self._rgb_psnr(src, "bt601", out, "bt709", seek)+ relabelled = self._rgb_psnr(src, "bt709", out, "bt709", seek)+ # measured 42.2 dB converted (5.1.1, 6.1, a 7.1 snapshot); the 2.10.0 relabel was 24.8 dB+ # here and 52 dB on the second comparison, which a converted picture can't reach+ self.assertGreater(converted, 38.0, f"{tool}: the BT.709 output does not show the BT.601 source's colours")+ self.assertLess(relabelled, 32.0, f"{tool}: the pixels were relabelled, not converted")++ def test_an_untagged_or_bt709_source_is_not_converted(self):+ """Untagged SDR is taken as BT.709 by players, and converting it is the 7.1 auto-conversion+ bt709_tag_args() exists to avoid: no conversion is planned and the pixels stay the source's."""+ for name in ("untagged", "bt709"):+ for tool, out, seek, doc in self._runs(name):+ with self.subTest(tool=tool, source=name):+ self.assertNotIn("colorspace=", " ".join(doc["commands"]))+ self._assert_bt709_tags(out)+ self.assertGreater(self._rgb_psnr(self.clips[name], "bt709", out, "bt709", seek), 45.0, tool)++class ScriptFontTests(unittest.TestCase):"""1.12: which script text is written in, and a font file that actually covers it."""