@alpha2-sh/editor 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +60 -3
  2. package/dist/browser/bridge.d.ts +5 -4
  3. package/dist/browser/bridge.js +390 -67
  4. package/dist/browser/extensions-worker.d.ts +4 -3
  5. package/dist/browser/extensions-worker.js +13 -6
  6. package/dist/browser/jobs.d.ts +17 -0
  7. package/dist/browser/jobs.js +40 -0
  8. package/dist/browser/resources.d.ts +9 -4
  9. package/dist/browser/resources.js +17 -5
  10. package/dist/browser/runtime/assets.d.ts +14 -2
  11. package/dist/browser/runtime/assets.js +37 -27
  12. package/dist/browser/runtime/audio.d.ts +12 -2
  13. package/dist/browser/runtime/audio.js +124 -14
  14. package/dist/browser/runtime/engine.js +8 -1
  15. package/dist/browser/runtime/exporter.d.ts +2 -1
  16. package/dist/browser/runtime/exporter.js +15 -4
  17. package/dist/browser/runtime/extension-import.d.ts +30 -10
  18. package/dist/browser/runtime/extension-import.js +52 -9
  19. package/dist/browser/runtime/preview-utils.d.ts +12 -0
  20. package/dist/browser/runtime/preview-utils.js +45 -0
  21. package/dist/browser/runtime/sources.d.ts +2 -2
  22. package/dist/browser/runtime/sources.js +23 -40
  23. package/dist/browser/runtime/wasm.d.ts +5 -5
  24. package/dist/browser/runtime/wasm.js +6 -13
  25. package/dist/browser/types.d.ts +138 -26
  26. package/dist/browser/worker.d.ts +4 -2
  27. package/dist/browser/worker.js +75 -25
  28. package/dist/core/commands.d.ts +46 -3
  29. package/dist/core/commands.js +212 -40
  30. package/dist/core/compositions.d.ts +27 -0
  31. package/dist/core/compositions.js +43 -0
  32. package/dist/core/data.d.ts +34 -0
  33. package/dist/core/data.js +69 -0
  34. package/dist/core/document.d.ts +20 -1
  35. package/dist/core/document.js +138 -8
  36. package/dist/core/keyframes.d.ts +3 -2
  37. package/dist/core/keyframes.js +6 -2
  38. package/dist/core/sameness.d.ts +6 -0
  39. package/dist/core/sameness.js +42 -0
  40. package/dist/core/session.d.ts +85 -7
  41. package/dist/core/session.js +124 -13
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.js +1 -0
  44. package/dist/native-client/index.d.ts +2 -2
  45. package/dist/native-client/index.js +2 -2
  46. package/dist/ports/index.d.ts +5 -4
  47. package/package.json +3 -3
@@ -1,23 +1,26 @@
1
1
  import { frameAt, frameStart } from "../core/time.js";
2
- import { compileEditorDocument, EditorError, sequenceEnd, } from "../core/document.js";
2
+ import { compileEditorDocument, EditorError, readsMediaFile, sequenceEnd, } from "../core/document.js";
3
3
  import { captionsAsset } from "../core/captions.js";
4
- import { MAX_CAPTION_FILE_BYTES } from "alpha2/project";
4
+ import { MAX_CAPTION_FILE_BYTES, providerKind, providerReadsFile, } from "alpha2/project";
5
5
  import { containerPolicy } from "alpha2/containers";
6
- import { PlanarDecodeUnavailableError } from "alpha2/hdr-frames";
6
+ import { applyEdit as applyEngineEdit } from "alpha2/apply-edit";
7
+ import { runExtractor } from "alpha2/extract";
8
+ import { loadPlugin } from "alpha2/plugins";
9
+ import { DecodeUnavailableError, PlanarDecodeUnavailableError, } from "alpha2/hdr-frames";
7
10
  import { drawnEffectResources, shownSources } from "../core/compositions.js";
8
11
  import { ResourceRegistry } from "./resources.js";
9
- import { ExportJob, requireExportFrameRate } from "./jobs.js";
12
+ import { ExportJob, ExtractionJob, requireExportFrameRate } from "./jobs.js";
10
13
  import { GpuRecoveryLadder, lossReportFromJson, pageGpuLosses, } from "alpha2/gpu-recovery";
11
14
  import { attemptOptions } from "./runtime/budget.js";
12
15
  import { readUserText } from "./runtime/text.js";
13
16
  import { createWorkerPreview } from "./worker.js";
14
17
  import { registerCaptionFonts } from "./runtime/caption-fonts.js";
15
- import { AssetLibrary, streamPeaks } from "./runtime/assets.js";
18
+ import { AssetLibrary, audioDecoding, streamPeaks } from "./runtime/assets.js";
16
19
  import { SourcePixels, providerSettings, sameProviderSettings, } from "./runtime/sources.js";
17
20
  import { fingerprintFile } from "./runtime/fingerprint.js";
18
21
  import { hashInWorker } from "./hash-worker.js";
19
22
  import { callExtensions } from "./extensions-worker.js";
20
- import { keepProviderChoices, mayBeExtension, providerDocumentLimit, stageProviderFile, stageSequence, } from "./runtime/extension-import.js";
23
+ import { keepProviderChoices, mayBeExtension, providerDocumentLimit, stageProviderFile, stageSequence, extensionWasmUrls, } from "./runtime/extension-import.js";
21
24
  import { ProxyStore } from "./runtime/proxies.js";
22
25
  import { blockingIssues, compareFingerprints, conformProject, sha256Blob, } from "alpha2/assets";
23
26
  /**
@@ -64,18 +67,18 @@ const AUDIO_START_TIMEOUT_MS = 3000;
64
67
  * per file from `extensionsWorkerFactory` (terminated on cancel or past
65
68
  * `EXTENSIONS_CALL_TIMEOUT_MS`), or on this thread without one. Fonts are checked with the engine's
66
69
  * 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]
70
+ * `hashWorkerFactory` worker when given. `hdrWithoutPlanes` says whether HDR video without planes
71
+ * imports degraded or is refused.
72
+ * @param {{ extensionsWasmUrl?: string | URL, extensionModuleUrls?: import("alpha2/extensions").ExtensionWasmUrls, wasmUrl?: string | URL, hashWorkerFactory?: () => Worker, extensionsWorkerFactory?: () => Worker, hdrWithoutPlanes?: "refuse" | "preview-degraded" }} [options]
70
73
  * @returns {import("./types.js").BrowserMediaAdapter}
71
74
  */
72
- export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFactory, extensionsWorkerFactory, hdrWithoutPlanes = "preview-degraded", } = {}) {
75
+ export function createMediaAdapter({ extensionsWasmUrl, extensionModuleUrls, wasmUrl, hashWorkerFactory, extensionsWorkerFactory, hdrWithoutPlanes = "preview-degraded", } = {}) {
73
76
  const hash = hashWorkerFactory
74
77
  ? (file, options) => hashInWorker(hashWorkerFactory, file, options)
75
78
  : sha256Blob;
76
79
  const module = {
77
80
  factory: extensionsWorkerFactory,
78
- wasmUrl: extensionsWasmUrl,
81
+ wasmUrl: extensionWasmUrls({ extensionsWasmUrl, extensionModuleUrls }),
79
82
  };
80
83
  /**
81
84
  * Runs provider `call` on `file`. A refusal becomes `unreadable_media` with its reason;
@@ -227,7 +230,7 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
227
230
  * @returns {import("./types.js").BrowserBridge}
228
231
  */
229
232
  export function createBrowserBridge(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;
233
+ const { editor, runtimeAssets = {}, hdrWithoutPlanes = "preview-degraded", mediaAdapter = createMediaAdapter({ ...runtimeAssets, hdrWithoutPlanes }), resourceLimit = 128, audio = true, workerRequestTimeoutMs, onError = () => { }, assetDecisions, previewScale: initialPreviewScale = 0.5, videoConversion: initialVideoConversion = "engine", } = options;
231
234
  let previewScale = checkedPreviewScale(initialPreviewScale);
232
235
  if (hdrWithoutPlanes !== "refuse" && hdrWithoutPlanes !== "preview-degraded")
233
236
  throw new RangeError('hdrWithoutPlanes must be "refuse" or "preview-degraded"');
@@ -280,7 +283,57 @@ export function createBrowserBridge(options) {
280
283
  /** What preview prefers where a source has a fresh proxy (see `setPreviewMedia`). */
281
284
  let preferredPreviewMedia = "original";
282
285
  const hashOf = (asset) => asset?.fingerprint?.content_sha256;
286
+ /** Runtime views of sources that read no file, by ID, so each keeps one identity. */
287
+ const fileless = new Map();
288
+ /**
289
+ * The runtime a source that reads no file draws from: its own provider settings, which
290
+ * `sourceView` keeps current. `null` for a source whose media is a file. Its report and
291
+ * thumbnail follow the settings, described again whenever they change.
292
+ */
293
+ function filelessRuntime(document, id) {
294
+ const source = document.project.sources.find((each) => each.id === id);
295
+ if (!source || readsMediaFile(source))
296
+ return null;
297
+ let runtime = fileless.get(id);
298
+ if (!runtime)
299
+ fileless.set(id, (runtime = { id, kind: source.kind, provider: source.provider }));
300
+ if (!sameProviderSettings(runtime.described ?? null, source.provider))
301
+ describeInBackground(runtime, source.provider);
302
+ return runtime;
303
+ }
304
+ /** Opens `provider` in the extensions worker for its report and thumbnail. */
305
+ function describeProvider(provider, signal) {
306
+ return callExtensions({
307
+ factory: runtimeAssets.extensionsWorkerFactory,
308
+ wasmUrl: extensionWasmUrls(runtimeAssets),
309
+ }, { call: "describe", provider }, { signal, operation: "describe" });
310
+ }
311
+ function describe(runtime, provider, { report, thumbnail }) {
312
+ Object.assign(runtime, {
313
+ described: provider,
314
+ report,
315
+ thumbnail,
316
+ width: report.width,
317
+ height: report.height,
318
+ });
319
+ }
320
+ function describeInBackground(runtime, provider) {
321
+ if (runtime.describing === provider)
322
+ return;
323
+ runtime.describing = provider;
324
+ describeProvider(provider, lifetime.signal).then((read) => {
325
+ if (disposed || runtime.describing !== provider)
326
+ return;
327
+ describe(runtime, provider, read);
328
+ notifyAssets();
329
+ },
330
+ // A source that does not open reports it when drawn; the next change tries again.
331
+ () => { });
332
+ }
283
333
  const originalOf = (document, id) => {
334
+ const contained = filelessRuntime(document, id);
335
+ if (contained)
336
+ return contained;
284
337
  const descriptor = document.assets[id];
285
338
  if (!descriptor || descriptor.missing)
286
339
  return null;
@@ -341,7 +394,9 @@ export function createBrowserBridge(options) {
341
394
  let staged;
342
395
  try {
343
396
  // Proxies are keyed by their original's hash, so skip hashing their own bytes.
344
- staged = await mediaAdapter.stage(found.file, new AbortController().signal, { fingerprint: false });
397
+ staged = await mediaAdapter.stage(found.file, lifetime.signal, {
398
+ fingerprint: false,
399
+ });
345
400
  }
346
401
  catch (error) {
347
402
  void hold.release();
@@ -356,10 +411,11 @@ export function createBrowserBridge(options) {
356
411
  try {
357
412
  const runtime = { ...staged.runtime, id: `proxy:${hash}` };
358
413
  proxy.revision = issue(runtime.id);
414
+ // At most one proxy per original, so it does not count against the import limit.
359
415
  proxy.lease = registry.put(runtime.id, proxy.revision, runtime, () => {
360
416
  staged.dispose();
361
417
  proxy.unlocked = hold.release();
362
- });
418
+ }, { counted: false });
363
419
  proxies.set(hash, proxy);
364
420
  }
365
421
  catch (error) {
@@ -373,7 +429,12 @@ export function createBrowserBridge(options) {
373
429
  }
374
430
  /** Hashes with no stored proxy, not asked again this session. */
375
431
  let absentProxies = new Set();
376
- /** Finds kept proxies for offline sources, and for every source while preview prefers proxies. */
432
+ /** Kept proxies that failed to adopt, by hash, not tried again in this project. */
433
+ let failedProxies = new Map();
434
+ /**
435
+ * Finds kept proxies for offline sources, and for every source while preview prefers proxies. A
436
+ * proxy that fails to adopt is reported once and its source reads the original.
437
+ */
377
438
  async function discoverProxies(document) {
378
439
  for (const source of document.project.sources) {
379
440
  const descriptor = document.assets[source.id];
@@ -381,17 +442,27 @@ export function createBrowserBridge(options) {
381
442
  if (!hash ||
382
443
  proxies.has(hash) ||
383
444
  absentProxies.has(hash) ||
445
+ failedProxies.has(hash) ||
384
446
  (preferredPreviewMedia === "original" &&
385
447
  originalOf(document, source.id)))
386
448
  continue;
387
449
  // Hold before reading so no other page removes it in between.
388
450
  const hold = await proxyStore.hold(hash);
389
451
  const found = await proxyStore.find(hash).catch(() => null);
390
- if (found)
391
- await adoptProxy(hash, found, hold);
392
- else {
452
+ if (!found) {
393
453
  absentProxies.add(hash);
394
454
  void hold.release();
455
+ continue;
456
+ }
457
+ try {
458
+ await adoptProxy(hash, found, hold);
459
+ }
460
+ catch (error) {
461
+ if (failedProxies.has(hash))
462
+ continue;
463
+ failedProxies.set(hash, error);
464
+ if (!disposed)
465
+ onError(new EditorError("proxy_unavailable", `The kept proxy of ${source.id} cannot be used (${error instanceof Error ? error.message : String(error)})`, "proxy", source.id, true, { cause: error }));
395
466
  }
396
467
  }
397
468
  }
@@ -403,8 +474,39 @@ export function createBrowserBridge(options) {
403
474
  if (compiled.diagnostics.length)
404
475
  throw compiled.diagnostics[0];
405
476
  requireShownText(document, compiled.project);
477
+ if (purpose === "export_original" || purpose === "export_proxy")
478
+ await reprobeAudio(document, compiled.project, purpose);
406
479
  return conformProject(binding, compiled.project, catalogOf(document), purpose);
407
480
  }
481
+ /**
482
+ * Decodes a trial again of each shown source's audio the import found undecodable (its probe has
483
+ * a 2 s limit), so `startExport` decides by facts taken at export time. Updates the runtimes.
484
+ */
485
+ async function reprobeAudio(document, project, purpose) {
486
+ const used = shownSources(project);
487
+ for (const source of project.sources) {
488
+ if (!used.has(source.id))
489
+ continue;
490
+ const runtimes = [originalOf(document, source.id)];
491
+ if (purpose === "export_proxy")
492
+ runtimes.push(proxies.get(hashOf(document.assets[source.id]))?.lease.value);
493
+ for (const runtime of runtimes) {
494
+ if (!runtime?.file ||
495
+ !runtime.hasAudio ||
496
+ runtime.audioDecodable !== false ||
497
+ runtime.audioBuffer)
498
+ continue;
499
+ const fresh = await audioDecoding(runtime.file).catch(() => null);
500
+ if (!fresh)
501
+ continue;
502
+ runtime.audioDecodable = fresh.decodable;
503
+ if (fresh.decodable)
504
+ delete runtime.audioDecodeFacts;
505
+ else if (fresh.facts)
506
+ runtime.audioDecodeFacts = fresh.facts;
507
+ }
508
+ }
509
+ }
408
510
  const pendingImports = new Set();
409
511
  const assetListeners = new Set();
410
512
  let analysis = Promise.resolve();
@@ -449,6 +551,8 @@ export function createBrowserBridge(options) {
449
551
  .catch(() => { });
450
552
  };
451
553
  const jobs = new Set();
554
+ /** Running extractions, kept apart from `jobs` so an export never waits for one. */
555
+ const extractions = new Set();
452
556
  let disposed = false, engine = null, workerPreview = null, boundCanvas = null, copySurface = false,
453
557
  // Set when the worker failed for a reason other than GPU loss; later previews for this binding
454
558
  // stay on the main thread.
@@ -467,6 +571,9 @@ export function createBrowserBridge(options) {
467
571
  * with the document's provider settings.
468
572
  */
469
573
  function previewMedia(document, id) {
574
+ const contained = filelessRuntime(document, id);
575
+ if (contained)
576
+ return sourceView(document, id, contained);
470
577
  const descriptor = document.assets[id];
471
578
  const original = descriptor
472
579
  ? sourceView(document, id, ownerOf(document, descriptor)?.lease.value)
@@ -502,6 +609,9 @@ export function createBrowserBridge(options) {
502
609
  }
503
610
  /** A lease on the runtime `asset` reads, for work that outlives the owner's hold. */
504
611
  function acquireOwned(document, asset) {
612
+ const contained = asset && filelessRuntime(document, asset.id);
613
+ if (contained)
614
+ return { value: contained, release() { } };
505
615
  const owner = asset && ownerOf(document, asset);
506
616
  if (!owner && asset?.kind === "text")
507
617
  throw undrawnText(document, asset);
@@ -643,8 +753,9 @@ export function createBrowserBridge(options) {
643
753
  fontFamily: familiesOf(document, asset.authoring.text).join(", "),
644
754
  }, { id: asset.id });
645
755
  const revision = issue(asset.id);
756
+ // Bounded by the document's own limits, so it does not count against the import limit.
646
757
  owners.set(resourceKey, {
647
- lease: registry.put(asset.id, revision, runtime, () => staged.dispose()),
758
+ lease: registry.put(asset.id, revision, runtime, () => staged.dispose(), { counted: false }),
648
759
  revision,
649
760
  });
650
761
  }
@@ -816,6 +927,7 @@ export function createBrowserBridge(options) {
816
927
  "duration",
817
928
  "hasAudio",
818
929
  "audioDecodable",
930
+ "audioStreams",
819
931
  "text",
820
932
  "fit",
821
933
  "provider",
@@ -855,7 +967,7 @@ export function createBrowserBridge(options) {
855
967
  if (editor.generation !== sessionGeneration) {
856
968
  sessionGeneration = editor.generation;
857
969
  for (const abort of pendingImports)
858
- abort.abort();
970
+ abort.abort(new EditorError("stale_import", "Project changed during import", "import"));
859
971
  pause();
860
972
  renderKey = null;
861
973
  workerSent = new Map();
@@ -866,6 +978,7 @@ export function createBrowserBridge(options) {
866
978
  previewSelection = new Map();
867
979
  previewConformKey = null;
868
980
  absentProxies = new Set();
981
+ failedProxies = new Map();
869
982
  }
870
983
  scheduleSweep();
871
984
  scheduleTextReports();
@@ -910,7 +1023,7 @@ export function createBrowserBridge(options) {
910
1023
  try {
911
1024
  diagnostics = await callExtensions({
912
1025
  factory: runtimeAssets.extensionsWorkerFactory,
913
- wasmUrl: runtimeAssets.extensionsWasmUrl,
1026
+ wasmUrl: extensionWasmUrls(runtimeAssets),
914
1027
  }, {
915
1028
  call: "svg-diagnostics",
916
1029
  file: runtime.file,
@@ -1186,18 +1299,19 @@ export function createBrowserBridge(options) {
1186
1299
  * Gives up the preview worker after `error` (failed start, load or draw). Until the next binding
1187
1300
  * the main renderer, which loads every project the worker does, draws off screen and each frame
1188
1301
  * 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.
1302
+ * recovers silently and lets a rebuilt preview try a worker again. `starting` is set while a
1303
+ * binding makes its worker, which may have failed before there was one to give up.
1190
1304
  */
1191
- async function abandonWorker(error) {
1305
+ async function abandonWorker(error, starting = false) {
1192
1306
  const failed = workerPreview;
1193
- if (!failed)
1307
+ if (!failed && !starting)
1194
1308
  return;
1195
1309
  workerPreview = null;
1196
1310
  workerSent = new Map();
1197
1311
  workerFonts = null;
1198
1312
  copySurface = true;
1199
- await failed.dispose().catch(() => { });
1200
- if (isGpuLoss(error))
1313
+ await failed?.dispose().catch(() => { });
1314
+ if (isGpuLoss(error) || disposed)
1201
1315
  return;
1202
1316
  workerGivenUp = true;
1203
1317
  const reason = error instanceof Error ? error.message : String(error ?? "");
@@ -1242,17 +1356,28 @@ export function createBrowserBridge(options) {
1242
1356
  // An audio start that missed its deadline and has not settled. A context that never resumes
1243
1357
  // (Firefox without usable output) or a stuck worklet would block Play, so video plays silent.
1244
1358
  let stalledAudio = null;
1245
- /** Whether `starting` settled within the deadline; a rejection propagates. */
1359
+ /**
1360
+ * Whether `starting` settled within the deadline. Sound that fails or misses it is reported once
1361
+ * and playback goes on silent.
1362
+ */
1246
1363
  async function audioStarts(starting) {
1247
1364
  let timer = 0;
1248
1365
  const started = await Promise.race([
1249
- starting.then(() => true),
1366
+ starting.then(() => true, (error) => ({ error })),
1250
1367
  new Promise((resolve) => {
1251
1368
  timer = setTimeout(() => resolve(false), AUDIO_START_TIMEOUT_MS);
1252
1369
  }),
1253
1370
  ]).finally(() => clearTimeout(timer));
1254
- if (started)
1371
+ if (started === true)
1255
1372
  return true;
1373
+ if (started) {
1374
+ mixer?.stop();
1375
+ const reason = started.error instanceof Error
1376
+ ? started.error.message
1377
+ : String(started.error);
1378
+ onError(new EditorError("audio_unavailable", `Audio output could not start (${reason}); playing without sound`, "play", undefined, true, { cause: started.error }));
1379
+ return false;
1380
+ }
1256
1381
  stalledAudio = starting;
1257
1382
  const settle = () => {
1258
1383
  if (stalledAudio === starting)
@@ -1372,7 +1497,7 @@ export function createBrowserBridge(options) {
1372
1497
  await engine?.dispose();
1373
1498
  await sources?.dispose();
1374
1499
  sources = new SourcePixels(library, {
1375
- extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1500
+ extensionWasmUrls: extensionWasmUrls(runtimeAssets),
1376
1501
  });
1377
1502
  const { Engine } = await import("./runtime/engine.js");
1378
1503
  // Until a project loads and sets the render size (see `loaded`).
@@ -1406,7 +1531,7 @@ export function createBrowserBridge(options) {
1406
1531
  mixer.setMasterVolume(monitorVolume);
1407
1532
  mixer.setLatencyOffset(audioOffsetMs);
1408
1533
  stalledAudio = null;
1409
- supplier = new AudioWindowSupplier(library);
1534
+ supplier = new AudioWindowSupplier(library, { onError });
1410
1535
  try {
1411
1536
  await engine.start();
1412
1537
  engine.setPreviewScale(previewScale);
@@ -1419,29 +1544,30 @@ export function createBrowserBridge(options) {
1419
1544
  ...(runtimeAssets.wasmUrl
1420
1545
  ? { wasmUrl: String(runtimeAssets.wasmUrl) }
1421
1546
  : {}),
1422
- ...(runtimeAssets.extensionsWasmUrl
1423
- ? { extensionsWasmUrl: String(runtimeAssets.extensionsWasmUrl) }
1424
- : {}),
1547
+ extensionModuleUrls: extensionWasmUrls(runtimeAssets),
1425
1548
  };
1426
- workerPreview = createWorkerPreview(runtimeAssets.workerFactory(), {
1427
- runtimeAssets: workerRuntime,
1428
- bitmapOutput: true,
1429
- width: canvas.width,
1430
- height: canvas.height,
1431
- videoConversion,
1432
- opaqueEngineFrames,
1433
- // Match the main renderer: the CPU once recovery or `auto` moved there.
1434
- renderer: onCpu() ? "cpu" : rendererMode,
1435
- });
1436
- // A worker that cannot start leaves the surface to the main renderer.
1549
+ // A worker that cannot be made or started leaves the surface to the main renderer.
1437
1550
  try {
1551
+ workerPreview = createWorkerPreview(runtimeAssets.workerFactory(), {
1552
+ runtimeAssets: workerRuntime,
1553
+ bitmapOutput: true,
1554
+ width: canvas.width,
1555
+ height: canvas.height,
1556
+ videoConversion,
1557
+ opaqueEngineFrames,
1558
+ // The main renderer's mode, which is the CPU once recovery or `auto` moved there.
1559
+ renderer: onCpu() ? "cpu" : rendererMode,
1560
+ ...(workerRequestTimeoutMs === undefined
1561
+ ? {}
1562
+ : { requestTimeoutMs: workerRequestTimeoutMs }),
1563
+ });
1438
1564
  await workerPreview.ready;
1439
1565
  await workerPreview.setPreviewScale(previewScale);
1440
1566
  if (effectDefinitions.size)
1441
1567
  await workerPreview.registerEffects(keptEffects());
1442
1568
  }
1443
1569
  catch (error) {
1444
- await abandonWorker(error);
1570
+ await abandonWorker(error, true);
1445
1571
  }
1446
1572
  }
1447
1573
  if (passTiming || traceUploads)
@@ -1708,6 +1834,24 @@ export function createBrowserBridge(options) {
1708
1834
  stage: (signal) => mediaAdapter.stageSequence(files, options, signal),
1709
1835
  };
1710
1836
  }
1837
+ /**
1838
+ * The project an operation started in. `assert` throws once its result no longer belongs there:
1839
+ * `signal`'s reason when aborted, `disposed` after the bridge or the session is disposed, and
1840
+ * `stale_import` once another project was opened. Call it after the operation's last await,
1841
+ * directly before it changes the document.
1842
+ */
1843
+ function projectScope(signal) {
1844
+ const generation = editor.generation;
1845
+ return {
1846
+ assert(operation, entityId) {
1847
+ signal?.throwIfAborted();
1848
+ if (disposed || editor.disposed)
1849
+ throw new EditorError("disposed", "Bridge is disposed", operation, entityId);
1850
+ if (editor.generation !== generation)
1851
+ throw new EditorError("stale_import", "Project changed during import", operation, entityId);
1852
+ },
1853
+ };
1854
+ }
1711
1855
  /**
1712
1856
  * Stages `units` (at most {@link IMPORT_STAGE_CONCURRENCY} at once) and adds them to the document
1713
1857
  * in order as one undo step. A relink has exactly one unit.
@@ -1715,7 +1859,7 @@ export function createBrowserBridge(options) {
1715
1859
  async function importUnits(units, { signal, relinkId } = {}) {
1716
1860
  if (disposed)
1717
1861
  throw new EditorError("disposed", "Bridge is disposed", "import");
1718
- const generation = editor.generation, controller = new AbortController();
1862
+ const controller = new AbortController(), scope = projectScope(controller.signal), operation = relinkId ? "relink" : "import";
1719
1863
  pendingImports.add(controller);
1720
1864
  const abort = () => controller.abort(signal?.reason);
1721
1865
  signal?.addEventListener("abort", abort, { once: true });
@@ -1746,19 +1890,19 @@ export function createBrowserBridge(options) {
1746
1890
  await Promise.all(Array.from({ length: Math.min(limit, units.length) }, stageNext));
1747
1891
  if (failure)
1748
1892
  throw failure.error;
1893
+ // Loaded before the commit loop, which must not await.
1894
+ const binding = relinkId && staged[0]?.fingerprint ? await decisions() : null;
1749
1895
  for (const [index, unit] of units.entries()) {
1750
1896
  const item = staged[index];
1751
1897
  const fileName = unit.name ?? item.name ?? item.runtime.name;
1752
- controller.signal.throwIfAborted();
1753
- if (disposed || editor.disposed || editor.generation !== generation)
1754
- throw new EditorError("stale_import", "Project changed during import", "import");
1898
+ scope.assert(operation);
1755
1899
  const old = relinkId ? editor.document.assets[relinkId] : null;
1756
1900
  if (relinkId && !old)
1757
1901
  throw new EditorError("missing_asset", "Unknown relink target", "relink", relinkId);
1758
- // Equal hashes match whatever else differs; without them any differing recorded part means
1759
- // other media.
1902
+ // Equal hashes match whatever else differs. Without hashes, any recorded part that differs
1903
+ // means other media.
1760
1904
  if (old?.fingerprint && item.fingerprint) {
1761
- const match = compareFingerprints(await decisions(), old.fingerprint, item.fingerprint);
1905
+ const match = compareFingerprints(binding, old.fingerprint, item.fingerprint);
1762
1906
  if (match.kind === "mismatch")
1763
1907
  throw new EditorError("relink_conflict", `${fileName} is not the saved media: its ${match.fields
1764
1908
  .map((field) => field.replace(/_/g, " "))
@@ -1792,8 +1936,16 @@ export function createBrowserBridge(options) {
1792
1936
  ...(item.fingerprint ? { fingerprint: item.fingerprint } : {}),
1793
1937
  authoring,
1794
1938
  };
1795
- // Call as a method, since a staged asset may be a class instance.
1796
- const lease = registry.put(id, contentRevision, runtime, () => item.dispose());
1939
+ let lease;
1940
+ try {
1941
+ // Call as a method, since a staged asset may be a class instance.
1942
+ lease = registry.put(id, contentRevision, runtime, () => item.dispose());
1943
+ }
1944
+ catch (error) {
1945
+ if (error?.code !== "resource_budget")
1946
+ throw error;
1947
+ throw new EditorError("resource_budget", `${fileName} is not imported: this session holds ${registry.limit} imported media files, its resourceLimit. Removed media counts while undo can still reach it`, "import", id, true, { cause: error });
1948
+ }
1797
1949
  leases.push({ id, contentRevision, lease });
1798
1950
  commands.push({
1799
1951
  type: "asset.put",
@@ -1822,6 +1974,7 @@ export function createBrowserBridge(options) {
1822
1974
  lease: entry.lease,
1823
1975
  revision: entry.contentRevision,
1824
1976
  });
1977
+ scope.assert(operation);
1825
1978
  const result = editor.dispatch({ type: "transaction", commands });
1826
1979
  if (!result.ok)
1827
1980
  throw result.error;
@@ -1843,6 +1996,14 @@ export function createBrowserBridge(options) {
1843
1996
  signal?.removeEventListener("abort", abort);
1844
1997
  }
1845
1998
  }
1999
+ /** Whether a document the session can return to has media with content hash `hash`. */
2000
+ function readsMedia(hash) {
2001
+ for (const document of editor.reachableDocuments())
2002
+ for (const asset of Object.values(document.assets))
2003
+ if (hashOf(asset) === hash)
2004
+ return true;
2005
+ return false;
2006
+ }
1846
2007
  /** The running proxy conversion: `preempt` stops it for an export, `done` settles at its end. */
1847
2008
  let proxyRun = null;
1848
2009
  /**
@@ -1891,6 +2052,37 @@ export function createBrowserBridge(options) {
1891
2052
  cause: new PlanarDecodeUnavailableError(`${names}: no planar decode in this browser`, facts),
1892
2053
  });
1893
2054
  }
2055
+ /**
2056
+ * The audible sources an export reads whose audio this browser cannot decode, by the runtime it
2057
+ * reads (`map`), as `{ id, name, facts }`. None when the export writes no audio.
2058
+ */
2059
+ function undecodableAudioOf(document, project, used, map, options) {
2060
+ if (options.includeAudio === false)
2061
+ return [];
2062
+ return project.sources
2063
+ .filter((source) => used.has(source.id) &&
2064
+ (source.kind === "audio" || source.has_audio === true))
2065
+ .filter((source) => {
2066
+ const runtime = map.get(source.id);
2067
+ return (runtime?.hasAudio === true &&
2068
+ runtime.audioDecodable === false &&
2069
+ !runtime.audioBuffer);
2070
+ })
2071
+ .map((source) => ({
2072
+ id: source.id,
2073
+ name: document.assets[source.id]?.name ?? source.id,
2074
+ facts: map.get(source.id).audioDecodeFacts ?? null,
2075
+ }));
2076
+ }
2077
+ /** Throws the refusal of an export whose audible audio this browser cannot decode. */
2078
+ function refuseUndecodableAudio(undecodable) {
2079
+ const [first] = undecodable;
2080
+ const names = undecodable.map((source) => source.name).join(", ");
2081
+ throw new EditorError("unsupported_media", `This browser cannot decode the sound of ${names}; export with undecodableAudio: "silence" to write them silent, or with the native host`, "export", first.id, true, {
2082
+ cause: new DecodeUnavailableError(`${first.name}: no audio decoder in this browser`, first.facts ?? { kind: "audio", codec: null }),
2083
+ details: { sources: undecodable },
2084
+ });
2085
+ }
1894
2086
  let sweptExports = false;
1895
2087
  /** Settles when the running export does. */
1896
2088
  let exportSettled = Promise.resolve();
@@ -1909,6 +2101,9 @@ export function createBrowserBridge(options) {
1909
2101
  if (videoDecode !== "auto" && videoDecode !== "software")
1910
2102
  throw new EditorError("invalid_video_decode", `Export videoDecode must be "auto" or "software"; received ${JSON.stringify(videoDecode)}`, "export");
1911
2103
  const exportConversion = checkedVideoConversion(options.videoConversion ?? videoConversion, "export");
2104
+ const undecodableAudio = options.undecodableAudio ?? "refuse";
2105
+ if (undecodableAudio !== "refuse" && undecodableAudio !== "silence")
2106
+ throw new EditorError("invalid_undecodable_audio", `Export undecodableAudio must be "refuse" or "silence"; received ${JSON.stringify(undecodableAudio)}`, "export");
1912
2107
  materializeText(editor.document);
1913
2108
  const snapshot = editor.document, revision = editor.revision, effects = keptEffects();
1914
2109
  const compiled = compileEditorDocument(snapshot);
@@ -1945,6 +2140,11 @@ export function createBrowserBridge(options) {
1945
2140
  held.forEach((l) => l.release());
1946
2141
  throw error;
1947
2142
  }
2143
+ const silentAudio = undecodableAudioOf(snapshot, compiled.project, used, map, options);
2144
+ if (silentAudio.length > 0 && undecodableAudio !== "silence") {
2145
+ held.forEach((l) => l.release());
2146
+ refuseUndecodableAudio(silentAudio);
2147
+ }
1948
2148
  let fontsReported = false;
1949
2149
  const backend = {
1950
2150
  // Each attempt builds its own engine, device, decoders and output; nothing failed is reused.
@@ -1954,7 +2154,7 @@ export function createBrowserBridge(options) {
1954
2154
  const { openExportOutput } = await import("./runtime/output.js");
1955
2155
  const project = compiled.project, lib = { get: (id) => map.get(id) };
1956
2156
  const pixels = new SourcePixels(lib, {
1957
- extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
2157
+ extensionWasmUrls: extensionWasmUrls(runtimeAssets),
1958
2158
  videoDecode,
1959
2159
  });
1960
2160
  // The retry policy picks the renderer: CPU after a self-caused loss or a second page loss.
@@ -2044,6 +2244,7 @@ export function createBrowserBridge(options) {
2044
2244
  videoDecode,
2045
2245
  videoConversion: exportConversion,
2046
2246
  decodeFallbacks: pixels.decodeFallbacks,
2247
+ silentAudioSources: silentAudio.map((source) => source.id),
2047
2248
  renderer: renderer.rendererChoice,
2048
2249
  },
2049
2250
  };
@@ -2102,11 +2303,18 @@ export function createBrowserBridge(options) {
2102
2303
  : clearTimeout)(refreshFrame);
2103
2304
  ++binding;
2104
2305
  for (const controller of pendingImports)
2105
- controller.abort();
2306
+ controller.abort(new EditorError("disposed", "Bridge is disposed", "import"));
2106
2307
  for (const controller of analyses.values())
2107
2308
  controller.abort();
2108
2309
  globalThis.document?.removeEventListener("visibilitychange", visibility);
2109
2310
  await Promise.all([...jobs].map((job) => job.cancel()));
2311
+ await Promise.all([...extractions].map((job) => job.cancel()));
2312
+ // Its conversion stops on `lifetime`; nothing may write after teardown.
2313
+ await proxyRun?.done;
2314
+ // Before the queue drains, so a queued render waiting on the worker is rejected.
2315
+ const worker = workerPreview;
2316
+ workerPreview = null;
2317
+ await worker?.dispose();
2110
2318
  await queue;
2111
2319
  await mixer?.close();
2112
2320
  await supplier?.close();
@@ -2136,6 +2344,49 @@ export function createBrowserBridge(options) {
2136
2344
  relink: (id, file, options) => importFiles([file], { ...options, relinkId: id }),
2137
2345
  importSequence,
2138
2346
  relinkSequence,
2347
+ async putProviderSource({ id, name, provider }, { signal } = {}) {
2348
+ if (providerReadsFile(provider))
2349
+ throw new EditorError("unsupported_media", "A provider source that reads a file is imported with importFiles", "provider", id);
2350
+ const scope = projectScope(signal);
2351
+ let read;
2352
+ try {
2353
+ read = await describeProvider(provider, signal);
2354
+ }
2355
+ catch (error) {
2356
+ if (error?.name === "AbortError")
2357
+ throw error;
2358
+ throw new EditorError("unreadable_media", String(error?.message ?? error), "provider", id);
2359
+ }
2360
+ scope.assert("provider", id);
2361
+ const assetId = id ?? crypto.randomUUID();
2362
+ const descriptor = editor.document.assets[assetId];
2363
+ const previous = editor.document.project.sources.find((candidate) => candidate.id === assetId);
2364
+ const kind = providerKind(provider);
2365
+ const result = editor.dispatch({
2366
+ type: "asset.put",
2367
+ asset: {
2368
+ ...(descriptor ?? { contentRevision: 0 }),
2369
+ id: assetId,
2370
+ kind,
2371
+ name: name ?? descriptor?.name ?? provider.format,
2372
+ missing: false,
2373
+ },
2374
+ source: {
2375
+ ...previous,
2376
+ id: assetId,
2377
+ kind,
2378
+ locator: "",
2379
+ provider,
2380
+ },
2381
+ });
2382
+ if (!result.ok)
2383
+ throw result.error;
2384
+ const runtime = filelessRuntime(editor.document, assetId);
2385
+ if (runtime)
2386
+ describe(runtime, provider, read);
2387
+ notifyAssets();
2388
+ return { assetId };
2389
+ },
2139
2390
  selectAnimation(id, animation) {
2140
2391
  const descriptor = editor.document.assets[id];
2141
2392
  const source = editor.document.project.sources.find((candidate) => candidate.id === id);
@@ -2178,7 +2429,9 @@ export function createBrowserBridge(options) {
2178
2429
  pause,
2179
2430
  startExport,
2180
2431
  async importCaptions(file) {
2181
- const generation = editor.generation;
2432
+ if (disposed)
2433
+ throw new EditorError("disposed", "Bridge is disposed", "import");
2434
+ const scope = projectScope();
2182
2435
  // A larger file holds more cues than a project can, so refuse it unread.
2183
2436
  if (file.size > MAX_CAPTION_FILE_BYTES)
2184
2437
  throw new EditorError("invalid_captions", `${file.name} is ${file.size} bytes; a subtitle file is read up to ${MAX_CAPTION_FILE_BYTES}`, "import");
@@ -2191,8 +2444,7 @@ export function createBrowserBridge(options) {
2191
2444
  catch (error) {
2192
2445
  throw new EditorError("invalid_captions", `${file.name}: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
2193
2446
  }
2194
- if (disposed || editor.generation !== generation)
2195
- throw Error("Project changed during caption import");
2447
+ scope.assert("import");
2196
2448
  const assetId = crypto.randomUUID();
2197
2449
  const result = editor.dispatch({
2198
2450
  type: "asset.put",
@@ -2228,7 +2480,64 @@ export function createBrowserBridge(options) {
2228
2480
  return JSON.parse(measurer.measureLayout(JSON.stringify(generator), width, height, time, width, height));
2229
2481
  },
2230
2482
  conform,
2483
+ async applyEdit(request, { then, label, signal } = {}) {
2484
+ if (disposed)
2485
+ throw new EditorError("disposed", "Bridge is disposed", "edit");
2486
+ const { project, read } = editor.editProject();
2487
+ const binding = await loadWasm();
2488
+ signal?.throwIfAborted();
2489
+ if (disposed)
2490
+ throw new EditorError("disposed", "Bridge is disposed", "edit");
2491
+ const applied = applyEngineEdit(binding, project, request);
2492
+ const result = editor.applyEdit(applied, { read, request, then, label });
2493
+ if (!result.ok)
2494
+ throw result.error;
2495
+ return result.value;
2496
+ },
2497
+ async extract(run, { plugin, extractor, signal, onProgress } = {}) {
2498
+ if (disposed)
2499
+ throw new EditorError("disposed", "Bridge is disposed", "extract");
2500
+ if ((plugin === undefined) === (extractor === undefined))
2501
+ throw new EditorError("invalid_command", "Pass a plugin or an extractor", "extract");
2502
+ if (run.input.from !== "source")
2503
+ throw new EditorError("unsupported_media", "The browser runtime extracts from source media; it draws no timeline frames for an extractor", "extract");
2504
+ const id = run.input.source_id ?? "";
2505
+ const { project, read } = editor.extractionProject();
2506
+ const document = editor.document;
2507
+ const file = originalOf(document, id)?.file;
2508
+ if (!file)
2509
+ throw new EditorError("missing_asset", "Relink the original to extract from it", "extract", id);
2510
+ const madeFrom = project.sources.find((source) => source.id === id)?.fingerprint ??
2511
+ document.assets[id]?.fingerprint;
2512
+ const job = new ExtractionJob(async (aborted) => {
2513
+ const binding = await loadWasm();
2514
+ const loaded = plugin
2515
+ ? await loadPlugin(plugin.manifest, plugin.sha256, {
2516
+ ...(plugin.memoryBytes === undefined
2517
+ ? {}
2518
+ : { memoryBytes: plugin.memoryBytes }),
2519
+ signal: aborted,
2520
+ })
2521
+ : undefined;
2522
+ const result = await runExtractor({
2523
+ binding,
2524
+ audioBinding: binding,
2525
+ project,
2526
+ request: run,
2527
+ media: { [id]: file },
2528
+ ...(madeFrom ? { madeFrom } : {}),
2529
+ ...(loaded ? { plugin: loaded } : {}),
2530
+ signal: aborted,
2531
+ ...(onProgress ? { onProgress } : {}),
2532
+ }, loaded ? loaded.extractor(run.params) : extractor);
2533
+ return { result, read };
2534
+ }, signal, () => extractions.delete(job));
2535
+ extractions.add(job);
2536
+ return job.result;
2537
+ },
2231
2538
  async generateProxy(id, { signal } = {}) {
2539
+ if (disposed)
2540
+ throw new EditorError("disposed", "Bridge is disposed", "proxy", id);
2232
2541
  const descriptor = editor.document.assets[id];
2233
2542
  // No single video file for the proxy maker to read.
2234
2543
  const provider = editor.document.project.sources.find((source) => source.id === id)?.provider;
@@ -2242,20 +2551,23 @@ export function createBrowserBridge(options) {
2242
2551
  throw new EditorError("proxy_busy", "A proxy of this source is being made", "proxy", id);
2243
2552
  proxyJobs.set(id, 0);
2244
2553
  notifyAssets();
2554
+ // A conversion lives as long as the bridge, not the project: a proxy serves every project
2555
+ // with the same media.
2556
+ const stop = signal
2557
+ ? AbortSignal.any([lifetime.signal, signal])
2558
+ : lifetime.signal;
2245
2559
  let hold = null;
2246
2560
  try {
2247
2561
  for (;;) {
2248
2562
  // One proxy at a time and none during an export; a starting export preempts it.
2249
- const turn = await proxyTurn(signal);
2563
+ const turn = await proxyTurn(stop);
2250
2564
  try {
2251
2565
  // Held until its runtime is released so no page removes it meanwhile.
2252
2566
  hold = await proxyStore.hold(hash);
2253
2567
  // Notify listeners once per whole percent.
2254
2568
  let percent = 0;
2255
2569
  const found = await proxyStore.generate(runtime.file, descriptor.fingerprint, {
2256
- signal: signal
2257
- ? AbortSignal.any([signal, turn.signal])
2258
- : turn.signal,
2570
+ signal: AbortSignal.any([stop, turn.signal]),
2259
2571
  onProgress: (fraction) => {
2260
2572
  proxyJobs.set(id, fraction);
2261
2573
  const next = Math.floor(fraction * 100);
@@ -2265,13 +2577,20 @@ export function createBrowserBridge(options) {
2265
2577
  notifyAssets();
2266
2578
  },
2267
2579
  });
2580
+ if (disposed)
2581
+ throw new EditorError("disposed", "Bridge is disposed", "proxy", id);
2582
+ // Kept on disk either way; adopted only while a document this session can show has
2583
+ // that media.
2584
+ if (!readsMedia(hash))
2585
+ break;
2268
2586
  const adopted = adoptProxy(hash, found, hold);
2269
2587
  hold = null;
2270
2588
  await adopted;
2589
+ failedProxies.delete(hash);
2271
2590
  break;
2272
2591
  }
2273
2592
  catch (error) {
2274
- if (!turn.signal.aborted || signal?.aborted)
2593
+ if (!turn.signal.aborted || stop.aborted)
2275
2594
  throw error;
2276
2595
  void hold?.release();
2277
2596
  hold = null;
@@ -2342,6 +2661,8 @@ export function createBrowserBridge(options) {
2342
2661
  async removeProxies(hashes) {
2343
2662
  const wanted = new Set(hashes);
2344
2663
  const unlocked = [];
2664
+ for (const hash of wanted)
2665
+ failedProxies.delete(hash);
2345
2666
  for (const [hash, proxy] of proxies)
2346
2667
  if (wanted.has(hash)) {
2347
2668
  proxies.delete(hash);
@@ -2375,7 +2696,9 @@ export function createBrowserBridge(options) {
2375
2696
  const result = [];
2376
2697
  const fonts = new Set(heldFonts(snapshot));
2377
2698
  for (const asset of Object.values(snapshot.assets)) {
2699
+ // A source that reads no file goes to the host in the project alone.
2378
2700
  if (drawnByEngine(asset) ||
2701
+ filelessRuntime(snapshot, asset.id) ||
2379
2702
  (asset.kind === "font" ? !fonts.has(asset) : !used.has(asset.id)))
2380
2703
  continue;
2381
2704
  const proxied = selection.get(asset.id)?.media === "proxy";
@@ -2532,8 +2855,8 @@ export function createBrowserBridge(options) {
2532
2855
  return engine?.catalog ?? null;
2533
2856
  },
2534
2857
  registerEffects,
2535
- // A source's own media while online, whichever preview reads, so size, file and peaks are the
2536
- // original's.
2858
+ // A source's own media while online, whichever one preview reads, so the size, file and peaks
2859
+ // come from the original.
2537
2860
  getAsset: (id) => (preferredPreviewMedia === "proxies" &&
2538
2861
  sourceView(editor.draft, id, originalOf(editor.draft, id))) ||
2539
2862
  library.get(id),