vizmatic 0.7.1 → 0.7.2

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.
@@ -1753,6 +1753,35 @@ async function renderToSvgInContext(element, width, height, options) {
1753
1753
  }
1754
1754
 
1755
1755
  // src/video.ts
1756
+ function chapterMetadata(title, chapters, duration) {
1757
+ const escape = (value) => value.replace(/[\\=;#]/g, (c) => `\\${c}`).replace(/\r?\n/g, " ");
1758
+ const marks = chapters.filter((chapter) => Number.isFinite(chapter.time) && chapter.time < duration).map((chapter) => ({ title: chapter.title, time: Math.max(0, chapter.time) })).sort((a, b) => a.time - b.time);
1759
+ if (marks.length > 0) marks[0].time = 0;
1760
+ let out = ";FFMETADATA1\n";
1761
+ if (title) out += `title=${escape(title)}
1762
+ `;
1763
+ marks.forEach((mark, index) => {
1764
+ const end = index + 1 < marks.length ? marks[index + 1].time : duration;
1765
+ out += `[CHAPTER]
1766
+ TIMEBASE=1/1000
1767
+ START=${Math.round(mark.time * 1e3)}
1768
+ END=${Math.round(end * 1e3)}
1769
+ title=${escape(mark.title)}
1770
+ `;
1771
+ });
1772
+ return out;
1773
+ }
1774
+ function captionsToSrt(captions, duration) {
1775
+ const stamp = (seconds) => {
1776
+ const ms = Math.round(seconds * 1e3);
1777
+ const pad = (value, size = 2) => String(value).padStart(size, "0");
1778
+ return `${pad(Math.floor(ms / 36e5))}:${pad(Math.floor(ms / 6e4) % 60)}:${pad(Math.floor(ms / 1e3) % 60)},${pad(ms % 1e3, 3)}`;
1779
+ };
1780
+ return captions.filter((cue) => cue.t1 > 0 && cue.t0 < duration && cue.t1 > cue.t0 && cue.text.trim().length > 0).sort((a, b) => a.t0 - b.t0).map((cue, index) => `${index + 1}
1781
+ ${stamp(Math.max(0, cue.t0))} --> ${stamp(Math.min(duration, cue.t1))}
1782
+ ${cue.text.trim()}
1783
+ `).join("\n");
1784
+ }
1756
1785
  var MAX_STDERR_CHARS = 8192;
1757
1786
  var COLOR_FILTER = "scale=in_range=pc:out_range=tv:out_color_matrix=bt709:flags=lanczos+accurate_rnd+full_chroma_int,format=yuv420p,setparams=range=tv:color_primaries=bt709:color_trc=bt709:colorspace=bt709";
1758
1787
  var COLOR_TAGS = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"];
@@ -1899,12 +1928,37 @@ async function renderRgbaVideo(renderFrame, options) {
1899
1928
  "-i",
1900
1929
  "pipe:0"
1901
1930
  ];
1931
+ let inputs = 1;
1932
+ let audioInput = -1;
1902
1933
  if (options.audioPath) {
1903
1934
  if (options.audioOffset) args.push("-ss", String(options.audioOffset));
1904
1935
  args.push("-i", (0, import_path2.resolve)(options.audioPath));
1936
+ audioInput = inputs++;
1937
+ }
1938
+ const sidecars = [];
1939
+ let metadataInput = -1, captionInput = -1;
1940
+ if (codec === "h264") {
1941
+ const chapters = options.chapters ?? [];
1942
+ if (options.title || chapters.length > 0) {
1943
+ const path = (0, import_path2.join)(outputDirectory, `.${(0, import_path2.basename)(outputPath)}.${(0, import_crypto.randomUUID)()}.tmp.ffmeta`);
1944
+ await (0, import_promises2.writeFile)(path, chapterMetadata(options.title, chapters, schedule.duration), { mode: 384 });
1945
+ sidecars.push(path);
1946
+ args.push("-f", "ffmetadata", "-i", path);
1947
+ metadataInput = inputs++;
1948
+ }
1949
+ const srt = captionsToSrt(options.captions ?? [], schedule.duration);
1950
+ if (srt) {
1951
+ const path = (0, import_path2.join)(outputDirectory, `.${(0, import_path2.basename)(outputPath)}.${(0, import_crypto.randomUUID)()}.tmp.srt`);
1952
+ await (0, import_promises2.writeFile)(path, srt, { mode: 384 });
1953
+ sidecars.push(path);
1954
+ args.push("-f", "srt", "-i", path);
1955
+ captionInput = inputs++;
1956
+ }
1905
1957
  }
1906
1958
  args.push("-map", "0:v:0");
1907
- if (options.audioPath) args.push("-map", "1:a:0", "-af", `asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);
1959
+ if (options.audioPath) args.push("-map", `${audioInput}:a:0`, "-af", `asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);
1960
+ if (captionInput >= 0) args.push("-map", `${captionInput}:0`, "-c:s", "mov_text", "-metadata:s:s:0", "language=eng");
1961
+ if (metadataInput >= 0) args.push("-map_metadata", String(metadataInput), "-map_chapters", String(metadataInput));
1908
1962
  args.push("-frames:v", String(schedule.count), "-t", seconds, "-vf", COLOR_FILTER);
1909
1963
  if (codec === "vp9") {
1910
1964
  args.push("-c:v", "libvpx-vp9", "-crf", String(crf), "-b:v", "0", "-deadline", "good", "-cpu-used", "2", "-row-mt", "1", "-threads:v", String(threads));
@@ -1928,6 +1982,7 @@ async function renderRgbaVideo(renderFrame, options) {
1928
1982
  child = (0, import_child_process.spawn)(ffmpegPath, args, { stdio: ["pipe", "ignore", "pipe"] });
1929
1983
  } catch (error) {
1930
1984
  await (0, import_promises2.rm)(tempPath, { force: true });
1985
+ for (const path of sidecars) await (0, import_promises2.rm)(path, { force: true });
1931
1986
  throw error;
1932
1987
  }
1933
1988
  child.stderr?.on("data", (chunk) => {
@@ -2029,6 +2084,7 @@ async function renderRgbaVideo(renderFrame, options) {
2029
2084
  throw error;
2030
2085
  } finally {
2031
2086
  await (0, import_promises2.rm)(tempPath, { force: true });
2087
+ for (const path of sidecars) await (0, import_promises2.rm)(path, { force: true });
2032
2088
  }
2033
2089
  }
2034
2090
 
@@ -4800,6 +4856,10 @@ async function renderFilmVideo(film, outputPath, options = {}) {
4800
4856
  audioPath: options.audioPath,
4801
4857
  audioOffset: from > 0 ? from : void 0,
4802
4858
  ffmpegPath: options.ffmpegPath,
4859
+ // An MP4 carries the film's title, chapters, and captions. A range render shifts them to its own start.
4860
+ title: compiled.title,
4861
+ chapters: options.chapters === false ? [] : shiftedChapters(compiled, from),
4862
+ captions: options.embedCaptions === false ? [] : compiled.captions.map((cue) => ({ t0: cue.t0 - from, t1: cue.t1 - from, text: cue.text })),
4803
4863
  signal: options.signal,
4804
4864
  onProgress: options.onProgress
4805
4865
  });
@@ -4808,6 +4868,12 @@ async function renderFilmVideo(film, outputPath, options = {}) {
4808
4868
  await pool.close();
4809
4869
  }
4810
4870
  }
4871
+ function shiftedChapters(film, from) {
4872
+ const sorted = [...film.chapters].sort((a, b) => a.time - b.time);
4873
+ const running = sorted.filter((chapter) => chapter.time <= from).pop();
4874
+ const later = sorted.filter((chapter) => chapter.time > from).map((chapter) => ({ title: chapter.title, time: chapter.time - from }));
4875
+ return running ? [{ title: running.title, time: 0 }, ...later] : later;
4876
+ }
4811
4877
  var gifApi = typeof gifenc.GIFEncoder === "function" ? gifenc : gifenc.default;
4812
4878
  function changedRegion(previous, current, width, height) {
4813
4879
  let minX = width, minY = height, maxX = -1, maxY = -1;
@@ -1,4 +1,4 @@
1
- import { V as VideoCodec } from './video-CcHW1qhV.cjs';
1
+ import { V as VideoCodec } from './video-BSwNJZkn.cjs';
2
2
  import { ThemeMode, RenderBackground, VideoFrameInfo, RgbaVideoOutput } from './index.cjs';
3
3
  import { FromSvgOptions, SvgNode, CompileOverrides, CompiledFilm, FilmDefinition } from './stage.cjs';
4
4
  import { ReactNode } from 'react';
@@ -38,6 +38,10 @@ interface FilmRenderOptions extends CompileOverrides {
38
38
  memoryBudget?: number;
39
39
  from?: number;
40
40
  to?: number;
41
+ /** Set to false to leave chapter markers out of an MP4. */
42
+ chapters?: boolean;
43
+ /** Set to false to leave the caption track out of an MP4. The WebVTT sidecar is not affected. */
44
+ embedCaptions?: boolean;
41
45
  audioPath?: string;
42
46
  ffmpegPath?: string;
43
47
  /** Encoder threads. Rasterizing is usually the slower step, so a few are enough. */
@@ -1,4 +1,4 @@
1
- import { V as VideoCodec } from './video-CcHW1qhV.js';
1
+ import { V as VideoCodec } from './video-BSwNJZkn.js';
2
2
  import { ThemeMode, RenderBackground, VideoFrameInfo, RgbaVideoOutput } from './index.js';
3
3
  import { FromSvgOptions, SvgNode, CompileOverrides, CompiledFilm, FilmDefinition } from './stage.js';
4
4
  import { ReactNode } from 'react';
@@ -38,6 +38,10 @@ interface FilmRenderOptions extends CompileOverrides {
38
38
  memoryBudget?: number;
39
39
  from?: number;
40
40
  to?: number;
41
+ /** Set to false to leave chapter markers out of an MP4. */
42
+ chapters?: boolean;
43
+ /** Set to false to leave the caption track out of an MP4. The WebVTT sidecar is not affected. */
44
+ embedCaptions?: boolean;
41
45
  audioPath?: string;
42
46
  ffmpegPath?: string;
43
47
  /** Encoder threads. Rasterizing is usually the slower step, so a few are enough. */
@@ -2,7 +2,7 @@ import {
2
2
  encodePng,
3
3
  renderRgbaVideo,
4
4
  renderToSvg
5
- } from "./chunk-DTD35LPT.js";
5
+ } from "./chunk-F6QI6QJY.js";
6
6
  import "./chunk-RPAHMKAR.js";
7
7
  import {
8
8
  frameToSvg,
@@ -347,6 +347,10 @@ async function renderFilmVideo(film, outputPath, options = {}) {
347
347
  audioPath: options.audioPath,
348
348
  audioOffset: from > 0 ? from : void 0,
349
349
  ffmpegPath: options.ffmpegPath,
350
+ // An MP4 carries the film's title, chapters, and captions. A range render shifts them to its own start.
351
+ title: compiled.title,
352
+ chapters: options.chapters === false ? [] : shiftedChapters(compiled, from),
353
+ captions: options.embedCaptions === false ? [] : compiled.captions.map((cue) => ({ t0: cue.t0 - from, t1: cue.t1 - from, text: cue.text })),
350
354
  signal: options.signal,
351
355
  onProgress: options.onProgress
352
356
  });
@@ -355,6 +359,12 @@ async function renderFilmVideo(film, outputPath, options = {}) {
355
359
  await pool.close();
356
360
  }
357
361
  }
362
+ function shiftedChapters(film, from) {
363
+ const sorted = [...film.chapters].sort((a, b) => a.time - b.time);
364
+ const running = sorted.filter((chapter) => chapter.time <= from).pop();
365
+ const later = sorted.filter((chapter) => chapter.time > from).map((chapter) => ({ title: chapter.title, time: chapter.time - from }));
366
+ return running ? [{ title: running.title, time: 0 }, ...later] : later;
367
+ }
358
368
  var gifApi = typeof gifenc.GIFEncoder === "function" ? gifenc : gifenc.default;
359
369
  function changedRegion(previous, current, width, height) {
360
370
  let minX = width, minY = height, maxX = -1, maxY = -1;
package/dist/stage.cjs CHANGED
@@ -184,6 +184,7 @@ __export(stage_exports, {
184
184
  Line3D: () => Line3D,
185
185
  LineChart: () => LineChart,
186
186
  MatrixNode: () => MatrixNode,
187
+ Narration: () => Narration,
187
188
  NeuralNet: () => NeuralNet,
188
189
  Node: () => Node,
189
190
  NumberLine: () => NumberLine,
@@ -193,6 +194,7 @@ __export(stage_exports, {
193
194
  Points3D: () => Points3D,
194
195
  Scatter: () => Scatter,
195
196
  Scene3D: () => Scene3D,
197
+ SceneClock: () => SceneClock,
196
198
  Stage: () => Stage,
197
199
  StreamLines: () => StreamLines,
198
200
  Surface3D: () => Surface3D,
@@ -229,6 +231,7 @@ __export(stage_exports, {
229
231
  buildOps: () => buildOps,
230
232
  call: () => call,
231
233
  callout: () => callout,
234
+ captionLines: () => captionLines,
232
235
  chalk: () => chalk,
233
236
  checkFilm: () => checkFilm,
234
237
  circle: () => circle,
@@ -288,6 +291,7 @@ __export(stage_exports, {
288
291
  heatmap: () => heatmap,
289
292
  highlightSweep: () => highlightSweep,
290
293
  histogram: () => histogram,
294
+ image: () => image,
291
295
  indicate: () => indicate,
292
296
  infoBox: () => infoBox,
293
297
  invert: () => invert,
@@ -313,6 +317,7 @@ __export(stage_exports, {
313
317
  morphMatching: () => morphMatching,
314
318
  moveTo: () => moveTo,
315
319
  mul: () => mul,
320
+ narration: () => narration,
316
321
  neon: () => neon,
317
322
  neuralNet: () => neuralNet,
318
323
  notQuiteThere: () => notQuiteThere,
@@ -857,17 +862,17 @@ function reverseRing(r) {
857
862
  return { p: out, closed: r.closed };
858
863
  }
859
864
  function parseSvgPath(d) {
860
- const tokens3 = d.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g);
861
- if (!tokens3) return [];
865
+ const tokens4 = d.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g);
866
+ if (!tokens4) return [];
862
867
  const rings = [];
863
868
  let out = [];
864
869
  let i = 0, x = 0, y = 0, startX = 0, startY = 0;
865
870
  let lastCmd = "", lastCx = 0, lastCy = 0;
866
- const num = () => Number(tokens3[i++]);
871
+ const num = () => Number(tokens4[i++]);
867
872
  const flags = () => {
868
- const token = tokens3[i];
873
+ const token = tokens4[i];
869
874
  if (token.length > 1 && (token[0] === "0" || token[0] === "1") && !token.startsWith("0.") && !token.startsWith("1.")) {
870
- tokens3[i] = token.slice(1);
875
+ tokens4[i] = token.slice(1);
871
876
  return Number(token[0]);
872
877
  }
873
878
  i++;
@@ -881,8 +886,8 @@ function parseSvgPath(d) {
881
886
  if (out.length === 0) out.push(px, py);
882
887
  };
883
888
  let cmd = "";
884
- while (i < tokens3.length) {
885
- const token = tokens3[i];
889
+ while (i < tokens4.length) {
890
+ const token = tokens4[i];
886
891
  if (/^[a-zA-Z]$/.test(token)) {
887
892
  cmd = token;
888
893
  i++;
@@ -1885,8 +1890,8 @@ var Node = class _Node {
1885
1890
  let result = null;
1886
1891
  const path = this.get("path");
1887
1892
  if (path) result = pathBounds(transformPath(path, m));
1888
- const image = this.get("image");
1889
- if (image) result = unionBounds(result, boundsOfRect(m, image.width, image.height));
1893
+ const image2 = this.get("image");
1894
+ if (image2) result = unionBounds(result, boundsOfRect(m, image2.width, image2.height));
1890
1895
  if (this.draw) {
1891
1896
  const built = this.draw(clock.now);
1892
1897
  const list3 = built === null ? [] : Array.isArray(built) ? built : [built];
@@ -2889,8 +2894,8 @@ function walk(node, parent, screen, alpha, ops) {
2889
2894
  const m = mul(base, node.localMatrix());
2890
2895
  const path = node.get("path");
2891
2896
  if (path && path.length > 0) emit(node, path, m, opacity, ops);
2892
- const image = node.get("image");
2893
- if (image) ops.push({ kind: "image", image, matrix: m, alpha: opacity });
2897
+ const image2 = node.get("image");
2898
+ if (image2) ops.push({ kind: "image", image: image2, matrix: m, alpha: opacity });
2894
2899
  if (node.rawOps) node.rawOps(m, opacity, ops);
2895
2900
  if (node.draw) {
2896
2901
  const built = node.draw(clockNow());
@@ -4313,6 +4318,45 @@ function regularPolygon(sides, radius, style = {}) {
4313
4318
  }
4314
4319
  return polygon(points, style);
4315
4320
  }
4321
+ function intrinsicSize(src) {
4322
+ const match = /^data:image\/(png|gif|jpeg|jpg);base64,/.exec(src);
4323
+ if (!match || typeof atob !== "function") return null;
4324
+ let head;
4325
+ try {
4326
+ head = atob(src.slice(match[0].length, match[0].length + (match[1] === "jpeg" || match[1] === "jpg" ? 87384 : 44)));
4327
+ } catch {
4328
+ return null;
4329
+ }
4330
+ const byte = (i) => head.charCodeAt(i);
4331
+ if (match[1] === "png") return head.length >= 24 ? [byte(16) * 16777216 + byte(17) * 65536 + byte(18) * 256 + byte(19), byte(20) * 16777216 + byte(21) * 65536 + byte(22) * 256 + byte(23)] : null;
4332
+ if (match[1] === "gif") return head.length >= 10 ? [byte(6) + byte(7) * 256, byte(8) + byte(9) * 256] : null;
4333
+ for (let i = 2; i + 9 < head.length; ) {
4334
+ if (byte(i) !== 255) return null;
4335
+ const marker = byte(i + 1);
4336
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) return [byte(i + 7) * 256 + byte(i + 8), byte(i + 5) * 256 + byte(i + 6)];
4337
+ i += 2 + byte(i + 2) * 256 + byte(i + 3);
4338
+ }
4339
+ return null;
4340
+ }
4341
+ function image(src, options = {}) {
4342
+ const natural = intrinsicSize(src);
4343
+ let width = options.width, height = options.height;
4344
+ if (width === void 0 && height === void 0) {
4345
+ if (!natural) throw new Error("image() needs a width or a height when the picture is not a PNG, GIF, or JPEG data URL.");
4346
+ [width, height] = natural;
4347
+ } else if (width === void 0 || height === void 0) {
4348
+ if (!natural) throw new Error("image() needs both width and height when the picture is not a PNG, GIF, or JPEG data URL.");
4349
+ if (width === void 0) width = height * natural[0] / natural[1];
4350
+ else height = width * natural[1] / natural[0];
4351
+ }
4352
+ if (!(width > 0) || !(height > 0)) throw new Error("image() needs a positive width and height.");
4353
+ const picture = new Node().at(-width / 2, -height / 2);
4354
+ picture.base.image = { src, width, height };
4355
+ const out = new Node();
4356
+ out.add(picture);
4357
+ if (options.opacity !== void 0) out.opacity(options.opacity);
4358
+ return out;
4359
+ }
4316
4360
  function dot(radius = 9, color = "ink", style = {}) {
4317
4361
  return styled(new Node(circlePath(0, 0, radius)), style, { fill: color });
4318
4362
  }
@@ -7094,7 +7138,7 @@ var CodeBlock = class extends Node {
7094
7138
  const font = fontFor("mono", 400);
7095
7139
  const scale = size / font.unitsPerEm;
7096
7140
  const advance = font.advance(font.glyphFor(48)) * scale;
7097
- const tokens3 = tokenize(source, options.language ?? "ts");
7141
+ const tokens4 = tokenize(source, options.language ?? "ts");
7098
7142
  const rows = source.split("\n");
7099
7143
  const gutter = options.lineNumbers ? (String(rows.length).length + 2) * advance : 0;
7100
7144
  const pad2 = options.padding ?? size * 0.9;
@@ -7126,7 +7170,7 @@ var CodeBlock = class extends Node {
7126
7170
  }
7127
7171
  const colors = { ...CODE_COLORS, ...options.colors };
7128
7172
  const column = /* @__PURE__ */ new Map();
7129
- for (const token of tokens3) {
7173
+ for (const token of tokens4) {
7130
7174
  const start = column.get(token.line) ?? 0;
7131
7175
  column.set(token.line, start + token.text.length);
7132
7176
  const entry = { ...token, glyphs: [] };
@@ -8483,9 +8527,9 @@ function fromSvg(source, options = {}) {
8483
8527
  const width = parseFloat(element.attrs["width"] ?? "0"), height = parseFloat(element.attrs["height"] ?? "0");
8484
8528
  const [x, y] = apply(m, parseFloat(element.attrs["x"] ?? "0") || 0, parseFloat(element.attrs["y"] ?? "0") || 0);
8485
8529
  const unit = matScale(m);
8486
- const image = { src: href, width, height };
8530
+ const image2 = { src: href, width, height };
8487
8531
  const node = new Node().at(x, y);
8488
- node.base.image = image;
8532
+ node.base.image = image2;
8489
8533
  node.base.sx = unit;
8490
8534
  node.base.sy = unit;
8491
8535
  if (opacity < 1) node.base.opacity = opacity;
@@ -8554,6 +8598,144 @@ function shiftPaint(paint, dx, dy) {
8554
8598
  return gradient;
8555
8599
  }
8556
8600
 
8601
+ // src/stage/narration.ts
8602
+ var tokens3 = (text2) => text2.toLowerCase().replace(/[^a-z0-9.]+/g, " ").split(" ").map((token) => token.replace(/^\.+|\.+$/g, "")).filter(Boolean);
8603
+ function captionLines(text2, length = 74) {
8604
+ const lines = [];
8605
+ for (const sentence of text2.match(/[^.?!]+(?:[.?!]+(?=\s|$)|\.\d[^.?!]*[.?!]?|$)/g) ?? []) {
8606
+ let line2 = "";
8607
+ for (const word of sentence.split(/\s+/).filter(Boolean)) {
8608
+ if (line2 && line2.length + word.length + 1 > length) {
8609
+ lines.push(line2);
8610
+ line2 = word;
8611
+ } else {
8612
+ line2 = line2 ? `${line2} ${word}` : word;
8613
+ }
8614
+ }
8615
+ if (line2) lines.push(line2);
8616
+ }
8617
+ return lines;
8618
+ }
8619
+ var SceneClock = class {
8620
+ constructor(stage, id, start, end, beats) {
8621
+ this.stage = stage;
8622
+ this.id = id;
8623
+ this.start = start;
8624
+ this.end = end;
8625
+ this.beats = beats;
8626
+ }
8627
+ stage;
8628
+ id;
8629
+ start;
8630
+ end;
8631
+ beats;
8632
+ /** When the voice says a phrase. Pass a beat index to search one beat only. Throws if the phrase is not spoken. */
8633
+ cue(phrase, beat) {
8634
+ const want = tokens3(phrase);
8635
+ if (want.length === 0) throw new Error(`narration: scene "${this.id}": a cue needs at least one word`);
8636
+ if (beat !== void 0 && !this.beats[beat]) throw new Error(`narration: scene "${this.id}" has no beat ${beat}`);
8637
+ const list3 = beat === void 0 ? this.beats : [this.beats[beat]];
8638
+ for (const placed of list3) {
8639
+ const spoken = placed.words.flatMap((word) => tokens3(word.text).map((token) => ({ token, start: word.start, end: word.end })));
8640
+ for (let i = 0; i + want.length <= spoken.length; i++) {
8641
+ if (want.every((token, j) => spoken[i + j].token === token)) {
8642
+ return { start: placed.start + spoken[i].start, end: placed.start + spoken[i + want.length - 1].end };
8643
+ }
8644
+ }
8645
+ }
8646
+ const where = beat === void 0 ? "" : ` in beat ${beat}`;
8647
+ throw new Error(`narration: scene "${this.id}": the voice never says "${phrase}"${where}`);
8648
+ }
8649
+ /** Build when the voice starts a phrase. `offset` moves it, in seconds. */
8650
+ on(phrase, build, offset = 0, beat) {
8651
+ this.stage.at(Math.max(0, this.cue(phrase, beat).start + offset), build);
8652
+ return this;
8653
+ }
8654
+ /** Build when the voice finishes a phrase. */
8655
+ after(phrase, build, offset = 0, beat) {
8656
+ this.stage.at(Math.max(0, this.cue(phrase, beat).end + offset), build);
8657
+ return this;
8658
+ }
8659
+ /** Build when a beat starts. */
8660
+ onBeat(index, build, offset = 0) {
8661
+ const beat = this.beats[index];
8662
+ if (!beat) throw new Error(`narration: scene "${this.id}" has no beat ${index}`);
8663
+ this.stage.at(Math.max(0, beat.start + offset), build);
8664
+ return this;
8665
+ }
8666
+ /** Build at a time counted from the start of the scene. */
8667
+ at(seconds, build) {
8668
+ this.stage.at(Math.max(0, this.start + seconds), build);
8669
+ return this;
8670
+ }
8671
+ /** Fade nodes out just before the scene ends, so the next picture starts on a clean frame. */
8672
+ clear(nodes, lead = 0.24, duration = 0.26) {
8673
+ this.stage.at(this.end - lead, () => this.stage.play(...nodes.map((node) => fade(node, 0, { duration }))));
8674
+ return this;
8675
+ }
8676
+ };
8677
+ var Narration = class {
8678
+ scenes;
8679
+ /** The end of the last scene, in seconds. Hold the film at least this long, or the voice is cut. */
8680
+ duration;
8681
+ lead;
8682
+ gap;
8683
+ constructor(stage, timing, options = {}) {
8684
+ this.lead = options.lead ?? timing.lead ?? 0.6;
8685
+ this.gap = options.gap ?? timing.gap ?? 0.4;
8686
+ if (!(this.lead >= 0) || !(this.gap >= 0)) throw new Error("narration: lead and gap must be zero or more seconds");
8687
+ const seen = /* @__PURE__ */ new Set();
8688
+ const scenes = [];
8689
+ let now = this.lead;
8690
+ let last = now;
8691
+ for (const scene of timing.scenes) {
8692
+ if (seen.has(scene.id)) throw new Error(`narration: two scenes are named "${scene.id}"`);
8693
+ seen.add(scene.id);
8694
+ const start = now;
8695
+ const beats = [];
8696
+ for (const beat of scene.beats) {
8697
+ if (!(beat.duration > 0)) throw new Error(`narration: scene "${scene.id}" has a beat without a measured duration: "${beat.say}"`);
8698
+ const hold = beat.hold ?? 0;
8699
+ beats.push({ start: now, end: now + beat.duration, until: now + beat.duration + hold, text: beat.say, words: beat.words ?? [] });
8700
+ now += beat.duration + hold;
8701
+ }
8702
+ scenes.push(new SceneClock(stage, scene.id, start, now, beats));
8703
+ if (options.chapters !== false && scene.title) stage.chapters.push({ title: scene.title, time: scenes.length === 1 ? 0 : start });
8704
+ if (options.captions !== false) {
8705
+ for (const beat of beats) {
8706
+ const lines = captionLines(beat.text, options.captionLength);
8707
+ const total = lines.reduce((sum, line2) => sum + line2.length, 0);
8708
+ let t0 = beat.start;
8709
+ for (const line2 of lines) {
8710
+ const t1 = t0 + (beat.end - beat.start) * line2.length / total;
8711
+ stage.captions.push({ t0, t1, text: line2 });
8712
+ t0 = t1;
8713
+ }
8714
+ }
8715
+ }
8716
+ last = now;
8717
+ now += this.gap;
8718
+ }
8719
+ this.scenes = scenes;
8720
+ this.duration = last;
8721
+ stage.at(last, () => {
8722
+ });
8723
+ }
8724
+ /** The clock of one scene. */
8725
+ scene(id) {
8726
+ const found = this.scenes.find((scene) => scene.id === id);
8727
+ if (!found) throw new Error(`narration: no scene "${id}". The scenes are: ${this.scenes.map((scene) => scene.id).join(", ")}`);
8728
+ return found;
8729
+ }
8730
+ /** Where every beat's recording starts, in order, for the script that mixes the sound. */
8731
+ placements() {
8732
+ return this.scenes.flatMap((scene) => scene.beats.map((beat, index) => ({ scene: scene.id, beat: index, start: beat.start, end: beat.end })));
8733
+ }
8734
+ };
8735
+ function narration(stage, timing, options = {}) {
8736
+ return new Narration(stage, timing, options);
8737
+ }
8738
+
8557
8739
  // src/stage/three/index.ts
8558
8740
  var read3 = (value) => typeof value === "function" ? value() : value;
8559
8741
  var normalize = (v) => {
@@ -9233,6 +9415,7 @@ var Vector3D = class extends Line3D {
9233
9415
  from3;
9234
9416
  to3;
9235
9417
  tipSize;
9418
+ tipBias;
9236
9419
  constructor(from, to2, style = {}) {
9237
9420
  super(from, () => {
9238
9421
  const a = read3(from), b = read3(to2);
@@ -9243,6 +9426,7 @@ var Vector3D = class extends Line3D {
9243
9426
  this.from3 = from;
9244
9427
  this.to3 = to2;
9245
9428
  this.tipSize = style.tip ?? 24;
9429
+ this.tipBias = style.onTop ? ON_TOP : style.bias ?? 0;
9246
9430
  }
9247
9431
  emit(view) {
9248
9432
  super.emit(view);
@@ -9261,7 +9445,7 @@ var Vector3D = class extends Line3D {
9261
9445
  const rgb = solidOf(this.get("stroke"));
9262
9446
  const color = view.fogged(rgb[0], rgb[1], rgb[2], depth);
9263
9447
  const ring2 = polygonRing([bx, by, bx - ux * size - uy * half, by - uy * size + ux * half, bx - ux * size + uy * half, by - uy * size - ux * half]);
9264
- view.push(fillOp([ring2], color, alpha, null, 0, 0), depth + 0.01);
9448
+ view.push(fillOp([ring2], color, alpha, null, 0, 0), depth + 0.01 + this.tipBias);
9265
9449
  }
9266
9450
  };
9267
9451
  function vector3d(from, to2, style = {}) {
@@ -9284,7 +9468,7 @@ var Points3D = class extends Object3D {
9284
9468
  const trim = this.get("trimTo");
9285
9469
  const shown = Math.ceil(points.length * trim);
9286
9470
  const base = solidOf(this.get("fill"));
9287
- const bias = this.style.onTop ? ON_TOP : 0;
9471
+ const bias = this.style.onTop ? ON_TOP : this.style.bias ?? 0;
9288
9472
  for (let i = 0; i < shown; i++) {
9289
9473
  const point = points[i];
9290
9474
  if (!view.project(point[0], point[1], point[2])) continue;
@@ -9343,13 +9527,23 @@ var Trail3D = class extends Object3D {
9343
9527
  const fade2 = this.style.fade ?? (tail !== void 0 ? 0 : 1);
9344
9528
  const bias = this.style.onTop ? ON_TOP : this.style.bias ?? 0;
9345
9529
  const glow = (this.style.glow ?? 0) * view.scale;
9346
- const piece = Math.max(1, Math.ceil((i1 - i0) / 48));
9347
- for (let i = i0; i < i1; i += piece) {
9530
+ const moved = [];
9531
+ let last = null;
9532
+ for (let k = i0; k <= i1; k++) {
9533
+ const p = this.sample(k, rate);
9534
+ if (last && Math.abs(p[0] - last[0]) + Math.abs(p[1] - last[1]) + Math.abs(p[2] - last[2]) < 1e-9) continue;
9535
+ moved.push(p);
9536
+ last = p;
9537
+ }
9538
+ const span = moved.length - 1;
9539
+ if (span < 1) return;
9540
+ const piece = Math.max(1, Math.ceil(span / 48));
9541
+ for (let i = 0; i < span; i += piece) {
9348
9542
  const coords = [];
9349
9543
  let depth = 0;
9350
9544
  let scale = 0;
9351
- for (let k = i; k <= Math.min(i1, i + piece); k++) {
9352
- const p = this.sample(k, rate);
9545
+ for (let k = i; k <= Math.min(span, i + piece); k++) {
9546
+ const p = moved[k];
9353
9547
  if (!view.project(p[0], p[1], p[2])) continue;
9354
9548
  coords.push([view.px, view.py]);
9355
9549
  depth += view.pz;
@@ -9358,7 +9552,7 @@ var Trail3D = class extends Object3D {
9358
9552
  if (coords.length < 2) continue;
9359
9553
  depth /= coords.length;
9360
9554
  scale /= coords.length;
9361
- const fraction = (i + piece / 2 - i0) / (i1 - i0);
9555
+ const fraction = Math.min(1, (i + piece / 2) / span);
9362
9556
  const light = fade2 + (1 - fade2) * Math.pow(fraction, 1.6);
9363
9557
  const color = view.fogged(base[0], base[1], base[2], depth);
9364
9558
  view.push(strokeOp([chain(coords)], color, alpha * light, width * scale, glow, "butt"), depth + bias);
@@ -9558,6 +9752,7 @@ function label3d(content, position, options = {}) {
9558
9752
  Line3D,
9559
9753
  LineChart,
9560
9754
  MatrixNode,
9755
+ Narration,
9561
9756
  NeuralNet,
9562
9757
  Node,
9563
9758
  NumberLine,
@@ -9567,6 +9762,7 @@ function label3d(content, position, options = {}) {
9567
9762
  Points3D,
9568
9763
  Scatter,
9569
9764
  Scene3D,
9765
+ SceneClock,
9570
9766
  Stage,
9571
9767
  StreamLines,
9572
9768
  Surface3D,
@@ -9603,6 +9799,7 @@ function label3d(content, position, options = {}) {
9603
9799
  buildOps,
9604
9800
  call,
9605
9801
  callout,
9802
+ captionLines,
9606
9803
  chalk,
9607
9804
  checkFilm,
9608
9805
  circle,
@@ -9662,6 +9859,7 @@ function label3d(content, position, options = {}) {
9662
9859
  heatmap,
9663
9860
  highlightSweep,
9664
9861
  histogram,
9862
+ image,
9665
9863
  indicate,
9666
9864
  infoBox,
9667
9865
  invert,
@@ -9687,6 +9885,7 @@ function label3d(content, position, options = {}) {
9687
9885
  morphMatching,
9688
9886
  moveTo,
9689
9887
  mul,
9888
+ narration,
9690
9889
  neon,
9691
9890
  neuralNet,
9692
9891
  notQuiteThere,