remotion-ffmpeg-skill 0.14.5 → 0.16.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/SKILL.md +2 -0
- package/package.json +1 -1
- package/references/scripts.md +15 -5
- package/references/timeline.md +9 -0
- package/scripts/_common.py +35 -3
- package/scripts/_kinetic.py +139 -0
- package/scripts/analyze.py +254 -20
- package/scripts/pipeline.py +32 -7
- package/scripts/render.py +3 -0
- package/templates/remotion-project/src/Root.tsx +2 -0
- package/templates/remotion-project/src/compositions/BeatMontage.tsx +1 -1
- package/templates/remotion-project/src/compositions/Captioned.tsx +1 -1
- package/templates/remotion-project/src/compositions/Emphasis.tsx +1 -1
- package/templates/remotion-project/src/compositions/Highlights.tsx +1 -1
- package/templates/remotion-project/src/compositions/Jumpcut.tsx +1 -1
- package/templates/remotion-project/src/compositions/Karaoke.tsx +1 -1
- package/templates/remotion-project/src/compositions/KineticType.tsx +121 -0
- package/templates/remotion-project/src/compositions/PeakPulse.tsx +1 -1
- package/templates/remotion-project/src/compositions/Pip.tsx +1 -1
- package/templates/remotion-project/src/compositions/Titled.tsx +1 -1
- package/templates/remotion-project/src/lib/SourceVideo.tsx +13 -1
- package/templates/remotion-project/src/timeline.ts +36 -0
package/SKILL.md
CHANGED
|
@@ -67,6 +67,8 @@ Moving text has three owners: word-timed caption effects are this skill's, anima
|
|
|
67
67
|
| "use our brand" / a `brand.json` (ffmpeg-skill's format) | `--brand brand.json` on render / still / pipeline: its colours, caption colour, font and font file set the look (an `--options` file wins key by key); `deliver.py` / `pipeline.py --brand` places its logo with the template |
|
|
68
68
|
| a phone clip (VFR) or HDR / iPhone HDR / HLG footage | `analyze.py --conform` (or `pipeline.py --conform`): drawn on a CFR SDR BT.709 copy ffmpeg-skill made; without the flag it is refused |
|
|
69
69
|
| several clips ("intro + talk + outro") | `analyze.py A.mp4 B.mov C.mp4` (or `pipeline.py` with several inputs): ffmpeg-skill join.py normalises and joins them, then everything is measured on the joined file |
|
|
70
|
+
| "kinetic type / lyric video / words that hit on the beat" | `analyze.py [SOURCE \| --blank S --music song.wav] --captions lyrics.srt --beats --kinetic beats` (each word, or Japanese / Chinese character, on the next measured beat; `--kinetic-step N` beats apart) or `--words WORDS.json --kinetic words` (each word at its spoken time) → `render.py --comp KineticType` (`kineticStyle`, `kineticReveal`, `kineticStagger`, `kineticSize`). Only measured timings: kinetic type from a JSON request with no measurement is hyperframes-skill's |
|
|
71
|
+
| "a video from just this music" / text or a visualizer with no footage | `analyze.py --blank SECONDS --size WxH [--fps N] [--music bgm.wav] [--beats]` (or `pipeline.py --blank ...`; through MCP, `input` is `["-"]`): a timeline with no footage, the music measured for peaks and beats as a source's audio is; any composition draws on the `background` option (default black). Length, size and rate are the caller's, so ask for them |
|
|
70
72
|
| "preview" / "show me a frame" | `still.py` |
|
|
71
73
|
| a new kind of graphic | add a composition to `src/` of the project that reads `Props` from `src/timeline.ts`; render with `--comp YourId` (render.py then reports measured numbers without a built-in expectation) |
|
|
72
74
|
| plain cut / trim / resize / loudness with no graphics | not this skill: use ffmpeg-skill directly |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "remotion-ffmpeg-skill",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.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
|
@@ -19,7 +19,7 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
|
|
|
19
19
|
|
|
20
20
|
| Argument | Type | Default | Meaning |
|
|
21
21
|
|---|---|---|---|
|
|
22
|
-
| `input` | string, repeatable | | source video (or audio) file; several are joined in order first |
|
|
22
|
+
| `input` | string, repeatable | | source video (or audio) file; several are joined in order first (with --blank: none, or `-`) |
|
|
23
23
|
| `--joined` | string | | with several inputs: where the joined source goes (default: <first>_joined.mp4) |
|
|
24
24
|
| `--join-transition` | string | `none` | with several inputs: ffmpeg-skill join.py --transition (default none = straight cuts) |
|
|
25
25
|
| `--join-duration` | number | `0.5` | transition length in seconds (default 0.5) |
|
|
@@ -35,7 +35,13 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
|
|
|
35
35
|
| `--conform` | boolean | | a variable-frame-rate or HDR / BT.2020 source (or --pip camera) is first made into a constant-frame-rate, SDR BT.709 copy with ffmpeg-skill (fit.py --fps, color.py --to-sdr: tone-mapped, so the look changes) and everything is measured and drawn on that copy; the original is never modified. Without it such a source is refused |
|
|
36
36
|
| `--conformed` | string | | with --conform: where the conformed copy of the source goes (default: <name>_conformed.mp4) |
|
|
37
37
|
| `--conform-fps` | number | | with --conform: the constant frame rate for a VFR source (default: the stream's base rate, r_frame_rate, so no frame is dropped) |
|
|
38
|
+
| `--blank` | number | | a source-less run: a timeline of this many seconds with no footage (a plain background), so a composition draws from nothing. With --music the music plays under it and is measured for peaks (and --beats) as a source's audio is; no input file is given |
|
|
39
|
+
| `--size` | string | | with --blank: the frame size in px, even numbers (default 1920x1080) |
|
|
40
|
+
| `--fps` | string | | with --blank: the frame rate, e.g. 30, 25, 30000/1001 (default 30) |
|
|
41
|
+
| `--music` | string | | with --blank: the music (any file with an audio stream) that plays under the blank timeline from 0 s; measured with ffmpeg-skill (scenes.py peaks and --beats, silence.py). Cut at the blank's end when longer, silence after it when shorter |
|
|
38
42
|
| `--beats` | boolean | | also measure the beat grid (scenes.py --beats) |
|
|
43
|
+
| `--kinetic` | string: auto / words / beats | | schedule the caption cues' words for the KineticType composition: `words` (each word at the time --words measured), `beats` (each word, or CJK character, on the next measured beat; needs --beats) or `auto` (words when given, else beats). Never from unmeasured times |
|
|
44
|
+
| `--kinetic-step` | integer | `1` | with --kinetic beats: measured beats per word (default 1) |
|
|
39
45
|
| `--highlights` | integer | | also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition |
|
|
40
46
|
| `--target` | number | | with --highlights: total length the picks add up to |
|
|
41
47
|
| `--no-scenes` | boolean | | skip scene-cut detection |
|
|
@@ -83,7 +89,7 @@ Render single frames as PNG to check the look before a full render.
|
|
|
83
89
|
| Argument | Type | Default | Meaning |
|
|
84
90
|
|---|---|---|---|
|
|
85
91
|
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
86
|
-
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or yours) |
|
|
92
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, or yours) |
|
|
87
93
|
| `--timeline (required)` | string | | timeline.json written by analyze.py |
|
|
88
94
|
| `--options` | string | | JSON object of look-and-feel options |
|
|
89
95
|
| `--at` | number, repeatable | | time in seconds (repeatable) |
|
|
@@ -114,7 +120,7 @@ Render a composition from a timeline, verify it (frames, fps, size, audio) and w
|
|
|
114
120
|
| Argument | Type | Default | Meaning |
|
|
115
121
|
|---|---|---|---|
|
|
116
122
|
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
117
|
-
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or one you added) |
|
|
123
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, or one you added) |
|
|
118
124
|
| `--timeline (required)` | string | | timeline.json written by analyze.py |
|
|
119
125
|
| `--options` | string | | JSON object of look-and-feel options (see references/timeline.md) |
|
|
120
126
|
| `--output` | string | | output file (default: <source>_<comp>.mp4, .mov for prores) |
|
|
@@ -177,9 +183,9 @@ analyze -> render -> deliver in one call, stopping at the first failed step.
|
|
|
177
183
|
|
|
178
184
|
| Argument | Type | Default | Meaning |
|
|
179
185
|
|---|---|---|---|
|
|
180
|
-
| `input` | string, repeatable | | source video; several are joined in order (ffmpeg-skill join.py) first |
|
|
186
|
+
| `input` | string, repeatable | | source video; several are joined in order (ffmpeg-skill join.py) first (with --blank: none, or `-`) |
|
|
181
187
|
| `--project (required)` | string | | Remotion project folder made by init.py |
|
|
182
|
-
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or yours) |
|
|
188
|
+
| `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, or yours) |
|
|
183
189
|
| `--captions` | string | | SRT / WebVTT / JSON cues for the timeline |
|
|
184
190
|
| `--chapters` | string | | chapters (`TIME TITLE` per line, or `source`): cards in Titled and, with --platform, chapter markers in the deliverable |
|
|
185
191
|
| `--options` | string | | JSON options file passed to the composition |
|
|
@@ -187,6 +193,10 @@ analyze -> render -> deliver in one call, stopping at the first failed step.
|
|
|
187
193
|
| `--platform` | string: youtube / youtube-shorts / shorts / reels / tiktok / x / facebook / linkedin / podcast / audiogram | | deliver with this ffmpeg-skill template and check it |
|
|
188
194
|
| `--out-dir` | string | | where the timeline, render and deliverable go (default: next to the input) |
|
|
189
195
|
| `--beats` | boolean | | measure the beat grid too |
|
|
196
|
+
| `--blank` | number | | no footage: draw the composition on a plain background this many seconds long (analyze.py --blank); give no input file |
|
|
197
|
+
| `--size` | string | | with --blank: frame size (default 1920x1080) |
|
|
198
|
+
| `--fps` | string | | with --blank: frame rate (default 30) |
|
|
199
|
+
| `--music` | string | | with --blank: music under it, measured for peaks and --beats |
|
|
190
200
|
| `--conform` | boolean | | a variable-frame-rate or HDR source is made into a constant-frame-rate, SDR BT.709 copy with ffmpeg-skill first (analyze.py --conform; the copy goes in --out-dir) and drawn on; without it such a source is refused |
|
|
191
201
|
| `--fast` | boolean | | preview-quality render |
|
|
192
202
|
| `--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) |
|
package/references/timeline.md
CHANGED
|
@@ -17,6 +17,8 @@ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay":
|
|
|
17
17
|
| `source.fps` | number | probe.py | composition fps = source fps |
|
|
18
18
|
| `source.width` / `height` | px | probe.py | composition size = source size |
|
|
19
19
|
| `source.has_video` / `has_audio` | bool | probe.py | |
|
|
20
|
+
| `source.blank` | bool (optional) | analyze.py `--blank` | `true` for a source-less run: no footage, the picture is the `background` option; `source.path` is the music (or null), `has_video` false |
|
|
21
|
+
| `blank` | object \| null (optional) | analyze.py `--blank` | `{duration, width, height, fps, music}`: the caller's length, size and rate (not measurements) and the music's `{path, name, duration, fingerprint}` or null. The music's peaks, beats and silences fill `peaks`, `beats`, `silences` and `speech`, cut at the blank's end |
|
|
20
22
|
| `scenes` | `[{start, end}]` | scenes.py | shot boundaries (one scene = whole file when skipped) |
|
|
21
23
|
| `silences` | `[[start, end]]` | silence.py `--list` | measured silent gaps |
|
|
22
24
|
| `speech` | `[[start, end]]` | silence.py `--list` | ranges kept between silences (with margin) |
|
|
@@ -29,6 +31,7 @@ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay":
|
|
|
29
31
|
| `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
32
|
| `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
33
|
| `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`) |
|
|
34
|
+
| `kinetic` | object \| null (optional) | analyze.py `--kinetic words\|beats\|auto` | the KineticType schedule: `{by, step, lines: [{cue, start, end, units: [{text, gap, start}]}]}`. One line per caption cue; a unit is a word (split at spaces) or, in text written without spaces (Japanese, Chinese), one character, punctuation staying with the one before. `start` is measured: the word's own time from `--words` (`by: words`), or the next measured beat from `--beats`, `step` beats apart (`by: beats`, `--kinetic-step`). `gap`: a space before the unit. A line shows from its first unit's start until `end` (its cue's end, later when the beats run past it, never into the next line). No measurement, no schedule: refused (`kind: input`) |
|
|
32
35
|
| `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 |
|
|
33
36
|
| `warnings` | `[string]` | analyze.py | rotation, odd frame rate, chapters, transcript (VFR and HDR are never warnings: conformed or refused) |
|
|
34
37
|
|
|
@@ -48,6 +51,7 @@ composition exactly.
|
|
|
48
51
|
| `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
52
|
| `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 |
|
|
50
53
|
| `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 |
|
|
54
|
+
| `KineticType` | source duration | the `kinetic` schedule: each line centred, its units (words, or CJK characters) entering at their measured starts -- invisible before that frame, visible on it, never reflowing the line; `kineticStyle` pop, wipe, tracking or rise; `kineticReveal: "char"` lets a unit's characters follow each other `kineticStagger` s apart. The current unit takes the accent colour. Needs `analyze.py --kinetic` |
|
|
51
55
|
| `BeatMontage` | source duration | audio unbroken; the picture cuts every `beatsPerCut` measured beats, cycling through highlights (or scenes); no usable grid → cuts on scene changes |
|
|
52
56
|
|
|
53
57
|
## Options (`--options look.json`)
|
|
@@ -76,6 +80,11 @@ Every key is optional.
|
|
|
76
80
|
| `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
81
|
| `bubbles` | `[]` | Emphasis: speech bubbles `[{"text", "start", "end", "side"?}]` (`side`: `left` or `right`), the user's text, seconds on the source timeline |
|
|
78
82
|
| `comments` | `[]` | Emphasis: comment-style cards `[{"text", "start", "end", "author"?}]`, top left, stacked while they overlap; the user's text |
|
|
83
|
+
| `background` | `"#000000"` | the picture of a source-less run (analyze.py `--blank`): any CSS colour or gradient |
|
|
84
|
+
| `kineticStyle` | `"pop"` | KineticType: how a unit enters: `pop` (scales down into place), `wipe` (a mask opens left to right), `tracking` (its characters close in), `rise` |
|
|
85
|
+
| `kineticReveal` | `"char"` | KineticType: `char` (characters one after another from the unit's start) or `unit` (the whole unit at its start) |
|
|
86
|
+
| `kineticStagger` | `0.04` | KineticType: seconds between characters with `kineticReveal: "char"`, 0–1 |
|
|
87
|
+
| `kineticSize` | `0.09` | KineticType: text size as a fraction of the frame's short side, 0.01–0.5 |
|
|
79
88
|
| `chapterSeconds` | `4` | Titled: how long a chapter card stays up (cut short by the next chapter; 0 = none) |
|
|
80
89
|
|
|
81
90
|
Unknown keys and wrong types are refused by render.py / still.py before anything renders.
|
package/scripts/_common.py
CHANGED
|
@@ -27,6 +27,8 @@ from fractions import Fraction
|
|
|
27
27
|
from pathlib import Path
|
|
28
28
|
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
29
29
|
|
|
30
|
+
from _kinetic import validate as validate_kinetic
|
|
31
|
+
|
|
30
32
|
HERE = Path(__file__).resolve().parent
|
|
31
33
|
ROOT = HERE.parent
|
|
32
34
|
SKILL_ID = "remotion-ffmpeg-skill"
|
|
@@ -257,6 +259,7 @@ def validate_timeline(t: Any) -> List[str]:
|
|
|
257
259
|
p.append(f"emphasis[{i}] needs start < end, text, its caption cue, the span of the text in that cue, "
|
|
258
260
|
"its word range and a style (pop, color, box or null) -- analyze.py --emphasis writes it")
|
|
259
261
|
break
|
|
262
|
+
p += validate_kinetic(t.get("kinetic"), len(caps))
|
|
260
263
|
for i, r in enumerate(t.get("speech", []) or []):
|
|
261
264
|
if not (isinstance(r, list) and len(r) == 2 and r[1] > r[0]):
|
|
262
265
|
p.append(f"speech[{i}] must be [start, end] with start < end")
|
|
@@ -334,7 +337,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
|
|
|
334
337
|
and render.py then only reports the measured numbers.
|
|
335
338
|
"""
|
|
336
339
|
fps = float(t["source"]["fps"])
|
|
337
|
-
if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip", "Emphasis"):
|
|
340
|
+
if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip", "Emphasis", "KineticType"):
|
|
338
341
|
return max(1, sec_to_frames(float(t["source"]["duration"]), fps))
|
|
339
342
|
if comp in ("Jumpcut", "Highlights"):
|
|
340
343
|
if comp == "Jumpcut":
|
|
@@ -349,7 +352,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
|
|
|
349
352
|
# ---------------------------------------------------------------- Remotion project
|
|
350
353
|
|
|
351
354
|
BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke", "Pip",
|
|
352
|
-
"Emphasis")
|
|
355
|
+
"Emphasis", "KineticType")
|
|
353
356
|
|
|
354
357
|
|
|
355
358
|
def remotion_bin(project: Path) -> Path:
|
|
@@ -674,7 +677,8 @@ _OPTION_TYPES: Dict[str, Any] = {
|
|
|
674
677
|
"progressBar": bool, "driver": str, "lowerThirds": list, "sceneTitles": list,
|
|
675
678
|
"title": (str, type(None)), "beatsPerCut": int, "chapterSeconds": (int, float),
|
|
676
679
|
"pipCorner": str, "pipSize": (int, float), "pipShape": str, "pipAudio": bool,
|
|
677
|
-
"emphasisStyle": str, "bubbles": list, "comments": list,
|
|
680
|
+
"emphasisStyle": str, "bubbles": list, "comments": list, "background": str,
|
|
681
|
+
"kineticStyle": str, "kineticReveal": str, "kineticStagger": (int, float), "kineticSize": (int, float),
|
|
678
682
|
}
|
|
679
683
|
|
|
680
684
|
|
|
@@ -707,6 +711,16 @@ def validate_options(o: Dict[str, Any]) -> List[str]:
|
|
|
707
711
|
if isinstance(o.get("pipSize"), (int, float)) and not isinstance(o["pipSize"], bool) \
|
|
708
712
|
and not 0.05 <= o["pipSize"] <= 0.6:
|
|
709
713
|
p.append("pipSize must be between 0.05 and 0.6 (a fraction of the frame width)")
|
|
714
|
+
if "kineticStyle" in o and o["kineticStyle"] not in ("pop", "wipe", "tracking", "rise"):
|
|
715
|
+
p.append("kineticStyle must be pop, wipe, tracking or rise")
|
|
716
|
+
if "kineticReveal" in o and o["kineticReveal"] not in ("unit", "char"):
|
|
717
|
+
p.append("kineticReveal must be unit or char")
|
|
718
|
+
if isinstance(o.get("kineticStagger"), (int, float)) and not isinstance(o["kineticStagger"], bool) \
|
|
719
|
+
and not 0 <= o["kineticStagger"] <= 1:
|
|
720
|
+
p.append("kineticStagger must be between 0 and 1 second")
|
|
721
|
+
if isinstance(o.get("kineticSize"), (int, float)) and not isinstance(o["kineticSize"], bool) \
|
|
722
|
+
and not 0.01 <= o["kineticSize"] <= 0.5:
|
|
723
|
+
p.append("kineticSize must be between 0.01 and 0.5 (a fraction of the frame's short side)")
|
|
710
724
|
if "emphasisStyle" in o and o["emphasisStyle"] not in ("pop", "color", "box"):
|
|
711
725
|
p.append("emphasisStyle must be pop, color or box")
|
|
712
726
|
for key, extra in (("bubbles", "side"), ("comments", "author")):
|
|
@@ -727,5 +741,23 @@ def validate_options(o: Dict[str, Any]) -> List[str]:
|
|
|
727
741
|
return p
|
|
728
742
|
|
|
729
743
|
|
|
744
|
+
NO_INPUT = "-"
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def parse_with_blank(parser: argparse.ArgumentParser, argv: Optional[List[str]] = None) -> argparse.Namespace:
|
|
748
|
+
"""Parse argv for analyze.py / pipeline.py. Their `input` takes one or more files (the contract's minItems 1);
|
|
749
|
+
a source-less run (--blank) has none: on the command line it may simply be left out, and `-` (NO_INPUT) is the
|
|
750
|
+
placeholder a caller that must send at least one item (an MCP client) gives instead. Either way the
|
|
751
|
+
namespace's `input` is then the real files only."""
|
|
752
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
753
|
+
if any(x == "--blank" or x.startswith("--blank=") for x in argv):
|
|
754
|
+
for act in parser._actions:
|
|
755
|
+
if act.dest == "input":
|
|
756
|
+
act.nargs = "*"
|
|
757
|
+
a = parser.parse_args(argv)
|
|
758
|
+
a.input = [i for i in (a.input or []) if i != NO_INPUT]
|
|
759
|
+
return a
|
|
760
|
+
|
|
761
|
+
|
|
730
762
|
def now() -> float:
|
|
731
763
|
return time.monotonic()
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The KineticType schedule (internal module, not a tool): when each word (or CJK character) of the caption
|
|
3
|
+
cues starts, from a measurement only -- the speech engine's word timings (analyze.py --words) or the measured
|
|
4
|
+
beat grid (analyze.py --beats). analyze.py --kinetic writes it into the timeline as `kinetic`; the composition
|
|
5
|
+
draws it and computes no time of its own, so the frame a unit starts on is round(start * fps) on both sides.
|
|
6
|
+
|
|
7
|
+
Kinetic typography with no measured timing belongs to hyperframes-skill (Velisa ownership decisions O17), so
|
|
8
|
+
there is no fallback to evenly spread or guessed times: no usable measurement, no schedule.
|
|
9
|
+
"""
|
|
10
|
+
import re
|
|
11
|
+
import unicodedata
|
|
12
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
13
|
+
|
|
14
|
+
KINETIC_TIMINGS = ("auto", "words", "beats")
|
|
15
|
+
# A character that is never a unit of its own: it stays with the character before it.
|
|
16
|
+
_ATTACH = set("、。,.・:;!?!?,.)])」』】〉》〕”’ー〜ゝゞヽヾ")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class KineticError(ValueError):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _is_cjk(ch: str) -> bool:
|
|
24
|
+
o = ord(ch)
|
|
25
|
+
return (0x3040 <= o <= 0x30FF or 0x3400 <= o <= 0x4DBF or 0x4E00 <= o <= 0x9FFF or 0xAC00 <= o <= 0xD7AF
|
|
26
|
+
or 0xF900 <= o <= 0xFAFF or 0xFF66 <= o <= 0xFF9F)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def split_units(text: str) -> List[Tuple[str, bool]]:
|
|
30
|
+
"""A cue's text as (unit, space before it): words split at whitespace; a run of CJK characters (written
|
|
31
|
+
without spaces) is one unit per character, punctuation and the long-vowel mark staying with the character
|
|
32
|
+
before. The text itself is never changed: joining the units (a space where marked) gives it back, apart
|
|
33
|
+
from runs of whitespace, which become one space."""
|
|
34
|
+
out: List[Tuple[str, bool]] = []
|
|
35
|
+
for ti, tok in enumerate(t for t in re.split(r"\s+", unicodedata.normalize("NFC", text)) if t):
|
|
36
|
+
gap = ti > 0
|
|
37
|
+
if not any(_is_cjk(ch) for ch in tok):
|
|
38
|
+
out.append((tok, gap))
|
|
39
|
+
continue
|
|
40
|
+
buf = ""
|
|
41
|
+
for ch in tok:
|
|
42
|
+
latin_run = buf and not _is_cjk(ch) and not _is_cjk(buf[-1]) and ch not in _ATTACH
|
|
43
|
+
if buf and (ch in _ATTACH or latin_run):
|
|
44
|
+
buf += ch
|
|
45
|
+
continue
|
|
46
|
+
if buf:
|
|
47
|
+
out.append((buf, gap))
|
|
48
|
+
gap = False
|
|
49
|
+
buf = ch
|
|
50
|
+
if buf:
|
|
51
|
+
out.append((buf, gap))
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _cue_words(cue: Dict[str, Any], words: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
56
|
+
"""The timed words of a cue: their midpoint falls inside it (as the Karaoke composition takes them)."""
|
|
57
|
+
return [w for w in words if cue["start"] <= (w["start"] + w["end"]) / 2 <= cue["end"]]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def schedule(captions: List[Dict[str, Any]], words: List[Dict[str, Any]], beats: Optional[Dict[str, Any]],
|
|
61
|
+
timing: str = "auto", step: int = 1, duration: Optional[float] = None) -> Dict[str, Any]:
|
|
62
|
+
"""{by, step, lines, warnings}: one line per caption cue, `units` = [{text, gap, start}] in order, `start` the
|
|
63
|
+
measured time the unit first shows; `start`/`end` of the line = its first unit's start and the time it clears
|
|
64
|
+
(the cue's end, or later when the beats run past it -- a warning says so)."""
|
|
65
|
+
if timing not in KINETIC_TIMINGS:
|
|
66
|
+
raise KineticError(f"--kinetic must be one of {', '.join(KINETIC_TIMINGS)}, got {timing!r}")
|
|
67
|
+
if step < 1:
|
|
68
|
+
raise KineticError("--kinetic-step must be at least 1 beat per unit")
|
|
69
|
+
if not captions:
|
|
70
|
+
raise KineticError("--kinetic needs text: caption cues from --captions (a lyric SRT) or --words")
|
|
71
|
+
beat_times = sorted(float(b) for b in ((beats or {}).get("times") or [])) if (beats or {}).get("usable") else []
|
|
72
|
+
if timing == "auto":
|
|
73
|
+
timing = "words" if words else "beats"
|
|
74
|
+
if timing == "words" and not words:
|
|
75
|
+
raise KineticError("--kinetic words needs word timings (--words): every word starts at the time the "
|
|
76
|
+
"speech engine measured")
|
|
77
|
+
if timing == "beats" and not beat_times:
|
|
78
|
+
why = "was not measured (add --beats)" if not beats else "is not usable (too little confidence)"
|
|
79
|
+
raise KineticError(f"--kinetic beats needs the measured beat grid, which {why}; kinetic type from no "
|
|
80
|
+
"measurement is hyperframes-skill's")
|
|
81
|
+
lines: List[Dict[str, Any]] = []
|
|
82
|
+
warnings: List[str] = []
|
|
83
|
+
bi = 0 # next beat a unit may take (beats are used in order, each by one unit at most)
|
|
84
|
+
for ci, cue in enumerate(captions):
|
|
85
|
+
if timing == "words":
|
|
86
|
+
own = _cue_words(cue, words)
|
|
87
|
+
if not own:
|
|
88
|
+
warnings.append(f"kinetic: cue {ci + 1} ({cue['text'][:24]!r}) has no timed words and is not drawn")
|
|
89
|
+
continue
|
|
90
|
+
units = []
|
|
91
|
+
for wi, w in enumerate(own):
|
|
92
|
+
raw = str(w["text"])
|
|
93
|
+
# a word the engine timed is one unit, its spacing the engine's own (a leading space)
|
|
94
|
+
units.append({"text": raw.strip(), "gap": wi > 0 and raw[:1].isspace(),
|
|
95
|
+
"start": round(float(w["start"]), 3)})
|
|
96
|
+
units = [u for u in units if u["text"]]
|
|
97
|
+
else:
|
|
98
|
+
parts = split_units(cue["text"])
|
|
99
|
+
while bi < len(beat_times) and beat_times[bi] < cue["start"] - 1e-6:
|
|
100
|
+
bi += 1
|
|
101
|
+
units = []
|
|
102
|
+
for text, gap in parts:
|
|
103
|
+
if bi >= len(beat_times):
|
|
104
|
+
break
|
|
105
|
+
units.append({"text": text, "gap": gap, "start": round(beat_times[bi], 3)})
|
|
106
|
+
bi += step
|
|
107
|
+
if len(units) < len(parts):
|
|
108
|
+
warnings.append(f"kinetic: cue {ci + 1} ({cue['text'][:24]!r}): the measured beats ran out after "
|
|
109
|
+
f"{len(units)} of {len(parts)} units; the rest is not drawn")
|
|
110
|
+
if not units:
|
|
111
|
+
continue
|
|
112
|
+
end = max(float(cue["end"]), units[-1]["start"] + 0.25)
|
|
113
|
+
if timing == "beats" and units[-1]["start"] >= cue["end"]:
|
|
114
|
+
warnings.append(f"kinetic: cue {ci + 1} ({cue['text'][:24]!r}) needs beats up to "
|
|
115
|
+
f"{units[-1]['start']:.3f} s, past its end {cue['end']:.3f} s: it stays up until then")
|
|
116
|
+
if duration is not None:
|
|
117
|
+
end = min(end, duration)
|
|
118
|
+
lines.append({"cue": ci, "start": units[0]["start"], "end": round(end, 3), "units": units})
|
|
119
|
+
# a line clears when the next one starts, so two lines never overlap
|
|
120
|
+
for a, b in zip(lines, lines[1:]):
|
|
121
|
+
if a["end"] > b["start"]:
|
|
122
|
+
a["end"] = b["start"]
|
|
123
|
+
if not lines:
|
|
124
|
+
raise KineticError("--kinetic: no caption cue could be timed")
|
|
125
|
+
return {"by": timing, "step": step if timing == "beats" else None, "lines": lines, "warnings": warnings}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def validate(k: Any, n_captions: int) -> List[str]:
|
|
129
|
+
if k is None:
|
|
130
|
+
return []
|
|
131
|
+
ok = isinstance(k, dict) and k.get("by") in ("words", "beats") and isinstance(k.get("lines"), list)
|
|
132
|
+
for ln in (k.get("lines") if ok else []):
|
|
133
|
+
ok = ok and isinstance(ln, dict) and isinstance(ln.get("cue"), int) and 0 <= ln["cue"] < n_captions \
|
|
134
|
+
and isinstance(ln.get("units"), list) and ln["units"] and isinstance(ln.get("end"), (int, float))
|
|
135
|
+
for u in (ln.get("units") if ok else []):
|
|
136
|
+
ok = ok and isinstance(u, dict) and isinstance(u.get("text"), str) and u["text"] \
|
|
137
|
+
and isinstance(u.get("start"), (int, float)) and isinstance(u.get("gap"), bool)
|
|
138
|
+
return [] if ok else ["kinetic must be {by: words|beats, lines: [{cue, start, end, units: [{text, gap, start}]}]} "
|
|
139
|
+
"-- analyze.py --kinetic writes it"]
|
package/scripts/analyze.py
CHANGED
|
@@ -21,9 +21,12 @@ Examples:
|
|
|
21
21
|
python3 analyze.py talk.mp4 --words talk.transcript.json # captions from a transcription-skill transcript
|
|
22
22
|
python3 analyze.py talk.mp4 --words talk.transcript.json --emphasis words.json # Emphasis composition
|
|
23
23
|
python3 analyze.py phone_hdr.mov --conform # VFR / HDR: measure and draw on a CFR SDR copy
|
|
24
|
+
python3 analyze.py --blank 15 --size 1080x1920 --music bgm.wav --beats # no footage: a 15 s blank timeline
|
|
25
|
+
python3 analyze.py --blank 15 --music song.wav --beats --captions lyrics.srt --kinetic beats # KineticType
|
|
24
26
|
"""
|
|
25
27
|
import argparse
|
|
26
28
|
import hashlib
|
|
29
|
+
import os
|
|
27
30
|
import shutil
|
|
28
31
|
import sys
|
|
29
32
|
import tempfile
|
|
@@ -34,7 +37,8 @@ from typing import Any, Dict, List, Optional, Tuple
|
|
|
34
37
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
35
38
|
from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
|
|
36
39
|
emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
|
|
37
|
-
require_ffmpeg_skill, shell_join, stream_rate, version)
|
|
40
|
+
exact_rate, require_ffmpeg_skill, shell_join, stream_rate, version, parse_with_blank)
|
|
41
|
+
from _kinetic import KINETIC_TIMINGS, KineticError, schedule as kinetic_schedule
|
|
38
42
|
from _captions import (CaptionError, cues_from_words, parse_chapters, read_captions, read_emphasis,
|
|
39
43
|
read_word_timings, resolve_emphasis, youtube_chapter_warnings)
|
|
40
44
|
|
|
@@ -54,7 +58,8 @@ def file_fingerprint(path: Path) -> str:
|
|
|
54
58
|
def build_parser() -> argparse.ArgumentParser:
|
|
55
59
|
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
|
|
56
60
|
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
|
|
57
|
-
p.add_argument("input", nargs="+", help="source video (or audio) file; several are joined in order first"
|
|
61
|
+
p.add_argument("input", nargs="+", help="source video (or audio) file; several are joined in order first "
|
|
62
|
+
"(with --blank: none, or `-`)")
|
|
58
63
|
p.add_argument("--joined", help="with several inputs: where the joined source goes (default: <first>_joined.mp4)")
|
|
59
64
|
p.add_argument("--join-transition", default="none",
|
|
60
65
|
help="with several inputs: ffmpeg-skill join.py --transition (default none = straight cuts)")
|
|
@@ -93,7 +98,23 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
93
98
|
p.add_argument("--conform-fps", type=float, metavar="FPS",
|
|
94
99
|
help="with --conform: the constant frame rate for a VFR source (default: the stream's base rate, "
|
|
95
100
|
"r_frame_rate, so no frame is dropped)")
|
|
101
|
+
p.add_argument("--blank", type=float, metavar="SECONDS",
|
|
102
|
+
help="a source-less run: a timeline of this many seconds with no footage (a plain background), "
|
|
103
|
+
"so a composition draws from nothing. With --music the music plays under it and is measured "
|
|
104
|
+
"for peaks (and --beats) as a source's audio is; no input file is given")
|
|
105
|
+
p.add_argument("--size", metavar="WxH", help="with --blank: the frame size in px, even numbers (default 1920x1080)")
|
|
106
|
+
p.add_argument("--fps", metavar="RATE", help="with --blank: the frame rate, e.g. 30, 25, 30000/1001 (default 30)")
|
|
107
|
+
p.add_argument("--music", metavar="FILE",
|
|
108
|
+
help="with --blank: the music (any file with an audio stream) that plays under the blank timeline "
|
|
109
|
+
"from 0 s; measured with ffmpeg-skill (scenes.py peaks and --beats, silence.py). Cut at the "
|
|
110
|
+
"blank's end when longer, silence after it when shorter")
|
|
96
111
|
p.add_argument("--beats", action="store_true", help="also measure the beat grid (scenes.py --beats)")
|
|
112
|
+
p.add_argument("--kinetic", choices=KINETIC_TIMINGS, metavar="TIMING",
|
|
113
|
+
help="schedule the caption cues' words for the KineticType composition: `words` (each word at "
|
|
114
|
+
"the time --words measured), `beats` (each word, or CJK character, on the next measured "
|
|
115
|
+
"beat; needs --beats) or `auto` (words when given, else beats). Never from unmeasured times")
|
|
116
|
+
p.add_argument("--kinetic-step", type=int, default=1, metavar="N",
|
|
117
|
+
help="with --kinetic beats: measured beats per word (default 1)")
|
|
97
118
|
p.add_argument("--highlights", type=int, metavar="N",
|
|
98
119
|
help="also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition")
|
|
99
120
|
p.add_argument("--target", type=float, metavar="SECONDS", help="with --highlights: total length the picks add up to")
|
|
@@ -272,25 +293,207 @@ def conform_source(label: str, src: Path, probe: Dict[str, Any], out: Path, fps:
|
|
|
272
293
|
return out, after, record
|
|
273
294
|
|
|
274
295
|
|
|
275
|
-
def
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
296
|
+
def kinetic_for(a: argparse.Namespace, captions: List[Dict[str, Any]], words: List[Dict[str, Any]], beats: Any,
|
|
297
|
+
duration: float) -> Tuple[Optional[Dict[str, Any]], List[str]]:
|
|
298
|
+
"""The KineticType schedule (scripts/_kinetic.py) when --kinetic was given, and its warnings."""
|
|
299
|
+
if a.kinetic is None:
|
|
300
|
+
if a.kinetic_step != 1:
|
|
301
|
+
die("--kinetic-step needs --kinetic", "input")
|
|
302
|
+
return None, []
|
|
303
|
+
try:
|
|
304
|
+
k = kinetic_schedule(captions, words, beats, a.kinetic, a.kinetic_step, duration)
|
|
305
|
+
except KineticError as e:
|
|
306
|
+
die(str(e), "input")
|
|
307
|
+
return {key: k[key] for key in ("by", "step", "lines")}, k["warnings"]
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
# ---------------------------------------------------------------- source-less runs (--blank)
|
|
311
|
+
|
|
312
|
+
BLANK_MAX_SECONDS = 24 * 3600.0
|
|
313
|
+
# Flags that only mean something with footage: refused with --blank instead of silently doing nothing.
|
|
314
|
+
BLANK_REFUSES = (("joined", "--joined"), ("pip", "--pip"), ("pip_offset", "--pip-offset"), ("conform", "--conform"),
|
|
315
|
+
("conformed", "--conformed"), ("conform_fps", "--conform-fps"), ("highlights", "--highlights"),
|
|
316
|
+
("target", "--target"))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def parse_size(spec: Optional[str]) -> Tuple[int, int]:
|
|
320
|
+
"""`WxH` -> (W, H): positive even integers (H.264 needs even sides), at most 8192."""
|
|
321
|
+
if spec is None:
|
|
322
|
+
return 1920, 1080
|
|
323
|
+
parts = str(spec).lower().replace("×", "x").split("x")
|
|
324
|
+
try:
|
|
325
|
+
w, h = (int(x) for x in parts)
|
|
326
|
+
except ValueError:
|
|
327
|
+
die(f"--size must look like 1080x1920, got {spec!r}", "input")
|
|
328
|
+
if not (16 <= w <= 8192 and 16 <= h <= 8192) or w % 2 or h % 2:
|
|
329
|
+
die(f"--size {spec}: both sides must be even numbers between 16 and 8192 px", "input")
|
|
330
|
+
return w, h
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def parse_fps(spec: Optional[str]) -> float:
|
|
334
|
+
if spec is None:
|
|
335
|
+
return 30.0
|
|
336
|
+
r = exact_rate(spec)
|
|
337
|
+
if r is None or not 1 <= r <= 240:
|
|
338
|
+
die(f"--fps must be a frame rate between 1 and 240 (30, 25, 29.97, 30000/1001), got {spec!r}", "input")
|
|
339
|
+
return float(r)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def blank_flags_check(a: argparse.Namespace) -> None:
|
|
343
|
+
if a.blank is None:
|
|
344
|
+
given = [f for f, v in (("--size", a.size), ("--fps", a.fps), ("--music", a.music)) if v is not None]
|
|
345
|
+
if given:
|
|
346
|
+
die(f"{', '.join(given)} {'needs' if len(given) == 1 else 'need'} --blank SECONDS (a source's own size, rate and audio are measured)", "input")
|
|
347
|
+
if not a.input:
|
|
348
|
+
die("give an input file, or --blank SECONDS for a timeline with no footage", "input")
|
|
349
|
+
return
|
|
350
|
+
if a.input:
|
|
351
|
+
die("--blank makes a timeline with no footage: give no input file (the music goes in --music)", "input")
|
|
352
|
+
if not (0.001 <= a.blank <= BLANK_MAX_SECONDS):
|
|
353
|
+
die(f"--blank must be at least 0.001 and at most {BLANK_MAX_SECONDS:g} seconds, got {a.blank:g}", "input")
|
|
354
|
+
bad = [flag for dest, flag in BLANK_REFUSES if getattr(a, dest, None) not in (None, False)]
|
|
355
|
+
if a.chapters == "source":
|
|
356
|
+
bad.append("--chapters source")
|
|
357
|
+
if bad:
|
|
358
|
+
die(f"{', '.join(bad)} {'needs' if len(bad) == 1 else 'need'} footage; --blank has none", "input")
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def blank_main(a: argparse.Namespace) -> None:
|
|
362
|
+
"""A timeline with no footage: the given size, rate and length, and the music measured as a source's audio is."""
|
|
363
|
+
width, height = parse_size(a.size)
|
|
364
|
+
fps = parse_fps(a.fps)
|
|
365
|
+
duration = round(float(a.blank), 3)
|
|
366
|
+
music = Path(a.music).expanduser() if a.music else None
|
|
367
|
+
if music is not None and not music.is_file():
|
|
368
|
+
die(f"--music not found: {music}", "input")
|
|
369
|
+
if a.output:
|
|
370
|
+
out = Path(a.output).expanduser()
|
|
371
|
+
else:
|
|
372
|
+
out = default_output(music, "_blank.timeline", ".json") if music else Path("blank.timeline.json")
|
|
373
|
+
if music is not None and (out.resolve() == music.resolve() or (out.exists() and os.path.samefile(out, music))):
|
|
374
|
+
die(f"-o {out} is the --music file itself: the original is never overwritten", "input")
|
|
285
375
|
refuse_existing(out)
|
|
286
|
-
if (a.conformed or a.conform_fps is not None) and not a.conform:
|
|
287
|
-
die("--conformed / --conform-fps need --conform", "input")
|
|
288
|
-
if a.conform_fps is not None and not 0 < a.conform_fps <= 240:
|
|
289
|
-
die(f"--conform-fps must be between 0 and 240, got {a.conform_fps:g}", "input")
|
|
290
|
-
conformed: Path = (Path(a.conformed).expanduser() if a.conformed
|
|
291
|
-
else default_output(joined if len(inputs) > 1 else src, "_conformed", ".mp4"))
|
|
292
376
|
skill = require_ffmpeg_skill()
|
|
377
|
+
captions, words, transcript, emphasis, emphasis_warnings = read_text_inputs(a)
|
|
378
|
+
|
|
379
|
+
plan = []
|
|
380
|
+
if music is not None:
|
|
381
|
+
plan.append(shell_join(ffskill_cmd("probe", [str(music)])))
|
|
382
|
+
if not a.no_scenes:
|
|
383
|
+
plan.append(shell_join(ffskill_cmd("scenes", [str(music), *(["--beats"] if a.beats else [])])))
|
|
384
|
+
if not a.no_silence:
|
|
385
|
+
plan.append(shell_join(ffskill_cmd("silence", [str(music), *silence_args(a)])))
|
|
386
|
+
if STATE.dry_run:
|
|
387
|
+
emit({"output": str(out), "commands": plan}, f"would write {out} (blank {duration:g} s, {width}x{height} at "
|
|
388
|
+
f"{fps:g} fps{', music ' + music.name if music else ''}) after {len(plan)} ffmpeg-skill steps")
|
|
389
|
+
return
|
|
390
|
+
|
|
391
|
+
commands: List[str] = []
|
|
392
|
+
warnings: List[str] = []
|
|
393
|
+
peaks: List[Dict[str, float]] = []
|
|
394
|
+
beats: Any = None
|
|
395
|
+
silences: List[List[float]] = []
|
|
396
|
+
speech: List[List[float]] = [[0.0, duration]]
|
|
397
|
+
music_rec: Optional[Dict[str, Any]] = None
|
|
398
|
+
if music is not None:
|
|
399
|
+
pr = ffskill("probe", [str(music)])
|
|
400
|
+
commands.append(pr["_command"])
|
|
401
|
+
if not pr.get("audio"):
|
|
402
|
+
die(f"--music {music.name} has no audio stream", "input")
|
|
403
|
+
mdur = float((pr.get("audio") or {}).get("duration") or pr.get("duration") or 0)
|
|
404
|
+
if mdur <= 0:
|
|
405
|
+
die(f"--music {music.name} has no measurable duration", "input")
|
|
406
|
+
music_rec = {"path": str(music.resolve()), "name": music.name, "duration": round(mdur, 3),
|
|
407
|
+
"fingerprint": file_fingerprint(music)}
|
|
408
|
+
if mdur < duration - 0.05:
|
|
409
|
+
warnings.append(f"--music {music.name} is {mdur:.3f} s, the blank {duration:g} s: silence after "
|
|
410
|
+
f"{mdur:.3f} s")
|
|
411
|
+
elif mdur > duration + 0.05:
|
|
412
|
+
warnings.append(f"--music {music.name} is {mdur:.3f} s: cut at the blank's end ({duration:g} s)")
|
|
413
|
+
if not a.no_scenes:
|
|
414
|
+
# ffmpeg-skill 3.2.0 and later measure an audio-only file: peaks, and the beat grid with --beats.
|
|
415
|
+
sc = ffskill("scenes", [str(music), *(["--beats"] if a.beats else [])])
|
|
416
|
+
commands.append(sc["_command"])
|
|
417
|
+
peaks = [pk for pk in ({"time": round(float(p["time"]), 3), "rms": float(p.get("rms", 0))}
|
|
418
|
+
for p in sc.get("audio_peaks", [])) if pk["time"] < duration]
|
|
419
|
+
if a.beats:
|
|
420
|
+
grid = sc.get("beat_grid") or {}
|
|
421
|
+
times = [t for t in (round(float(b), 3) for b in (sc.get("beats") or [])) if t < duration]
|
|
422
|
+
beats = {"times": times, "tempo_bpm": grid.get("tempo_bpm"), "confidence": grid.get("confidence"),
|
|
423
|
+
"usable": bool(grid.get("usable")) and bool(times)}
|
|
424
|
+
if not a.no_silence:
|
|
425
|
+
si = ffskill("silence", [str(music), *silence_args(a)])
|
|
426
|
+
commands.append(si["_command"])
|
|
427
|
+
clip = lambda r: [round(min(float(r[0]), duration), 3), round(min(float(r[1]), duration), 3)] # noqa: E731
|
|
428
|
+
silences = [c for c in map(clip, si.get("silences", [])) if c[1] > c[0]]
|
|
429
|
+
if mdur < duration - 0.05:
|
|
430
|
+
silences.append([round(mdur, 3), duration])
|
|
431
|
+
speech = [c for c in map(clip, si.get("keep", [])) if c[1] > c[0]] or speech
|
|
432
|
+
|
|
433
|
+
if transcript:
|
|
434
|
+
ref = music_rec or {}
|
|
435
|
+
if not ref:
|
|
436
|
+
warnings.append("--words: a transcript with no --music: its times are used as written on the blank")
|
|
437
|
+
elif abs(transcript["duration"] - ref["duration"]) > TRANSCRIPT_DURATION_TOLERANCE:
|
|
438
|
+
die(f"--words: the transcript is of a {transcript['duration']:.3f} s file ({transcript['filename']}), "
|
|
439
|
+
f"the music measures {ref['duration']:.3f} s; transcribe this music", "input")
|
|
440
|
+
elif transcript["fingerprint"] != ref["fingerprint"]:
|
|
441
|
+
warnings.append(f"--words: the transcript was made from {transcript['filename']}, not these exact bytes "
|
|
442
|
+
"(same length, so its times are used as written)")
|
|
443
|
+
warnings += transcript["warnings"]
|
|
444
|
+
late = [c for c in captions if c["start"] >= duration]
|
|
445
|
+
if late:
|
|
446
|
+
warnings.append(f"{len(late)} caption cue(s) start at or after the blank's end ({duration:g} s) and never show")
|
|
447
|
+
|
|
448
|
+
chapters: List[Dict[str, Any]] = []
|
|
449
|
+
if a.chapters:
|
|
450
|
+
chpath = Path(a.chapters).expanduser()
|
|
451
|
+
if not chpath.is_file():
|
|
452
|
+
die(f"chapters file not found: {chpath}", "input")
|
|
453
|
+
try:
|
|
454
|
+
chapters = parse_chapters(chpath.read_text(encoding="utf-8-sig"), duration)
|
|
455
|
+
except CaptionError as e:
|
|
456
|
+
die(f"{chpath}: {e}", "input")
|
|
457
|
+
|
|
458
|
+
kinetic, kinetic_warnings = kinetic_for(a, captions, words, beats, duration)
|
|
459
|
+
warnings += kinetic_warnings
|
|
460
|
+
timeline: Dict[str, Any] = {
|
|
461
|
+
"schema": TIMELINE_SCHEMA,
|
|
462
|
+
"generator": {"name": SKILL_ID, "version": version(), "ffmpeg_skill": ffmpeg_skill_version(skill)},
|
|
463
|
+
# No footage: the picture is the composition's own background; the music (if any) is the source's audio.
|
|
464
|
+
"source": {"path": music_rec["path"] if music_rec else None,
|
|
465
|
+
"name": music.name if music else "blank", "duration": duration, "fps": fps,
|
|
466
|
+
"width": width, "height": height, "has_video": False, "has_audio": bool(music_rec),
|
|
467
|
+
"blank": True},
|
|
468
|
+
"blank": {"duration": duration, "width": width, "height": height, "fps": fps, "music": music_rec},
|
|
469
|
+
"scenes": [{"start": 0.0, "end": duration}],
|
|
470
|
+
"silences": silences, "speech": speech, "peaks": peaks, "beats": beats, "highlights": [], "clips": [],
|
|
471
|
+
"captions": captions, "words": words, "emphasis": emphasis, "chapters": chapters, "pip": None,
|
|
472
|
+
"kinetic": kinetic, "conform": None,
|
|
473
|
+
"warnings": warnings + (youtube_chapter_warnings(chapters) if chapters else []) + emphasis_warnings,
|
|
474
|
+
}
|
|
475
|
+
for w in timeline["warnings"]:
|
|
476
|
+
info(f"warning: {w}")
|
|
477
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
478
|
+
import json
|
|
479
|
+
out.write_text(json.dumps(timeline, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
480
|
+
emit({"output": str(out), "commands": commands, "verified": True,
|
|
481
|
+
"summary": {"duration": duration, "fps": fps, "size": f"{width}x{height}", "scenes": 1,
|
|
482
|
+
"silences": len(silences), "speech_seconds": round(sum(e - s for s, e in speech), 3),
|
|
483
|
+
"peaks": len(peaks), "captions": len(captions), "chapters": len(chapters), "pip_offset": None,
|
|
484
|
+
"beats": bool(beats and beats.get("usable")), "tempo_bpm": (beats or {}).get("tempo_bpm"),
|
|
485
|
+
"highlights": 0, "clips": 1, "words": len(words), "emphasis": len(emphasis), "conformed": [],
|
|
486
|
+
"blank": True, "music": music.name if music else None,
|
|
487
|
+
"kinetic": sum(len(ln["units"]) for ln in kinetic["lines"]) if kinetic else 0},
|
|
488
|
+
"warnings": timeline["warnings"]},
|
|
489
|
+
f"wrote {out}: blank {duration:g} s, {width}x{height} at {fps:g} fps, "
|
|
490
|
+
+ (f"music {music.name} ({len(peaks)} peaks" + (f", {len((beats or {}).get('times') or [])} beats" if beats else "")
|
|
491
|
+
+ ")" if music else "no music") + f", {len(captions)} captions")
|
|
293
492
|
|
|
493
|
+
|
|
494
|
+
def read_text_inputs(a: argparse.Namespace) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], Optional[Dict[str, Any]],
|
|
495
|
+
List[Dict[str, Any]], List[str]]:
|
|
496
|
+
"""--captions, --words and --emphasis: (captions, words, transcript or None, emphasis, emphasis warnings)."""
|
|
294
497
|
captions: List[Dict[str, Any]] = []
|
|
295
498
|
if a.captions:
|
|
296
499
|
cpath = Path(a.captions).expanduser()
|
|
@@ -336,6 +539,33 @@ def main() -> None:
|
|
|
336
539
|
emphasis, emphasis_warnings = resolve_emphasis(captions, words, entries, auto)
|
|
337
540
|
except (CaptionError, ValueError) as e:
|
|
338
541
|
die(f"--emphasis: {e}", "input")
|
|
542
|
+
return captions, words, transcript, emphasis, emphasis_warnings
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def main() -> None:
|
|
546
|
+
a = parse_with_blank(build_parser())
|
|
547
|
+
apply_common(a)
|
|
548
|
+
blank_flags_check(a)
|
|
549
|
+
if a.blank is not None:
|
|
550
|
+
blank_main(a)
|
|
551
|
+
return
|
|
552
|
+
inputs = [Path(i).expanduser() for i in a.input]
|
|
553
|
+
missing = [str(i) for i in inputs if not i.is_file()]
|
|
554
|
+
if missing:
|
|
555
|
+
die(f"input not found: {', '.join(missing)}", "input")
|
|
556
|
+
src = inputs[0]
|
|
557
|
+
joined: Path = Path(a.joined).expanduser() if a.joined else default_output(src, "_joined", ".mp4")
|
|
558
|
+
out = Path(a.output) if a.output else default_output(joined if len(inputs) > 1 else src, ".timeline", ".json")
|
|
559
|
+
refuse_existing(out)
|
|
560
|
+
if (a.conformed or a.conform_fps is not None) and not a.conform:
|
|
561
|
+
die("--conformed / --conform-fps need --conform", "input")
|
|
562
|
+
if a.conform_fps is not None and not 0 < a.conform_fps <= 240:
|
|
563
|
+
die(f"--conform-fps must be between 0 and 240, got {a.conform_fps:g}", "input")
|
|
564
|
+
conformed: Path = (Path(a.conformed).expanduser() if a.conformed
|
|
565
|
+
else default_output(joined if len(inputs) > 1 else src, "_conformed", ".mp4"))
|
|
566
|
+
skill = require_ffmpeg_skill()
|
|
567
|
+
|
|
568
|
+
captions, words, transcript, emphasis, emphasis_warnings = read_text_inputs(a)
|
|
339
569
|
|
|
340
570
|
join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
|
|
341
571
|
"--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
|
|
@@ -505,6 +735,7 @@ def main() -> None:
|
|
|
505
735
|
if pip["offset"] >= duration or pip["offset"] + pip["duration"] <= 0:
|
|
506
736
|
die(f"--pip: with an offset of {pip['offset']:g} s the camera never overlaps the source", "input")
|
|
507
737
|
|
|
738
|
+
kinetic, kinetic_warnings = kinetic_for(a, captions, words, beats, duration)
|
|
508
739
|
v = video or {}
|
|
509
740
|
timeline: Dict[str, Any] = {
|
|
510
741
|
"schema": TIMELINE_SCHEMA,
|
|
@@ -532,10 +763,12 @@ def main() -> None:
|
|
|
532
763
|
"emphasis": emphasis,
|
|
533
764
|
"chapters": chapters,
|
|
534
765
|
"pip": pip,
|
|
766
|
+
# The KineticType schedule (--kinetic): when each word or CJK character starts, from words or beats.
|
|
767
|
+
"kinetic": kinetic,
|
|
535
768
|
# Provenance of a conformed source (--conform): the original, each ffmpeg-skill step, the measured copy.
|
|
536
769
|
"conform": conform,
|
|
537
770
|
"warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings
|
|
538
|
-
+ emphasis_warnings,
|
|
771
|
+
+ emphasis_warnings + kinetic_warnings,
|
|
539
772
|
}
|
|
540
773
|
if pip and pip["measured"] and (pip["confidence"] or 0) < 0.3:
|
|
541
774
|
timeline["warnings"].append(f"pip: the measured offset ({pip['offset']:g} s) has low confidence "
|
|
@@ -562,7 +795,8 @@ def main() -> None:
|
|
|
562
795
|
"pip_offset": pip["offset"] if pip else None, "beats": bool(beats and beats.get("usable")),
|
|
563
796
|
"tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
|
|
564
797
|
"clips": len(clips) or 1, "words": len(words), "emphasis": len(emphasis),
|
|
565
|
-
"conformed": (conform or {}).get("reasons", [])
|
|
798
|
+
"conformed": (conform or {}).get("reasons", []),
|
|
799
|
+
"kinetic": sum(len(ln["units"]) for ln in kinetic["lines"]) if kinetic else 0},
|
|
566
800
|
"warnings": timeline["warnings"]},
|
|
567
801
|
f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
|
|
568
802
|
f"(speech {speech_total:.2f}s), {len(peaks)} peaks, {len(captions)} captions"
|
package/scripts/pipeline.py
CHANGED
|
@@ -7,6 +7,7 @@ Examples:
|
|
|
7
7
|
python3 pipeline.py talk.mp4 --project ./motion --comp Jumpcut --captions talk.srt --platform youtube
|
|
8
8
|
python3 pipeline.py clip.mp4 --project ./motion --comp PeakPulse --platform reels --out-dir out/
|
|
9
9
|
python3 pipeline.py talk.mp4 --project ./motion --comp Captioned --captions talk.srt # no delivery step
|
|
10
|
+
python3 pipeline.py --blank 15 --size 1080x1920 --music bgm.wav --project ./motion --comp PeakPulse # no footage
|
|
10
11
|
"""
|
|
11
12
|
import argparse
|
|
12
13
|
import json
|
|
@@ -17,14 +18,15 @@ from typing import Any, Dict, List
|
|
|
17
18
|
|
|
18
19
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
19
20
|
from _common import (ASPECTS, BUILTIN_COMPOSITIONS, FITS, HERE, STATE, add_common, apply_common, die, emit, info,
|
|
20
|
-
platform_aspect, shell_join)
|
|
21
|
+
platform_aspect, shell_join, parse_with_blank)
|
|
21
22
|
from deliver import PLATFORMS
|
|
22
23
|
|
|
23
24
|
|
|
24
25
|
def build_parser() -> argparse.ArgumentParser:
|
|
25
26
|
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
|
|
26
27
|
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
|
|
27
|
-
p.add_argument("input", nargs="+", help="source video; several are joined in order (ffmpeg-skill join.py) first"
|
|
28
|
+
p.add_argument("input", nargs="+", help="source video; several are joined in order (ffmpeg-skill join.py) first "
|
|
29
|
+
"(with --blank: none, or `-`)")
|
|
28
30
|
p.add_argument("--project", required=True, help="Remotion project folder made by init.py")
|
|
29
31
|
p.add_argument("--comp", required=True, help=f"composition id ({', '.join(BUILTIN_COMPOSITIONS)}, or yours)")
|
|
30
32
|
p.add_argument("--captions", help="SRT / WebVTT / JSON cues for the timeline")
|
|
@@ -36,6 +38,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
36
38
|
p.add_argument("--platform", choices=PLATFORMS, help="deliver with this ffmpeg-skill template and check it")
|
|
37
39
|
p.add_argument("--out-dir", help="where the timeline, render and deliverable go (default: next to the input)")
|
|
38
40
|
p.add_argument("--beats", action="store_true", help="measure the beat grid too")
|
|
41
|
+
p.add_argument("--blank", type=float, metavar="SECONDS",
|
|
42
|
+
help="no footage: draw the composition on a plain background this many seconds long "
|
|
43
|
+
"(analyze.py --blank); give no input file")
|
|
44
|
+
p.add_argument("--size", metavar="WxH", help="with --blank: frame size (default 1920x1080)")
|
|
45
|
+
p.add_argument("--fps", metavar="RATE", help="with --blank: frame rate (default 30)")
|
|
46
|
+
p.add_argument("--music", metavar="FILE", help="with --blank: music under it, measured for peaks and --beats")
|
|
39
47
|
p.add_argument("--conform", action="store_true",
|
|
40
48
|
help="a variable-frame-rate or HDR source is made into a constant-frame-rate, SDR BT.709 copy "
|
|
41
49
|
"with ffmpeg-skill first (analyze.py --conform; the copy goes in --out-dir) and drawn on; "
|
|
@@ -71,22 +79,39 @@ def step(name: str, script: str, args: List[str], steps: List[Dict[str, Any]]) -
|
|
|
71
79
|
|
|
72
80
|
|
|
73
81
|
def main() -> None:
|
|
74
|
-
a = build_parser()
|
|
82
|
+
a = parse_with_blank(build_parser())
|
|
75
83
|
apply_common(a)
|
|
76
84
|
inputs = [Path(i).expanduser() for i in a.input]
|
|
77
85
|
missing = [str(i) for i in inputs if not i.is_file()]
|
|
78
86
|
if missing:
|
|
79
87
|
die(f"input not found: {', '.join(missing)}", "input")
|
|
80
|
-
|
|
81
|
-
|
|
88
|
+
if a.blank is None and not inputs:
|
|
89
|
+
die("give an input file, or --blank SECONDS for a run with no footage", "input")
|
|
90
|
+
if a.blank is not None and inputs:
|
|
91
|
+
die("--blank makes a run with no footage: give no input file (the music goes in --music)", "input")
|
|
92
|
+
if a.blank is None:
|
|
93
|
+
given = [f for f, v in (("--size", a.size), ("--fps", a.fps), ("--music", a.music)) if v is not None]
|
|
94
|
+
if given:
|
|
95
|
+
die(f"{', '.join(given)} {'needs' if len(given) == 1 else 'need'} --blank SECONDS", "input")
|
|
96
|
+
blank_args: List[str] = []
|
|
97
|
+
if a.blank is not None:
|
|
98
|
+
music = Path(a.music).expanduser() if a.music else None
|
|
99
|
+
blank_args = ["--blank", repr(a.blank)] + [x for flag, v in (("--size", a.size), ("--fps", a.fps),
|
|
100
|
+
("--music", a.music)) if v for x in (flag, v)]
|
|
101
|
+
out_dir = Path(a.out_dir).expanduser() if a.out_dir else (music.parent if music else Path.cwd())
|
|
102
|
+
stem = f"{music.stem}_blank" if music else "blank"
|
|
103
|
+
else:
|
|
104
|
+
src = inputs[0]
|
|
105
|
+
out_dir = Path(a.out_dir).expanduser() if a.out_dir else src.parent
|
|
106
|
+
stem = src.stem + ("_joined" if len(inputs) > 1 else "")
|
|
82
107
|
if not STATE.dry_run:
|
|
83
108
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
84
|
-
stem = src.stem + ("_joined" if len(inputs) > 1 else "")
|
|
85
109
|
tl = out_dir / f"{stem}.timeline.json"
|
|
86
110
|
render_out = out_dir / f"{stem}_{a.comp}.mp4"
|
|
87
111
|
steps: List[Dict[str, Any]] = []
|
|
88
112
|
|
|
89
|
-
an_args = [*map(str, inputs), "-o", str(tl)]
|
|
113
|
+
an_args = [*map(str, inputs), *blank_args, "-o", str(tl)]
|
|
114
|
+
an_args += ["--joined", str(out_dir / f"{stem}.mp4")] if len(inputs) > 1 else []
|
|
90
115
|
an_args += (["--captions", a.captions] if a.captions else []) + (["--beats"] if a.beats else [])
|
|
91
116
|
an_args += ["--chapters", a.chapters] if a.chapters else []
|
|
92
117
|
an_args += ["--conform", "--conformed", str(out_dir / f"{stem}_conformed.mp4")] if a.conform else []
|
package/scripts/render.py
CHANGED
|
@@ -202,6 +202,9 @@ def main() -> None:
|
|
|
202
202
|
output = output.resolve()
|
|
203
203
|
refuse_existing(output)
|
|
204
204
|
|
|
205
|
+
if a.comp == "KineticType" and not timeline.get("kinetic"):
|
|
206
|
+
die("KineticType draws the schedule analyze.py --kinetic writes (words or measured beats); this timeline "
|
|
207
|
+
"has none: re-run analyze.py with --kinetic", "input")
|
|
205
208
|
if a.sparse:
|
|
206
209
|
if a.comp not in _sparse.SPARSE_COMPOSITIONS:
|
|
207
210
|
die(f"--sparse draws only the stretches where graphics show: {a.comp} is not one of "
|
|
@@ -9,6 +9,7 @@ import { BeatMontage } from "./compositions/BeatMontage";
|
|
|
9
9
|
import { Karaoke } from "./compositions/Karaoke";
|
|
10
10
|
import { Pip } from "./compositions/Pip";
|
|
11
11
|
import { Emphasis } from "./compositions/Emphasis";
|
|
12
|
+
import { KineticType } from "./compositions/KineticType";
|
|
12
13
|
import { SAMPLE_TIMELINE, fullLengthFrames, highlightFrames, jumpcutFrames, outputFrame, type Props, type Timeline } from "./timeline";
|
|
13
14
|
|
|
14
15
|
// Length and fps come from the measured timeline, never from constants; the frame is the
|
|
@@ -34,5 +35,6 @@ export const RemotionRoot: React.FC = () => (
|
|
|
34
35
|
<Composition id="Karaoke" component={Karaoke} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
35
36
|
<Composition id="Pip" component={Pip} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
36
37
|
<Composition id="Emphasis" component={Emphasis} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
38
|
+
<Composition id="KineticType" component={KineticType} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
37
39
|
</>
|
|
38
40
|
);
|
|
@@ -40,7 +40,7 @@ export const BeatMontage: React.FC<Props> = (props) => {
|
|
|
40
40
|
const src = { ...timeline.source, has_audio: false };
|
|
41
41
|
return (
|
|
42
42
|
<Sequence key={i} from={from} durationInFrames={len} name={`shot ${i + 1}`}>
|
|
43
|
-
<SourceVideo source={src} fit={fit} trimBefore={start} trimAfter={start + len} />
|
|
43
|
+
<SourceVideo background={o.background} source={src} fit={fit} trimBefore={start} trimAfter={start + len} />
|
|
44
44
|
{i > 0 ? <BeatFlash accent={o.accent} /> : null}
|
|
45
45
|
</Sequence>
|
|
46
46
|
);
|
|
@@ -16,7 +16,7 @@ export const Captioned: React.FC<Props> = (props) => {
|
|
|
16
16
|
const { fps } = useVideoConfig();
|
|
17
17
|
return (
|
|
18
18
|
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
19
|
-
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
|
|
19
|
+
{overlay ? null : <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} />}
|
|
20
20
|
{timeline.captions.map((c, i) => {
|
|
21
21
|
const from = secToFrames(c.start, fps);
|
|
22
22
|
const dur = Math.max(1, secToFrames(c.end, fps) - from);
|
|
@@ -39,7 +39,7 @@ export const Emphasis: React.FC<Props> = (props) => {
|
|
|
39
39
|
});
|
|
40
40
|
return (
|
|
41
41
|
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
42
|
-
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
|
|
42
|
+
{overlay ? null : <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} />}
|
|
43
43
|
{timeline.captions.map((c, i) => {
|
|
44
44
|
const from = secToFrames(c.start, fps);
|
|
45
45
|
const dur = Math.max(1, secToFrames(c.end, fps) - from);
|
|
@@ -25,7 +25,7 @@ export const Highlights: React.FC<Props> = (props) => {
|
|
|
25
25
|
const len = Math.max(1, secToFrames(e, fps) - a);
|
|
26
26
|
return (
|
|
27
27
|
<Series.Sequence key={i} durationInFrames={len} name={`highlight ${i + 1}`}>
|
|
28
|
-
<SourceVideo source={timeline.source} fit={fit} trimBefore={a} trimAfter={a + len} />
|
|
28
|
+
<SourceVideo background={o.background} source={timeline.source} fit={fit} trimBefore={a} trimAfter={a + len} />
|
|
29
29
|
{i > 0 ? <CutFlash /> : null}
|
|
30
30
|
<Counter index={i} total={ranges.length} o={o} fontFamily={family} />
|
|
31
31
|
{i === 0 && o.title ? <Title text={o.title} len={len} o={o} fontFamily={family} /> : null}
|
|
@@ -29,7 +29,7 @@ export const Jumpcut: React.FC<Props> = (props) => {
|
|
|
29
29
|
return (
|
|
30
30
|
<Series.Sequence key={i} durationInFrames={len} name={`cut ${i + 1}`}>
|
|
31
31
|
<Punch zoom={zoom} len={len}>
|
|
32
|
-
<SourceVideo source={timeline.source} fit={fit} trimBefore={a} trimAfter={a + len} />
|
|
32
|
+
<SourceVideo background={o.background} source={timeline.source} fit={fit} trimBefore={a} trimAfter={a + len} />
|
|
33
33
|
</Punch>
|
|
34
34
|
</Series.Sequence>
|
|
35
35
|
);
|
|
@@ -19,7 +19,7 @@ export const Karaoke: React.FC<Props> = (props) => {
|
|
|
19
19
|
const words = timeline.words ?? [];
|
|
20
20
|
return (
|
|
21
21
|
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
22
|
-
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
|
|
22
|
+
{overlay ? null : <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} />}
|
|
23
23
|
{timeline.captions.map((c, i) => {
|
|
24
24
|
const from = secToFrames(c.start, fps);
|
|
25
25
|
const dur = Math.max(1, secToFrames(c.end, fps) - from);
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import { AbsoluteFill, interpolate, useCurrentFrame, useVideoConfig } from "remotion";
|
|
3
|
+
import { SourceVideo } from "../lib/SourceVideo";
|
|
4
|
+
import { useStagedFont } from "../lib/useStagedFont";
|
|
5
|
+
import { Props, fontStack, outputFrame, resolveOptions, secToFrames, type KineticLine, type Options } from "../timeline";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* KineticType: the caption cues' words (or CJK characters) entering one by one at the times analyze.py
|
|
9
|
+
* --kinetic scheduled from a measurement -- each word's own time from a speech engine (--words) or the next
|
|
10
|
+
* measured beat (--beats). Nothing here makes up a time: a unit is invisible before the frame of its `start`
|
|
11
|
+
* and visible on it. Units keep their place in the line while hidden, so nothing reflows as they enter.
|
|
12
|
+
* kineticStyle: pop (scale), wipe (a mask from the left), tracking (characters closing in), rise.
|
|
13
|
+
* kineticReveal "char": a unit's characters follow each other kineticStagger seconds apart from its start.
|
|
14
|
+
*/
|
|
15
|
+
export const KineticType: React.FC<Props> = (props) => {
|
|
16
|
+
const { timeline, options, font, overlay } = props;
|
|
17
|
+
useStagedFont(font);
|
|
18
|
+
const o = resolveOptions(options);
|
|
19
|
+
const family = fontStack(o, font);
|
|
20
|
+
const frame = useCurrentFrame();
|
|
21
|
+
const { fps } = useVideoConfig();
|
|
22
|
+
const lines = timeline.kinetic?.lines ?? [];
|
|
23
|
+
const line = lines.find((ln) => frame >= secToFrames(ln.start, fps) && frame < secToFrames(ln.end, fps));
|
|
24
|
+
return (
|
|
25
|
+
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
26
|
+
{overlay ? null : <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} />}
|
|
27
|
+
{line ? <Line line={line} o={o} fontFamily={family} /> : null}
|
|
28
|
+
</AbsoluteFill>
|
|
29
|
+
);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Frames a unit (or character) takes to settle once it has started. */
|
|
33
|
+
const ENTER_SECONDS = 0.18;
|
|
34
|
+
|
|
35
|
+
const Line: React.FC<{ line: KineticLine; o: Options; fontFamily: string }> = ({ line, o, fontFamily }) => {
|
|
36
|
+
const frame = useCurrentFrame();
|
|
37
|
+
const { fps, width, height } = useVideoConfig();
|
|
38
|
+
const size = Math.round(Math.min(width, height) * o.kineticSize);
|
|
39
|
+
const enter = Math.max(1, Math.round(fps * ENTER_SECONDS));
|
|
40
|
+
const endFrame = secToFrames(line.end, fps);
|
|
41
|
+
const fade = Math.min(6, Math.max(0, endFrame - secToFrames(line.start, fps) - 1));
|
|
42
|
+
const exit = fade > 0 ? interpolate(frame, [endFrame - fade, endFrame], [1, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }) : 1;
|
|
43
|
+
const text = line.units.map((u) => u.text).join("");
|
|
44
|
+
const lang = /[-ヿ]/.test(text) ? "ja" : /[가-]/.test(text) ? "ko" : undefined;
|
|
45
|
+
const starts = line.units.map((u) => secToFrames(u.start, fps));
|
|
46
|
+
// The unit that started last is the current one: it takes the accent colour.
|
|
47
|
+
let current = -1;
|
|
48
|
+
starts.forEach((s, i) => {
|
|
49
|
+
if (s <= frame) current = i;
|
|
50
|
+
});
|
|
51
|
+
// progress 0 before the start frame, > 0 on it, 1 once settled
|
|
52
|
+
const progress = (start: number): number => (frame < start ? 0 : Math.min(1, (frame - start + 1) / enter));
|
|
53
|
+
return (
|
|
54
|
+
<AbsoluteFill style={{ justifyContent: "center", alignItems: "center" }}>
|
|
55
|
+
<div
|
|
56
|
+
lang={lang}
|
|
57
|
+
style={{
|
|
58
|
+
maxWidth: width * 0.88,
|
|
59
|
+
display: "flex",
|
|
60
|
+
flexWrap: "wrap",
|
|
61
|
+
justifyContent: "center",
|
|
62
|
+
alignItems: "baseline",
|
|
63
|
+
fontFamily,
|
|
64
|
+
fontWeight: 800,
|
|
65
|
+
fontSize: size,
|
|
66
|
+
lineHeight: 1.25,
|
|
67
|
+
color: o.textColor,
|
|
68
|
+
opacity: exit,
|
|
69
|
+
}}
|
|
70
|
+
>
|
|
71
|
+
{line.units.map((u, i) => {
|
|
72
|
+
const chars = Array.from(u.text);
|
|
73
|
+
const charStart = (j: number) =>
|
|
74
|
+
o.kineticReveal === "char" ? secToFrames(u.start + j * o.kineticStagger, fps) : starts[i];
|
|
75
|
+
return (
|
|
76
|
+
<span
|
|
77
|
+
key={i}
|
|
78
|
+
style={{
|
|
79
|
+
display: "inline-flex",
|
|
80
|
+
whiteSpace: "pre",
|
|
81
|
+
marginLeft: u.gap ? "0.28em" : 0,
|
|
82
|
+
color: i === current ? o.accent : o.textColor,
|
|
83
|
+
}}
|
|
84
|
+
>
|
|
85
|
+
{chars.map((ch, j) => {
|
|
86
|
+
const p = progress(Math.max(starts[i], charStart(j)));
|
|
87
|
+
return (
|
|
88
|
+
<span key={j} style={{ display: "inline-block", ...enterStyle(o.kineticStyle, p, j, chars.length) }}>
|
|
89
|
+
{ch}
|
|
90
|
+
</span>
|
|
91
|
+
);
|
|
92
|
+
})}
|
|
93
|
+
</span>
|
|
94
|
+
);
|
|
95
|
+
})}
|
|
96
|
+
</div>
|
|
97
|
+
</AbsoluteFill>
|
|
98
|
+
);
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const ease = (p: number): number => 1 - Math.pow(1 - p, 3);
|
|
102
|
+
|
|
103
|
+
/** How a character looks at progress p (0 = not started: drawn invisibly so the line keeps its layout). */
|
|
104
|
+
const enterStyle = (style: Options["kineticStyle"], p: number, j: number, n: number): React.CSSProperties => {
|
|
105
|
+
if (p <= 0) return { opacity: 0 };
|
|
106
|
+
const e = ease(p);
|
|
107
|
+
switch (style) {
|
|
108
|
+
case "wipe":
|
|
109
|
+
return { clipPath: `inset(0 ${(1 - e) * 100}% 0 0)` };
|
|
110
|
+
case "tracking": {
|
|
111
|
+
// characters start spread out from the unit's centre and close in: a transform, so nothing reflows
|
|
112
|
+
const offset = (j - (n - 1) / 2) * 0.35 * (1 - e);
|
|
113
|
+
return { opacity: Math.min(1, 0.35 + e), transform: `translateX(${offset}em)` };
|
|
114
|
+
}
|
|
115
|
+
case "rise":
|
|
116
|
+
return { opacity: Math.min(1, 0.25 + e), transform: `translateY(${(1 - e) * 0.5}em)` };
|
|
117
|
+
case "pop":
|
|
118
|
+
default:
|
|
119
|
+
return { opacity: Math.min(1, 0.4 + e), transform: `scale(${1 + 0.6 * (1 - e)})` };
|
|
120
|
+
}
|
|
121
|
+
};
|
|
@@ -45,7 +45,7 @@ export const PeakPulse: React.FC<Props> = (props) => {
|
|
|
45
45
|
return (
|
|
46
46
|
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
47
47
|
{/* In overlay mode the source (and its slight zoom on peaks) is left to the composite step. */}
|
|
48
|
-
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} style={{ transform: `scale(${1 + 0.02 * o.pulse * hit})` }} />}
|
|
48
|
+
{overlay ? null : <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} style={{ transform: `scale(${1 + 0.02 * o.pulse * hit})` }} />}
|
|
49
49
|
<AbsoluteFill style={{ boxShadow: `inset 0 0 ${glow * 2}px ${glow}px ${o.accent}`, opacity: 0.85, pointerEvents: "none" }} />
|
|
50
50
|
{flash > 0 ? <AbsoluteFill style={{ backgroundColor: "white", opacity: 0.18 * flash }} /> : null}
|
|
51
51
|
{o.progressBar ? (
|
|
@@ -38,7 +38,7 @@ export const Pip: React.FC<Props> = (props) => {
|
|
|
38
38
|
const [from, dur, trimBefore] = pip ? pipFrames(pip, fps, durationInFrames) : [0, 1, 0];
|
|
39
39
|
return (
|
|
40
40
|
<AbsoluteFill style={{ backgroundColor: "black" }}>
|
|
41
|
-
<SourceVideo source={timeline.source} fit={outputFrame(props).fit} />
|
|
41
|
+
<SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} />
|
|
42
42
|
{pip && pip.src ? (
|
|
43
43
|
<Sequence from={from} durationInFrames={dur} name="camera" layout="none">
|
|
44
44
|
<div style={box}>
|
|
@@ -21,7 +21,7 @@ export const Titled: React.FC<Props> = (props) => {
|
|
|
21
21
|
.filter((x): x is { sc: { start: number; end: number }; text: string } => Boolean(x.text));
|
|
22
22
|
return (
|
|
23
23
|
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
24
|
-
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
|
|
24
|
+
{overlay ? null : <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} />}
|
|
25
25
|
{sceneCards.map(({ sc, text }, i) => {
|
|
26
26
|
const from = secToFrames(sc.start, fps);
|
|
27
27
|
const dur = Math.max(1, Math.min(secToFrames(sc.end, fps), from + Math.round(fps * 2.5)) - from);
|
|
@@ -11,15 +11,27 @@ type Props = {
|
|
|
11
11
|
/** Source frame to stop at. */
|
|
12
12
|
trimAfter?: number;
|
|
13
13
|
style?: React.CSSProperties;
|
|
14
|
+
/** The picture of a blank source (analyze.py --blank): options.background. */
|
|
15
|
+
background?: string;
|
|
14
16
|
};
|
|
15
17
|
|
|
16
18
|
/**
|
|
17
19
|
* The measured source as the bottom layer.
|
|
18
20
|
* - video: OffthreadVideo, placed by `fit` (contain / cover / blur)
|
|
19
21
|
* - audio only: a neutral placeholder picture with the audio playing under it
|
|
22
|
+
* - blank (analyze.py --blank): the background, with the music (if any) playing under it
|
|
20
23
|
* - nothing staged: the placeholder alone (Studio previews)
|
|
21
24
|
*/
|
|
22
|
-
export const SourceVideo: React.FC<Props> = ({ source, fit = "contain", trimBefore, trimAfter, style }) => {
|
|
25
|
+
export const SourceVideo: React.FC<Props> = ({ source, fit = "contain", trimBefore, trimAfter, style, background }) => {
|
|
26
|
+
if (source.blank) {
|
|
27
|
+
return (
|
|
28
|
+
<AbsoluteFill style={{ ...style, background: background ?? "#000000" }}>
|
|
29
|
+
{source.src && source.has_audio ? (
|
|
30
|
+
<Audio src={staticFile(source.src)} trimBefore={trimBefore} trimAfter={trimAfter} />
|
|
31
|
+
) : null}
|
|
32
|
+
</AbsoluteFill>
|
|
33
|
+
);
|
|
34
|
+
}
|
|
23
35
|
if (!source.src) {
|
|
24
36
|
return <Placeholder label={source.name} />;
|
|
25
37
|
}
|
|
@@ -15,6 +15,17 @@ export type Source = {
|
|
|
15
15
|
height: number;
|
|
16
16
|
has_video: boolean;
|
|
17
17
|
has_audio: boolean;
|
|
18
|
+
/** analyze.py --blank: no footage. The picture is options.background; src (if any) is the music. */
|
|
19
|
+
blank?: boolean;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** A source-less run (analyze.py --blank): the asked size, rate and length, and the music measured (or null). */
|
|
23
|
+
export type Blank = {
|
|
24
|
+
duration: number;
|
|
25
|
+
width: number;
|
|
26
|
+
height: number;
|
|
27
|
+
fps: number;
|
|
28
|
+
music: { path: string; name: string; duration: number; fingerprint: string } | null;
|
|
18
29
|
};
|
|
19
30
|
|
|
20
31
|
export type Caption = { start: number; end: number; text: string };
|
|
@@ -66,6 +77,12 @@ export type Highlight = { start: number; end: number };
|
|
|
66
77
|
/** A lower third: text from the user (options), timing in source seconds. */
|
|
67
78
|
export type LowerThird = { text: string; sub?: string; start: number; end: number };
|
|
68
79
|
export type Peak = { time: number; rms: number };
|
|
80
|
+
/** The KineticType schedule (analyze.py --kinetic): one line per caption cue, each unit (a word, or one CJK
|
|
81
|
+
* character) starting at a measured time -- its word's (by "words") or a beat's (by "beats"). gap: a space before
|
|
82
|
+
* the unit. The line shows from its first unit's start until `end`. */
|
|
83
|
+
export type KineticUnit = { text: string; gap: boolean; start: number };
|
|
84
|
+
export type KineticLine = { cue: number; start: number; end: number; units: KineticUnit[] };
|
|
85
|
+
export type Kinetic = { by: "words" | "beats"; step: number | null; lines: KineticLine[] };
|
|
69
86
|
export type Scene = { start: number; end: number };
|
|
70
87
|
|
|
71
88
|
export type Timeline = {
|
|
@@ -87,6 +104,10 @@ export type Timeline = {
|
|
|
87
104
|
/** Emphasised caption words (analyze.py --emphasis); drawn by the Emphasis composition. */
|
|
88
105
|
emphasis?: Emphasis[];
|
|
89
106
|
pip?: Pip | null;
|
|
107
|
+
/** The KineticType schedule (analyze.py --kinetic); absent or null otherwise. */
|
|
108
|
+
kinetic?: Kinetic | null;
|
|
109
|
+
/** Set by analyze.py --blank (a timeline with no footage); absent or null otherwise. */
|
|
110
|
+
blank?: Blank | null;
|
|
90
111
|
/** Set when analyze.py --conform measured a conformed copy instead of the original (null otherwise). */
|
|
91
112
|
conform?: Conform | null;
|
|
92
113
|
warnings?: string[];
|
|
@@ -133,6 +154,16 @@ export type Options = {
|
|
|
133
154
|
bubbles: Bubble[];
|
|
134
155
|
/** Emphasis: comment-style cards (text and author from the user). */
|
|
135
156
|
comments: CommentCard[];
|
|
157
|
+
/** The picture of a source-less run (analyze.py --blank): a CSS colour or gradient. */
|
|
158
|
+
background: string;
|
|
159
|
+
/** KineticType: how a unit enters -- scale pop, a mask wipe, tracking (letter-spacing closing in) or a rise. */
|
|
160
|
+
kineticStyle: "pop" | "wipe" | "tracking" | "rise";
|
|
161
|
+
/** KineticType: the whole unit enters at its start, or its characters one after another from that start. */
|
|
162
|
+
kineticReveal: "unit" | "char";
|
|
163
|
+
/** KineticType: seconds between characters with kineticReveal "char" (the first is at the unit's start). */
|
|
164
|
+
kineticStagger: number;
|
|
165
|
+
/** KineticType: text size as a fraction of the frame's short side. */
|
|
166
|
+
kineticSize: number;
|
|
136
167
|
};
|
|
137
168
|
|
|
138
169
|
export const DEFAULT_OPTIONS: Options = {
|
|
@@ -157,6 +188,11 @@ export const DEFAULT_OPTIONS: Options = {
|
|
|
157
188
|
emphasisStyle: "pop",
|
|
158
189
|
bubbles: [],
|
|
159
190
|
comments: [],
|
|
191
|
+
background: "#000000",
|
|
192
|
+
kineticStyle: "pop",
|
|
193
|
+
kineticReveal: "char",
|
|
194
|
+
kineticStagger: 0.04,
|
|
195
|
+
kineticSize: 0.09,
|
|
160
196
|
};
|
|
161
197
|
|
|
162
198
|
/** Where the camera plays on the source timeline: [from, durationInFrames, trimBefore] in frames. */
|