@alpha2-sh/editor 0.4.5 → 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 (81) hide show
  1. package/dist/browser/bridge.d.ts +15 -16
  2. package/dist/browser/bridge.js +533 -387
  3. package/dist/browser/extensions-worker.d.ts +12 -16
  4. package/dist/browser/extensions-worker.js +17 -24
  5. package/dist/browser/hash-worker.d.ts +4 -5
  6. package/dist/browser/hash-worker.js +7 -8
  7. package/dist/browser/jobs.d.ts +17 -19
  8. package/dist/browser/jobs.js +41 -28
  9. package/dist/browser/resources.d.ts +6 -11
  10. package/dist/browser/resources.js +5 -9
  11. package/dist/browser/runtime/assets.d.ts +52 -31
  12. package/dist/browser/runtime/assets.js +206 -47
  13. package/dist/browser/runtime/audio.d.ts +16 -11
  14. package/dist/browser/runtime/audio.js +58 -31
  15. package/dist/browser/runtime/budget.d.ts +4 -5
  16. package/dist/browser/runtime/budget.js +4 -5
  17. package/dist/browser/runtime/caption-fonts.d.ts +3 -7
  18. package/dist/browser/runtime/caption-fonts.js +4 -8
  19. package/dist/browser/runtime/engine.d.ts +40 -43
  20. package/dist/browser/runtime/engine.js +82 -63
  21. package/dist/browser/runtime/export-audio.d.ts +6 -6
  22. package/dist/browser/runtime/export-audio.js +8 -9
  23. package/dist/browser/runtime/exporter.d.ts +33 -66
  24. package/dist/browser/runtime/exporter.js +111 -137
  25. package/dist/browser/runtime/extension-import.d.ts +28 -35
  26. package/dist/browser/runtime/extension-import.js +36 -46
  27. package/dist/browser/runtime/fingerprint.d.ts +11 -14
  28. package/dist/browser/runtime/fingerprint.js +20 -24
  29. package/dist/browser/runtime/generators.d.ts +2 -3
  30. package/dist/browser/runtime/generators.js +5 -7
  31. package/dist/browser/runtime/locks.d.ts +5 -7
  32. package/dist/browser/runtime/locks.js +5 -7
  33. package/dist/browser/runtime/output.d.ts +7 -9
  34. package/dist/browser/runtime/output.js +17 -21
  35. package/dist/browser/runtime/preview-utils.js +10 -6
  36. package/dist/browser/runtime/proxies.d.ts +10 -17
  37. package/dist/browser/runtime/proxies.js +33 -45
  38. package/dist/browser/runtime/proxy-storage.d.ts +15 -19
  39. package/dist/browser/runtime/proxy-storage.js +20 -24
  40. package/dist/browser/runtime/sources.d.ts +23 -31
  41. package/dist/browser/runtime/sources.js +98 -105
  42. package/dist/browser/runtime/staging.d.ts +2 -6
  43. package/dist/browser/runtime/staging.js +7 -11
  44. package/dist/browser/runtime/still.d.ts +2 -6
  45. package/dist/browser/runtime/still.js +6 -12
  46. package/dist/browser/runtime/text.d.ts +14 -0
  47. package/dist/browser/runtime/text.js +27 -0
  48. package/dist/browser/runtime/wasm.d.ts +4 -5
  49. package/dist/browser/runtime/wasm.js +4 -5
  50. package/dist/browser/types.d.ts +243 -221
  51. package/dist/browser/worker.d.ts +8 -9
  52. package/dist/browser/worker.js +55 -22
  53. package/dist/core/captions.d.ts +8 -10
  54. package/dist/core/captions.js +10 -18
  55. package/dist/core/clip-time.d.ts +8 -10
  56. package/dist/core/clip-time.js +12 -15
  57. package/dist/core/commands.d.ts +46 -46
  58. package/dist/core/commands.js +38 -36
  59. package/dist/core/compositions.d.ts +78 -112
  60. package/dist/core/compositions.js +66 -94
  61. package/dist/core/document.d.ts +59 -92
  62. package/dist/core/document.js +65 -90
  63. package/dist/core/keyframes.d.ts +11 -12
  64. package/dist/core/keyframes.js +11 -13
  65. package/dist/core/presets.d.ts +14 -20
  66. package/dist/core/presets.js +12 -18
  67. package/dist/core/session.d.ts +26 -38
  68. package/dist/core/session.js +38 -53
  69. package/dist/core/text.d.ts +2 -3
  70. package/dist/core/text.js +2 -3
  71. package/dist/core/timeline-index.d.ts +2 -3
  72. package/dist/core/timeline-index.js +11 -7
  73. package/dist/core/transitions.js +4 -5
  74. package/dist/core/validated.d.ts +6 -7
  75. package/dist/core/validated.js +8 -11
  76. package/dist/native-client/index.d.ts +31 -32
  77. package/dist/native-client/index.js +40 -41
  78. package/dist/ports/index.d.ts +19 -19
  79. package/dist/react/index.d.ts +5 -6
  80. package/dist/react/index.js +5 -6
  81. package/package.json +4 -4
@@ -3,10 +3,13 @@ import { compileEditorDocument, EditorError, sequenceEnd, } from "../core/docume
3
3
  import { captionsAsset } from "../core/captions.js";
4
4
  import { MAX_CAPTION_FILE_BYTES } from "alpha2/project";
5
5
  import { containerPolicy } from "alpha2/containers";
6
+ import { PlanarDecodeUnavailableError } from "alpha2/hdr-frames";
6
7
  import { drawnEffectResources, shownSources } from "../core/compositions.js";
7
8
  import { ResourceRegistry } from "./resources.js";
8
9
  import { ExportJob, requireExportFrameRate } from "./jobs.js";
10
+ import { GpuRecoveryLadder, lossReportFromJson, pageGpuLosses, } from "alpha2/gpu-recovery";
9
11
  import { attemptOptions } from "./runtime/budget.js";
12
+ import { readUserText } from "./runtime/text.js";
10
13
  import { createWorkerPreview } from "./worker.js";
11
14
  import { registerCaptionFonts } from "./runtime/caption-fonts.js";
12
15
  import { AssetLibrary, streamPeaks } from "./runtime/assets.js";
@@ -16,10 +19,10 @@ import { hashInWorker } from "./hash-worker.js";
16
19
  import { callExtensions } from "./extensions-worker.js";
17
20
  import { keepProviderChoices, mayBeExtension, providerDocumentLimit, stageProviderFile, stageSequence, } from "./runtime/extension-import.js";
18
21
  import { ProxyStore } from "./runtime/proxies.js";
19
- import { blockingIssues, compareFingerprints, conformProject, } from "alpha2/assets";
22
+ import { blockingIssues, compareFingerprints, conformProject, sha256Blob, } from "alpha2/assets";
20
23
  /**
21
- * An export refused before it rendered: the engine's conform report says why. The message names
22
- * each source as `nameOf` does (the document's asset names), the report and `entityId` by ID.
24
+ * An export refused before it rendered, with the engine's conform report. The message names sources
25
+ * by `nameOf` (the document's asset names); the report and `entityId` use IDs.
23
26
  */
24
27
  export class ConformError extends EditorError {
25
28
  /**
@@ -36,7 +39,6 @@ export class ConformError extends EditorError {
36
39
  }
37
40
  }
38
41
  import { EngineAudioMixer, AudioWindowSupplier } from "./runtime/audio.js";
39
- /** The engine's playback policies (`PlaybackPolicy`), in its order. */
40
42
  const PLAYBACK_POLICIES = Object.freeze([
41
43
  "drop_video_keep_audio",
42
44
  "preserve_every_video_frame",
@@ -44,34 +46,40 @@ const PLAYBACK_POLICIES = Object.freeze([
44
46
  "offline_exact",
45
47
  ]);
46
48
  /**
47
- * How long Play waits for sound to start before playing the picture without it. A first start loads
48
- * and compiles the audio worklet and decodes the first block, about 1.5 s on Firefox.
49
+ * Files of one import staged at once. Each hashes in its own worker at about 200 MB/s, so four stay
50
+ * below a local SSD's read rate and leave one core for the page.
51
+ */
52
+ const IMPORT_STAGE_CONCURRENCY = 4;
53
+ /** `previewIssue` while the frame shows an HDR source this browser hands over only degraded. */
54
+ const DEGRADED_PREVIEW_ISSUE = "HDR shown with the browser's tone mapping; the browser cannot export it: export with the native host";
55
+ /**
56
+ * How long Play waits for sound before playing the picture without it. A first start loads the
57
+ * audio worklet and decodes the first block, about 1.5 s on Firefox.
49
58
  */
50
59
  const AUDIO_START_TIMEOUT_MS = 3000;
51
60
  /**
52
- * The default media adapter: stages each file in its own `AssetLibrary`, apart from the
53
- * bridge's live one, so a failed or cancelled import leaves nothing behind. Files an extension
54
- * provider reads (SVG, animated images, Lottie, OpenEXR) are probed, opened and drawn for their
55
- * thumbnail by `alpha2/extensions`, loaded from `extensionsWasmUrl`: in a worker
56
- * `extensionsWorkerFactory` makes for each file, which a cancelled import or a call past
57
- * `EXTENSIONS_CALL_TIMEOUT_MS` terminates, or, without one, on this thread. A font is checked with
58
- * the engine's parser (`alpha2/wasm`, from `wasmUrl`) and also registered with the page's
59
- * `FontFace` set. A file's content hash is made in a worker `hashWorkerFactory` makes, where there
60
- * is one.
61
- * @param {{ extensionsWasmUrl?: string | URL, wasmUrl?: string | URL, hashWorkerFactory?: () => Worker, extensionsWorkerFactory?: () => Worker }} [options]
61
+ * The default media adapter. Each file stages in its own `AssetLibrary`, apart from the bridge's
62
+ * live one, so a failed or cancelled import leaves nothing behind. Extension provider files (SVG,
63
+ * animated images, Lottie, OpenEXR) are probed and thumbnailed by `alpha2/extensions` in a worker
64
+ * per file from `extensionsWorkerFactory` (terminated on cancel or past
65
+ * `EXTENSIONS_CALL_TIMEOUT_MS`), or on this thread without one. Fonts are checked with the engine's
66
+ * parser and also registered with the page's `FontFace` set. Content hashes run in a
67
+ * `hashWorkerFactory` worker when given. HDR video without planes imports degraded or is refused,
68
+ * per `hdrWithoutPlanes`.
69
+ * @param {{ extensionsWasmUrl?: string | URL, wasmUrl?: string | URL, hashWorkerFactory?: () => Worker, extensionsWorkerFactory?: () => Worker, hdrWithoutPlanes?: "refuse" | "preview-degraded" }} [options]
62
70
  * @returns {import("./types.js").BrowserMediaAdapter}
63
71
  */
64
- export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFactory, extensionsWorkerFactory, } = {}) {
72
+ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFactory, extensionsWorkerFactory, hdrWithoutPlanes = "preview-degraded", } = {}) {
65
73
  const hash = hashWorkerFactory
66
74
  ? (file, options) => hashInWorker(hashWorkerFactory, file, options)
67
- : undefined;
75
+ : sha256Blob;
68
76
  const module = {
69
77
  factory: extensionsWorkerFactory,
70
78
  wasmUrl: extensionsWasmUrl,
71
79
  };
72
80
  /**
73
- * What the provider module makes of `file` with `call`. A file it refuses is `unreadable_media`
74
- * with its reason; a cancellation or a stall is passed on as it is.
81
+ * Runs provider `call` on `file`. A refusal becomes `unreadable_media` with its reason;
82
+ * cancellation and stalls pass through unchanged.
75
83
  */
76
84
  const read = async (call, file, signal) => {
77
85
  try {
@@ -84,7 +92,6 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
84
92
  }
85
93
  };
86
94
  return {
87
- /** Stages numbered PNGs or OpenEXR images as one image sequence. */
88
95
  async stageSequence(files, options, signal) {
89
96
  signal.throwIfAborted();
90
97
  const item = await stageSequence(files, {
@@ -96,140 +103,166 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
96
103
  },
97
104
  async stage(file, signal, { fingerprint: wanted = true } = {}) {
98
105
  signal.throwIfAborted();
99
- /** The file's fingerprint, unless the caller has no use for it (a proxy being adopted). */
106
+ // Start hashing now so it overlaps probing.
107
+ const hashing = new AbortController();
108
+ const stop = () => hashing.abort(signal.reason);
109
+ signal.addEventListener("abort", stop, { once: true });
110
+ const started = wanted ? hash(file, { signal: hashing.signal }) : null;
111
+ started?.catch(() => { }); // awaited below when used; a failed stage aborts it
112
+ /** Skipped when the caller does not need it (a proxy being adopted). */
100
113
  const fingerprintOf = (kind, options) => wanted
101
- ? fingerprintFile(file, kind, { signal, hash, ...options })
114
+ ? fingerprintFile(file, kind, {
115
+ signal,
116
+ hash: () => started,
117
+ ...options,
118
+ })
102
119
  : undefined;
103
- // Recognized by its bytes; the provider module loads only for bytes that could be one.
104
- const head = new Uint8Array(await file.slice(0, 4096).arrayBuffer());
105
- if (mayBeExtension(head)) {
106
- // Parsed whole in provider memory that never shrinks, so an oversize file is refused unread.
107
- const document = providerDocumentLimit(head);
108
- if (document !== null && file.size > document.limit)
109
- throw new EditorError("too_large", `${file.name} is ${file.size} bytes; a ${document.what} is read up to ${document.limit}`, "import");
110
- const found = await read("read", file, signal);
111
- signal.throwIfAborted();
112
- if (found)
113
- return stageProviderFile(file, found, await fingerprintOf("image"));
120
+ try {
121
+ return await stageFile(file, signal, fingerprintOf);
122
+ }
123
+ catch (error) {
124
+ hashing.abort(error);
125
+ throw error;
126
+ }
127
+ finally {
128
+ signal.removeEventListener("abort", stop);
129
+ }
130
+ },
131
+ };
132
+ /** Stages `file` as the media its bytes or name indicate. */
133
+ async function stageFile(file, signal, fingerprintOf) {
134
+ // Sniff the bytes first; the provider module loads only for bytes that could match.
135
+ const head = new Uint8Array(await file.slice(0, 4096).arrayBuffer());
136
+ if (mayBeExtension(head)) {
137
+ // Providers parse whole files into memory that never shrinks; refuse oversize files unread.
138
+ const document = providerDocumentLimit(head);
139
+ if (document !== null && file.size > document.limit)
140
+ throw new EditorError("too_large", `${file.name} is ${file.size} bytes; a ${document.what} is read up to ${document.limit}`, "import");
141
+ const found = await read("read", file, signal);
142
+ signal.throwIfAborted();
143
+ if (found)
144
+ return stageProviderFile(file, found, await fingerprintOf("image"));
145
+ }
146
+ if (/\.(ttf|otf|ttc|otc)$/i.test(file.name)) {
147
+ const bytes = new Uint8Array(await file.arrayBuffer());
148
+ signal.throwIfAborted();
149
+ // The engine's parser decides: FontFace also loads WOFF and WOFF2, which the engine refuses.
150
+ const { loadEngineWasm } = await import("./runtime/wasm.js");
151
+ const { checkFont } = await loadEngineWasm(wasmUrl);
152
+ signal.throwIfAborted();
153
+ try {
154
+ checkFont(bytes, 0);
114
155
  }
115
- if (/\.(ttf|otf|ttc|otc)$/i.test(file.name)) {
116
- const bytes = new Uint8Array(await file.arrayBuffer());
156
+ catch (error) {
157
+ throw new EditorError("unreadable_media", `Cannot read ${file.name} as a font: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
158
+ }
159
+ const id = crypto.randomUUID();
160
+ let face;
161
+ if (typeof FontFace !== "undefined") {
162
+ face = new FontFace(`alpha2-font-${id}`, bytes);
163
+ await face.load();
117
164
  signal.throwIfAborted();
118
- // The engine's parser decides: FontFace also loads WOFF and WOFF2, which the engine refuses.
165
+ globalThis.document?.fonts.add(face);
166
+ }
167
+ return {
168
+ runtime: {
169
+ id,
170
+ kind: "font",
171
+ name: file.name,
172
+ bytes,
173
+ faceIndex: 0,
174
+ family: `alpha2-font-${id}`,
175
+ },
176
+ description: { id, kind: "font", name: file.name },
177
+ fingerprint: await fingerprintOf("font"),
178
+ dispose() {
179
+ if (face)
180
+ globalThis.document?.fonts.delete(face);
181
+ },
182
+ };
183
+ }
184
+ const library = new AssetLibrary({ hdrWithoutPlanes });
185
+ try {
186
+ const runtime = file.name.toLowerCase().endsWith(".cube")
187
+ ? await library.importEffectResource(file, "lut3d")
188
+ : await library.importFile(file, { signal });
189
+ signal.throwIfAborted();
190
+ if (runtime.kind === "lut3d") {
191
+ // Validate the LUT once here rather than at every load.
119
192
  const { loadEngineWasm } = await import("./runtime/wasm.js");
120
- const { checkFont } = await loadEngineWasm(wasmUrl);
193
+ const { checkLut3d } = await loadEngineWasm(wasmUrl);
121
194
  signal.throwIfAborted();
122
195
  try {
123
- checkFont(bytes, 0);
196
+ checkLut3d(runtime.text);
124
197
  }
125
198
  catch (error) {
126
- throw new EditorError("unreadable_media", `Cannot read ${file.name} as a font: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
127
- }
128
- const id = crypto.randomUUID();
129
- let face;
130
- if (typeof FontFace !== "undefined") {
131
- face = new FontFace(`alpha2-font-${id}`, bytes);
132
- await face.load();
133
- signal.throwIfAborted();
134
- globalThis.document?.fonts.add(face);
135
- }
136
- return {
137
- runtime: {
138
- id,
139
- kind: "font",
140
- name: file.name,
141
- bytes,
142
- faceIndex: 0,
143
- family: `alpha2-font-${id}`,
144
- },
145
- description: { id, kind: "font", name: file.name },
146
- fingerprint: await fingerprintOf("font"),
147
- dispose() {
148
- if (face)
149
- globalThis.document?.fonts.delete(face);
150
- },
151
- };
152
- }
153
- const library = new AssetLibrary();
154
- try {
155
- const runtime = file.name.toLowerCase().endsWith(".cube")
156
- ? await library.importEffectResource(file, "lut3d")
157
- : await library.importFile(file);
158
- signal.throwIfAborted();
159
- if (runtime.kind === "lut3d") {
160
- // The engine's parser validates the LUT once here rather than at every load.
161
- const { loadEngineWasm } = await import("./runtime/wasm.js");
162
- const { checkLut3d } = await loadEngineWasm(wasmUrl);
163
- signal.throwIfAborted();
164
- try {
165
- checkLut3d(runtime.text);
166
- }
167
- catch (error) {
168
- throw new EditorError("unreadable_media", `Cannot read ${file.name} as a 3D LUT: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
169
- }
199
+ throw new EditorError("unreadable_media", `Cannot read ${file.name} as a 3D LUT: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
170
200
  }
171
- const description = library.projectManifest()[0];
172
- const fingerprint = await fingerprintOf(runtime.kind, {
173
- size: runtime.width
174
- ? { width: runtime.width, height: runtime.height }
175
- : undefined,
176
- });
177
- signal.throwIfAborted();
178
- return {
179
- runtime,
180
- description,
181
- fingerprint,
182
- dispose: () => library.dispose(),
183
- };
184
201
  }
185
- catch (error) {
186
- library.dispose();
187
- throw error;
188
- }
189
- },
190
- };
202
+ const description = library.projectManifest()[0];
203
+ const fingerprint = await fingerprintOf(runtime.kind, {
204
+ size: runtime.width
205
+ ? { width: runtime.width, height: runtime.height }
206
+ : undefined,
207
+ });
208
+ signal.throwIfAborted();
209
+ return {
210
+ runtime,
211
+ description,
212
+ fingerprint,
213
+ dispose: () => library.dispose(),
214
+ };
215
+ }
216
+ catch (error) {
217
+ library.dispose();
218
+ throw error;
219
+ }
220
+ }
191
221
  }
192
222
  /**
193
223
  * Creates the browser runtime for an editor session: preview, playback, import, proxies and
194
- * export. No GPU device, AudioContext, worker or decoder is created until `bindPreview`, an
195
- * import, `play` or `startExport` needs one. The bridge registers itself as an owner of
196
- * `editor`, so disposing the session disposes it.
224
+ * export. GPU devices, AudioContexts, workers and decoders are created lazily. The bridge registers
225
+ * as an owner of `editor`, so disposing the session disposes it.
197
226
  * @param {import("./types.js").BrowserBridgeOptions} options
198
227
  * @returns {import("./types.js").BrowserBridge}
199
228
  */
200
229
  export function createBrowserBridge(options) {
201
- const { editor, runtimeAssets = {}, mediaAdapter = createMediaAdapter(runtimeAssets), resourceLimit = 128, audio = true, onError = () => { }, assetDecisions, previewScale: initialPreviewScale = 0.5, } = options;
230
+ const { editor, runtimeAssets = {}, hdrWithoutPlanes = "preview-degraded", mediaAdapter = createMediaAdapter({ ...runtimeAssets, hdrWithoutPlanes }), resourceLimit = 128, audio = true, onError = () => { }, assetDecisions, previewScale: initialPreviewScale = 0.5, videoConversion: initialVideoConversion = "engine", } = options;
202
231
  let previewScale = checkedPreviewScale(initialPreviewScale);
203
- // A test's stand-in for origin storage, kept out of the public options.
232
+ if (hdrWithoutPlanes !== "refuse" && hdrWithoutPlanes !== "preview-degraded")
233
+ throw new RangeError('hdrWithoutPlanes must be "refuse" or "preview-degraded"');
234
+ // How preview frame supplies treat an HDR source imported degraded.
235
+ const opaqueEngineFrames = hdrWithoutPlanes === "preview-degraded" ? "present-degraded" : "refuse";
236
+ const videoConversion = checkedVideoConversion(initialVideoConversion, "bridge");
237
+ const rendererMode = options.renderer ?? "auto";
238
+ if (rendererMode !== "auto" &&
239
+ rendererMode !== "gpu" &&
240
+ rendererMode !== "cpu")
241
+ throw new RangeError('renderer must be "auto", "gpu" or "cpu"');
242
+ // Test-only stand-in for origin storage, kept out of the public options.
204
243
  const proxyStore =
205
244
  /** @type {{ proxyStore?: ProxyStore }} */ (options).proxyStore ??
206
245
  new ProxyStore();
207
246
  let decisionBinding = assetDecisions ?? null;
208
- /**
209
- * The wasm module's authoring functions, loaded on first use: the same instance the preview
210
- * engine renders with.
211
- */
247
+ /** The wasm module's authoring functions, loaded on first use; the preview engine's instance. */
212
248
  const loadWasm = async () => {
213
249
  const { loadEngineWasm } = await import("./runtime/wasm.js");
214
250
  return loadEngineWasm(runtimeAssets.wasmUrl);
215
251
  };
216
252
  /** The engine's asset decisions, from the wasm module, loaded on first use. */
217
253
  const decisions = async () => (decisionBinding ??= await loadWasm());
218
- /**
219
- * What `measureText` and `measureLayout` lay text out with, made on first use, and the font
220
- * stack it holds.
221
- */
254
+ /** Text measurer for `measureText` and `measureLayout`, made on first use, and its font stack. */
222
255
  let measurer = null, measuredFonts = null;
223
256
  const registry = new ResourceRegistry(resourceLimit);
224
257
  /**
225
- * The runtimes this session holds, by {@link ownerKey}: a lease and the registry revision it was
226
- * put under. Media is keyed by its content revision, which this bridge issues; text by what it
227
- * draws, since an edit after an undo may give other text a revision an undone edit already used.
258
+ * Runtimes this session holds, by {@link ownerKey}: a lease and its registry revision. Media is
259
+ * keyed by content revision; text by what it draws, since an edit after an undo may reuse an
260
+ * undone edit's revision for other text.
228
261
  */
229
262
  const owners = new Map();
230
263
  /**
231
- * The highest registry revision issued for each runtime ID: none is issued twice, so a runtime
232
- * released while an export still leases it never collides with the one that replaces it.
264
+ * The highest registry revision issued per runtime ID. Never reused, so a runtime released while
265
+ * an export still leases it cannot collide with its replacement.
233
266
  */
234
267
  const issued = new Map();
235
268
  const issue = (id, atLeast = 0) => {
@@ -237,16 +270,12 @@ export function createBrowserBridge(options) {
237
270
  issued.set(id, revision);
238
271
  return revision;
239
272
  };
240
- /**
241
- * Proxies by their original's hash: the kept record, a lease on the decoded runtime and its
242
- * registry revision.
243
- */
273
+ /** Proxies by their original's hash: kept record, runtime lease and registry revision. */
244
274
  const proxies = new Map();
245
- /** Proxies being made, by source ID: their progress from 0 to 1. */
275
+ /** Progress (0 to 1) of proxies being made, by source ID. */
246
276
  const proxyJobs = new Map();
247
- /** What preview reads for each source, as the engine last selected it. */
248
277
  let previewSelection = new Map();
249
- /** What that selection was decided from (see `loaded`). */
278
+ /** The key `previewSelection` was decided from (see `loaded`). */
250
279
  let previewConformKey = null;
251
280
  /** What preview prefers where a source has a fresh proxy (see `setPreviewMedia`). */
252
281
  let preferredPreviewMedia = "original";
@@ -258,9 +287,8 @@ export function createBrowserBridge(options) {
258
287
  return ownerOf(document, descriptor)?.lease.value ?? null;
259
288
  };
260
289
  /**
261
- * The host's view of each source's media, for the engine to decide with: the original is online
262
- * when this session holds its file, and a kept proxy is offered when it was made from the media
263
- * the project recorded.
290
+ * Each source's media as the engine should see it: the original is online when this session holds
291
+ * its file, and a kept proxy is offered when made from the media the project recorded.
264
292
  */
265
293
  const catalogOf = (document) => ({
266
294
  assets: document.project.sources
@@ -292,9 +320,8 @@ export function createBrowserBridge(options) {
292
320
  /** Proxies being adopted, by hash, so two callers share one adoption. */
293
321
  const adopting = new Map();
294
322
  /**
295
- * Adopts a kept proxy: its file staged like any import, under its own ID. `hold` (the store's
296
- * `hold`) keeps the proxy in use until the runtime is disposed: once no document and no export
297
- * reads it.
323
+ * Adopts a kept proxy, staging its file like any import under its own ID. `hold` (the store's)
324
+ * keeps the proxy in use until the runtime is disposed.
298
325
  */
299
326
  function adoptProxy(hash, found, hold) {
300
327
  if (proxies.has(hash)) {
@@ -309,7 +336,7 @@ export function createBrowserBridge(options) {
309
336
  pending = (async () => {
310
337
  let staged;
311
338
  try {
312
- // A proxy is known by its original's hash; hashing its own bytes again would be wasted.
339
+ // Proxies are keyed by their original's hash, so skip hashing their own bytes.
313
340
  staged = await mediaAdapter.stage(found.file, new AbortController().signal, { fingerprint: false });
314
341
  }
315
342
  catch (error) {
@@ -340,15 +367,9 @@ export function createBrowserBridge(options) {
340
367
  adopting.set(hash, pending);
341
368
  return pending;
342
369
  }
343
- /**
344
- * Hashes the store had no proxy for, this session: not asked again until the session changes.
345
- * A proxy this session makes is adopted directly.
346
- */
370
+ /** Hashes with no stored proxy, not asked again this session. */
347
371
  let absentProxies = new Set();
348
- /**
349
- * Finds the kept proxies of sources this session has no original for, and of every source while
350
- * preview prefers proxies.
351
- */
372
+ /** Finds kept proxies for offline sources, and for every source while preview prefers proxies. */
352
373
  async function discoverProxies(document) {
353
374
  for (const source of document.project.sources) {
354
375
  const descriptor = document.assets[source.id];
@@ -359,7 +380,7 @@ export function createBrowserBridge(options) {
359
380
  (preferredPreviewMedia === "original" &&
360
381
  originalOf(document, source.id)))
361
382
  continue;
362
- // Held before it is read, so no page removes it between.
383
+ // Hold before reading so no other page removes it in between.
363
384
  const hold = await proxyStore.hold(hash);
364
385
  const found = await proxyStore.find(hash).catch(() => null);
365
386
  if (found)
@@ -370,7 +391,6 @@ export function createBrowserBridge(options) {
370
391
  }
371
392
  }
372
393
  }
373
- /** Whether `document`'s media is ready for `purpose`, as the engine decides. */
374
394
  async function conform(purpose, document = editor.document) {
375
395
  await discoverProxies(document);
376
396
  const binding = await decisions();
@@ -388,15 +408,14 @@ export function createBrowserBridge(options) {
388
408
  for (const listener of assetListeners)
389
409
  listener();
390
410
  };
391
- /** The waveform analysis running for each runtime, to abort when the runtime is let go. */
411
+ /** Running waveform analyses by runtime, aborted when the runtime is released. */
392
412
  const analyses = new Map();
393
413
  /** Whether this session still holds `runtime` for some document it can show. */
394
414
  const held = (runtime) => [...owners.values()].some((owner) => owner.lease.value === runtime);
395
415
  /**
396
- * Waveform peaks are derived after import, one file at a time, so an import commits as soon as
397
- * the media is readable. The analysis belongs to the runtime, not to the document that imported
398
- * it: a document opened again over the same media keeps it, and only letting the runtime go (no
399
- * reachable document reads it) drops it.
416
+ * Derives waveform peaks after import, one file at a time, so imports commit as soon as media is
417
+ * readable. The analysis belongs to the runtime, not the importing document, and is dropped only
418
+ * when the runtime is released.
400
419
  */
401
420
  const analyze = (runtime) => {
402
421
  if (!runtime.file ||
@@ -427,21 +446,21 @@ export function createBrowserBridge(options) {
427
446
  };
428
447
  const jobs = new Set();
429
448
  let disposed = false, engine = null, workerPreview = null, boundCanvas = null, copySurface = false,
430
- // The worker failed for a reason other than a lost GPU: later previews for this binding stay on
431
- // the main thread. A new binding tries a worker again.
449
+ // Set when the worker failed for a reason other than GPU loss; later previews for this binding
450
+ // stay on the main thread.
432
451
  workerGivenUp = false, sources = null, mixer = null, supplier = null, binding = 0, queue = Promise.resolve(), renderKey = null, tick = 0, playing = false,
433
- // How the current or last playback was asked for, so a recovered preview plays on alike.
434
- playRequest = null, renderScheduled = false, raf = 0, playClock = null, loadRevision = 0, loadedAssets = new Map(), loadedSelection = "", loadedFonts = null, audioKey = null,
435
- // What the preview worker holds from its last load.
436
- workerSent = new Map(), workerFonts = null, refreshFrame = 0, monitorVolume = 1,
437
- // Tracing the drawing renderer applies, kept for every renderer a binding makes.
452
+ // How playback was requested, so a recovered preview resumes it the same way.
453
+ playRequest = null, renderScheduled = false, raf = 0, playClock = null, loadRevision = 0, loadedAssets = new Map(), loadedSelection = "", loadedFonts = null, audioKey = null, workerSent = new Map(), workerFonts = null, refreshFrame = 0, monitorVolume = 1,
454
+ // User A/V offset for output delay the browser does not report.
455
+ audioOffsetMs = 0,
456
+ // Tracing settings, applied to every renderer a binding makes.
438
457
  passTiming = false, traceUploads = false,
439
- // The worker's last renderer diagnostics snapshot, and counters since `bindPreview`: playback
440
- // refreshes that asked for no frame, and frames copied to the bound canvas.
458
+ // The worker's last renderer diagnostics, plus counters since `bindPreview`: refreshes that
459
+ // needed no frame, and frames copied to the bound canvas.
441
460
  workerDiagnostics = null, skippedRequests = 0, bitmapTransfers = 0, playGeneration = 0, sessionGeneration = editor.generation;
442
461
  /**
443
- * Preview's media for a source of `document`: what the engine selected, the original unless it is
444
- * offline, opened as the document's source says.
462
+ * Preview's media for a source: what the engine selected (the original unless offline), opened
463
+ * with the document's provider settings.
445
464
  */
446
465
  function previewMedia(document, id) {
447
466
  const descriptor = document.assets[id];
@@ -455,10 +474,7 @@ export function createBrowserBridge(options) {
455
474
  }
456
475
  const library = { get: (id) => previewMedia(editor.draft, id) };
457
476
  const key = (id, revision) => JSON.stringify([id, revision]);
458
- /**
459
- * The font families a text style draws with: each imported font's by the family its runtime
460
- * registered, other names as written.
461
- */
477
+ /** Font families a text style draws with: imported fonts by their registered family. */
462
478
  function familiesOf(document, text) {
463
479
  return (text?.fontFamily ?? "sans-serif").split(",").map((name) => {
464
480
  const plain = name.trim().replace(/^["']|["']$/g, "");
@@ -466,10 +482,7 @@ export function createBrowserBridge(options) {
466
482
  return (font && ownerOf(document, font)?.lease.value.family) ?? plain;
467
483
  });
468
484
  }
469
- /**
470
- * Which runtime `asset` of `document` reads: media by its content revision, text by its authoring
471
- * and the fonts it resolves to.
472
- */
485
+ /** Which runtime `asset` reads: media by content revision, text by authoring and fonts. */
473
486
  function ownerKey(document, asset) {
474
487
  return asset.kind === "text"
475
488
  ? JSON.stringify([
@@ -483,10 +496,7 @@ export function createBrowserBridge(options) {
483
496
  function ownerOf(document, asset) {
484
497
  return owners.get(ownerKey(document, asset)) ?? null;
485
498
  }
486
- /**
487
- * A lease on the runtime `asset` of `document` reads, for work that outlives the owner's hold on
488
- * it.
489
- */
499
+ /** A lease on the runtime `asset` reads, for work that outlives the owner's hold. */
490
500
  function acquireOwned(document, asset) {
491
501
  const owner = asset && ownerOf(document, asset);
492
502
  if (!owner && asset?.kind === "text")
@@ -501,12 +511,11 @@ export function createBrowserBridge(options) {
501
511
  throw new EditorError("missing_asset", `${editor.document.assets[id]?.name ?? id} has no proxy in this session`, "resource", id);
502
512
  return registry.acquire(`proxy:${hash}`, proxy.revision);
503
513
  }
504
- /** Runtime views by runtime, then by provider settings, so one choice is one value. */
514
+ /** Runtime views by runtime, then provider settings, so each choice maps to one value. */
505
515
  const views = new WeakMap();
506
516
  /**
507
- * `runtime` opened as source `id` of `document` says: a provider's settings (a package's
508
- * animation, an OpenEXR still's primaries) are the document's, so undo and redo change what is
509
- * drawn. A view reads everything else from the runtime itself, and a new choice is a new value.
517
+ * `runtime` opened with document `id`'s provider settings (a package's animation, an OpenEXR
518
+ * still's primaries), so undo and redo change what is drawn.
510
519
  */
511
520
  function sourceView(document, id, runtime) {
512
521
  if (!runtime?.provider)
@@ -528,8 +537,8 @@ export function createBrowserBridge(options) {
528
537
  return view;
529
538
  }
530
539
  /**
531
- * Runs `fn` after the preview work already queued. Its failure goes to the caller, which reports
532
- * it: to whoever awaits it, or to `onError` for work the bridge started itself, never to both.
540
+ * Runs `fn` after queued preview work. Its failure goes only to the caller, which reports it to
541
+ * whoever awaits it, or to `onError` for work the bridge started itself.
533
542
  */
534
543
  const enqueue = (fn) => {
535
544
  const next = queue.then(() => {
@@ -549,8 +558,14 @@ export function createBrowserBridge(options) {
549
558
  return asset?.kind === "text" ? { id, kind: "image", asset } : asset;
550
559
  },
551
560
  });
561
+ // Preview needs the engine module and canvases, not a GPU: without one it renders on the CPU.
552
562
  const features = Object.freeze({
553
- preview: { available: typeof OffscreenCanvas !== "undefined" },
563
+ preview: {
564
+ available: typeof WebAssembly !== "undefined" &&
565
+ typeof OffscreenCanvas !== "undefined" &&
566
+ typeof VideoFrame !== "undefined",
567
+ reason: "Preview needs WebAssembly, OffscreenCanvas and WebCodecs; it renders on the CPU where the browser offers no hardware GPU",
568
+ },
554
569
  audioPreview: {
555
570
  available: typeof SharedArrayBuffer !== "undefined" &&
556
571
  globalThis.crossOriginIsolated === true,
@@ -562,16 +577,18 @@ export function createBrowserBridge(options) {
562
577
  reason: "Provide a bundled workerFactory; otherwise the main-thread adapter is used",
563
578
  },
564
579
  export: {
565
- available: typeof VideoEncoder !== "undefined",
566
- reason: "Codec availability is checked at export; output streams to a temporary origin-private file unless a file or memory output is chosen",
580
+ available: typeof WebAssembly !== "undefined" &&
581
+ typeof OffscreenCanvas !== "undefined" &&
582
+ typeof VideoEncoder !== "undefined",
583
+ reason: "Codec availability is checked at export, which renders on the CPU where the browser offers no hardware GPU; output streams to a temporary origin-private file unless a file or memory output is chosen",
567
584
  },
568
585
  });
569
- /** The page's capability report; the GPU and color are known once a preview is bound. */
586
+ /** The page's capability report; GPU and color are known once a preview is bound. */
570
587
  let capabilities = capabilityReport(null);
571
588
  function capabilityReport(rendered) {
572
589
  return Object.freeze({
573
590
  schema: "alpha2-capabilities",
574
- version: 1,
591
+ version: 2,
575
592
  runtime: "browser",
576
593
  gpu: rendered?.gpu ?? null,
577
594
  color: rendered?.color ?? null,
@@ -583,25 +600,18 @@ export function createBrowserBridge(options) {
583
600
  decode: null,
584
601
  encode: null,
585
602
  features,
603
+ adapters: null,
604
+ renderer: rendered?.renderer ?? null,
586
605
  });
587
606
  }
588
- /**
589
- * Why each text could not be drawn, by {@link ownerKey}: a failed raster is not retried until its
590
- * authoring or fonts change.
591
- */
607
+ /** Raster failures by {@link ownerKey}; not retried until authoring or fonts change. */
592
608
  const textFailures = new Map();
593
- /**
594
- * The error a render that shows `asset`, a text of `document` that could not be rasterized, fails
595
- * with.
596
- */
609
+ /** The error a render fails with when it shows text `asset` that could not be rasterized. */
597
610
  function undrawnText(document, asset) {
598
611
  const failure = textFailures.get(ownerKey(document, asset));
599
612
  return new EditorError("text_unrenderable", `Text "${asset.name}" cannot be drawn: ${failure?.message ?? "it was not rasterized"}`, "resource", asset.id);
600
613
  }
601
- /**
602
- * Fails with {@link undrawnText} when `project`, compiled from `document`, shows a text that
603
- * could not be drawn.
604
- */
614
+ /** Throws {@link undrawnText} when compiled `project` shows text that could not be drawn. */
605
615
  function requireShownText(document, project) {
606
616
  const used = shownSources(project);
607
617
  for (const asset of Object.values(document.assets))
@@ -611,9 +621,9 @@ export function createBrowserBridge(options) {
611
621
  throw undrawnText(document, asset);
612
622
  }
613
623
  /**
614
- * Rasterizes each text of `document` that no held runtime draws yet: new authoring, or a font
615
- * that resolves to another family now that it is linked. A text that cannot be drawn (too large
616
- * for a texture, say) is recorded, not thrown: it fails only the renders that show it.
624
+ * Rasterizes each text of `document` that no held runtime draws yet (new authoring, or a font
625
+ * that now resolves to another family). A text that cannot be drawn (too large for a texture,
626
+ * say) is recorded, not thrown, and fails only renders that show it.
617
627
  */
618
628
  function materializeText(document) {
619
629
  for (const asset of Object.values(document.assets)) {
@@ -641,7 +651,7 @@ export function createBrowserBridge(options) {
641
651
  }
642
652
  }
643
653
  const hasContent = (project) => project?.timeline.tracks.some((track) => (track.clips?.length ?? 0) + (track.captions?.cues.length ?? 0) > 0);
644
- // A node the viewer shows instead of a composition's output; preview only.
654
+ // Node shown instead of a composition's output; preview only.
645
655
  let previewOutput = null;
646
656
  const withPreviewOutput = (project) => {
647
657
  if (!previewOutput)
@@ -656,12 +666,8 @@ export function createBrowserBridge(options) {
656
666
  };
657
667
  };
658
668
  /**
659
- * The fonts captions and an SVG's text draw with, in fallback order: the document's font assets,
660
- * then the runtime's own. Native exports get the same stack (`nativeAssets`).
661
- */
662
- /**
663
- * Reports each font of a registered stack the engine could not parse, by name: it was left out,
664
- * and captions and SVG text draw with the fonts after it.
669
+ * Reports each font of a registered stack the engine could not parse. It was left out, and
670
+ * captions and SVG text fall back to the fonts after it.
665
671
  */
666
672
  function reportRefusedFonts(refused, operation) {
667
673
  for (const { font, error } of refused ?? [])
@@ -672,16 +678,13 @@ export function createBrowserBridge(options) {
672
678
  ...(runtimeAssets.fonts ?? []),
673
679
  ];
674
680
  /**
675
- * The document's font assets this session holds a file for. A font is no source the engine
676
- * checks: one not linked is left out of the stack, by preview and exports alike, never refused.
681
+ * The document's font assets this session holds a file for. Unlinked fonts are left out of the
682
+ * stack by preview and exports alike, never refused.
677
683
  */
678
684
  function heldFonts(document) {
679
685
  return Object.values(document.assets).filter((a) => a.kind === "font" && !a.missing && ownerOf(document, a));
680
686
  }
681
- /**
682
- * Readies `measurer` with the fonts preview draws the draft with, and answers the draft's canvas
683
- * size, which preview draws it at.
684
- */
687
+ /** Loads `measurer` with preview's fonts for the draft and returns the draft's canvas size. */
685
688
  async function draftMeasurer() {
686
689
  const { WasmTextMeasurer } = await loadWasm();
687
690
  if (disposed)
@@ -690,7 +693,7 @@ export function createBrowserBridge(options) {
690
693
  const fonts = fontStackOf(document);
691
694
  measurer ??= new WasmTextMeasurer();
692
695
  if (!sameList(measuredFonts, fonts)) {
693
- // A font the engine refuses is left out here as preview leaves it out, and reported there.
696
+ // Refused fonts are left out here as preview does, and reported there.
694
697
  registerCaptionFonts(measurer, fonts);
695
698
  measuredFonts = fonts;
696
699
  }
@@ -729,7 +732,6 @@ export function createBrowserBridge(options) {
729
732
  previewConformKey = conformKey;
730
733
  }
731
734
  const selectionKey = JSON.stringify([...previewSelection]);
732
- // `proxyStatus` reports what preview reads.
733
735
  if (selectionKey !== before)
734
736
  notifyAssets();
735
737
  const used = shownSources(compiled.project);
@@ -747,12 +749,12 @@ export function createBrowserBridge(options) {
747
749
  throw new EditorError("missing_asset", `Relink ${document.assets[resource.id]?.name ?? resource.id} before preview`, "preview", resource.id);
748
750
  const allFonts = fontStackOf(document);
749
751
  const key = renderKeyOf(document);
750
- // Audio is configured once the edit settles: sound only plays after a gesture.
752
+ // Configure audio once the edit settles; sound only plays after a gesture anyway.
751
753
  const settled = document === editor.document;
752
754
  if (renderKey !== key || loadedSelection !== selectionKey) {
753
755
  mixer.stop();
754
756
  engine.invalidate();
755
- // Keep decoders warm: only a source whose runtime changed is reopened.
757
+ // Keep decoders warm by reopening only sources whose runtime changed.
756
758
  const reads = new Map(Object.values(document.assets).map((a) => [
757
759
  a.id,
758
760
  previewMedia(document, a.id),
@@ -772,8 +774,10 @@ export function createBrowserBridge(options) {
772
774
  reportRefusedFonts(refused, "preview");
773
775
  }
774
776
  engine.loadProject(compiled.project);
775
- // Frames render at the document's size times the preview scale, and the surfaces are that
776
- // size: the engine rounds it.
777
+ // A worker given up for one project is tried again for the next.
778
+ if (renderKey !== null && !workerPreview)
779
+ workerGivenUp = false;
780
+ // Frames and surfaces are the document size times the preview scale, rounded by the engine.
777
781
  let renderSize = engine.previewSize;
778
782
  engine.resize(renderSize[0], renderSize[1]);
779
783
  // Sources are fitted in document space; the render scales them.
@@ -786,14 +790,14 @@ export function createBrowserBridge(options) {
786
790
  ]
787
791
  .map((source) => [source.id, previewMedia(document, source.id)])
788
792
  .filter(([, asset]) => asset);
789
- // The worker keeps runtime assets it already holds; only new or changed ones are sent.
793
+ // The worker keeps assets it already holds; only new or changed ones are sent.
790
794
  const keep = used
791
795
  .filter(([id, asset]) => workerSent.get(id) === asset)
792
796
  .map(([id]) => id);
793
797
  const kept = new Set(keep);
794
798
  const workerAssets = used
795
799
  .filter(([id]) => !kept.has(id))
796
- // Keyed by the source it serves: a proxy's runtime has an ID of its own.
800
+ // Keyed by the source it serves, since a proxy's runtime has its own ID.
797
801
  .map(([id, asset]) => {
798
802
  const data = { id };
799
803
  for (const field of [
@@ -816,7 +820,7 @@ export function createBrowserBridge(options) {
816
820
  return data;
817
821
  });
818
822
  const sendFonts = !sameList(workerFonts, allFonts);
819
- // Until the worker confirms, what it holds is unknown: a failed load resends everything.
823
+ // Unknown until the worker confirms, so a failed load resends everything.
820
824
  workerSent = new Map();
821
825
  workerFonts = null;
822
826
  try {
@@ -859,19 +863,18 @@ export function createBrowserBridge(options) {
859
863
  }
860
864
  scheduleSweep();
861
865
  scheduleTextReports();
862
- // A drag changes the draft on every pointer move; the preview follows at most once a frame.
866
+ // Drags change the draft on every pointer move; follow at most once a frame.
863
867
  if (engine && !refreshFrame)
864
868
  refreshFrame = nextFrame(refresh);
865
869
  });
866
- /** The font stack each SVG runtime's report was last computed with. */
867
870
  const reportedFonts = new WeakMap();
868
- /** Aborted when the bridge is disposed: work it started for no caller (text reports) stops. */
871
+ /** Aborted on dispose, stopping work started for no caller (text reports). */
869
872
  const lifetime = new AbortController();
870
873
  let textReports = Promise.resolve(), textReportsQueued = false;
871
874
  /**
872
- * An SVG's report says which of its text no font draws (`missing_font`). Import probes it with no
873
- * fonts at all, so it is computed again with the stack its text draws with whenever that stack or
874
- * the SVG changes; `subscribeAssets` listeners hear of a report that changed.
875
+ * An SVG's report lists text no font draws (`missing_font`). Import probes with no fonts, so the
876
+ * report is recomputed whenever the SVG or its font stack changes, and `subscribeAssets` hears of
877
+ * changes.
875
878
  */
876
879
  function scheduleTextReports() {
877
880
  if (textReportsQueued || disposed)
@@ -928,7 +931,7 @@ export function createBrowserBridge(options) {
928
931
  notifyAssets();
929
932
  }
930
933
  let sweepQueued = false;
931
- /** Releases, after the preview work already queued, what no reachable document reads any more. */
934
+ /** Releases, after queued preview work, what no reachable document reads. */
932
935
  function scheduleSweep() {
933
936
  if (sweepQueued || disposed)
934
937
  return;
@@ -942,15 +945,15 @@ export function createBrowserBridge(options) {
942
945
  });
943
946
  }
944
947
  /**
945
- * Media and proxies stay held while any document the session can return to reads them: a relink
946
- * or import undone, or a removed asset, comes back with its runtime. Text is held only while the
947
- * document or the draft draws it, since its authoring makes it again. Work that leased a runtime
948
- * (an export, a native upload) keeps it until it releases the lease.
948
+ * Media and proxies stay held while any document the session can return to reads them, so undone
949
+ * imports, relinks and removals come back with their runtime. Text is held only while the
950
+ * document or draft draws it, since authoring recreates it. Leased runtimes (exports, native
951
+ * uploads) stay until released.
949
952
  */
950
953
  function sweep() {
951
954
  const media = new Set(), hashes = new Set(), seen = new Set();
952
955
  for (const document of editor.reachableDocuments()) {
953
- // Shared by commands that leave assets alone, so a long history is read once per media change.
956
+ // Commands that leave assets alone share them, so history is read once per media change.
954
957
  if (seen.has(document.assets))
955
958
  continue;
956
959
  seen.add(document.assets);
@@ -995,8 +998,8 @@ export function createBrowserBridge(options) {
995
998
  refreshPreview();
996
999
  return;
997
1000
  }
998
- // Playback reads the project it started with, so an edit restarts it from where it stood, at the
999
- // same rate, loop and policy, unless a seek, pause or Play comes first.
1001
+ // Playback reads the project it started with, so an edit restarts it from the same point, rate,
1002
+ // loop and policy, unless a seek, pause or Play comes first.
1000
1003
  const resume = playRequest;
1001
1004
  pause();
1002
1005
  refreshPreview();
@@ -1024,9 +1027,15 @@ export function createBrowserBridge(options) {
1024
1027
  }).catch(onError);
1025
1028
  }
1026
1029
  let previewIssue = null;
1027
- /** A lost GPU left no renderer and making it again failed; the next render tries again. */
1030
+ /** Sources the last frame showed through the browser's own tone mapping. */
1031
+ let degradedShown = [];
1032
+ /** Rebuilding after GPU loss failed; the next render retries. */
1028
1033
  let recoveryPending = false;
1029
- /** How many times a lost GPU's preview was made again. */
1034
+ /** The recovery rung to try next while `recoveryPending`. */
1035
+ let pendingStep = null;
1036
+ let previewLadder = new GpuRecoveryLadder();
1037
+ /** All recovery rungs failed; nothing draws until the preview is bound again. */
1038
+ let previewUnavailable = false;
1030
1039
  let previewRecoveries = 0;
1031
1040
  const previewListeners = new Set();
1032
1041
  const setPreviewIssue = (issue) => {
@@ -1037,13 +1046,13 @@ export function createBrowserBridge(options) {
1037
1046
  listener();
1038
1047
  };
1039
1048
  /**
1040
- * Renders the frame at `at`. A composition that cannot draw its output yet is not an error here:
1041
- * the previous frame stays up and `previewIssue` says why, until a render succeeds.
1049
+ * Renders the frame at `at`. A composition that cannot draw its output yet keeps the previous
1050
+ * frame up with `previewIssue` set, rather than failing.
1042
1051
  */
1043
1052
  async function renderAt(at, project, recovered = false) {
1044
1053
  try {
1045
- const rendered = await renderFrame(at, project);
1046
- setPreviewIssue(null);
1054
+ const rendered = await renderFrame(at, project, recovered);
1055
+ setPreviewIssue(degradedShown.length > 0 ? DEGRADED_PREVIEW_ISSUE : null);
1047
1056
  return rendered;
1048
1057
  }
1049
1058
  catch (error) {
@@ -1051,15 +1060,35 @@ export function createBrowserBridge(options) {
1051
1060
  setPreviewIssue(error.message ?? String(error));
1052
1061
  return false;
1053
1062
  }
1054
- const lost = error?.code === "GPU_DEVICE_LOST" || engine?.deviceLost === true;
1063
+ // A source the preview cannot draw fails every frame it is in; report it once with its own
1064
+ // code and keep the frame up.
1065
+ if (isSourceError(error)) {
1066
+ const issue = error.message ?? String(error);
1067
+ if (issue === previewIssue)
1068
+ return false;
1069
+ setPreviewIssue(issue);
1070
+ throw error;
1071
+ }
1072
+ const lost = error?.code === "GPU_DEVICE_LOST" ||
1073
+ error?.code === "GPU_DEVICE_HUNG" ||
1074
+ engine?.deviceLost === true;
1055
1075
  if (recovered || !lost || !boundCanvas || disposed)
1056
1076
  throw error;
1057
- if (!(await recoverPreview()))
1077
+ // The worker's report travels with its error; the main renderer reads its own.
1078
+ const report = error?.lossReport ??
1079
+ engine?.lossReport() ??
1080
+ lossReportFromJson(undefined, error?.message ?? String(error));
1081
+ // Every rebuild draws on a fresh internal canvas, so no rung needs the lost one.
1082
+ const step = previewLadder.onLoss(report, {
1083
+ kind: "none",
1084
+ webgpuAdapter: false,
1085
+ });
1086
+ if (!(await recoverPreview(step)))
1058
1087
  return false;
1059
1088
  return renderAt(at, await loaded(), true);
1060
1089
  }
1061
1090
  }
1062
- async function renderFrame(at, project) {
1091
+ async function renderFrame(at, project, recovered = false) {
1063
1092
  if (boundCanvas?.style)
1064
1093
  boundCanvas.style.visibility = hasContent(project) ? "visible" : "hidden";
1065
1094
  if (!hasContent(project))
@@ -1069,7 +1098,8 @@ export function createBrowserBridge(options) {
1069
1098
  const result = await workerPreview.seek(at);
1070
1099
  if (result.engineDiagnostics)
1071
1100
  workerDiagnostics = result.engineDiagnostics;
1072
- // An unchanged frame comes without a bitmap: the canvas still shows it.
1101
+ degradedShown = result.degradedSources ?? [];
1102
+ // Unchanged frames come without a bitmap; the canvas still shows them.
1073
1103
  if (result.bitmap) {
1074
1104
  boundCanvas
1075
1105
  .getContext("bitmaprenderer")
@@ -1079,26 +1109,32 @@ export function createBrowserBridge(options) {
1079
1109
  return result.rendered;
1080
1110
  }
1081
1111
  catch (error) {
1082
- if (error?.code === "INCOMPLETE_COMPOSITION")
1112
+ // Give up the worker only for its own faults; source errors would hit the main renderer
1113
+ // too. GPU loss goes to the recovery ladder, and a worker that loses it again on the
1114
+ // recovered frame is let go.
1115
+ if (!isWorkerFault(error) || (isGpuLoss(error) && !recovered))
1083
1116
  throw error;
1084
1117
  // The main renderer has the same project loaded and draws this frame instead.
1085
1118
  await abandonWorker(error);
1086
1119
  }
1087
1120
  }
1088
- const { rendered, unchanged } = await engine.render(at / 120000, {
1121
+ const { rendered, unchanged, degradedSources = [], } = await engine.render(at / 120000, {
1089
1122
  generation: engine.generation,
1090
1123
  context: context(project, library),
1091
1124
  });
1092
- // An unchanged frame was not presented: the bound canvas still shows the last copy.
1125
+ degradedShown = degradedSources;
1126
+ // Unchanged frames were not presented. Copy the frame instead of transferring the canvas:
1127
+ // Chrome on macOS crashes the page when an engine WebGL2 canvas gives up its buffer with
1128
+ // `transferToImageBitmap`.
1093
1129
  if (rendered && !unchanged && copySurface) {
1094
1130
  boundCanvas
1095
1131
  .getContext("bitmaprenderer")
1096
- .transferFromImageBitmap(engine.canvas.transferToImageBitmap());
1132
+ .transferFromImageBitmap(await createImageBitmap(engine.canvas));
1097
1133
  bitmapTransfers += 1;
1098
1134
  }
1099
1135
  return rendered;
1100
1136
  }
1101
- /** Gives the bound canvas the size frames render at, which `size` is, unless it has it. */
1137
+ /** Resizes the bound canvas to the render size if needed. */
1102
1138
  function sizeBoundCanvas(size) {
1103
1139
  if (!boundCanvas || !size)
1104
1140
  return;
@@ -1107,7 +1143,6 @@ export function createBrowserBridge(options) {
1107
1143
  if (boundCanvas.height !== size[1])
1108
1144
  boundCanvas.height = size[1];
1109
1145
  }
1110
- /** Applies the bridge's tracing to the renderers drawing now. */
1111
1146
  function applyTracing() {
1112
1147
  if (engine) {
1113
1148
  engine.traceUploads = traceUploads;
@@ -1118,12 +1153,34 @@ export function createBrowserBridge(options) {
1118
1153
  .catch(() => { });
1119
1154
  }
1120
1155
  /**
1121
- * Gives up the preview worker after `error`, whether it failed to start, to load a project or to
1122
- * draw: the main renderer, which loads every project the worker does, draws from then on, off
1123
- * screen, and each frame is copied to the bound surface (a canvas element or an OffscreenCanvas
1124
- * alike); a preview made again after a lost GPU does too, until the next binding. `onError` hears
1125
- * once why, unless the worker lost its GPU: that is recovered from, as the main renderer recovers
1126
- * from its own, without a report, and a preview made again tries a worker again.
1156
+ * Whether a preview worker draw `error` is the worker's fault: fatal (wasm trap, lost or hung
1157
+ * GPU), a codec its decoder refused (falls back to the main thread's media elements), or uncoded.
1158
+ * A source's own coded error is not.
1159
+ */
1160
+ function isWorkerFault(error) {
1161
+ const code = error?.code;
1162
+ return (error?.fatal === true ||
1163
+ typeof code !== "string" ||
1164
+ code === "worker_error" ||
1165
+ code === "unsupported_codec" ||
1166
+ code === "GPU_DEVICE_LOST" ||
1167
+ code === "GPU_DEVICE_HUNG");
1168
+ }
1169
+ /** Whether `error` says the GPU was lost or hung on its work. */
1170
+ function isGpuLoss(error) {
1171
+ return (error?.code === "GPU_DEVICE_LOST" || error?.code === "GPU_DEVICE_HUNG");
1172
+ }
1173
+ /** Whether `error` is a source's coded error, which a redraw would hit again. */
1174
+ function isSourceError(error) {
1175
+ return (!isWorkerFault(error) &&
1176
+ error?.code !== "INCOMPLETE_COMPOSITION" &&
1177
+ !String(error.code).startsWith("GPU_"));
1178
+ }
1179
+ /**
1180
+ * Gives up the preview worker after `error` (failed start, load or draw). Until the next binding
1181
+ * the main renderer, which loads every project the worker does, draws off screen and each frame
1182
+ * is copied to the bound surface. `onError` hears once why, unless the worker lost its GPU, which
1183
+ * recovers silently and lets a rebuilt preview try a worker again.
1127
1184
  */
1128
1185
  async function abandonWorker(error) {
1129
1186
  const failed = workerPreview;
@@ -1134,7 +1191,7 @@ export function createBrowserBridge(options) {
1134
1191
  workerFonts = null;
1135
1192
  copySurface = true;
1136
1193
  await failed.dispose().catch(() => { });
1137
- if (error?.code === "GPU_DEVICE_LOST")
1194
+ if (isGpuLoss(error))
1138
1195
  return;
1139
1196
  workerGivenUp = true;
1140
1197
  const reason = error instanceof Error ? error.message : String(error ?? "");
@@ -1151,7 +1208,7 @@ export function createBrowserBridge(options) {
1151
1208
  engine?.invalidate();
1152
1209
  mixer?.stop();
1153
1210
  const requested = tick;
1154
- // Only a newer seek supersedes this one: `loaded` reads the draft as it is when the task runs.
1211
+ // Only a newer seek supersedes this; `loaded` reads the draft when the task runs.
1155
1212
  return enqueue(async () => {
1156
1213
  if (requested !== tick)
1157
1214
  return false;
@@ -1177,7 +1234,7 @@ export function createBrowserBridge(options) {
1177
1234
  void workerPreview.cancel().catch(onError);
1178
1235
  }
1179
1236
  // An audio start that missed its deadline and has not settled. A context that never resumes
1180
- // (Firefox without usable output) or a stuck worklet would hold Play forever; video plays silent.
1237
+ // (Firefox without usable output) or a stuck worklet would block Play, so video plays silent.
1181
1238
  let stalledAudio = null;
1182
1239
  /** Whether `starting` settled within the deadline; a rejection propagates. */
1183
1240
  async function audioStarts(starting) {
@@ -1200,9 +1257,9 @@ export function createBrowserBridge(options) {
1200
1257
  return false;
1201
1258
  }
1202
1259
  /**
1203
- * Plays from the current time at `rate` (negative plays backwards) under a playback `policy`: the
1260
+ * Plays from the current time at `rate` (negative plays backwards) under playback `policy`; the
1204
1261
  * engine's clock decides which frame shows when and whether sound plays. Sound that cannot start
1205
- * in time is left out rather than holding the picture.
1262
+ * in time is dropped rather than holding the picture.
1206
1263
  */
1207
1264
  async function play(rate = 1, { loop = false, policy = "drop_video_keep_audio" } = {}) {
1208
1265
  if (!Number.isFinite(rate) || rate === 0)
@@ -1214,7 +1271,7 @@ export function createBrowserBridge(options) {
1214
1271
  let audible = (engine?.audible(policy, rate) ?? false) && stalledAudio === null;
1215
1272
  if (audible)
1216
1273
  audible = await audioStarts(mixer.resume());
1217
- // Plays the compiled projection preview shows, never a project the renderer loaded earlier.
1274
+ // Play the compiled projection preview shows, never a project the renderer loaded earlier.
1218
1275
  let project = null;
1219
1276
  await enqueue(async () => {
1220
1277
  if (!engine || generation !== playGeneration)
@@ -1237,13 +1294,13 @@ export function createBrowserBridge(options) {
1237
1294
  playing = true;
1238
1295
  playRequest = { rate, loop, policy };
1239
1296
  const clock = (playClock = engine.playbackClock(policy, project.settings.frame_rate, rate, tick, performance.now()));
1240
- // The tick last asked for, and for a policy that waits for frames, whether it has been shown.
1297
+ // The last requested tick and, for a policy that waits for frames, whether it was shown.
1241
1298
  let requested = null, presented = false;
1242
1299
  const step = (now) => {
1243
1300
  if (!playing || disposed || generation !== playGeneration)
1244
1301
  return;
1245
1302
  // At 1x under the default policy the audio clock leads while output consumes samples; the
1246
- // engine's clock falls back to the wall clock while it stands still.
1303
+ // engine falls back to the wall clock while it stands still.
1247
1304
  const heard = audible ? (mixer.tick ?? undefined) : undefined;
1248
1305
  const wanted = clock.step(now, heard, presented);
1249
1306
  tick = wanted.tick;
@@ -1266,9 +1323,8 @@ export function createBrowserBridge(options) {
1266
1323
  .catch(onError);
1267
1324
  return;
1268
1325
  }
1269
- // The clock asks for frame starts, so every policy asks for each frame once however often
1270
- // the display refreshes; a waiting policy also moves on only after it is shown, and the
1271
- // others let late frames go.
1326
+ // The clock requests frame starts, so each frame is asked for once at any refresh rate. A
1327
+ // waiting policy moves on only after the frame is shown; the others drop late frames.
1272
1328
  const due = requested !== tick;
1273
1329
  if (!due)
1274
1330
  skippedRequests += 1;
@@ -1300,9 +1356,8 @@ export function createBrowserBridge(options) {
1300
1356
  pause();
1301
1357
  };
1302
1358
  /**
1303
- * Makes the preview's renderer, audio, and worker for `canvas`, disposing what the last one made.
1304
- * Runs inside the render queue. Returns false when a later binding or disposal superseded
1305
- * `token`.
1359
+ * Makes the preview's renderer, audio and worker for `canvas`, disposing the previous ones. Runs
1360
+ * in the render queue. Returns false when a later binding or disposal superseded `token`.
1306
1361
  */
1307
1362
  async function buildPreview(canvas, token) {
1308
1363
  pause();
@@ -1314,7 +1369,7 @@ export function createBrowserBridge(options) {
1314
1369
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1315
1370
  });
1316
1371
  const { Engine } = await import("./runtime/engine.js");
1317
- // Until a project loads and gives the render size (see `loaded`).
1372
+ // Until a project loads and sets the render size (see `loaded`).
1318
1373
  canvas.width = editor.document.project.settings.width;
1319
1374
  canvas.height = editor.document.project.settings.height;
1320
1375
  boundCanvas = canvas;
@@ -1322,12 +1377,28 @@ export function createBrowserBridge(options) {
1322
1377
  await workerPreview?.dispose();
1323
1378
  workerPreview = null;
1324
1379
  workerDiagnostics = null;
1325
- const useWorker = features.worker.available && typeof canvas.getContext === "function";
1326
- engine = new Engine(useWorker ? new OffscreenCanvas(canvas.width, canvas.height) : canvas, sources, library, runtimeAssets,
1327
- // A frame shown at once matters more in a preview than the engine's conversion of it.
1328
- { unreadableFrames: "present" });
1329
- mixer = new EngineAudioMixer(runtimeAssets, { enabled: audio });
1380
+ // The main renderer draws on its own canvas and each frame is copied to the bound one, so a
1381
+ // renderer rebuilt after GPU loss (or the CPU renderer) needs nothing from the page.
1382
+ const copyable = typeof canvas.getContext === "function";
1383
+ const useWorker = features.worker.available && copyable;
1384
+ engine = new Engine(copyable ? new OffscreenCanvas(canvas.width, canvas.height) : canvas, sources, library, runtimeAssets,
1385
+ // In a preview, showing a frame at once matters more than the engine's conversion of it.
1386
+ {
1387
+ unreadableFrames: "present",
1388
+ videoConversion,
1389
+ opaqueEngineFrames,
1390
+ renderer: previewLadder.renderer === "cpu" ? "cpu" : rendererMode,
1391
+ });
1392
+ mixer = new EngineAudioMixer(runtimeAssets, {
1393
+ enabled: audio,
1394
+ onInterrupted: (state) => {
1395
+ if (playing)
1396
+ pause();
1397
+ onError(new EditorError("audio_unavailable", `Audio output was ${state} by the browser or the system; playback paused`, "play"));
1398
+ },
1399
+ });
1330
1400
  mixer.setMasterVolume(monitorVolume);
1401
+ mixer.setLatencyOffset(audioOffsetMs);
1331
1402
  stalledAudio = null;
1332
1403
  supplier = new AudioWindowSupplier(library);
1333
1404
  try {
@@ -1335,10 +1406,9 @@ export function createBrowserBridge(options) {
1335
1406
  engine.setPreviewScale(previewScale);
1336
1407
  capabilities = capabilityReport(engine.capabilityReport());
1337
1408
  await registerKeptEffects();
1338
- // The surface already shows copied frames (its context is a bitmap renderer's).
1339
- if (useWorker && workerGivenUp)
1340
- copySurface = true;
1341
- else if (useWorker) {
1409
+ // The worker posts frames to the same bitmap renderer, so copying stays on either way.
1410
+ copySurface = copyable;
1411
+ if (useWorker && !workerGivenUp) {
1342
1412
  const workerRuntime = {
1343
1413
  ...(runtimeAssets.wasmUrl
1344
1414
  ? { wasmUrl: String(runtimeAssets.wasmUrl) }
@@ -1352,12 +1422,16 @@ export function createBrowserBridge(options) {
1352
1422
  bitmapOutput: true,
1353
1423
  width: canvas.width,
1354
1424
  height: canvas.height,
1425
+ videoConversion,
1426
+ opaqueEngineFrames,
1427
+ // Match the main renderer: the CPU once recovery or `auto` moved there.
1428
+ renderer: onCpu() ? "cpu" : rendererMode,
1355
1429
  });
1356
1430
  // A worker that cannot start leaves the surface to the main renderer.
1357
1431
  try {
1358
1432
  await workerPreview.ready;
1359
1433
  await workerPreview.setPreviewScale(previewScale);
1360
- if (effectDefinitions.size)
1434
+ if (effectDefinitions.size && !onCpu())
1361
1435
  await workerPreview.registerEffects(keptEffects());
1362
1436
  }
1363
1437
  catch (error) {
@@ -1387,27 +1461,44 @@ export function createBrowserBridge(options) {
1387
1461
  return true;
1388
1462
  }
1389
1463
  /**
1390
- * A lost GPU (a WebGPU device, a WebGL context) is recovered here rather than reported: the
1391
- * preview is made again on the same canvas, as binding it did, and the frame drawn once more. The
1392
- * binding waits for the browser to restore a WebGL context on that canvas. When that fails the
1393
- * error is reported and the next render tries again.
1464
+ * Recovers a lost GPU (WebGPU device or WebGL context) silently: the preview is rebuilt on fresh
1465
+ * internal canvases with the renderer `step` names (the binding's `GpuRecoveryLadder` picks the
1466
+ * GPU again after a first external loss, the CPU after a self-caused loss or a second page loss),
1467
+ * and the frame is redrawn. A failed rung moves down the ladder; with none left the preview is
1468
+ * unavailable for this binding, reported once (`preview_unavailable`).
1394
1469
  *
1395
- * Since nothing is reported, what the user sees goes on: playback that was running plays on from
1396
- * where it stood, at the same rate, loop and policy, once the preview is made again, unless a
1397
- * seek, a pause or another Play came first. Sound that had not started in time is not waited for
1398
- * again: the audio output is not what was lost.
1470
+ * Running playback resumes from the same point, rate, loop and policy once rebuilt, unless a
1471
+ * seek, pause or Play came first. Sound that missed its start deadline is not waited for again.
1399
1472
  */
1400
- async function recoverPreview() {
1473
+ async function recoverPreview(step) {
1401
1474
  recoveryPending = true;
1475
+ pendingStep = step;
1402
1476
  const resume = playing ? playRequest : null;
1403
1477
  const stalled = stalledAudio;
1404
- if (!(await buildPreview(boundCanvas, binding)))
1405
- return false;
1478
+ for (;;) {
1479
+ try {
1480
+ if (!(await buildPreview(boundCanvas, binding)))
1481
+ return false;
1482
+ break;
1483
+ }
1484
+ catch (error) {
1485
+ const next = previewLadder.onRecoveryFailed(pendingStep, error);
1486
+ if (next !== "terminal") {
1487
+ pendingStep = next;
1488
+ continue;
1489
+ }
1490
+ recoveryPending = false;
1491
+ previewUnavailable = true;
1492
+ onError(new EditorError("preview_unavailable", `The GPU was lost and no renderer could be made again (${error instanceof Error ? error.message : String(error)}); bind the preview again to retry`, "preview", undefined, false, { cause: error }));
1493
+ return false;
1494
+ }
1495
+ }
1406
1496
  stalledAudio = stalled;
1407
1497
  recoveryPending = false;
1498
+ pendingStep = null;
1408
1499
  previewRecoveries += 1;
1409
1500
  if (resume) {
1410
- // Queued behind the render that is recovering, which draws the frame first.
1501
+ // Queued behind the recovering render, which draws the frame first.
1411
1502
  const stopped = playGeneration;
1412
1503
  void Promise.resolve()
1413
1504
  .then(() => disposed || playing || playGeneration !== stopped
@@ -1417,9 +1508,23 @@ export function createBrowserBridge(options) {
1417
1508
  }
1418
1509
  return true;
1419
1510
  }
1511
+ /** Whether the main renderer draws on the CPU, where runtime effects are refused. */
1512
+ function onCpu() {
1513
+ return engine?.rendererChoice?.renderer === "cpu";
1514
+ }
1515
+ /** Runtime effects already reported as refused by the CPU renderer, by `id@version`. */
1516
+ const cpuRefusedEffects = new Set();
1517
+ function reportCpuEffects(keys) {
1518
+ for (const key of keys) {
1519
+ if (cpuRefusedEffects.has(key))
1520
+ continue;
1521
+ cpuRefusedEffects.add(key);
1522
+ onError(new EditorError("effect_unavailable", `Effect ${key} is not drawn: the preview renders on the CPU (${engine?.rendererChoice?.rendererReason ?? "no GPU"}), which runs no runtime effect`, "effects", key));
1523
+ }
1524
+ }
1420
1525
  /**
1421
- * Runtime effects `registerEffects` kept, by `id@version`, with their JSON text, in the order they
1422
- * came: every renderer the bridge makes registers them.
1526
+ * Effects `registerEffects` kept, by `id@version`, with their JSON text in arrival order. Every
1527
+ * renderer the bridge makes registers them.
1423
1528
  */
1424
1529
  const effectDefinitions = new Map();
1425
1530
  const keptEffects = () => [...effectDefinitions.values()].map(({ definition }) => definition);
@@ -1442,6 +1547,13 @@ export function createBrowserBridge(options) {
1442
1547
  if (!added.size)
1443
1548
  return;
1444
1549
  const fresh = [...added.values()].map(({ definition }) => definition);
1550
+ if (onCpu()) {
1551
+ // Kept for a GPU preview or export even though the current CPU renderer refuses them.
1552
+ for (const [key, entry] of added)
1553
+ effectDefinitions.set(key, entry);
1554
+ reportCpuEffects([...added.keys()]);
1555
+ return;
1556
+ }
1445
1557
  // The main renderer loads every project the worker does, so both hold every effect.
1446
1558
  if (engine)
1447
1559
  await engine.registerEffects(fresh);
@@ -1456,18 +1568,22 @@ export function createBrowserBridge(options) {
1456
1568
  }
1457
1569
  for (const [key, entry] of added)
1458
1570
  effectDefinitions.set(key, entry);
1459
- // A frame that drew one of them failed; it draws now.
1571
+ // A frame that used one of them failed; redraw it.
1460
1572
  if (engine)
1461
1573
  refreshPreview();
1462
1574
  });
1463
1575
  }
1464
1576
  /**
1465
- * Registers the kept runtime effects on the main renderer `buildPreview` just started, one by
1466
- * one: one its device refuses (kept while no preview was bound, so never compiled) is dropped and
1467
- * reported, and the others draw. A device lost meanwhile drops none: the next render makes the
1468
- * preview again, which registers them again.
1577
+ * Registers kept effects on the main renderer `buildPreview` just started, one at a time. One its
1578
+ * device refuses (kept unbound, so never compiled) is dropped and reported. A device lost
1579
+ * meanwhile drops none, since the next render rebuilds and re-registers. On the CPU renderer none
1580
+ * is dropped (a later GPU preview or export runs them) and each is reported once.
1469
1581
  */
1470
1582
  async function registerKeptEffects() {
1583
+ if (onCpu()) {
1584
+ reportCpuEffects([...effectDefinitions.keys()]);
1585
+ return;
1586
+ }
1471
1587
  const kept = [...effectDefinitions];
1472
1588
  const results = await Promise.allSettled(kept.map(([, { definition }]) => engine.registerEffects([definition])));
1473
1589
  if (engine.deviceLost)
@@ -1479,18 +1595,14 @@ export function createBrowserBridge(options) {
1479
1595
  onError(result.reason);
1480
1596
  }
1481
1597
  }
1482
- /** Whether a renderer is ready, making it again first if a lost GPU left none. */
1598
+ /** Whether a renderer is ready, rebuilding it first if GPU loss left none. */
1483
1599
  async function previewReady() {
1484
1600
  if (engine)
1485
1601
  return true;
1486
- if (!recoveryPending || !boundCanvas || disposed)
1602
+ if (previewUnavailable || !recoveryPending || !boundCanvas || disposed)
1487
1603
  return false;
1488
- return recoverPreview();
1604
+ return recoverPreview(pendingStep);
1489
1605
  }
1490
- /**
1491
- * Renders the preview at `scale` times the document's size from now on, sizing the surfaces to
1492
- * it, and draws the current frame again. Resolves once that frame is drawn.
1493
- */
1494
1606
  async function setPreviewScale(scale) {
1495
1607
  const next = checkedPreviewScale(scale);
1496
1608
  if (next === previewScale)
@@ -1521,6 +1633,9 @@ export function createBrowserBridge(options) {
1521
1633
  const token = ++binding;
1522
1634
  await enqueue(async () => {
1523
1635
  recoveryPending = false;
1636
+ pendingStep = null;
1637
+ previewLadder = new GpuRecoveryLadder();
1638
+ previewUnavailable = false;
1524
1639
  workerGivenUp = false;
1525
1640
  skippedRequests = 0;
1526
1641
  bitmapTransfers = 0;
@@ -1573,14 +1688,12 @@ export function createBrowserBridge(options) {
1573
1688
  stage: (signal) => mediaAdapter.stage(file, signal),
1574
1689
  })), options);
1575
1690
  }
1576
- /** Imports numbered PNGs as one image sequence at `frameRate` (the project's by default). */
1577
1691
  function importSequence(files, { frameRate, missing = "reject", signal } = {}) {
1578
1692
  const rate = frameRate ?? editor.document.project.settings.frame_rate;
1579
1693
  return importUnits([sequenceUnit(files, { frameRate: rate, missing })], {
1580
1694
  signal,
1581
1695
  });
1582
1696
  }
1583
- /** Relinks the image sequence `id` to `files`, staged as the project recorded it. */
1584
1697
  function relinkSequence(id, files, { signal } = {}) {
1585
1698
  const provider = editor.document.project.sources.find((source) => source.id === id)?.provider;
1586
1699
  if (provider?.format !== "image_sequence")
@@ -1601,6 +1714,10 @@ export function createBrowserBridge(options) {
1601
1714
  stage: (signal) => mediaAdapter.stageSequence(files, options, signal),
1602
1715
  };
1603
1716
  }
1717
+ /**
1718
+ * Stages `units` (at most {@link IMPORT_STAGE_CONCURRENCY} at once) and adds them to the document
1719
+ * in order as one undo step. A relink has exactly one unit.
1720
+ */
1604
1721
  async function importUnits(units, { signal, relinkId } = {}) {
1605
1722
  if (disposed)
1606
1723
  throw new EditorError("disposed", "Bridge is disposed", "import");
@@ -1610,22 +1727,42 @@ export function createBrowserBridge(options) {
1610
1727
  signal?.addEventListener("abort", abort, { once: true });
1611
1728
  if (signal?.aborted)
1612
1729
  abort();
1613
- const staged = [], leases = [], commands = [];
1730
+ // Index `i` is unit `i`'s staged asset; a unit never started leaves its slot empty.
1731
+ const staged = new Array(units.length), leases = [], commands = [];
1614
1732
  try {
1615
1733
  if (relinkId && units.length !== 1)
1616
1734
  throw new EditorError("relink_conflict", "Relink accepts exactly one file", "relink", relinkId);
1617
- for (const unit of units) {
1618
- const item = await unit.stage(controller.signal);
1735
+ // Staged together, committed in order. The first failure stops the rest and is reported as
1736
+ // the import's error, not the cancellation the others then see.
1737
+ let failure = null;
1738
+ let next = 0;
1739
+ const stageNext = async () => {
1740
+ while (next < units.length && failure === null) {
1741
+ const index = next++;
1742
+ try {
1743
+ staged[index] = await units[index].stage(controller.signal);
1744
+ }
1745
+ catch (error) {
1746
+ failure ??= { error };
1747
+ controller.abort(error);
1748
+ }
1749
+ }
1750
+ };
1751
+ const limit = Math.max(1, Math.min(IMPORT_STAGE_CONCURRENCY, (globalThis.navigator?.hardwareConcurrency ?? 2) - 1));
1752
+ await Promise.all(Array.from({ length: Math.min(limit, units.length) }, stageNext));
1753
+ if (failure)
1754
+ throw failure.error;
1755
+ for (const [index, unit] of units.entries()) {
1756
+ const item = staged[index];
1619
1757
  const fileName = unit.name ?? item.name ?? item.runtime.name;
1620
- staged.push(item);
1621
1758
  controller.signal.throwIfAborted();
1622
1759
  if (disposed || editor.disposed || editor.generation !== generation)
1623
1760
  throw new EditorError("stale_import", "Project changed during import", "import");
1624
1761
  const old = relinkId ? editor.document.assets[relinkId] : null;
1625
1762
  if (relinkId && !old)
1626
1763
  throw new EditorError("missing_asset", "Unknown relink target", "relink", relinkId);
1627
- // The engine decides whether the file is the recorded media: equal hashes match whatever else
1628
- // differs; without them any differing recorded part means other media.
1764
+ // Equal hashes match whatever else differs; without them any differing recorded part means
1765
+ // other media.
1629
1766
  if (old?.fingerprint && item.fingerprint) {
1630
1767
  const match = compareFingerprints(await decisions(), old.fingerprint, item.fingerprint);
1631
1768
  if (match.kind === "mismatch")
@@ -1636,9 +1773,9 @@ export function createBrowserBridge(options) {
1636
1773
  if (old && old.kind !== item.runtime.kind)
1637
1774
  throw new EditorError("relink_conflict", "Media kind differs", "relink", relinkId);
1638
1775
  const id = relinkId ?? item.runtime.id;
1639
- // Above every revision this bridge issued: after an undo the next one may be an undone relink's.
1776
+ // Above every revision issued, since after an undo the next may match an undone relink's.
1640
1777
  const contentRevision = issue(id, (old?.contentRevision ?? -1) + 1);
1641
- // A relink reads the same media, so it opens as the project chose, not as a fresh import would.
1778
+ // A relink opens as the project chose, not as a fresh import would.
1642
1779
  const provider = relinkId
1643
1780
  ? keepProviderChoices(editor.document.project.sources.find((s) => s.id === relinkId)
1644
1781
  ?.provider, item.runtime.provider, item.runtime.report)
@@ -1661,7 +1798,7 @@ export function createBrowserBridge(options) {
1661
1798
  ...(item.fingerprint ? { fingerprint: item.fingerprint } : {}),
1662
1799
  authoring,
1663
1800
  };
1664
- // Called as a method: an adapter's staged asset may be a class instance.
1801
+ // Call as a method, since a staged asset may be a class instance.
1665
1802
  const lease = registry.put(id, contentRevision, runtime, () => item.dispose());
1666
1803
  leases.push({ id, contentRevision, lease });
1667
1804
  commands.push({
@@ -1704,7 +1841,7 @@ export function createBrowserBridge(options) {
1704
1841
  entry.lease.release();
1705
1842
  }
1706
1843
  for (const item of staged.slice(leases.length))
1707
- item.dispose();
1844
+ item?.dispose();
1708
1845
  throw error;
1709
1846
  }
1710
1847
  finally {
@@ -1712,14 +1849,11 @@ export function createBrowserBridge(options) {
1712
1849
  signal?.removeEventListener("abort", abort);
1713
1850
  }
1714
1851
  }
1715
- /**
1716
- * The proxy conversion running: `preempt` stops it for an export, and `done` settles when it
1717
- * ends.
1718
- */
1852
+ /** The running proxy conversion: `preempt` stops it for an export, `done` settles at its end. */
1719
1853
  let proxyRun = null;
1720
1854
  /**
1721
- * Waits until no export runs and no other proxy is being made, or `signal` aborts, and takes the
1722
- * turn: `signal` aborts when an export takes its place, and `end()` gives the turn back.
1855
+ * Waits until no export or other proxy runs (or `signal` aborts) and takes the turn. `signal`
1856
+ * aborts when an export preempts it, and `end()` gives the turn back.
1723
1857
  */
1724
1858
  async function proxyTurn(signal) {
1725
1859
  for (;;) {
@@ -1746,6 +1880,23 @@ export function createBrowserBridge(options) {
1746
1880
  },
1747
1881
  };
1748
1882
  }
1883
+ /**
1884
+ * Refuses an export up front when it shows a source imported for a degraded preview: the engine
1885
+ * would refuse its first frame, and browser tone mapping must not reach a file.
1886
+ */
1887
+ function refuseDegradedSources(document, project, used) {
1888
+ const degraded = project.sources
1889
+ .filter((source) => used.has(source.id) &&
1890
+ originalOf(document, source.id)?.planarDecode === "unavailable")
1891
+ .map((source) => document.assets[source.id]?.name ?? source.id);
1892
+ if (degraded.length === 0)
1893
+ return;
1894
+ const facts = { kind: "video", codec: null, softwareDecoder: "none" };
1895
+ const names = degraded.join(", ");
1896
+ throw new EditorError("unsupported_media", `This browser cannot export ${names}: it decodes this HDR video only to frames the engine cannot read, so the preview shows it with the browser's tone mapping. Export with the native host.`, "export", undefined, true, {
1897
+ cause: new PlanarDecodeUnavailableError(`${names}: no planar decode in this browser`, facts),
1898
+ });
1899
+ }
1749
1900
  let sweptExports = false;
1750
1901
  /** Settles when the running export does. */
1751
1902
  let exportSettled = Promise.resolve();
@@ -1754,7 +1905,7 @@ export function createBrowserBridge(options) {
1754
1905
  throw new EditorError("disposed", "Bridge is disposed", "export");
1755
1906
  if (!sweptExports) {
1756
1907
  sweptExports = true;
1757
- // Temporary files a closed page left: a day old at least and held by no page.
1908
+ // Temporary files closed pages left behind, at least a day old and held by no page.
1758
1909
  void import("./runtime/output.js").then(({ sweepStaleExports }) => sweepStaleExports());
1759
1910
  }
1760
1911
  if (jobs.size)
@@ -1763,6 +1914,7 @@ export function createBrowserBridge(options) {
1763
1914
  const videoDecode = options.videoDecode ?? "auto";
1764
1915
  if (videoDecode !== "auto" && videoDecode !== "software")
1765
1916
  throw new EditorError("invalid_video_decode", `Export videoDecode must be "auto" or "software"; received ${JSON.stringify(videoDecode)}`, "export");
1917
+ const exportConversion = checkedVideoConversion(options.videoConversion ?? videoConversion, "export");
1766
1918
  materializeText(editor.document);
1767
1919
  const snapshot = editor.document, revision = editor.revision, effects = keptEffects();
1768
1920
  const compiled = compileEditorDocument(snapshot);
@@ -1773,6 +1925,7 @@ export function createBrowserBridge(options) {
1773
1925
  const held = [], map = new Map(), fontStack = [];
1774
1926
  const used = shownSources(compiled.project);
1775
1927
  const drawnResources = drawnEffectResources(compiled.project);
1928
+ refuseDegradedSources(snapshot, compiled.project, used);
1776
1929
  try {
1777
1930
  for (const source of [
1778
1931
  ...compiled.project.sources.filter((s) => used.has(s.id)),
@@ -1810,7 +1963,11 @@ export function createBrowserBridge(options) {
1810
1963
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1811
1964
  videoDecode,
1812
1965
  });
1813
- const renderer = new Engine(new OffscreenCanvas(project.settings.width, project.settings.height), pixels, lib, runtimeAssets);
1966
+ // The retry policy picks the renderer: CPU after a self-caused loss or a second page loss.
1967
+ const renderer = new Engine(new OffscreenCanvas(project.settings.width, project.settings.height), pixels, lib, runtimeAssets, {
1968
+ videoConversion: exportConversion,
1969
+ renderer: attempt.renderer === "cpu" ? "cpu" : rendererMode,
1970
+ });
1814
1971
  const audio = new AudioWindowSupplier(lib);
1815
1972
  try {
1816
1973
  signal.throwIfAborted();
@@ -1820,7 +1977,7 @@ export function createBrowserBridge(options) {
1820
1977
  signal.throwIfAborted();
1821
1978
  renderer.loadProject(project, "export");
1822
1979
  const refused = renderer.setCaptionFonts(fontStack);
1823
- // Heard once per job, not once per attempt.
1980
+ // Reported once per job, not per attempt.
1824
1981
  if (!fontsReported)
1825
1982
  reportRefusedFonts(refused, "export");
1826
1983
  fontsReported = true;
@@ -1867,6 +2024,10 @@ export function createBrowserBridge(options) {
1867
2024
  supplyFrame: (seconds) => renderer.supply(seconds, { context: context(project, lib) }),
1868
2025
  renderFrame: () => renderer.beginExportFrame(),
1869
2026
  sourceTransfer: () => renderer.sourceTransfer,
2027
+ videoEncoder: attempt.videoEncoder,
2028
+ onSoftwareEncoder: (available) => {
2029
+ retryPolicy.softwareVideoEncoder = available;
2030
+ },
1870
2031
  });
1871
2032
  progress({ phase: "publishing", fraction: 0.99 });
1872
2033
  let artifact;
@@ -1884,10 +2045,18 @@ export function createBrowserBridge(options) {
1884
2045
  report: {
1885
2046
  ...result,
1886
2047
  videoDecode,
2048
+ videoConversion: exportConversion,
1887
2049
  decodeFallbacks: pixels.decodeFallbacks,
2050
+ renderer: renderer.rendererChoice,
1888
2051
  },
1889
2052
  };
1890
2053
  }
2054
+ catch (error) {
2055
+ // Count this loss for the page too; the next attempt's policy reads it.
2056
+ if (renderer.deviceLost)
2057
+ pageGpuLosses.add();
2058
+ throw error;
2059
+ }
1891
2060
  finally {
1892
2061
  await audio.close();
1893
2062
  await renderer.dispose();
@@ -1895,19 +2064,21 @@ export function createBrowserBridge(options) {
1895
2064
  }
1896
2065
  },
1897
2066
  };
2067
+ // The CPU renderer runs no runtime effects, so only exports without them can move there.
2068
+ const retryPolicy = { cpuRenderer: effects.length === 0 };
1898
2069
  const job = new ExportJob(revision, snapshot, backend, () => {
1899
2070
  held.forEach((l) => l.release());
1900
2071
  jobs.delete(job);
1901
- });
2072
+ }, { retry: retryPolicy });
1902
2073
  jobs.add(job);
1903
2074
  exportSettled = job.result.then(() => { }, () => { });
1904
- // A proxy being made yields (encoder, GPU, memory) and is made again once the export ends.
2075
+ // A proxy being made yields the encoder, GPU and memory, and restarts after the export.
1905
2076
  proxyRun?.preempt.abort(new DOMException("An export takes the proxy's place", "AbortError"));
1906
2077
  return job;
1907
2078
  }
1908
2079
  /**
1909
- * What an export of `snapshot` reads for each source, as the engine selects it: originals, unless
1910
- * `options.media` asks for proxies. Refuses before anything is held when the media is not ready.
2080
+ * What an export reads for each source, as the engine selects it: originals unless
2081
+ * `options.media` asks for proxies. Refuses before holding anything when the media is not ready.
1911
2082
  */
1912
2083
  function exportSelection(snapshot, project, options) {
1913
2084
  if (!decisionBinding)
@@ -1968,10 +2139,6 @@ export function createBrowserBridge(options) {
1968
2139
  relink: (id, file, options) => importFiles([file], { ...options, relinkId: id }),
1969
2140
  importSequence,
1970
2141
  relinkSequence,
1971
- /**
1972
- * Shows another animation of a package source (a dotLottie's), keeping its clips: an undoable
1973
- * document change.
1974
- */
1975
2142
  selectAnimation(id, animation) {
1976
2143
  const descriptor = editor.document.assets[id];
1977
2144
  const source = editor.document.project.sources.find((candidate) => candidate.id === id);
@@ -2015,11 +2182,11 @@ export function createBrowserBridge(options) {
2015
2182
  startExport,
2016
2183
  async importCaptions(file) {
2017
2184
  const generation = editor.generation;
2018
- // A larger file holds more cues than a project can, so it is not read at all.
2185
+ // A larger file holds more cues than a project can, so refuse it unread.
2019
2186
  if (file.size > MAX_CAPTION_FILE_BYTES)
2020
2187
  throw new EditorError("invalid_captions", `${file.name} is ${file.size} bytes; a subtitle file is read up to ${MAX_CAPTION_FILE_BYTES}`, "import");
2021
2188
  const { parseCaptions } = await loadWasm();
2022
- const text = await file.text();
2189
+ const text = await readUserText(file);
2023
2190
  let imported;
2024
2191
  try {
2025
2192
  imported = JSON.parse(parseCaptions(text, /\.vtt$/i.test(file.name) ? "webvtt" : "srt"));
@@ -2060,14 +2227,10 @@ export function createBrowserBridge(options) {
2060
2227
  },
2061
2228
  async measureLayout(generator, time = 0) {
2062
2229
  const { width, height } = await draftMeasurer();
2063
- // Measured at the canvas size, which its pixel lengths are pixels of.
2230
+ // Measured at the canvas size, whose pixels its lengths are in.
2064
2231
  return JSON.parse(measurer.measureLayout(JSON.stringify(generator), width, height, time, width, height));
2065
2232
  },
2066
2233
  conform,
2067
- /**
2068
- * Makes a proxy of a source whose original this session holds, keeps it, and previews from it
2069
- * wherever the original goes offline, or while preview prefers proxies.
2070
- */
2071
2234
  async generateProxy(id, { signal } = {}) {
2072
2235
  const descriptor = editor.document.assets[id];
2073
2236
  // No single video file for the proxy maker to read.
@@ -2085,12 +2248,12 @@ export function createBrowserBridge(options) {
2085
2248
  let hold = null;
2086
2249
  try {
2087
2250
  for (;;) {
2088
- // One proxy at a time, none while an export runs; an export that starts takes its place.
2251
+ // One proxy at a time and none during an export; a starting export preempts it.
2089
2252
  const turn = await proxyTurn(signal);
2090
2253
  try {
2091
- // Held until its runtime is let go, so no page removes it meanwhile.
2254
+ // Held until its runtime is released so no page removes it meanwhile.
2092
2255
  hold = await proxyStore.hold(hash);
2093
- // Listeners hear each whole percent once.
2256
+ // Notify listeners once per whole percent.
2094
2257
  let percent = 0;
2095
2258
  const found = await proxyStore.generate(runtime.file, descriptor.fingerprint, {
2096
2259
  signal: signal
@@ -2128,15 +2291,10 @@ export function createBrowserBridge(options) {
2128
2291
  proxyJobs.delete(id);
2129
2292
  notifyAssets();
2130
2293
  }
2131
- // The next load asks the engine again. Playback is left alone: every source it reads is online.
2294
+ // The next load asks the engine again. Playback reads only online sources, so leave it alone.
2132
2295
  if (engine && !playing)
2133
2296
  refreshPreview();
2134
2297
  },
2135
- /**
2136
- * Shows node `nodeId` of composition `compositionId` in the viewer instead of the composition's
2137
- * output, rendered by the same engine compiler; `null` shows the outputs again. Preview only:
2138
- * the document and export are unchanged.
2139
- */
2140
2298
  setPreviewOutput(target) {
2141
2299
  const next = target
2142
2300
  ? { compositionId: target.compositionId, nodeId: target.nodeId }
@@ -2151,11 +2309,6 @@ export function createBrowserBridge(options) {
2151
2309
  get previewOutput() {
2152
2310
  return previewOutput;
2153
2311
  },
2154
- /**
2155
- * Makes preview read a fresh proxy wherever a source has one (`proxies`), or the original
2156
- * wherever it is online (`original`, the default). Preview only: an export reads what its own
2157
- * `media` says.
2158
- */
2159
2312
  setPreviewMedia(media) {
2160
2313
  if (media !== "original" && media !== "proxies")
2161
2314
  throw Error("Preview media must be original or proxies");
@@ -2170,10 +2323,6 @@ export function createBrowserBridge(options) {
2170
2323
  return preferredPreviewMedia;
2171
2324
  },
2172
2325
  hasOriginal: (id) => !!originalOf(editor.document, id),
2173
- /**
2174
- * Which video codecs this browser encodes for an export of the current document at
2175
- * `videoQuality`: the question an export asks before it opens its encoder.
2176
- */
2177
2326
  async videoEncoders({ videoQuality } = {}) {
2178
2327
  await decisions();
2179
2328
  const { probeEncoders } = await import("./runtime/exporter.js");
@@ -2183,7 +2332,6 @@ export function createBrowserBridge(options) {
2183
2332
  videoQuality,
2184
2333
  });
2185
2334
  },
2186
- /** Whether a source has a kept proxy, and the progress of one being made. */
2187
2335
  proxyStatus(id) {
2188
2336
  const descriptor = editor.document.assets[id];
2189
2337
  const hash = hashOf(descriptor);
@@ -2193,17 +2341,7 @@ export function createBrowserBridge(options) {
2193
2341
  reading: previewSelection.get(id)?.media ?? "original",
2194
2342
  };
2195
2343
  },
2196
- /**
2197
- * The proxies this browser keeps, for every project: each original's hash and the bytes its
2198
- * proxy takes.
2199
- */
2200
2344
  listProxies: () => proxyStore.list(),
2201
- /**
2202
- * Removes the kept proxies of `hashes`. This session lets go of its own first and refreshes the
2203
- * preview; a proxy still read after that (by the preview, for a source whose original is
2204
- * offline, by an export of this session, or by another page of the origin) is left and listed
2205
- * in `inUse`.
2206
- */
2207
2345
  async removeProxies(hashes) {
2208
2346
  const wanted = new Set(hashes);
2209
2347
  const unlocked = [];
@@ -2228,7 +2366,7 @@ export function createBrowserBridge(options) {
2228
2366
  throw compiled.diagnostics[0];
2229
2367
  await discoverProxies(snapshot);
2230
2368
  await decisions();
2231
- // Leased after the waits and before the next, so no release can come between.
2369
+ // Leased after the waits and before the next await, so no release can come between.
2232
2370
  materializeText(snapshot);
2233
2371
  requireShownText(snapshot, compiled.project);
2234
2372
  const selection = exportSelection(snapshot, compiled.project, options);
@@ -2249,7 +2387,7 @@ export function createBrowserBridge(options) {
2249
2387
  : acquireOwned(snapshot, asset);
2250
2388
  held.push(lease);
2251
2389
  const runtime = lease.value;
2252
- // An image sequence is its frames' files, each uploaded under its locator.
2390
+ // An image sequence uploads each frame file under its locator.
2253
2391
  if (!proxied && runtime.frameFiles) {
2254
2392
  for (const [locator, file] of runtime.frameFiles)
2255
2393
  result.push({
@@ -2321,13 +2459,22 @@ export function createBrowserBridge(options) {
2321
2459
  setMonitorVolume(value) {
2322
2460
  if (!Number.isFinite(value) || value < 0 || value > 1)
2323
2461
  throw Error("Monitor volume must be between 0 and 1");
2324
- // The bridge's, not one mixer's: each preview binding's mixer starts at it.
2462
+ // Bridge-wide: each preview binding's mixer starts at it.
2325
2463
  monitorVolume = value;
2326
2464
  mixer?.setMasterVolume(value);
2327
2465
  },
2328
2466
  get monitorVolume() {
2329
2467
  return monitorVolume;
2330
2468
  },
2469
+ setAudioOffset(ms) {
2470
+ if (!Number.isFinite(ms) || Math.abs(ms) > 2000)
2471
+ throw Error("Audio offset must be between -2000 and 2000 ms");
2472
+ audioOffsetMs = ms;
2473
+ mixer?.setLatencyOffset(ms);
2474
+ },
2475
+ get audioOffsetMs() {
2476
+ return audioOffsetMs;
2477
+ },
2331
2478
  setTraceUploads(value) {
2332
2479
  traceUploads = value === true;
2333
2480
  applyTracing();
@@ -2341,7 +2488,7 @@ export function createBrowserBridge(options) {
2341
2488
  },
2342
2489
  setPreviewScale,
2343
2490
  get diagnostics() {
2344
- // The renderer that draws: in worker mode the main-thread one does not.
2491
+ // The renderer that draws; in worker mode the main-thread one does not.
2345
2492
  const snapshot = workerPreview
2346
2493
  ? workerDiagnostics
2347
2494
  : (engine?.lastDiagnostics ?? null);
@@ -2354,6 +2501,7 @@ export function createBrowserBridge(options) {
2354
2501
  skippedRequests,
2355
2502
  bitmapTransfers,
2356
2503
  previewScale,
2504
+ audioLatencySource: mixer?.latencySource ?? null,
2357
2505
  },
2358
2506
  };
2359
2507
  },
@@ -2387,30 +2535,28 @@ export function createBrowserBridge(options) {
2387
2535
  return engine?.catalog ?? null;
2388
2536
  },
2389
2537
  registerEffects,
2390
- // A source's own media while it is online, whichever preview reads: its size, file and peaks
2391
- // are the original's.
2538
+ // A source's own media while online, whichever preview reads, so size, file and peaks are the
2539
+ // original's.
2392
2540
  getAsset: (id) => (preferredPreviewMedia === "proxies" &&
2393
2541
  sourceView(editor.draft, id, originalOf(editor.draft, id))) ||
2394
2542
  library.get(id),
2395
2543
  };
2396
2544
  }
2397
- /**
2398
- * `scale` as a preview resolution scale: finite, above 0 and at most 8, as the engine's quality
2399
- * profile takes it.
2400
- */
2545
+ /** `scale` checked as a preview resolution scale: finite, above 0 and at most 8. */
2401
2546
  function checkedPreviewScale(scale) {
2402
2547
  if (typeof scale !== "number" || !(scale > 0 && scale <= 8))
2403
2548
  throw new EditorError("invalid_preview_scale", "The preview scale must be a number above 0 and at most 8", "preview");
2404
2549
  return scale;
2405
2550
  }
2406
- /**
2407
- * Whether the engine draws a source itself, so no file backs it: a generated source or a
2408
- * composition.
2409
- */
2551
+ function checkedVideoConversion(value, operation) {
2552
+ if (value !== "engine" && value !== "browser")
2553
+ throw new EditorError("invalid_video_conversion", `videoConversion must be "engine" or "browser"; received ${JSON.stringify(value)}`, operation);
2554
+ return value;
2555
+ }
2556
+ /** Whether the engine draws a source itself with no backing file (generated or a composition). */
2410
2557
  function drawnByEngine(source) {
2411
2558
  return source.kind === "generated" || source.kind === "composition";
2412
2559
  }
2413
- /** Waits for `promise`, or rejects when `signal` aborts first. */
2414
2560
  function settledOrAborted(promise, signal) {
2415
2561
  if (!signal)
2416
2562
  return promise;