remotion-ffmpeg-skill 0.12.1 → 0.14.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 +1 -0
- package/SKILL.md +5 -0
- package/package.json +1 -1
- package/references/scripts.md +43 -4
- package/references/timeline.md +5 -0
- package/scripts/_captions.py +210 -1
- package/scripts/_common.py +46 -3
- package/scripts/_contract.py +57 -1
- package/scripts/_docs.py +7 -0
- package/scripts/analyze.py +34 -4
- package/scripts/render.py +1 -1
- package/templates/remotion-project/package.json +3 -3
- package/templates/remotion-project/src/Root.tsx +2 -0
- package/templates/remotion-project/src/compositions/Emphasis.tsx +291 -0
- package/templates/remotion-project/src/timeline.ts +28 -0
package/README.md
CHANGED
|
@@ -97,6 +97,7 @@ Tool names and input schemas come from the machine-readable contract (`npx remot
|
|
|
97
97
|
| `Highlights` | sum of ranked highlights | ffmpeg-skill's audio-energy highlights back to back, counter, title |
|
|
98
98
|
| `BeatMontage` | source duration | audio unbroken, picture cuts on the measured beat grid |
|
|
99
99
|
| `Karaoke` | source duration | words light up at the times a local speech engine measured |
|
|
100
|
+
| `Emphasis` | source duration | YouTube-style captions: the words you name (or the captions' own numbers / names) pop, change colour or get a box when spoken; speech bubbles and comment cards |
|
|
100
101
|
| `Pip` | source duration | a second recording (camera) in a corner, synced by the offset measured between the two audio tracks; captions on top |
|
|
101
102
|
|
|
102
103
|
**Any shape:** `--aspect 9:16 | 1:1 | 4:5 | 16:9` with `--fit blur | contain | cover`; `pipeline.py --platform reels` picks 9:16 from ffmpeg-skill's own template so nothing gets cropped on delivery.
|
package/SKILL.md
CHANGED
|
@@ -42,13 +42,17 @@ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts
|
|
|
42
42
|
|
|
43
43
|
## Request → script / composition
|
|
44
44
|
|
|
45
|
+
Moving text has three owners: word-timed caption effects are this skill's, animated captions from subtitle cues alone are subtitle-skill's, and `Titled`'s titles stay inside these compositions (burned-in titles: motion-graphics-skill; title and stinger material files: hyperframes-skill). See [docs/design-decisions.md](docs/design-decisions.md), "Title and caption boundaries".
|
|
46
|
+
|
|
45
47
|
| Request | Run |
|
|
46
48
|
|---|---|
|
|
49
|
+
| animated captions from subtitle cues alone (fade / pop / slide, karaoke without word timings) | not this skill: subtitle-skill |
|
|
47
50
|
| "animated captions / subtitles on this video" | `analyze.py --captions` → `render.py --comp Captioned` |
|
|
48
51
|
| "cut the silences / jump cut / tighten this talk" (with motion) | `analyze.py` → `render.py --comp Jumpcut` (captions re-timed if given) |
|
|
49
52
|
| "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
53
|
| "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
54
|
| "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) |
|
|
55
|
+
| "YouTube-style captions" / "make these words pop" / speech bubbles, comment cards | `analyze.py --words WORDS.json --emphasis words.json` (the user's words: `["42%", {"text": "launch", "at": 12.3, "style": "box"}]`; `--emphasis-auto numbers,names` adds the captions' own numbers / capitalised or katakana names) → `render.py --comp Emphasis` (`emphasisStyle`, `bubbles`, `comments` in `--options`). A word that is not a whole, timed word of its cue is refused (`kind: input`): tell the user which, never respell the caption to make it fit |
|
|
52
56
|
| "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 |
|
|
53
57
|
| "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 |
|
|
54
58
|
| "highlight reel / best moments" | `analyze.py --highlights N [--target S]` → `render.py --comp Highlights` (audio-energy ranking: candidates, say so) |
|
|
@@ -82,3 +86,4 @@ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts
|
|
|
82
86
|
- Speed (measured on a 2-core Linux machine, all cores — render.py's default): about 2.6× the clip length for 1080p30 (30 s took 80 s). Preview with `still.py` and `--fast` before a full render of long footage; tell the user the expected time before starting a long render. `--sparse` cuts that to the share that shows graphics: 60 s with 7 s of captions went from 152 s to 46 s; 40 s with two scene titles and one lower third from 104 s to 39 s. `--concurrency` above the core count is refused by Remotion.
|
|
83
87
|
- Remotion packages in a project must all be the same version; the template pins them. Don't mix in a different `remotion` version.
|
|
84
88
|
- A render that fails verification is a failure: report the failed rows from `--json`, don't ship it.
|
|
89
|
+
- Re-renders: on the same machine and toolchain (Remotion, Chromium, FFmpeg, fonts) with the same inputs, `render.py` and `still.py` give byte-identical files (`idempotency_hint: bit_exact` in the contract), whatever `--concurrency` is; compare them by sha256. Across machines, OSes or toolchain updates the bytes can change: compare by content (per-frame PSNR). Conditions and what is unverified: `docs/adr/0001-render-determinism.md`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "remotion-ffmpeg-skill",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.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/scripts.md
CHANGED
|
@@ -15,6 +15,7 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
|
|
|
15
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
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
|
+
- Repeatability: `content_equivalent` (deterministic: yes)
|
|
18
19
|
|
|
19
20
|
| Argument | Type | Default | Meaning |
|
|
20
21
|
|---|---|---|---|
|
|
@@ -25,6 +26,8 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
|
|
|
25
26
|
| `--output` | string | | timeline file (default: <name>.timeline.json) |
|
|
26
27
|
| `--captions` | string | | SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written) |
|
|
27
28
|
| `--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 |
|
|
29
|
+
| `--emphasis` | string | | words to emphasise in the Emphasis composition (pop, colour or box at the time each is spoken): a JSON list of words or {text, at?, style?}. Each must be a whole, timed word of a caption cue (of the cue showing at `at`), or it is refused; needs --words |
|
|
30
|
+
| `--emphasis-auto` | string | | with --words: also emphasise the captions' own numbers and/or names (comma-separated: numbers, names = capitalised mid-sentence or katakana words) |
|
|
28
31
|
| `--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
32
|
| `--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
33
|
| `--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 |
|
|
@@ -42,7 +45,7 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
|
|
|
42
45
|
| `--margin` | number | | seconds of silence kept around speech (default 0.15) |
|
|
43
46
|
| `--scene-threshold` | number | | scenes.py --threshold (default 8) |
|
|
44
47
|
|
|
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])
|
|
48
|
+
--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, emphasis, conformed (list: vfr / hdr)), `warnings` (list[str])
|
|
46
49
|
|
|
47
50
|
--dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str])
|
|
48
51
|
|
|
@@ -55,6 +58,7 @@ Create a Remotion project with the built-in compositions (optionally npm install
|
|
|
55
58
|
- Verifies: refuses a non-empty folder; npm install exit status
|
|
56
59
|
- ffmpeg-skill: —
|
|
57
60
|
- `--dry-run`: plans without writing
|
|
61
|
+
- Repeatability: `content_equivalent` (deterministic: yes)
|
|
58
62
|
|
|
59
63
|
| Argument | Type | Default | Meaning |
|
|
60
64
|
|---|---|---|---|
|
|
@@ -74,11 +78,12 @@ Render single frames as PNG to check the look before a full render.
|
|
|
74
78
|
- Verifies: frames must lie inside the composition; view the PNGs
|
|
75
79
|
- ffmpeg-skill: _contract doctor (CJK font lookup)
|
|
76
80
|
- `--dry-run`: plans without writing
|
|
81
|
+
- Repeatability: `bit_exact` (deterministic: yes)
|
|
77
82
|
|
|
78
83
|
| Argument | Type | Default | Meaning |
|
|
79
84
|
|---|---|---|---|
|
|
80
85
|
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
81
|
-
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, or yours) |
|
|
86
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or yours) |
|
|
82
87
|
| `--timeline (required)` | string | | timeline.json written by analyze.py |
|
|
83
88
|
| `--options` | string | | JSON object of look-and-feel options |
|
|
84
89
|
| `--at` | number, repeatable | | time in seconds (repeatable) |
|
|
@@ -104,11 +109,12 @@ Render a composition from a timeline, verify it (frames, fps, size, audio) and w
|
|
|
104
109
|
- Verifies: exact frame count / fps / size / audio against the timeline; non-zero exit on mismatch
|
|
105
110
|
- ffmpeg-skill: probe, look, overlay (--overlay; --place with --sparse), _contract doctor (CJK font lookup)
|
|
106
111
|
- `--dry-run`: plans without writing
|
|
112
|
+
- Repeatability: `bit_exact` (deterministic: yes)
|
|
107
113
|
|
|
108
114
|
| Argument | Type | Default | Meaning |
|
|
109
115
|
|---|---|---|---|
|
|
110
116
|
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
111
|
-
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, or one you added) |
|
|
117
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or one you added) |
|
|
112
118
|
| `--timeline (required)` | string | | timeline.json written by analyze.py |
|
|
113
119
|
| `--options` | string | | JSON object of look-and-feel options (see references/timeline.md) |
|
|
114
120
|
| `--output` | string | | output file (default: <source>_<comp>.mp4, .mov for prores) |
|
|
@@ -142,6 +148,7 @@ Run an ffmpeg-skill delivery template (YouTube, Reels, ...) and its compliance c
|
|
|
142
148
|
- Verifies: ffmpeg-skill check.py table; non-zero exit on any FAIL row
|
|
143
149
|
- ffmpeg-skill: render --template, metadata (--chapters), check
|
|
144
150
|
- `--dry-run`: plans without writing
|
|
151
|
+
- Repeatability: `bit_exact` (deterministic: yes)
|
|
145
152
|
|
|
146
153
|
| Argument | Type | Default | Meaning |
|
|
147
154
|
|---|---|---|---|
|
|
@@ -166,12 +173,13 @@ analyze -> render -> deliver in one call, stopping at the first failed step.
|
|
|
166
173
|
- Verifies: each step's own verification
|
|
167
174
|
- ffmpeg-skill: probe, scenes, silence, fit (--conform), color (--conform), look, render --template, check
|
|
168
175
|
- `--dry-run`: plans without writing
|
|
176
|
+
- Repeatability: `content_equivalent` (deterministic: yes)
|
|
169
177
|
|
|
170
178
|
| Argument | Type | Default | Meaning |
|
|
171
179
|
|---|---|---|---|
|
|
172
180
|
| `input` | string, repeatable | | source video; several are joined in order (ffmpeg-skill join.py) first |
|
|
173
181
|
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
174
|
-
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, or yours) |
|
|
182
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or yours) |
|
|
175
183
|
| `--captions` | string | | SRT / WebVTT / JSON cues for the timeline |
|
|
176
184
|
| `--chapters` | string | | chapters (`TIME TITLE` per line, or `source`): cards in Titled and, with --platform, chapter markers in the deliverable |
|
|
177
185
|
| `--options` | string | | JSON options file passed to the composition |
|
|
@@ -199,6 +207,7 @@ What this machine can do: Python, Node/npm, ffmpeg-skill, ffmpeg, a project's Re
|
|
|
199
207
|
- Verifies: reports only
|
|
200
208
|
- ffmpeg-skill: _contract doctor
|
|
201
209
|
- `--dry-run`: not applicable (reports only)
|
|
210
|
+
- Repeatability: `environment_dependent` (deterministic: no)
|
|
202
211
|
|
|
203
212
|
| Argument | Type | Default | Meaning |
|
|
204
213
|
|---|---|---|---|
|
|
@@ -206,6 +215,36 @@ What this machine can do: Python, Node/npm, ffmpeg-skill, ffmpeg, a project's Re
|
|
|
206
215
|
|
|
207
216
|
--json result (besides `status`, `dry_run`, `output`): `ok` (bool), `version` (str), `checks` (list[{check, ok, value, fix}]), `ffmpeg_skill_doctor` (object|null)
|
|
208
217
|
|
|
218
|
+
## Repeatability
|
|
219
|
+
|
|
220
|
+
`idempotency_hint` per tool: `bit_exact`, `content_equivalent`, `environment_dependent`. Scope: same machine, same inputs (same paths, same options), same Remotion version, same Chromium (chrome-headless-shell) build and GL backend, same FFmpeg and ffmpeg-skill, same fonts.
|
|
221
|
+
|
|
222
|
+
Holds:
|
|
223
|
+
|
|
224
|
+
- every built-in composition renders twice to byte-identical files: per-frame md5 of the video, md5 of the audio and the file's sha256 match (render.py H.264, --fast, --codec prores, --overlay), in two separate runs
|
|
225
|
+
- --concurrency does not change the output: 1 tab and all cores give the same bytes
|
|
226
|
+
- still.py writes byte-identical PNGs
|
|
227
|
+
- analyze.py run twice on the same file writes a byte-identical timeline.json; on a copy at another path only source.path differs
|
|
228
|
+
- pipeline.py writes byte-identical render and deliverable files; it is content_equivalent, not bit_exact, because its timeline.json records the input's absolute path
|
|
229
|
+
- init.py (without --install) writes an identical project folder
|
|
230
|
+
|
|
231
|
+
Does not hold:
|
|
232
|
+
|
|
233
|
+
- another Chromium build: chrome-headless-shell 153 and 156 differed on every frame (PSNR 43 dB average, 38 dB lowest), so after a Remotion or browser update compare by content, not by hash
|
|
234
|
+
- another GL backend: Config.setChromiumOpenGlRenderer('swangle') in remotion.config.ts changed every frame (42 dB average); render.py sets none, and on a machine without a GPU the default, angle, egl, swiftshader and vulkan gave the same bytes
|
|
235
|
+
- another font: --font-file with a different font changed the captions (29 dB average); the CJK auto font is whatever ffmpeg-skill finds installed
|
|
236
|
+
- another input path: timeline.json records absolute paths, so its bytes differ (its numbers do not)
|
|
237
|
+
|
|
238
|
+
Unverified:
|
|
239
|
+
|
|
240
|
+
- across operating systems: CI checks each of Linux, macOS and Windows against itself only
|
|
241
|
+
- on a machine with a GPU, where the GL backends may no longer agree
|
|
242
|
+
- another FFmpeg or x264 build (the encoder Remotion bundles is pinned with Remotion)
|
|
243
|
+
- across two machines with the same OS and toolchain
|
|
244
|
+
- analyze.py --conform and several-input joins (their re-encoded copies were not compared); init.py --install
|
|
245
|
+
|
|
246
|
+
Not reproducible: none found.
|
|
247
|
+
|
|
209
248
|
## Failures
|
|
210
249
|
|
|
211
250
|
Every failure is one JSON object: `status` (failed), `error` (str), `kind` (input|missing_tool|timeout|failed), `dry_run` (bool).
|
package/references/timeline.md
CHANGED
|
@@ -28,6 +28,7 @@ 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
|
+
| `emphasis` | `[{start, end, text, style, cue, span, words, by}]` | `--emphasis FILE` (the caller's words: a JSON list of words or `{text, at?, style?}`) and / or `--emphasis-auto numbers,names`; needs `--words` | each emphasised word as a slice of caption cue `cue`'s own timed words (`words` = [first, last] index into `words`): `start` / `end` are the engine's times of those words, `text` the caption's own spelling, `span` its [start, end) code-point offsets in the cue's text (the cue text is what is drawn; when `--captions` and `--words` disagree about a word, it is refused). `style` is `pop`, `color`, `box` or null (= the `emphasisStyle` option); `by` is `caller`, `numbers` or `names`. A caller's word that is not a whole, timed word of the cue (or of the cue showing at `at`) is refused (`kind: input`) |
|
|
31
32
|
| `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
33
|
| `warnings` | `[string]` | analyze.py | rotation, odd frame rate, chapters, transcript (VFR and HDR are never warnings: conformed or refused) |
|
|
33
34
|
|
|
@@ -45,6 +46,7 @@ composition exactly.
|
|
|
45
46
|
| `Titled` | source duration | source + the user's lower thirds (`lowerThirds`) + a title card at the start of each measured scene (`sceneTitles`, in order) + a chapter card at each chapter start (`chapters`, numbered n / total) |
|
|
46
47
|
| `Highlights` | sum of `highlights` (whole file if none) | ranked ranges back to back in source order, flash on cuts, "2 / 5" counter, `title` over the first |
|
|
47
48
|
| `Karaoke` | source duration | caption cues whose words light up at their measured times (current word accent + lift, spoken white, upcoming dimmed); cues without timed words show plain |
|
|
49
|
+
| `Emphasis` | source duration | YouTube-style captions: each cue as written; its `emphasis` words pop, take the accent colour or get an accent box from the time they are spoken to the end of the cue; speech bubbles (`bubbles`) and comment-style cards (`comments`) with the user's text at their own times |
|
|
48
50
|
| `Pip` | source duration | the source with `pip` (a camera) in a corner while the camera has pictures, synced by `pip.offset`; captions on top as in Captioned |
|
|
49
51
|
| `BeatMontage` | source duration | audio unbroken; the picture cuts every `beatsPerCut` measured beats, cycling through highlights (or scenes); no usable grid → cuts on scene changes |
|
|
50
52
|
|
|
@@ -71,6 +73,9 @@ Every key is optional.
|
|
|
71
73
|
| `pipSize` | `0.28` | Pip: camera width as a fraction of the frame width (circle: of the short side), 0.05–0.6 |
|
|
72
74
|
| `pipShape` | `"rounded"` | Pip: `rounded` or `circle` |
|
|
73
75
|
| `pipAudio` | `false` | Pip: also play the camera's own audio |
|
|
76
|
+
| `emphasisStyle` | `"pop"` | Emphasis: `pop` (scales up, accent colour), `color` (accent colour) or `box` (accent box, dark text) for an emphasised word without its own `style` |
|
|
77
|
+
| `bubbles` | `[]` | Emphasis: speech bubbles `[{"text", "start", "end", "side"?}]` (`side`: `left` or `right`), the user's text, seconds on the source timeline |
|
|
78
|
+
| `comments` | `[]` | Emphasis: comment-style cards `[{"text", "start", "end", "author"?}]`, top left, stacked while they overlap; the user's text |
|
|
74
79
|
| `chapterSeconds` | `4` | Titled: how long a chapter card stays up (cut short by the next chapter; 0 = none) |
|
|
75
80
|
|
|
76
81
|
Unknown keys and wrong types are refused by render.py / still.py before anything renders.
|
package/scripts/_captions.py
CHANGED
|
@@ -9,7 +9,7 @@ import json
|
|
|
9
9
|
import re
|
|
10
10
|
import unicodedata
|
|
11
11
|
from pathlib import Path
|
|
12
|
-
from typing import Any, Dict, List, Optional
|
|
12
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
13
13
|
|
|
14
14
|
_TS = re.compile(r"(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})")
|
|
15
15
|
_ARROW = re.compile(r"^\s*(\S+)\s+-->\s+(\S+)")
|
|
@@ -345,6 +345,215 @@ def read_word_timings(path: Path) -> Dict[str, Any]:
|
|
|
345
345
|
return {"words": parse_words(text), "cues": None, "warnings": []}
|
|
346
346
|
|
|
347
347
|
|
|
348
|
+
# ---------------------------------------------------------------- emphasis (YouTube-style captions)
|
|
349
|
+
|
|
350
|
+
EMPHASIS_STYLES = ("pop", "color", "box")
|
|
351
|
+
EMPHASIS_AUTO = ("numbers", "names")
|
|
352
|
+
_SENTENCE_END = (".", "!", "?", "。", "!", "?")
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _fold(s: str) -> str:
|
|
356
|
+
"""Lower case, one character for one character, so offsets in the folded text are offsets in the original."""
|
|
357
|
+
return "".join(ch.lower() if len(ch.lower()) == 1 else ch for ch in s)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _is_punct(s: str) -> bool:
|
|
361
|
+
return all(unicodedata.category(ch)[0] in ("P", "Z") or ch.isspace() for ch in s)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def read_emphasis(text: str) -> List[Dict[str, Any]]:
|
|
365
|
+
"""`--emphasis FILE`: the words to emphasise, as written by the caller. A JSON list (or {"words": [...]})
|
|
366
|
+
of strings or {"text", "at"?, "style"?}: `at` (seconds) picks the cue showing at that time, `style`
|
|
367
|
+
is pop, color or box (default: the emphasisStyle option)."""
|
|
368
|
+
data = json.loads(text)
|
|
369
|
+
if isinstance(data, dict):
|
|
370
|
+
data = data.get("words")
|
|
371
|
+
if not isinstance(data, list) or not data:
|
|
372
|
+
raise CaptionError('emphasis must be a non-empty JSON list of words or {"text", "at"?, "style"?}')
|
|
373
|
+
out: List[Dict[str, Any]] = []
|
|
374
|
+
for i, e in enumerate(data):
|
|
375
|
+
if isinstance(e, str):
|
|
376
|
+
e = {"text": e}
|
|
377
|
+
if not isinstance(e, dict) or not isinstance(e.get("text"), str) or not e["text"].strip():
|
|
378
|
+
raise CaptionError(f"emphasis[{i}] needs a non-empty text")
|
|
379
|
+
unknown = set(e) - {"text", "at", "style"}
|
|
380
|
+
if unknown:
|
|
381
|
+
raise CaptionError(f"emphasis[{i}]: unknown key(s) {sorted(unknown)} (known: text, at, style)")
|
|
382
|
+
at = e.get("at")
|
|
383
|
+
if at is not None and not _num(at):
|
|
384
|
+
raise CaptionError(f"emphasis[{i}]: at must be seconds")
|
|
385
|
+
style = e.get("style")
|
|
386
|
+
if style is not None and style not in EMPHASIS_STYLES:
|
|
387
|
+
raise CaptionError(f"emphasis[{i}]: style must be one of {', '.join(EMPHASIS_STYLES)}")
|
|
388
|
+
out.append({"text": e["text"].strip(), "at": at, "style": style})
|
|
389
|
+
return out
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _cue_tokens(cue: Dict[str, Any], words: List[Dict[str, Any]]) -> Tuple[str, List[Tuple[int, int, int]]]:
|
|
393
|
+
"""The cue's timed words (by midpoint, as the compositions assign them) joined with their own spacing,
|
|
394
|
+
and per word (global index, offset where its text starts after the leading space, offset where it ends)."""
|
|
395
|
+
joined, toks = "", []
|
|
396
|
+
for gi, w in enumerate(words):
|
|
397
|
+
mid = (w["start"] + w["end"]) / 2
|
|
398
|
+
if not cue["start"] <= mid <= cue["end"]:
|
|
399
|
+
continue
|
|
400
|
+
lead = len(w["text"]) - len(w["text"].lstrip())
|
|
401
|
+
toks.append((gi, len(joined) + lead, len(joined) + len(w["text"])))
|
|
402
|
+
joined += w["text"]
|
|
403
|
+
return joined, toks
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _find(target: str, joined: str, toks: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int, int]]:
|
|
407
|
+
"""Every whole-word occurrence of target in the cue's words: (first word, last word, start, end offsets).
|
|
408
|
+
It starts where a word starts and ends where a word ends, or before only that word's trailing punctuation."""
|
|
409
|
+
folded, t, hits = _fold(joined), _fold(target), []
|
|
410
|
+
starts = {a: k for k, (_, a, _) in enumerate(toks)}
|
|
411
|
+
pos = folded.find(t)
|
|
412
|
+
while pos >= 0:
|
|
413
|
+
end = pos + len(t)
|
|
414
|
+
k = starts.get(pos)
|
|
415
|
+
if k is not None:
|
|
416
|
+
for m in range(k, len(toks)):
|
|
417
|
+
if toks[m][1] < end <= toks[m][2] and _is_punct(joined[end:toks[m][2]]):
|
|
418
|
+
hits.append((toks[k][0], toks[m][0], pos, end))
|
|
419
|
+
break
|
|
420
|
+
pos = folded.find(t, pos + 1)
|
|
421
|
+
return hits
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _cjk(ch: str) -> bool:
|
|
425
|
+
return "\u3040" <= ch <= "\u30ff" or "\u3400" <= ch <= "\u9fff" or "\uac00" <= ch <= "\ud7af" or "\uff00" <= ch <= "\uffef"
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _text_hits(target: str, text: str) -> List[Tuple[int, int]]:
|
|
429
|
+
"""Whole-word occurrences of target in a cue's own text, as [start, end) code-point offsets. Between
|
|
430
|
+
Latin letters or digits a boundary is needed (`foot` is not in `football`); CJK text has no spaces, so
|
|
431
|
+
there the timed words decide what a word is."""
|
|
432
|
+
folded, t, out = _fold(text), _fold(target), []
|
|
433
|
+
pos = folded.find(t)
|
|
434
|
+
while pos >= 0:
|
|
435
|
+
end = pos + len(t)
|
|
436
|
+
before = text[pos - 1] if pos else ""
|
|
437
|
+
after = text[end] if end < len(text) else ""
|
|
438
|
+
glued = lambda x, y: bool(x and y and x.isalnum() and y.isalnum() and not (_cjk(x) or _cjk(y)))
|
|
439
|
+
if not glued(before, text[pos]) and not glued(text[end - 1], after):
|
|
440
|
+
out.append((pos, end))
|
|
441
|
+
pos = folded.find(t, pos + 1)
|
|
442
|
+
return out
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _auto_candidates(kind: str, joined: str, toks: List[Tuple[int, int, int]]) -> List[Tuple[int, str]]:
|
|
446
|
+
"""(position among the cue's words, word) of each qualifying word: only that word, not every
|
|
447
|
+
occurrence of its spelling, is emphasised."""
|
|
448
|
+
out = []
|
|
449
|
+
for k, (_, a, b) in enumerate(toks):
|
|
450
|
+
word = joined[a:b]
|
|
451
|
+
core = word.rstrip("".join(ch for ch in word if _is_punct(ch)))
|
|
452
|
+
if not core:
|
|
453
|
+
continue
|
|
454
|
+
if kind == "numbers" and any(unicodedata.category(ch) == "Nd" for ch in core):
|
|
455
|
+
out.append((k, core))
|
|
456
|
+
elif kind == "names":
|
|
457
|
+
prev = joined[:a].rstrip()
|
|
458
|
+
katakana = len(core) >= 2 and all("\u30a0" <= ch <= "\u30ff" for ch in core)
|
|
459
|
+
capital = (core[0].isupper() and core[0].isascii() and k > 0 and prev and not prev.endswith(_SENTENCE_END))
|
|
460
|
+
if katakana or capital:
|
|
461
|
+
out.append((k, core))
|
|
462
|
+
return out
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def resolve_emphasis(captions: List[Dict[str, Any]], words: List[Dict[str, Any]], entries: List[Dict[str, Any]],
|
|
466
|
+
auto: List[str]) -> Tuple[List[Dict[str, Any]], List[str]]:
|
|
467
|
+
"""Place each emphasised word on the caption cue that shows it, at the time the speech engine measured.
|
|
468
|
+
|
|
469
|
+
The emphasised text is a slice of the cue's own words (case and spelling as spoken in the caption),
|
|
470
|
+
never the caller's spelling and never rewritten. A caller's word that is not a whole word of the cue
|
|
471
|
+
(or of any cue, without `at`) is refused; nothing is moved, guessed or interpolated. `auto` adds the
|
|
472
|
+
cue's own numbers ("numbers") and capitalised / katakana names ("names") without a style.
|
|
473
|
+
The word must also be a whole word of the cue's own text (that text is what is drawn); `span` is its
|
|
474
|
+
[start, end) code-point offsets there.
|
|
475
|
+
Returns ([{start, end, text, style, cue, span, words: [first, last], by}], warnings)."""
|
|
476
|
+
if not entries and not auto:
|
|
477
|
+
raise CaptionError("nothing to emphasise: give words (--emphasis) or kinds (--emphasis-auto)")
|
|
478
|
+
if not words:
|
|
479
|
+
raise CaptionError("emphasis needs word timings (--words): a word's time is measured, never guessed")
|
|
480
|
+
if not captions:
|
|
481
|
+
raise CaptionError("emphasis needs caption cues")
|
|
482
|
+
tokens = [_cue_tokens(c, words) for c in captions]
|
|
483
|
+
out: List[Dict[str, Any]] = []
|
|
484
|
+
warnings: List[str] = []
|
|
485
|
+
taken = set()
|
|
486
|
+
|
|
487
|
+
def matches(ci: int, target: str) -> List[Tuple[Tuple[int, int, int, int], Tuple[int, int]]]:
|
|
488
|
+
"""The timed whole-word hits of target in cue ci, each paired with the same occurrence in the
|
|
489
|
+
cue's own text (n-th with n-th). The caption text is what is drawn, so the two must agree."""
|
|
490
|
+
timed = _find(target, *tokens[ci])
|
|
491
|
+
if not timed:
|
|
492
|
+
return []
|
|
493
|
+
in_text = _text_hits(target, captions[ci]["text"])
|
|
494
|
+
if len(in_text) != len(timed):
|
|
495
|
+
raise CaptionError(f"emphasis {target!r}: cue {ci + 1} ({captions[ci]['text']!r}) has it "
|
|
496
|
+
f"{len(in_text)} time(s) as a whole word but its word timings {len(timed)}; the "
|
|
497
|
+
"caption and the word timings disagree, so its time cannot be placed")
|
|
498
|
+
return list(zip(timed, in_text))
|
|
499
|
+
|
|
500
|
+
def add(ci: int, hit: Tuple[int, int, int, int], span_text: Tuple[int, int], style: Optional[str], by: str) -> bool:
|
|
501
|
+
first, last, _, _ = hit
|
|
502
|
+
span = set(range(first, last + 1))
|
|
503
|
+
if span & taken:
|
|
504
|
+
return False
|
|
505
|
+
taken.update(span)
|
|
506
|
+
a, b = span_text
|
|
507
|
+
out.append({"start": words[first]["start"], "end": words[last]["end"], "text": captions[ci]["text"][a:b],
|
|
508
|
+
"style": style, "cue": ci, "span": [a, b], "words": [first, last], "by": by})
|
|
509
|
+
return True
|
|
510
|
+
|
|
511
|
+
for e in entries:
|
|
512
|
+
if e["at"] is not None:
|
|
513
|
+
cues = [i for i, c in enumerate(captions) if c["start"] <= e["at"] < c["end"]]
|
|
514
|
+
if not cues:
|
|
515
|
+
raise CaptionError(f"emphasis {e['text']!r}: no caption cue shows at {e['at']:g} s")
|
|
516
|
+
else:
|
|
517
|
+
cues = list(range(len(captions)))
|
|
518
|
+
found, untimed_hit = 0, None
|
|
519
|
+
for ci in cues:
|
|
520
|
+
if _fold(e["text"]) not in _fold(captions[ci]["text"]):
|
|
521
|
+
continue
|
|
522
|
+
if not tokens[ci][1]:
|
|
523
|
+
untimed_hit = ci
|
|
524
|
+
for hit, span_text in matches(ci, e["text"]):
|
|
525
|
+
if not add(ci, hit, span_text, e["style"], "caller"):
|
|
526
|
+
raise CaptionError(f"emphasis {e['text']!r} overlaps another emphasised word in cue {ci + 1}")
|
|
527
|
+
found += 1
|
|
528
|
+
if not found and untimed_hit is not None:
|
|
529
|
+
raise CaptionError(f"emphasis {e['text']!r}: cue {untimed_hit + 1} ({captions[untimed_hit]['text']!r}) "
|
|
530
|
+
"has no word timings, so its time is not measured")
|
|
531
|
+
if not found:
|
|
532
|
+
where = (f"the cue at {e['at']:g} s ({captions[cues[0]]['text']!r})" if e["at"] is not None
|
|
533
|
+
else "any caption cue")
|
|
534
|
+
raise CaptionError(f"emphasis {e['text']!r} is not a whole word of {where}: only the caption's own, "
|
|
535
|
+
"timed words can be emphasised")
|
|
536
|
+
for kind in auto:
|
|
537
|
+
if kind not in EMPHASIS_AUTO:
|
|
538
|
+
raise CaptionError(f"--emphasis-auto: unknown kind {kind!r} (known: {', '.join(EMPHASIS_AUTO)})")
|
|
539
|
+
n = 0
|
|
540
|
+
for ci, (joined, toks) in enumerate(tokens):
|
|
541
|
+
for k, cand in _auto_candidates(kind, joined, toks):
|
|
542
|
+
try:
|
|
543
|
+
pairs = matches(ci, cand)
|
|
544
|
+
except CaptionError as err:
|
|
545
|
+
warnings.append(f"{err} (skipped)")
|
|
546
|
+
continue
|
|
547
|
+
n += sum(add(ci, hit, span_text, None, kind) for hit, span_text in pairs if hit[0] == toks[k][0])
|
|
548
|
+
if not n:
|
|
549
|
+
warnings.append(f"emphasis: no {kind} found in the timed caption words")
|
|
550
|
+
untimed = [i + 1 for i, (_, toks) in enumerate(tokens) if not toks]
|
|
551
|
+
if untimed and (entries or auto):
|
|
552
|
+
warnings.append("emphasis: cue(s) " + ", ".join(map(str, untimed)) + " have no word timings, so nothing "
|
|
553
|
+
"in them can be emphasised")
|
|
554
|
+
return sorted(out, key=lambda x: x["start"]), warnings
|
|
555
|
+
|
|
556
|
+
|
|
348
557
|
# ---------------------------------------------------------------- chapters
|
|
349
558
|
|
|
350
559
|
def _chapter_time(tok: str) -> float:
|
package/scripts/_common.py
CHANGED
|
@@ -225,7 +225,7 @@ def validate_timeline(t: Any) -> List[str]:
|
|
|
225
225
|
if t.get("pip") is not None and not (isinstance(t["pip"], dict) and isinstance(t["pip"].get("offset"), (int, float))
|
|
226
226
|
and t["pip"].get("path")):
|
|
227
227
|
p.append("pip must be {path, offset, duration, ...} (analyze.py --pip)")
|
|
228
|
-
for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights", "words", "chapters"):
|
|
228
|
+
for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights", "words", "chapters", "emphasis"):
|
|
229
229
|
if not isinstance(t.get(k, []), list):
|
|
230
230
|
p.append(f"{k} must be a list")
|
|
231
231
|
for i, c in enumerate(t.get("captions", []) or []):
|
|
@@ -234,6 +234,28 @@ def validate_timeline(t: Any) -> List[str]:
|
|
|
234
234
|
and c["end"] > c["start"]):
|
|
235
235
|
p.append(f"captions[{i}] needs start < end and text")
|
|
236
236
|
break
|
|
237
|
+
emph = t.get("emphasis") or []
|
|
238
|
+
caps = t.get("captions") if isinstance(t.get("captions"), list) else []
|
|
239
|
+
nwords = len(t["words"]) if isinstance(t.get("words"), list) else 0
|
|
240
|
+
for i, e in enumerate(emph if isinstance(emph, list) else []):
|
|
241
|
+
ok = (isinstance(e, dict) and _finite(e.get("start")) and _finite(e.get("end")) and e["end"] > e["start"]
|
|
242
|
+
and isinstance(e.get("text"), str) and e["text"] and isinstance(e.get("cue"), int)
|
|
243
|
+
and not isinstance(e["cue"], bool) and 0 <= e["cue"] < len(caps)
|
|
244
|
+
and e.get("style") in (None, "pop", "color", "box"))
|
|
245
|
+
for key, limit in (("span", None), ("words", nwords)):
|
|
246
|
+
r = e.get(key) if ok else None
|
|
247
|
+
ok = ok and (isinstance(r, list) and len(r) == 2 and all(isinstance(x, int) and not isinstance(x, bool)
|
|
248
|
+
for x in r) and 0 <= r[0] <= r[1])
|
|
249
|
+
if ok and limit is not None:
|
|
250
|
+
ok = r[1] < limit
|
|
251
|
+
if ok:
|
|
252
|
+
cue_text = caps[e["cue"]].get("text") if isinstance(caps[e["cue"]], dict) else None
|
|
253
|
+
ok = isinstance(cue_text, str) and e["span"][1] <= len(cue_text) and \
|
|
254
|
+
cue_text[e["span"][0]:e["span"][1]] == e["text"]
|
|
255
|
+
if not ok:
|
|
256
|
+
p.append(f"emphasis[{i}] needs start < end, text, its caption cue, the span of the text in that cue, "
|
|
257
|
+
"its word range and a style (pop, color, box or null) -- analyze.py --emphasis writes it")
|
|
258
|
+
break
|
|
237
259
|
for i, r in enumerate(t.get("speech", []) or []):
|
|
238
260
|
if not (isinstance(r, list) and len(r) == 2 and r[1] > r[0]):
|
|
239
261
|
p.append(f"speech[{i}] must be [start, end] with start < end")
|
|
@@ -241,6 +263,10 @@ def validate_timeline(t: Any) -> List[str]:
|
|
|
241
263
|
return p
|
|
242
264
|
|
|
243
265
|
|
|
266
|
+
def _finite(v: Any) -> bool:
|
|
267
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
|
|
268
|
+
|
|
269
|
+
|
|
244
270
|
def sec_to_frames(seconds: float, fps: float) -> int:
|
|
245
271
|
# JavaScript's Math.round (round half up), not Python's round() (half to even): the TypeScript
|
|
246
272
|
# compositions compute the same frame numbers and the two must agree to the frame (94.5 -> 95).
|
|
@@ -254,7 +280,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
|
|
|
254
280
|
and render.py then only reports the measured numbers.
|
|
255
281
|
"""
|
|
256
282
|
fps = float(t["source"]["fps"])
|
|
257
|
-
if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip"):
|
|
283
|
+
if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip", "Emphasis"):
|
|
258
284
|
return max(1, sec_to_frames(float(t["source"]["duration"]), fps))
|
|
259
285
|
if comp in ("Jumpcut", "Highlights"):
|
|
260
286
|
if comp == "Jumpcut":
|
|
@@ -268,7 +294,8 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
|
|
|
268
294
|
|
|
269
295
|
# ---------------------------------------------------------------- Remotion project
|
|
270
296
|
|
|
271
|
-
BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke", "Pip"
|
|
297
|
+
BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke", "Pip",
|
|
298
|
+
"Emphasis")
|
|
272
299
|
|
|
273
300
|
|
|
274
301
|
def remotion_bin(project: Path) -> Path:
|
|
@@ -593,6 +620,7 @@ _OPTION_TYPES: Dict[str, Any] = {
|
|
|
593
620
|
"progressBar": bool, "driver": str, "lowerThirds": list, "sceneTitles": list,
|
|
594
621
|
"title": (str, type(None)), "beatsPerCut": int, "chapterSeconds": (int, float),
|
|
595
622
|
"pipCorner": str, "pipSize": (int, float), "pipShape": str, "pipAudio": bool,
|
|
623
|
+
"emphasisStyle": str, "bubbles": list, "comments": list,
|
|
596
624
|
}
|
|
597
625
|
|
|
598
626
|
|
|
@@ -625,6 +653,21 @@ def validate_options(o: Dict[str, Any]) -> List[str]:
|
|
|
625
653
|
if isinstance(o.get("pipSize"), (int, float)) and not isinstance(o["pipSize"], bool) \
|
|
626
654
|
and not 0.05 <= o["pipSize"] <= 0.6:
|
|
627
655
|
p.append("pipSize must be between 0.05 and 0.6 (a fraction of the frame width)")
|
|
656
|
+
if "emphasisStyle" in o and o["emphasisStyle"] not in ("pop", "color", "box"):
|
|
657
|
+
p.append("emphasisStyle must be pop, color or box")
|
|
658
|
+
for key, extra in (("bubbles", "side"), ("comments", "author")):
|
|
659
|
+
items = o.get(key)
|
|
660
|
+
for i, c in enumerate(items if isinstance(items, list) else []):
|
|
661
|
+
ok = (isinstance(c, dict) and isinstance(c.get("text"), str) and c["text"].strip()
|
|
662
|
+
and _finite(c.get("start")) and _finite(c.get("end")) and c["end"] > c["start"]
|
|
663
|
+
and set(c) <= {"text", "start", "end", extra})
|
|
664
|
+
if ok and key == "bubbles":
|
|
665
|
+
ok = c.get("side", "left") in ("left", "right")
|
|
666
|
+
if ok and key == "comments":
|
|
667
|
+
ok = isinstance(c.get("author", ""), str)
|
|
668
|
+
if not ok:
|
|
669
|
+
p.append(f"{key}[{i}] needs text, start < end (seconds) and an optional {extra}"
|
|
670
|
+
+ (" (left or right)" if key == "bubbles" else ""))
|
|
628
671
|
if any(not isinstance(s, str) for s in (o.get("sceneTitles") or [])):
|
|
629
672
|
p.append("sceneTitles must be a list of strings")
|
|
630
673
|
return p
|
package/scripts/_contract.py
CHANGED
|
@@ -43,6 +43,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
43
43
|
"ffmpeg_skill": ["probe", "scenes", "silence", "join (several inputs)", "sync (--pip)",
|
|
44
44
|
"fit (--conform: VFR -> CFR)", "color (--conform: HDR -> SDR)"],
|
|
45
45
|
"dry_run": True,
|
|
46
|
+
"deterministic": True,
|
|
47
|
+
"idempotency_hint": "content_equivalent",
|
|
46
48
|
},
|
|
47
49
|
"init": {
|
|
48
50
|
"role": "setup",
|
|
@@ -51,6 +53,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
51
53
|
"verification": "refuses a non-empty folder; npm install exit status",
|
|
52
54
|
"ffmpeg_skill": [],
|
|
53
55
|
"dry_run": True,
|
|
56
|
+
"deterministic": True,
|
|
57
|
+
"idempotency_hint": "content_equivalent",
|
|
54
58
|
},
|
|
55
59
|
"still": {
|
|
56
60
|
"role": "execution",
|
|
@@ -59,6 +63,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
59
63
|
"verification": "frames must lie inside the composition; view the PNGs",
|
|
60
64
|
"ffmpeg_skill": ["_contract doctor (CJK font lookup)"],
|
|
61
65
|
"dry_run": True,
|
|
66
|
+
"deterministic": True,
|
|
67
|
+
"idempotency_hint": "bit_exact",
|
|
62
68
|
},
|
|
63
69
|
"render": {
|
|
64
70
|
"role": "execution",
|
|
@@ -67,6 +73,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
67
73
|
"verification": "exact frame count / fps / size / audio against the timeline; non-zero exit on mismatch",
|
|
68
74
|
"ffmpeg_skill": ["probe", "look", "overlay (--overlay; --place with --sparse)", "_contract doctor (CJK font lookup)"],
|
|
69
75
|
"dry_run": True,
|
|
76
|
+
"deterministic": True,
|
|
77
|
+
"idempotency_hint": "bit_exact",
|
|
70
78
|
},
|
|
71
79
|
"deliver": {
|
|
72
80
|
"role": "execution",
|
|
@@ -75,6 +83,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
75
83
|
"verification": "ffmpeg-skill check.py table; non-zero exit on any FAIL row",
|
|
76
84
|
"ffmpeg_skill": ["render --template", "metadata (--chapters)", "check"],
|
|
77
85
|
"dry_run": True,
|
|
86
|
+
"deterministic": True,
|
|
87
|
+
"idempotency_hint": "bit_exact",
|
|
78
88
|
},
|
|
79
89
|
"pipeline": {
|
|
80
90
|
"role": "orchestration",
|
|
@@ -84,6 +94,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
84
94
|
"ffmpeg_skill": ["probe", "scenes", "silence", "fit (--conform)", "color (--conform)", "look",
|
|
85
95
|
"render --template", "check"],
|
|
86
96
|
"dry_run": True,
|
|
97
|
+
"deterministic": True,
|
|
98
|
+
"idempotency_hint": "content_equivalent",
|
|
87
99
|
},
|
|
88
100
|
"doctor": {
|
|
89
101
|
"role": "verification",
|
|
@@ -92,6 +104,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
92
104
|
"verification": "reports only",
|
|
93
105
|
"ffmpeg_skill": ["_contract doctor"],
|
|
94
106
|
"dry_run": False,
|
|
107
|
+
"deterministic": False,
|
|
108
|
+
"idempotency_hint": "environment_dependent",
|
|
95
109
|
},
|
|
96
110
|
}
|
|
97
111
|
|
|
@@ -101,7 +115,7 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
|
|
|
101
115
|
OUTPUTS: Dict[str, Dict[str, Dict[str, str]]] = {
|
|
102
116
|
"analyze": {
|
|
103
117
|
"result": {"commands": "list[str]", "verified": "bool", "summary": "object: duration, fps, size, scenes, "
|
|
104
|
-
"silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, "
|
|
118
|
+
"silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, emphasis, "
|
|
105
119
|
"conformed (list: vfr / hdr)",
|
|
106
120
|
"warnings": "list[str]"},
|
|
107
121
|
"dry_run": {"commands": "list[str]"},
|
|
@@ -145,6 +159,45 @@ OUTPUTS: Dict[str, Dict[str, Dict[str, str]]] = {
|
|
|
145
159
|
"dry_run": {},
|
|
146
160
|
},
|
|
147
161
|
}
|
|
162
|
+
# What `deterministic` / `idempotency_hint` promise, and under which conditions (docs/adr/0001-render-determinism.md).
|
|
163
|
+
# bit_exact: the same inputs give the same bytes. content_equivalent: the same content, but bytes that record where
|
|
164
|
+
# it ran (absolute paths in timeline.json, the npm resolution of --install) may differ. environment_dependent: it
|
|
165
|
+
# reports the machine. Measured, not assumed: tests/test_integration.Determinism renders two compositions twice on
|
|
166
|
+
# every CI machine and checks the stated level.
|
|
167
|
+
IDEMPOTENCY_HINTS = ("bit_exact", "content_equivalent", "environment_dependent")
|
|
168
|
+
DETERMINISM = {
|
|
169
|
+
"scope": "same machine, same inputs (same paths, same options), same Remotion version, same Chromium "
|
|
170
|
+
"(chrome-headless-shell) build and GL backend, same FFmpeg and ffmpeg-skill, same fonts",
|
|
171
|
+
"holds": [
|
|
172
|
+
"every built-in composition renders twice to byte-identical files: per-frame md5 of the video, md5 of the "
|
|
173
|
+
"audio and the file's sha256 match (render.py H.264, --fast, --codec prores, --overlay), in two separate runs",
|
|
174
|
+
"--concurrency does not change the output: 1 tab and all cores give the same bytes",
|
|
175
|
+
"still.py writes byte-identical PNGs",
|
|
176
|
+
"analyze.py run twice on the same file writes a byte-identical timeline.json; on a copy at another path "
|
|
177
|
+
"only source.path differs",
|
|
178
|
+
"pipeline.py writes byte-identical render and deliverable files; it is content_equivalent, not bit_exact, "
|
|
179
|
+
"because its timeline.json records the input's absolute path",
|
|
180
|
+
"init.py (without --install) writes an identical project folder",
|
|
181
|
+
],
|
|
182
|
+
"does_not_hold": [
|
|
183
|
+
"another Chromium build: chrome-headless-shell 153 and 156 differed on every frame (PSNR 43 dB average, "
|
|
184
|
+
"38 dB lowest), so after a Remotion or browser update compare by content, not by hash",
|
|
185
|
+
"another GL backend: Config.setChromiumOpenGlRenderer('swangle') in remotion.config.ts changed every frame "
|
|
186
|
+
"(42 dB average); render.py sets none, and on a machine without a GPU the default, angle, egl, "
|
|
187
|
+
"swiftshader and vulkan gave the same bytes",
|
|
188
|
+
"another font: --font-file with a different font changed the captions (29 dB average); the CJK auto font "
|
|
189
|
+
"is whatever ffmpeg-skill finds installed",
|
|
190
|
+
"another input path: timeline.json records absolute paths, so its bytes differ (its numbers do not)",
|
|
191
|
+
],
|
|
192
|
+
"unverified": [
|
|
193
|
+
"across operating systems: CI checks each of Linux, macOS and Windows against itself only",
|
|
194
|
+
"on a machine with a GPU, where the GL backends may no longer agree",
|
|
195
|
+
"another FFmpeg or x264 build (the encoder Remotion bundles is pinned with Remotion)",
|
|
196
|
+
"across two machines with the same OS and toolchain",
|
|
197
|
+
"analyze.py --conform and several-input joins (their re-encoded copies were not compared); init.py --install",
|
|
198
|
+
],
|
|
199
|
+
"not_reproducible_compositions": [],
|
|
200
|
+
}
|
|
148
201
|
SHARED_OUTPUT = {"status": "completed|failed", "dry_run": "bool", "output": "str|null (main artifact)"}
|
|
149
202
|
FAILURE_OUTPUT = {"status": "failed", "error": "str", "kind": "input|missing_tool|timeout|failed", "dry_run": "bool"}
|
|
150
203
|
|
|
@@ -235,6 +288,8 @@ def tool_spec(name: str) -> Dict[str, Any]:
|
|
|
235
288
|
"verification": meta["verification"],
|
|
236
289
|
"ffmpeg_skill": meta["ffmpeg_skill"],
|
|
237
290
|
"dry_run": meta["dry_run"],
|
|
291
|
+
"deterministic": meta["deterministic"],
|
|
292
|
+
"idempotency_hint": meta["idempotency_hint"],
|
|
238
293
|
"inputSchema": input_schema(parser),
|
|
239
294
|
"flags": flag_for(parser),
|
|
240
295
|
"output": OUTPUTS[name],
|
|
@@ -273,6 +328,7 @@ def build() -> Dict[str, Any]:
|
|
|
273
328
|
"roles": ROLES,
|
|
274
329
|
"output_shared": SHARED_OUTPUT,
|
|
275
330
|
"output_failure": FAILURE_OUTPUT,
|
|
331
|
+
"determinism": {"hints": list(IDEMPOTENCY_HINTS), **DETERMINISM},
|
|
276
332
|
"conventions": {
|
|
277
333
|
"output": "one JSON object on stdout with --json; human lines on stderr",
|
|
278
334
|
"errors": {"input": 2, "missing_tool": 3, "timeout": 4, "failed": 1},
|
package/scripts/_docs.py
CHANGED
|
@@ -37,6 +37,7 @@ def render() -> str:
|
|
|
37
37
|
f"- Verifies: {t['verification']}",
|
|
38
38
|
f"- ffmpeg-skill: {', '.join(t['ffmpeg_skill']) or '—'}",
|
|
39
39
|
f"- `--dry-run`: {'plans without writing' if t['dry_run'] else 'not applicable (reports only)'}",
|
|
40
|
+
f"- Repeatability: `{t['idempotency_hint']}` (deterministic: {'yes' if t['deterministic'] else 'no'})",
|
|
40
41
|
"", "| Argument | Type | Default | Meaning |", "|---|---|---|---|"]
|
|
41
42
|
for name, p in s["properties"].items():
|
|
42
43
|
if name in ("dry_run", "overwrite", "timeout"):
|
|
@@ -59,6 +60,12 @@ def render() -> str:
|
|
|
59
60
|
lines.append(f"{title} (besides `status`, `dry_run`, `output`): " +
|
|
60
61
|
", ".join(f"`{k}` ({v})" for k, v in keys.items()))
|
|
61
62
|
lines.append("")
|
|
63
|
+
d = c["determinism"]
|
|
64
|
+
lines += ["## Repeatability", "",
|
|
65
|
+
"`idempotency_hint` per tool: " + ", ".join(f"`{h}`" for h in d["hints"]) + ". Scope: " + d["scope"] + ".",
|
|
66
|
+
"", "Holds:", ""] + [f"- {x}" for x in d["holds"]] + ["", "Does not hold:", ""] + \
|
|
67
|
+
[f"- {x}" for x in d["does_not_hold"]] + ["", "Unverified:", ""] + [f"- {x}" for x in d["unverified"]] + \
|
|
68
|
+
["", "Not reproducible: " + (", ".join(d["not_reproducible_compositions"]) or "none found") + ".", ""]
|
|
62
69
|
lines += ["## Failures", "",
|
|
63
70
|
"Every failure is one JSON object: " + ", ".join(f"`{k}` ({v})" for k, v in c["output_failure"].items()) + ".", ""]
|
|
64
71
|
return "\n".join(lines)
|
package/scripts/analyze.py
CHANGED
|
@@ -19,6 +19,7 @@ Examples:
|
|
|
19
19
|
python3 analyze.py talk.mp4 --threshold -42 --min-silence 0.8 # quiet room
|
|
20
20
|
python3 analyze.py intro.mp4 talk.mov outro.mp4 --captions all.srt # joined, then measured
|
|
21
21
|
python3 analyze.py talk.mp4 --words talk.transcript.json # captions from a transcription-skill transcript
|
|
22
|
+
python3 analyze.py talk.mp4 --words talk.transcript.json --emphasis words.json # Emphasis composition
|
|
22
23
|
python3 analyze.py phone_hdr.mov --conform # VFR / HDR: measure and draw on a CFR SDR copy
|
|
23
24
|
"""
|
|
24
25
|
import argparse
|
|
@@ -34,8 +35,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
34
35
|
from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
|
|
35
36
|
emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
|
|
36
37
|
require_ffmpeg_skill, shell_join, version)
|
|
37
|
-
from _captions import (CaptionError, cues_from_words, parse_chapters, read_captions,
|
|
38
|
-
youtube_chapter_warnings)
|
|
38
|
+
from _captions import (CaptionError, cues_from_words, parse_chapters, read_captions, read_emphasis,
|
|
39
|
+
read_word_timings, resolve_emphasis, youtube_chapter_warnings)
|
|
39
40
|
|
|
40
41
|
# seconds a transcript's duration may differ from the measured source (transcription-skill's own END_TOLERANCE)
|
|
41
42
|
TRANSCRIPT_DURATION_TOLERANCE = 0.5
|
|
@@ -63,6 +64,13 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
63
64
|
p.add_argument("--words", help="word timings for the Karaoke and Captioned compositions: a transcription-skill "
|
|
64
65
|
"transcript (schema transcription-skill/transcript/0.1, validated strictly) or whisper "
|
|
65
66
|
"JSON with word timestamps; without --captions the cues are grouped from these words")
|
|
67
|
+
p.add_argument("--emphasis", metavar="FILE",
|
|
68
|
+
help="words to emphasise in the Emphasis composition (pop, colour or box at the time each is "
|
|
69
|
+
"spoken): a JSON list of words or {text, at?, style?}. Each must be a whole, timed word of "
|
|
70
|
+
"a caption cue (of the cue showing at `at`), or it is refused; needs --words")
|
|
71
|
+
p.add_argument("--emphasis-auto", metavar="KINDS",
|
|
72
|
+
help="with --words: also emphasise the captions' own numbers and/or names "
|
|
73
|
+
"(comma-separated: numbers, names = capitalised mid-sentence or katakana words)")
|
|
66
74
|
p.add_argument("--chapters", metavar="FILE|source",
|
|
67
75
|
help="chapter list, one `TIME TITLE` per line (YouTube's format, the same file ffmpeg-skill "
|
|
68
76
|
"metadata.py --chapters writes into the container), or `source` for the chapters already "
|
|
@@ -309,6 +317,26 @@ def main() -> None:
|
|
|
309
317
|
if not captions:
|
|
310
318
|
captions = timed["cues"] if transcript else cues_from_words(words)
|
|
311
319
|
|
|
320
|
+
emphasis: List[Dict[str, Any]] = []
|
|
321
|
+
emphasis_warnings: List[str] = []
|
|
322
|
+
if a.emphasis is not None or a.emphasis_auto is not None:
|
|
323
|
+
if not words:
|
|
324
|
+
die("--emphasis / --emphasis-auto need --words: an emphasised word shows at the time the speech "
|
|
325
|
+
"engine measured, never a guessed one", "input")
|
|
326
|
+
entries: List[Dict[str, Any]] = []
|
|
327
|
+
try:
|
|
328
|
+
if a.emphasis:
|
|
329
|
+
epath = Path(a.emphasis).expanduser()
|
|
330
|
+
if not epath.is_file():
|
|
331
|
+
die(f"emphasis file not found: {epath}", "input")
|
|
332
|
+
entries = read_emphasis(epath.read_text(encoding="utf-8-sig"))
|
|
333
|
+
auto = [k.strip() for k in (a.emphasis_auto or "").split(",") if k.strip()]
|
|
334
|
+
if a.emphasis_auto is not None and not auto:
|
|
335
|
+
die("--emphasis-auto needs at least one kind: numbers, names", "input")
|
|
336
|
+
emphasis, emphasis_warnings = resolve_emphasis(captions, words, entries, auto)
|
|
337
|
+
except (CaptionError, ValueError) as e:
|
|
338
|
+
die(f"--emphasis: {e}", "input")
|
|
339
|
+
|
|
312
340
|
join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
|
|
313
341
|
"--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
|
|
314
342
|
plan = ([shell_join(ffskill_cmd("join", join_args))] if len(inputs) > 1 else []) + \
|
|
@@ -501,11 +529,13 @@ def main() -> None:
|
|
|
501
529
|
"clips": clips,
|
|
502
530
|
"captions": captions,
|
|
503
531
|
"words": words,
|
|
532
|
+
"emphasis": emphasis,
|
|
504
533
|
"chapters": chapters,
|
|
505
534
|
"pip": pip,
|
|
506
535
|
# Provenance of a conformed source (--conform): the original, each ffmpeg-skill step, the measured copy.
|
|
507
536
|
"conform": conform,
|
|
508
|
-
"warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings
|
|
537
|
+
"warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings
|
|
538
|
+
+ emphasis_warnings,
|
|
509
539
|
}
|
|
510
540
|
if pip and pip["measured"] and (pip["confidence"] or 0) < 0.3:
|
|
511
541
|
timeline["warnings"].append(f"pip: the measured offset ({pip['offset']:g} s) has low confidence "
|
|
@@ -531,7 +561,7 @@ def main() -> None:
|
|
|
531
561
|
"captions": len(captions), "chapters": len(chapters),
|
|
532
562
|
"pip_offset": pip["offset"] if pip else None, "beats": bool(beats and beats.get("usable")),
|
|
533
563
|
"tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
|
|
534
|
-
"clips": len(clips) or 1, "words": len(words),
|
|
564
|
+
"clips": len(clips) or 1, "words": len(words), "emphasis": len(emphasis),
|
|
535
565
|
"conformed": (conform or {}).get("reasons", [])},
|
|
536
566
|
"warnings": timeline["warnings"]},
|
|
537
567
|
f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
|
package/scripts/render.py
CHANGED
|
@@ -212,7 +212,7 @@ def main() -> None:
|
|
|
212
212
|
if a.overlay:
|
|
213
213
|
if a.comp in ("Jumpcut", "Highlights", "BeatMontage", "Pip"):
|
|
214
214
|
die(f"--overlay cannot do {a.comp}: it changes the picture itself (overlay works for "
|
|
215
|
-
"Captioned, PeakPulse, Titled, Karaoke)", "input")
|
|
215
|
+
"Captioned, PeakPulse, Titled, Karaoke, Emphasis)", "input")
|
|
216
216
|
if a.aspect not in (None, "source") or a.width is not None or a.fit not in (None, "contain"):
|
|
217
217
|
die("--overlay draws on the source's own frame: drop --aspect / --width / --fit", "input")
|
|
218
218
|
if a.fast or a.codec != "h264" or frames:
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"typecheck": "tsc --noEmit"
|
|
9
9
|
},
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@remotion/cli": "4.0.
|
|
12
|
-
"remotion": "4.0.
|
|
11
|
+
"@remotion/cli": "4.0.540",
|
|
12
|
+
"remotion": "4.0.540",
|
|
13
13
|
"react": "19.3.1",
|
|
14
14
|
"react-dom": "19.3.1"
|
|
15
15
|
},
|
|
16
16
|
"devDependencies": {
|
|
17
17
|
"@types/react": "^19.0.0",
|
|
18
|
-
"typescript": "^
|
|
18
|
+
"typescript": "^7.0.2"
|
|
19
19
|
}
|
|
20
20
|
}
|
|
@@ -8,6 +8,7 @@ import { Highlights } from "./compositions/Highlights";
|
|
|
8
8
|
import { BeatMontage } from "./compositions/BeatMontage";
|
|
9
9
|
import { Karaoke } from "./compositions/Karaoke";
|
|
10
10
|
import { Pip } from "./compositions/Pip";
|
|
11
|
+
import { Emphasis } from "./compositions/Emphasis";
|
|
11
12
|
import { SAMPLE_TIMELINE, fullLengthFrames, highlightFrames, jumpcutFrames, outputFrame, type Props, type Timeline } from "./timeline";
|
|
12
13
|
|
|
13
14
|
// Length and fps come from the measured timeline, never from constants; the frame is the
|
|
@@ -32,5 +33,6 @@ export const RemotionRoot: React.FC = () => (
|
|
|
32
33
|
<Composition id="BeatMontage" component={BeatMontage} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
33
34
|
<Composition id="Karaoke" component={Karaoke} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
34
35
|
<Composition id="Pip" component={Pip} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
36
|
+
<Composition id="Emphasis" component={Emphasis} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
35
37
|
</>
|
|
36
38
|
);
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import { AbsoluteFill, Sequence, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
|
|
3
|
+
import { SourceVideo } from "../lib/SourceVideo";
|
|
4
|
+
import { useStagedFont } from "../lib/useStagedFont";
|
|
5
|
+
import { captionMarginPx } from "./Captioned";
|
|
6
|
+
import {
|
|
7
|
+
Props,
|
|
8
|
+
fontStack,
|
|
9
|
+
outputFrame,
|
|
10
|
+
resolveOptions,
|
|
11
|
+
secToFrames,
|
|
12
|
+
type Bubble,
|
|
13
|
+
type Caption,
|
|
14
|
+
type CommentCard,
|
|
15
|
+
type Emphasis as EmphasisWord,
|
|
16
|
+
type Options,
|
|
17
|
+
} from "../timeline";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Emphasis: YouTube-style captions. Each caption cue shows as written; the words analyze.py --emphasis
|
|
21
|
+
* placed on it pop, take the accent colour or get an accent box from the time the speech engine measured
|
|
22
|
+
* them to the end of the cue. Speech bubbles and comment-style cards (the user's text, options `bubbles`
|
|
23
|
+
* and `comments`) show at their own times. Nothing here chooses or rewrites a word.
|
|
24
|
+
*/
|
|
25
|
+
export const Emphasis: React.FC<Props> = (props) => {
|
|
26
|
+
const { timeline, options, font, overlay } = props;
|
|
27
|
+
useStagedFont(font);
|
|
28
|
+
const o = resolveOptions(options);
|
|
29
|
+
const family = fontStack(o, font);
|
|
30
|
+
const { fps } = useVideoConfig();
|
|
31
|
+
const emphasis = timeline.emphasis ?? [];
|
|
32
|
+
// Cards showing at once stack downwards: each takes the lowest slot no earlier overlapping card holds.
|
|
33
|
+
const slots: number[] = [];
|
|
34
|
+
o.comments.forEach((c, i) => {
|
|
35
|
+
const busy = new Set(o.comments.slice(0, i).flatMap((p, j) => (p.start < c.end && p.end > c.start ? [slots[j]] : [])));
|
|
36
|
+
let s = 0;
|
|
37
|
+
while (busy.has(s)) s += 1;
|
|
38
|
+
slots.push(s);
|
|
39
|
+
});
|
|
40
|
+
return (
|
|
41
|
+
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
42
|
+
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
|
|
43
|
+
{timeline.captions.map((c, i) => {
|
|
44
|
+
const from = secToFrames(c.start, fps);
|
|
45
|
+
const dur = Math.max(1, secToFrames(c.end, fps) - from);
|
|
46
|
+
return (
|
|
47
|
+
<Sequence key={`c${i}`} from={from} durationInFrames={dur} name={`cue ${i + 1}`} layout="none">
|
|
48
|
+
<EmphasisCue
|
|
49
|
+
cue={c}
|
|
50
|
+
from={from}
|
|
51
|
+
emphasis={emphasis.filter((e) => e.cue === i)}
|
|
52
|
+
len={dur}
|
|
53
|
+
o={o}
|
|
54
|
+
fontFamily={family}
|
|
55
|
+
/>
|
|
56
|
+
</Sequence>
|
|
57
|
+
);
|
|
58
|
+
})}
|
|
59
|
+
{o.bubbles.map((b, i) => {
|
|
60
|
+
const from = secToFrames(b.start, fps);
|
|
61
|
+
const dur = Math.max(1, secToFrames(b.end, fps) - from);
|
|
62
|
+
return (
|
|
63
|
+
<Sequence key={`b${i}`} from={from} durationInFrames={dur} name={`bubble ${i + 1}`} layout="none">
|
|
64
|
+
<SpeechBubble bubble={b} len={dur} o={o} fontFamily={family} />
|
|
65
|
+
</Sequence>
|
|
66
|
+
);
|
|
67
|
+
})}
|
|
68
|
+
{o.comments.map((c, i) => {
|
|
69
|
+
const from = secToFrames(c.start, fps);
|
|
70
|
+
const dur = Math.max(1, secToFrames(c.end, fps) - from);
|
|
71
|
+
const slot = slots[i];
|
|
72
|
+
return (
|
|
73
|
+
<Sequence key={`m${i}`} from={from} durationInFrames={dur} name={`comment ${i + 1}`} layout="none">
|
|
74
|
+
<Comment card={c} slot={slot} len={dur} o={o} fontFamily={family} />
|
|
75
|
+
</Sequence>
|
|
76
|
+
);
|
|
77
|
+
})}
|
|
78
|
+
</AbsoluteFill>
|
|
79
|
+
);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const langOf = (text: string): string | undefined =>
|
|
83
|
+
/[-ヿ㐀-鿿]/.test(text) ? "ja" : /[가-]/.test(text) ? "ko" : undefined;
|
|
84
|
+
|
|
85
|
+
const useInOut = (len: number) => {
|
|
86
|
+
const frame = useCurrentFrame();
|
|
87
|
+
const { fps } = useVideoConfig();
|
|
88
|
+
const enter = spring({ frame, fps, config: { damping: 14, stiffness: 180, mass: 0.6 } });
|
|
89
|
+
const fade = Math.min(6, Math.floor(len / 3));
|
|
90
|
+
const exit = fade > 0 ? interpolate(frame, [len - fade, len], [1, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }) : 1;
|
|
91
|
+
return { frame, enter, exit };
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const EmphasisCue: React.FC<{
|
|
95
|
+
cue: Caption;
|
|
96
|
+
from: number;
|
|
97
|
+
emphasis: EmphasisWord[];
|
|
98
|
+
len: number;
|
|
99
|
+
o: Options;
|
|
100
|
+
fontFamily: string;
|
|
101
|
+
}> = ({ cue, from, emphasis, len, o, fontFamily }) => {
|
|
102
|
+
const { fps, width, height } = useVideoConfig();
|
|
103
|
+
const { frame, enter, exit } = useInOut(len);
|
|
104
|
+
const size = Math.round(Math.min(width, height) * o.captionSize * 1.1);
|
|
105
|
+
// Source time of this frame, nudged by a microsecond as in Karaoke so a word starting exactly on a
|
|
106
|
+
// frame shows on that frame.
|
|
107
|
+
const now = (from + frame) / fps + 1e-6;
|
|
108
|
+
// The cue's own text, cut at the emphasised spans (code points, as analyze.py counted them).
|
|
109
|
+
const chars = Array.from(cue.text);
|
|
110
|
+
const parts: React.ReactNode[] = [];
|
|
111
|
+
let at = 0;
|
|
112
|
+
for (const [k, e] of [...emphasis].sort((x, y) => x.span[0] - y.span[0]).entries()) {
|
|
113
|
+
if (e.span[0] < at) continue;
|
|
114
|
+
parts.push(chars.slice(at, e.span[0]).join(""));
|
|
115
|
+
parts.push(
|
|
116
|
+
<Emphasised key={k} text={chars.slice(e.span[0], e.span[1]).join("")} style={e.style ?? o.emphasisStyle} at={e.start} now={now} o={o} />,
|
|
117
|
+
);
|
|
118
|
+
at = e.span[1];
|
|
119
|
+
}
|
|
120
|
+
parts.push(chars.slice(at).join(""));
|
|
121
|
+
return (
|
|
122
|
+
<AbsoluteFill style={{ justifyContent: "flex-end", alignItems: "center", paddingBottom: captionMarginPx(o, width, height) }}>
|
|
123
|
+
<div
|
|
124
|
+
lang={langOf(cue.text)}
|
|
125
|
+
style={{
|
|
126
|
+
maxWidth: width * 0.88,
|
|
127
|
+
padding: `${size * 0.25}px ${size * 0.55}px`,
|
|
128
|
+
borderRadius: size * 0.3,
|
|
129
|
+
background: "rgba(0,0,0,0.6)",
|
|
130
|
+
color: o.textColor,
|
|
131
|
+
fontFamily,
|
|
132
|
+
fontWeight: 800,
|
|
133
|
+
fontSize: size,
|
|
134
|
+
lineHeight: 1.45,
|
|
135
|
+
textAlign: "center",
|
|
136
|
+
whiteSpace: "pre-wrap",
|
|
137
|
+
textWrap: "balance",
|
|
138
|
+
opacity: Math.min(enter, exit),
|
|
139
|
+
transform: `translateY(${(1 - enter) * size * 0.5}px)`,
|
|
140
|
+
}}
|
|
141
|
+
>
|
|
142
|
+
{parts}
|
|
143
|
+
</div>
|
|
144
|
+
</AbsoluteFill>
|
|
145
|
+
);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** One emphasised word: plain until it is spoken, then popped, coloured or boxed until the cue ends. */
|
|
149
|
+
const Emphasised: React.FC<{ text: string; style: "pop" | "color" | "box"; at: number; now: number; o: Options }> = ({
|
|
150
|
+
text,
|
|
151
|
+
style,
|
|
152
|
+
at,
|
|
153
|
+
now,
|
|
154
|
+
o,
|
|
155
|
+
}) => {
|
|
156
|
+
const on = now >= at;
|
|
157
|
+
const t = now - at;
|
|
158
|
+
const scale = !on
|
|
159
|
+
? 1
|
|
160
|
+
: style === "pop"
|
|
161
|
+
? interpolate(t, [0, 0.08, 0.25], [1, 1.35, 1.15], { extrapolateRight: "clamp" })
|
|
162
|
+
: interpolate(t, [0, 0.06, 0.18], [1, 1.12, 1], { extrapolateRight: "clamp" });
|
|
163
|
+
const boxed = on && style === "box";
|
|
164
|
+
return (
|
|
165
|
+
<span
|
|
166
|
+
style={{
|
|
167
|
+
display: "inline-block",
|
|
168
|
+
transform: `scale(${scale})`,
|
|
169
|
+
transformOrigin: "50% 70%",
|
|
170
|
+
color: on ? (boxed ? "#111111" : o.accent) : o.textColor,
|
|
171
|
+
background: boxed ? o.accent : "transparent",
|
|
172
|
+
borderRadius: "0.18em",
|
|
173
|
+
padding: "0 0.12em",
|
|
174
|
+
margin: "0 -0.12em",
|
|
175
|
+
textShadow: on && style === "pop" ? "0 0.06em 0 rgba(0,0,0,0.65)" : "none",
|
|
176
|
+
}}
|
|
177
|
+
>
|
|
178
|
+
{text}
|
|
179
|
+
</span>
|
|
180
|
+
);
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
/** A speech bubble in the upper part of the frame, its tail pointing down-left or down-right. */
|
|
184
|
+
const SpeechBubble: React.FC<{ bubble: Bubble; len: number; o: Options; fontFamily: string }> = ({ bubble, len, o, fontFamily }) => {
|
|
185
|
+
const { width, height } = useVideoConfig();
|
|
186
|
+
const { enter, exit } = useInOut(len);
|
|
187
|
+
const size = Math.round(Math.min(width, height) * o.captionSize);
|
|
188
|
+
const right = bubble.side === "right";
|
|
189
|
+
const tail = size * 0.6;
|
|
190
|
+
return (
|
|
191
|
+
<AbsoluteFill
|
|
192
|
+
style={{ justifyContent: "flex-start", alignItems: right ? "flex-end" : "flex-start", padding: `${height * 0.1}px ${width * 0.08}px` }}
|
|
193
|
+
>
|
|
194
|
+
<div
|
|
195
|
+
lang={langOf(bubble.text)}
|
|
196
|
+
style={{
|
|
197
|
+
position: "relative",
|
|
198
|
+
maxWidth: width * 0.5,
|
|
199
|
+
padding: `${size * 0.45}px ${size * 0.7}px`,
|
|
200
|
+
borderRadius: size * 0.9,
|
|
201
|
+
background: "#ffffff",
|
|
202
|
+
color: "#111111",
|
|
203
|
+
fontFamily,
|
|
204
|
+
fontWeight: 800,
|
|
205
|
+
fontSize: size,
|
|
206
|
+
lineHeight: 1.3,
|
|
207
|
+
whiteSpace: "pre-wrap",
|
|
208
|
+
boxShadow: `0 ${size * 0.12}px ${size * 0.4}px rgba(0,0,0,0.35)`,
|
|
209
|
+
opacity: exit,
|
|
210
|
+
transform: `scale(${enter})`,
|
|
211
|
+
transformOrigin: right ? "85% 100%" : "15% 100%",
|
|
212
|
+
}}
|
|
213
|
+
>
|
|
214
|
+
{bubble.text}
|
|
215
|
+
<div
|
|
216
|
+
style={{
|
|
217
|
+
position: "absolute",
|
|
218
|
+
bottom: -tail * 0.8,
|
|
219
|
+
[right ? "right" : "left"]: size * 0.9,
|
|
220
|
+
width: 0,
|
|
221
|
+
height: 0,
|
|
222
|
+
borderLeft: `${tail * 0.5}px solid transparent`,
|
|
223
|
+
borderRight: `${tail * 0.5}px solid transparent`,
|
|
224
|
+
borderTop: `${tail}px solid #ffffff`,
|
|
225
|
+
transform: `skewX(${right ? 25 : -25}deg)`,
|
|
226
|
+
}}
|
|
227
|
+
/>
|
|
228
|
+
</div>
|
|
229
|
+
</AbsoluteFill>
|
|
230
|
+
);
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
/** A comment-style card sliding in at the top left (a live-chat / comment look), cards at once stacked. */
|
|
234
|
+
const Comment: React.FC<{ card: CommentCard; slot: number; len: number; o: Options; fontFamily: string }> = ({
|
|
235
|
+
card,
|
|
236
|
+
slot,
|
|
237
|
+
len,
|
|
238
|
+
o,
|
|
239
|
+
fontFamily,
|
|
240
|
+
}) => {
|
|
241
|
+
const { width, height } = useVideoConfig();
|
|
242
|
+
const { enter, exit } = useInOut(len);
|
|
243
|
+
const size = Math.round(Math.min(width, height) * o.captionSize * 0.7);
|
|
244
|
+
const avatar = size * 2;
|
|
245
|
+
return (
|
|
246
|
+
<AbsoluteFill style={{ justifyContent: "flex-start", alignItems: "flex-start", padding: `${height * 0.06}px ${width * 0.04}px` }}>
|
|
247
|
+
<div
|
|
248
|
+
lang={langOf(card.text)}
|
|
249
|
+
style={{
|
|
250
|
+
marginTop: slot * size * 4.2,
|
|
251
|
+
display: "flex",
|
|
252
|
+
alignItems: "center",
|
|
253
|
+
gap: size * 0.6,
|
|
254
|
+
maxWidth: width * 0.55,
|
|
255
|
+
padding: `${size * 0.5}px ${size * 0.8}px ${size * 0.5}px ${size * 0.5}px`,
|
|
256
|
+
borderRadius: size * 0.6,
|
|
257
|
+
background: "rgba(255,255,255,0.94)",
|
|
258
|
+
color: "#111111",
|
|
259
|
+
fontFamily,
|
|
260
|
+
fontSize: size,
|
|
261
|
+
lineHeight: 1.3,
|
|
262
|
+
boxShadow: `0 ${size * 0.1}px ${size * 0.4}px rgba(0,0,0,0.3)`,
|
|
263
|
+
opacity: Math.min(enter, exit),
|
|
264
|
+
transform: `translateX(${(1 - enter) * -width * 0.1}px)`,
|
|
265
|
+
}}
|
|
266
|
+
>
|
|
267
|
+
<div
|
|
268
|
+
style={{
|
|
269
|
+
flex: "none",
|
|
270
|
+
width: avatar,
|
|
271
|
+
height: avatar,
|
|
272
|
+
borderRadius: "50%",
|
|
273
|
+
background: o.accent,
|
|
274
|
+
color: "#111111",
|
|
275
|
+
fontWeight: 800,
|
|
276
|
+
fontSize: size * 1.1,
|
|
277
|
+
display: "flex",
|
|
278
|
+
alignItems: "center",
|
|
279
|
+
justifyContent: "center",
|
|
280
|
+
}}
|
|
281
|
+
>
|
|
282
|
+
{card.author ? Array.from(card.author.trim())[0] ?? "" : ""}
|
|
283
|
+
</div>
|
|
284
|
+
<div style={{ whiteSpace: "pre-wrap" }}>
|
|
285
|
+
{card.author ? <div style={{ fontWeight: 800, fontSize: size * 0.85, opacity: 0.7 }}>{card.author}</div> : null}
|
|
286
|
+
<div style={{ fontWeight: 600 }}>{card.text}</div>
|
|
287
|
+
</div>
|
|
288
|
+
</div>
|
|
289
|
+
</AbsoluteFill>
|
|
290
|
+
);
|
|
291
|
+
};
|
|
@@ -19,6 +19,23 @@ export type Source = {
|
|
|
19
19
|
|
|
20
20
|
export type Caption = { start: number; end: number; text: string };
|
|
21
21
|
export type Chapter = { start: number; end: number; title: string };
|
|
22
|
+
/** An emphasised word (analyze.py --emphasis / --emphasis-auto): the slice `span` ([start, end) in code
|
|
23
|
+
* points) of caption cue `cue`'s own text, timed by the words `words` = [first, last] (indices into
|
|
24
|
+
* timeline.words), shown from the time the engine measured. style null = the emphasisStyle option. */
|
|
25
|
+
export type EmphasisStyle = "pop" | "color" | "box";
|
|
26
|
+
export type Emphasis = {
|
|
27
|
+
start: number;
|
|
28
|
+
end: number;
|
|
29
|
+
text: string;
|
|
30
|
+
style: EmphasisStyle | null;
|
|
31
|
+
cue: number;
|
|
32
|
+
span: [number, number];
|
|
33
|
+
words: [number, number];
|
|
34
|
+
by: "caller" | "numbers" | "names";
|
|
35
|
+
};
|
|
36
|
+
/** A speech bubble or a comment-style card: the user's text, timing in source seconds. */
|
|
37
|
+
export type Bubble = { text: string; start: number; end: number; side?: "left" | "right" };
|
|
38
|
+
export type CommentCard = { text: string; start: number; end: number; author?: string };
|
|
22
39
|
/** A second recording shown picture-in-picture (analyze.py --pip). offset: seconds after the source's
|
|
23
40
|
* start at which the camera's first frame belongs (measured from both audio tracks, or given). */
|
|
24
41
|
export type Pip = {
|
|
@@ -67,6 +84,8 @@ export type Timeline = {
|
|
|
67
84
|
words?: Caption[];
|
|
68
85
|
/** Chapters from the user's list or the source's own markers (analyze.py --chapters); titles as written. */
|
|
69
86
|
chapters?: Chapter[];
|
|
87
|
+
/** Emphasised caption words (analyze.py --emphasis); drawn by the Emphasis composition. */
|
|
88
|
+
emphasis?: Emphasis[];
|
|
70
89
|
pip?: Pip | null;
|
|
71
90
|
/** Set when analyze.py --conform measured a conformed copy instead of the original (null otherwise). */
|
|
72
91
|
conform?: Conform | null;
|
|
@@ -108,6 +127,12 @@ export type Options = {
|
|
|
108
127
|
pipShape: "rounded" | "circle";
|
|
109
128
|
/** Pip: play the camera's own audio too (off: the source's audio only). */
|
|
110
129
|
pipAudio: boolean;
|
|
130
|
+
/** Emphasis: how an emphasised word shows when it is spoken (an entry's own style wins). */
|
|
131
|
+
emphasisStyle: EmphasisStyle;
|
|
132
|
+
/** Emphasis: speech bubbles (text from the user, never invented). */
|
|
133
|
+
bubbles: Bubble[];
|
|
134
|
+
/** Emphasis: comment-style cards (text and author from the user). */
|
|
135
|
+
comments: CommentCard[];
|
|
111
136
|
};
|
|
112
137
|
|
|
113
138
|
export const DEFAULT_OPTIONS: Options = {
|
|
@@ -129,6 +154,9 @@ export const DEFAULT_OPTIONS: Options = {
|
|
|
129
154
|
pipSize: 0.28,
|
|
130
155
|
pipShape: "rounded",
|
|
131
156
|
pipAudio: false,
|
|
157
|
+
emphasisStyle: "pop",
|
|
158
|
+
bubbles: [],
|
|
159
|
+
comments: [],
|
|
132
160
|
};
|
|
133
161
|
|
|
134
162
|
/** Where the camera plays on the source timeline: [from, durationInFrames, trimBefore] in frames. */
|