remotion-ffmpeg-skill 0.3.0 → 0.4.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 +4 -3
- package/SKILL.md +3 -2
- package/mcp/server.py +7 -1
- package/package.json +1 -1
- package/references/gotchas.md +30 -0
- package/references/scripts.md +164 -0
- package/references/timeline.md +4 -1
- package/scripts/_captions.py +62 -0
- package/scripts/_common.py +8 -4
- package/scripts/_contract.py +3 -1
- package/scripts/_docs.py +72 -0
- package/scripts/analyze.py +17 -2
- package/scripts/render.py +14 -3
- package/templates/remotion-project/src/Root.tsx +2 -0
- package/templates/remotion-project/src/compositions/Karaoke.tsx +104 -0
- package/templates/remotion-project/src/timeline.ts +2 -0
package/README.md
CHANGED
|
@@ -76,6 +76,7 @@ Tool names and input schemas come from the machine-readable contract (`npx remot
|
|
|
76
76
|
| `Titled` | source duration | your lower thirds + a title card at each measured scene change |
|
|
77
77
|
| `Highlights` | sum of ranked highlights | ffmpeg-skill's audio-energy highlights back to back, counter, title |
|
|
78
78
|
| `BeatMontage` | source duration | audio unbroken, picture cuts on the measured beat grid |
|
|
79
|
+
| `Karaoke` | source duration | words light up at the times a local speech engine measured |
|
|
79
80
|
|
|
80
81
|
**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.
|
|
81
82
|
|
|
@@ -106,12 +107,12 @@ This skill is MIT. **Remotion itself has its own licence**: free for individuals
|
|
|
106
107
|
|
|
107
108
|
## Speed
|
|
108
109
|
|
|
109
|
-
Remotion renders in a headless browser. Measured on a 2-core Linux machine: a 30 s 1080p30 render takes about
|
|
110
|
+
Remotion renders in a headless browser. Measured on a 2-core Linux machine: a 30 s 1080p30 render takes about 80 s (≈ 2.6× the clip length) with render.py's default of all CPU cores — Remotion's own default (half the cores) took 170 s. More cores scale it further. Check with `still.py` and `--fast` before a full render of long footage.
|
|
110
111
|
|
|
111
112
|
## Agent evals
|
|
112
113
|
|
|
113
|
-
|
|
114
|
+
Plain requests ("captions for YouTube", a Japanese Reels jump cut, "cut to the beat", a lower third without a name, a plain trim that is *not* this skill's job, a square highlight reel), run by an agent that only has the skill files, graded on what it leaves behind — plus a transparent layer for an editor, joining clips with titles, and karaoke from word timings: **9 / 9** ([run 1](evals/results/2026-10-24.md), [run 2](evals/results/2026-10-24b.md), [how to run](evals/README.md)).
|
|
114
115
|
|
|
115
116
|
## Status
|
|
116
117
|
|
|
117
|
-
0.
|
|
118
|
+
0.4.0. CI renders every composition on Linux, macOS and Windows (Node 22, Remotion 4.0.538, ffmpeg-skill main).
|
package/SKILL.md
CHANGED
|
@@ -21,7 +21,7 @@ Shared flags (every script): `--json` (one JSON object on stdout; prefer it), `-
|
|
|
21
21
|
- **Fonts:** Japanese / Chinese / Korean captions get the CJK font ffmpeg-skill finds on the machine automatically (staged into the project, so no tofu); `--font-file F.ttf` uses a specific font; the report line `font:` says which was used, or that none was found.
|
|
22
22
|
- **Editing-app layer:** `--overlay --keep-graphics` (Captioned / PeakPulse, source shape) draws the graphics alone as a transparent ProRes 4444 `.graphics.mov` and composites it over the untouched source with ffmpeg-skill `overlay.py`; hand the `.mov` to someone finishing in Premiere / Resolve / Final Cut. It is not faster than a normal render.
|
|
23
23
|
5. **Deliver.** `deliver.py OUT.mp4 --platform youtube|reels|tiktok|shorts|x|...` runs ffmpeg-skill's delivery template and its `check.py` table. Format rows are safe to fix; judgement rows (duration, aspect) change content — ask. Mention WARNs, don't chase them. No destination named: skip this step and say so.
|
|
24
|
-
6. **Look.** Not finished until the reply names the contact sheet render.py wrote (`Look: PATH`) and says what it shows. Mechanical (check and report): text is where it was asked, cues appear at their times, nothing is cut off by the frame. Judgement (say what you see, the user decides): text over a face, a jump that lands badly. No image view: `Look: PATH (pixels not inspected)` — never claim you looked.
|
|
24
|
+
6. **Look.** Not finished until the reply names the contact sheet render.py wrote (`Look: PATH`) and says what it shows. Mechanical (check and report): text is where it was asked, cues appear at their times, nothing is cut off by the frame. Judgement (say what you see, the user decides): text over a face, a jump that lands badly. No image view: `Look: PATH (pixels not inspected)` — never claim you looked. No contact sheet (`look_error` in the result, e.g. an FFmpeg without `drawtext`): look at `still.py` frames instead and pass on the fix the error names.
|
|
25
25
|
|
|
26
26
|
Options files are checked before rendering: an unknown key or a wrong type is refused (`kind: input`) instead of silently doing nothing.
|
|
27
27
|
|
|
@@ -36,6 +36,7 @@ Everything in one go: `pipeline.py SOURCE --project ./motion --comp NAME [--capt
|
|
|
36
36
|
| "animated captions / subtitles on this video" | `analyze.py --captions` → `render.py --comp Captioned` |
|
|
37
37
|
| "cut the silences / jump cut / tighten this talk" (with motion) | `analyze.py` → `render.py --comp Jumpcut` (captions re-timed if given) |
|
|
38
38
|
| "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) |
|
|
39
|
+
| "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) |
|
|
39
40
|
| "lower thirds / name titles / chapter titles" | `render.py --comp Titled --options` with `lowerThirds` / `sceneTitles` — the text comes from the user; ask for it, never invent names |
|
|
40
41
|
| "highlight reel / best moments" | `analyze.py --highlights N [--target S]` → `render.py --comp Highlights` (audio-energy ranking: candidates, say so) |
|
|
41
42
|
| "cut to the beat / music montage" | `analyze.py --beats [--highlights N]` → `render.py --comp BeatMontage` (audio unbroken, picture cuts every `beatsPerCut` measured beats; scene cuts if no confident grid) |
|
|
@@ -61,6 +62,6 @@ Everything in one go: `pipeline.py SOURCE --project ./motion --comp NAME [--capt
|
|
|
61
62
|
- Remotion licence: free for individuals and for-profit organisations with up to 3 employees; larger companies need a Remotion company licence (https://www.remotion.dev/license). If the user is plainly a larger company, say so once.
|
|
62
63
|
- Keep the user's originals: sources are linked into `public/media/` of the project, never modified; outputs never overwrite an existing file without `--overwrite`.
|
|
63
64
|
- CJK captions: the auto font comes from ffmpeg-skill's font detection; when the report says no font was found, install one (Noto Sans CJK) or pass `--font-file` — tofu in the contact sheet is a failed job. Japanese lines break between phrases, not inside words.
|
|
64
|
-
- Speed (measured on a 2-core Linux machine): about
|
|
65
|
+
- 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. `--concurrency` above the core count is refused by Remotion.
|
|
65
66
|
- Remotion packages in a project must all be the same version; the template pins them. Don't mix in a different `remotion` version.
|
|
66
67
|
- A render that fails verification is a failure: report the failed rows from `--json`, don't ship it.
|
package/mcp/server.py
CHANGED
|
@@ -56,7 +56,13 @@ def build_argv(name: str, args: Dict[str, Any]) -> List[str]:
|
|
|
56
56
|
missing = [k for k in schema["required"] if args.get(k) in (None, "")]
|
|
57
57
|
if missing:
|
|
58
58
|
raise ValueError(f"{name}: missing required argument(s) {missing}")
|
|
59
|
-
argv: List[str] = [
|
|
59
|
+
argv: List[str] = []
|
|
60
|
+
for k in schema["x-positional"]:
|
|
61
|
+
v = args.get(k)
|
|
62
|
+
if isinstance(v, list):
|
|
63
|
+
argv += [str(x) for x in v]
|
|
64
|
+
elif v is not None:
|
|
65
|
+
argv.append(str(v))
|
|
60
66
|
flags = dict(s["flags"], dry_run="--dry-run", overwrite="--overwrite", timeout="--timeout")
|
|
61
67
|
for key, val in args.items():
|
|
62
68
|
if key in schema["x-positional"] or val is None or val is False:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "remotion-ffmpeg-skill",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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": ["remotion", "ffmpeg", "ffmpeg-skill", "video", "motion-graphics", "captions", "agent-skill", "agent-skills", "claude-code", "claude-skill", "cursor", "codex", "ai-agents"],
|
|
6
6
|
"license": "MIT",
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Gotchas
|
|
2
|
+
|
|
3
|
+
Things that went wrong while building and running this skill, and what the scripts now do about them.
|
|
4
|
+
Read the one you need; SKILL.md has the one-line versions.
|
|
5
|
+
|
|
6
|
+
## Frames and timing
|
|
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
|
+
- **Count frames, not seconds.** AAC priming/padding makes a container 20–50 ms longer than its picture. render.py compares the video stream's `nb_frames` with the expected count exactly and only falls back to a duration tolerance when the container has no frame count.
|
|
9
|
+
- **Variable frame rate sources drift.** Remotion renders on a fixed grid; analyze.py warns on suspected VFR. Make a constant-frame-rate copy with ffmpeg-skill first.
|
|
10
|
+
|
|
11
|
+
## Files Remotion can and cannot read
|
|
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.
|
|
13
|
+
- **Remotion's CLI does not copy `public/` per render on macOS/Linux** (it links the folder into its temporary bundle); **on Windows it copies it every time.** Big sources make Windows renders slower to start.
|
|
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
|
+
|
|
16
|
+
## Picture
|
|
17
|
+
- **HDR / BT.2020 looks washed out.** Chrome composites in SDR. analyze.py warns; convert with ffmpeg-skill `color.py --to-sdr` first.
|
|
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
|
+
- **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
|
+
- **`--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.
|
|
21
|
+
|
|
22
|
+
## Text
|
|
23
|
+
- **CJK captions need a CJK font on the rendering machine**, or they render as tofu. render.py stages the font ffmpeg-skill's doctor resolves for the caption's script and loads it before the first frame; `cancelRender` stops the render if it cannot load.
|
|
24
|
+
- **Japanese line breaks** use `word-break: auto-phrase` (phrase boundaries) with `text-wrap: balance`; Korean gets `lang="ko"` so it is not treated as Japanese.
|
|
25
|
+
- **An options typo used to do nothing.** Unknown keys and wrong types are refused before rendering.
|
|
26
|
+
|
|
27
|
+
## Containers and CI
|
|
28
|
+
- **Homebrew's `ffmpeg` has no `drawtext`.** ffmpeg-skill's contact sheets fail on it (the render itself still verifies). `brew install ffmpeg-full` (keg-only: put its `bin` on PATH). render.py says so in `look_error`.
|
|
29
|
+
- **`remotion` packages must share one version.** The template pins them; Dependabot groups them.
|
|
30
|
+
- **Container memory warnings** ("Detected differing memory amounts") are noise in Docker; error extraction drops them and keeps what follows "An error occurred".
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# Script reference
|
|
2
|
+
|
|
3
|
+
<!-- Generated by scripts/_docs.py from scripts/_contract.py. Do not edit by hand. -->
|
|
4
|
+
|
|
5
|
+
remotion-ffmpeg-skill 0.3.0 · contract 1.0 · timeline schema `remotion-ffmpeg-skill/timeline@1`.
|
|
6
|
+
Every script also takes `--json`, `--dry-run`, `--overwrite` and `--timeout SECONDS`.
|
|
7
|
+
Exit codes: input = 2, missing_tool = 3, timeout = 4, failed = 1.
|
|
8
|
+
|
|
9
|
+
## analyze.py
|
|
10
|
+
|
|
11
|
+
Measure a source with ffmpeg-skill and write timeline.json (+ captions from a file).
|
|
12
|
+
|
|
13
|
+
- Role: analysis — measures media and writes a data file (no media)
|
|
14
|
+
- Writes: timeline.json
|
|
15
|
+
- Verifies: every number comes from ffmpeg-skill probe/scenes/silence; warnings for VFR/HDR/rotation
|
|
16
|
+
- ffmpeg-skill: probe, scenes, silence
|
|
17
|
+
- `--dry-run`: plans without writing
|
|
18
|
+
|
|
19
|
+
| Argument | Type | Default | Meaning |
|
|
20
|
+
|---|---|---|---|
|
|
21
|
+
| `input` | string, repeatable | | source video (or audio) file; several are joined in order first |
|
|
22
|
+
| `--joined` | string | | with several inputs: where the joined source goes (default: <first>_joined.mp4) |
|
|
23
|
+
| `--join-transition` | string | `none` | with several inputs: ffmpeg-skill join.py --transition (default none = straight cuts) |
|
|
24
|
+
| `--join-duration` | number | `0.5` | transition length in seconds (default 0.5) |
|
|
25
|
+
| `--output` | string | | timeline file (default: <name>.timeline.json) |
|
|
26
|
+
| `--captions` | string | | SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written) |
|
|
27
|
+
| `--words` | string | | word timings from a speech engine (whisper JSON with word timestamps) for the Karaoke composition; without --captions the cues are grouped from these words |
|
|
28
|
+
| `--beats` | boolean | | also measure the beat grid (scenes.py --beats) |
|
|
29
|
+
| `--highlights` | integer | | also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition |
|
|
30
|
+
| `--target` | number | | with --highlights: total length the picks add up to |
|
|
31
|
+
| `--no-scenes` | boolean | | skip scene-cut detection |
|
|
32
|
+
| `--no-silence` | boolean | | skip silence detection (speech = whole file) |
|
|
33
|
+
| `--threshold` | number | | silence level in dBFS for silence.py (default -35) |
|
|
34
|
+
| `--min-silence` | number | | shortest gap in seconds that counts as silence (default 0.6) |
|
|
35
|
+
| `--margin` | number | | seconds of silence kept around speech (default 0.15) |
|
|
36
|
+
| `--scene-threshold` | number | | scenes.py --threshold (default 8) |
|
|
37
|
+
|
|
38
|
+
## init.py
|
|
39
|
+
|
|
40
|
+
Create a Remotion project with the built-in compositions (optionally npm install).
|
|
41
|
+
|
|
42
|
+
- Role: setup — creates a project folder
|
|
43
|
+
- Writes: project folder
|
|
44
|
+
- Verifies: refuses a non-empty folder; npm install exit status
|
|
45
|
+
- ffmpeg-skill: —
|
|
46
|
+
- `--dry-run`: plans without writing
|
|
47
|
+
|
|
48
|
+
| Argument | Type | Default | Meaning |
|
|
49
|
+
|---|---|---|---|
|
|
50
|
+
| `directory` | string | | new project folder (must not exist, or be empty) |
|
|
51
|
+
| `--install` | boolean | | run npm install after copying |
|
|
52
|
+
|
|
53
|
+
## still.py
|
|
54
|
+
|
|
55
|
+
Render single frames as PNG to check the look before a full render.
|
|
56
|
+
|
|
57
|
+
- Role: execution — writes a new media artifact; inputs are never modified
|
|
58
|
+
- Writes: PNG files
|
|
59
|
+
- Verifies: frames must lie inside the composition; view the PNGs
|
|
60
|
+
- ffmpeg-skill: _contract doctor (CJK font lookup)
|
|
61
|
+
- `--dry-run`: plans without writing
|
|
62
|
+
|
|
63
|
+
| Argument | Type | Default | Meaning |
|
|
64
|
+
|---|---|---|---|
|
|
65
|
+
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
66
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, or yours) |
|
|
67
|
+
| `--timeline (required)` | string | | timeline.json written by analyze.py |
|
|
68
|
+
| `--options` | string | | JSON object of look-and-feel options |
|
|
69
|
+
| `--at` | number, repeatable | | time in seconds (repeatable) |
|
|
70
|
+
| `--frame` | integer, repeatable | | frame number (repeatable) |
|
|
71
|
+
| `--out-dir` | string | | folder for the PNGs (default: next to the timeline) |
|
|
72
|
+
| `--aspect` | string: source / 16:9 / 9:16 / 1:1 / 4:5 / 4:3 | | output shape (default: the source's own). 9:16 for Reels/TikTok/Shorts, 1:1, 4:5, 16:9 |
|
|
73
|
+
| `--width` | integer | | output width in px (default: keep the source's short side) |
|
|
74
|
+
| `--fit` | string: blur / contain / cover | | how the source fills another shape: blur (default when the shape changes), contain (bars) or cover (crop) |
|
|
75
|
+
| `--font-file` | string | | caption font file (.ttf/.otf/.ttc/.woff2), staged into the project |
|
|
76
|
+
| `--no-auto-font` | boolean | | don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions |
|
|
77
|
+
|
|
78
|
+
## render.py
|
|
79
|
+
|
|
80
|
+
Render a composition from a timeline, verify it (frames, fps, size, audio) and write a contact sheet.
|
|
81
|
+
|
|
82
|
+
- Role: execution — writes a new media artifact; inputs are never modified
|
|
83
|
+
- Writes: video file (+ contact sheet PNG)
|
|
84
|
+
- Verifies: exact frame count / fps / size / audio against the timeline; non-zero exit on mismatch
|
|
85
|
+
- ffmpeg-skill: probe, look, overlay (--overlay), _contract doctor (CJK font lookup)
|
|
86
|
+
- `--dry-run`: plans without writing
|
|
87
|
+
|
|
88
|
+
| Argument | Type | Default | Meaning |
|
|
89
|
+
|---|---|---|---|
|
|
90
|
+
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
91
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, or one you added) |
|
|
92
|
+
| `--timeline (required)` | string | | timeline.json written by analyze.py |
|
|
93
|
+
| `--options` | string | | JSON object of look-and-feel options (see references/timeline.md) |
|
|
94
|
+
| `--output` | string | | output file (default: <source>_<comp>.mp4, .mov for prores) |
|
|
95
|
+
| `--codec` | string: h264 / prores | `h264` | h264 (default) or prores (ProRes 422 HQ master, .mov) |
|
|
96
|
+
| `--crf` | integer | | h264 quality (Remotion default 18; lower = better) |
|
|
97
|
+
| `--frames` | string | | render only this frame range, e.g. 0-89 (inclusive) |
|
|
98
|
+
| `--fast` | boolean | | preview quality: half resolution, quicker encode |
|
|
99
|
+
| `--concurrency` | string | `100%` | parallel browser tabs: a number up to the CPU cores, or a percentage (default 100%: all cores -- about twice as fast as Remotion's own default of half the cores) |
|
|
100
|
+
| `--no-look` | boolean | | skip the contact sheet |
|
|
101
|
+
| `--overlay` | boolean | | draw the graphics only as a transparent ProRes 4444 layer and composite it over the untouched source with ffmpeg-skill overlay.py (Captioned / PeakPulse, source frame only); with --keep-graphics the layer is kept for an editing app (Premiere, Resolve, Final Cut) |
|
|
102
|
+
| `--keep-graphics` | boolean | | with --overlay: keep the transparent graphics .mov |
|
|
103
|
+
| `--aspect` | string: source / 16:9 / 9:16 / 1:1 / 4:5 / 4:3 | | output shape (default: the source's own). 9:16 for Reels/TikTok/Shorts, 1:1, 4:5, 16:9 |
|
|
104
|
+
| `--width` | integer | | output width in px (default: keep the source's short side) |
|
|
105
|
+
| `--fit` | string: blur / contain / cover | | how the source fills another shape: blur (default when the shape changes), contain (bars) or cover (crop) |
|
|
106
|
+
| `--font-file` | string | | caption font file (.ttf/.otf/.ttc/.woff2), staged into the project |
|
|
107
|
+
| `--no-auto-font` | boolean | | don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions |
|
|
108
|
+
|
|
109
|
+
## deliver.py
|
|
110
|
+
|
|
111
|
+
Run an ffmpeg-skill delivery template (YouTube, Reels, ...) and its compliance check.
|
|
112
|
+
|
|
113
|
+
- Role: execution — writes a new media artifact; inputs are never modified
|
|
114
|
+
- Writes: deliverable video
|
|
115
|
+
- Verifies: ffmpeg-skill check.py table; non-zero exit on any FAIL row
|
|
116
|
+
- ffmpeg-skill: render --template, check
|
|
117
|
+
- `--dry-run`: plans without writing
|
|
118
|
+
|
|
119
|
+
| Argument | Type | Default | Meaning |
|
|
120
|
+
|---|---|---|---|
|
|
121
|
+
| `input` | string | | rendered video |
|
|
122
|
+
| `--platform` | string: youtube / youtube-shorts / shorts / reels / tiktok / x / facebook / linkedin / podcast / audiogram | | ffmpeg-skill delivery template to run |
|
|
123
|
+
| `--output` | string | | deliverable path (default: <name>_<platform>.mp4) |
|
|
124
|
+
| `--check-only` | boolean | | run check.py only, write nothing |
|
|
125
|
+
|
|
126
|
+
## pipeline.py
|
|
127
|
+
|
|
128
|
+
analyze -> render -> deliver in one call, stopping at the first failed step.
|
|
129
|
+
|
|
130
|
+
- Role: orchestration — runs other tools in order, each verified before the next
|
|
131
|
+
- Writes: timeline.json, render, deliverable
|
|
132
|
+
- Verifies: each step's own verification
|
|
133
|
+
- ffmpeg-skill: probe, scenes, silence, look, render --template, check
|
|
134
|
+
- `--dry-run`: plans without writing
|
|
135
|
+
|
|
136
|
+
| Argument | Type | Default | Meaning |
|
|
137
|
+
|---|---|---|---|
|
|
138
|
+
| `input` | string, repeatable | | source video; several are joined in order (ffmpeg-skill join.py) first |
|
|
139
|
+
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
140
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, or yours) |
|
|
141
|
+
| `--captions` | string | | SRT / WebVTT / JSON cues for the timeline |
|
|
142
|
+
| `--options` | string | | JSON options file passed to the composition |
|
|
143
|
+
| `--platform` | string: youtube / youtube-shorts / shorts / reels / tiktok / x / facebook / linkedin / podcast / audiogram | | deliver with this ffmpeg-skill template and check it |
|
|
144
|
+
| `--out-dir` | string | | where the timeline, render and deliverable go (default: next to the input) |
|
|
145
|
+
| `--beats` | boolean | | measure the beat grid too |
|
|
146
|
+
| `--fast` | boolean | | preview-quality render |
|
|
147
|
+
| `--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) |
|
|
148
|
+
| `--width` | integer | | output width in px |
|
|
149
|
+
| `--fit` | string: blur / contain / cover | | blur (default when the shape changes), contain or cover |
|
|
150
|
+
| `--font-file` | string | | caption font file |
|
|
151
|
+
|
|
152
|
+
## doctor.py
|
|
153
|
+
|
|
154
|
+
What this machine can do: Python, Node/npm, ffmpeg-skill, ffmpeg, a project's Remotion install.
|
|
155
|
+
|
|
156
|
+
- Role: verification — checks an artifact or the environment; writes no media
|
|
157
|
+
- Writes: nothing
|
|
158
|
+
- Verifies: reports only
|
|
159
|
+
- ffmpeg-skill: _contract doctor
|
|
160
|
+
- `--dry-run`: not applicable (reports only)
|
|
161
|
+
|
|
162
|
+
| Argument | Type | Default | Meaning |
|
|
163
|
+
|---|---|---|---|
|
|
164
|
+
| `--project` | string | | Remotion project folder to inspect |
|
package/references/timeline.md
CHANGED
|
@@ -24,7 +24,8 @@ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay":
|
|
|
24
24
|
| `beats` | object \| null | scenes.py `--beats` | `{times, tempo_bpm, confidence, usable}`; compositions use the times only when `usable` |
|
|
25
25
|
| `highlights` | `[{start, end}]` | scenes.py `--highlights` | ranked by audio energy, stored in source order (analyze.py `--highlights N [--target S]`) |
|
|
26
26
|
| `clips` | `[{name, path, start, end}]` | analyze.py with several inputs | where each input sits after ffmpeg-skill join.py joined them (empty for one input) |
|
|
27
|
-
| `captions` | `[{start, end, text}]` | your SRT / VTT / JSON | text exactly as written, timed on the (joined) source |
|
|
27
|
+
| `captions` | `[{start, end, text}]` | your SRT / VTT / JSON, or grouped from `words` | text exactly as written, timed on the (joined) source |
|
|
28
|
+
| `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 |
|
|
28
29
|
| `warnings` | `[string]` | analyze.py | VFR, HDR, rotation, odd frame rate |
|
|
29
30
|
|
|
30
31
|
All times are seconds on the source timeline. Frames are `Math.round(seconds * fps)` (round
|
|
@@ -40,6 +41,7 @@ composition exactly.
|
|
|
40
41
|
| `PeakPulse` | source duration | source + edge glow and slight zoom on each audio peak (scaled by its rms) or on each measured beat (`driver`), flash on scene cuts, progress bar with cut ticks |
|
|
41
42
|
| `Titled` | source duration | source + the user's lower thirds (`lowerThirds`) + a title card at the start of each measured scene (`sceneTitles`, in order) |
|
|
42
43
|
| `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 |
|
|
44
|
+
| `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 |
|
|
43
45
|
| `BeatMontage` | source duration | audio unbroken; the picture cuts every `beatsPerCut` measured beats, cycling through highlights (or scenes); no usable grid → cuts on scene changes |
|
|
44
46
|
|
|
45
47
|
## Options (`--options look.json`)
|
|
@@ -84,6 +86,7 @@ Example:
|
|
|
84
86
|
|
|
85
87
|
- **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.
|
|
86
88
|
- **JSON**: `[{"start": 1.0, "end": 3.5, "text": "..."}]` or `{"cues": [...]}`.
|
|
89
|
+
- **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.
|
|
87
90
|
|
|
88
91
|
## Adding your own composition
|
|
89
92
|
|
package/scripts/_captions.py
CHANGED
|
@@ -77,3 +77,65 @@ def read_captions(path: Path) -> List[Dict]:
|
|
|
77
77
|
else:
|
|
78
78
|
cues = parse_srt_or_vtt(text)
|
|
79
79
|
return sorted(cues, key=lambda c: c["start"])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# ---------------------------------------------------------------- word timings (karaoke)
|
|
83
|
+
|
|
84
|
+
def parse_words(text: str) -> List[Dict]:
|
|
85
|
+
"""Word timings from a speech engine's JSON, as [{start, end, text}] in time order.
|
|
86
|
+
|
|
87
|
+
Accepts the whisper / faster-whisper layout ({"segments": [{"words": [{"word", "start", "end"}]}]}),
|
|
88
|
+
a top-level {"words": [...]} and a plain list. `text` keeps the engine's own spacing (English words
|
|
89
|
+
carry a leading space, Japanese tokens none), so joining them reproduces the transcript exactly.
|
|
90
|
+
"""
|
|
91
|
+
data = json.loads(text)
|
|
92
|
+
raw: List[Dict] = []
|
|
93
|
+
if isinstance(data, dict) and isinstance(data.get("segments"), list):
|
|
94
|
+
for seg in data["segments"]:
|
|
95
|
+
raw += list(seg.get("words") or [])
|
|
96
|
+
elif isinstance(data, dict) and isinstance(data.get("words"), list):
|
|
97
|
+
raw = data["words"]
|
|
98
|
+
elif isinstance(data, list):
|
|
99
|
+
raw = data
|
|
100
|
+
else:
|
|
101
|
+
raise CaptionError("word timings must be whisper JSON (segments[].words[]) or a list of {word, start, end}")
|
|
102
|
+
words: List[Dict] = []
|
|
103
|
+
for i, w in enumerate(raw):
|
|
104
|
+
try:
|
|
105
|
+
body = str(w.get("word", w.get("text")))
|
|
106
|
+
start, end = float(w["start"]), float(w["end"])
|
|
107
|
+
except (AttributeError, KeyError, TypeError, ValueError):
|
|
108
|
+
raise CaptionError(f"word {i} needs word/text, start and end")
|
|
109
|
+
if body in ("", "None") or end < start:
|
|
110
|
+
continue
|
|
111
|
+
words.append({"start": round(start, 3), "end": round(max(end, start + 0.01), 3), "text": body})
|
|
112
|
+
if not words:
|
|
113
|
+
raise CaptionError("no timed words found (was the transcript made with word timestamps?)")
|
|
114
|
+
return sorted(words, key=lambda w: w["start"])
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def read_words(path: Path) -> List[Dict]:
|
|
118
|
+
return parse_words(path.read_text(encoding="utf-8-sig"))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cues_from_words(words: List[Dict], max_chars: int = 32, max_gap: float = 0.7, max_len: float = 4.0) -> List[Dict]:
|
|
122
|
+
"""Group timed words into caption cues mechanically: a new cue after a pause longer than max_gap,
|
|
123
|
+
when the cue would pass max_chars characters, or last longer than max_len seconds. The words and
|
|
124
|
+
their order are the engine's; nothing is added, dropped or reworded."""
|
|
125
|
+
cues: List[Dict] = []
|
|
126
|
+
cur: List[Dict] = []
|
|
127
|
+
for w in words:
|
|
128
|
+
if cur:
|
|
129
|
+
text_len = len("".join(x["text"] for x in cur + [w]).strip())
|
|
130
|
+
if (w["start"] - cur[-1]["end"] > max_gap or text_len > max_chars
|
|
131
|
+
or w["end"] - cur[0]["start"] > max_len):
|
|
132
|
+
cues.append(_cue(cur))
|
|
133
|
+
cur = []
|
|
134
|
+
cur.append(w)
|
|
135
|
+
if cur:
|
|
136
|
+
cues.append(_cue(cur))
|
|
137
|
+
return cues
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _cue(ws: List[Dict]) -> Dict:
|
|
141
|
+
return {"start": ws[0]["start"], "end": ws[-1]["end"], "text": "".join(w["text"] for w in ws).strip()}
|
package/scripts/_common.py
CHANGED
|
@@ -221,7 +221,7 @@ def validate_timeline(t: Any) -> List[str]:
|
|
|
221
221
|
v = src.get(k)
|
|
222
222
|
if not isinstance(v, (int, float)) or v <= 0:
|
|
223
223
|
p.append(f"source.{k} must be a positive number")
|
|
224
|
-
for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights"):
|
|
224
|
+
for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights", "words"):
|
|
225
225
|
if not isinstance(t.get(k, []), list):
|
|
226
226
|
p.append(f"{k} must be a list")
|
|
227
227
|
for i, c in enumerate(t.get("captions", []) or []):
|
|
@@ -250,7 +250,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
|
|
|
250
250
|
and render.py then only reports the measured numbers.
|
|
251
251
|
"""
|
|
252
252
|
fps = float(t["source"]["fps"])
|
|
253
|
-
if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage"):
|
|
253
|
+
if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke"):
|
|
254
254
|
return max(1, sec_to_frames(float(t["source"]["duration"]), fps))
|
|
255
255
|
if comp in ("Jumpcut", "Highlights"):
|
|
256
256
|
if comp == "Jumpcut":
|
|
@@ -264,7 +264,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
|
|
|
264
264
|
|
|
265
265
|
# ---------------------------------------------------------------- Remotion project
|
|
266
266
|
|
|
267
|
-
BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage")
|
|
267
|
+
BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke")
|
|
268
268
|
|
|
269
269
|
|
|
270
270
|
def remotion_bin(project: Path) -> Path:
|
|
@@ -293,7 +293,11 @@ def remotion_error(text: str, limit: int = 15) -> str:
|
|
|
293
293
|
for i, ln in enumerate(lines):
|
|
294
294
|
if "An error occurred" in ln:
|
|
295
295
|
return "\n".join(ln2.strip() for ln2 in lines[i + 1:i + 1 + limit])
|
|
296
|
-
|
|
296
|
+
# No marker: the Error lines themselves, without the JavaScript stack frames under them.
|
|
297
|
+
errors = [ln.strip() for ln in lines if "Error" in ln and not ln.lstrip().startswith("at ")]
|
|
298
|
+
if errors:
|
|
299
|
+
return "\n".join(errors[-limit:])
|
|
300
|
+
return "\n".join(ln for ln in lines if not ln.lstrip().startswith("at "))[-4000:] or "\n".join(lines[-limit:])
|
|
297
301
|
|
|
298
302
|
|
|
299
303
|
def stage_source(project: Path, source_path: str) -> str:
|
package/scripts/_contract.py
CHANGED
|
@@ -111,8 +111,10 @@ def _json_type(action: argparse.Action) -> Dict[str, Any]:
|
|
|
111
111
|
t = {"type": "string"}
|
|
112
112
|
if action.choices:
|
|
113
113
|
t["enum"] = list(action.choices)
|
|
114
|
-
if isinstance(action, argparse._AppendAction):
|
|
114
|
+
if isinstance(action, argparse._AppendAction) or action.nargs in ("+", "*"):
|
|
115
115
|
t = {"type": "array", "items": t}
|
|
116
|
+
if action.nargs == "+":
|
|
117
|
+
t["minItems"] = 1
|
|
116
118
|
return t
|
|
117
119
|
|
|
118
120
|
|
package/scripts/_docs.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Generate references/scripts.md from the contract (internal; not a tool).
|
|
3
|
+
|
|
4
|
+
python3 scripts/_docs.py # rewrite references/scripts.md
|
|
5
|
+
python3 scripts/_docs.py --check # exit 1 if it is out of date (tests run this)
|
|
6
|
+
|
|
7
|
+
The reference is generated, never edited by hand, so it cannot drift from the scripts' own parsers.
|
|
8
|
+
"""
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
HERE = Path(__file__).resolve().parent
|
|
13
|
+
sys.path.insert(0, str(HERE))
|
|
14
|
+
import _contract # noqa: E402
|
|
15
|
+
|
|
16
|
+
OUT = HERE.parent / "references" / "scripts.md"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def render() -> str:
|
|
20
|
+
c = _contract.build()
|
|
21
|
+
lines = [
|
|
22
|
+
"# Script reference",
|
|
23
|
+
"",
|
|
24
|
+
"<!-- Generated by scripts/_docs.py from scripts/_contract.py. Do not edit by hand. -->",
|
|
25
|
+
"",
|
|
26
|
+
f"remotion-ffmpeg-skill {c['version']} · contract {c['contract_version']} · timeline schema `{c['timeline_schema']}`.",
|
|
27
|
+
"Every script also takes `--json`, `--dry-run`, `--overwrite` and `--timeout SECONDS`.",
|
|
28
|
+
"Exit codes: " + ", ".join(f"{k} = {v}" for k, v in c["conventions"]["errors"].items()) + ".",
|
|
29
|
+
"",
|
|
30
|
+
]
|
|
31
|
+
for t in c["tools"]:
|
|
32
|
+
s = t["inputSchema"]
|
|
33
|
+
lines += [f"## {t['name']}.py", "", t["summary"], "",
|
|
34
|
+
f"- Role: {t['role']} — {c['roles'][t['role']]}",
|
|
35
|
+
f"- Writes: {t['writes'] or 'nothing'}",
|
|
36
|
+
f"- Verifies: {t['verification']}",
|
|
37
|
+
f"- ffmpeg-skill: {', '.join(t['ffmpeg_skill']) or '—'}",
|
|
38
|
+
f"- `--dry-run`: {'plans without writing' if t['dry_run'] else 'not applicable (reports only)'}",
|
|
39
|
+
"", "| Argument | Type | Default | Meaning |", "|---|---|---|---|"]
|
|
40
|
+
for name, p in s["properties"].items():
|
|
41
|
+
if name in ("dry_run", "overwrite", "timeout"):
|
|
42
|
+
continue
|
|
43
|
+
arg = name if name in s["x-positional"] else t["flags"].get(name, "--" + name.replace("_", "-"))
|
|
44
|
+
if name in s["required"] and name not in s["x-positional"]:
|
|
45
|
+
arg += " (required)"
|
|
46
|
+
typ = p.get("type", "")
|
|
47
|
+
if typ == "array":
|
|
48
|
+
typ = f"{p['items'].get('type', '')}, repeatable"
|
|
49
|
+
if "enum" in p or ("items" in p and "enum" in p["items"]):
|
|
50
|
+
typ += ": " + " / ".join(map(str, p.get("enum") or p["items"]["enum"]))
|
|
51
|
+
default = f"`{p['default']}`" if "default" in p else ""
|
|
52
|
+
desc = (p.get("description") or "").replace("|", "\\|").replace("\n", " ")
|
|
53
|
+
lines.append(f"| `{arg}` | {typ} | {default} | {desc} |")
|
|
54
|
+
lines.append("")
|
|
55
|
+
return "\n".join(lines)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def main() -> None:
|
|
59
|
+
text = render()
|
|
60
|
+
if "--check" in sys.argv:
|
|
61
|
+
current = OUT.read_text(encoding="utf-8") if OUT.exists() else ""
|
|
62
|
+
if current != text:
|
|
63
|
+
print("references/scripts.md is out of date: run python3 scripts/_docs.py", file=sys.stderr)
|
|
64
|
+
sys.exit(1)
|
|
65
|
+
print("references/scripts.md is up to date")
|
|
66
|
+
return
|
|
67
|
+
OUT.write_text(text, encoding="utf-8")
|
|
68
|
+
print(f"wrote {OUT}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
if __name__ == "__main__":
|
|
72
|
+
main()
|
package/scripts/analyze.py
CHANGED
|
@@ -24,7 +24,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
24
24
|
from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
|
|
25
25
|
emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
|
|
26
26
|
require_ffmpeg_skill, shell_join, version)
|
|
27
|
-
from _captions import CaptionError, read_captions
|
|
27
|
+
from _captions import CaptionError, cues_from_words, read_captions, read_words
|
|
28
28
|
|
|
29
29
|
|
|
30
30
|
def build_parser() -> argparse.ArgumentParser:
|
|
@@ -37,6 +37,8 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
37
37
|
p.add_argument("--join-duration", type=float, default=0.5, help="transition length in seconds (default 0.5)")
|
|
38
38
|
p.add_argument("-o", "--output", help="timeline file (default: <name>.timeline.json)")
|
|
39
39
|
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 from a speech engine (whisper JSON with word timestamps) for the "
|
|
41
|
+
"Karaoke composition; without --captions the cues are grouped from these words")
|
|
40
42
|
p.add_argument("--beats", action="store_true", help="also measure the beat grid (scenes.py --beats)")
|
|
41
43
|
p.add_argument("--highlights", type=int, metavar="N",
|
|
42
44
|
help="also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition")
|
|
@@ -112,6 +114,18 @@ def main() -> None:
|
|
|
112
114
|
except (CaptionError, ValueError) as e:
|
|
113
115
|
die(f"cannot read {cpath}: {e}", "input")
|
|
114
116
|
|
|
117
|
+
words: List[Dict[str, Any]] = []
|
|
118
|
+
if a.words:
|
|
119
|
+
wpath = Path(a.words).expanduser()
|
|
120
|
+
if not wpath.is_file():
|
|
121
|
+
die(f"word timings file not found: {wpath}", "input")
|
|
122
|
+
try:
|
|
123
|
+
words = read_words(wpath)
|
|
124
|
+
except (CaptionError, ValueError) as e:
|
|
125
|
+
die(f"cannot read {wpath}: {e}", "input")
|
|
126
|
+
if not captions:
|
|
127
|
+
captions = cues_from_words(words)
|
|
128
|
+
|
|
115
129
|
join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
|
|
116
130
|
"--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
|
|
117
131
|
plan = ([shell_join(ffskill_cmd("join", join_args))] if len(inputs) > 1 else []) + \
|
|
@@ -211,6 +225,7 @@ def main() -> None:
|
|
|
211
225
|
"highlights": highlights,
|
|
212
226
|
"clips": clips,
|
|
213
227
|
"captions": captions,
|
|
228
|
+
"words": words,
|
|
214
229
|
"warnings": warnings_for(probe),
|
|
215
230
|
}
|
|
216
231
|
if not video:
|
|
@@ -230,7 +245,7 @@ def main() -> None:
|
|
|
230
245
|
"speech_seconds": round(speech_total, 3), "peaks": len(peaks),
|
|
231
246
|
"captions": len(captions), "beats": bool(beats and beats.get("usable")),
|
|
232
247
|
"tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
|
|
233
|
-
"clips": len(clips) or 1},
|
|
248
|
+
"clips": len(clips) or 1, "words": len(words)},
|
|
234
249
|
"warnings": timeline["warnings"]},
|
|
235
250
|
f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
|
|
236
251
|
f"(speech {speech_total:.2f}s), {len(peaks)} peaks, {len(captions)} captions")
|
package/scripts/render.py
CHANGED
|
@@ -34,7 +34,9 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
34
34
|
p.add_argument("--crf", type=int, help="h264 quality (Remotion default 18; lower = better)")
|
|
35
35
|
p.add_argument("--frames", help="render only this frame range, e.g. 0-89 (inclusive)")
|
|
36
36
|
p.add_argument("--fast", action="store_true", help="preview quality: half resolution, quicker encode")
|
|
37
|
-
p.add_argument("--concurrency",
|
|
37
|
+
p.add_argument("--concurrency", default="100%",
|
|
38
|
+
help="parallel browser tabs: a number up to the CPU cores, or a percentage (default 100%%: all "
|
|
39
|
+
"cores -- about twice as fast as Remotion's own default of half the cores)")
|
|
38
40
|
p.add_argument("--no-look", action="store_true", help="skip the contact sheet")
|
|
39
41
|
p.add_argument("--overlay", action="store_true",
|
|
40
42
|
help="draw the graphics only as a transparent ProRes 4444 layer and composite it over the "
|
|
@@ -148,7 +150,7 @@ def main() -> None:
|
|
|
148
150
|
if a.overlay:
|
|
149
151
|
if a.comp in ("Jumpcut", "Highlights", "BeatMontage"):
|
|
150
152
|
die(f"--overlay cannot do {a.comp}: its cuts move the picture itself (overlay works for "
|
|
151
|
-
"Captioned, PeakPulse, Titled)", "input")
|
|
153
|
+
"Captioned, PeakPulse, Titled, Karaoke)", "input")
|
|
152
154
|
if a.aspect not in (None, "source") or a.width is not None or a.fit not in (None, "contain"):
|
|
153
155
|
die("--overlay draws on the source's own frame: drop --aspect / --width / --fit", "input")
|
|
154
156
|
if a.fast or a.codec != "h264" or frames:
|
|
@@ -190,18 +192,27 @@ def main() -> None:
|
|
|
190
192
|
probe = ffskill("probe", [str(output)])
|
|
191
193
|
ok, rows = verify(probe, timeline, a.comp, frames, a.fast, frame)
|
|
192
194
|
look: Optional[str] = None
|
|
195
|
+
look_error: Optional[str] = None
|
|
193
196
|
commands.append(probe["_command"])
|
|
194
197
|
if not a.no_look:
|
|
195
198
|
lk = ffskill("look", [str(output), "--tiles", "3x2"], allow_fail=True)
|
|
196
199
|
if lk.get("status") == "completed":
|
|
197
200
|
look = lk.get("output")
|
|
201
|
+
if look and not Path(look).is_absolute():
|
|
202
|
+
look = str((Path.cwd() / look).resolve())
|
|
198
203
|
commands.append(lk.get("_command", ""))
|
|
204
|
+
else:
|
|
205
|
+
look_error = f"{lk.get('kind') or 'failed'}: {str(lk.get('error') or '')[-400:]}"
|
|
206
|
+
if "drawtext" in look_error:
|
|
207
|
+
look_error += (" -- this FFmpeg build has no drawtext filter. macOS Homebrew: `brew install ffmpeg-full` "
|
|
208
|
+
"(the plain ffmpeg formula dropped it); use still.py frames to look meanwhile")
|
|
209
|
+
info(f"warning: contact sheet failed ({look_error}); view the render itself")
|
|
199
210
|
v = probe.get("video") or {}
|
|
200
211
|
summary = (f"{output.name}: {float(probe.get('duration') or 0):.2f} s, {v.get('width')}x{v.get('height')}, "
|
|
201
212
|
f"{v.get('fps')} fps, {'audio' if probe.get('audio') else 'no audio'}")
|
|
202
213
|
result = {"status": "completed" if ok else "failed", "output": str(output), "verified": ok,
|
|
203
214
|
"verification": rows, "commands": commands, "look": look, "summary": summary,
|
|
204
|
-
"frame": frame, "font": font_note, "mode": "overlay" if a.overlay else "full",
|
|
215
|
+
"frame": frame, "font": font_note, "mode": "overlay" if a.overlay else "full", "look_error": look_error,
|
|
205
216
|
"graphics": str(graphics) if a.overlay and a.keep_graphics else None,
|
|
206
217
|
"kind": None if ok else "failed"}
|
|
207
218
|
table = "\n".join(f" {r['check']:<9} {r['status']:<4} {r['value']} (expected {r['expected']})" for r in rows)
|
|
@@ -6,6 +6,7 @@ import { PeakPulse } from "./compositions/PeakPulse";
|
|
|
6
6
|
import { Titled } from "./compositions/Titled";
|
|
7
7
|
import { Highlights } from "./compositions/Highlights";
|
|
8
8
|
import { BeatMontage } from "./compositions/BeatMontage";
|
|
9
|
+
import { Karaoke } from "./compositions/Karaoke";
|
|
9
10
|
import { SAMPLE_TIMELINE, fullLengthFrames, highlightFrames, jumpcutFrames, outputFrame, type Props, type Timeline } from "./timeline";
|
|
10
11
|
|
|
11
12
|
// Length and fps come from the measured timeline, never from constants; the frame is the
|
|
@@ -28,5 +29,6 @@ export const RemotionRoot: React.FC = () => (
|
|
|
28
29
|
<Composition id="Titled" component={Titled} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
29
30
|
<Composition id="Highlights" component={Highlights} {...base} calculateMetadata={metadataFrom(highlightFrames)} />
|
|
30
31
|
<Composition id="BeatMontage" component={BeatMontage} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
32
|
+
<Composition id="Karaoke" component={Karaoke} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
31
33
|
</>
|
|
32
34
|
);
|
|
@@ -0,0 +1,104 @@
|
|
|
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 { Props, fontStack, outputFrame, resolveOptions, secToFrames, type Caption, type Options } from "../timeline";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Karaoke: each caption cue with its words lit one by one at the times the speech engine measured
|
|
10
|
+
* (analyze.py --words). The current word takes the accent colour and lifts, spoken words stay white,
|
|
11
|
+
* words still to come are dimmed. Cues without timed words fall back to a plain caption.
|
|
12
|
+
*/
|
|
13
|
+
export const Karaoke: React.FC<Props> = (props) => {
|
|
14
|
+
const { timeline, options, font, overlay } = props;
|
|
15
|
+
useStagedFont(font);
|
|
16
|
+
const o = resolveOptions(options);
|
|
17
|
+
const family = fontStack(o, font);
|
|
18
|
+
const { fps } = useVideoConfig();
|
|
19
|
+
const words = timeline.words ?? [];
|
|
20
|
+
return (
|
|
21
|
+
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
22
|
+
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
|
|
23
|
+
{timeline.captions.map((c, i) => {
|
|
24
|
+
const from = secToFrames(c.start, fps);
|
|
25
|
+
const dur = Math.max(1, secToFrames(c.end, fps) - from);
|
|
26
|
+
// Words that belong to this cue: their midpoint falls inside it.
|
|
27
|
+
const own = words.filter((w) => (w.start + w.end) / 2 >= c.start && (w.start + w.end) / 2 <= c.end);
|
|
28
|
+
return (
|
|
29
|
+
<Sequence key={i} from={from} durationInFrames={dur} name={`cue ${i + 1}`} layout="none">
|
|
30
|
+
<KaraokeCue cue={c} words={own} len={dur} o={o} fontFamily={family} />
|
|
31
|
+
</Sequence>
|
|
32
|
+
);
|
|
33
|
+
})}
|
|
34
|
+
</AbsoluteFill>
|
|
35
|
+
);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const KaraokeCue: React.FC<{ cue: Caption; words: Caption[]; len: number; o: Options; fontFamily: string }> = ({
|
|
39
|
+
cue,
|
|
40
|
+
words,
|
|
41
|
+
len,
|
|
42
|
+
o,
|
|
43
|
+
fontFamily,
|
|
44
|
+
}) => {
|
|
45
|
+
const frame = useCurrentFrame();
|
|
46
|
+
const { fps, width, height } = useVideoConfig();
|
|
47
|
+
const enter = spring({ frame, fps, config: { damping: 14, stiffness: 180, mass: 0.6 } });
|
|
48
|
+
const fade = Math.min(6, Math.floor(len / 3));
|
|
49
|
+
const exit = fade > 0 ? interpolate(frame, [len - fade, len], [1, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }) : 1;
|
|
50
|
+
const size = Math.round(Math.min(width, height) * o.captionSize * 1.1);
|
|
51
|
+
const now = cue.start + frame / fps; // source time at this frame
|
|
52
|
+
const lang = /[-ヿ]/.test(cue.text) ? "ja" : /[가-]/.test(cue.text) ? "ko" : undefined;
|
|
53
|
+
return (
|
|
54
|
+
<AbsoluteFill style={{ justifyContent: "flex-end", alignItems: "center", paddingBottom: captionMarginPx(o, width, height) }}>
|
|
55
|
+
<div
|
|
56
|
+
lang={lang}
|
|
57
|
+
style={{
|
|
58
|
+
maxWidth: width * 0.88,
|
|
59
|
+
padding: `${size * 0.25}px ${size * 0.55}px`,
|
|
60
|
+
borderRadius: size * 0.3,
|
|
61
|
+
background: "rgba(0,0,0,0.6)",
|
|
62
|
+
fontFamily,
|
|
63
|
+
fontWeight: 800,
|
|
64
|
+
fontSize: size,
|
|
65
|
+
lineHeight: 1.35,
|
|
66
|
+
textAlign: "center",
|
|
67
|
+
whiteSpace: "pre-wrap",
|
|
68
|
+
textWrap: "balance",
|
|
69
|
+
opacity: Math.min(enter, exit),
|
|
70
|
+
transform: `translateY(${(1 - enter) * size * 0.5}px)`,
|
|
71
|
+
}}
|
|
72
|
+
>
|
|
73
|
+
{words.length === 0 ? (
|
|
74
|
+
<span style={{ color: o.textColor }}>{cue.text}</span>
|
|
75
|
+
) : (
|
|
76
|
+
words.map((w, i) => {
|
|
77
|
+
const spoken = now >= w.end;
|
|
78
|
+
const active = now >= w.start && now < w.end;
|
|
79
|
+
// A lift, not a scale: scaling a word would grow it over the spaces beside it.
|
|
80
|
+
const lift = active ? interpolate(now, [w.start, Math.min(w.end, w.start + 0.12)], [-0.12, -0.05], { extrapolateRight: "clamp" }) : 0;
|
|
81
|
+
// The engine's leading space stays a plain text node between words: inside an
|
|
82
|
+
// inline-block it would collapse and glue the words together.
|
|
83
|
+
const lead = w.text.match(/^\s*/)?.[0] ?? "";
|
|
84
|
+
return (
|
|
85
|
+
<React.Fragment key={i}>
|
|
86
|
+
{lead}
|
|
87
|
+
<span
|
|
88
|
+
style={{
|
|
89
|
+
color: active ? o.accent : spoken ? o.textColor : "rgba(255,255,255,0.45)",
|
|
90
|
+
display: "inline-block",
|
|
91
|
+
transform: `translateY(${lift}em)`,
|
|
92
|
+
textShadow: active ? `0 0 0.35em ${o.accent}` : "none",
|
|
93
|
+
}}
|
|
94
|
+
>
|
|
95
|
+
{w.text.slice(lead.length)}
|
|
96
|
+
</span>
|
|
97
|
+
</React.Fragment>
|
|
98
|
+
);
|
|
99
|
+
})
|
|
100
|
+
)}
|
|
101
|
+
</div>
|
|
102
|
+
</AbsoluteFill>
|
|
103
|
+
);
|
|
104
|
+
};
|
|
@@ -37,6 +37,8 @@ export type Timeline = {
|
|
|
37
37
|
/** Several inputs joined by ffmpeg-skill: where each clip sits on the joined timeline. */
|
|
38
38
|
clips?: { name: string; start: number; end: number }[];
|
|
39
39
|
captions: Caption[];
|
|
40
|
+
/** Word timings from a speech engine (analyze.py --words), text with the engine's own spacing. */
|
|
41
|
+
words?: Caption[];
|
|
40
42
|
warnings?: string[];
|
|
41
43
|
};
|
|
42
44
|
|