vizmatic 0.3.2 → 0.5.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.
Files changed (150) hide show
  1. package/PROMPT.md +75 -525
  2. package/README.md +87 -578
  3. package/ROADMAP.md +49 -67
  4. package/SCIENCE.md +250 -0
  5. package/assets/THIRD_PARTY_LICENSES.md +40 -1
  6. package/assets/fonts/InstrumentSerif-Italic.ttf +0 -0
  7. package/assets/fonts/InstrumentSerif-Regular.ttf +0 -0
  8. package/assets/licenses/raster-codecs-MIT.txt +74 -0
  9. package/dist/chunk-3F2VQ7NW.js +1 -0
  10. package/dist/chunk-4XE64I2U.js +755 -0
  11. package/dist/chunk-JHHPLALU.js +79 -0
  12. package/dist/chunk-LTX44BAE.js +112 -0
  13. package/dist/chunk-MLKGABMK.js +9 -0
  14. package/dist/chunk-PSBF4TEK.js +1 -0
  15. package/dist/chunk-RPAHMKAR.js +605 -0
  16. package/dist/chunk-RWF4VBUL.js +3617 -0
  17. package/dist/chunk-WHT6HRMX.js +4201 -0
  18. package/dist/cli.js +371 -10
  19. package/dist/index.cjs +11129 -2922
  20. package/dist/index.d.cts +1225 -369
  21. package/dist/index.d.ts +1225 -369
  22. package/dist/index.js +6220 -3015
  23. package/dist/math-LXB4FH4E.js +7 -0
  24. package/dist/math-QVCETQDQ.js +1 -0
  25. package/dist/scene-browser-assets.d.ts +38 -0
  26. package/dist/scene-browser-assets.js +53 -0
  27. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +70 -0
  28. package/dist/scene-browser-chunks/chunk-ASXKN3NU.js +1 -0
  29. package/dist/scene-browser-chunks/chunk-CM5Y5LZP.js +1 -0
  30. package/dist/scene-browser-chunks/chunk-DP7NB4EW.js +6 -0
  31. package/dist/scene-browser-chunks/emscripten-module.browser-M5AEKJGE.js +1 -0
  32. package/dist/scene-browser-chunks/ffi-FL6ORJU3.js +1 -0
  33. package/dist/scene-browser-chunks/module-ES6BEMUI-JD5S5VKR.js +1 -0
  34. package/dist/scene-browser-chunks/module-asyncify-2EFITU5U-HWPFJFJC.js +1 -0
  35. package/dist/scene-browser-chunks/scene-browser-layout-M3XSXMV4.js +27 -0
  36. package/dist/scene-browser.d.ts +117 -0
  37. package/dist/scene-browser.js +220 -0
  38. package/dist/scene-cli.d.ts +1 -0
  39. package/dist/scene-cli.js +4 -0
  40. package/dist/scene-runtime.cjs +995 -0
  41. package/dist/scene-runtime.d.cts +81 -0
  42. package/dist/scene-runtime.d.ts +81 -0
  43. package/dist/scene-runtime.js +22 -0
  44. package/dist/server-2FYHZ4UO.js +331 -0
  45. package/dist/stage-browser/browser.d.ts +2482 -0
  46. package/dist/stage-browser/chunk-SQE76S5B.js +1 -0
  47. package/dist/stage-browser/chunk-VZNL6JY2.js +59 -0
  48. package/dist/stage-browser/dagre.esm-N2NIVIAZ.js +6 -0
  49. package/dist/stage-browser/math-4WFNHVV2.js +18 -0
  50. package/dist/stage-browser/stage.js +19 -0
  51. package/dist/stage-export.cjs +4950 -0
  52. package/dist/stage-export.d.cts +112 -0
  53. package/dist/stage-export.d.ts +112 -0
  54. package/dist/stage-export.js +544 -0
  55. package/dist/stage.cjs +9745 -0
  56. package/dist/stage.d.cts +1678 -0
  57. package/dist/stage.d.ts +1678 -0
  58. package/dist/stage.js +5404 -0
  59. package/dist/svg-import-Djj2q7Pc.d.cts +742 -0
  60. package/dist/svg-import-Djj2q7Pc.d.ts +742 -0
  61. package/dist/video-CcHW1qhV.d.cts +532 -0
  62. package/dist/video-CcHW1qhV.d.ts +532 -0
  63. package/examples/README.md +18 -0
  64. package/examples/agent-pipeline.tsx +4 -4
  65. package/examples/animated-pipeline.tsx +1 -5
  66. package/examples/attention-head.tsx +12 -12
  67. package/examples/aurora-incident.tsx +4 -3
  68. package/examples/building-blocks.tsx +8 -9
  69. package/examples/catalog-charts.tsx +4 -4
  70. package/examples/catalog-content.tsx +7 -9
  71. package/examples/catalog-convolution-kernel.tsx +116 -0
  72. package/examples/catalog-data.tsx +2 -8
  73. package/examples/catalog-dataflow.tsx +5 -9
  74. package/examples/catalog-dense.tsx +80 -0
  75. package/examples/catalog-deployment.tsx +5 -11
  76. package/examples/catalog-diagrams.tsx +13 -16
  77. package/examples/catalog-drawing.tsx +7 -7
  78. package/examples/catalog-flows.tsx +4 -4
  79. package/examples/catalog-foundations.tsx +11 -11
  80. package/examples/catalog-gaussian-blur.tsx +146 -0
  81. package/examples/catalog-image-tensors.tsx +115 -0
  82. package/examples/catalog-ml.tsx +36 -31
  83. package/examples/catalog-numeric-matrices.tsx +93 -0
  84. package/examples/catalog-photo-blur.tsx +209 -0
  85. package/examples/catalog-science-ai.tsx +130 -0
  86. package/examples/catalog-science-chemistry.tsx +103 -0
  87. package/examples/catalog-science-math.tsx +93 -0
  88. package/examples/catalog-science-physics.tsx +84 -0
  89. package/examples/catalog-sequence.tsx +59 -38
  90. package/examples/data-pipeline-lineage-presentation.tsx +5 -0
  91. package/examples/data-pipeline-lineage.tsx +85 -0
  92. package/examples/daybreak-launch.tsx +1 -0
  93. package/examples/desired-quadrant.tsx +7 -8
  94. package/examples/engineering-dashboard-presentation.tsx +13 -0
  95. package/examples/engineering-dashboard.tsx +160 -0
  96. package/examples/engineering-flow.tsx +2 -4
  97. package/examples/eval-dashboard.tsx +6 -6
  98. package/examples/films/attention.ts +278 -0
  99. package/examples/films/cache-miss.ts +431 -0
  100. package/examples/films/catalog.json +132 -0
  101. package/examples/films/central-limit.ts +269 -0
  102. package/examples/films/complex-maps.ts +273 -0
  103. package/examples/films/deck-example.ts +224 -0
  104. package/examples/films/euler-circle.ts +179 -0
  105. package/examples/films/fourier-epicycles.ts +265 -0
  106. package/examples/films/gradient-descent.ts +345 -0
  107. package/examples/films/linear-maps.ts +175 -0
  108. package/examples/films/lorenz.ts +207 -0
  109. package/examples/films/pythagoras.ts +185 -0
  110. package/examples/films/taylor-series.ts +159 -0
  111. package/examples/films/vizmatic-title.ts +117 -0
  112. package/examples/llm-serving-stack-presentation.tsx +5 -0
  113. package/examples/llm-serving-stack.tsx +94 -0
  114. package/examples/model-garden.tsx +1 -0
  115. package/examples/model-router.tsx +6 -6
  116. package/examples/nccl-all-gather.tsx +3 -3
  117. package/examples/nccl-all-reduce.tsx +3 -3
  118. package/examples/nccl-all-to-all.tsx +1 -1
  119. package/examples/nccl-broadcast.tsx +1 -1
  120. package/examples/nccl-reduce-scatter.tsx +5 -5
  121. package/examples/orthogonal-routing.tsx +4 -4
  122. package/examples/pareto-frontier.tsx +9 -10
  123. package/examples/presentation-frame.tsx +6 -6
  124. package/examples/pressure-mechanism.scene.json +14 -0
  125. package/examples/production-system-map-presentation.tsx +5 -0
  126. package/examples/production-system-map.tsx +130 -0
  127. package/examples/rag-graph.tsx +7 -7
  128. package/examples/release-card.tsx +5 -5
  129. package/examples/spec-anatomy.tsx +5 -5
  130. package/examples/system-architecture.tsx +19 -32
  131. package/examples/theme-system.tsx +1 -1
  132. package/examples/token-matrix.tsx +4 -2
  133. package/examples/transparent-badge.tsx +1 -2
  134. package/examples/videos/README.md +62 -0
  135. package/examples/videos/calculus-tangent.tsx +101 -0
  136. package/examples/videos/catalyst-pathway.tsx +56 -0
  137. package/examples/videos/causal-attention.tsx +91 -0
  138. package/examples/videos/convolution-kernel.tsx +34 -0
  139. package/examples/videos/gaussian-blur.tsx +32 -0
  140. package/examples/videos/image-to-matrix.tsx +22 -0
  141. package/examples/videos/matrix-multiplication.tsx +128 -0
  142. package/examples/videos/photo-gaussian-blur.tsx +39 -0
  143. package/examples/videos/request-lifecycle.tsx +99 -0
  144. package/examples/videos/signal-to-story.tsx +126 -0
  145. package/examples/videos/wave-interference.tsx +80 -0
  146. package/examples/vizmatic-bare.d.ts +1 -0
  147. package/examples/vizmatic-hero.tsx +9 -18
  148. package/examples/website-workflow.tsx +7 -7
  149. package/examples/weekend-field-notes.tsx +3 -2
  150. package/package.json +77 -12
@@ -0,0 +1,544 @@
1
+ import {
2
+ encodePng,
3
+ renderRgbaVideo,
4
+ renderToSvg
5
+ } from "./chunk-RWF4VBUL.js";
6
+ import "./chunk-RPAHMKAR.js";
7
+ import {
8
+ frameToSvg,
9
+ fromSvg,
10
+ isFilm,
11
+ isSuspend,
12
+ parseColor
13
+ } from "./chunk-WHT6HRMX.js";
14
+ import "./chunk-MLKGABMK.js";
15
+
16
+ // src/stage/export.ts
17
+ import { mkdir, stat, writeFile } from "fs/promises";
18
+ import { totalmem } from "os";
19
+ import { dirname, resolve } from "path";
20
+ import * as gifenc from "gifenc";
21
+
22
+ // src/stage/raster.ts
23
+ import { createRequire } from "module";
24
+ import { cpus } from "os";
25
+ import { Worker } from "worker_threads";
26
+ import { fileURLToPath } from "url";
27
+ var RASTER_WORKER_SOURCE = String.raw`
28
+ const { parentPort, workerData } = require('node:worker_threads')
29
+ const { Resvg } = require(workerData.resvgPath)
30
+
31
+ function downsample(src, w, h, factor) {
32
+ const dw = Math.max(1, Math.floor(w / factor)), dh = Math.max(1, Math.floor(h / factor))
33
+ const out = new Float32Array(dw * dh * 3)
34
+ const norm = 1 / (factor * factor)
35
+ for (let y = 0; y < dh; y++) {
36
+ for (let x = 0; x < dw; x++) {
37
+ let r = 0, g = 0, b = 0
38
+ for (let yy = 0; yy < factor; yy++) {
39
+ let o = ((y * factor + yy) * w + x * factor) * 4
40
+ for (let xx = 0; xx < factor; xx++) { r += src[o]; g += src[o + 1]; b += src[o + 2]; o += 4 }
41
+ }
42
+ const i = (y * dw + x) * 3
43
+ out[i] = r * norm; out[i + 1] = g * norm; out[i + 2] = b * norm
44
+ }
45
+ }
46
+ return { data: out, w: dw, h: dh }
47
+ }
48
+
49
+ function boxBlur(img, radius) {
50
+ const { data, w, h } = img
51
+ const tmp = new Float32Array(data.length)
52
+ const norm = 1 / (radius * 2 + 1)
53
+ for (let y = 0; y < h; y++) {
54
+ for (let c = 0; c < 3; c++) {
55
+ let sum = 0
56
+ for (let k = -radius; k <= radius; k++) sum += data[(y * w + Math.min(w - 1, Math.max(0, k))) * 3 + c]
57
+ for (let x = 0; x < w; x++) {
58
+ tmp[(y * w + x) * 3 + c] = sum * norm
59
+ sum += data[(y * w + Math.min(w - 1, x + radius + 1)) * 3 + c] - data[(y * w + Math.max(0, x - radius)) * 3 + c]
60
+ }
61
+ }
62
+ }
63
+ for (let x = 0; x < w; x++) {
64
+ for (let c = 0; c < 3; c++) {
65
+ let sum = 0
66
+ for (let k = -radius; k <= radius; k++) sum += tmp[(Math.min(h - 1, Math.max(0, k)) * w + x) * 3 + c]
67
+ for (let y = 0; y < h; y++) {
68
+ data[(y * w + x) * 3 + c] = sum * norm
69
+ sum += tmp[(Math.min(h - 1, y + radius + 1) * w + x) * 3 + c] - tmp[(Math.max(0, y - radius) * w + x) * 3 + c]
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ // Bloom: bright marks spill soft light. Blurred layers add on top of the sharp image.
76
+ function bloom(pixels, w, h, amount, background) {
77
+ const [br, bg, bb] = background
78
+ const layers = []
79
+ // The spread follows output width, so a small preview and a 4K master look alike.
80
+ const k = w / 1920
81
+ for (const [base, radius, weight] of [[4, 3, 0.55], [8, 4, 0.3], [16, 4, 0.15]]) {
82
+ const factor = Math.max(1, Math.round(base * k))
83
+ const layer = downsample(pixels, w, h, factor)
84
+ const d = layer.data
85
+ for (let i = 0; i < d.length; i += 3) {
86
+ // Only light above the background contributes, so the page never lifts or fogs.
87
+ d[i] = Math.max(0, d[i] - br); d[i + 1] = Math.max(0, d[i + 1] - bg); d[i + 2] = Math.max(0, d[i + 2] - bb)
88
+ }
89
+ boxBlur(layer, radius); boxBlur(layer, radius)
90
+ layers.push({ ...layer, factor, weight })
91
+ }
92
+ for (let y = 0; y < h; y++) {
93
+ for (let x = 0; x < w; x++) {
94
+ const o = (y * w + x) * 4
95
+ let r = 0, g = 0, b = 0
96
+ for (const layer of layers) {
97
+ const fx = (x + 0.5) / layer.factor - 0.5, fy = (y + 0.5) / layer.factor - 0.5
98
+ const x0 = Math.max(0, Math.floor(fx)), y0 = Math.max(0, Math.floor(fy))
99
+ const x1 = Math.min(layer.w - 1, x0 + 1), y1 = Math.min(layer.h - 1, y0 + 1)
100
+ const tx = Math.max(0, fx - x0), ty = Math.max(0, fy - y0)
101
+ const d = layer.data, lw = layer.w
102
+ for (let c = 0; c < 3; c++) {
103
+ const v = (d[(y0 * lw + x0) * 3 + c] * (1 - tx) + d[(y0 * lw + x1) * 3 + c] * tx) * (1 - ty)
104
+ + (d[(y1 * lw + x0) * 3 + c] * (1 - tx) + d[(y1 * lw + x1) * 3 + c] * tx) * ty
105
+ if (c === 0) r += v * layer.weight
106
+ else if (c === 1) g += v * layer.weight
107
+ else b += v * layer.weight
108
+ }
109
+ }
110
+ // Screen blend keeps highlights from clipping harshly.
111
+ pixels[o] = 255 - (255 - pixels[o]) * (255 - Math.min(255, r * amount * 2.4)) / 255
112
+ pixels[o + 1] = 255 - (255 - pixels[o + 1]) * (255 - Math.min(255, g * amount * 2.4)) / 255
113
+ pixels[o + 2] = 255 - (255 - pixels[o + 2]) * (255 - Math.min(255, b * amount * 2.4)) / 255
114
+ }
115
+ }
116
+ }
117
+
118
+ function raster(svg, width, height) {
119
+ const image = new Resvg(svg, { fitTo: { mode: 'width', value: width }, font: { loadSystemFonts: false } }).render()
120
+ if (image.height === height) return image.pixels
121
+ // Rounding can differ by a row at unusual sizes. Keep the requested size exactly.
122
+ const out = new Uint8Array(width * height * 4)
123
+ for (let y = 0; y < height; y++) {
124
+ const row = Math.min(image.height - 1, y) * width * 4
125
+ out.set(image.pixels.subarray(row, row + width * 4), y * width * 4)
126
+ }
127
+ return out
128
+ }
129
+
130
+ parentPort.on('message', (job) => {
131
+ try {
132
+ let out
133
+ if (job.svgs.length === 1) {
134
+ out = new Uint8Array(raster(job.svgs[0], job.width, job.height))
135
+ } else {
136
+ // Motion blur: average sub-frames across the shutter.
137
+ const n = job.svgs.length
138
+ // Sixteen bits hold 257 full-white sub-frames, at half the memory of thirty-two.
139
+ let sum = null
140
+ for (const svg of job.svgs) {
141
+ const px = raster(svg, job.width, job.height)
142
+ if (!sum) sum = n <= 257 ? new Uint16Array(px.length) : new Uint32Array(px.length)
143
+ for (let i = 0; i < px.length; i++) sum[i] += px[i]
144
+ }
145
+ out = new Uint8Array(sum.length)
146
+ for (let i = 0; i < sum.length; i++) out[i] = sum[i] / n + 0.5
147
+ }
148
+ if (job.bloom > 0) bloom(out, job.width, job.height, job.bloom, job.background)
149
+ parentPort.postMessage({ id: job.id, pixels: out }, [out.buffer])
150
+ } catch (error) {
151
+ parentPort.postMessage({ id: job.id, error: String(error && error.message || error) })
152
+ }
153
+ })
154
+ `;
155
+ function resolveResvg() {
156
+ const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
157
+ return createRequire(here).resolve("@resvg/resvg-js");
158
+ }
159
+ var RasterPool = class {
160
+ workers = [];
161
+ idle = [];
162
+ queue = [];
163
+ pending = /* @__PURE__ */ new Map();
164
+ nextId = 1;
165
+ failure = null;
166
+ constructor(size = defaultPoolSize()) {
167
+ const resvgPath = resolveResvg();
168
+ for (let i = 0; i < size; i++) {
169
+ const worker = new Worker(RASTER_WORKER_SOURCE, { eval: true, workerData: { resvgPath } });
170
+ worker.on("message", (message) => {
171
+ const entry = this.pending.get(message.id);
172
+ this.pending.delete(message.id);
173
+ this.idle.push(worker);
174
+ this.pump();
175
+ if (!entry) return;
176
+ if (message.error || !message.pixels) entry.reject(new Error(`Frame rasterization failed: ${message.error}`));
177
+ else entry.resolve(message.pixels);
178
+ });
179
+ worker.on("error", (error) => this.fail(error instanceof Error ? error : new Error(String(error))));
180
+ this.workers.push(worker);
181
+ this.idle.push(worker);
182
+ }
183
+ }
184
+ get size() {
185
+ return this.workers.length;
186
+ }
187
+ fail(error) {
188
+ this.failure = error;
189
+ for (const entry of this.pending.values()) entry.reject(error);
190
+ this.pending.clear();
191
+ }
192
+ pump() {
193
+ while (this.idle.length > 0 && this.queue.length > 0) {
194
+ const worker = this.idle.pop();
195
+ const { job, id } = this.queue.shift();
196
+ worker.postMessage({ id, ...job });
197
+ }
198
+ }
199
+ run(job) {
200
+ if (this.failure) return Promise.reject(this.failure);
201
+ const id = this.nextId++;
202
+ return new Promise((resolve2, reject) => {
203
+ this.pending.set(id, { resolve: resolve2, reject });
204
+ this.queue.push({ job, id });
205
+ this.pump();
206
+ });
207
+ }
208
+ async close() {
209
+ this.failure ??= new Error("The raster pool was closed.");
210
+ for (const entry of this.pending.values()) entry.reject(this.failure);
211
+ this.pending.clear();
212
+ this.queue.length = 0;
213
+ await Promise.all(this.workers.map((worker) => worker.terminate()));
214
+ }
215
+ };
216
+ function defaultPoolSize() {
217
+ return Math.max(1, Math.min(12, cpus().length - 2));
218
+ }
219
+ function framesToJob(frames, width, parseBackground, height) {
220
+ const first = frames[0];
221
+ const scale = width / first.width;
222
+ return {
223
+ svgs: frames.map((frame) => frameToSvg(frame)),
224
+ width,
225
+ height: height ?? Math.round(first.height * scale),
226
+ bloom: first.dark ? first.bloom : 0,
227
+ background: parseBackground(first.background)
228
+ };
229
+ }
230
+
231
+ // src/stage/objects/from-component.ts
232
+ async function fromComponent(element, options) {
233
+ const { width, height, theme, canvas, scale, ...rest } = options;
234
+ const svg = await renderToSvg(element, width, height, { theme: theme ?? "dark", background: canvas, watermark: false });
235
+ return fromSvg(svg, { ...rest, width: width * (scale ?? 1), height: height * (scale ?? 1) });
236
+ }
237
+
238
+ // src/stage/export.ts
239
+ var QUALITY = {
240
+ draft: { crf: 26, vp9Crf: 40, preset: "veryfast", motionBlur: 1 },
241
+ standard: { crf: 18, vp9Crf: 31, preset: "medium", motionBlur: 1 },
242
+ high: { crf: 15, vp9Crf: 24, preset: "slow", motionBlur: 4 },
243
+ master: { crf: 11, vp9Crf: 15, preset: "slow", motionBlur: 8 }
244
+ };
245
+ var DEFAULT_GIF_WIDTH = 960;
246
+ var DEFAULT_GIF_FPS = 25;
247
+ var GIF_PALETTE_FRAMES = 12;
248
+ var GIF_PALETTE_PIXELS = 1 << 19;
249
+ var MAX_GIF_DELAY = 655350;
250
+ async function resolveFilm(film, overrides) {
251
+ return isFilm(film) ? film.compile(overrides) : film;
252
+ }
253
+ function frameAt(film, time) {
254
+ try {
255
+ return film.frame(time);
256
+ } catch (error) {
257
+ if (!isSuspend(error)) throw error;
258
+ return error.promise.then(() => frameAt(film, time));
259
+ }
260
+ }
261
+ function backgroundBytes(color) {
262
+ if (!color) return [0, 0, 0];
263
+ const rgba = parseColor(color);
264
+ return [rgba[0], rgba[1], rgba[2]];
265
+ }
266
+ function outputSize(film, requested) {
267
+ const width = requested ?? film.width;
268
+ if (!Number.isInteger(width) || width < 2) throw new Error(`Output width must be an integer of at least 2, but received ${width}.`);
269
+ return { width, height: Math.max(1, Math.round(width * film.height / film.width)) };
270
+ }
271
+ function evenSize(film, requested) {
272
+ const { width, height } = outputSize(film, requested);
273
+ return { width: width + width % 2, height: Math.max(2, height + height % 2) };
274
+ }
275
+ function timeRange(film, options) {
276
+ const from = Math.max(0, options.from ?? 0);
277
+ const to = Math.min(film.duration, options.to ?? film.duration);
278
+ if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) {
279
+ throw new Error(`The render range ${from}:${to} is empty. The film is ${film.duration.toFixed(2)} seconds long.`);
280
+ }
281
+ return { from, to };
282
+ }
283
+ function planRender(width, height, motionBlur, options = {}) {
284
+ const frameBytes = width * height * 4;
285
+ const budget = options.memoryBudget ?? Math.min(2 * 1024 ** 3, totalmem() * 0.25);
286
+ const requested = Math.max(1, Math.floor(options.workers ?? defaultPoolSize()));
287
+ const perWorker = frameBytes * (motionBlur > 1 ? motionBlur + 4 : 3);
288
+ const workers = Math.max(1, Math.min(requested, Math.floor(budget * 0.75 / perWorker)));
289
+ const extra = Math.floor(budget * 0.25 / frameBytes);
290
+ return { workers, readAhead: Math.max(workers + 1, Math.min(workers * 2, workers + extra)) };
291
+ }
292
+ function frameStream(film, pool, timeOf, size, count, readAhead, subframes = 1, shutterSpan = 0) {
293
+ const inFlight = /* @__PURE__ */ new Map();
294
+ const submit = async (index) => {
295
+ const base = timeOf(index);
296
+ const frames = [];
297
+ for (let sub = 0; sub < subframes; sub++) {
298
+ frames.push(await frameAt(film, base + sub / subframes * shutterSpan));
299
+ }
300
+ return pool.run(framesToJob(frames, size.width, backgroundBytes, size.height));
301
+ };
302
+ return async (index) => {
303
+ for (let ahead = index; ahead < Math.min(count, index + readAhead); ahead++) {
304
+ if (inFlight.has(ahead)) continue;
305
+ const job = submit(ahead);
306
+ job.catch(() => {
307
+ });
308
+ inFlight.set(ahead, job);
309
+ }
310
+ const pixels = await inFlight.get(index);
311
+ inFlight.delete(index);
312
+ return pixels;
313
+ };
314
+ }
315
+ async function renderFilmVideo(film, outputPath, options = {}) {
316
+ const compiled = await resolveFilm(film, options);
317
+ const quality = QUALITY[options.quality ?? "standard"];
318
+ if (!quality) throw new Error(`Unknown quality: ${options.quality}. Use draft, standard, high, or master.`);
319
+ const size = evenSize(compiled, options.width);
320
+ const motionBlur = Math.max(1, Math.floor(options.motionBlur ?? quality.motionBlur));
321
+ const shutter = options.shutter ?? 0.5;
322
+ const fps = compiled.fps;
323
+ const codec = options.codec ?? "h264";
324
+ const { from, to } = timeRange(compiled, options);
325
+ const plan = planRender(size.width, size.height, motionBlur, options);
326
+ const pool = new RasterPool(plan.workers);
327
+ try {
328
+ const count = Math.max(1, Math.round((to - from) * fps));
329
+ const next = frameStream(compiled, pool, (index) => from + index / fps, size, count, plan.readAhead, motionBlur, shutter / fps);
330
+ const output = await renderRgbaVideo((info) => next(info.index), {
331
+ width: size.width,
332
+ height: size.height,
333
+ fps,
334
+ duration: (to - from) * 1e3,
335
+ outputPath,
336
+ codec,
337
+ crf: codec === "vp9" ? quality.vp9Crf : quality.crf,
338
+ preset: quality.preset,
339
+ // Flat color and fine lines keep their edges better with this tuning.
340
+ tune: codec === "h264" ? "animation" : void 0,
341
+ threads: options.threads ?? 6,
342
+ audioPath: options.audioPath,
343
+ audioOffset: from > 0 ? from : void 0,
344
+ ffmpegPath: options.ffmpegPath,
345
+ signal: options.signal,
346
+ onProgress: options.onProgress
347
+ });
348
+ return { ...output, title: compiled.title, workers: pool.size, motionBlur, codec };
349
+ } finally {
350
+ await pool.close();
351
+ }
352
+ }
353
+ var gifApi = typeof gifenc.GIFEncoder === "function" ? gifenc : gifenc.default;
354
+ function changedRegion(previous, current, width, height) {
355
+ let minX = width, minY = height, maxX = -1, maxY = -1;
356
+ for (let y = 0; y < height; y++) {
357
+ const row = y * width * 4;
358
+ for (let x = 0; x < width; x++) {
359
+ const o = row + x * 4;
360
+ if (previous[o] !== current[o] || previous[o + 1] !== current[o + 1] || previous[o + 2] !== current[o + 2]) {
361
+ if (x < minX) minX = x;
362
+ if (x > maxX) maxX = x;
363
+ if (y < minY) minY = y;
364
+ maxY = y;
365
+ }
366
+ }
367
+ }
368
+ return maxX < 0 ? null : { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 };
369
+ }
370
+ function cropRegion(pixels, canvasWidth, region) {
371
+ const out = new Uint8Array(region.width * region.height * 4);
372
+ for (let y = 0; y < region.height; y++) {
373
+ const start = ((region.y + y) * canvasWidth + region.x) * 4;
374
+ out.set(pixels.subarray(start, start + region.width * 4), y * region.width * 4);
375
+ }
376
+ return out;
377
+ }
378
+ async function renderFilmGif(film, outputPath, options = {}) {
379
+ const compiled = await resolveFilm(film, { ...options, fps: void 0 });
380
+ const size = outputSize(compiled, options.width ?? Math.min(DEFAULT_GIF_WIDTH, compiled.width));
381
+ const fps = Math.min(options.fps ?? DEFAULT_GIF_FPS, 50);
382
+ const { from, to } = timeRange(compiled, options);
383
+ const count = Math.max(1, Math.round((to - from) * fps));
384
+ const delay = 1e3 / fps;
385
+ const plan = planRender(size.width, size.height, 1, options);
386
+ const pool = new RasterPool(plan.workers);
387
+ try {
388
+ const sampleCount = Math.min(count, GIF_PALETTE_FRAMES);
389
+ const samples = await Promise.all(Array.from({ length: sampleCount }, async (_, i) => {
390
+ const index = Math.floor((i + 0.5) * count / sampleCount);
391
+ return pool.run(framesToJob([await frameAt(compiled, from + index / fps)], size.width, backgroundBytes, size.height));
392
+ }));
393
+ const perFrame = Math.max(1, Math.floor(GIF_PALETTE_PIXELS / sampleCount));
394
+ const combined = new Uint8Array(perFrame * sampleCount * 4);
395
+ samples.forEach((pixels, i) => {
396
+ const total = pixels.length / 4;
397
+ for (let k = 0; k < perFrame; k++) {
398
+ const at = Math.floor((k + 0.5) * total / perFrame) * 4;
399
+ combined.set(pixels.subarray(at, at + 4), (i * perFrame + k) * 4);
400
+ }
401
+ });
402
+ const palette = gifApi.quantize(combined, 256, { format: "rgb565" });
403
+ const gif = gifApi.GIFEncoder();
404
+ const next = frameStream(compiled, pool, (index) => from + index / fps, size, count, plan.readAhead);
405
+ const repeat = options.loop === false ? -1 : 0;
406
+ let previous = null;
407
+ let pending = null;
408
+ const flush = (first) => {
409
+ if (!pending) return;
410
+ let remaining = pending.delay;
411
+ let includePalette = first;
412
+ do {
413
+ const span = Math.min(MAX_GIF_DELAY, remaining);
414
+ const start = gif.bytesView().length;
415
+ gif.writeFrame(pending.index, pending.region.width, pending.region.height, {
416
+ ...includePalette ? { palette } : {},
417
+ delay: Math.max(20, span),
418
+ repeat,
419
+ dispose: 1
420
+ });
421
+ if (pending.region.x !== 0 || pending.region.y !== 0) {
422
+ const bytes = gif.bytesView();
423
+ const descriptor = start + 8;
424
+ if (bytes[descriptor] !== 44) throw new Error("The GIF encoder wrote an unexpected frame layout.");
425
+ bytes[descriptor + 1] = pending.region.x & 255;
426
+ bytes[descriptor + 2] = pending.region.x >> 8 & 255;
427
+ bytes[descriptor + 3] = pending.region.y & 255;
428
+ bytes[descriptor + 4] = pending.region.y >> 8 & 255;
429
+ }
430
+ includePalette = false;
431
+ remaining -= span;
432
+ } while (remaining > 0);
433
+ };
434
+ let wroteAny = false;
435
+ for (let i = 0; i < count; i++) {
436
+ options.signal?.throwIfAborted();
437
+ const pixels = await next(i);
438
+ const region = previous ? changedRegion(previous, pixels, size.width, size.height) : { x: 0, y: 0, width: size.width, height: size.height };
439
+ if (!region) {
440
+ if (pending) pending.delay += delay;
441
+ } else {
442
+ flush(!wroteAny);
443
+ if (pending) wroteAny = true;
444
+ const cropped = region.width === size.width && region.height === size.height ? pixels : cropRegion(pixels, size.width, region);
445
+ pending = { index: gifApi.applyPalette(cropped, palette, "rgb565"), region, delay };
446
+ previous = pixels;
447
+ }
448
+ await options.onProgress?.({ index: i, count, time: i * delay, duration: count * delay, progress: i / count, fps });
449
+ }
450
+ flush(!wroteAny);
451
+ gif.finish();
452
+ const path = resolve(outputPath);
453
+ await mkdir(dirname(path), { recursive: true });
454
+ await writeFile(path, gif.bytesView());
455
+ return { width: size.width, height: size.height, frameCount: count, duration: count * delay, fps, bytes: (await stat(path)).size, outputPath: path, title: compiled.title };
456
+ } finally {
457
+ await pool.close();
458
+ }
459
+ }
460
+ async function renderFilmFrame(film, time, outputPath, options = {}) {
461
+ const compiled = await resolveFilm(film, options);
462
+ const { width, height } = outputSize(compiled, options.width);
463
+ const pool = new RasterPool(1);
464
+ try {
465
+ const frame = await frameAt(compiled, time);
466
+ const pixels = await pool.run(framesToJob([frame], width, backgroundBytes, height));
467
+ const path = resolve(outputPath);
468
+ await mkdir(dirname(path), { recursive: true });
469
+ await writeFile(path, encodePng({ width, height, data: pixels, depth: 8, channels: 4 }));
470
+ return { width, height, outputPath: path };
471
+ } finally {
472
+ await pool.close();
473
+ }
474
+ }
475
+ async function renderFilmFrames(film, times, outputPrefix, options = {}) {
476
+ const compiled = await resolveFilm(film, options);
477
+ const { width, height } = outputSize(compiled, options.width);
478
+ const plan = planRender(width, height, 1, options);
479
+ const pool = new RasterPool(plan.workers);
480
+ try {
481
+ await mkdir(dirname(resolve(outputPrefix)), { recursive: true });
482
+ const frames = [];
483
+ for (const time of times) frames.push(await frameAt(compiled, time));
484
+ return await Promise.all(frames.map(async (frame, index) => {
485
+ const pixels = await pool.run(framesToJob([frame], width, backgroundBytes, height));
486
+ const path = resolve(`${outputPrefix}${String(index).padStart(3, "0")}.png`);
487
+ await writeFile(path, encodePng({ width, height, data: pixels, depth: 8, channels: 4 }));
488
+ return path;
489
+ }));
490
+ } finally {
491
+ await pool.close();
492
+ }
493
+ }
494
+ async function renderFilmSvg(film, time, outputPath, options = {}) {
495
+ const compiled = await resolveFilm(film, options);
496
+ const path = resolve(outputPath);
497
+ await mkdir(dirname(path), { recursive: true });
498
+ const frame = await frameAt(compiled, time);
499
+ const scale = (options.width ?? compiled.width) / compiled.width;
500
+ await writeFile(path, frameToSvg(frame, { scale }));
501
+ return { width: Math.round(compiled.width * scale), height: Math.round(compiled.height * scale), outputPath: path };
502
+ }
503
+ async function posterTime(film) {
504
+ if (film.posterTime !== void 0) return Math.max(0, Math.min(film.duration, film.posterTime));
505
+ const active = (t) => film.clips.some((clip) => clip.t0 < t && t < clip.t1);
506
+ const nudge = 1e-3;
507
+ const candidates = /* @__PURE__ */ new Set();
508
+ for (const clip of film.clips) {
509
+ const t = clip.t1 + nudge;
510
+ if (t < film.duration && !active(t)) candidates.add(t);
511
+ }
512
+ if (candidates.size === 0) for (let i = 1; i <= 10; i++) candidates.add(film.duration * i / 10 - nudge);
513
+ const scored = [];
514
+ for (const time of [...candidates].sort((a, b) => a - b)) {
515
+ const frame = await frameAt(film, time);
516
+ scored.push({ time, ink: frame.ops.length });
517
+ }
518
+ const fullest = Math.max(...scored.map((entry) => entry.ink));
519
+ const rich = scored.filter((entry) => entry.ink >= fullest * 0.75);
520
+ return rich[rich.length - 1]?.time ?? film.duration;
521
+ }
522
+ function captionsToVtt(film) {
523
+ const stamp = (seconds) => {
524
+ const m = Math.floor(seconds / 60), s = seconds - m * 60;
525
+ return `${String(m).padStart(2, "0")}:${s.toFixed(3).padStart(6, "0")}`;
526
+ };
527
+ const cues = film.captions.map((cue) => `${stamp(cue.t0)} --> ${stamp(cue.t1)}
528
+ ${cue.text}`);
529
+ return `WEBVTT
530
+
531
+ ${cues.join("\n\n")}
532
+ `;
533
+ }
534
+ export {
535
+ captionsToVtt,
536
+ fromComponent,
537
+ planRender,
538
+ posterTime,
539
+ renderFilmFrame,
540
+ renderFilmFrames,
541
+ renderFilmGif,
542
+ renderFilmSvg,
543
+ renderFilmVideo
544
+ };