remotion-ffmpeg-skill 0.10.2 → 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 +2 -1
- package/SKILL.md +3 -1
- package/package.json +1 -1
- package/references/gotchas.md +2 -2
- package/references/scripts.md +10 -6
- package/references/timeline.md +6 -2
- package/scripts/_captions.py +210 -6
- package/scripts/_common.py +2 -1
- package/scripts/_contract.py +10 -5
- package/scripts/analyze.py +245 -19
- package/scripts/pipeline.py +5 -0
- package/templates/remotion-project/src/timeline.ts +13 -0
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
|
-
|
|
|
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` |
|
|
@@ -58,6 +58,7 @@ npx remotion-ffmpeg-skill # this skill, next to it in ~/.claude/skills
|
|
|
58
58
|
- "Cut the silences out of this recording, jump-cut style, and keep the subtitles in sync."
|
|
59
59
|
- "Make graphics that hit on the loud moments of `clip.mp4`, as a Reel."
|
|
60
60
|
- "Here are my chapters (`0:00 Intro` …): put them on screen and make it a YouTube upload." — a card at each chapter start, chapter markers in the file, and the description block to paste.
|
|
61
|
+
- "Caption `talk.mp4` from the transcript transcription-skill made, words lighting up as they're spoken." — `analyze.py --words talk.transcript.json`; the transcript's schema version is checked and its times are used exactly as written.
|
|
61
62
|
- "Japanese captions, vertical, for TikTok." — renders 9:16 with a blurred fill, stages a CJK font automatically, breaks lines between phrases.
|
|
62
63
|
|
|
63
64
|
## Under the hood
|
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
|
|
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.
|
|
@@ -48,6 +48,7 @@ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts
|
|
|
48
48
|
| "cut the silences / jump cut / tighten this talk" (with motion) | `analyze.py` → `render.py --comp Jumpcut` (captions re-timed if given) |
|
|
49
49
|
| "graphics that react to the audio / hit on the beat / on cuts" | `analyze.py [--beats]` → `render.py --comp PeakPulse` (pulses on beats when the grid was measured) |
|
|
50
50
|
| "karaoke captions / words light up as they're spoken" | `analyze.py --words WORDS.json [--captions F.srt]` → `render.py --comp Karaoke` (word timings from a local speech engine, whisper JSON; without an SRT the cues are grouped from the words) |
|
|
51
|
+
| "captions from the transcript" (transcription-skill output) | `analyze.py --words talk.transcript.json` → `render.py --comp Captioned` or `Karaoke`. Only schema `transcription-skill/transcript/0.1` is read, checked against its contract; another version, a broken document or one whose duration differs from the source by more than 0.5 s is refused (`kind: input`) — ask for a fresh transcript, never patch its times. Segments without word timings become one plain cue each (named in the warnings) |
|
|
51
52
|
| "lower thirds / name titles / scene titles" | `render.py --comp Titled --options` with `lowerThirds` / `sceneTitles` — the text comes from the user; ask for it, never invent names |
|
|
52
53
|
| "chapters" / a YouTube chapter list (`0:00 Intro` per line) | `analyze.py --chapters chapters.txt` (or `--chapters source` for markers the file already has) → `render.py --comp Titled` (a card at each chapter start, `chapterSeconds`) → `deliver.py --platform youtube --chapters chapters.txt` (markers in the file + `<name>_description.txt` to paste). Titles as written; a line without one is refused. Not with Jumpcut / Highlights: their cuts move every chapter |
|
|
53
54
|
| "highlight reel / best moments" | `analyze.py --highlights N [--target S]` → `render.py --comp Highlights` (audio-energy ranking: candidates, say so) |
|
|
@@ -60,6 +61,7 @@ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts
|
|
|
60
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 |
|
|
61
62
|
| "change colour / font / caption size / zoom" | an `--options` JSON (`references/timeline.md`), re-render |
|
|
62
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 |
|
|
63
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 |
|
|
64
66
|
| "preview" / "show me a frame" | `still.py` |
|
|
65
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.
|
|
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",
|
package/references/gotchas.md
CHANGED
|
@@ -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
|
|
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
|
|
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.
|
package/references/scripts.md
CHANGED
|
@@ -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
|
|
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 |
|
|
@@ -24,11 +24,14 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
|
|
|
24
24
|
| `--join-duration` | number | `0.5` | transition length in seconds (default 0.5) |
|
|
25
25
|
| `--output` | string | | timeline file (default: <name>.timeline.json) |
|
|
26
26
|
| `--captions` | string | | SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written) |
|
|
27
|
-
| `--words` | string | | word timings
|
|
27
|
+
| `--words` | string | | word timings for the Karaoke and Captioned compositions: a transcription-skill transcript (schema transcription-skill/transcript/0.1, validated strictly) or whisper JSON with word timestamps; without --captions the cues are grouped from these words |
|
|
28
28
|
| `--chapters` | string | | chapter list, one `TIME TITLE` per line (YouTube's format, the same file ffmpeg-skill metadata.py --chapters writes into the container), or `source` for the chapters already in the input file; titles are kept as written |
|
|
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 |
|
package/references/timeline.md
CHANGED
|
@@ -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
|
-
| `
|
|
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
|
|
@@ -95,6 +96,9 @@ Example:
|
|
|
95
96
|
- **SRT** and **WebVTT**: timing lines `00:00:01,000 --> 00:00:03,500` (comma or dot), multi-line cue text kept; simple formatting tags (`<i>`, `<b>`, `<c>`, `<v ...>`) are stripped.
|
|
96
97
|
- **JSON**: `[{"start": 1.0, "end": 3.5, "text": "..."}]` or `{"cues": [...]}`.
|
|
97
98
|
- **Word timings** (`--words`): whisper / faster-whisper JSON made with word timestamps (`segments[].words[]` with `word`, `start`, `end`), `{"words": [...]}` or a plain list. With no `--captions`, cues are grouped mechanically: a new cue after a pause over 0.7 s, past 32 characters or 4 s. Words are never added, dropped or reworded.
|
|
99
|
+
- **transcription-skill transcript** (`--words`): a JSON document with a `schema` key is read as a [transcription-skill](https://github.com/kajisho5/transcription-skill) Transcript and must be `transcription-skill/transcript/0.1`; any other schema id or version is refused. The document is checked against that contract (required fields, finite numbers, `0 ≤ start < end`, segments ordered and not overlapping, words ordered and inside their segment within 0.01 s, ends within the duration + 0.5 s, confidences in [0, 1], `duration` = `source.media_duration`) and refused on the first violation; a transcript whose `duration` differs from the measured source by more than 0.5 s is refused too (it is of another file). Times are used exactly as written — not rounded, snapped or interpolated.
|
|
100
|
+
- Words are trimmed in a transcript, so each word's leading space is read back from the segment's verbatim `raw_text` (one space where `raw_text` has whitespace before the word; none between Japanese tokens). Words that do not spell `raw_text` in order are not trusted: that segment becomes one plain cue, with a warning.
|
|
101
|
+
- Without `--captions`, cues are grouped from the words with the rule above **inside each segment** — a cue never spans two segments. A segment whose `words` is `null` becomes one cue with the segment's own `start`, `end` and `text`; it gets no `words`, so Karaoke shows it plain. The transcript's own `warnings` are carried into the timeline's `warnings` (prefixed `transcript:`), and so is a note when `source.fingerprint` is not the source's sha256.
|
|
98
102
|
|
|
99
103
|
## Adding your own composition
|
|
100
104
|
|
package/scripts/_captions.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""Caption file readers (internal module): SRT, WebVTT
|
|
2
|
+
"""Caption file readers (internal module): SRT, WebVTT, a plain JSON cue list, whisper word timings and
|
|
3
|
+
transcription-skill transcripts.
|
|
3
4
|
|
|
4
5
|
Cue text is kept exactly as written (line breaks included): this skill never rewrites,
|
|
5
6
|
shortens or paraphrases caption words -- the same rule as ffmpeg-skill.
|
|
6
7
|
"""
|
|
7
8
|
import json
|
|
8
9
|
import re
|
|
10
|
+
import unicodedata
|
|
9
11
|
from pathlib import Path
|
|
10
|
-
from typing import Any, Dict, List
|
|
12
|
+
from typing import Any, Dict, List, Optional
|
|
11
13
|
|
|
12
14
|
_TS = re.compile(r"(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})")
|
|
13
15
|
_ARROW = re.compile(r"^\s*(\S+)\s+-->\s+(\S+)")
|
|
@@ -114,10 +116,6 @@ def parse_words(text: str) -> List[Dict]:
|
|
|
114
116
|
return sorted(words, key=lambda w: w["start"])
|
|
115
117
|
|
|
116
118
|
|
|
117
|
-
def read_words(path: Path) -> List[Dict]:
|
|
118
|
-
return parse_words(path.read_text(encoding="utf-8-sig"))
|
|
119
|
-
|
|
120
|
-
|
|
121
119
|
def cues_from_words(words: List[Dict], max_chars: int = 32, max_gap: float = 0.7, max_len: float = 4.0) -> List[Dict]:
|
|
122
120
|
"""Group timed words into caption cues mechanically: a new cue after a pause longer than max_gap,
|
|
123
121
|
when the cue would pass max_chars characters, or last longer than max_len seconds. The words and
|
|
@@ -141,6 +139,212 @@ def _cue(ws: List[Dict]) -> Dict:
|
|
|
141
139
|
return {"start": ws[0]["start"], "end": ws[-1]["end"], "text": "".join(w["text"] for w in ws).strip()}
|
|
142
140
|
|
|
143
141
|
|
|
142
|
+
# ---------------------------------------------------------------- transcription-skill transcripts
|
|
143
|
+
|
|
144
|
+
TRANSCRIPT_SCHEMA = "transcription-skill/transcript/0.1"
|
|
145
|
+
_TRANSCRIPT_END_TOLERANCE = 0.5 # transcription-skill validate.py END_TOLERANCE
|
|
146
|
+
_TRANSCRIPT_CONTAINMENT = 0.01 # transcription-skill validate.py CONTAINMENT_TOLERANCE
|
|
147
|
+
_TRANSCRIPT_REQUIRED = ("schema", "id", "asset_id", "language", "language_source", "language_confidence", "duration",
|
|
148
|
+
"segments", "source", "engine", "engine_version", "created_at", "provenance", "warnings")
|
|
149
|
+
_SEGMENT_REQUIRED = ("id", "start", "end", "text", "raw_text", "confidence", "words", "speaker_id")
|
|
150
|
+
_WORD_REQUIRED = ("start", "end", "text", "confidence")
|
|
151
|
+
_SOURCE_REQUIRED = ("filename", "fingerprint", "size_bytes", "media_duration")
|
|
152
|
+
_PROVENANCE_REQUIRED = ("engine", "engine_version", "execution_mode", "model", "model_version", "parameters",
|
|
153
|
+
"parameters_hash", "cache_key", "created_at", "processing_seconds", "skill_version", "skill", "tool")
|
|
154
|
+
_FINGERPRINT = re.compile(r"sha256:[0-9a-f]{64}")
|
|
155
|
+
_SPACE = re.compile(r"[\s ]+")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def is_transcript(data: Any) -> bool:
|
|
159
|
+
"""A document that names a schema is read as a transcript (and refused if it is not one we know)."""
|
|
160
|
+
return isinstance(data, dict) and "schema" in data
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _num(v: Any) -> bool:
|
|
164
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool) and v == v and v not in (float("inf"), float("-inf"))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _conf_ok(v: Any) -> bool:
|
|
168
|
+
return v is None or (_num(v) and 0.0 <= v <= 1.0)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def validate_transcript(doc: Any) -> List[str]:
|
|
172
|
+
"""Errors against transcription-skill's Transcript contract (schemas/transcript.schema.json and the
|
|
173
|
+
timing rules of its validate.py). Empty list = valid. An unknown schema version is an error: its
|
|
174
|
+
fields could mean something else."""
|
|
175
|
+
if not isinstance(doc, dict):
|
|
176
|
+
return ["a transcript must be a JSON object"]
|
|
177
|
+
if doc.get("schema") != TRANSCRIPT_SCHEMA:
|
|
178
|
+
return [f"unsupported transcript schema {doc.get('schema')!r}: this version reads {TRANSCRIPT_SCHEMA} only"]
|
|
179
|
+
errs = [f"missing required field: {k}" for k in _TRANSCRIPT_REQUIRED if k not in doc]
|
|
180
|
+
if errs:
|
|
181
|
+
return errs
|
|
182
|
+
for k in ("id", "asset_id", "engine", "engine_version", "created_at"):
|
|
183
|
+
if not isinstance(doc[k], str) or not doc[k]:
|
|
184
|
+
errs.append(f"{k} must be a non-empty string")
|
|
185
|
+
if not isinstance(doc["language"], str) or not re.fullmatch(r"[a-z]{2,3}|unknown", doc["language"]):
|
|
186
|
+
errs.append(f"language must be an ISO 639 code or 'unknown', got {doc['language']!r}")
|
|
187
|
+
if doc["language_source"] not in ("requested", "detected", "unknown"):
|
|
188
|
+
errs.append(f"language_source must be requested, detected or unknown, got {doc['language_source']!r}")
|
|
189
|
+
if not _conf_ok(doc["language_confidence"]):
|
|
190
|
+
errs.append("language_confidence must be null or a number in [0, 1]")
|
|
191
|
+
if not isinstance(doc["warnings"], list) or not all(isinstance(w, str) for w in doc["warnings"]):
|
|
192
|
+
errs.append("warnings must be a list of strings")
|
|
193
|
+
dur = doc["duration"]
|
|
194
|
+
if not _num(dur) or dur <= 0:
|
|
195
|
+
errs.append(f"duration must be a positive number, got {dur!r}")
|
|
196
|
+
dur = None
|
|
197
|
+
src = doc["source"]
|
|
198
|
+
if not isinstance(src, dict):
|
|
199
|
+
errs.append("source must be an object")
|
|
200
|
+
else:
|
|
201
|
+
errs += [f"source.{k} is required" for k in _SOURCE_REQUIRED if k not in src]
|
|
202
|
+
if not isinstance(src.get("fingerprint"), str) or not _FINGERPRINT.fullmatch(src["fingerprint"]):
|
|
203
|
+
errs.append("source.fingerprint must be 'sha256:<64 hex>'")
|
|
204
|
+
if not isinstance(src.get("filename"), str) or not src["filename"]:
|
|
205
|
+
errs.append("source.filename must be a non-empty string")
|
|
206
|
+
md = src.get("media_duration")
|
|
207
|
+
if "media_duration" in src and (not _num(md) or md <= 0):
|
|
208
|
+
errs.append("source.media_duration must be a positive number")
|
|
209
|
+
elif dur is not None and _num(md) and abs(md - dur) > 1e-6:
|
|
210
|
+
errs.append("duration must equal source.media_duration")
|
|
211
|
+
prov = doc["provenance"]
|
|
212
|
+
if not isinstance(prov, dict):
|
|
213
|
+
errs.append("provenance must be an object")
|
|
214
|
+
else:
|
|
215
|
+
errs += [f"provenance.{k} is required" for k in _PROVENANCE_REQUIRED if k not in prov]
|
|
216
|
+
if prov.get("skill", "transcription-skill") != "transcription-skill":
|
|
217
|
+
errs.append(f"provenance.skill must be transcription-skill, got {prov.get('skill')!r}")
|
|
218
|
+
if not str(prov.get("tool", "transcription/")).startswith("transcription/"):
|
|
219
|
+
errs.append("provenance.tool must be a transcription/* tool name")
|
|
220
|
+
segs = doc["segments"]
|
|
221
|
+
if not isinstance(segs, list):
|
|
222
|
+
return errs + ["segments must be a list"]
|
|
223
|
+
ids = set()
|
|
224
|
+
prev: Optional[Dict[str, Any]] = None
|
|
225
|
+
for i, seg in enumerate(segs):
|
|
226
|
+
where = f"segments[{i}]"
|
|
227
|
+
if not isinstance(seg, dict):
|
|
228
|
+
errs.append(f"{where}: must be an object")
|
|
229
|
+
continue
|
|
230
|
+
missing = [k for k in _SEGMENT_REQUIRED if k not in seg]
|
|
231
|
+
if missing:
|
|
232
|
+
errs.append(f"{where}: missing {missing}")
|
|
233
|
+
continue
|
|
234
|
+
if not isinstance(seg["id"], str) or not seg["id"] or seg["id"] in ids:
|
|
235
|
+
errs.append(f"{where}: id must be a unique non-empty string")
|
|
236
|
+
ids.add(seg["id"])
|
|
237
|
+
s, e = seg["start"], seg["end"]
|
|
238
|
+
if not _num(s) or not _num(e):
|
|
239
|
+
errs.append(f"{where}: start/end must be numbers")
|
|
240
|
+
continue
|
|
241
|
+
if s < 0 or e <= s:
|
|
242
|
+
errs.append(f"{where}: needs 0 <= start < end, got [{s}, {e}]")
|
|
243
|
+
if dur is not None and e > dur + _TRANSCRIPT_END_TOLERANCE:
|
|
244
|
+
errs.append(f"{where}: end {e} is past the media duration {dur}")
|
|
245
|
+
if prev is not None and (s < prev["start"] or s < prev["end"] - _TRANSCRIPT_CONTAINMENT):
|
|
246
|
+
errs.append(f"{where}: starts before the previous segment ends (not ordered / overlapping)")
|
|
247
|
+
prev = seg
|
|
248
|
+
if not isinstance(seg["text"], str) or not isinstance(seg["raw_text"], str):
|
|
249
|
+
errs.append(f"{where}: text and raw_text must be strings")
|
|
250
|
+
if not _conf_ok(seg["confidence"]):
|
|
251
|
+
errs.append(f"{where}: confidence must be null or a number in [0, 1]")
|
|
252
|
+
words = seg["words"]
|
|
253
|
+
if words is None:
|
|
254
|
+
continue
|
|
255
|
+
if not isinstance(words, list):
|
|
256
|
+
errs.append(f"{where}: words must be null or a list")
|
|
257
|
+
continue
|
|
258
|
+
wprev = None
|
|
259
|
+
for j, w in enumerate(words):
|
|
260
|
+
ww = f"{where}.words[{j}]"
|
|
261
|
+
if not isinstance(w, dict) or any(k not in w for k in _WORD_REQUIRED):
|
|
262
|
+
errs.append(f"{ww}: must have {list(_WORD_REQUIRED)}")
|
|
263
|
+
continue
|
|
264
|
+
ws, we = w["start"], w["end"]
|
|
265
|
+
if not _num(ws) or not _num(we):
|
|
266
|
+
errs.append(f"{ww}: start/end must be numbers")
|
|
267
|
+
continue
|
|
268
|
+
if ws < 0 or we <= ws:
|
|
269
|
+
errs.append(f"{ww}: needs 0 <= start < end, got [{ws}, {we}]")
|
|
270
|
+
if ws < s - _TRANSCRIPT_CONTAINMENT or we > e + _TRANSCRIPT_CONTAINMENT:
|
|
271
|
+
errs.append(f"{ww}: [{ws}, {we}] is outside its segment [{s}, {e}]")
|
|
272
|
+
if wprev is not None and ws < wprev - _TRANSCRIPT_CONTAINMENT:
|
|
273
|
+
errs.append(f"{ww}: words not in time order")
|
|
274
|
+
wprev = we
|
|
275
|
+
if not isinstance(w["text"], str) or not w["text"].strip():
|
|
276
|
+
errs.append(f"{ww}: text must be a non-empty string")
|
|
277
|
+
if not _conf_ok(w["confidence"]):
|
|
278
|
+
errs.append(f"{ww}: confidence must be null or a number in [0, 1]")
|
|
279
|
+
return errs
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _spaced_words(seg: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]:
|
|
283
|
+
"""The segment's words with the engine's own spacing put back in front of each (`" world"`, `"字幕"`).
|
|
284
|
+
|
|
285
|
+
transcription-skill trims each word, so the spacing is read from the segment's verbatim `raw_text`:
|
|
286
|
+
a word gets one leading space when whitespace precedes it there (whitespace runs collapse to one, as
|
|
287
|
+
in the transcript's own `text`). None when the words do not spell `raw_text` in order -- then the
|
|
288
|
+
segment's word timings cannot be trusted to belong to its text."""
|
|
289
|
+
raw = "".join(ch for ch in seg["raw_text"] if unicodedata.category(ch) not in ("Cc", "Cf") or ch in "\t\n\r")
|
|
290
|
+
pos, out = 0, []
|
|
291
|
+
for w in seg["words"]:
|
|
292
|
+
m = _SPACE.match(raw, pos)
|
|
293
|
+
lead = " " if m else ""
|
|
294
|
+
pos = m.end() if m else pos
|
|
295
|
+
token = _SPACE.sub(" ", w["text"]).strip()
|
|
296
|
+
if not raw.startswith(token, pos):
|
|
297
|
+
return None
|
|
298
|
+
pos += len(token)
|
|
299
|
+
out.append({"start": w["start"], "end": w["end"], "text": lead + token})
|
|
300
|
+
return out if not raw[pos:].strip() else None
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def parse_transcript(doc: Any) -> Dict[str, Any]:
|
|
304
|
+
"""A validated transcription-skill Transcript -> {words, cues, warnings, duration, fingerprint, filename}.
|
|
305
|
+
|
|
306
|
+
Every time comes from the transcript as written (not rounded, shifted or stretched). Cues are grouped
|
|
307
|
+
from the words inside each segment (cues_from_words) and never cross a segment boundary; a segment
|
|
308
|
+
without usable word timings becomes one cue with the segment's own times and text, and its words
|
|
309
|
+
are left out of `words` (Karaoke shows that cue plain) -- no word time is ever interpolated."""
|
|
310
|
+
errs = validate_transcript(doc)
|
|
311
|
+
if errs:
|
|
312
|
+
more = f" (+{len(errs) - 5} more)" if len(errs) > 5 else ""
|
|
313
|
+
raise CaptionError("not a valid transcription-skill transcript: " + "; ".join(errs[:5]) + more)
|
|
314
|
+
words: List[Dict[str, Any]] = []
|
|
315
|
+
cues: List[Dict[str, Any]] = []
|
|
316
|
+
warnings = [f"transcript: {w}" for w in doc["warnings"]]
|
|
317
|
+
plain: List[str] = []
|
|
318
|
+
for seg in doc["segments"]:
|
|
319
|
+
sw = _spaced_words(seg) if seg["words"] else None
|
|
320
|
+
if sw:
|
|
321
|
+
words += sw
|
|
322
|
+
cues += cues_from_words(sw)
|
|
323
|
+
elif seg["text"].strip():
|
|
324
|
+
if seg["words"]:
|
|
325
|
+
warnings.append(f"transcript {seg['id']}: its words do not spell its text; shown as one plain cue")
|
|
326
|
+
else:
|
|
327
|
+
plain.append(seg["id"])
|
|
328
|
+
cues.append({"start": seg["start"], "end": seg["end"], "text": seg["text"].strip()})
|
|
329
|
+
if plain:
|
|
330
|
+
warnings.append("transcript has no word timings for " + ", ".join(plain)
|
|
331
|
+
+ " (shown as plain cues; transcribe with word timestamps for Karaoke)")
|
|
332
|
+
if not cues:
|
|
333
|
+
raise CaptionError("the transcript has no speech segments")
|
|
334
|
+
return {"words": words, "cues": cues, "warnings": warnings, "duration": float(doc["duration"]),
|
|
335
|
+
"fingerprint": doc["source"]["fingerprint"], "filename": doc["source"]["filename"]}
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def read_word_timings(path: Path) -> Dict[str, Any]:
|
|
339
|
+
"""`--words`: a transcription-skill transcript (validated strictly) or whisper-style word JSON.
|
|
340
|
+
Returns {words, cues (None for whisper JSON: grouped later only without --captions), warnings, ...}."""
|
|
341
|
+
text = path.read_text(encoding="utf-8-sig")
|
|
342
|
+
data = json.loads(text)
|
|
343
|
+
if is_transcript(data):
|
|
344
|
+
return parse_transcript(data)
|
|
345
|
+
return {"words": parse_words(text), "cues": None, "warnings": []}
|
|
346
|
+
|
|
347
|
+
|
|
144
348
|
# ---------------------------------------------------------------- chapters
|
|
145
349
|
|
|
146
350
|
def _chapter_time(tok: str) -> float:
|
package/scripts/_common.py
CHANGED
|
@@ -332,7 +332,8 @@ def _stage(project: Path, src: Path, folder: str) -> str:
|
|
|
332
332
|
os.link(src, dst)
|
|
333
333
|
except OSError:
|
|
334
334
|
info(f"copying {src.name} into the project (hard link not possible across drives) ...")
|
|
335
|
-
|
|
335
|
+
# Bytes only: copying a macOS system font's file flags (copy2 -> chflags) is not permitted.
|
|
336
|
+
shutil.copyfile(src, dst)
|
|
336
337
|
return rel
|
|
337
338
|
|
|
338
339
|
|
package/scripts/_contract.py
CHANGED
|
@@ -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;
|
|
41
|
-
|
|
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", "
|
|
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
|
},
|
package/scripts/analyze.py
CHANGED
|
@@ -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.
|
|
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
|
|
|
@@ -14,17 +18,36 @@ Examples:
|
|
|
14
18
|
python3 analyze.py music.mp4 --beats # also measure the beat grid
|
|
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
|
|
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
|
|
17
23
|
"""
|
|
18
24
|
import argparse
|
|
25
|
+
import hashlib
|
|
26
|
+
import shutil
|
|
19
27
|
import sys
|
|
28
|
+
import tempfile
|
|
29
|
+
from fractions import Fraction
|
|
20
30
|
from pathlib import Path
|
|
21
|
-
from typing import Any, Dict, List, Optional
|
|
31
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
22
32
|
|
|
23
33
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
24
34
|
from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
|
|
25
35
|
emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
|
|
26
36
|
require_ffmpeg_skill, shell_join, version)
|
|
27
|
-
from _captions import CaptionError, cues_from_words, parse_chapters, read_captions,
|
|
37
|
+
from _captions import (CaptionError, cues_from_words, parse_chapters, read_captions, read_word_timings,
|
|
38
|
+
youtube_chapter_warnings)
|
|
39
|
+
|
|
40
|
+
# seconds a transcript's duration may differ from the measured source (transcription-skill's own END_TOLERANCE)
|
|
41
|
+
TRANSCRIPT_DURATION_TOLERANCE = 0.5
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def file_fingerprint(path: Path) -> str:
|
|
45
|
+
"""`sha256:<hex>` of the file bytes -- the identity transcription-skill writes to source.fingerprint."""
|
|
46
|
+
h = hashlib.sha256()
|
|
47
|
+
with open(path, "rb") as f:
|
|
48
|
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
49
|
+
h.update(chunk)
|
|
50
|
+
return "sha256:" + h.hexdigest()
|
|
28
51
|
|
|
29
52
|
|
|
30
53
|
def build_parser() -> argparse.ArgumentParser:
|
|
@@ -37,8 +60,9 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
37
60
|
p.add_argument("--join-duration", type=float, default=0.5, help="transition length in seconds (default 0.5)")
|
|
38
61
|
p.add_argument("-o", "--output", help="timeline file (default: <name>.timeline.json)")
|
|
39
62
|
p.add_argument("--captions", help="SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written)")
|
|
40
|
-
p.add_argument("--words", help="word timings
|
|
41
|
-
"
|
|
63
|
+
p.add_argument("--words", help="word timings for the Karaoke and Captioned compositions: a transcription-skill "
|
|
64
|
+
"transcript (schema transcription-skill/transcript/0.1, validated strictly) or whisper "
|
|
65
|
+
"JSON with word timestamps; without --captions the cues are grouped from these words")
|
|
42
66
|
p.add_argument("--chapters", metavar="FILE|source",
|
|
43
67
|
help="chapter list, one `TIME TITLE` per line (YouTube's format, the same file ffmpeg-skill "
|
|
44
68
|
"metadata.py --chapters writes into the container), or `source` for the chapters already "
|
|
@@ -51,6 +75,16 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
51
75
|
"instead of measuring it -- for a camera without usable audio")
|
|
52
76
|
p.add_argument("--pip-max-offset", type=float, default=30.0,
|
|
53
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)")
|
|
54
88
|
p.add_argument("--beats", action="store_true", help="also measure the beat grid (scenes.py --beats)")
|
|
55
89
|
p.add_argument("--highlights", type=int, metavar="N",
|
|
56
90
|
help="also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition")
|
|
@@ -87,14 +121,10 @@ def scene_args(a: argparse.Namespace) -> List[str]:
|
|
|
87
121
|
|
|
88
122
|
|
|
89
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)."""
|
|
90
126
|
w: List[str] = []
|
|
91
127
|
v = probe.get("video") or {}
|
|
92
|
-
if v.get("variable_frame_rate_suspected"):
|
|
93
|
-
w.append("variable frame rate suspected: Remotion renders on a fixed frame grid, so cuts and captions "
|
|
94
|
-
"can drift. Make a constant-frame-rate copy first (ffmpeg-skill export.py / fit.py --fps).")
|
|
95
|
-
if v.get("hdr") or v.get("hdr_signal") or v.get("bt2020_or_hdr"):
|
|
96
|
-
w.append("HDR / BT.2020 source: Remotion composites in the browser's SDR colour space, so the picture "
|
|
97
|
-
"will look washed out. Convert first: ffmpeg-skill color.py --to-sdr.")
|
|
98
128
|
if v.get("rotation"):
|
|
99
129
|
w.append(f"source is rotated {v.get('rotation')} degrees by metadata; check the first still.py frame.")
|
|
100
130
|
fps = v.get("fps")
|
|
@@ -103,6 +133,137 @@ def warnings_for(probe: Dict[str, Any]) -> List[str]:
|
|
|
103
133
|
return w
|
|
104
134
|
|
|
105
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
|
+
|
|
106
267
|
def main() -> None:
|
|
107
268
|
a = build_parser().parse_args()
|
|
108
269
|
apply_common(a)
|
|
@@ -114,6 +275,12 @@ def main() -> None:
|
|
|
114
275
|
joined: Path = Path(a.joined).expanduser() if a.joined else default_output(src, "_joined", ".mp4")
|
|
115
276
|
out = Path(a.output) if a.output else default_output(joined if len(inputs) > 1 else src, ".timeline", ".json")
|
|
116
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"))
|
|
117
284
|
skill = require_ffmpeg_skill()
|
|
118
285
|
|
|
119
286
|
captions: List[Dict[str, Any]] = []
|
|
@@ -127,16 +294,20 @@ def main() -> None:
|
|
|
127
294
|
die(f"cannot read {cpath}: {e}", "input")
|
|
128
295
|
|
|
129
296
|
words: List[Dict[str, Any]] = []
|
|
297
|
+
transcript: Optional[Dict[str, Any]] = None
|
|
130
298
|
if a.words:
|
|
131
299
|
wpath = Path(a.words).expanduser()
|
|
132
300
|
if not wpath.is_file():
|
|
133
301
|
die(f"word timings file not found: {wpath}", "input")
|
|
134
302
|
try:
|
|
135
|
-
|
|
303
|
+
timed = read_word_timings(wpath)
|
|
136
304
|
except (CaptionError, ValueError) as e:
|
|
137
305
|
die(f"cannot read {wpath}: {e}", "input")
|
|
306
|
+
words = timed["words"]
|
|
307
|
+
if timed["cues"] is not None:
|
|
308
|
+
transcript = timed
|
|
138
309
|
if not captions:
|
|
139
|
-
captions = cues_from_words(words)
|
|
310
|
+
captions = timed["cues"] if transcript else cues_from_words(words)
|
|
140
311
|
|
|
141
312
|
join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
|
|
142
313
|
"--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
|
|
@@ -144,11 +315,27 @@ def main() -> None:
|
|
|
144
315
|
[shell_join(ffskill_cmd("probe", [str(joined if len(inputs) > 1 else src)]))]
|
|
145
316
|
if STATE.dry_run:
|
|
146
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"
|
|
147
333
|
if not a.no_scenes:
|
|
148
334
|
plan.append(shell_join(ffskill_cmd("scenes", [target, *scene_args(a)])))
|
|
149
335
|
if not a.no_silence:
|
|
150
336
|
plan.append(shell_join(ffskill_cmd("silence", [target, *silence_args(a)])))
|
|
151
|
-
emit({"output": str(out), "commands": plan
|
|
337
|
+
emit({"output": str(out), "commands": plan, **({"note": note} if note else {})},
|
|
338
|
+
f"would write {out} after {len(plan)} ffmpeg-skill steps")
|
|
152
339
|
return
|
|
153
340
|
|
|
154
341
|
clips: List[Dict[str, Any]] = []
|
|
@@ -173,15 +360,37 @@ def main() -> None:
|
|
|
173
360
|
src = joined
|
|
174
361
|
|
|
175
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)
|
|
176
372
|
video, audio = probe.get("video"), probe.get("audio")
|
|
177
373
|
duration = float(probe.get("duration") or (video or {}).get("duration") or (audio or {}).get("duration") or 0)
|
|
178
374
|
if duration <= 0:
|
|
179
375
|
die(f"{src} has no measurable duration", "input")
|
|
180
|
-
commands = pre_commands + [probe["_command"]]
|
|
181
376
|
if clips:
|
|
182
377
|
# The last boundary is the measured joined duration (encoders can round the tail by a frame).
|
|
183
378
|
clips[-1]["end"] = round(duration, 3)
|
|
184
379
|
|
|
380
|
+
transcript_warnings: List[str] = []
|
|
381
|
+
if transcript:
|
|
382
|
+
# The transcript's times are seconds on the file it was made from: a different length means a
|
|
383
|
+
# different file, and its words would land in the wrong places.
|
|
384
|
+
if abs(transcript["duration"] - duration) > TRANSCRIPT_DURATION_TOLERANCE:
|
|
385
|
+
die(f"--words: the transcript is of a {transcript['duration']:.3f} s file ({transcript['filename']}), "
|
|
386
|
+
f"the source measures {duration:.3f} s; transcribe this source (or the joined file)", "input")
|
|
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")}:
|
|
389
|
+
transcript_warnings.append(
|
|
390
|
+
f"--words: the transcript was made from {transcript['filename']}, not these exact bytes "
|
|
391
|
+
f"(same length, so its times are used as written)")
|
|
392
|
+
transcript_warnings += transcript["warnings"]
|
|
393
|
+
|
|
185
394
|
scenes: List[Dict[str, float]] = [{"start": 0.0, "end": round(duration, 3)}]
|
|
186
395
|
peaks: List[Dict[str, float]] = []
|
|
187
396
|
beats: Any = None
|
|
@@ -242,10 +451,19 @@ def main() -> None:
|
|
|
242
451
|
cv = cp.get("video") or {}
|
|
243
452
|
if not cv:
|
|
244
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 {}
|
|
245
462
|
pip = {"path": str(cam.resolve()), "name": cam.name,
|
|
246
463
|
"duration": round(float(cv.get("duration") or cp.get("duration") or 0), 3),
|
|
247
464
|
"width": int(cv.get("width") or 0), "height": int(cv.get("height") or 0),
|
|
248
|
-
"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}
|
|
249
467
|
if a.pip_offset is not None:
|
|
250
468
|
pip["offset"] = round(float(a.pip_offset), 4)
|
|
251
469
|
elif not (audio and cp.get("audio")):
|
|
@@ -285,7 +503,9 @@ def main() -> None:
|
|
|
285
503
|
"words": words,
|
|
286
504
|
"chapters": chapters,
|
|
287
505
|
"pip": pip,
|
|
288
|
-
|
|
506
|
+
# Provenance of a conformed source (--conform): the original, each ffmpeg-skill step, the measured copy.
|
|
507
|
+
"conform": conform,
|
|
508
|
+
"warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings,
|
|
289
509
|
}
|
|
290
510
|
if pip and pip["measured"] and (pip["confidence"] or 0) < 0.3:
|
|
291
511
|
timeline["warnings"].append(f"pip: the measured offset ({pip['offset']:g} s) has low confidence "
|
|
@@ -295,6 +515,9 @@ def main() -> None:
|
|
|
295
515
|
"render with --aspect / --width to choose the frame.")
|
|
296
516
|
for w in timeline["warnings"]:
|
|
297
517
|
info(f"warning: {w}")
|
|
518
|
+
for st in (conform or {}).get("steps", []):
|
|
519
|
+
for n in st["notes"]:
|
|
520
|
+
info(f"conform: {n}")
|
|
298
521
|
|
|
299
522
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
300
523
|
import json
|
|
@@ -308,10 +531,13 @@ def main() -> None:
|
|
|
308
531
|
"captions": len(captions), "chapters": len(chapters),
|
|
309
532
|
"pip_offset": pip["offset"] if pip else None, "beats": bool(beats and beats.get("usable")),
|
|
310
533
|
"tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
|
|
311
|
-
"clips": len(clips) or 1, "words": len(words)
|
|
534
|
+
"clips": len(clips) or 1, "words": len(words),
|
|
535
|
+
"conformed": (conform or {}).get("reasons", [])},
|
|
312
536
|
"warnings": timeline["warnings"]},
|
|
313
537
|
f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
|
|
314
|
-
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 ""))
|
|
315
541
|
|
|
316
542
|
|
|
317
543
|
if __name__ == "__main__":
|
package/scripts/pipeline.py
CHANGED
|
@@ -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
|
|