@alpha2-sh/editor 0.4.6 → 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 +396 -312
  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 +47 -28
  12. package/dist/browser/runtime/assets.js +129 -45
  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 +39 -44
  20. package/dist/browser/runtime/engine.js +78 -64
  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 +85 -103
  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 +233 -238
  51. package/dist/browser/worker.d.ts +8 -9
  52. package/dist/browser/worker.js +50 -21
  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 +64 -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 -20
  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";
@@ -18,8 +21,8 @@ import { keepProviderChoices, mayBeExtension, providerDocumentLimit, stageProvid
18
21
  import { ProxyStore } from "./runtime/proxies.js";
19
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,29 +46,30 @@ const PLAYBACK_POLICIES = Object.freeze([
44
46
  "offline_exact",
45
47
  ]);
46
48
  /**
47
- * Files of one import staged at once. Each hashes its whole file in its own worker, at about
48
- * 200 MB/s: four read about 800 MB/s, below a local SSD, and one core stays with the page.
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.
49
51
  */
50
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";
51
55
  /**
52
- * How long Play waits for sound to start before playing the picture without it. A first start loads
53
- * and compiles the audio worklet and decodes the first block, about 1.5 s on Firefox.
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.
54
58
  */
55
59
  const AUDIO_START_TIMEOUT_MS = 3000;
56
60
  /**
57
- * The default media adapter: stages each file in its own `AssetLibrary`, apart from the
58
- * bridge's live one, so a failed or cancelled import leaves nothing behind. Files an extension
59
- * provider reads (SVG, animated images, Lottie, OpenEXR) are probed, opened and drawn for their
60
- * thumbnail by `alpha2/extensions`, loaded from `extensionsWasmUrl`: in a worker
61
- * `extensionsWorkerFactory` makes for each file, which a cancelled import or a call past
62
- * `EXTENSIONS_CALL_TIMEOUT_MS` terminates, or, without one, on this thread. A font is checked with
63
- * the engine's parser (`alpha2/wasm`, from `wasmUrl`) and also registered with the page's
64
- * `FontFace` set. A file's content hash is made in a worker `hashWorkerFactory` makes, where there
65
- * is one.
66
- * @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]
67
70
  * @returns {import("./types.js").BrowserMediaAdapter}
68
71
  */
69
- export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFactory, extensionsWorkerFactory, } = {}) {
72
+ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFactory, extensionsWorkerFactory, hdrWithoutPlanes = "preview-degraded", } = {}) {
70
73
  const hash = hashWorkerFactory
71
74
  ? (file, options) => hashInWorker(hashWorkerFactory, file, options)
72
75
  : sha256Blob;
@@ -75,8 +78,8 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
75
78
  wasmUrl: extensionsWasmUrl,
76
79
  };
77
80
  /**
78
- * What the provider module makes of `file` with `call`. A file it refuses is `unreadable_media`
79
- * 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.
80
83
  */
81
84
  const read = async (call, file, signal) => {
82
85
  try {
@@ -89,7 +92,6 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
89
92
  }
90
93
  };
91
94
  return {
92
- /** Stages numbered PNGs or OpenEXR images as one image sequence. */
93
95
  async stageSequence(files, options, signal) {
94
96
  signal.throwIfAborted();
95
97
  const item = await stageSequence(files, {
@@ -101,13 +103,13 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
101
103
  },
102
104
  async stage(file, signal, { fingerprint: wanted = true } = {}) {
103
105
  signal.throwIfAborted();
104
- // The hash reads the whole file, so it starts now and runs while the file is probed.
106
+ // Start hashing now so it overlaps probing.
105
107
  const hashing = new AbortController();
106
108
  const stop = () => hashing.abort(signal.reason);
107
109
  signal.addEventListener("abort", stop, { once: true });
108
110
  const started = wanted ? hash(file, { signal: hashing.signal }) : null;
109
111
  started?.catch(() => { }); // awaited below when used; a failed stage aborts it
110
- /** The file's fingerprint, unless the caller has no use for it (a proxy being adopted). */
112
+ /** Skipped when the caller does not need it (a proxy being adopted). */
111
113
  const fingerprintOf = (kind, options) => wanted
112
114
  ? fingerprintFile(file, kind, {
113
115
  signal,
@@ -127,12 +129,12 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
127
129
  }
128
130
  },
129
131
  };
130
- /** Stages `file` as the media its bytes or name say it is; `fingerprintOf` gives its evidence. */
132
+ /** Stages `file` as the media its bytes or name indicate. */
131
133
  async function stageFile(file, signal, fingerprintOf) {
132
- // Recognized by its bytes; the provider module loads only for bytes that could be one.
134
+ // Sniff the bytes first; the provider module loads only for bytes that could match.
133
135
  const head = new Uint8Array(await file.slice(0, 4096).arrayBuffer());
134
136
  if (mayBeExtension(head)) {
135
- // Parsed whole in provider memory that never shrinks, so an oversize file is refused unread.
137
+ // Providers parse whole files into memory that never shrinks; refuse oversize files unread.
136
138
  const document = providerDocumentLimit(head);
137
139
  if (document !== null && file.size > document.limit)
138
140
  throw new EditorError("too_large", `${file.name} is ${file.size} bytes; a ${document.what} is read up to ${document.limit}`, "import");
@@ -179,14 +181,14 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
179
181
  },
180
182
  };
181
183
  }
182
- const library = new AssetLibrary();
184
+ const library = new AssetLibrary({ hdrWithoutPlanes });
183
185
  try {
184
186
  const runtime = file.name.toLowerCase().endsWith(".cube")
185
187
  ? await library.importEffectResource(file, "lut3d")
186
188
  : await library.importFile(file, { signal });
187
189
  signal.throwIfAborted();
188
190
  if (runtime.kind === "lut3d") {
189
- // The engine's parser validates the LUT once here rather than at every load.
191
+ // Validate the LUT once here rather than at every load.
190
192
  const { loadEngineWasm } = await import("./runtime/wasm.js");
191
193
  const { checkLut3d } = await loadEngineWasm(wasmUrl);
192
194
  signal.throwIfAborted();
@@ -219,46 +221,48 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
219
221
  }
220
222
  /**
221
223
  * Creates the browser runtime for an editor session: preview, playback, import, proxies and
222
- * export. No GPU device, AudioContext, worker or decoder is created until `bindPreview`, an
223
- * import, `play` or `startExport` needs one. The bridge registers itself as an owner of
224
- * `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.
225
226
  * @param {import("./types.js").BrowserBridgeOptions} options
226
227
  * @returns {import("./types.js").BrowserBridge}
227
228
  */
228
229
  export function createBrowserBridge(options) {
229
- const { editor, runtimeAssets = {}, mediaAdapter = createMediaAdapter(runtimeAssets), resourceLimit = 128, audio = true, onError = () => { }, assetDecisions, previewScale: initialPreviewScale = 0.5, videoConversion: initialVideoConversion = "engine", } = 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;
230
231
  let previewScale = checkedPreviewScale(initialPreviewScale);
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";
231
236
  const videoConversion = checkedVideoConversion(initialVideoConversion, "bridge");
232
- // A test's stand-in for origin storage, kept out of the public options.
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.
233
243
  const proxyStore =
234
244
  /** @type {{ proxyStore?: ProxyStore }} */ (options).proxyStore ??
235
245
  new ProxyStore();
236
246
  let decisionBinding = assetDecisions ?? null;
237
- /**
238
- * The wasm module's authoring functions, loaded on first use: the same instance the preview
239
- * engine renders with.
240
- */
247
+ /** The wasm module's authoring functions, loaded on first use; the preview engine's instance. */
241
248
  const loadWasm = async () => {
242
249
  const { loadEngineWasm } = await import("./runtime/wasm.js");
243
250
  return loadEngineWasm(runtimeAssets.wasmUrl);
244
251
  };
245
252
  /** The engine's asset decisions, from the wasm module, loaded on first use. */
246
253
  const decisions = async () => (decisionBinding ??= await loadWasm());
247
- /**
248
- * What `measureText` and `measureLayout` lay text out with, made on first use, and the font
249
- * stack it holds.
250
- */
254
+ /** Text measurer for `measureText` and `measureLayout`, made on first use, and its font stack. */
251
255
  let measurer = null, measuredFonts = null;
252
256
  const registry = new ResourceRegistry(resourceLimit);
253
257
  /**
254
- * The runtimes this session holds, by {@link ownerKey}: a lease and the registry revision it was
255
- * put under. Media is keyed by its content revision, which this bridge issues; text by what it
256
- * 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.
257
261
  */
258
262
  const owners = new Map();
259
263
  /**
260
- * The highest registry revision issued for each runtime ID: none is issued twice, so a runtime
261
- * 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.
262
266
  */
263
267
  const issued = new Map();
264
268
  const issue = (id, atLeast = 0) => {
@@ -266,16 +270,12 @@ export function createBrowserBridge(options) {
266
270
  issued.set(id, revision);
267
271
  return revision;
268
272
  };
269
- /**
270
- * Proxies by their original's hash: the kept record, a lease on the decoded runtime and its
271
- * registry revision.
272
- */
273
+ /** Proxies by their original's hash: kept record, runtime lease and registry revision. */
273
274
  const proxies = new Map();
274
- /** Proxies being made, by source ID: their progress from 0 to 1. */
275
+ /** Progress (0 to 1) of proxies being made, by source ID. */
275
276
  const proxyJobs = new Map();
276
- /** What preview reads for each source, as the engine last selected it. */
277
277
  let previewSelection = new Map();
278
- /** What that selection was decided from (see `loaded`). */
278
+ /** The key `previewSelection` was decided from (see `loaded`). */
279
279
  let previewConformKey = null;
280
280
  /** What preview prefers where a source has a fresh proxy (see `setPreviewMedia`). */
281
281
  let preferredPreviewMedia = "original";
@@ -287,9 +287,8 @@ export function createBrowserBridge(options) {
287
287
  return ownerOf(document, descriptor)?.lease.value ?? null;
288
288
  };
289
289
  /**
290
- * The host's view of each source's media, for the engine to decide with: the original is online
291
- * when this session holds its file, and a kept proxy is offered when it was made from the media
292
- * 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.
293
292
  */
294
293
  const catalogOf = (document) => ({
295
294
  assets: document.project.sources
@@ -321,9 +320,8 @@ export function createBrowserBridge(options) {
321
320
  /** Proxies being adopted, by hash, so two callers share one adoption. */
322
321
  const adopting = new Map();
323
322
  /**
324
- * Adopts a kept proxy: its file staged like any import, under its own ID. `hold` (the store's
325
- * `hold`) keeps the proxy in use until the runtime is disposed: once no document and no export
326
- * 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.
327
325
  */
328
326
  function adoptProxy(hash, found, hold) {
329
327
  if (proxies.has(hash)) {
@@ -338,7 +336,7 @@ export function createBrowserBridge(options) {
338
336
  pending = (async () => {
339
337
  let staged;
340
338
  try {
341
- // 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.
342
340
  staged = await mediaAdapter.stage(found.file, new AbortController().signal, { fingerprint: false });
343
341
  }
344
342
  catch (error) {
@@ -369,15 +367,9 @@ export function createBrowserBridge(options) {
369
367
  adopting.set(hash, pending);
370
368
  return pending;
371
369
  }
372
- /**
373
- * Hashes the store had no proxy for, this session: not asked again until the session changes.
374
- * A proxy this session makes is adopted directly.
375
- */
370
+ /** Hashes with no stored proxy, not asked again this session. */
376
371
  let absentProxies = new Set();
377
- /**
378
- * Finds the kept proxies of sources this session has no original for, and of every source while
379
- * preview prefers proxies.
380
- */
372
+ /** Finds kept proxies for offline sources, and for every source while preview prefers proxies. */
381
373
  async function discoverProxies(document) {
382
374
  for (const source of document.project.sources) {
383
375
  const descriptor = document.assets[source.id];
@@ -388,7 +380,7 @@ export function createBrowserBridge(options) {
388
380
  (preferredPreviewMedia === "original" &&
389
381
  originalOf(document, source.id)))
390
382
  continue;
391
- // Held before it is read, so no page removes it between.
383
+ // Hold before reading so no other page removes it in between.
392
384
  const hold = await proxyStore.hold(hash);
393
385
  const found = await proxyStore.find(hash).catch(() => null);
394
386
  if (found)
@@ -399,7 +391,6 @@ export function createBrowserBridge(options) {
399
391
  }
400
392
  }
401
393
  }
402
- /** Whether `document`'s media is ready for `purpose`, as the engine decides. */
403
394
  async function conform(purpose, document = editor.document) {
404
395
  await discoverProxies(document);
405
396
  const binding = await decisions();
@@ -417,15 +408,14 @@ export function createBrowserBridge(options) {
417
408
  for (const listener of assetListeners)
418
409
  listener();
419
410
  };
420
- /** 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. */
421
412
  const analyses = new Map();
422
413
  /** Whether this session still holds `runtime` for some document it can show. */
423
414
  const held = (runtime) => [...owners.values()].some((owner) => owner.lease.value === runtime);
424
415
  /**
425
- * Waveform peaks are derived after import, one file at a time, so an import commits as soon as
426
- * the media is readable. The analysis belongs to the runtime, not to the document that imported
427
- * it: a document opened again over the same media keeps it, and only letting the runtime go (no
428
- * 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.
429
419
  */
430
420
  const analyze = (runtime) => {
431
421
  if (!runtime.file ||
@@ -456,21 +446,21 @@ export function createBrowserBridge(options) {
456
446
  };
457
447
  const jobs = new Set();
458
448
  let disposed = false, engine = null, workerPreview = null, boundCanvas = null, copySurface = false,
459
- // The worker failed for a reason other than a lost GPU: later previews for this binding stay on
460
- // 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.
461
451
  workerGivenUp = false, sources = null, mixer = null, supplier = null, binding = 0, queue = Promise.resolve(), renderKey = null, tick = 0, playing = false,
462
- // How the current or last playback was asked for, so a recovered preview plays on alike.
463
- playRequest = null, renderScheduled = false, raf = 0, playClock = null, loadRevision = 0, loadedAssets = new Map(), loadedSelection = "", loadedFonts = null, audioKey = null,
464
- // What the preview worker holds from its last load.
465
- workerSent = new Map(), workerFonts = null, refreshFrame = 0, monitorVolume = 1,
466
- // 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.
467
457
  passTiming = false, traceUploads = false,
468
- // The worker's last renderer diagnostics snapshot, and counters since `bindPreview`: playback
469
- // 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.
470
460
  workerDiagnostics = null, skippedRequests = 0, bitmapTransfers = 0, playGeneration = 0, sessionGeneration = editor.generation;
471
461
  /**
472
- * Preview's media for a source of `document`: what the engine selected, the original unless it is
473
- * 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.
474
464
  */
475
465
  function previewMedia(document, id) {
476
466
  const descriptor = document.assets[id];
@@ -484,10 +474,7 @@ export function createBrowserBridge(options) {
484
474
  }
485
475
  const library = { get: (id) => previewMedia(editor.draft, id) };
486
476
  const key = (id, revision) => JSON.stringify([id, revision]);
487
- /**
488
- * The font families a text style draws with: each imported font's by the family its runtime
489
- * registered, other names as written.
490
- */
477
+ /** Font families a text style draws with: imported fonts by their registered family. */
491
478
  function familiesOf(document, text) {
492
479
  return (text?.fontFamily ?? "sans-serif").split(",").map((name) => {
493
480
  const plain = name.trim().replace(/^["']|["']$/g, "");
@@ -495,10 +482,7 @@ export function createBrowserBridge(options) {
495
482
  return (font && ownerOf(document, font)?.lease.value.family) ?? plain;
496
483
  });
497
484
  }
498
- /**
499
- * Which runtime `asset` of `document` reads: media by its content revision, text by its authoring
500
- * and the fonts it resolves to.
501
- */
485
+ /** Which runtime `asset` reads: media by content revision, text by authoring and fonts. */
502
486
  function ownerKey(document, asset) {
503
487
  return asset.kind === "text"
504
488
  ? JSON.stringify([
@@ -512,10 +496,7 @@ export function createBrowserBridge(options) {
512
496
  function ownerOf(document, asset) {
513
497
  return owners.get(ownerKey(document, asset)) ?? null;
514
498
  }
515
- /**
516
- * A lease on the runtime `asset` of `document` reads, for work that outlives the owner's hold on
517
- * it.
518
- */
499
+ /** A lease on the runtime `asset` reads, for work that outlives the owner's hold. */
519
500
  function acquireOwned(document, asset) {
520
501
  const owner = asset && ownerOf(document, asset);
521
502
  if (!owner && asset?.kind === "text")
@@ -530,12 +511,11 @@ export function createBrowserBridge(options) {
530
511
  throw new EditorError("missing_asset", `${editor.document.assets[id]?.name ?? id} has no proxy in this session`, "resource", id);
531
512
  return registry.acquire(`proxy:${hash}`, proxy.revision);
532
513
  }
533
- /** 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. */
534
515
  const views = new WeakMap();
535
516
  /**
536
- * `runtime` opened as source `id` of `document` says: a provider's settings (a package's
537
- * animation, an OpenEXR still's primaries) are the document's, so undo and redo change what is
538
- * 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.
539
519
  */
540
520
  function sourceView(document, id, runtime) {
541
521
  if (!runtime?.provider)
@@ -557,8 +537,8 @@ export function createBrowserBridge(options) {
557
537
  return view;
558
538
  }
559
539
  /**
560
- * Runs `fn` after the preview work already queued. Its failure goes to the caller, which reports
561
- * 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.
562
542
  */
563
543
  const enqueue = (fn) => {
564
544
  const next = queue.then(() => {
@@ -578,8 +558,14 @@ export function createBrowserBridge(options) {
578
558
  return asset?.kind === "text" ? { id, kind: "image", asset } : asset;
579
559
  },
580
560
  });
561
+ // Preview needs the engine module and canvases, not a GPU: without one it renders on the CPU.
581
562
  const features = Object.freeze({
582
- 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
+ },
583
569
  audioPreview: {
584
570
  available: typeof SharedArrayBuffer !== "undefined" &&
585
571
  globalThis.crossOriginIsolated === true,
@@ -591,16 +577,18 @@ export function createBrowserBridge(options) {
591
577
  reason: "Provide a bundled workerFactory; otherwise the main-thread adapter is used",
592
578
  },
593
579
  export: {
594
- available: typeof VideoEncoder !== "undefined",
595
- 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",
596
584
  },
597
585
  });
598
- /** 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. */
599
587
  let capabilities = capabilityReport(null);
600
588
  function capabilityReport(rendered) {
601
589
  return Object.freeze({
602
590
  schema: "alpha2-capabilities",
603
- version: 1,
591
+ version: 2,
604
592
  runtime: "browser",
605
593
  gpu: rendered?.gpu ?? null,
606
594
  color: rendered?.color ?? null,
@@ -612,25 +600,18 @@ export function createBrowserBridge(options) {
612
600
  decode: null,
613
601
  encode: null,
614
602
  features,
603
+ adapters: null,
604
+ renderer: rendered?.renderer ?? null,
615
605
  });
616
606
  }
617
- /**
618
- * Why each text could not be drawn, by {@link ownerKey}: a failed raster is not retried until its
619
- * authoring or fonts change.
620
- */
607
+ /** Raster failures by {@link ownerKey}; not retried until authoring or fonts change. */
621
608
  const textFailures = new Map();
622
- /**
623
- * The error a render that shows `asset`, a text of `document` that could not be rasterized, fails
624
- * with.
625
- */
609
+ /** The error a render fails with when it shows text `asset` that could not be rasterized. */
626
610
  function undrawnText(document, asset) {
627
611
  const failure = textFailures.get(ownerKey(document, asset));
628
612
  return new EditorError("text_unrenderable", `Text "${asset.name}" cannot be drawn: ${failure?.message ?? "it was not rasterized"}`, "resource", asset.id);
629
613
  }
630
- /**
631
- * Fails with {@link undrawnText} when `project`, compiled from `document`, shows a text that
632
- * could not be drawn.
633
- */
614
+ /** Throws {@link undrawnText} when compiled `project` shows text that could not be drawn. */
634
615
  function requireShownText(document, project) {
635
616
  const used = shownSources(project);
636
617
  for (const asset of Object.values(document.assets))
@@ -640,9 +621,9 @@ export function createBrowserBridge(options) {
640
621
  throw undrawnText(document, asset);
641
622
  }
642
623
  /**
643
- * Rasterizes each text of `document` that no held runtime draws yet: new authoring, or a font
644
- * that resolves to another family now that it is linked. A text that cannot be drawn (too large
645
- * 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.
646
627
  */
647
628
  function materializeText(document) {
648
629
  for (const asset of Object.values(document.assets)) {
@@ -670,7 +651,7 @@ export function createBrowserBridge(options) {
670
651
  }
671
652
  }
672
653
  const hasContent = (project) => project?.timeline.tracks.some((track) => (track.clips?.length ?? 0) + (track.captions?.cues.length ?? 0) > 0);
673
- // A node the viewer shows instead of a composition's output; preview only.
654
+ // Node shown instead of a composition's output; preview only.
674
655
  let previewOutput = null;
675
656
  const withPreviewOutput = (project) => {
676
657
  if (!previewOutput)
@@ -685,12 +666,8 @@ export function createBrowserBridge(options) {
685
666
  };
686
667
  };
687
668
  /**
688
- * The fonts captions and an SVG's text draw with, in fallback order: the document's font assets,
689
- * then the runtime's own. Native exports get the same stack (`nativeAssets`).
690
- */
691
- /**
692
- * Reports each font of a registered stack the engine could not parse, by name: it was left out,
693
- * 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.
694
671
  */
695
672
  function reportRefusedFonts(refused, operation) {
696
673
  for (const { font, error } of refused ?? [])
@@ -701,16 +678,13 @@ export function createBrowserBridge(options) {
701
678
  ...(runtimeAssets.fonts ?? []),
702
679
  ];
703
680
  /**
704
- * The document's font assets this session holds a file for. A font is no source the engine
705
- * 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.
706
683
  */
707
684
  function heldFonts(document) {
708
685
  return Object.values(document.assets).filter((a) => a.kind === "font" && !a.missing && ownerOf(document, a));
709
686
  }
710
- /**
711
- * Readies `measurer` with the fonts preview draws the draft with, and answers the draft's canvas
712
- * size, which preview draws it at.
713
- */
687
+ /** Loads `measurer` with preview's fonts for the draft and returns the draft's canvas size. */
714
688
  async function draftMeasurer() {
715
689
  const { WasmTextMeasurer } = await loadWasm();
716
690
  if (disposed)
@@ -719,7 +693,7 @@ export function createBrowserBridge(options) {
719
693
  const fonts = fontStackOf(document);
720
694
  measurer ??= new WasmTextMeasurer();
721
695
  if (!sameList(measuredFonts, fonts)) {
722
- // 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.
723
697
  registerCaptionFonts(measurer, fonts);
724
698
  measuredFonts = fonts;
725
699
  }
@@ -758,7 +732,6 @@ export function createBrowserBridge(options) {
758
732
  previewConformKey = conformKey;
759
733
  }
760
734
  const selectionKey = JSON.stringify([...previewSelection]);
761
- // `proxyStatus` reports what preview reads.
762
735
  if (selectionKey !== before)
763
736
  notifyAssets();
764
737
  const used = shownSources(compiled.project);
@@ -776,12 +749,12 @@ export function createBrowserBridge(options) {
776
749
  throw new EditorError("missing_asset", `Relink ${document.assets[resource.id]?.name ?? resource.id} before preview`, "preview", resource.id);
777
750
  const allFonts = fontStackOf(document);
778
751
  const key = renderKeyOf(document);
779
- // 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.
780
753
  const settled = document === editor.document;
781
754
  if (renderKey !== key || loadedSelection !== selectionKey) {
782
755
  mixer.stop();
783
756
  engine.invalidate();
784
- // Keep decoders warm: only a source whose runtime changed is reopened.
757
+ // Keep decoders warm by reopening only sources whose runtime changed.
785
758
  const reads = new Map(Object.values(document.assets).map((a) => [
786
759
  a.id,
787
760
  previewMedia(document, a.id),
@@ -801,8 +774,10 @@ export function createBrowserBridge(options) {
801
774
  reportRefusedFonts(refused, "preview");
802
775
  }
803
776
  engine.loadProject(compiled.project);
804
- // Frames render at the document's size times the preview scale, and the surfaces are that
805
- // 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.
806
781
  let renderSize = engine.previewSize;
807
782
  engine.resize(renderSize[0], renderSize[1]);
808
783
  // Sources are fitted in document space; the render scales them.
@@ -815,14 +790,14 @@ export function createBrowserBridge(options) {
815
790
  ]
816
791
  .map((source) => [source.id, previewMedia(document, source.id)])
817
792
  .filter(([, asset]) => asset);
818
- // 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.
819
794
  const keep = used
820
795
  .filter(([id, asset]) => workerSent.get(id) === asset)
821
796
  .map(([id]) => id);
822
797
  const kept = new Set(keep);
823
798
  const workerAssets = used
824
799
  .filter(([id]) => !kept.has(id))
825
- // 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.
826
801
  .map(([id, asset]) => {
827
802
  const data = { id };
828
803
  for (const field of [
@@ -845,7 +820,7 @@ export function createBrowserBridge(options) {
845
820
  return data;
846
821
  });
847
822
  const sendFonts = !sameList(workerFonts, allFonts);
848
- // 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.
849
824
  workerSent = new Map();
850
825
  workerFonts = null;
851
826
  try {
@@ -888,19 +863,18 @@ export function createBrowserBridge(options) {
888
863
  }
889
864
  scheduleSweep();
890
865
  scheduleTextReports();
891
- // 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.
892
867
  if (engine && !refreshFrame)
893
868
  refreshFrame = nextFrame(refresh);
894
869
  });
895
- /** The font stack each SVG runtime's report was last computed with. */
896
870
  const reportedFonts = new WeakMap();
897
- /** 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). */
898
872
  const lifetime = new AbortController();
899
873
  let textReports = Promise.resolve(), textReportsQueued = false;
900
874
  /**
901
- * An SVG's report says which of its text no font draws (`missing_font`). Import probes it with no
902
- * fonts at all, so it is computed again with the stack its text draws with whenever that stack or
903
- * 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.
904
878
  */
905
879
  function scheduleTextReports() {
906
880
  if (textReportsQueued || disposed)
@@ -957,7 +931,7 @@ export function createBrowserBridge(options) {
957
931
  notifyAssets();
958
932
  }
959
933
  let sweepQueued = false;
960
- /** 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. */
961
935
  function scheduleSweep() {
962
936
  if (sweepQueued || disposed)
963
937
  return;
@@ -971,15 +945,15 @@ export function createBrowserBridge(options) {
971
945
  });
972
946
  }
973
947
  /**
974
- * Media and proxies stay held while any document the session can return to reads them: a relink
975
- * or import undone, or a removed asset, comes back with its runtime. Text is held only while the
976
- * document or the draft draws it, since its authoring makes it again. Work that leased a runtime
977
- * (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.
978
952
  */
979
953
  function sweep() {
980
954
  const media = new Set(), hashes = new Set(), seen = new Set();
981
955
  for (const document of editor.reachableDocuments()) {
982
- // 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.
983
957
  if (seen.has(document.assets))
984
958
  continue;
985
959
  seen.add(document.assets);
@@ -1024,8 +998,8 @@ export function createBrowserBridge(options) {
1024
998
  refreshPreview();
1025
999
  return;
1026
1000
  }
1027
- // Playback reads the project it started with, so an edit restarts it from where it stood, at the
1028
- // 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.
1029
1003
  const resume = playRequest;
1030
1004
  pause();
1031
1005
  refreshPreview();
@@ -1053,9 +1027,15 @@ export function createBrowserBridge(options) {
1053
1027
  }).catch(onError);
1054
1028
  }
1055
1029
  let previewIssue = null;
1056
- /** 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. */
1057
1033
  let recoveryPending = false;
1058
- /** 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;
1059
1039
  let previewRecoveries = 0;
1060
1040
  const previewListeners = new Set();
1061
1041
  const setPreviewIssue = (issue) => {
@@ -1066,13 +1046,13 @@ export function createBrowserBridge(options) {
1066
1046
  listener();
1067
1047
  };
1068
1048
  /**
1069
- * Renders the frame at `at`. A composition that cannot draw its output yet is not an error here:
1070
- * 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.
1071
1051
  */
1072
1052
  async function renderAt(at, project, recovered = false) {
1073
1053
  try {
1074
- const rendered = await renderFrame(at, project);
1075
- setPreviewIssue(null);
1054
+ const rendered = await renderFrame(at, project, recovered);
1055
+ setPreviewIssue(degradedShown.length > 0 ? DEGRADED_PREVIEW_ISSUE : null);
1076
1056
  return rendered;
1077
1057
  }
1078
1058
  catch (error) {
@@ -1080,15 +1060,35 @@ export function createBrowserBridge(options) {
1080
1060
  setPreviewIssue(error.message ?? String(error));
1081
1061
  return false;
1082
1062
  }
1083
- 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;
1084
1075
  if (recovered || !lost || !boundCanvas || disposed)
1085
1076
  throw error;
1086
- 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)))
1087
1087
  return false;
1088
1088
  return renderAt(at, await loaded(), true);
1089
1089
  }
1090
1090
  }
1091
- async function renderFrame(at, project) {
1091
+ async function renderFrame(at, project, recovered = false) {
1092
1092
  if (boundCanvas?.style)
1093
1093
  boundCanvas.style.visibility = hasContent(project) ? "visible" : "hidden";
1094
1094
  if (!hasContent(project))
@@ -1098,7 +1098,8 @@ export function createBrowserBridge(options) {
1098
1098
  const result = await workerPreview.seek(at);
1099
1099
  if (result.engineDiagnostics)
1100
1100
  workerDiagnostics = result.engineDiagnostics;
1101
- // 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.
1102
1103
  if (result.bitmap) {
1103
1104
  boundCanvas
1104
1105
  .getContext("bitmaprenderer")
@@ -1108,26 +1109,32 @@ export function createBrowserBridge(options) {
1108
1109
  return result.rendered;
1109
1110
  }
1110
1111
  catch (error) {
1111
- 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))
1112
1116
  throw error;
1113
1117
  // The main renderer has the same project loaded and draws this frame instead.
1114
1118
  await abandonWorker(error);
1115
1119
  }
1116
1120
  }
1117
- const { rendered, unchanged } = await engine.render(at / 120000, {
1121
+ const { rendered, unchanged, degradedSources = [], } = await engine.render(at / 120000, {
1118
1122
  generation: engine.generation,
1119
1123
  context: context(project, library),
1120
1124
  });
1121
- // 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`.
1122
1129
  if (rendered && !unchanged && copySurface) {
1123
1130
  boundCanvas
1124
1131
  .getContext("bitmaprenderer")
1125
- .transferFromImageBitmap(engine.canvas.transferToImageBitmap());
1132
+ .transferFromImageBitmap(await createImageBitmap(engine.canvas));
1126
1133
  bitmapTransfers += 1;
1127
1134
  }
1128
1135
  return rendered;
1129
1136
  }
1130
- /** 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. */
1131
1138
  function sizeBoundCanvas(size) {
1132
1139
  if (!boundCanvas || !size)
1133
1140
  return;
@@ -1136,7 +1143,6 @@ export function createBrowserBridge(options) {
1136
1143
  if (boundCanvas.height !== size[1])
1137
1144
  boundCanvas.height = size[1];
1138
1145
  }
1139
- /** Applies the bridge's tracing to the renderers drawing now. */
1140
1146
  function applyTracing() {
1141
1147
  if (engine) {
1142
1148
  engine.traceUploads = traceUploads;
@@ -1147,12 +1153,34 @@ export function createBrowserBridge(options) {
1147
1153
  .catch(() => { });
1148
1154
  }
1149
1155
  /**
1150
- * Gives up the preview worker after `error`, whether it failed to start, to load a project or to
1151
- * draw: the main renderer, which loads every project the worker does, draws from then on, off
1152
- * screen, and each frame is copied to the bound surface (a canvas element or an OffscreenCanvas
1153
- * alike); a preview made again after a lost GPU does too, until the next binding. `onError` hears
1154
- * once why, unless the worker lost its GPU: that is recovered from, as the main renderer recovers
1155
- * 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.
1156
1184
  */
1157
1185
  async function abandonWorker(error) {
1158
1186
  const failed = workerPreview;
@@ -1163,7 +1191,7 @@ export function createBrowserBridge(options) {
1163
1191
  workerFonts = null;
1164
1192
  copySurface = true;
1165
1193
  await failed.dispose().catch(() => { });
1166
- if (error?.code === "GPU_DEVICE_LOST")
1194
+ if (isGpuLoss(error))
1167
1195
  return;
1168
1196
  workerGivenUp = true;
1169
1197
  const reason = error instanceof Error ? error.message : String(error ?? "");
@@ -1180,7 +1208,7 @@ export function createBrowserBridge(options) {
1180
1208
  engine?.invalidate();
1181
1209
  mixer?.stop();
1182
1210
  const requested = tick;
1183
- // 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.
1184
1212
  return enqueue(async () => {
1185
1213
  if (requested !== tick)
1186
1214
  return false;
@@ -1206,7 +1234,7 @@ export function createBrowserBridge(options) {
1206
1234
  void workerPreview.cancel().catch(onError);
1207
1235
  }
1208
1236
  // An audio start that missed its deadline and has not settled. A context that never resumes
1209
- // (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.
1210
1238
  let stalledAudio = null;
1211
1239
  /** Whether `starting` settled within the deadline; a rejection propagates. */
1212
1240
  async function audioStarts(starting) {
@@ -1229,9 +1257,9 @@ export function createBrowserBridge(options) {
1229
1257
  return false;
1230
1258
  }
1231
1259
  /**
1232
- * 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
1233
1261
  * engine's clock decides which frame shows when and whether sound plays. Sound that cannot start
1234
- * in time is left out rather than holding the picture.
1262
+ * in time is dropped rather than holding the picture.
1235
1263
  */
1236
1264
  async function play(rate = 1, { loop = false, policy = "drop_video_keep_audio" } = {}) {
1237
1265
  if (!Number.isFinite(rate) || rate === 0)
@@ -1243,7 +1271,7 @@ export function createBrowserBridge(options) {
1243
1271
  let audible = (engine?.audible(policy, rate) ?? false) && stalledAudio === null;
1244
1272
  if (audible)
1245
1273
  audible = await audioStarts(mixer.resume());
1246
- // 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.
1247
1275
  let project = null;
1248
1276
  await enqueue(async () => {
1249
1277
  if (!engine || generation !== playGeneration)
@@ -1266,13 +1294,13 @@ export function createBrowserBridge(options) {
1266
1294
  playing = true;
1267
1295
  playRequest = { rate, loop, policy };
1268
1296
  const clock = (playClock = engine.playbackClock(policy, project.settings.frame_rate, rate, tick, performance.now()));
1269
- // 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.
1270
1298
  let requested = null, presented = false;
1271
1299
  const step = (now) => {
1272
1300
  if (!playing || disposed || generation !== playGeneration)
1273
1301
  return;
1274
1302
  // At 1x under the default policy the audio clock leads while output consumes samples; the
1275
- // 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.
1276
1304
  const heard = audible ? (mixer.tick ?? undefined) : undefined;
1277
1305
  const wanted = clock.step(now, heard, presented);
1278
1306
  tick = wanted.tick;
@@ -1295,9 +1323,8 @@ export function createBrowserBridge(options) {
1295
1323
  .catch(onError);
1296
1324
  return;
1297
1325
  }
1298
- // The clock asks for frame starts, so every policy asks for each frame once however often
1299
- // the display refreshes; a waiting policy also moves on only after it is shown, and the
1300
- // 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.
1301
1328
  const due = requested !== tick;
1302
1329
  if (!due)
1303
1330
  skippedRequests += 1;
@@ -1329,9 +1356,8 @@ export function createBrowserBridge(options) {
1329
1356
  pause();
1330
1357
  };
1331
1358
  /**
1332
- * Makes the preview's renderer, audio, and worker for `canvas`, disposing what the last one made.
1333
- * Runs inside the render queue. Returns false when a later binding or disposal superseded
1334
- * `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`.
1335
1361
  */
1336
1362
  async function buildPreview(canvas, token) {
1337
1363
  pause();
@@ -1343,7 +1369,7 @@ export function createBrowserBridge(options) {
1343
1369
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1344
1370
  });
1345
1371
  const { Engine } = await import("./runtime/engine.js");
1346
- // Until a project loads and gives the render size (see `loaded`).
1372
+ // Until a project loads and sets the render size (see `loaded`).
1347
1373
  canvas.width = editor.document.project.settings.width;
1348
1374
  canvas.height = editor.document.project.settings.height;
1349
1375
  boundCanvas = canvas;
@@ -1351,12 +1377,28 @@ export function createBrowserBridge(options) {
1351
1377
  await workerPreview?.dispose();
1352
1378
  workerPreview = null;
1353
1379
  workerDiagnostics = null;
1354
- const useWorker = features.worker.available && typeof canvas.getContext === "function";
1355
- engine = new Engine(useWorker ? new OffscreenCanvas(canvas.width, canvas.height) : canvas, sources, library, runtimeAssets,
1356
- // A frame shown at once matters more in a preview than the engine's conversion of it.
1357
- { unreadableFrames: "present", videoConversion });
1358
- 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
+ });
1359
1400
  mixer.setMasterVolume(monitorVolume);
1401
+ mixer.setLatencyOffset(audioOffsetMs);
1360
1402
  stalledAudio = null;
1361
1403
  supplier = new AudioWindowSupplier(library);
1362
1404
  try {
@@ -1364,10 +1406,9 @@ export function createBrowserBridge(options) {
1364
1406
  engine.setPreviewScale(previewScale);
1365
1407
  capabilities = capabilityReport(engine.capabilityReport());
1366
1408
  await registerKeptEffects();
1367
- // The surface already shows copied frames (its context is a bitmap renderer's).
1368
- if (useWorker && workerGivenUp)
1369
- copySurface = true;
1370
- 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) {
1371
1412
  const workerRuntime = {
1372
1413
  ...(runtimeAssets.wasmUrl
1373
1414
  ? { wasmUrl: String(runtimeAssets.wasmUrl) }
@@ -1382,12 +1423,15 @@ export function createBrowserBridge(options) {
1382
1423
  width: canvas.width,
1383
1424
  height: canvas.height,
1384
1425
  videoConversion,
1426
+ opaqueEngineFrames,
1427
+ // Match the main renderer: the CPU once recovery or `auto` moved there.
1428
+ renderer: onCpu() ? "cpu" : rendererMode,
1385
1429
  });
1386
1430
  // A worker that cannot start leaves the surface to the main renderer.
1387
1431
  try {
1388
1432
  await workerPreview.ready;
1389
1433
  await workerPreview.setPreviewScale(previewScale);
1390
- if (effectDefinitions.size)
1434
+ if (effectDefinitions.size && !onCpu())
1391
1435
  await workerPreview.registerEffects(keptEffects());
1392
1436
  }
1393
1437
  catch (error) {
@@ -1417,27 +1461,44 @@ export function createBrowserBridge(options) {
1417
1461
  return true;
1418
1462
  }
1419
1463
  /**
1420
- * A lost GPU (a WebGPU device, a WebGL context) is recovered here rather than reported: the
1421
- * preview is made again on the same canvas, as binding it did, and the frame drawn once more. The
1422
- * binding waits for the browser to restore a WebGL context on that canvas. When that fails the
1423
- * 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`).
1424
1469
  *
1425
- * Since nothing is reported, what the user sees goes on: playback that was running plays on from
1426
- * where it stood, at the same rate, loop and policy, once the preview is made again, unless a
1427
- * seek, a pause or another Play came first. Sound that had not started in time is not waited for
1428
- * 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.
1429
1472
  */
1430
- async function recoverPreview() {
1473
+ async function recoverPreview(step) {
1431
1474
  recoveryPending = true;
1475
+ pendingStep = step;
1432
1476
  const resume = playing ? playRequest : null;
1433
1477
  const stalled = stalledAudio;
1434
- if (!(await buildPreview(boundCanvas, binding)))
1435
- 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
+ }
1436
1496
  stalledAudio = stalled;
1437
1497
  recoveryPending = false;
1498
+ pendingStep = null;
1438
1499
  previewRecoveries += 1;
1439
1500
  if (resume) {
1440
- // Queued behind the render that is recovering, which draws the frame first.
1501
+ // Queued behind the recovering render, which draws the frame first.
1441
1502
  const stopped = playGeneration;
1442
1503
  void Promise.resolve()
1443
1504
  .then(() => disposed || playing || playGeneration !== stopped
@@ -1447,9 +1508,23 @@ export function createBrowserBridge(options) {
1447
1508
  }
1448
1509
  return true;
1449
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
+ }
1450
1525
  /**
1451
- * Runtime effects `registerEffects` kept, by `id@version`, with their JSON text, in the order they
1452
- * 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.
1453
1528
  */
1454
1529
  const effectDefinitions = new Map();
1455
1530
  const keptEffects = () => [...effectDefinitions.values()].map(({ definition }) => definition);
@@ -1472,6 +1547,13 @@ export function createBrowserBridge(options) {
1472
1547
  if (!added.size)
1473
1548
  return;
1474
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
+ }
1475
1557
  // The main renderer loads every project the worker does, so both hold every effect.
1476
1558
  if (engine)
1477
1559
  await engine.registerEffects(fresh);
@@ -1486,18 +1568,22 @@ export function createBrowserBridge(options) {
1486
1568
  }
1487
1569
  for (const [key, entry] of added)
1488
1570
  effectDefinitions.set(key, entry);
1489
- // A frame that drew one of them failed; it draws now.
1571
+ // A frame that used one of them failed; redraw it.
1490
1572
  if (engine)
1491
1573
  refreshPreview();
1492
1574
  });
1493
1575
  }
1494
1576
  /**
1495
- * Registers the kept runtime effects on the main renderer `buildPreview` just started, one by
1496
- * one: one its device refuses (kept while no preview was bound, so never compiled) is dropped and
1497
- * reported, and the others draw. A device lost meanwhile drops none: the next render makes the
1498
- * 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.
1499
1581
  */
1500
1582
  async function registerKeptEffects() {
1583
+ if (onCpu()) {
1584
+ reportCpuEffects([...effectDefinitions.keys()]);
1585
+ return;
1586
+ }
1501
1587
  const kept = [...effectDefinitions];
1502
1588
  const results = await Promise.allSettled(kept.map(([, { definition }]) => engine.registerEffects([definition])));
1503
1589
  if (engine.deviceLost)
@@ -1509,18 +1595,14 @@ export function createBrowserBridge(options) {
1509
1595
  onError(result.reason);
1510
1596
  }
1511
1597
  }
1512
- /** 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. */
1513
1599
  async function previewReady() {
1514
1600
  if (engine)
1515
1601
  return true;
1516
- if (!recoveryPending || !boundCanvas || disposed)
1602
+ if (previewUnavailable || !recoveryPending || !boundCanvas || disposed)
1517
1603
  return false;
1518
- return recoverPreview();
1604
+ return recoverPreview(pendingStep);
1519
1605
  }
1520
- /**
1521
- * Renders the preview at `scale` times the document's size from now on, sizing the surfaces to
1522
- * it, and draws the current frame again. Resolves once that frame is drawn.
1523
- */
1524
1606
  async function setPreviewScale(scale) {
1525
1607
  const next = checkedPreviewScale(scale);
1526
1608
  if (next === previewScale)
@@ -1551,6 +1633,9 @@ export function createBrowserBridge(options) {
1551
1633
  const token = ++binding;
1552
1634
  await enqueue(async () => {
1553
1635
  recoveryPending = false;
1636
+ pendingStep = null;
1637
+ previewLadder = new GpuRecoveryLadder();
1638
+ previewUnavailable = false;
1554
1639
  workerGivenUp = false;
1555
1640
  skippedRequests = 0;
1556
1641
  bitmapTransfers = 0;
@@ -1603,14 +1688,12 @@ export function createBrowserBridge(options) {
1603
1688
  stage: (signal) => mediaAdapter.stage(file, signal),
1604
1689
  })), options);
1605
1690
  }
1606
- /** Imports numbered PNGs as one image sequence at `frameRate` (the project's by default). */
1607
1691
  function importSequence(files, { frameRate, missing = "reject", signal } = {}) {
1608
1692
  const rate = frameRate ?? editor.document.project.settings.frame_rate;
1609
1693
  return importUnits([sequenceUnit(files, { frameRate: rate, missing })], {
1610
1694
  signal,
1611
1695
  });
1612
1696
  }
1613
- /** Relinks the image sequence `id` to `files`, staged as the project recorded it. */
1614
1697
  function relinkSequence(id, files, { signal } = {}) {
1615
1698
  const provider = editor.document.project.sources.find((source) => source.id === id)?.provider;
1616
1699
  if (provider?.format !== "image_sequence")
@@ -1633,7 +1716,7 @@ export function createBrowserBridge(options) {
1633
1716
  }
1634
1717
  /**
1635
1718
  * Stages `units` (at most {@link IMPORT_STAGE_CONCURRENCY} at once) and adds them to the document
1636
- * in their order, as one undo step; a relink has exactly one.
1719
+ * in order as one undo step. A relink has exactly one unit.
1637
1720
  */
1638
1721
  async function importUnits(units, { signal, relinkId } = {}) {
1639
1722
  if (disposed)
@@ -1649,8 +1732,8 @@ export function createBrowserBridge(options) {
1649
1732
  try {
1650
1733
  if (relinkId && units.length !== 1)
1651
1734
  throw new EditorError("relink_conflict", "Relink accepts exactly one file", "relink", relinkId);
1652
- // Staged together, committed in order. The first file that fails stops the rest, and its
1653
- // error is the import's, not the cancellation the others then see.
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.
1654
1737
  let failure = null;
1655
1738
  let next = 0;
1656
1739
  const stageNext = async () => {
@@ -1678,8 +1761,8 @@ export function createBrowserBridge(options) {
1678
1761
  const old = relinkId ? editor.document.assets[relinkId] : null;
1679
1762
  if (relinkId && !old)
1680
1763
  throw new EditorError("missing_asset", "Unknown relink target", "relink", relinkId);
1681
- // The engine decides whether the file is the recorded media: equal hashes match whatever else
1682
- // 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.
1683
1766
  if (old?.fingerprint && item.fingerprint) {
1684
1767
  const match = compareFingerprints(await decisions(), old.fingerprint, item.fingerprint);
1685
1768
  if (match.kind === "mismatch")
@@ -1690,9 +1773,9 @@ export function createBrowserBridge(options) {
1690
1773
  if (old && old.kind !== item.runtime.kind)
1691
1774
  throw new EditorError("relink_conflict", "Media kind differs", "relink", relinkId);
1692
1775
  const id = relinkId ?? item.runtime.id;
1693
- // 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.
1694
1777
  const contentRevision = issue(id, (old?.contentRevision ?? -1) + 1);
1695
- // 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.
1696
1779
  const provider = relinkId
1697
1780
  ? keepProviderChoices(editor.document.project.sources.find((s) => s.id === relinkId)
1698
1781
  ?.provider, item.runtime.provider, item.runtime.report)
@@ -1715,7 +1798,7 @@ export function createBrowserBridge(options) {
1715
1798
  ...(item.fingerprint ? { fingerprint: item.fingerprint } : {}),
1716
1799
  authoring,
1717
1800
  };
1718
- // 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.
1719
1802
  const lease = registry.put(id, contentRevision, runtime, () => item.dispose());
1720
1803
  leases.push({ id, contentRevision, lease });
1721
1804
  commands.push({
@@ -1766,14 +1849,11 @@ export function createBrowserBridge(options) {
1766
1849
  signal?.removeEventListener("abort", abort);
1767
1850
  }
1768
1851
  }
1769
- /**
1770
- * The proxy conversion running: `preempt` stops it for an export, and `done` settles when it
1771
- * ends.
1772
- */
1852
+ /** The running proxy conversion: `preempt` stops it for an export, `done` settles at its end. */
1773
1853
  let proxyRun = null;
1774
1854
  /**
1775
- * Waits until no export runs and no other proxy is being made, or `signal` aborts, and takes the
1776
- * 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.
1777
1857
  */
1778
1858
  async function proxyTurn(signal) {
1779
1859
  for (;;) {
@@ -1800,6 +1880,23 @@ export function createBrowserBridge(options) {
1800
1880
  },
1801
1881
  };
1802
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
+ }
1803
1900
  let sweptExports = false;
1804
1901
  /** Settles when the running export does. */
1805
1902
  let exportSettled = Promise.resolve();
@@ -1808,7 +1905,7 @@ export function createBrowserBridge(options) {
1808
1905
  throw new EditorError("disposed", "Bridge is disposed", "export");
1809
1906
  if (!sweptExports) {
1810
1907
  sweptExports = true;
1811
- // 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.
1812
1909
  void import("./runtime/output.js").then(({ sweepStaleExports }) => sweepStaleExports());
1813
1910
  }
1814
1911
  if (jobs.size)
@@ -1828,6 +1925,7 @@ export function createBrowserBridge(options) {
1828
1925
  const held = [], map = new Map(), fontStack = [];
1829
1926
  const used = shownSources(compiled.project);
1830
1927
  const drawnResources = drawnEffectResources(compiled.project);
1928
+ refuseDegradedSources(snapshot, compiled.project, used);
1831
1929
  try {
1832
1930
  for (const source of [
1833
1931
  ...compiled.project.sources.filter((s) => used.has(s.id)),
@@ -1865,7 +1963,11 @@ export function createBrowserBridge(options) {
1865
1963
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1866
1964
  videoDecode,
1867
1965
  });
1868
- const renderer = new Engine(new OffscreenCanvas(project.settings.width, project.settings.height), pixels, lib, runtimeAssets, { videoConversion: exportConversion });
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
+ });
1869
1971
  const audio = new AudioWindowSupplier(lib);
1870
1972
  try {
1871
1973
  signal.throwIfAborted();
@@ -1875,7 +1977,7 @@ export function createBrowserBridge(options) {
1875
1977
  signal.throwIfAborted();
1876
1978
  renderer.loadProject(project, "export");
1877
1979
  const refused = renderer.setCaptionFonts(fontStack);
1878
- // Heard once per job, not once per attempt.
1980
+ // Reported once per job, not per attempt.
1879
1981
  if (!fontsReported)
1880
1982
  reportRefusedFonts(refused, "export");
1881
1983
  fontsReported = true;
@@ -1922,6 +2024,10 @@ export function createBrowserBridge(options) {
1922
2024
  supplyFrame: (seconds) => renderer.supply(seconds, { context: context(project, lib) }),
1923
2025
  renderFrame: () => renderer.beginExportFrame(),
1924
2026
  sourceTransfer: () => renderer.sourceTransfer,
2027
+ videoEncoder: attempt.videoEncoder,
2028
+ onSoftwareEncoder: (available) => {
2029
+ retryPolicy.softwareVideoEncoder = available;
2030
+ },
1925
2031
  });
1926
2032
  progress({ phase: "publishing", fraction: 0.99 });
1927
2033
  let artifact;
@@ -1941,9 +2047,16 @@ export function createBrowserBridge(options) {
1941
2047
  videoDecode,
1942
2048
  videoConversion: exportConversion,
1943
2049
  decodeFallbacks: pixels.decodeFallbacks,
2050
+ renderer: renderer.rendererChoice,
1944
2051
  },
1945
2052
  };
1946
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
+ }
1947
2060
  finally {
1948
2061
  await audio.close();
1949
2062
  await renderer.dispose();
@@ -1951,19 +2064,21 @@ export function createBrowserBridge(options) {
1951
2064
  }
1952
2065
  },
1953
2066
  };
2067
+ // The CPU renderer runs no runtime effects, so only exports without them can move there.
2068
+ const retryPolicy = { cpuRenderer: effects.length === 0 };
1954
2069
  const job = new ExportJob(revision, snapshot, backend, () => {
1955
2070
  held.forEach((l) => l.release());
1956
2071
  jobs.delete(job);
1957
- });
2072
+ }, { retry: retryPolicy });
1958
2073
  jobs.add(job);
1959
2074
  exportSettled = job.result.then(() => { }, () => { });
1960
- // 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.
1961
2076
  proxyRun?.preempt.abort(new DOMException("An export takes the proxy's place", "AbortError"));
1962
2077
  return job;
1963
2078
  }
1964
2079
  /**
1965
- * What an export of `snapshot` reads for each source, as the engine selects it: originals, unless
1966
- * `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.
1967
2082
  */
1968
2083
  function exportSelection(snapshot, project, options) {
1969
2084
  if (!decisionBinding)
@@ -2024,10 +2139,6 @@ export function createBrowserBridge(options) {
2024
2139
  relink: (id, file, options) => importFiles([file], { ...options, relinkId: id }),
2025
2140
  importSequence,
2026
2141
  relinkSequence,
2027
- /**
2028
- * Shows another animation of a package source (a dotLottie's), keeping its clips: an undoable
2029
- * document change.
2030
- */
2031
2142
  selectAnimation(id, animation) {
2032
2143
  const descriptor = editor.document.assets[id];
2033
2144
  const source = editor.document.project.sources.find((candidate) => candidate.id === id);
@@ -2071,11 +2182,11 @@ export function createBrowserBridge(options) {
2071
2182
  startExport,
2072
2183
  async importCaptions(file) {
2073
2184
  const generation = editor.generation;
2074
- // 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.
2075
2186
  if (file.size > MAX_CAPTION_FILE_BYTES)
2076
2187
  throw new EditorError("invalid_captions", `${file.name} is ${file.size} bytes; a subtitle file is read up to ${MAX_CAPTION_FILE_BYTES}`, "import");
2077
2188
  const { parseCaptions } = await loadWasm();
2078
- const text = await file.text();
2189
+ const text = await readUserText(file);
2079
2190
  let imported;
2080
2191
  try {
2081
2192
  imported = JSON.parse(parseCaptions(text, /\.vtt$/i.test(file.name) ? "webvtt" : "srt"));
@@ -2116,14 +2227,10 @@ export function createBrowserBridge(options) {
2116
2227
  },
2117
2228
  async measureLayout(generator, time = 0) {
2118
2229
  const { width, height } = await draftMeasurer();
2119
- // Measured at the canvas size, which its pixel lengths are pixels of.
2230
+ // Measured at the canvas size, whose pixels its lengths are in.
2120
2231
  return JSON.parse(measurer.measureLayout(JSON.stringify(generator), width, height, time, width, height));
2121
2232
  },
2122
2233
  conform,
2123
- /**
2124
- * Makes a proxy of a source whose original this session holds, keeps it, and previews from it
2125
- * wherever the original goes offline, or while preview prefers proxies.
2126
- */
2127
2234
  async generateProxy(id, { signal } = {}) {
2128
2235
  const descriptor = editor.document.assets[id];
2129
2236
  // No single video file for the proxy maker to read.
@@ -2141,12 +2248,12 @@ export function createBrowserBridge(options) {
2141
2248
  let hold = null;
2142
2249
  try {
2143
2250
  for (;;) {
2144
- // 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.
2145
2252
  const turn = await proxyTurn(signal);
2146
2253
  try {
2147
- // 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.
2148
2255
  hold = await proxyStore.hold(hash);
2149
- // Listeners hear each whole percent once.
2256
+ // Notify listeners once per whole percent.
2150
2257
  let percent = 0;
2151
2258
  const found = await proxyStore.generate(runtime.file, descriptor.fingerprint, {
2152
2259
  signal: signal
@@ -2184,15 +2291,10 @@ export function createBrowserBridge(options) {
2184
2291
  proxyJobs.delete(id);
2185
2292
  notifyAssets();
2186
2293
  }
2187
- // 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.
2188
2295
  if (engine && !playing)
2189
2296
  refreshPreview();
2190
2297
  },
2191
- /**
2192
- * Shows node `nodeId` of composition `compositionId` in the viewer instead of the composition's
2193
- * output, rendered by the same engine compiler; `null` shows the outputs again. Preview only:
2194
- * the document and export are unchanged.
2195
- */
2196
2298
  setPreviewOutput(target) {
2197
2299
  const next = target
2198
2300
  ? { compositionId: target.compositionId, nodeId: target.nodeId }
@@ -2207,11 +2309,6 @@ export function createBrowserBridge(options) {
2207
2309
  get previewOutput() {
2208
2310
  return previewOutput;
2209
2311
  },
2210
- /**
2211
- * Makes preview read a fresh proxy wherever a source has one (`proxies`), or the original
2212
- * wherever it is online (`original`, the default). Preview only: an export reads what its own
2213
- * `media` says.
2214
- */
2215
2312
  setPreviewMedia(media) {
2216
2313
  if (media !== "original" && media !== "proxies")
2217
2314
  throw Error("Preview media must be original or proxies");
@@ -2226,10 +2323,6 @@ export function createBrowserBridge(options) {
2226
2323
  return preferredPreviewMedia;
2227
2324
  },
2228
2325
  hasOriginal: (id) => !!originalOf(editor.document, id),
2229
- /**
2230
- * Which video codecs this browser encodes for an export of the current document at
2231
- * `videoQuality`: the question an export asks before it opens its encoder.
2232
- */
2233
2326
  async videoEncoders({ videoQuality } = {}) {
2234
2327
  await decisions();
2235
2328
  const { probeEncoders } = await import("./runtime/exporter.js");
@@ -2239,7 +2332,6 @@ export function createBrowserBridge(options) {
2239
2332
  videoQuality,
2240
2333
  });
2241
2334
  },
2242
- /** Whether a source has a kept proxy, and the progress of one being made. */
2243
2335
  proxyStatus(id) {
2244
2336
  const descriptor = editor.document.assets[id];
2245
2337
  const hash = hashOf(descriptor);
@@ -2249,17 +2341,7 @@ export function createBrowserBridge(options) {
2249
2341
  reading: previewSelection.get(id)?.media ?? "original",
2250
2342
  };
2251
2343
  },
2252
- /**
2253
- * The proxies this browser keeps, for every project: each original's hash and the bytes its
2254
- * proxy takes.
2255
- */
2256
2344
  listProxies: () => proxyStore.list(),
2257
- /**
2258
- * Removes the kept proxies of `hashes`. This session lets go of its own first and refreshes the
2259
- * preview; a proxy still read after that (by the preview, for a source whose original is
2260
- * offline, by an export of this session, or by another page of the origin) is left and listed
2261
- * in `inUse`.
2262
- */
2263
2345
  async removeProxies(hashes) {
2264
2346
  const wanted = new Set(hashes);
2265
2347
  const unlocked = [];
@@ -2284,7 +2366,7 @@ export function createBrowserBridge(options) {
2284
2366
  throw compiled.diagnostics[0];
2285
2367
  await discoverProxies(snapshot);
2286
2368
  await decisions();
2287
- // 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.
2288
2370
  materializeText(snapshot);
2289
2371
  requireShownText(snapshot, compiled.project);
2290
2372
  const selection = exportSelection(snapshot, compiled.project, options);
@@ -2305,7 +2387,7 @@ export function createBrowserBridge(options) {
2305
2387
  : acquireOwned(snapshot, asset);
2306
2388
  held.push(lease);
2307
2389
  const runtime = lease.value;
2308
- // An image sequence is its frames' files, each uploaded under its locator.
2390
+ // An image sequence uploads each frame file under its locator.
2309
2391
  if (!proxied && runtime.frameFiles) {
2310
2392
  for (const [locator, file] of runtime.frameFiles)
2311
2393
  result.push({
@@ -2377,13 +2459,22 @@ export function createBrowserBridge(options) {
2377
2459
  setMonitorVolume(value) {
2378
2460
  if (!Number.isFinite(value) || value < 0 || value > 1)
2379
2461
  throw Error("Monitor volume must be between 0 and 1");
2380
- // 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.
2381
2463
  monitorVolume = value;
2382
2464
  mixer?.setMasterVolume(value);
2383
2465
  },
2384
2466
  get monitorVolume() {
2385
2467
  return monitorVolume;
2386
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
+ },
2387
2478
  setTraceUploads(value) {
2388
2479
  traceUploads = value === true;
2389
2480
  applyTracing();
@@ -2397,7 +2488,7 @@ export function createBrowserBridge(options) {
2397
2488
  },
2398
2489
  setPreviewScale,
2399
2490
  get diagnostics() {
2400
- // 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.
2401
2492
  const snapshot = workerPreview
2402
2493
  ? workerDiagnostics
2403
2494
  : (engine?.lastDiagnostics ?? null);
@@ -2410,6 +2501,7 @@ export function createBrowserBridge(options) {
2410
2501
  skippedRequests,
2411
2502
  bitmapTransfers,
2412
2503
  previewScale,
2504
+ audioLatencySource: mixer?.latencySource ?? null,
2413
2505
  },
2414
2506
  };
2415
2507
  },
@@ -2443,36 +2535,28 @@ export function createBrowserBridge(options) {
2443
2535
  return engine?.catalog ?? null;
2444
2536
  },
2445
2537
  registerEffects,
2446
- // A source's own media while it is online, whichever preview reads: its size, file and peaks
2447
- // 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.
2448
2540
  getAsset: (id) => (preferredPreviewMedia === "proxies" &&
2449
2541
  sourceView(editor.draft, id, originalOf(editor.draft, id))) ||
2450
2542
  library.get(id),
2451
2543
  };
2452
2544
  }
2453
- /**
2454
- * `scale` as a preview resolution scale: finite, above 0 and at most 8, as the engine's quality
2455
- * profile takes it.
2456
- */
2545
+ /** `scale` checked as a preview resolution scale: finite, above 0 and at most 8. */
2457
2546
  function checkedPreviewScale(scale) {
2458
2547
  if (typeof scale !== "number" || !(scale > 0 && scale <= 8))
2459
2548
  throw new EditorError("invalid_preview_scale", "The preview scale must be a number above 0 and at most 8", "preview");
2460
2549
  return scale;
2461
2550
  }
2462
- /** `value` as who converts decoded SDR frames: `engine` or `browser`. */
2463
2551
  function checkedVideoConversion(value, operation) {
2464
2552
  if (value !== "engine" && value !== "browser")
2465
2553
  throw new EditorError("invalid_video_conversion", `videoConversion must be "engine" or "browser"; received ${JSON.stringify(value)}`, operation);
2466
2554
  return value;
2467
2555
  }
2468
- /**
2469
- * Whether the engine draws a source itself, so no file backs it: a generated source or a
2470
- * composition.
2471
- */
2556
+ /** Whether the engine draws a source itself with no backing file (generated or a composition). */
2472
2557
  function drawnByEngine(source) {
2473
2558
  return source.kind === "generated" || source.kind === "composition";
2474
2559
  }
2475
- /** Waits for `promise`, or rejects when `signal` aborts first. */
2476
2560
  function settledOrAborted(promise, signal) {
2477
2561
  if (!signal)
2478
2562
  return promise;