remotion-ffmpeg-skill 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,7 +36,7 @@ Built on [**ffmpeg-skill**](https://github.com/kajisho5/ffmpeg-skill). Unofficia
36
36
  |---|---|---|
37
37
  | Writes Remotion compositions | ✅ | ✅ (three ready-made, timeline-driven) |
38
38
  | Knows the source's real duration / fps / size / silences / scene cuts / audio peaks | — | ✅ measured by ffmpeg-skill |
39
- | Warns before drawing on VFR or HDR footage | — | ✅ |
39
+ | Never draws on VFR or HDR footage as is: refuses it, or (`--conform`) draws on a CFR, SDR BT.709 copy ffmpeg-skill made, original untouched | — | ✅ |
40
40
  | Verifies the render (exact frame count, fps, size, audio) | — | ✅ non-zero exit on mismatch |
41
41
  | Looks at the result (contact sheet) | — | ✅ |
42
42
  | Delivers for YouTube / Reels / TikTok / Shorts / X with loudness and compliance checks | — | ✅ ffmpeg-skill templates + `check.py` |
package/SKILL.md CHANGED
@@ -14,7 +14,7 @@ Shared flags (every script): `--json` (one JSON object on stdout; prefer it), `-
14
14
  ## Workflow (in this order)
15
15
 
16
16
  1. **Project once.** No Remotion project yet: `init.py ./motion --install` (copies the template, runs `npm install`; Remotion's headless browser downloads on the first render). An existing project from this skill: reuse it.
17
- 2. **Measure.** `analyze.py SOURCE [--captions FILE.srt] [--beats] -o SOURCE.timeline.json`. Read the summary and the `warnings`: a VFR or HDR source must be fixed with ffmpeg-skill *before* drawing (`color.py --to-sdr`, a constant-frame-rate export) — Remotion renders SDR on a fixed frame grid. Never write or edit timeline numbers by hand; re-measure instead (`--threshold`, `--min-silence` for a quiet room).
17
+ 2. **Measure.** `analyze.py SOURCE [--captions FILE.srt] [--beats] -o SOURCE.timeline.json`. Read the summary and the `warnings`. A variable-frame-rate or HDR / BT.2020 source is refused (`kind: input`, `conform_needed`): Remotion renders SDR on a fixed frame grid. Re-run with `--conform` and ffmpeg-skill makes a constant-frame-rate (`fit.py --fps`, the stream's base rate; `--conform-fps` to choose) SDR BT.709 (`color.py --to-sdr`, tone-mapped) copy, `<name>_conformed.mp4` (`--conformed` to place it); that copy is measured and drawn on, the original stays untouched and the timeline's `conform` records the steps. HDR → SDR changes the look: tell the user, and check a still. The same goes for a `--pip` camera. Never write or edit timeline numbers by hand; re-measure instead (`--threshold`, `--min-silence` for a quiet room).
18
18
  3. **Preview stills.** `still.py --project ./motion --comp NAME --timeline TL --at 1.5 --at 6` and view the PNGs: caption placement, punch-in, colours. Cheap; do it before a full render.
19
19
  4. **Render.** `render.py --project ./motion --comp NAME --timeline TL [--options look.json] -o OUT.mp4` (`--fast` = half-size preview, `--frames 0-89` = a range, `--codec prores -o master.mov` = a master). It verifies the output against the timeline (frame count, fps, size, audio) and exits non-zero on a mismatch.
20
20
  - **Shape:** draw in the shape it will be delivered in. `--aspect 9:16` for Reels / TikTok / Shorts (`1:1`, `4:5`, `16:9` too); `--fit blur` (default when the shape changes: contained over a blurred copy), `contain` (bars) or `cover` (crop — check the subject in the still first). Never render 16:9 and let a 9:16 template crop it: captions lose their edges. `pipeline.py --platform` picks the aspect from ffmpeg-skill's template for you.
@@ -61,6 +61,7 @@ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts
61
61
  | captions or name titles on long footage (a talk, a lecture) | `render.py --comp Captioned --sparse` (or `Karaoke`, `Titled`): only the stretches where something shows are drawn |
62
62
  | "change colour / font / caption size / zoom" | an `--options` JSON (`references/timeline.md`), re-render |
63
63
  | "use our brand" / a `brand.json` (ffmpeg-skill's format) | `--brand brand.json` on render / still / pipeline: its colours, caption colour, font and font file set the look (an `--options` file wins key by key); `deliver.py` / `pipeline.py --brand` places its logo with the template |
64
+ | a phone clip (VFR) or HDR / iPhone HDR / HLG footage | `analyze.py --conform` (or `pipeline.py --conform`): drawn on a CFR SDR BT.709 copy ffmpeg-skill made; without the flag it is refused |
64
65
  | several clips ("intro + talk + outro") | `analyze.py A.mp4 B.mov C.mp4` (or `pipeline.py` with several inputs): ffmpeg-skill join.py normalises and joins them, then everything is measured on the joined file |
65
66
  | "preview" / "show me a frame" | `still.py` |
66
67
  | a new kind of graphic | add a composition to `src/` of the project that reads `Props` from `src/timeline.ts`; render with `--comp YourId` (render.py then reports measured numbers without a built-in expectation) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remotion-ffmpeg-skill",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Agent Skill: ffmpeg-skill measures the footage, Remotion draws the motion graphics from those measurements, ffmpeg-skill checks and delivers the result. Timeline-driven captions, silence jump cuts and audio-peak motion with probe-first / verify-last rendering. Local, no API keys.",
5
5
  "keywords": [
6
6
  "remotion",
@@ -6,7 +6,7 @@ Read the one you need; SKILL.md has the one-line versions.
6
6
  ## Frames and timing
7
7
  - **Python `round()` is not JavaScript `Math.round()`.** 3.15 s × 30 fps = 94.5: Python gives 94 (half to even), the composition gives 95. render.py's expected frame count was off by one frame per half-frame boundary. Both sides now use round-half-up (`sec_to_frames`, `secToFrames`); a test pins it.
8
8
  - **Count frames, not seconds.** AAC priming/padding makes a container 20–50 ms longer than its picture. render.py compares the video stream's `nb_frames` with the expected count exactly and only falls back to a duration tolerance when the container has no frame count.
9
- - **Variable frame rate sources drift.** Remotion renders on a fixed grid; analyze.py warns on suspected VFR. Make a constant-frame-rate copy with ffmpeg-skill first.
9
+ - **Variable frame rate sources drift.** Remotion renders on a fixed grid. analyze.py refuses a suspected-VFR source; `--conform` makes a constant-frame-rate copy with ffmpeg-skill `fit.py --fps` at the stream's base rate (r_frame_rate, so no frame is dropped; the average rate of a phone clip is not a frame grid) and measures and draws on that.
10
10
 
11
11
  ## Files Remotion can and cannot read
12
12
  - **Symlinks in `public/` 404.** Remotion's file server refuses a symlink that points outside the project. Sources and fonts are hard-linked (instant, no extra space) or copied once.
@@ -14,7 +14,7 @@ Read the one you need; SKILL.md has the one-line versions.
14
14
  - **Props files are named by content** (`.rfs/props-<comp>-<hash>.json`): one name per composition used to let two parallel renders overwrite each other's props.
15
15
 
16
16
  ## Picture
17
- - **HDR / BT.2020 looks washed out.** Chrome composites in SDR. analyze.py warns; convert with ffmpeg-skill `color.py --to-sdr` first.
17
+ - **HDR / BT.2020 looks washed out.** Chrome composites in SDR. analyze.py refuses PQ / HLG / Dolby Vision and BT.2020 sources; `--conform` tone-maps a copy to SDR BT.709 with ffmpeg-skill `color.py --to-sdr`. A VFR HDR source is made CFR first (`fit.py` keeps HDR), then tone-mapped once: `color.py` on a VFR input would conform it to the *average* rate itself.
18
18
  - **Delivery templates crop.** ffmpeg-skill's Reels / TikTok / Shorts templates fit to 9:16 by cropping, so a 16:9 render loses the edges of every caption. Render in the delivery shape (`--aspect 9:16`, or `pipeline.py --platform`, which reads the template's aspect).
19
19
  - **Remotion's default concurrency is half the CPU cores.** render.py passes `--concurrency 100%`: 30 s of 1080p30 on 2 cores went from 170 s to 80 s. A number above the core count is an error.
20
20
  - **`--overlay` is not faster.** Transparent PNG frames plus ProRes 4444 cost about what decoding the source saves (170 s vs 174 s for 30 s of 1080p30 on 2 cores). It exists for handing a graphics layer to an editing app.
@@ -11,9 +11,9 @@ Exit codes: input = 2, missing_tool = 3, timeout = 4, failed = 1.
11
11
  Measure a source with ffmpeg-skill and write timeline.json (+ captions from a file).
12
12
 
13
13
  - Role: analysis — measures media and writes a data file (no media)
14
- - Writes: timeline.json
15
- - Verifies: every number comes from ffmpeg-skill probe/scenes/silence; warnings for VFR/HDR/rotation
16
- - ffmpeg-skill: probe, scenes, silence
14
+ - Writes: timeline.json (+ the joined source for several inputs, the conformed copy with --conform)
15
+ - Verifies: every number comes from ffmpeg-skill probe/scenes/silence; a VFR or HDR source is refused, or with --conform conformed and re-measured (CFR at the asked rate, SDR BT.709) before use; warnings for rotation and odd frame rates
16
+ - ffmpeg-skill: probe, scenes, silence, join (several inputs), sync (--pip), fit (--conform: VFR -> CFR), color (--conform: HDR -> SDR)
17
17
  - `--dry-run`: plans without writing
18
18
 
19
19
  | Argument | Type | Default | Meaning |
@@ -29,6 +29,9 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
29
29
  | `--pip` | string | | a second recording (camera) for the Pip composition: picture-in-picture over the source. The offset between the two is measured from their audio with ffmpeg-skill sync.py |
30
30
  | `--pip-offset` | number | | with --pip: the camera starts this many seconds after the source (negative: before), instead of measuring it -- for a camera without usable audio |
31
31
  | `--pip-max-offset` | number | `30.0` | with --pip: largest offset sync.py searches, in seconds (default 30) |
32
+ | `--conform` | boolean | | a variable-frame-rate or HDR / BT.2020 source (or --pip camera) is first made into a constant-frame-rate, SDR BT.709 copy with ffmpeg-skill (fit.py --fps, color.py --to-sdr: tone-mapped, so the look changes) and everything is measured and drawn on that copy; the original is never modified. Without it such a source is refused |
33
+ | `--conformed` | string | | with --conform: where the conformed copy of the source goes (default: <name>_conformed.mp4) |
34
+ | `--conform-fps` | number | | with --conform: the constant frame rate for a VFR source (default: the stream's base rate, r_frame_rate, so no frame is dropped) |
32
35
  | `--beats` | boolean | | also measure the beat grid (scenes.py --beats) |
33
36
  | `--highlights` | integer | | also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition |
34
37
  | `--target` | number | | with --highlights: total length the picks add up to |
@@ -39,7 +42,7 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
39
42
  | `--margin` | number | | seconds of silence kept around speech (default 0.15) |
40
43
  | `--scene-threshold` | number | | scenes.py --threshold (default 8) |
41
44
 
42
- --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `verified` (bool), `summary` (object: duration, fps, size, scenes, silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words), `warnings` (list[str])
45
+ --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `verified` (bool), `summary` (object: duration, fps, size, scenes, silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, conformed (list: vfr / hdr)), `warnings` (list[str])
43
46
 
44
47
  --dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str])
45
48
 
@@ -161,7 +164,7 @@ analyze -> render -> deliver in one call, stopping at the first failed step.
161
164
  - Role: orchestration — runs other tools in order, each verified before the next
162
165
  - Writes: timeline.json, render, deliverable
163
166
  - Verifies: each step's own verification
164
- - ffmpeg-skill: probe, scenes, silence, look, render --template, check
167
+ - ffmpeg-skill: probe, scenes, silence, fit (--conform), color (--conform), look, render --template, check
165
168
  - `--dry-run`: plans without writing
166
169
 
167
170
  | Argument | Type | Default | Meaning |
@@ -176,6 +179,7 @@ analyze -> render -> deliver in one call, stopping at the first failed step.
176
179
  | `--platform` | string: youtube / youtube-shorts / shorts / reels / tiktok / x / facebook / linkedin / podcast / audiogram | | deliver with this ffmpeg-skill template and check it |
177
180
  | `--out-dir` | string | | where the timeline, render and deliverable go (default: next to the input) |
178
181
  | `--beats` | boolean | | measure the beat grid too |
182
+ | `--conform` | boolean | | a variable-frame-rate or HDR source is made into a constant-frame-rate, SDR BT.709 copy with ffmpeg-skill first (analyze.py --conform; the copy goes in --out-dir) and drawn on; without it such a source is refused |
179
183
  | `--fast` | boolean | | preview-quality render |
180
184
  | `--aspect` | string: source / 16:9 / 9:16 / 1:1 / 4:5 / 4:3 | | output shape (default: the shape the --platform template delivers, else the source's) |
181
185
  | `--width` | integer | | output width in px |
@@ -11,7 +11,7 @@ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay":
11
11
  |---|---|---|---|
12
12
  | `schema` | string | — | always `remotion-ffmpeg-skill/timeline@1` |
13
13
  | `generator` | object | — | this skill's version and the ffmpeg-skill version that measured |
14
- | `source.path` | string | analyze.py | absolute path of the measured file |
14
+ | `source.path` | string | analyze.py | absolute path of the measured file (the conformed copy after `--conform`) |
15
15
  | `source.src` | string \| null | render.py | `staticFile()` path inside `public/` (added at render time) |
16
16
  | `source.duration` | seconds | probe.py | container duration |
17
17
  | `source.fps` | number | probe.py | composition fps = source fps |
@@ -28,7 +28,8 @@ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay":
28
28
  | `chapters` | `[{start, end, title}]` | `--chapters FILE` (`TIME TITLE` per line, YouTube's format) or `--chapters source` (the file's own markers) | titles as written; each ends where the next starts. YouTube's rules (first at 0:00, at least three, each ≥ 10 s) become warnings |
29
29
  | `pip` | `{path, name, duration, width, height, fps, offset, confidence, measured}` or null | `--pip CAMERA` (offset from ffmpeg-skill sync.py over both audio tracks) or `--pip-offset` | offset = seconds after the source's start at which the camera's first frame belongs (negative: the camera started first) |
30
30
  | `words` | `[{start, end, text}]` | `--words` (whisper JSON with word timestamps, `{"words": [...]}` or a list) | per-word timings with the engine's own spacing; Karaoke lights them up |
31
- | `warnings` | `[string]` | analyze.py | VFR, HDR, rotation, odd frame rate |
31
+ | `conform` | object \| null | analyze.py `--conform` | provenance when the source was VFR or HDR: `reasons` (`vfr`, `hdr`), `original` (path, name, sha256 fingerprint, duration, frame rates, colour tags), `output` (= `source.path`), `steps` (`{reason, tool, args, command, notes}` per ffmpeg-skill call: `fit.py --fps`, then `color.py --to-sdr`), `measured` (ffmpeg-skill probe of the copy: CFR, BT.709). `pip.conform` is the same for a conformed camera. null = the source was drawn on as it is |
32
+ | `warnings` | `[string]` | analyze.py | rotation, odd frame rate, chapters, transcript (VFR and HDR are never warnings: conformed or refused) |
32
33
 
33
34
  All times are seconds on the source timeline. Frames are `Math.round(seconds * fps)` (round
34
35
  half up) in both TypeScript and Python, so render.py's expected frame count matches the
@@ -36,9 +36,12 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
36
36
  "analyze": {
37
37
  "role": "analysis",
38
38
  "summary": "Measure a source with ffmpeg-skill and write timeline.json (+ captions from a file).",
39
- "writes": "timeline.json",
40
- "verification": "every number comes from ffmpeg-skill probe/scenes/silence; warnings for VFR/HDR/rotation",
41
- "ffmpeg_skill": ["probe", "scenes", "silence"],
39
+ "writes": "timeline.json (+ the joined source for several inputs, the conformed copy with --conform)",
40
+ "verification": "every number comes from ffmpeg-skill probe/scenes/silence; a VFR or HDR source is refused, "
41
+ "or with --conform conformed and re-measured (CFR at the asked rate, SDR BT.709) before use; "
42
+ "warnings for rotation and odd frame rates",
43
+ "ffmpeg_skill": ["probe", "scenes", "silence", "join (several inputs)", "sync (--pip)",
44
+ "fit (--conform: VFR -> CFR)", "color (--conform: HDR -> SDR)"],
42
45
  "dry_run": True,
43
46
  },
44
47
  "init": {
@@ -78,7 +81,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
78
81
  "summary": "analyze -> render -> deliver in one call, stopping at the first failed step.",
79
82
  "writes": "timeline.json, render, deliverable",
80
83
  "verification": "each step's own verification",
81
- "ffmpeg_skill": ["probe", "scenes", "silence", "look", "render --template", "check"],
84
+ "ffmpeg_skill": ["probe", "scenes", "silence", "fit (--conform)", "color (--conform)", "look",
85
+ "render --template", "check"],
82
86
  "dry_run": True,
83
87
  },
84
88
  "doctor": {
@@ -97,7 +101,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
97
101
  OUTPUTS: Dict[str, Dict[str, Dict[str, str]]] = {
98
102
  "analyze": {
99
103
  "result": {"commands": "list[str]", "verified": "bool", "summary": "object: duration, fps, size, scenes, "
100
- "silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words",
104
+ "silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, "
105
+ "conformed (list: vfr / hdr)",
101
106
  "warnings": "list[str]"},
102
107
  "dry_run": {"commands": "list[str]"},
103
108
  },
@@ -4,7 +4,11 @@ compositions read as props: real duration/fps/size, scene cuts, silences and the
4
4
  ranges between them, audio peaks, an optional beat grid, and captions from a file.
5
5
 
6
6
  Every number comes from a measurement (ffmpeg-skill's probe.py / scenes.py / silence.py);
7
- nothing is guessed. Warnings flag sources Remotion handles badly (variable frame rate, HDR).
7
+ nothing is guessed. A source Remotion cannot draw on faithfully -- variable frame rate (it renders
8
+ on a fixed frame grid) or HDR / BT.2020 (the browser composites in SDR) -- is refused, or with
9
+ --conform first made into a constant-frame-rate, SDR BT.709 copy by ffmpeg-skill (fit.py --fps,
10
+ color.py --to-sdr); that copy is measured and drawn on, the original is never modified, and the
11
+ timeline's `conform` records the steps.
8
12
  Several inputs are joined first with ffmpeg-skill join.py (size, fps and audio normalised to the
9
13
  first clip) and measured as one source; the clip boundaries are kept in the timeline.
10
14
 
@@ -15,12 +19,16 @@ Examples:
15
19
  python3 analyze.py talk.mp4 --threshold -42 --min-silence 0.8 # quiet room
16
20
  python3 analyze.py intro.mp4 talk.mov outro.mp4 --captions all.srt # joined, then measured
17
21
  python3 analyze.py talk.mp4 --words talk.transcript.json # captions from a transcription-skill transcript
22
+ python3 analyze.py phone_hdr.mov --conform # VFR / HDR: measure and draw on a CFR SDR copy
18
23
  """
19
24
  import argparse
20
25
  import hashlib
26
+ import shutil
21
27
  import sys
28
+ import tempfile
29
+ from fractions import Fraction
22
30
  from pathlib import Path
23
- from typing import Any, Dict, List, Optional
31
+ from typing import Any, Dict, List, Optional, Tuple
24
32
 
25
33
  sys.path.insert(0, str(Path(__file__).resolve().parent))
26
34
  from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
@@ -67,6 +75,16 @@ def build_parser() -> argparse.ArgumentParser:
67
75
  "instead of measuring it -- for a camera without usable audio")
68
76
  p.add_argument("--pip-max-offset", type=float, default=30.0,
69
77
  help="with --pip: largest offset sync.py searches, in seconds (default 30)")
78
+ p.add_argument("--conform", action="store_true",
79
+ help="a variable-frame-rate or HDR / BT.2020 source (or --pip camera) is first made into a "
80
+ "constant-frame-rate, SDR BT.709 copy with ffmpeg-skill (fit.py --fps, color.py --to-sdr: "
81
+ "tone-mapped, so the look changes) and everything is measured and drawn on that copy; the "
82
+ "original is never modified. Without it such a source is refused")
83
+ p.add_argument("--conformed", metavar="FILE",
84
+ help="with --conform: where the conformed copy of the source goes (default: <name>_conformed.mp4)")
85
+ p.add_argument("--conform-fps", type=float, metavar="FPS",
86
+ help="with --conform: the constant frame rate for a VFR source (default: the stream's base rate, "
87
+ "r_frame_rate, so no frame is dropped)")
70
88
  p.add_argument("--beats", action="store_true", help="also measure the beat grid (scenes.py --beats)")
71
89
  p.add_argument("--highlights", type=int, metavar="N",
72
90
  help="also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition")
@@ -103,14 +121,10 @@ def scene_args(a: argparse.Namespace) -> List[str]:
103
121
 
104
122
 
105
123
  def warnings_for(probe: Dict[str, Any]) -> List[str]:
124
+ """What the source can still be drawn on but deserves a look. VFR and HDR are not here: they are
125
+ conformed (--conform) or refused before anything is measured (conform_needs)."""
106
126
  w: List[str] = []
107
127
  v = probe.get("video") or {}
108
- if v.get("variable_frame_rate_suspected"):
109
- w.append("variable frame rate suspected: Remotion renders on a fixed frame grid, so cuts and captions "
110
- "can drift. Make a constant-frame-rate copy first (ffmpeg-skill export.py / fit.py --fps).")
111
- if v.get("hdr") or v.get("hdr_signal") or v.get("bt2020_or_hdr"):
112
- w.append("HDR / BT.2020 source: Remotion composites in the browser's SDR colour space, so the picture "
113
- "will look washed out. Convert first: ffmpeg-skill color.py --to-sdr.")
114
128
  if v.get("rotation"):
115
129
  w.append(f"source is rotated {v.get('rotation')} degrees by metadata; check the first still.py frame.")
116
130
  fps = v.get("fps")
@@ -119,6 +133,137 @@ def warnings_for(probe: Dict[str, Any]) -> List[str]:
119
133
  return w
120
134
 
121
135
 
136
+ # ---------------------------------------------------------------- conform (VFR -> CFR, HDR -> SDR)
137
+
138
+ def conform_needs(probe: Dict[str, Any]) -> List[str]:
139
+ """Why Remotion cannot draw on this video as it is: "vfr" (it renders on a fixed frame grid, so
140
+ cuts and captions drift), "hdr" (a PQ / HLG / Dolby Vision signal, or BT.2020 primaries: Chrome
141
+ composites in SDR BT.709, so the picture comes out washed out). Empty = draw on it as it is."""
142
+ v = probe.get("video") or {}
143
+ needs: List[str] = []
144
+ if v.get("variable_frame_rate_suspected"):
145
+ needs.append("vfr")
146
+ if v.get("hdr") or v.get("hdr_signal") or v.get("bt2020_or_hdr"):
147
+ needs.append("hdr")
148
+ return needs
149
+
150
+
151
+ def conform_rate(v: Dict[str, Any], override: Optional[float]) -> float:
152
+ """The constant rate a VFR source is conformed to: --conform-fps, else the stream's base rate
153
+ (r_frame_rate, the finest grid its frames sit on, so none is dropped; gaps repeat the previous
154
+ frame), else its average. Within 0.02 of a whole number it is that number (as ffmpeg-skill's
155
+ cfr_args rounds)."""
156
+ if override:
157
+ return float(override)
158
+ rate: Optional[float] = None
159
+ try:
160
+ r = float(Fraction(str(v.get("r_frame_rate") or "")))
161
+ rate = r if 1.0 <= r <= 120.0 else None
162
+ except (ValueError, ZeroDivisionError):
163
+ rate = None
164
+ rate = rate or float(v.get("fps") or 0) or 30.0
165
+ return float(round(rate)) if abs(rate - round(rate)) < 0.02 else round(rate, 3)
166
+
167
+
168
+ def describe_needs(needs: List[str], v: Dict[str, Any]) -> str:
169
+ parts = []
170
+ if "vfr" in needs:
171
+ parts.append(f"variable frame rate (r_frame_rate {v.get('r_frame_rate')}, average {v.get('avg_frame_rate')}): "
172
+ "Remotion renders on a fixed frame grid, so cuts and captions would drift")
173
+ if "hdr" in needs:
174
+ parts.append(f"{v.get('hdr_format') or 'HDR / BT.2020'} (transfer {v.get('color_transfer')}, primaries "
175
+ f"{v.get('color_primaries')}): Remotion composites in SDR BT.709, so the picture would look "
176
+ "washed out")
177
+ return "; ".join(parts)
178
+
179
+
180
+ def refuse_unconformed(label: str, path: Path, needs: List[str], v: Dict[str, Any]) -> None:
181
+ fixes = []
182
+ if "vfr" in needs:
183
+ fixes.append(f"a constant {conform_rate(v, None):g} fps copy (ffmpeg-skill fit.py --fps)")
184
+ if "hdr" in needs:
185
+ fixes.append("an SDR BT.709 copy (ffmpeg-skill color.py --to-sdr; tone-mapped, so the look changes)")
186
+ die(f"{label} {path.name} is {describe_needs(needs, v)}. Re-run with --conform to measure and draw on "
187
+ f"{' and '.join(fixes)} -- the original is never modified -- or give a source that is already "
188
+ "constant-frame-rate SDR", "input", conform_needed=needs)
189
+
190
+
191
+ def conform_plan(src: Path, v: Dict[str, Any], needs: List[str], out: Path, tmp: Path,
192
+ fps: Optional[float]) -> List[Tuple[str, str, List[str]]]:
193
+ """(reason, ffmpeg-skill script, args) in order. VFR first: color.py on a VFR input would conform it
194
+ to the *average* rate itself; fit.py --fps keeps HDR (x265 Main10), so color.py then tone-maps once."""
195
+ steps: List[Tuple[str, str, List[str]]] = []
196
+ cur = src
197
+ if "vfr" in needs:
198
+ dest = tmp if "hdr" in needs else out
199
+ steps.append(("vfr", "fit", [str(cur), "--fps", f"{conform_rate(v, fps):g}", "-o", str(dest)]
200
+ + (["--overwrite"] if dest == out and STATE.overwrite else [])))
201
+ cur = dest
202
+ if "hdr" in needs:
203
+ steps.append(("hdr", "color", [str(cur), "--to-sdr", "-o", str(out)] + (["--overwrite"] if STATE.overwrite else [])))
204
+ return steps
205
+
206
+
207
+ def conform_source(label: str, src: Path, probe: Dict[str, Any], out: Path, fps: Optional[float],
208
+ commands: List[str]) -> Tuple[Path, Dict[str, Any], Dict[str, Any]]:
209
+ """Make the CFR / SDR BT.709 copy with ffmpeg-skill, re-measure it and refuse it unless the measured
210
+ result is what was asked for. Returns (copy, its probe, the provenance record for the timeline)."""
211
+ v = probe.get("video") or {}
212
+ needs = conform_needs(probe)
213
+ if src.resolve() == out.resolve():
214
+ die(f"--conformed {out} is the {label} itself: the original is never overwritten", "input")
215
+ refuse_existing(out)
216
+ out.parent.mkdir(parents=True, exist_ok=True)
217
+ rate = conform_rate(v, fps) if "vfr" in needs else None
218
+ info(f"conforming {label} {src.name}: {describe_needs(needs, v)} -> {out}")
219
+ tmpdir = Path(tempfile.mkdtemp(prefix=".rfs-conform-", dir=str(out.parent)))
220
+ steps: List[Dict[str, Any]] = []
221
+ try:
222
+ for reason, script, args in conform_plan(src, v, needs, out, tmpdir / "cfr.mp4", fps):
223
+ res = ffskill(script, args)
224
+ commands.append(res["_command"])
225
+ steps.append({"reason": reason, "tool": f"ffmpeg-skill {script}.py",
226
+ "args": [a for a in args if a != "--overwrite"], "command": res["_command"],
227
+ "notes": res.get("notes") or []})
228
+ finally:
229
+ shutil.rmtree(tmpdir, ignore_errors=True)
230
+ after = ffskill("probe", [str(out)])
231
+ commands.append(after["_command"])
232
+ av = after.get("video") or {}
233
+ problems = []
234
+ if av.get("variable_frame_rate_suspected"):
235
+ problems.append(f"still variable frame rate ({av.get('r_frame_rate')} vs {av.get('avg_frame_rate')})")
236
+ if rate is not None and abs(float(av.get("fps") or 0) - rate) > 0.01:
237
+ problems.append(f"{av.get('fps')} fps, not the {rate:g} asked for")
238
+ if "hdr" in needs and (conform_needs(after) or av.get("color_transfer") != "bt709"
239
+ or av.get("color_primaries") != "bt709"):
240
+ problems.append(f"not SDR BT.709 (transfer {av.get('color_transfer')}, primaries {av.get('color_primaries')})")
241
+ before_d = float(probe.get("duration") or v.get("duration") or 0)
242
+ after_d = float(after.get("duration") or av.get("duration") or 0)
243
+ if abs(after_d - before_d) > TRANSCRIPT_DURATION_TOLERANCE:
244
+ problems.append(f"{after_d:.3f} s long, the {label} is {before_d:.3f} s")
245
+ if problems:
246
+ die(f"the conformed copy {out} of {src.name} does not measure as asked: {'; '.join(problems)}", "failed",
247
+ commands=commands)
248
+ record = {
249
+ "reasons": needs,
250
+ "original": {"path": str(src.resolve()), "name": src.name, "fingerprint": file_fingerprint(src),
251
+ "duration": round(before_d, 3), "fps": v.get("fps"), "r_frame_rate": v.get("r_frame_rate"),
252
+ "avg_frame_rate": v.get("avg_frame_rate"),
253
+ "variable_frame_rate_suspected": bool(v.get("variable_frame_rate_suspected")),
254
+ "hdr_format": v.get("hdr_format"), "color_transfer": v.get("color_transfer"),
255
+ "color_primaries": v.get("color_primaries"), "color_space": v.get("color_space")},
256
+ "output": str(out.resolve()),
257
+ "steps": steps,
258
+ "measured": {"duration": round(after_d, 3), "fps": av.get("fps"), "r_frame_rate": av.get("r_frame_rate"),
259
+ "avg_frame_rate": av.get("avg_frame_rate"),
260
+ "variable_frame_rate_suspected": bool(av.get("variable_frame_rate_suspected")),
261
+ "color_transfer": av.get("color_transfer"), "color_primaries": av.get("color_primaries"),
262
+ "color_space": av.get("color_space"), "pix_fmt": av.get("pix_fmt")},
263
+ }
264
+ return out, after, record
265
+
266
+
122
267
  def main() -> None:
123
268
  a = build_parser().parse_args()
124
269
  apply_common(a)
@@ -130,6 +275,12 @@ def main() -> None:
130
275
  joined: Path = Path(a.joined).expanduser() if a.joined else default_output(src, "_joined", ".mp4")
131
276
  out = Path(a.output) if a.output else default_output(joined if len(inputs) > 1 else src, ".timeline", ".json")
132
277
  refuse_existing(out)
278
+ if (a.conformed or a.conform_fps is not None) and not a.conform:
279
+ die("--conformed / --conform-fps need --conform", "input")
280
+ if a.conform_fps is not None and not 0 < a.conform_fps <= 240:
281
+ die(f"--conform-fps must be between 0 and 240, got {a.conform_fps:g}", "input")
282
+ conformed: Path = (Path(a.conformed).expanduser() if a.conformed
283
+ else default_output(joined if len(inputs) > 1 else src, "_conformed", ".mp4"))
133
284
  skill = require_ffmpeg_skill()
134
285
 
135
286
  captions: List[Dict[str, Any]] = []
@@ -164,11 +315,27 @@ def main() -> None:
164
315
  [shell_join(ffskill_cmd("probe", [str(joined if len(inputs) > 1 else src)]))]
165
316
  if STATE.dry_run:
166
317
  target = str(joined if len(inputs) > 1 else src)
318
+ note = None
319
+ if len(inputs) == 1:
320
+ # Reading the source writes nothing: plan the conform steps (or refuse) exactly as a run would.
321
+ pr = ffskill("probe", [str(src)])
322
+ needs = conform_needs(pr)
323
+ if needs and not a.conform:
324
+ refuse_unconformed("source", src, needs, pr.get("video") or {})
325
+ if needs:
326
+ plan += [shell_join(ffskill_cmd(script, args)) for _, script, args in
327
+ conform_plan(src, pr.get("video") or {}, needs, conformed,
328
+ conformed.parent / ".rfs-conform-XXXX" / "cfr.mp4", a.conform_fps)]
329
+ plan.append(shell_join(ffskill_cmd("probe", [str(conformed)])))
330
+ target = str(conformed)
331
+ else:
332
+ note = "a variable-frame-rate or HDR joined file is conformed (--conform) or refused once it is measured"
167
333
  if not a.no_scenes:
168
334
  plan.append(shell_join(ffskill_cmd("scenes", [target, *scene_args(a)])))
169
335
  if not a.no_silence:
170
336
  plan.append(shell_join(ffskill_cmd("silence", [target, *silence_args(a)])))
171
- emit({"output": str(out), "commands": plan}, f"would write {out} after {len(plan)} ffmpeg-skill steps")
337
+ emit({"output": str(out), "commands": plan, **({"note": note} if note else {})},
338
+ f"would write {out} after {len(plan)} ffmpeg-skill steps")
172
339
  return
173
340
 
174
341
  clips: List[Dict[str, Any]] = []
@@ -193,11 +360,19 @@ def main() -> None:
193
360
  src = joined
194
361
 
195
362
  probe = ffskill("probe", [str(src)])
363
+ commands = pre_commands + [probe["_command"]]
364
+ measured_from = src
365
+ conform: Optional[Dict[str, Any]] = None
366
+ needs = conform_needs(probe)
367
+ if needs and not a.conform:
368
+ refuse_unconformed("joined source" if clips else "source", src, needs, probe.get("video") or {})
369
+ if needs:
370
+ src, probe, conform = conform_source("joined source" if clips else "source", src, probe, conformed,
371
+ a.conform_fps, commands)
196
372
  video, audio = probe.get("video"), probe.get("audio")
197
373
  duration = float(probe.get("duration") or (video or {}).get("duration") or (audio or {}).get("duration") or 0)
198
374
  if duration <= 0:
199
375
  die(f"{src} has no measurable duration", "input")
200
- commands = pre_commands + [probe["_command"]]
201
376
  if clips:
202
377
  # The last boundary is the measured joined duration (encoders can round the tail by a frame).
203
378
  clips[-1]["end"] = round(duration, 3)
@@ -209,7 +384,8 @@ def main() -> None:
209
384
  if abs(transcript["duration"] - duration) > TRANSCRIPT_DURATION_TOLERANCE:
210
385
  die(f"--words: the transcript is of a {transcript['duration']:.3f} s file ({transcript['filename']}), "
211
386
  f"the source measures {duration:.3f} s; transcribe this source (or the joined file)", "input")
212
- if transcript["fingerprint"] != file_fingerprint(src):
387
+ # A conformed copy keeps the original's times: the transcript of the original still fits it.
388
+ if transcript["fingerprint"] not in {file_fingerprint(src), (conform or {}).get("original", {}).get("fingerprint")}:
213
389
  transcript_warnings.append(
214
390
  f"--words: the transcript was made from {transcript['filename']}, not these exact bytes "
215
391
  f"(same length, so its times are used as written)")
@@ -275,10 +451,19 @@ def main() -> None:
275
451
  cv = cp.get("video") or {}
276
452
  if not cv:
277
453
  die(f"--pip {cam} has no video stream", "input")
454
+ cam_needs = conform_needs(cp)
455
+ cam_conform: Optional[Dict[str, Any]] = None
456
+ if cam_needs and not a.conform:
457
+ refuse_unconformed("--pip camera", cam, cam_needs, cv)
458
+ if cam_needs:
459
+ cam, cp, cam_conform = conform_source("--pip camera", cam, cp, default_output(cam, "_conformed", ".mp4"),
460
+ a.conform_fps, commands)
461
+ cv = cp.get("video") or {}
278
462
  pip = {"path": str(cam.resolve()), "name": cam.name,
279
463
  "duration": round(float(cv.get("duration") or cp.get("duration") or 0), 3),
280
464
  "width": int(cv.get("width") or 0), "height": int(cv.get("height") or 0),
281
- "fps": float(cv.get("fps") or 0), "offset": 0.0, "confidence": None, "measured": False}
465
+ "fps": float(cv.get("fps") or 0), "offset": 0.0, "confidence": None, "measured": False,
466
+ "conform": cam_conform}
282
467
  if a.pip_offset is not None:
283
468
  pip["offset"] = round(float(a.pip_offset), 4)
284
469
  elif not (audio and cp.get("audio")):
@@ -318,6 +503,8 @@ def main() -> None:
318
503
  "words": words,
319
504
  "chapters": chapters,
320
505
  "pip": pip,
506
+ # Provenance of a conformed source (--conform): the original, each ffmpeg-skill step, the measured copy.
507
+ "conform": conform,
321
508
  "warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings,
322
509
  }
323
510
  if pip and pip["measured"] and (pip["confidence"] or 0) < 0.3:
@@ -328,6 +515,9 @@ def main() -> None:
328
515
  "render with --aspect / --width to choose the frame.")
329
516
  for w in timeline["warnings"]:
330
517
  info(f"warning: {w}")
518
+ for st in (conform or {}).get("steps", []):
519
+ for n in st["notes"]:
520
+ info(f"conform: {n}")
331
521
 
332
522
  out.parent.mkdir(parents=True, exist_ok=True)
333
523
  import json
@@ -341,10 +531,13 @@ def main() -> None:
341
531
  "captions": len(captions), "chapters": len(chapters),
342
532
  "pip_offset": pip["offset"] if pip else None, "beats": bool(beats and beats.get("usable")),
343
533
  "tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
344
- "clips": len(clips) or 1, "words": len(words)},
534
+ "clips": len(clips) or 1, "words": len(words),
535
+ "conformed": (conform or {}).get("reasons", [])},
345
536
  "warnings": timeline["warnings"]},
346
537
  f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
347
- f"(speech {speech_total:.2f}s), {len(peaks)} peaks, {len(captions)} captions")
538
+ f"(speech {speech_total:.2f}s), {len(peaks)} peaks, {len(captions)} captions"
539
+ + (f"; measured and drawn on {src.name}, conformed ({' + '.join(conform['reasons'])}) from "
540
+ f"{measured_from.name}" if conform else ""))
348
541
 
349
542
 
350
543
  if __name__ == "__main__":
@@ -36,6 +36,10 @@ def build_parser() -> argparse.ArgumentParser:
36
36
  p.add_argument("--platform", choices=PLATFORMS, help="deliver with this ffmpeg-skill template and check it")
37
37
  p.add_argument("--out-dir", help="where the timeline, render and deliverable go (default: next to the input)")
38
38
  p.add_argument("--beats", action="store_true", help="measure the beat grid too")
39
+ p.add_argument("--conform", action="store_true",
40
+ help="a variable-frame-rate or HDR source is made into a constant-frame-rate, SDR BT.709 copy "
41
+ "with ffmpeg-skill first (analyze.py --conform; the copy goes in --out-dir) and drawn on; "
42
+ "without it such a source is refused")
39
43
  p.add_argument("--fast", action="store_true", help="preview-quality render")
40
44
  p.add_argument("--aspect", choices=["source", *ASPECTS],
41
45
  help="output shape (default: the shape the --platform template delivers, else the source's)")
@@ -85,6 +89,7 @@ def main() -> None:
85
89
  an_args = [*map(str, inputs), "-o", str(tl)] + (["--joined", str(out_dir / f"{stem}.mp4")] if len(inputs) > 1 else [])
86
90
  an_args += (["--captions", a.captions] if a.captions else []) + (["--beats"] if a.beats else [])
87
91
  an_args += ["--chapters", a.chapters] if a.chapters else []
92
+ an_args += ["--conform", "--conformed", str(out_dir / f"{stem}_conformed.mp4")] if a.conform else []
88
93
  analysis = step("measure", "analyze", an_args, steps)
89
94
  if STATE.dry_run and not tl.exists():
90
95
  emit({"output": None, "steps": steps,
@@ -32,6 +32,17 @@ export type Pip = {
32
32
  offset: number;
33
33
  confidence: number | null;
34
34
  measured: boolean;
35
+ /** The camera's own conform record when analyze.py --conform conformed it. */
36
+ conform?: Conform | null;
37
+ };
38
+ /** Provenance of a source analyze.py --conform made drawable (VFR -> CFR, HDR -> SDR BT.709 with
39
+ * ffmpeg-skill). The compositions never read it: the source above is already the conformed copy. */
40
+ export type Conform = {
41
+ reasons: ("vfr" | "hdr")[];
42
+ original: { path: string; name: string; fingerprint: string } & Record<string, unknown>;
43
+ output: string;
44
+ steps: { reason: "vfr" | "hdr"; tool: string; args: string[]; command: string; notes: string[] }[];
45
+ measured: Record<string, unknown>;
35
46
  };
36
47
  export type Beats = { times: number[]; tempo_bpm: number | null; confidence: number | null; usable: boolean };
37
48
  export type Highlight = { start: number; end: number };
@@ -57,6 +68,8 @@ export type Timeline = {
57
68
  /** Chapters from the user's list or the source's own markers (analyze.py --chapters); titles as written. */
58
69
  chapters?: Chapter[];
59
70
  pip?: Pip | null;
71
+ /** Set when analyze.py --conform measured a conformed copy instead of the original (null otherwise). */
72
+ conform?: Conform | null;
60
73
  warnings?: string[];
61
74
  };
62
75