remotion-ffmpeg-skill 0.16.0 → 0.18.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 CHANGED
@@ -68,6 +68,8 @@ Moving text has three owners: word-timed caption effects are this skill's, anima
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
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
+ | "audio visualizer / spectrum / waveform / podcast or music video from the audio" / a loop for an edit | `analyze.py SOURCE` (or `--blank S --music song.wav`) `[--beats] [--words W.json]` → `render.py --comp Visualizer` (`visualizer`: bars, spectrum, radial, waveform; lyrics as Karaoke draws them). A loop: `--beats` and `{"loopBars": 0}` (or N) in `--options`: whole measured bars, seam halfway between beats; check it with qc-skill's `video.loop_seam` |
72
+ | "3D / Three.js / particles that hit on the beat" | `analyze.py [--beats]` (or `--blank S --music song.wav --beats`) → `render.py --comp ThreeScene` (`seed`, `threeParticles`). WebGL renders with `--gl swangle` (software, no GPU needed); `--gl angle` on a machine with a GPU. `doctor.py --project` names the backend in use; another backend changes the pixels |
71
73
  | "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 |
72
74
  | "preview" / "show me a frame" | `still.py` |
73
75
  | a new kind of graphic | add a composition to `src/` of the project that reads `Props` from `src/timeline.ts`; render with `--comp YourId` (render.py then reports measured numbers without a built-in expectation) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remotion-ffmpeg-skill",
3
- "version": "0.16.0",
3
+ "version": "0.18.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",
@@ -89,7 +89,7 @@ Render single frames as PNG to check the look before a full render.
89
89
  | Argument | Type | Default | Meaning |
90
90
  |---|---|---|---|
91
91
  | `--project (required)` | string | | Remotion project folder made by init.py |
92
- | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, or yours) |
92
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, Visualizer, ThreeScene, or yours) |
93
93
  | `--timeline (required)` | string | | timeline.json written by analyze.py |
94
94
  | `--options` | string | | JSON object of look-and-feel options |
95
95
  | `--at` | number, repeatable | | time in seconds (repeatable) |
@@ -100,6 +100,7 @@ Render single frames as PNG to check the look before a full render.
100
100
  | `--fit` | string: blur / contain / cover | | how the source fills another shape: blur (default when the shape changes), contain (bars) or cover (crop) |
101
101
  | `--font-file` | string | | caption font file (.ttf/.otf/.ttc/.woff2), staged into the project |
102
102
  | `--brand` | string | | ffmpeg-skill brand.json: its colours, caption colour, font and font file set the look (an --options file still wins key by key) |
103
+ | `--gl` | string: angle / egl / swiftshader / swangle / vulkan / angle-egl | | Chromium's OpenGL backend for Remotion (default: swangle -- software WebGL, works without a GPU -- for ThreeScene, none for the other compositions: Chrome's choice; angle uses a GPU). Another backend changes the pixels; doctor.py names the one in use |
103
104
  | `--no-auto-font` | boolean | | don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions |
104
105
 
105
106
  --json result (besides `status`, `dry_run`, `output`): `outputs` (list[str] (PNG paths)), `frames` (list[int]), `commands` (list[str]), `verified` (bool), `frame` (object|null {width, height, fit}), `font` (str|null)
@@ -120,7 +121,7 @@ Render a composition from a timeline, verify it (frames, fps, size, audio) and w
120
121
  | Argument | Type | Default | Meaning |
121
122
  |---|---|---|---|
122
123
  | `--project (required)` | string | | Remotion project folder made by init.py |
123
- | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, or one you added) |
124
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, Visualizer, ThreeScene, or one you added) |
124
125
  | `--timeline (required)` | string | | timeline.json written by analyze.py |
125
126
  | `--options` | string | | JSON object of look-and-feel options (see references/timeline.md) |
126
127
  | `--output` | string | | output file (default: <source>_<comp>.mp4, .mov for prores) |
@@ -139,6 +140,7 @@ Render a composition from a timeline, verify it (frames, fps, size, audio) and w
139
140
  | `--fit` | string: blur / contain / cover | | how the source fills another shape: blur (default when the shape changes), contain (bars) or cover (crop) |
140
141
  | `--font-file` | string | | caption font file (.ttf/.otf/.ttc/.woff2), staged into the project |
141
142
  | `--brand` | string | | ffmpeg-skill brand.json: its colours, caption colour, font and font file set the look (an --options file still wins key by key) |
143
+ | `--gl` | string: angle / egl / swiftshader / swangle / vulkan / angle-egl | | Chromium's OpenGL backend for Remotion (default: swangle -- software WebGL, works without a GPU -- for ThreeScene, none for the other compositions: Chrome's choice; angle uses a GPU). Another backend changes the pixels; doctor.py names the one in use |
142
144
  | `--no-auto-font` | boolean | | don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions |
143
145
 
144
146
  --json result (besides `status`, `dry_run`, `output`): `verified` (bool), `verification` (list[{check, status, value, expected}]), `commands` (list[str]), `look` (str|null (contact sheet PNG)), `look_error` (str|null), `summary` (str), `frame` (object|null), `font` (str|null), `mode` (full|overlay), `graphics` (str|null (kept ProRes 4444 layer)), `sparse` (null|{used, reason, stretches, drawn_frames, source_frames} (--sparse)), `kind` (null|failed), `error` (null|str (which verification rows failed))
@@ -185,7 +187,7 @@ analyze -> render -> deliver in one call, stopping at the first failed step.
185
187
  |---|---|---|---|
186
188
  | `input` | string, repeatable | | source video; several are joined in order (ffmpeg-skill join.py) first (with --blank: none, or `-`) |
187
189
  | `--project (required)` | string | | Remotion project folder made by init.py |
188
- | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, or yours) |
190
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, KineticType, Visualizer, ThreeScene, or yours) |
189
191
  | `--captions` | string | | SRT / WebVTT / JSON cues for the timeline |
190
192
  | `--chapters` | string | | chapters (`TIME TITLE` per line, or `source`): cards in Titled and, with --platform, chapter markers in the deliverable |
191
193
  | `--options` | string | | JSON options file passed to the composition |
@@ -237,6 +239,7 @@ Holds:
237
239
  - analyze.py run twice on the same file writes a byte-identical timeline.json; on a copy at another path only source.path differs
238
240
  - pipeline.py writes byte-identical render and deliverable files; it is content_equivalent, not bit_exact, because its timeline.json records the input's absolute path
239
241
  - init.py (without --install) writes an identical project folder
242
+ - ThreeScene (WebGL through @remotion/three, render.py --gl swangle by default) renders twice to byte-identical files, --concurrency 1 included; the scene is a function of the frame and options.seed alone
240
243
 
241
244
  Does not hold:
242
245
 
@@ -52,6 +52,8 @@ composition exactly.
52
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 |
53
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
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` |
55
+ | `Visualizer` | source duration, or with `loopBars` a whole number of measured bars | the source's audio drawn each frame (`visualizer`: `bars`, `spectrum`, `radial` or `waveform`; @remotion/media-utils, a 1024-sample FFT centred on the frame's time, no smoothing across frames), a ring that hits on every measured beat, and the caption cues as Karaoke draws them (lyrics with `--words`). Over the source's picture, or over `background` on a `--blank` run. `loopBars`: a loop of that many bars of `beatsPerBar` measured beats (0 = as many as the beats hold) whose seam falls halfway between two beats -- from halfway between beats 0 and 1 to halfway between beats k and k+1 -- so its last frame runs into its first; refused when the beats cannot hold it |
56
+ | `ThreeScene` | source duration | a Three.js scene (@remotion/three) over the source (or `background`): seeded particles (`seed`, `threeParticles`) drifting round a centre shape that hits on every measured beat (measured peaks without a grid), the scene turning under a fixed camera. A function of the frame and `seed` only; rendered with `--gl swangle` unless `--gl` says otherwise |
55
57
  | `BeatMontage` | source duration | audio unbroken; the picture cuts every `beatsPerCut` measured beats, cycling through highlights (or scenes); no usable grid → cuts on scene changes |
56
58
 
57
59
  ## Options (`--options look.json`)
@@ -85,6 +87,12 @@ Every key is optional.
85
87
  | `kineticReveal` | `"char"` | KineticType: `char` (characters one after another from the unit's start) or `unit` (the whole unit at its start) |
86
88
  | `kineticStagger` | `0.04` | KineticType: seconds between characters with `kineticReveal: "char"`, 0–1 |
87
89
  | `kineticSize` | `0.09` | KineticType: text size as a fraction of the frame's short side, 0.01–0.5 |
90
+ | `visualizer` | `"bars"` | Visualizer: `bars`, `spectrum`, `radial` or `waveform` |
91
+ | `visualizerBars` | `48` | Visualizer: bars (or points) drawn, 8–256 |
92
+ | `loopBars` | `null` | Visualizer: `null` = the whole source; `0` = a loop of as many whole measured bars as fit; `N` = N bars (needs `analyze.py --beats`) |
93
+ | `beatsPerBar` | `4` | Visualizer: measured beats per bar for `loopBars`, 1–16 |
94
+ | `seed` | `1` | ThreeScene: places the particles; same seed, same scene (0–4294967295) |
95
+ | `threeParticles` | `300` | ThreeScene: number of particles, 1–5000 |
88
96
  | `chapterSeconds` | `4` | Titled: how long a chapter card stays up (cut short by the next chapter; 0 = none) |
89
97
 
90
98
  Unknown keys and wrong types are refused by render.py / still.py before anything renders.
@@ -330,14 +330,46 @@ def sec_to_frames(seconds: float, fps: float) -> int:
330
330
  return int(math.floor(seconds * fps + 0.5))
331
331
 
332
332
 
333
- def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
333
+ def loop_range(t: Dict[str, Any], options: Optional[Dict[str, Any]]) -> Optional[Tuple[int, int, int]]:
334
+ """The Visualizer's loop (visualizerRange in src/timeline.ts mirrors it): (first frame, frames, bars), or None
335
+ without loopBars. loopBars * beatsPerBar measured beats, the seam halfway between two beats (where motion that
336
+ hits on the beat is quietest): from halfway between beats 0 and 1 to halfway between beats k and k + 1.
337
+ Refused (die) when the measured beats cannot hold one whole bar, or the bars asked for."""
338
+ o = options or {}
339
+ want = o.get("loopBars")
340
+ if want is None:
341
+ return None
342
+ fps = float(t["source"]["fps"])
343
+ beats = t.get("beats") or {}
344
+ times = [float(b) for b in (beats.get("times") or []) if float(b) < float(t["source"]["duration"])] \
345
+ if beats.get("usable") else []
346
+ per = max(1, int(round(o.get("beatsPerBar", 4))))
347
+ most = (len(times) - 2) // per if len(times) >= 2 else 0
348
+ if most < 1:
349
+ die(f"loopBars needs the measured beat grid to hold at least one whole bar ({per} beats, plus one on each "
350
+ "side for the seam): " + ("analyze.py --beats measured none usable" if not times
351
+ else f"{len(times)} usable beats measured"), "input")
352
+ if want and want > most:
353
+ die(f"loopBars {want}: the measured beats hold {most} whole bar(s) of {per} beats", "input")
354
+ bars = want or most
355
+ k = bars * per
356
+ start = sec_to_frames((times[0] + times[1]) / 2, fps)
357
+ return start, max(1, sec_to_frames((times[k] + times[k + 1]) / 2, fps) - start), bars
358
+
359
+
360
+ def expected_frames(comp: str, t: Dict[str, Any], options: Optional[Dict[str, Any]] = None) -> Optional[int]:
334
361
  """Duration the built-in compositions compute in calculateMetadata (src/timeline.ts mirrors this).
335
362
 
336
363
  Custom compositions return None: their length is whatever their own calculateMetadata says,
337
364
  and render.py then only reports the measured numbers.
338
365
  """
339
366
  fps = float(t["source"]["fps"])
340
- if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip", "Emphasis", "KineticType"):
367
+ if comp == "Visualizer":
368
+ loop = loop_range(t, options)
369
+ if loop:
370
+ return loop[1]
371
+ if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip", "Emphasis", "KineticType",
372
+ "Visualizer", "ThreeScene"):
341
373
  return max(1, sec_to_frames(float(t["source"]["duration"]), fps))
342
374
  if comp in ("Jumpcut", "Highlights"):
343
375
  if comp == "Jumpcut":
@@ -352,7 +384,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
352
384
  # ---------------------------------------------------------------- Remotion project
353
385
 
354
386
  BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke", "Pip",
355
- "Emphasis", "KineticType")
387
+ "Emphasis", "KineticType", "Visualizer", "ThreeScene")
356
388
 
357
389
 
358
390
  def remotion_bin(project: Path) -> Path:
@@ -555,6 +587,17 @@ def write_props(project: Path, comp: str, timeline: Dict[str, Any], options: Dic
555
587
  return path, props
556
588
 
557
589
 
590
+ # Chromium's OpenGL backends Remotion accepts (--gl). None = Remotion's own default (4.x: none passed, Chrome
591
+ # chooses), as render.py has always rendered the 2D compositions; WebGL compositions get GL_DEFAULTS.
592
+ GL_BACKENDS = ("angle", "egl", "swiftshader", "swangle", "vulkan", "angle-egl")
593
+ GL_DEFAULTS = {"ThreeScene": "swangle"}
594
+
595
+
596
+ def gl_backend(comp: str, given: Optional[str]) -> Optional[str]:
597
+ """The --gl a render or still of this composition passes to Remotion (None: none)."""
598
+ return given or GL_DEFAULTS.get(comp)
599
+
600
+
558
601
  def add_frame_args(p: argparse.ArgumentParser) -> None:
559
602
  g = p.add_argument_group("output frame and font")
560
603
  g.add_argument("--aspect", choices=["source", *ASPECTS], default=None,
@@ -565,6 +608,10 @@ def add_frame_args(p: argparse.ArgumentParser) -> None:
565
608
  g.add_argument("--font-file", help="caption font file (.ttf/.otf/.ttc/.woff2), staged into the project")
566
609
  g.add_argument("--brand", help="ffmpeg-skill brand.json: its colours, caption colour, font and font file set "
567
610
  "the look (an --options file still wins key by key)")
611
+ g.add_argument("--gl", choices=GL_BACKENDS,
612
+ help="Chromium's OpenGL backend for Remotion (default: swangle -- software WebGL, works without a "
613
+ "GPU -- for ThreeScene, none for the other compositions: Chrome's choice; angle uses a GPU). "
614
+ "Another backend changes the pixels; doctor.py names the one in use")
568
615
  g.add_argument("--no-auto-font", action="store_true",
569
616
  help="don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions")
570
617
 
@@ -679,6 +726,8 @@ _OPTION_TYPES: Dict[str, Any] = {
679
726
  "pipCorner": str, "pipSize": (int, float), "pipShape": str, "pipAudio": bool,
680
727
  "emphasisStyle": str, "bubbles": list, "comments": list, "background": str,
681
728
  "kineticStyle": str, "kineticReveal": str, "kineticStagger": (int, float), "kineticSize": (int, float),
729
+ "visualizer": str, "visualizerBars": int, "loopBars": (int, type(None)), "beatsPerBar": int,
730
+ "seed": int, "threeParticles": int,
682
731
  }
683
732
 
684
733
 
@@ -721,6 +770,20 @@ def validate_options(o: Dict[str, Any]) -> List[str]:
721
770
  if isinstance(o.get("kineticSize"), (int, float)) and not isinstance(o["kineticSize"], bool) \
722
771
  and not 0.01 <= o["kineticSize"] <= 0.5:
723
772
  p.append("kineticSize must be between 0.01 and 0.5 (a fraction of the frame's short side)")
773
+ if "visualizer" in o and o["visualizer"] not in ("bars", "spectrum", "radial", "waveform"):
774
+ p.append("visualizer must be bars, spectrum, radial or waveform")
775
+ if isinstance(o.get("visualizerBars"), int) and not isinstance(o["visualizerBars"], bool) \
776
+ and not 8 <= o["visualizerBars"] <= 256:
777
+ p.append("visualizerBars must be between 8 and 256")
778
+ if isinstance(o.get("loopBars"), int) and not isinstance(o["loopBars"], bool) and o["loopBars"] < 0:
779
+ p.append("loopBars must be 0 (as many whole bars as measured), a number of bars, or null")
780
+ if isinstance(o.get("beatsPerBar"), int) and not isinstance(o["beatsPerBar"], bool) and not 1 <= o["beatsPerBar"] <= 16:
781
+ p.append("beatsPerBar must be between 1 and 16")
782
+ if isinstance(o.get("seed"), int) and not isinstance(o["seed"], bool) and not 0 <= o["seed"] <= 2 ** 32 - 1:
783
+ p.append("seed must be a whole number from 0 to 4294967295")
784
+ if isinstance(o.get("threeParticles"), int) and not isinstance(o["threeParticles"], bool) \
785
+ and not 1 <= o["threeParticles"] <= 5000:
786
+ p.append("threeParticles must be between 1 and 5000")
724
787
  if "emphasisStyle" in o and o["emphasisStyle"] not in ("pop", "color", "box"):
725
788
  p.append("emphasisStyle must be pop, color or box")
726
789
  for key, extra in (("bubbles", "side"), ("comments", "author")):
@@ -178,6 +178,8 @@ DETERMINISM = {
178
178
  "pipeline.py writes byte-identical render and deliverable files; it is content_equivalent, not bit_exact, "
179
179
  "because its timeline.json records the input's absolute path",
180
180
  "init.py (without --install) writes an identical project folder",
181
+ "ThreeScene (WebGL through @remotion/three, render.py --gl swangle by default) renders twice to byte-identical "
182
+ "files, --concurrency 1 included; the scene is a function of the frame and options.seed alone",
181
183
  ],
182
184
  "does_not_hold": [
183
185
  "another Chromium build: chrome-headless-shell 153 and 156 differed on every frame (PSNR 43 dB average, "
package/scripts/doctor.py CHANGED
@@ -16,7 +16,23 @@ import sys
16
16
  from pathlib import Path
17
17
 
18
18
  sys.path.insert(0, str(Path(__file__).resolve().parent))
19
- from _common import add_common, apply_common, emit, ffmpeg_skill_version, find_ffmpeg_skill, remotion_bin, version
19
+ import re
20
+
21
+ from _common import (GL_DEFAULTS, add_common, apply_common, emit, ffmpeg_skill_version, find_ffmpeg_skill, remotion_bin,
22
+ version)
23
+
24
+
25
+ def project_gl(proj: Path) -> str:
26
+ """The GL backend renders in this project use, as doctor reports it: the remotion.config.ts override when
27
+ there is one (Config.setChromiumOpenGlRenderer), else render.py's --gl defaults."""
28
+ cfg = proj / "remotion.config.ts"
29
+ text = cfg.read_text(encoding="utf-8") if cfg.is_file() else ""
30
+ text = re.sub(r"//[^\n]*", "", text)
31
+ m = re.search(r"setChromiumOpenGlRenderer\(\s*['\"]([\w-]+)['\"]", text)
32
+ if m:
33
+ return f"{m.group(1)} (remotion.config.ts, every composition unless --gl is given)"
34
+ three = ", ".join(f"{c}: {b}" for c, b in GL_DEFAULTS.items())
35
+ return f"{three}; other compositions: none set (Chrome's choice); --gl overrides"
20
36
 
21
37
 
22
38
  def _version(cmd):
@@ -71,6 +87,7 @@ def main() -> None:
71
87
  rv = json.loads(pkg.read_text(encoding="utf-8")).get("version")
72
88
  row("remotion project", rb.exists(), f"{proj} (remotion {rv})" if rv else str(proj),
73
89
  f"cd {proj} && npm install")
90
+ row("gl backend", True, project_gl(proj))
74
91
 
75
92
  ok = all(r["ok"] for r in rows)
76
93
  lines = [f"{'ok ' if r['ok'] else 'NO '} {r['check']}: {r['value']}" + (f" -> {r['fix']}" if r["fix"] else "")
package/scripts/render.py CHANGED
@@ -16,7 +16,7 @@ from typing import Any, Dict, List, Optional, Tuple
16
16
 
17
17
  sys.path.insert(0, str(Path(__file__).resolve().parent))
18
18
  import _sparse
19
- from _common import (BUILTIN_COMPOSITIONS, STATE, add_common, add_frame_args, apply_common, die, emit, expected_frames,
19
+ from _common import (gl_backend, loop_range, BUILTIN_COMPOSITIONS, STATE, add_common, add_frame_args, apply_common, die, emit, expected_frames,
20
20
  ffskill, ffskill_cmd, frame_size, info, load_look, load_timeline, prepare_props, refuse_existing,
21
21
  remotion_bin, require_ffmpeg_skill, require_project, remotion_error, run, shell_join)
22
22
 
@@ -79,6 +79,8 @@ def remotion_render_cmd(project: Path, comp: str, output: Path, props: Path, a:
79
79
  cmd.append(f"--frames={a.frames}")
80
80
  if a.concurrency:
81
81
  cmd.append(f"--concurrency={a.concurrency}")
82
+ if gl_backend(comp, getattr(a, "gl", None)):
83
+ cmd.append(f"--gl={gl_backend(comp, a.gl)}")
82
84
  return cmd
83
85
  cmd = [str(remotion_bin(project)), "render", "src/index.ts", comp, str(output), f"--props={props}",
84
86
  f"--codec={a.codec}", "--log=warn"]
@@ -94,12 +96,15 @@ def remotion_render_cmd(project: Path, comp: str, output: Path, props: Path, a:
94
96
  cmd.append("--crf=28")
95
97
  if a.concurrency:
96
98
  cmd.append(f"--concurrency={a.concurrency}")
99
+ if gl_backend(comp, getattr(a, "gl", None)):
100
+ cmd.append(f"--gl={gl_backend(comp, a.gl)}")
97
101
  return cmd
98
102
 
99
103
 
100
104
  def verify(out_probe: Dict[str, Any], timeline: Dict[str, Any], comp: str,
101
105
  frames: Optional[Tuple[int, int]], fast: bool,
102
- frame: Optional[Dict[str, Any]] = None) -> Tuple[bool, List[Dict[str, Any]]]:
106
+ frame: Optional[Dict[str, Any]] = None,
107
+ options: Optional[Dict[str, Any]] = None) -> Tuple[bool, List[Dict[str, Any]]]:
103
108
  src = timeline["source"]
104
109
  fps = float(src["fps"])
105
110
  v = out_probe.get("video") or {}
@@ -117,7 +122,7 @@ def verify(out_probe: Dict[str, Any], timeline: Dict[str, Any], comp: str,
117
122
  out_fps = float(v.get("fps") or 0)
118
123
  row("fps", abs(out_fps - fps) < 0.01, out_fps, fps)
119
124
 
120
- want = (frames[1] - frames[0] + 1) if frames else expected_frames(comp, timeline)
125
+ want = (frames[1] - frames[0] + 1) if frames else expected_frames(comp, timeline, options)
121
126
  duration = float(out_probe.get("duration") or v.get("duration") or 0)
122
127
  nb = v.get("nb_frames")
123
128
  if want is not None and isinstance(nb, int) and nb > 0:
@@ -202,6 +207,11 @@ def main() -> None:
202
207
  output = output.resolve()
203
208
  refuse_existing(output)
204
209
 
210
+ if a.comp == "Visualizer":
211
+ loop_range(timeline, options) # refuses a loop the measured beats cannot hold, before any render
212
+ if not (timeline["source"].get("has_audio") and timeline["source"].get("path")):
213
+ die("Visualizer draws the audio: this timeline's source has none (give a source with audio, or "
214
+ "analyze.py --blank with --music)", "input")
205
215
  if a.comp == "KineticType" and not timeline.get("kinetic"):
206
216
  die("KineticType draws the schedule analyze.py --kinetic writes (words or measured beats); this timeline "
207
217
  "has none: re-run analyze.py with --kinetic", "input")
@@ -240,7 +250,7 @@ def main() -> None:
240
250
  if STATE.dry_run:
241
251
  plan = [shell_join(cmd)] + ([shell_join(ffskill_cmd("overlay", ov_args))] if a.overlay else [])
242
252
  emit({"output": str(output), "commands": plan, "props": str(props_path),
243
- "expected_frames": (frames[1] - frames[0] + 1) if frames else expected_frames(a.comp, timeline),
253
+ "expected_frames": (frames[1] - frames[0] + 1) if frames else expected_frames(a.comp, timeline, options),
244
254
  "frame": frame, "font": font_note, "sparse": sparse_note},
245
255
  f"would render {a.comp} -> {output}")
246
256
  return
@@ -269,7 +279,7 @@ def main() -> None:
269
279
  graphics.unlink(missing_ok=True)
270
280
 
271
281
  probe = ffskill("probe", [str(output)])
272
- ok, rows = verify(probe, timeline, a.comp, frames, a.fast, frame)
282
+ ok, rows = verify(probe, timeline, a.comp, frames, a.fast, frame, options)
273
283
  look: Optional[str] = None
274
284
  look_error: Optional[str] = None
275
285
  commands.append(probe["_command"])
package/scripts/still.py CHANGED
@@ -13,7 +13,7 @@ from pathlib import Path
13
13
  from typing import List
14
14
 
15
15
  sys.path.insert(0, str(Path(__file__).resolve().parent))
16
- from _common import (BUILTIN_COMPOSITIONS, STATE, add_common, add_frame_args, apply_common, die, emit,
16
+ from _common import (gl_backend, BUILTIN_COMPOSITIONS, STATE, add_common, add_frame_args, apply_common, die, emit,
17
17
  expected_frames, info, load_look, load_timeline, prepare_props, refuse_existing, remotion_bin,
18
18
  require_project, remotion_error, run, sec_to_frames, shell_join)
19
19
 
@@ -43,7 +43,7 @@ def main() -> None:
43
43
  fps = float(timeline["source"]["fps"])
44
44
 
45
45
  frames: List[int] = list(a.frame) + [sec_to_frames(t, fps) for t in a.at]
46
- total = expected_frames(a.comp, timeline)
46
+ total = expected_frames(a.comp, timeline, options)
47
47
  if not frames:
48
48
  if total is None:
49
49
  die("custom composition: pass --frame or --at", "input")
@@ -64,6 +64,8 @@ def main() -> None:
64
64
  refuse_existing(out)
65
65
  cmd = [str(remotion_bin(project)), "still", "src/index.ts", a.comp, str(out),
66
66
  f"--props={props_path}", f"--frame={f}", "--log=warn"]
67
+ if gl_backend(a.comp, a.gl):
68
+ cmd.append(f"--gl={gl_backend(a.comp, a.gl)}")
67
69
  commands.append(shell_join(cmd))
68
70
  if STATE.dry_run:
69
71
  outputs.append(str(out))
@@ -9,12 +9,17 @@
9
9
  },
10
10
  "dependencies": {
11
11
  "@remotion/cli": "4.0.540",
12
+ "@remotion/media-utils": "4.0.540",
13
+ "@remotion/three": "4.0.540",
14
+ "@react-three/fiber": "9.8.2",
12
15
  "remotion": "4.0.540",
13
16
  "react": "19.3.1",
14
- "react-dom": "19.3.1"
17
+ "react-dom": "19.3.1",
18
+ "three": "0.186.1"
15
19
  },
16
20
  "devDependencies": {
17
21
  "@types/react": "^19.0.0",
22
+ "@types/three": "0.186.0",
18
23
  "typescript": "^7.0.2"
19
24
  }
20
25
  }
@@ -10,7 +10,19 @@ import { Karaoke } from "./compositions/Karaoke";
10
10
  import { Pip } from "./compositions/Pip";
11
11
  import { Emphasis } from "./compositions/Emphasis";
12
12
  import { KineticType } from "./compositions/KineticType";
13
- import { SAMPLE_TIMELINE, fullLengthFrames, highlightFrames, jumpcutFrames, outputFrame, type Props, type Timeline } from "./timeline";
13
+ import { Visualizer } from "./compositions/Visualizer";
14
+ import { ThreeScene } from "./compositions/ThreeScene";
15
+ import {
16
+ SAMPLE_TIMELINE,
17
+ fullLengthFrames,
18
+ highlightFrames,
19
+ jumpcutFrames,
20
+ outputFrame,
21
+ resolveOptions,
22
+ visualizerRange,
23
+ type Props,
24
+ type Timeline,
25
+ } from "./timeline";
14
26
 
15
27
  // Length and fps come from the measured timeline, never from constants; the frame is the
16
28
  // source's probed size unless render.py was given another shape (--aspect).
@@ -21,6 +33,13 @@ const metadataFrom =
21
33
  return { durationInFrames: frames(props.timeline), fps: props.timeline.source.fps, width: f.width, height: f.height };
22
34
  };
23
35
 
36
+ // The Visualizer's length also depends on its options: a loop is a whole number of measured bars.
37
+ const visualizerMetadata: CalculateMetadataFunction<Props> = ({ props }) => {
38
+ const f = outputFrame(props);
39
+ const [, frames] = visualizerRange(props.timeline, resolveOptions(props.options));
40
+ return { durationInFrames: frames, fps: props.timeline.source.fps, width: f.width, height: f.height };
41
+ };
42
+
24
43
  const defaultProps: Props = { timeline: SAMPLE_TIMELINE, options: {}, frame: null, font: null };
25
44
  const base = { durationInFrames: 240, fps: 30, width: 1280, height: 720, defaultProps };
26
45
 
@@ -36,5 +55,7 @@ export const RemotionRoot: React.FC = () => (
36
55
  <Composition id="Pip" component={Pip} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
37
56
  <Composition id="Emphasis" component={Emphasis} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
38
57
  <Composition id="KineticType" component={KineticType} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
58
+ <Composition id="Visualizer" component={Visualizer} {...base} calculateMetadata={visualizerMetadata} />
59
+ <Composition id="ThreeScene" component={ThreeScene} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
39
60
  </>
40
61
  );
@@ -35,7 +35,7 @@ export const Karaoke: React.FC<Props> = (props) => {
35
35
  );
36
36
  };
37
37
 
38
- const KaraokeCue: React.FC<{ cue: Caption; words: Caption[]; len: number; o: Options; fontFamily: string }> = ({
38
+ export const KaraokeCue: React.FC<{ cue: Caption; words: Caption[]; len: number; o: Options; fontFamily: string }> = ({
39
39
  cue,
40
40
  words,
41
41
  len,
@@ -0,0 +1,83 @@
1
+ import React, { useMemo } from "react";
2
+ import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";
3
+ import { ThreeCanvas } from "@remotion/three";
4
+ import { SourceVideo } from "../lib/SourceVideo";
5
+ import { Props, beatTimes, outputFrame, resolveOptions, secToFrames } from "../timeline";
6
+
7
+ /** mulberry32: a small seeded generator, so the same seed always places the same particles. */
8
+ const seeded = (seed: number) => {
9
+ let a = seed >>> 0;
10
+ return () => {
11
+ a = (a + 0x6d2b79f5) >>> 0;
12
+ let t = a;
13
+ t = Math.imul(t ^ (t >>> 15), t | 1);
14
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
15
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
16
+ };
17
+ };
18
+
19
+ /**
20
+ * ThreeScene: a Three.js scene (@remotion/three) over the source, a function of the frame number and
21
+ * options.seed alone -- no clock, no requestAnimationFrame, no Math.random -- so the same frame gives the same
22
+ * pixels on one machine and GL backend (render.py --gl; doctor.py names it). A field of seeded particles drifts
23
+ * round a centre shape while the camera orbits; the shape hits on every measured beat (or measured audio peak
24
+ * when no beat grid was measured), with the same decay PeakPulse uses.
25
+ */
26
+ export const ThreeScene: React.FC<Props> = (props) => {
27
+ const { timeline, options, overlay } = props;
28
+ const o = resolveOptions(options);
29
+ const frame = useCurrentFrame();
30
+ const { fps, width, height } = useVideoConfig();
31
+ const beats = beatTimes(timeline);
32
+ const maxRms = Math.max(1e-6, ...timeline.peaks.map((p) => p.rms));
33
+ const events = beats.length > 0 ? beats.map((t) => ({ t, s: 1 })) : timeline.peaks.map((p) => ({ t: p.time, s: p.rms / maxRms }));
34
+ let hit = 0;
35
+ for (const ev of events) {
36
+ const f = secToFrames(ev.t, fps);
37
+ if (f > frame) continue;
38
+ hit = Math.max(hit, ev.s * Math.exp(-(frame - f) / (fps * 0.15)));
39
+ }
40
+ const count = Math.max(1, Math.min(5000, Math.round(o.threeParticles)));
41
+ const particles = useMemo(() => {
42
+ const rnd = seeded(o.seed);
43
+ return Array.from({ length: count }, () => {
44
+ const r = 2.2 + rnd() * 4;
45
+ const theta = rnd() * Math.PI * 2;
46
+ const y = (rnd() - 0.5) * 4;
47
+ return { r, theta, y, speed: 0.2 + rnd() * 0.6, size: 0.02 + rnd() * 0.05 };
48
+ });
49
+ }, [o.seed, count]);
50
+ const t = frame / fps;
51
+ const cam = 0.25 * t;
52
+ return (
53
+ <AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
54
+ {overlay ? null : <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} />}
55
+ <ThreeCanvas
56
+ width={width}
57
+ height={height}
58
+ gl={{ antialias: true, alpha: true, preserveDrawingBuffer: true }}
59
+ camera={{ fov: 50, near: 0.1, far: 100, position: [0, 0, 9] }}
60
+ style={{ position: "absolute", inset: 0 }}
61
+ >
62
+ <ambientLight intensity={0.5} />
63
+ <directionalLight position={[4, 6, 5]} intensity={1.6} />
64
+ {/* the "orbit": the scene turns under a fixed camera, a function of the frame */}
65
+ <group rotation={[0.25, -cam, 0]}>
66
+ <mesh rotation={[t * 0.6, t * 0.9, 0]} scale={1 + 0.35 * hit}>
67
+ <icosahedronGeometry args={[1.3, 1]} />
68
+ <meshStandardMaterial color={o.accent} emissive={o.accent} emissiveIntensity={0.15 + 0.85 * hit} flatShading />
69
+ </mesh>
70
+ {particles.map((p, i) => {
71
+ const a = p.theta + t * p.speed * 0.5;
72
+ return (
73
+ <mesh key={i} position={[Math.cos(a) * p.r, p.y + Math.sin(t * p.speed + i) * 0.15, Math.sin(a) * p.r]}>
74
+ <sphereGeometry args={[p.size * (1 + hit), 8, 8]} />
75
+ <meshBasicMaterial color={o.textColor} />
76
+ </mesh>
77
+ );
78
+ })}
79
+ </group>
80
+ </ThreeCanvas>
81
+ </AbsoluteFill>
82
+ );
83
+ };
@@ -0,0 +1,168 @@
1
+ import React from "react";
2
+ import { AbsoluteFill, Sequence, staticFile, useCurrentFrame, useVideoConfig } from "remotion";
3
+ import { createSmoothSvgPath, useAudioData, visualizeAudio, visualizeAudioWaveform } from "@remotion/media-utils";
4
+ import { SourceVideo } from "../lib/SourceVideo";
5
+ import { useStagedFont } from "../lib/useStagedFont";
6
+ import { KaraokeCue } from "./Karaoke";
7
+ import { Props, beatTimes, fontStack, outputFrame, resolveOptions, secToFrames, visualizerRange, type Options } from "../timeline";
8
+
9
+ /** FFT size / 2 that visualizeAudio is asked for: 1024 samples (23 ms at 44.1 kHz), centred on the frame's time. */
10
+ const FFT_BINS = 512;
11
+
12
+ /**
13
+ * Visualizer: the source's own audio drawn each frame (@remotion/media-utils, decoded in the browser) as bars,
14
+ * a spectrum, radial bars or a waveform, a ring that hits on every measured beat, and the caption cues as
15
+ * Karaoke draws them. With loopBars it is a loop: from the first measured beat over a whole number of measured
16
+ * bars, so its last frame runs into its first. No smoothing across frames: what a frame shows is the audio
17
+ * around that frame's time and nothing later.
18
+ */
19
+ export const Visualizer: React.FC<Props> = (props) => {
20
+ const { timeline, options, font, overlay } = props;
21
+ useStagedFont(font);
22
+ const o = resolveOptions(options);
23
+ const family = fontStack(o, font);
24
+ const { fps } = useVideoConfig();
25
+ const [start] = visualizerRange(timeline, o);
26
+ const words = timeline.words ?? [];
27
+ return (
28
+ <AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
29
+ {overlay ? null : (
30
+ <SourceVideo background={o.background} source={timeline.source} fit={outputFrame(props).fit} trimBefore={start > 0 ? start : undefined} />
31
+ )}
32
+ {timeline.source.src ? <Drawing src={timeline.source.src} start={start} o={o} beats={beatTimes(timeline)} /> : null}
33
+ {timeline.captions.map((c, i) => {
34
+ const from = secToFrames(c.start, fps) - start;
35
+ const dur = Math.max(1, secToFrames(c.end, fps) - secToFrames(c.start, fps));
36
+ if (from + dur <= 0) return null;
37
+ const own = words.filter((w) => (w.start + w.end) / 2 >= c.start && (w.start + w.end) / 2 <= c.end);
38
+ return (
39
+ <Sequence key={i} from={from} durationInFrames={dur} name={`cue ${i + 1}`} layout="none">
40
+ <KaraokeCue cue={c} words={own} len={dur} o={o} fontFamily={family} />
41
+ </Sequence>
42
+ );
43
+ })}
44
+ </AbsoluteFill>
45
+ );
46
+ };
47
+
48
+ /** Bin edges for `n` bars over FFT_BINS bins, spaced logarithmically (low frequencies get more bars). */
49
+ const edges = (n: number): number[] => {
50
+ const out: number[] = [1];
51
+ for (let i = 1; i <= n; i++) {
52
+ const e = Math.round(Math.pow(FFT_BINS, i / n));
53
+ out.push(Math.max(out[i - 1] + 1, Math.min(FFT_BINS, e)));
54
+ }
55
+ return out;
56
+ };
57
+
58
+ /** A magnitude as 0..1 on a 60 dB scale. */
59
+ const level = (m: number): number => Math.max(0, Math.min(1, (20 * Math.log10(Math.max(m, 1e-9)) + 60) / 60));
60
+
61
+ const Drawing: React.FC<{ src: string; start: number; o: Options; beats: number[] }> = ({ src, start, o, beats }) => {
62
+ const frame = useCurrentFrame();
63
+ const { fps, width, height } = useVideoConfig();
64
+ const audioData = useAudioData(staticFile(src));
65
+ const sourceFrame = start + frame;
66
+ const n = Math.max(8, Math.min(256, Math.round(o.visualizerBars)));
67
+ // the ring: the strongest decaying hit of the measured beats at or before this frame
68
+ let hit = 0;
69
+ for (const b of beats) {
70
+ const bf = secToFrames(b, fps);
71
+ if (bf > sourceFrame) break;
72
+ hit = Math.exp(-(sourceFrame - bf) / (fps * 0.15));
73
+ }
74
+ if (!audioData) return null;
75
+ const short = Math.min(width, height);
76
+ let values: number[];
77
+ if (o.visualizer === "waveform") {
78
+ values = visualizeAudioWaveform({ audioData, frame: sourceFrame, fps, windowInSeconds: 0.08, numberOfSamples: n });
79
+ } else {
80
+ const mags = visualizeAudio({ audioData, frame: sourceFrame, fps, numberOfSamples: FFT_BINS, smoothing: false });
81
+ const e = edges(n);
82
+ values = Array.from({ length: n }, (_, i) => level(Math.max(...mags.slice(e[i], e[i + 1]))));
83
+ }
84
+ const ring = (
85
+ <div
86
+ style={{
87
+ position: "absolute",
88
+ left: width / 2 - short * 0.12,
89
+ top: height / 2 - short * 0.12,
90
+ width: short * 0.24,
91
+ height: short * 0.24,
92
+ borderRadius: "50%",
93
+ border: `${Math.max(2, Math.round(short * 0.012))}px solid ${o.accent}`,
94
+ opacity: 0.35 + 0.65 * hit,
95
+ transform: `scale(${1 + 0.25 * hit})`,
96
+ }}
97
+ />
98
+ );
99
+ if (o.visualizer === "radial") {
100
+ const r = short * 0.16;
101
+ return (
102
+ <AbsoluteFill>
103
+ {ring}
104
+ {values.map((v, i) => {
105
+ const len = Math.max(2, v * short * 0.24);
106
+ const angle = (i / n) * 360;
107
+ return (
108
+ <div
109
+ key={i}
110
+ style={{
111
+ position: "absolute",
112
+ left: width / 2 - short * 0.006,
113
+ top: height / 2,
114
+ width: short * 0.012,
115
+ height: len,
116
+ background: o.textColor,
117
+ borderRadius: short * 0.006,
118
+ transformOrigin: "50% 0",
119
+ transform: `rotate(${angle + 180}deg) translateY(${r}px)`,
120
+ }}
121
+ />
122
+ );
123
+ })}
124
+ </AbsoluteFill>
125
+ );
126
+ }
127
+ if (o.visualizer === "spectrum" || o.visualizer === "waveform") {
128
+ const mid = height * 0.5;
129
+ const amp = height * 0.3;
130
+ const points = values.map((v, i) => ({
131
+ x: (width * (i + 0.5)) / n,
132
+ y: o.visualizer === "waveform" ? mid - v * amp : height * 0.85 - v * height * 0.5,
133
+ }));
134
+ const path = createSmoothSvgPath({ points });
135
+ return (
136
+ <AbsoluteFill>
137
+ {ring}
138
+ <svg width={width} height={height} style={{ position: "absolute" }}>
139
+ {o.visualizer === "spectrum" ? (
140
+ <path d={`${path} L ${points[n - 1].x} ${height * 0.85} L ${points[0].x} ${height * 0.85} Z`} fill={o.accent} fillOpacity={0.75} />
141
+ ) : (
142
+ <path d={path} fill="none" stroke={o.accent} strokeWidth={Math.max(2, short * 0.008)} />
143
+ )}
144
+ </svg>
145
+ </AbsoluteFill>
146
+ );
147
+ }
148
+ const slot = width / n;
149
+ return (
150
+ <AbsoluteFill>
151
+ {ring}
152
+ {values.map((v, i) => (
153
+ <div
154
+ key={i}
155
+ style={{
156
+ position: "absolute",
157
+ left: i * slot + slot * 0.15,
158
+ width: slot * 0.7,
159
+ bottom: height * 0.06,
160
+ height: Math.max(2, v * height * 0.45),
161
+ background: i % 2 === 0 ? o.accent : o.textColor,
162
+ borderRadius: slot * 0.2,
163
+ }}
164
+ />
165
+ ))}
166
+ </AbsoluteFill>
167
+ );
168
+ };
@@ -164,6 +164,19 @@ export type Options = {
164
164
  kineticStagger: number;
165
165
  /** KineticType: text size as a fraction of the frame's short side. */
166
166
  kineticSize: number;
167
+ /** Visualizer: what is drawn from the audio each frame. */
168
+ visualizer: "bars" | "spectrum" | "radial" | "waveform";
169
+ /** Visualizer: number of bars (or points) drawn, 8..256. */
170
+ visualizerBars: number;
171
+ /** Visualizer: null = the whole source; 0 = a loop of as many whole bars as the measured beats hold; N = N bars.
172
+ * A loop starts on the first measured beat and ends on the beat N * beatsPerBar after it. */
173
+ loopBars: number | null;
174
+ /** Visualizer: measured beats per bar (4 for 4/4). */
175
+ beatsPerBar: number;
176
+ /** ThreeScene: the seed that places the particles (same seed, same scene). */
177
+ seed: number;
178
+ /** ThreeScene: number of particles, 1..5000. */
179
+ threeParticles: number;
167
180
  };
168
181
 
169
182
  export const DEFAULT_OPTIONS: Options = {
@@ -193,6 +206,12 @@ export const DEFAULT_OPTIONS: Options = {
193
206
  kineticReveal: "char",
194
207
  kineticStagger: 0.04,
195
208
  kineticSize: 0.09,
209
+ visualizer: "bars",
210
+ visualizerBars: 48,
211
+ loopBars: null,
212
+ beatsPerBar: 4,
213
+ seed: 1,
214
+ threeParticles: 300,
196
215
  };
197
216
 
198
217
  /** Where the camera plays on the source timeline: [from, durationInFrames, trimBefore] in frames. */
@@ -304,6 +323,27 @@ export const highlightFrames = (t: Timeline): number => {
304
323
  return Math.max(1, total);
305
324
  };
306
325
 
326
+ /**
327
+ * The Visualizer's range on the source, in frames: [first frame, length]. Without loopBars, the whole source.
328
+ * With it, a loop of loopBars * beatsPerBar measured beats (0 = as many whole bars as the beats hold). Its seam
329
+ * falls halfway between two measured beats, where beat-driven motion is quietest: it starts halfway between the
330
+ * first and second beats and ends halfway between beat k and beat k + 1 (k = bars * beatsPerBar), so the last
331
+ * frame runs into the first. loop_range() in scripts/_common.py mirrors this; render.py refuses a loop the
332
+ * beats cannot hold before rendering.
333
+ */
334
+ export const visualizerRange = (t: Timeline, o: Options): [number, number] => {
335
+ const fps = t.source.fps;
336
+ if (o.loopBars === null || o.loopBars === undefined) return [0, fullLengthFrames(t)];
337
+ const beats = beatTimes(t).filter((b) => b < t.source.duration);
338
+ const per = Math.max(1, Math.round(o.beatsPerBar));
339
+ const most = Math.floor((beats.length - 2) / per);
340
+ const bars = o.loopBars === 0 ? most : Math.min(o.loopBars, most);
341
+ if (bars < 1) return [0, fullLengthFrames(t)];
342
+ const k = bars * per;
343
+ const start = secToFrames((beats[0] + beats[1]) / 2, fps);
344
+ return [start, Math.max(1, secToFrames((beats[k] + beats[k + 1]) / 2, fps) - start)];
345
+ };
346
+
307
347
  /** Usable measured beat times (empty when the grid was not measured or not confident). */
308
348
  export const beatTimes = (t: Timeline): number[] => (t.beats && t.beats.usable ? t.beats.times : []);
309
349