@alpha2-sh/editor 0.4.6 → 0.5.1

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 +393 -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 +52 -28
  12. package/dist/browser/runtime/assets.js +136 -45
  13. package/dist/browser/runtime/audio.d.ts +16 -11
  14. package/dist/browser/runtime/audio.js +102 -59
  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 +44 -44
  20. package/dist/browser/runtime/engine.js +87 -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 +19 -19
  37. package/dist/browser/runtime/proxies.js +72 -51
  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 +244 -239
  51. package/dist/browser/worker.d.ts +10 -10
  52. package/dist/browser/worker.js +64 -22
  53. package/dist/core/captions.d.ts +8 -10
  54. package/dist/core/captions.js +10 -18
  55. package/dist/core/clip-time.d.ts +8 -10
  56. package/dist/core/clip-time.js +12 -15
  57. package/dist/core/commands.d.ts +46 -46
  58. package/dist/core/commands.js +38 -36
  59. package/dist/core/compositions.d.ts +78 -112
  60. package/dist/core/compositions.js +66 -94
  61. package/dist/core/document.d.ts +59 -92
  62. package/dist/core/document.js +65 -90
  63. package/dist/core/keyframes.d.ts +11 -12
  64. package/dist/core/keyframes.js +11 -13
  65. package/dist/core/presets.d.ts +14 -20
  66. package/dist/core/presets.js +12 -18
  67. package/dist/core/session.d.ts +26 -38
  68. package/dist/core/session.js +38 -53
  69. package/dist/core/text.d.ts +2 -3
  70. package/dist/core/text.js +2 -3
  71. package/dist/core/timeline-index.d.ts +2 -3
  72. package/dist/core/timeline-index.js +11 -7
  73. package/dist/core/transitions.js +4 -5
  74. package/dist/core/validated.d.ts +6 -7
  75. package/dist/core/validated.js +8 -11
  76. package/dist/native-client/index.d.ts +31 -32
  77. package/dist/native-client/index.js +40 -41
  78. package/dist/ports/index.d.ts +19 -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
@@ -298,12 +297,16 @@ export function createBrowserBridge(options) {
298
297
  const descriptor = document.assets[source.id];
299
298
  const record = proxies.get(hashOf(descriptor))?.record;
300
299
  const revision = descriptor?.contentRevision ?? 0;
300
+ const original = originalOf(document, source.id);
301
301
  return {
302
302
  source_id: source.id,
303
303
  revision,
304
- original: originalOf(document, source.id)
304
+ original: original
305
305
  ? { state: "online", fingerprint: descriptor?.fingerprint ?? {} }
306
306
  : { state: "offline" },
307
+ ...(original?.audioStreams
308
+ ? { audio_streams: original.audioStreams }
309
+ : {}),
307
310
  proxies: record
308
311
  ? [
309
312
  {
@@ -321,9 +324,8 @@ export function createBrowserBridge(options) {
321
324
  /** Proxies being adopted, by hash, so two callers share one adoption. */
322
325
  const adopting = new Map();
323
326
  /**
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.
327
+ * Adopts a kept proxy, staging its file like any import under its own ID. `hold` (the store's)
328
+ * keeps the proxy in use until the runtime is disposed.
327
329
  */
328
330
  function adoptProxy(hash, found, hold) {
329
331
  if (proxies.has(hash)) {
@@ -338,7 +340,7 @@ export function createBrowserBridge(options) {
338
340
  pending = (async () => {
339
341
  let staged;
340
342
  try {
341
- // A proxy is known by its original's hash; hashing its own bytes again would be wasted.
343
+ // Proxies are keyed by their original's hash, so skip hashing their own bytes.
342
344
  staged = await mediaAdapter.stage(found.file, new AbortController().signal, { fingerprint: false });
343
345
  }
344
346
  catch (error) {
@@ -369,15 +371,9 @@ export function createBrowserBridge(options) {
369
371
  adopting.set(hash, pending);
370
372
  return pending;
371
373
  }
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
- */
374
+ /** Hashes with no stored proxy, not asked again this session. */
376
375
  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
- */
376
+ /** Finds kept proxies for offline sources, and for every source while preview prefers proxies. */
381
377
  async function discoverProxies(document) {
382
378
  for (const source of document.project.sources) {
383
379
  const descriptor = document.assets[source.id];
@@ -388,7 +384,7 @@ export function createBrowserBridge(options) {
388
384
  (preferredPreviewMedia === "original" &&
389
385
  originalOf(document, source.id)))
390
386
  continue;
391
- // Held before it is read, so no page removes it between.
387
+ // Hold before reading so no other page removes it in between.
392
388
  const hold = await proxyStore.hold(hash);
393
389
  const found = await proxyStore.find(hash).catch(() => null);
394
390
  if (found)
@@ -399,7 +395,6 @@ export function createBrowserBridge(options) {
399
395
  }
400
396
  }
401
397
  }
402
- /** Whether `document`'s media is ready for `purpose`, as the engine decides. */
403
398
  async function conform(purpose, document = editor.document) {
404
399
  await discoverProxies(document);
405
400
  const binding = await decisions();
@@ -417,15 +412,14 @@ export function createBrowserBridge(options) {
417
412
  for (const listener of assetListeners)
418
413
  listener();
419
414
  };
420
- /** The waveform analysis running for each runtime, to abort when the runtime is let go. */
415
+ /** Running waveform analyses by runtime, aborted when the runtime is released. */
421
416
  const analyses = new Map();
422
417
  /** Whether this session still holds `runtime` for some document it can show. */
423
418
  const held = (runtime) => [...owners.values()].some((owner) => owner.lease.value === runtime);
424
419
  /**
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.
420
+ * Derives waveform peaks after import, one file at a time, so imports commit as soon as media is
421
+ * readable. The analysis belongs to the runtime, not the importing document, and is dropped only
422
+ * when the runtime is released.
429
423
  */
430
424
  const analyze = (runtime) => {
431
425
  if (!runtime.file ||
@@ -456,21 +450,21 @@ export function createBrowserBridge(options) {
456
450
  };
457
451
  const jobs = new Set();
458
452
  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.
453
+ // Set when the worker failed for a reason other than GPU loss; later previews for this binding
454
+ // stay on the main thread.
461
455
  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.
456
+ // How playback was requested, so a recovered preview resumes it the same way.
457
+ 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,
458
+ // User A/V offset for output delay the browser does not report.
459
+ audioOffsetMs = 0,
460
+ // Tracing settings, applied to every renderer a binding makes.
467
461
  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.
462
+ // The worker's last renderer diagnostics, plus counters since `bindPreview`: refreshes that
463
+ // needed no frame, and frames copied to the bound canvas.
470
464
  workerDiagnostics = null, skippedRequests = 0, bitmapTransfers = 0, playGeneration = 0, sessionGeneration = editor.generation;
471
465
  /**
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.
466
+ * Preview's media for a source: what the engine selected (the original unless offline), opened
467
+ * with the document's provider settings.
474
468
  */
475
469
  function previewMedia(document, id) {
476
470
  const descriptor = document.assets[id];
@@ -484,10 +478,7 @@ export function createBrowserBridge(options) {
484
478
  }
485
479
  const library = { get: (id) => previewMedia(editor.draft, id) };
486
480
  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
- */
481
+ /** Font families a text style draws with: imported fonts by their registered family. */
491
482
  function familiesOf(document, text) {
492
483
  return (text?.fontFamily ?? "sans-serif").split(",").map((name) => {
493
484
  const plain = name.trim().replace(/^["']|["']$/g, "");
@@ -495,10 +486,7 @@ export function createBrowserBridge(options) {
495
486
  return (font && ownerOf(document, font)?.lease.value.family) ?? plain;
496
487
  });
497
488
  }
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
- */
489
+ /** Which runtime `asset` reads: media by content revision, text by authoring and fonts. */
502
490
  function ownerKey(document, asset) {
503
491
  return asset.kind === "text"
504
492
  ? JSON.stringify([
@@ -512,10 +500,7 @@ export function createBrowserBridge(options) {
512
500
  function ownerOf(document, asset) {
513
501
  return owners.get(ownerKey(document, asset)) ?? null;
514
502
  }
515
- /**
516
- * A lease on the runtime `asset` of `document` reads, for work that outlives the owner's hold on
517
- * it.
518
- */
503
+ /** A lease on the runtime `asset` reads, for work that outlives the owner's hold. */
519
504
  function acquireOwned(document, asset) {
520
505
  const owner = asset && ownerOf(document, asset);
521
506
  if (!owner && asset?.kind === "text")
@@ -530,12 +515,11 @@ export function createBrowserBridge(options) {
530
515
  throw new EditorError("missing_asset", `${editor.document.assets[id]?.name ?? id} has no proxy in this session`, "resource", id);
531
516
  return registry.acquire(`proxy:${hash}`, proxy.revision);
532
517
  }
533
- /** Runtime views by runtime, then by provider settings, so one choice is one value. */
518
+ /** Runtime views by runtime, then provider settings, so each choice maps to one value. */
534
519
  const views = new WeakMap();
535
520
  /**
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.
521
+ * `runtime` opened with document `id`'s provider settings (a package's animation, an OpenEXR
522
+ * still's primaries), so undo and redo change what is drawn.
539
523
  */
540
524
  function sourceView(document, id, runtime) {
541
525
  if (!runtime?.provider)
@@ -557,8 +541,8 @@ export function createBrowserBridge(options) {
557
541
  return view;
558
542
  }
559
543
  /**
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.
544
+ * Runs `fn` after queued preview work. Its failure goes only to the caller, which reports it to
545
+ * whoever awaits it, or to `onError` for work the bridge started itself.
562
546
  */
563
547
  const enqueue = (fn) => {
564
548
  const next = queue.then(() => {
@@ -578,8 +562,14 @@ export function createBrowserBridge(options) {
578
562
  return asset?.kind === "text" ? { id, kind: "image", asset } : asset;
579
563
  },
580
564
  });
565
+ // Preview needs the engine module and canvases, not a GPU: without one it renders on the CPU.
581
566
  const features = Object.freeze({
582
- preview: { available: typeof OffscreenCanvas !== "undefined" },
567
+ preview: {
568
+ available: typeof WebAssembly !== "undefined" &&
569
+ typeof OffscreenCanvas !== "undefined" &&
570
+ typeof VideoFrame !== "undefined",
571
+ reason: "Preview needs WebAssembly, OffscreenCanvas and WebCodecs; it renders on the CPU where the browser offers no hardware GPU",
572
+ },
583
573
  audioPreview: {
584
574
  available: typeof SharedArrayBuffer !== "undefined" &&
585
575
  globalThis.crossOriginIsolated === true,
@@ -591,16 +581,18 @@ export function createBrowserBridge(options) {
591
581
  reason: "Provide a bundled workerFactory; otherwise the main-thread adapter is used",
592
582
  },
593
583
  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",
584
+ available: typeof WebAssembly !== "undefined" &&
585
+ typeof OffscreenCanvas !== "undefined" &&
586
+ typeof VideoEncoder !== "undefined",
587
+ 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
588
  },
597
589
  });
598
- /** The page's capability report; the GPU and color are known once a preview is bound. */
590
+ /** The page's capability report; GPU and color are known once a preview is bound. */
599
591
  let capabilities = capabilityReport(null);
600
592
  function capabilityReport(rendered) {
601
593
  return Object.freeze({
602
594
  schema: "alpha2-capabilities",
603
- version: 1,
595
+ version: 2,
604
596
  runtime: "browser",
605
597
  gpu: rendered?.gpu ?? null,
606
598
  color: rendered?.color ?? null,
@@ -612,25 +604,18 @@ export function createBrowserBridge(options) {
612
604
  decode: null,
613
605
  encode: null,
614
606
  features,
607
+ adapters: null,
608
+ renderer: rendered?.renderer ?? null,
615
609
  });
616
610
  }
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
- */
611
+ /** Raster failures by {@link ownerKey}; not retried until authoring or fonts change. */
621
612
  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
- */
613
+ /** The error a render fails with when it shows text `asset` that could not be rasterized. */
626
614
  function undrawnText(document, asset) {
627
615
  const failure = textFailures.get(ownerKey(document, asset));
628
616
  return new EditorError("text_unrenderable", `Text "${asset.name}" cannot be drawn: ${failure?.message ?? "it was not rasterized"}`, "resource", asset.id);
629
617
  }
630
- /**
631
- * Fails with {@link undrawnText} when `project`, compiled from `document`, shows a text that
632
- * could not be drawn.
633
- */
618
+ /** Throws {@link undrawnText} when compiled `project` shows text that could not be drawn. */
634
619
  function requireShownText(document, project) {
635
620
  const used = shownSources(project);
636
621
  for (const asset of Object.values(document.assets))
@@ -640,9 +625,9 @@ export function createBrowserBridge(options) {
640
625
  throw undrawnText(document, asset);
641
626
  }
642
627
  /**
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.
628
+ * Rasterizes each text of `document` that no held runtime draws yet (new authoring, or a font
629
+ * that now resolves to another family). A text that cannot be drawn (too large for a texture,
630
+ * say) is recorded, not thrown, and fails only renders that show it.
646
631
  */
647
632
  function materializeText(document) {
648
633
  for (const asset of Object.values(document.assets)) {
@@ -670,7 +655,7 @@ export function createBrowserBridge(options) {
670
655
  }
671
656
  }
672
657
  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.
658
+ // Node shown instead of a composition's output; preview only.
674
659
  let previewOutput = null;
675
660
  const withPreviewOutput = (project) => {
676
661
  if (!previewOutput)
@@ -685,12 +670,8 @@ export function createBrowserBridge(options) {
685
670
  };
686
671
  };
687
672
  /**
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.
673
+ * Reports each font of a registered stack the engine could not parse. It was left out, and
674
+ * captions and SVG text fall back to the fonts after it.
694
675
  */
695
676
  function reportRefusedFonts(refused, operation) {
696
677
  for (const { font, error } of refused ?? [])
@@ -701,16 +682,13 @@ export function createBrowserBridge(options) {
701
682
  ...(runtimeAssets.fonts ?? []),
702
683
  ];
703
684
  /**
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.
685
+ * The document's font assets this session holds a file for. Unlinked fonts are left out of the
686
+ * stack by preview and exports alike, never refused.
706
687
  */
707
688
  function heldFonts(document) {
708
689
  return Object.values(document.assets).filter((a) => a.kind === "font" && !a.missing && ownerOf(document, a));
709
690
  }
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
- */
691
+ /** Loads `measurer` with preview's fonts for the draft and returns the draft's canvas size. */
714
692
  async function draftMeasurer() {
715
693
  const { WasmTextMeasurer } = await loadWasm();
716
694
  if (disposed)
@@ -719,7 +697,7 @@ export function createBrowserBridge(options) {
719
697
  const fonts = fontStackOf(document);
720
698
  measurer ??= new WasmTextMeasurer();
721
699
  if (!sameList(measuredFonts, fonts)) {
722
- // A font the engine refuses is left out here as preview leaves it out, and reported there.
700
+ // Refused fonts are left out here as preview does, and reported there.
723
701
  registerCaptionFonts(measurer, fonts);
724
702
  measuredFonts = fonts;
725
703
  }
@@ -758,7 +736,6 @@ export function createBrowserBridge(options) {
758
736
  previewConformKey = conformKey;
759
737
  }
760
738
  const selectionKey = JSON.stringify([...previewSelection]);
761
- // `proxyStatus` reports what preview reads.
762
739
  if (selectionKey !== before)
763
740
  notifyAssets();
764
741
  const used = shownSources(compiled.project);
@@ -776,12 +753,12 @@ export function createBrowserBridge(options) {
776
753
  throw new EditorError("missing_asset", `Relink ${document.assets[resource.id]?.name ?? resource.id} before preview`, "preview", resource.id);
777
754
  const allFonts = fontStackOf(document);
778
755
  const key = renderKeyOf(document);
779
- // Audio is configured once the edit settles: sound only plays after a gesture.
756
+ // Configure audio once the edit settles; sound only plays after a gesture anyway.
780
757
  const settled = document === editor.document;
781
758
  if (renderKey !== key || loadedSelection !== selectionKey) {
782
759
  mixer.stop();
783
760
  engine.invalidate();
784
- // Keep decoders warm: only a source whose runtime changed is reopened.
761
+ // Keep decoders warm by reopening only sources whose runtime changed.
785
762
  const reads = new Map(Object.values(document.assets).map((a) => [
786
763
  a.id,
787
764
  previewMedia(document, a.id),
@@ -801,8 +778,12 @@ export function createBrowserBridge(options) {
801
778
  reportRefusedFonts(refused, "preview");
802
779
  }
803
780
  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.
781
+ if (onCpu())
782
+ reportCpuEffects(engine.projectRuntimeEffects());
783
+ // A worker given up for one project is tried again for the next.
784
+ if (renderKey !== null && !workerPreview)
785
+ workerGivenUp = false;
786
+ // Frames and surfaces are the document size times the preview scale, rounded by the engine.
806
787
  let renderSize = engine.previewSize;
807
788
  engine.resize(renderSize[0], renderSize[1]);
808
789
  // Sources are fitted in document space; the render scales them.
@@ -815,14 +796,14 @@ export function createBrowserBridge(options) {
815
796
  ]
816
797
  .map((source) => [source.id, previewMedia(document, source.id)])
817
798
  .filter(([, asset]) => asset);
818
- // The worker keeps runtime assets it already holds; only new or changed ones are sent.
799
+ // The worker keeps assets it already holds; only new or changed ones are sent.
819
800
  const keep = used
820
801
  .filter(([id, asset]) => workerSent.get(id) === asset)
821
802
  .map(([id]) => id);
822
803
  const kept = new Set(keep);
823
804
  const workerAssets = used
824
805
  .filter(([id]) => !kept.has(id))
825
- // Keyed by the source it serves: a proxy's runtime has an ID of its own.
806
+ // Keyed by the source it serves, since a proxy's runtime has its own ID.
826
807
  .map(([id, asset]) => {
827
808
  const data = { id };
828
809
  for (const field of [
@@ -845,7 +826,7 @@ export function createBrowserBridge(options) {
845
826
  return data;
846
827
  });
847
828
  const sendFonts = !sameList(workerFonts, allFonts);
848
- // Until the worker confirms, what it holds is unknown: a failed load resends everything.
829
+ // Unknown until the worker confirms, so a failed load resends everything.
849
830
  workerSent = new Map();
850
831
  workerFonts = null;
851
832
  try {
@@ -888,19 +869,18 @@ export function createBrowserBridge(options) {
888
869
  }
889
870
  scheduleSweep();
890
871
  scheduleTextReports();
891
- // A drag changes the draft on every pointer move; the preview follows at most once a frame.
872
+ // Drags change the draft on every pointer move; follow at most once a frame.
892
873
  if (engine && !refreshFrame)
893
874
  refreshFrame = nextFrame(refresh);
894
875
  });
895
- /** The font stack each SVG runtime's report was last computed with. */
896
876
  const reportedFonts = new WeakMap();
897
- /** Aborted when the bridge is disposed: work it started for no caller (text reports) stops. */
877
+ /** Aborted on dispose, stopping work started for no caller (text reports). */
898
878
  const lifetime = new AbortController();
899
879
  let textReports = Promise.resolve(), textReportsQueued = false;
900
880
  /**
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.
881
+ * An SVG's report lists text no font draws (`missing_font`). Import probes with no fonts, so the
882
+ * report is recomputed whenever the SVG or its font stack changes, and `subscribeAssets` hears of
883
+ * changes.
904
884
  */
905
885
  function scheduleTextReports() {
906
886
  if (textReportsQueued || disposed)
@@ -957,7 +937,7 @@ export function createBrowserBridge(options) {
957
937
  notifyAssets();
958
938
  }
959
939
  let sweepQueued = false;
960
- /** Releases, after the preview work already queued, what no reachable document reads any more. */
940
+ /** Releases, after queued preview work, what no reachable document reads. */
961
941
  function scheduleSweep() {
962
942
  if (sweepQueued || disposed)
963
943
  return;
@@ -971,15 +951,15 @@ export function createBrowserBridge(options) {
971
951
  });
972
952
  }
973
953
  /**
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.
954
+ * Media and proxies stay held while any document the session can return to reads them, so undone
955
+ * imports, relinks and removals come back with their runtime. Text is held only while the
956
+ * document or draft draws it, since authoring recreates it. Leased runtimes (exports, native
957
+ * uploads) stay until released.
978
958
  */
979
959
  function sweep() {
980
960
  const media = new Set(), hashes = new Set(), seen = new Set();
981
961
  for (const document of editor.reachableDocuments()) {
982
- // Shared by commands that leave assets alone, so a long history is read once per media change.
962
+ // Commands that leave assets alone share them, so history is read once per media change.
983
963
  if (seen.has(document.assets))
984
964
  continue;
985
965
  seen.add(document.assets);
@@ -1024,8 +1004,8 @@ export function createBrowserBridge(options) {
1024
1004
  refreshPreview();
1025
1005
  return;
1026
1006
  }
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.
1007
+ // Playback reads the project it started with, so an edit restarts it from the same point, rate,
1008
+ // loop and policy, unless a seek, pause or Play comes first.
1029
1009
  const resume = playRequest;
1030
1010
  pause();
1031
1011
  refreshPreview();
@@ -1053,9 +1033,15 @@ export function createBrowserBridge(options) {
1053
1033
  }).catch(onError);
1054
1034
  }
1055
1035
  let previewIssue = null;
1056
- /** A lost GPU left no renderer and making it again failed; the next render tries again. */
1036
+ /** Sources the last frame showed through the browser's own tone mapping. */
1037
+ let degradedShown = [];
1038
+ /** Rebuilding after GPU loss failed; the next render retries. */
1057
1039
  let recoveryPending = false;
1058
- /** How many times a lost GPU's preview was made again. */
1040
+ /** The recovery rung to try next while `recoveryPending`. */
1041
+ let pendingStep = null;
1042
+ let previewLadder = new GpuRecoveryLadder();
1043
+ /** All recovery rungs failed; nothing draws until the preview is bound again. */
1044
+ let previewUnavailable = false;
1059
1045
  let previewRecoveries = 0;
1060
1046
  const previewListeners = new Set();
1061
1047
  const setPreviewIssue = (issue) => {
@@ -1066,13 +1052,13 @@ export function createBrowserBridge(options) {
1066
1052
  listener();
1067
1053
  };
1068
1054
  /**
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.
1055
+ * Renders the frame at `at`. A composition that cannot draw its output yet keeps the previous
1056
+ * frame up with `previewIssue` set, rather than failing.
1071
1057
  */
1072
1058
  async function renderAt(at, project, recovered = false) {
1073
1059
  try {
1074
- const rendered = await renderFrame(at, project);
1075
- setPreviewIssue(null);
1060
+ const rendered = await renderFrame(at, project, recovered);
1061
+ setPreviewIssue(degradedShown.length > 0 ? DEGRADED_PREVIEW_ISSUE : null);
1076
1062
  return rendered;
1077
1063
  }
1078
1064
  catch (error) {
@@ -1080,15 +1066,35 @@ export function createBrowserBridge(options) {
1080
1066
  setPreviewIssue(error.message ?? String(error));
1081
1067
  return false;
1082
1068
  }
1083
- const lost = error?.code === "GPU_DEVICE_LOST" || engine?.deviceLost === true;
1069
+ // A source the preview cannot draw fails every frame it is in; report it once with its own
1070
+ // code and keep the frame up.
1071
+ if (isSourceError(error)) {
1072
+ const issue = error.message ?? String(error);
1073
+ if (issue === previewIssue)
1074
+ return false;
1075
+ setPreviewIssue(issue);
1076
+ throw error;
1077
+ }
1078
+ const lost = error?.code === "GPU_DEVICE_LOST" ||
1079
+ error?.code === "GPU_DEVICE_HUNG" ||
1080
+ engine?.deviceLost === true;
1084
1081
  if (recovered || !lost || !boundCanvas || disposed)
1085
1082
  throw error;
1086
- if (!(await recoverPreview()))
1083
+ // The worker's report travels with its error; the main renderer reads its own.
1084
+ const report = error?.lossReport ??
1085
+ engine?.lossReport() ??
1086
+ lossReportFromJson(undefined, error?.message ?? String(error));
1087
+ // Every rebuild draws on a fresh internal canvas, so no rung needs the lost one.
1088
+ const step = previewLadder.onLoss(report, {
1089
+ kind: "none",
1090
+ webgpuAdapter: false,
1091
+ });
1092
+ if (!(await recoverPreview(step)))
1087
1093
  return false;
1088
1094
  return renderAt(at, await loaded(), true);
1089
1095
  }
1090
1096
  }
1091
- async function renderFrame(at, project) {
1097
+ async function renderFrame(at, project, recovered = false) {
1092
1098
  if (boundCanvas?.style)
1093
1099
  boundCanvas.style.visibility = hasContent(project) ? "visible" : "hidden";
1094
1100
  if (!hasContent(project))
@@ -1098,7 +1104,8 @@ export function createBrowserBridge(options) {
1098
1104
  const result = await workerPreview.seek(at);
1099
1105
  if (result.engineDiagnostics)
1100
1106
  workerDiagnostics = result.engineDiagnostics;
1101
- // An unchanged frame comes without a bitmap: the canvas still shows it.
1107
+ degradedShown = result.degradedSources ?? [];
1108
+ // Unchanged frames come without a bitmap; the canvas still shows them.
1102
1109
  if (result.bitmap) {
1103
1110
  boundCanvas
1104
1111
  .getContext("bitmaprenderer")
@@ -1108,26 +1115,32 @@ export function createBrowserBridge(options) {
1108
1115
  return result.rendered;
1109
1116
  }
1110
1117
  catch (error) {
1111
- if (error?.code === "INCOMPLETE_COMPOSITION")
1118
+ // Give up the worker only for its own faults; source errors would hit the main renderer
1119
+ // too. GPU loss goes to the recovery ladder, and a worker that loses it again on the
1120
+ // recovered frame is let go.
1121
+ if (!isWorkerFault(error) || (isGpuLoss(error) && !recovered))
1112
1122
  throw error;
1113
1123
  // The main renderer has the same project loaded and draws this frame instead.
1114
1124
  await abandonWorker(error);
1115
1125
  }
1116
1126
  }
1117
- const { rendered, unchanged } = await engine.render(at / 120000, {
1127
+ const { rendered, unchanged, degradedSources = [], } = await engine.render(at / 120000, {
1118
1128
  generation: engine.generation,
1119
1129
  context: context(project, library),
1120
1130
  });
1121
- // An unchanged frame was not presented: the bound canvas still shows the last copy.
1131
+ degradedShown = degradedSources;
1132
+ // Unchanged frames were not presented. Copy the frame instead of transferring the canvas:
1133
+ // Chrome on macOS crashes the page when an engine WebGL2 canvas gives up its buffer with
1134
+ // `transferToImageBitmap`.
1122
1135
  if (rendered && !unchanged && copySurface) {
1123
1136
  boundCanvas
1124
1137
  .getContext("bitmaprenderer")
1125
- .transferFromImageBitmap(engine.canvas.transferToImageBitmap());
1138
+ .transferFromImageBitmap(await createImageBitmap(engine.canvas));
1126
1139
  bitmapTransfers += 1;
1127
1140
  }
1128
1141
  return rendered;
1129
1142
  }
1130
- /** Gives the bound canvas the size frames render at, which `size` is, unless it has it. */
1143
+ /** Resizes the bound canvas to the render size if needed. */
1131
1144
  function sizeBoundCanvas(size) {
1132
1145
  if (!boundCanvas || !size)
1133
1146
  return;
@@ -1136,7 +1149,6 @@ export function createBrowserBridge(options) {
1136
1149
  if (boundCanvas.height !== size[1])
1137
1150
  boundCanvas.height = size[1];
1138
1151
  }
1139
- /** Applies the bridge's tracing to the renderers drawing now. */
1140
1152
  function applyTracing() {
1141
1153
  if (engine) {
1142
1154
  engine.traceUploads = traceUploads;
@@ -1147,12 +1159,34 @@ export function createBrowserBridge(options) {
1147
1159
  .catch(() => { });
1148
1160
  }
1149
1161
  /**
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.
1162
+ * Whether a preview worker draw `error` is the worker's fault: fatal (wasm trap, lost or hung
1163
+ * GPU), a codec its decoder refused (falls back to the main thread's media elements), or uncoded.
1164
+ * A source's own coded error is not.
1165
+ */
1166
+ function isWorkerFault(error) {
1167
+ const code = error?.code;
1168
+ return (error?.fatal === true ||
1169
+ typeof code !== "string" ||
1170
+ code === "worker_error" ||
1171
+ code === "unsupported_codec" ||
1172
+ code === "GPU_DEVICE_LOST" ||
1173
+ code === "GPU_DEVICE_HUNG");
1174
+ }
1175
+ /** Whether `error` says the GPU was lost or hung on its work. */
1176
+ function isGpuLoss(error) {
1177
+ return (error?.code === "GPU_DEVICE_LOST" || error?.code === "GPU_DEVICE_HUNG");
1178
+ }
1179
+ /** Whether `error` is a source's coded error, which a redraw would hit again. */
1180
+ function isSourceError(error) {
1181
+ return (!isWorkerFault(error) &&
1182
+ error?.code !== "INCOMPLETE_COMPOSITION" &&
1183
+ !String(error.code).startsWith("GPU_"));
1184
+ }
1185
+ /**
1186
+ * Gives up the preview worker after `error` (failed start, load or draw). Until the next binding
1187
+ * the main renderer, which loads every project the worker does, draws off screen and each frame
1188
+ * is copied to the bound surface. `onError` hears once why, unless the worker lost its GPU, which
1189
+ * recovers silently and lets a rebuilt preview try a worker again.
1156
1190
  */
1157
1191
  async function abandonWorker(error) {
1158
1192
  const failed = workerPreview;
@@ -1163,7 +1197,7 @@ export function createBrowserBridge(options) {
1163
1197
  workerFonts = null;
1164
1198
  copySurface = true;
1165
1199
  await failed.dispose().catch(() => { });
1166
- if (error?.code === "GPU_DEVICE_LOST")
1200
+ if (isGpuLoss(error))
1167
1201
  return;
1168
1202
  workerGivenUp = true;
1169
1203
  const reason = error instanceof Error ? error.message : String(error ?? "");
@@ -1180,7 +1214,7 @@ export function createBrowserBridge(options) {
1180
1214
  engine?.invalidate();
1181
1215
  mixer?.stop();
1182
1216
  const requested = tick;
1183
- // Only a newer seek supersedes this one: `loaded` reads the draft as it is when the task runs.
1217
+ // Only a newer seek supersedes this; `loaded` reads the draft when the task runs.
1184
1218
  return enqueue(async () => {
1185
1219
  if (requested !== tick)
1186
1220
  return false;
@@ -1206,7 +1240,7 @@ export function createBrowserBridge(options) {
1206
1240
  void workerPreview.cancel().catch(onError);
1207
1241
  }
1208
1242
  // 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.
1243
+ // (Firefox without usable output) or a stuck worklet would block Play, so video plays silent.
1210
1244
  let stalledAudio = null;
1211
1245
  /** Whether `starting` settled within the deadline; a rejection propagates. */
1212
1246
  async function audioStarts(starting) {
@@ -1229,9 +1263,9 @@ export function createBrowserBridge(options) {
1229
1263
  return false;
1230
1264
  }
1231
1265
  /**
1232
- * Plays from the current time at `rate` (negative plays backwards) under a playback `policy`: the
1266
+ * Plays from the current time at `rate` (negative plays backwards) under playback `policy`; the
1233
1267
  * 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.
1268
+ * in time is dropped rather than holding the picture.
1235
1269
  */
1236
1270
  async function play(rate = 1, { loop = false, policy = "drop_video_keep_audio" } = {}) {
1237
1271
  if (!Number.isFinite(rate) || rate === 0)
@@ -1243,7 +1277,7 @@ export function createBrowserBridge(options) {
1243
1277
  let audible = (engine?.audible(policy, rate) ?? false) && stalledAudio === null;
1244
1278
  if (audible)
1245
1279
  audible = await audioStarts(mixer.resume());
1246
- // Plays the compiled projection preview shows, never a project the renderer loaded earlier.
1280
+ // Play the compiled projection preview shows, never a project the renderer loaded earlier.
1247
1281
  let project = null;
1248
1282
  await enqueue(async () => {
1249
1283
  if (!engine || generation !== playGeneration)
@@ -1266,13 +1300,13 @@ export function createBrowserBridge(options) {
1266
1300
  playing = true;
1267
1301
  playRequest = { rate, loop, policy };
1268
1302
  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.
1303
+ // The last requested tick and, for a policy that waits for frames, whether it was shown.
1270
1304
  let requested = null, presented = false;
1271
1305
  const step = (now) => {
1272
1306
  if (!playing || disposed || generation !== playGeneration)
1273
1307
  return;
1274
1308
  // 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.
1309
+ // engine falls back to the wall clock while it stands still.
1276
1310
  const heard = audible ? (mixer.tick ?? undefined) : undefined;
1277
1311
  const wanted = clock.step(now, heard, presented);
1278
1312
  tick = wanted.tick;
@@ -1295,9 +1329,8 @@ export function createBrowserBridge(options) {
1295
1329
  .catch(onError);
1296
1330
  return;
1297
1331
  }
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.
1332
+ // The clock requests frame starts, so each frame is asked for once at any refresh rate. A
1333
+ // waiting policy moves on only after the frame is shown; the others drop late frames.
1301
1334
  const due = requested !== tick;
1302
1335
  if (!due)
1303
1336
  skippedRequests += 1;
@@ -1329,9 +1362,8 @@ export function createBrowserBridge(options) {
1329
1362
  pause();
1330
1363
  };
1331
1364
  /**
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`.
1365
+ * Makes the preview's renderer, audio and worker for `canvas`, disposing the previous ones. Runs
1366
+ * in the render queue. Returns false when a later binding or disposal superseded `token`.
1335
1367
  */
1336
1368
  async function buildPreview(canvas, token) {
1337
1369
  pause();
@@ -1343,7 +1375,7 @@ export function createBrowserBridge(options) {
1343
1375
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1344
1376
  });
1345
1377
  const { Engine } = await import("./runtime/engine.js");
1346
- // Until a project loads and gives the render size (see `loaded`).
1378
+ // Until a project loads and sets the render size (see `loaded`).
1347
1379
  canvas.width = editor.document.project.settings.width;
1348
1380
  canvas.height = editor.document.project.settings.height;
1349
1381
  boundCanvas = canvas;
@@ -1351,12 +1383,28 @@ export function createBrowserBridge(options) {
1351
1383
  await workerPreview?.dispose();
1352
1384
  workerPreview = null;
1353
1385
  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 });
1386
+ // The main renderer draws on its own canvas and each frame is copied to the bound one, so a
1387
+ // renderer rebuilt after GPU loss (or the CPU renderer) needs nothing from the page.
1388
+ const copyable = typeof canvas.getContext === "function";
1389
+ const useWorker = features.worker.available && copyable;
1390
+ engine = new Engine(copyable ? new OffscreenCanvas(canvas.width, canvas.height) : canvas, sources, library, runtimeAssets,
1391
+ // In a preview, showing a frame at once matters more than the engine's conversion of it.
1392
+ {
1393
+ unreadableFrames: "present",
1394
+ videoConversion,
1395
+ opaqueEngineFrames,
1396
+ renderer: previewLadder.renderer === "cpu" ? "cpu" : rendererMode,
1397
+ });
1398
+ mixer = new EngineAudioMixer(runtimeAssets, {
1399
+ enabled: audio,
1400
+ onInterrupted: (state) => {
1401
+ if (playing)
1402
+ pause();
1403
+ onError(new EditorError("audio_unavailable", `Audio output was ${state} by the browser or the system; playback paused`, "play"));
1404
+ },
1405
+ });
1359
1406
  mixer.setMasterVolume(monitorVolume);
1407
+ mixer.setLatencyOffset(audioOffsetMs);
1360
1408
  stalledAudio = null;
1361
1409
  supplier = new AudioWindowSupplier(library);
1362
1410
  try {
@@ -1364,10 +1412,9 @@ export function createBrowserBridge(options) {
1364
1412
  engine.setPreviewScale(previewScale);
1365
1413
  capabilities = capabilityReport(engine.capabilityReport());
1366
1414
  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) {
1415
+ // The worker posts frames to the same bitmap renderer, so copying stays on either way.
1416
+ copySurface = copyable;
1417
+ if (useWorker && !workerGivenUp) {
1371
1418
  const workerRuntime = {
1372
1419
  ...(runtimeAssets.wasmUrl
1373
1420
  ? { wasmUrl: String(runtimeAssets.wasmUrl) }
@@ -1382,6 +1429,9 @@ export function createBrowserBridge(options) {
1382
1429
  width: canvas.width,
1383
1430
  height: canvas.height,
1384
1431
  videoConversion,
1432
+ opaqueEngineFrames,
1433
+ // Match the main renderer: the CPU once recovery or `auto` moved there.
1434
+ renderer: onCpu() ? "cpu" : rendererMode,
1385
1435
  });
1386
1436
  // A worker that cannot start leaves the surface to the main renderer.
1387
1437
  try {
@@ -1417,27 +1467,44 @@ export function createBrowserBridge(options) {
1417
1467
  return true;
1418
1468
  }
1419
1469
  /**
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.
1470
+ * Recovers a lost GPU (WebGPU device or WebGL context) silently: the preview is rebuilt on fresh
1471
+ * internal canvases with the renderer `step` names (the binding's `GpuRecoveryLadder` picks the
1472
+ * GPU again after a first external loss, the CPU after a self-caused loss or a second page loss),
1473
+ * and the frame is redrawn. A failed rung moves down the ladder; with none left the preview is
1474
+ * unavailable for this binding, reported once (`preview_unavailable`).
1424
1475
  *
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.
1476
+ * Running playback resumes from the same point, rate, loop and policy once rebuilt, unless a
1477
+ * seek, pause or Play came first. Sound that missed its start deadline is not waited for again.
1429
1478
  */
1430
- async function recoverPreview() {
1479
+ async function recoverPreview(step) {
1431
1480
  recoveryPending = true;
1481
+ pendingStep = step;
1432
1482
  const resume = playing ? playRequest : null;
1433
1483
  const stalled = stalledAudio;
1434
- if (!(await buildPreview(boundCanvas, binding)))
1435
- return false;
1484
+ for (;;) {
1485
+ try {
1486
+ if (!(await buildPreview(boundCanvas, binding)))
1487
+ return false;
1488
+ break;
1489
+ }
1490
+ catch (error) {
1491
+ const next = previewLadder.onRecoveryFailed(pendingStep, error);
1492
+ if (next !== "terminal") {
1493
+ pendingStep = next;
1494
+ continue;
1495
+ }
1496
+ recoveryPending = false;
1497
+ previewUnavailable = true;
1498
+ 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 }));
1499
+ return false;
1500
+ }
1501
+ }
1436
1502
  stalledAudio = stalled;
1437
1503
  recoveryPending = false;
1504
+ pendingStep = null;
1438
1505
  previewRecoveries += 1;
1439
1506
  if (resume) {
1440
- // Queued behind the render that is recovering, which draws the frame first.
1507
+ // Queued behind the recovering render, which draws the frame first.
1441
1508
  const stopped = playGeneration;
1442
1509
  void Promise.resolve()
1443
1510
  .then(() => disposed || playing || playGeneration !== stopped
@@ -1447,9 +1514,23 @@ export function createBrowserBridge(options) {
1447
1514
  }
1448
1515
  return true;
1449
1516
  }
1517
+ /** Whether the main renderer draws on the CPU, where projects drawing runtime effects fail. */
1518
+ function onCpu() {
1519
+ return engine?.rendererChoice?.renderer === "cpu";
1520
+ }
1521
+ /** Drawn runtime effects already reported on the CPU renderer, by `id@version`. */
1522
+ const cpuRefusedEffects = new Set();
1523
+ function reportCpuEffects(keys) {
1524
+ for (const key of keys) {
1525
+ if (cpuRefusedEffects.has(key))
1526
+ continue;
1527
+ cpuRefusedEffects.add(key);
1528
+ 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));
1529
+ }
1530
+ }
1450
1531
  /**
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.
1532
+ * Effects `registerEffects` kept, by `id@version`, with their JSON text in arrival order. Every
1533
+ * renderer the bridge makes registers them.
1453
1534
  */
1454
1535
  const effectDefinitions = new Map();
1455
1536
  const keptEffects = () => [...effectDefinitions.values()].map(({ definition }) => definition);
@@ -1486,16 +1567,15 @@ export function createBrowserBridge(options) {
1486
1567
  }
1487
1568
  for (const [key, entry] of added)
1488
1569
  effectDefinitions.set(key, entry);
1489
- // A frame that drew one of them failed; it draws now.
1570
+ // A frame that used one of them failed; redraw it.
1490
1571
  if (engine)
1491
1572
  refreshPreview();
1492
1573
  });
1493
1574
  }
1494
1575
  /**
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.
1576
+ * Registers kept effects on the main renderer `buildPreview` just started, one at a time. One its
1577
+ * device refuses (kept unbound, so never compiled) is dropped and reported. A device lost
1578
+ * meanwhile drops none, since the next render rebuilds and re-registers.
1499
1579
  */
1500
1580
  async function registerKeptEffects() {
1501
1581
  const kept = [...effectDefinitions];
@@ -1509,18 +1589,14 @@ export function createBrowserBridge(options) {
1509
1589
  onError(result.reason);
1510
1590
  }
1511
1591
  }
1512
- /** Whether a renderer is ready, making it again first if a lost GPU left none. */
1592
+ /** Whether a renderer is ready, rebuilding it first if GPU loss left none. */
1513
1593
  async function previewReady() {
1514
1594
  if (engine)
1515
1595
  return true;
1516
- if (!recoveryPending || !boundCanvas || disposed)
1596
+ if (previewUnavailable || !recoveryPending || !boundCanvas || disposed)
1517
1597
  return false;
1518
- return recoverPreview();
1598
+ return recoverPreview(pendingStep);
1519
1599
  }
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
1600
  async function setPreviewScale(scale) {
1525
1601
  const next = checkedPreviewScale(scale);
1526
1602
  if (next === previewScale)
@@ -1551,6 +1627,9 @@ export function createBrowserBridge(options) {
1551
1627
  const token = ++binding;
1552
1628
  await enqueue(async () => {
1553
1629
  recoveryPending = false;
1630
+ pendingStep = null;
1631
+ previewLadder = new GpuRecoveryLadder();
1632
+ previewUnavailable = false;
1554
1633
  workerGivenUp = false;
1555
1634
  skippedRequests = 0;
1556
1635
  bitmapTransfers = 0;
@@ -1603,14 +1682,12 @@ export function createBrowserBridge(options) {
1603
1682
  stage: (signal) => mediaAdapter.stage(file, signal),
1604
1683
  })), options);
1605
1684
  }
1606
- /** Imports numbered PNGs as one image sequence at `frameRate` (the project's by default). */
1607
1685
  function importSequence(files, { frameRate, missing = "reject", signal } = {}) {
1608
1686
  const rate = frameRate ?? editor.document.project.settings.frame_rate;
1609
1687
  return importUnits([sequenceUnit(files, { frameRate: rate, missing })], {
1610
1688
  signal,
1611
1689
  });
1612
1690
  }
1613
- /** Relinks the image sequence `id` to `files`, staged as the project recorded it. */
1614
1691
  function relinkSequence(id, files, { signal } = {}) {
1615
1692
  const provider = editor.document.project.sources.find((source) => source.id === id)?.provider;
1616
1693
  if (provider?.format !== "image_sequence")
@@ -1633,7 +1710,7 @@ export function createBrowserBridge(options) {
1633
1710
  }
1634
1711
  /**
1635
1712
  * 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.
1713
+ * in order as one undo step. A relink has exactly one unit.
1637
1714
  */
1638
1715
  async function importUnits(units, { signal, relinkId } = {}) {
1639
1716
  if (disposed)
@@ -1649,8 +1726,8 @@ export function createBrowserBridge(options) {
1649
1726
  try {
1650
1727
  if (relinkId && units.length !== 1)
1651
1728
  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.
1729
+ // Staged together, committed in order. The first failure stops the rest and is reported as
1730
+ // the import's error, not the cancellation the others then see.
1654
1731
  let failure = null;
1655
1732
  let next = 0;
1656
1733
  const stageNext = async () => {
@@ -1678,8 +1755,8 @@ export function createBrowserBridge(options) {
1678
1755
  const old = relinkId ? editor.document.assets[relinkId] : null;
1679
1756
  if (relinkId && !old)
1680
1757
  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.
1758
+ // Equal hashes match whatever else differs; without them any differing recorded part means
1759
+ // other media.
1683
1760
  if (old?.fingerprint && item.fingerprint) {
1684
1761
  const match = compareFingerprints(await decisions(), old.fingerprint, item.fingerprint);
1685
1762
  if (match.kind === "mismatch")
@@ -1690,9 +1767,9 @@ export function createBrowserBridge(options) {
1690
1767
  if (old && old.kind !== item.runtime.kind)
1691
1768
  throw new EditorError("relink_conflict", "Media kind differs", "relink", relinkId);
1692
1769
  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.
1770
+ // Above every revision issued, since after an undo the next may match an undone relink's.
1694
1771
  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.
1772
+ // A relink opens as the project chose, not as a fresh import would.
1696
1773
  const provider = relinkId
1697
1774
  ? keepProviderChoices(editor.document.project.sources.find((s) => s.id === relinkId)
1698
1775
  ?.provider, item.runtime.provider, item.runtime.report)
@@ -1715,7 +1792,7 @@ export function createBrowserBridge(options) {
1715
1792
  ...(item.fingerprint ? { fingerprint: item.fingerprint } : {}),
1716
1793
  authoring,
1717
1794
  };
1718
- // Called as a method: an adapter's staged asset may be a class instance.
1795
+ // Call as a method, since a staged asset may be a class instance.
1719
1796
  const lease = registry.put(id, contentRevision, runtime, () => item.dispose());
1720
1797
  leases.push({ id, contentRevision, lease });
1721
1798
  commands.push({
@@ -1766,14 +1843,11 @@ export function createBrowserBridge(options) {
1766
1843
  signal?.removeEventListener("abort", abort);
1767
1844
  }
1768
1845
  }
1769
- /**
1770
- * The proxy conversion running: `preempt` stops it for an export, and `done` settles when it
1771
- * ends.
1772
- */
1846
+ /** The running proxy conversion: `preempt` stops it for an export, `done` settles at its end. */
1773
1847
  let proxyRun = null;
1774
1848
  /**
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.
1849
+ * Waits until no export or other proxy runs (or `signal` aborts) and takes the turn. `signal`
1850
+ * aborts when an export preempts it, and `end()` gives the turn back.
1777
1851
  */
1778
1852
  async function proxyTurn(signal) {
1779
1853
  for (;;) {
@@ -1800,6 +1874,23 @@ export function createBrowserBridge(options) {
1800
1874
  },
1801
1875
  };
1802
1876
  }
1877
+ /**
1878
+ * Refuses an export up front when it shows a source imported for a degraded preview: the engine
1879
+ * would refuse its first frame, and browser tone mapping must not reach a file.
1880
+ */
1881
+ function refuseDegradedSources(document, project, used) {
1882
+ const degraded = project.sources
1883
+ .filter((source) => used.has(source.id) &&
1884
+ originalOf(document, source.id)?.planarDecode === "unavailable")
1885
+ .map((source) => document.assets[source.id]?.name ?? source.id);
1886
+ if (degraded.length === 0)
1887
+ return;
1888
+ const facts = { kind: "video", codec: null, softwareDecoder: "none" };
1889
+ const names = degraded.join(", ");
1890
+ 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, {
1891
+ cause: new PlanarDecodeUnavailableError(`${names}: no planar decode in this browser`, facts),
1892
+ });
1893
+ }
1803
1894
  let sweptExports = false;
1804
1895
  /** Settles when the running export does. */
1805
1896
  let exportSettled = Promise.resolve();
@@ -1808,7 +1899,7 @@ export function createBrowserBridge(options) {
1808
1899
  throw new EditorError("disposed", "Bridge is disposed", "export");
1809
1900
  if (!sweptExports) {
1810
1901
  sweptExports = true;
1811
- // Temporary files a closed page left: a day old at least and held by no page.
1902
+ // Temporary files closed pages left behind, at least a day old and held by no page.
1812
1903
  void import("./runtime/output.js").then(({ sweepStaleExports }) => sweepStaleExports());
1813
1904
  }
1814
1905
  if (jobs.size)
@@ -1828,6 +1919,7 @@ export function createBrowserBridge(options) {
1828
1919
  const held = [], map = new Map(), fontStack = [];
1829
1920
  const used = shownSources(compiled.project);
1830
1921
  const drawnResources = drawnEffectResources(compiled.project);
1922
+ refuseDegradedSources(snapshot, compiled.project, used);
1831
1923
  try {
1832
1924
  for (const source of [
1833
1925
  ...compiled.project.sources.filter((s) => used.has(s.id)),
@@ -1865,7 +1957,11 @@ export function createBrowserBridge(options) {
1865
1957
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1866
1958
  videoDecode,
1867
1959
  });
1868
- const renderer = new Engine(new OffscreenCanvas(project.settings.width, project.settings.height), pixels, lib, runtimeAssets, { videoConversion: exportConversion });
1960
+ // The retry policy picks the renderer: CPU after a self-caused loss or a second page loss.
1961
+ const renderer = new Engine(new OffscreenCanvas(project.settings.width, project.settings.height), pixels, lib, runtimeAssets, {
1962
+ videoConversion: exportConversion,
1963
+ renderer: attempt.renderer === "cpu" ? "cpu" : rendererMode,
1964
+ });
1869
1965
  const audio = new AudioWindowSupplier(lib);
1870
1966
  try {
1871
1967
  signal.throwIfAborted();
@@ -1874,8 +1970,11 @@ export function createBrowserBridge(options) {
1874
1970
  await renderer.registerEffects(effects, "export");
1875
1971
  signal.throwIfAborted();
1876
1972
  renderer.loadProject(project, "export");
1973
+ // Only an export that draws no runtime effect can move to the CPU renderer.
1974
+ retryPolicy.cpuRenderer =
1975
+ renderer.projectRuntimeEffects().length === 0;
1877
1976
  const refused = renderer.setCaptionFonts(fontStack);
1878
- // Heard once per job, not once per attempt.
1977
+ // Reported once per job, not per attempt.
1879
1978
  if (!fontsReported)
1880
1979
  reportRefusedFonts(refused, "export");
1881
1980
  fontsReported = true;
@@ -1922,6 +2021,10 @@ export function createBrowserBridge(options) {
1922
2021
  supplyFrame: (seconds) => renderer.supply(seconds, { context: context(project, lib) }),
1923
2022
  renderFrame: () => renderer.beginExportFrame(),
1924
2023
  sourceTransfer: () => renderer.sourceTransfer,
2024
+ videoEncoder: attempt.videoEncoder,
2025
+ onSoftwareEncoder: (available) => {
2026
+ retryPolicy.softwareVideoEncoder = available;
2027
+ },
1925
2028
  });
1926
2029
  progress({ phase: "publishing", fraction: 0.99 });
1927
2030
  let artifact;
@@ -1941,9 +2044,16 @@ export function createBrowserBridge(options) {
1941
2044
  videoDecode,
1942
2045
  videoConversion: exportConversion,
1943
2046
  decodeFallbacks: pixels.decodeFallbacks,
2047
+ renderer: renderer.rendererChoice,
1944
2048
  },
1945
2049
  };
1946
2050
  }
2051
+ catch (error) {
2052
+ // Count this loss for the page too; the next attempt's policy reads it.
2053
+ if (renderer.deviceLost)
2054
+ pageGpuLosses.add();
2055
+ throw error;
2056
+ }
1947
2057
  finally {
1948
2058
  await audio.close();
1949
2059
  await renderer.dispose();
@@ -1951,19 +2061,21 @@ export function createBrowserBridge(options) {
1951
2061
  }
1952
2062
  },
1953
2063
  };
2064
+ // Narrowed by each attempt once its renderer has loaded the project.
2065
+ const retryPolicy = { cpuRenderer: true };
1954
2066
  const job = new ExportJob(revision, snapshot, backend, () => {
1955
2067
  held.forEach((l) => l.release());
1956
2068
  jobs.delete(job);
1957
- });
2069
+ }, { retry: retryPolicy });
1958
2070
  jobs.add(job);
1959
2071
  exportSettled = job.result.then(() => { }, () => { });
1960
- // A proxy being made yields (encoder, GPU, memory) and is made again once the export ends.
2072
+ // A proxy being made yields the encoder, GPU and memory, and restarts after the export.
1961
2073
  proxyRun?.preempt.abort(new DOMException("An export takes the proxy's place", "AbortError"));
1962
2074
  return job;
1963
2075
  }
1964
2076
  /**
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.
2077
+ * What an export reads for each source, as the engine selects it: originals unless
2078
+ * `options.media` asks for proxies. Refuses before holding anything when the media is not ready.
1967
2079
  */
1968
2080
  function exportSelection(snapshot, project, options) {
1969
2081
  if (!decisionBinding)
@@ -2024,10 +2136,6 @@ export function createBrowserBridge(options) {
2024
2136
  relink: (id, file, options) => importFiles([file], { ...options, relinkId: id }),
2025
2137
  importSequence,
2026
2138
  relinkSequence,
2027
- /**
2028
- * Shows another animation of a package source (a dotLottie's), keeping its clips: an undoable
2029
- * document change.
2030
- */
2031
2139
  selectAnimation(id, animation) {
2032
2140
  const descriptor = editor.document.assets[id];
2033
2141
  const source = editor.document.project.sources.find((candidate) => candidate.id === id);
@@ -2071,11 +2179,11 @@ export function createBrowserBridge(options) {
2071
2179
  startExport,
2072
2180
  async importCaptions(file) {
2073
2181
  const generation = editor.generation;
2074
- // A larger file holds more cues than a project can, so it is not read at all.
2182
+ // A larger file holds more cues than a project can, so refuse it unread.
2075
2183
  if (file.size > MAX_CAPTION_FILE_BYTES)
2076
2184
  throw new EditorError("invalid_captions", `${file.name} is ${file.size} bytes; a subtitle file is read up to ${MAX_CAPTION_FILE_BYTES}`, "import");
2077
2185
  const { parseCaptions } = await loadWasm();
2078
- const text = await file.text();
2186
+ const text = await readUserText(file);
2079
2187
  let imported;
2080
2188
  try {
2081
2189
  imported = JSON.parse(parseCaptions(text, /\.vtt$/i.test(file.name) ? "webvtt" : "srt"));
@@ -2116,14 +2224,10 @@ export function createBrowserBridge(options) {
2116
2224
  },
2117
2225
  async measureLayout(generator, time = 0) {
2118
2226
  const { width, height } = await draftMeasurer();
2119
- // Measured at the canvas size, which its pixel lengths are pixels of.
2227
+ // Measured at the canvas size, whose pixels its lengths are in.
2120
2228
  return JSON.parse(measurer.measureLayout(JSON.stringify(generator), width, height, time, width, height));
2121
2229
  },
2122
2230
  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
2231
  async generateProxy(id, { signal } = {}) {
2128
2232
  const descriptor = editor.document.assets[id];
2129
2233
  // No single video file for the proxy maker to read.
@@ -2141,12 +2245,12 @@ export function createBrowserBridge(options) {
2141
2245
  let hold = null;
2142
2246
  try {
2143
2247
  for (;;) {
2144
- // One proxy at a time, none while an export runs; an export that starts takes its place.
2248
+ // One proxy at a time and none during an export; a starting export preempts it.
2145
2249
  const turn = await proxyTurn(signal);
2146
2250
  try {
2147
- // Held until its runtime is let go, so no page removes it meanwhile.
2251
+ // Held until its runtime is released so no page removes it meanwhile.
2148
2252
  hold = await proxyStore.hold(hash);
2149
- // Listeners hear each whole percent once.
2253
+ // Notify listeners once per whole percent.
2150
2254
  let percent = 0;
2151
2255
  const found = await proxyStore.generate(runtime.file, descriptor.fingerprint, {
2152
2256
  signal: signal
@@ -2184,15 +2288,10 @@ export function createBrowserBridge(options) {
2184
2288
  proxyJobs.delete(id);
2185
2289
  notifyAssets();
2186
2290
  }
2187
- // The next load asks the engine again. Playback is left alone: every source it reads is online.
2291
+ // The next load asks the engine again. Playback reads only online sources, so leave it alone.
2188
2292
  if (engine && !playing)
2189
2293
  refreshPreview();
2190
2294
  },
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
2295
  setPreviewOutput(target) {
2197
2296
  const next = target
2198
2297
  ? { compositionId: target.compositionId, nodeId: target.nodeId }
@@ -2207,11 +2306,6 @@ export function createBrowserBridge(options) {
2207
2306
  get previewOutput() {
2208
2307
  return previewOutput;
2209
2308
  },
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
2309
  setPreviewMedia(media) {
2216
2310
  if (media !== "original" && media !== "proxies")
2217
2311
  throw Error("Preview media must be original or proxies");
@@ -2226,10 +2320,6 @@ export function createBrowserBridge(options) {
2226
2320
  return preferredPreviewMedia;
2227
2321
  },
2228
2322
  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
2323
  async videoEncoders({ videoQuality } = {}) {
2234
2324
  await decisions();
2235
2325
  const { probeEncoders } = await import("./runtime/exporter.js");
@@ -2239,7 +2329,6 @@ export function createBrowserBridge(options) {
2239
2329
  videoQuality,
2240
2330
  });
2241
2331
  },
2242
- /** Whether a source has a kept proxy, and the progress of one being made. */
2243
2332
  proxyStatus(id) {
2244
2333
  const descriptor = editor.document.assets[id];
2245
2334
  const hash = hashOf(descriptor);
@@ -2249,17 +2338,7 @@ export function createBrowserBridge(options) {
2249
2338
  reading: previewSelection.get(id)?.media ?? "original",
2250
2339
  };
2251
2340
  },
2252
- /**
2253
- * The proxies this browser keeps, for every project: each original's hash and the bytes its
2254
- * proxy takes.
2255
- */
2256
2341
  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
2342
  async removeProxies(hashes) {
2264
2343
  const wanted = new Set(hashes);
2265
2344
  const unlocked = [];
@@ -2284,7 +2363,7 @@ export function createBrowserBridge(options) {
2284
2363
  throw compiled.diagnostics[0];
2285
2364
  await discoverProxies(snapshot);
2286
2365
  await decisions();
2287
- // Leased after the waits and before the next, so no release can come between.
2366
+ // Leased after the waits and before the next await, so no release can come between.
2288
2367
  materializeText(snapshot);
2289
2368
  requireShownText(snapshot, compiled.project);
2290
2369
  const selection = exportSelection(snapshot, compiled.project, options);
@@ -2305,7 +2384,7 @@ export function createBrowserBridge(options) {
2305
2384
  : acquireOwned(snapshot, asset);
2306
2385
  held.push(lease);
2307
2386
  const runtime = lease.value;
2308
- // An image sequence is its frames' files, each uploaded under its locator.
2387
+ // An image sequence uploads each frame file under its locator.
2309
2388
  if (!proxied && runtime.frameFiles) {
2310
2389
  for (const [locator, file] of runtime.frameFiles)
2311
2390
  result.push({
@@ -2377,13 +2456,22 @@ export function createBrowserBridge(options) {
2377
2456
  setMonitorVolume(value) {
2378
2457
  if (!Number.isFinite(value) || value < 0 || value > 1)
2379
2458
  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.
2459
+ // Bridge-wide: each preview binding's mixer starts at it.
2381
2460
  monitorVolume = value;
2382
2461
  mixer?.setMasterVolume(value);
2383
2462
  },
2384
2463
  get monitorVolume() {
2385
2464
  return monitorVolume;
2386
2465
  },
2466
+ setAudioOffset(ms) {
2467
+ if (!Number.isFinite(ms) || Math.abs(ms) > 2000)
2468
+ throw Error("Audio offset must be between -2000 and 2000 ms");
2469
+ audioOffsetMs = ms;
2470
+ mixer?.setLatencyOffset(ms);
2471
+ },
2472
+ get audioOffsetMs() {
2473
+ return audioOffsetMs;
2474
+ },
2387
2475
  setTraceUploads(value) {
2388
2476
  traceUploads = value === true;
2389
2477
  applyTracing();
@@ -2397,7 +2485,7 @@ export function createBrowserBridge(options) {
2397
2485
  },
2398
2486
  setPreviewScale,
2399
2487
  get diagnostics() {
2400
- // The renderer that draws: in worker mode the main-thread one does not.
2488
+ // The renderer that draws; in worker mode the main-thread one does not.
2401
2489
  const snapshot = workerPreview
2402
2490
  ? workerDiagnostics
2403
2491
  : (engine?.lastDiagnostics ?? null);
@@ -2410,6 +2498,7 @@ export function createBrowserBridge(options) {
2410
2498
  skippedRequests,
2411
2499
  bitmapTransfers,
2412
2500
  previewScale,
2501
+ audioLatencySource: mixer?.latencySource ?? null,
2413
2502
  },
2414
2503
  };
2415
2504
  },
@@ -2443,36 +2532,28 @@ export function createBrowserBridge(options) {
2443
2532
  return engine?.catalog ?? null;
2444
2533
  },
2445
2534
  registerEffects,
2446
- // A source's own media while it is online, whichever preview reads: its size, file and peaks
2447
- // are the original's.
2535
+ // A source's own media while online, whichever preview reads, so size, file and peaks are the
2536
+ // original's.
2448
2537
  getAsset: (id) => (preferredPreviewMedia === "proxies" &&
2449
2538
  sourceView(editor.draft, id, originalOf(editor.draft, id))) ||
2450
2539
  library.get(id),
2451
2540
  };
2452
2541
  }
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
- */
2542
+ /** `scale` checked as a preview resolution scale: finite, above 0 and at most 8. */
2457
2543
  function checkedPreviewScale(scale) {
2458
2544
  if (typeof scale !== "number" || !(scale > 0 && scale <= 8))
2459
2545
  throw new EditorError("invalid_preview_scale", "The preview scale must be a number above 0 and at most 8", "preview");
2460
2546
  return scale;
2461
2547
  }
2462
- /** `value` as who converts decoded SDR frames: `engine` or `browser`. */
2463
2548
  function checkedVideoConversion(value, operation) {
2464
2549
  if (value !== "engine" && value !== "browser")
2465
2550
  throw new EditorError("invalid_video_conversion", `videoConversion must be "engine" or "browser"; received ${JSON.stringify(value)}`, operation);
2466
2551
  return value;
2467
2552
  }
2468
- /**
2469
- * Whether the engine draws a source itself, so no file backs it: a generated source or a
2470
- * composition.
2471
- */
2553
+ /** Whether the engine draws a source itself with no backing file (generated or a composition). */
2472
2554
  function drawnByEngine(source) {
2473
2555
  return source.kind === "generated" || source.kind === "composition";
2474
2556
  }
2475
- /** Waits for `promise`, or rejects when `signal` aborts first. */
2476
2557
  function settledOrAborted(promise, signal) {
2477
2558
  if (!signal)
2478
2559
  return promise;