@alpha2-sh/editor 0.5.3 → 0.6.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 (39) hide show
  1. package/README.md +58 -1
  2. package/dist/browser/bridge.js +275 -52
  3. package/dist/browser/jobs.d.ts +17 -0
  4. package/dist/browser/jobs.js +40 -0
  5. package/dist/browser/resources.d.ts +9 -4
  6. package/dist/browser/resources.js +17 -5
  7. package/dist/browser/runtime/assets.d.ts +14 -2
  8. package/dist/browser/runtime/assets.js +37 -27
  9. package/dist/browser/runtime/audio.d.ts +12 -2
  10. package/dist/browser/runtime/audio.js +124 -14
  11. package/dist/browser/runtime/engine.js +8 -1
  12. package/dist/browser/runtime/exporter.d.ts +2 -1
  13. package/dist/browser/runtime/exporter.js +15 -4
  14. package/dist/browser/runtime/preview-utils.d.ts +12 -0
  15. package/dist/browser/runtime/preview-utils.js +45 -0
  16. package/dist/browser/runtime/sources.js +11 -34
  17. package/dist/browser/types.d.ts +105 -19
  18. package/dist/browser/worker.d.ts +4 -2
  19. package/dist/browser/worker.js +73 -24
  20. package/dist/core/commands.d.ts +46 -3
  21. package/dist/core/commands.js +212 -40
  22. package/dist/core/compositions.d.ts +27 -0
  23. package/dist/core/compositions.js +43 -0
  24. package/dist/core/data.d.ts +34 -0
  25. package/dist/core/data.js +69 -0
  26. package/dist/core/document.d.ts +10 -1
  27. package/dist/core/document.js +127 -6
  28. package/dist/core/keyframes.d.ts +3 -2
  29. package/dist/core/keyframes.js +6 -2
  30. package/dist/core/sameness.d.ts +6 -0
  31. package/dist/core/sameness.js +42 -0
  32. package/dist/core/session.d.ts +85 -7
  33. package/dist/core/session.js +124 -13
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/native-client/index.d.ts +2 -2
  37. package/dist/native-client/index.js +2 -2
  38. package/dist/ports/index.d.ts +5 -4
  39. package/package.json +3 -3
@@ -3,16 +3,19 @@ import { compileEditorDocument, EditorError, readsMediaFile, sequenceEnd, } from
3
3
  import { captionsAsset } from "../core/captions.js";
4
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";
@@ -227,7 +230,7 @@ export function createMediaAdapter({ extensionsWasmUrl, extensionModuleUrls, was
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"');
@@ -391,7 +394,9 @@ export function createBrowserBridge(options) {
391
394
  let staged;
392
395
  try {
393
396
  // Proxies are keyed by their original's hash, so skip hashing their own bytes.
394
- staged = await mediaAdapter.stage(found.file, new AbortController().signal, { fingerprint: false });
397
+ staged = await mediaAdapter.stage(found.file, lifetime.signal, {
398
+ fingerprint: false,
399
+ });
395
400
  }
396
401
  catch (error) {
397
402
  void hold.release();
@@ -406,10 +411,11 @@ export function createBrowserBridge(options) {
406
411
  try {
407
412
  const runtime = { ...staged.runtime, id: `proxy:${hash}` };
408
413
  proxy.revision = issue(runtime.id);
414
+ // At most one proxy per original, so it does not count against the import limit.
409
415
  proxy.lease = registry.put(runtime.id, proxy.revision, runtime, () => {
410
416
  staged.dispose();
411
417
  proxy.unlocked = hold.release();
412
- });
418
+ }, { counted: false });
413
419
  proxies.set(hash, proxy);
414
420
  }
415
421
  catch (error) {
@@ -423,7 +429,12 @@ export function createBrowserBridge(options) {
423
429
  }
424
430
  /** Hashes with no stored proxy, not asked again this session. */
425
431
  let absentProxies = new Set();
426
- /** 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
+ */
427
438
  async function discoverProxies(document) {
428
439
  for (const source of document.project.sources) {
429
440
  const descriptor = document.assets[source.id];
@@ -431,17 +442,27 @@ export function createBrowserBridge(options) {
431
442
  if (!hash ||
432
443
  proxies.has(hash) ||
433
444
  absentProxies.has(hash) ||
445
+ failedProxies.has(hash) ||
434
446
  (preferredPreviewMedia === "original" &&
435
447
  originalOf(document, source.id)))
436
448
  continue;
437
449
  // Hold before reading so no other page removes it in between.
438
450
  const hold = await proxyStore.hold(hash);
439
451
  const found = await proxyStore.find(hash).catch(() => null);
440
- if (found)
441
- await adoptProxy(hash, found, hold);
442
- else {
452
+ if (!found) {
443
453
  absentProxies.add(hash);
444
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 }));
445
466
  }
446
467
  }
447
468
  }
@@ -453,8 +474,39 @@ export function createBrowserBridge(options) {
453
474
  if (compiled.diagnostics.length)
454
475
  throw compiled.diagnostics[0];
455
476
  requireShownText(document, compiled.project);
477
+ if (purpose === "export_original" || purpose === "export_proxy")
478
+ await reprobeAudio(document, compiled.project, purpose);
456
479
  return conformProject(binding, compiled.project, catalogOf(document), purpose);
457
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
+ }
458
510
  const pendingImports = new Set();
459
511
  const assetListeners = new Set();
460
512
  let analysis = Promise.resolve();
@@ -499,6 +551,8 @@ export function createBrowserBridge(options) {
499
551
  .catch(() => { });
500
552
  };
501
553
  const jobs = new Set();
554
+ /** Running extractions, kept apart from `jobs` so an export never waits for one. */
555
+ const extractions = new Set();
502
556
  let disposed = false, engine = null, workerPreview = null, boundCanvas = null, copySurface = false,
503
557
  // Set when the worker failed for a reason other than GPU loss; later previews for this binding
504
558
  // stay on the main thread.
@@ -699,8 +753,9 @@ export function createBrowserBridge(options) {
699
753
  fontFamily: familiesOf(document, asset.authoring.text).join(", "),
700
754
  }, { id: asset.id });
701
755
  const revision = issue(asset.id);
756
+ // Bounded by the document's own limits, so it does not count against the import limit.
702
757
  owners.set(resourceKey, {
703
- lease: registry.put(asset.id, revision, runtime, () => staged.dispose()),
758
+ lease: registry.put(asset.id, revision, runtime, () => staged.dispose(), { counted: false }),
704
759
  revision,
705
760
  });
706
761
  }
@@ -872,6 +927,7 @@ export function createBrowserBridge(options) {
872
927
  "duration",
873
928
  "hasAudio",
874
929
  "audioDecodable",
930
+ "audioStreams",
875
931
  "text",
876
932
  "fit",
877
933
  "provider",
@@ -911,7 +967,7 @@ export function createBrowserBridge(options) {
911
967
  if (editor.generation !== sessionGeneration) {
912
968
  sessionGeneration = editor.generation;
913
969
  for (const abort of pendingImports)
914
- abort.abort();
970
+ abort.abort(new EditorError("stale_import", "Project changed during import", "import"));
915
971
  pause();
916
972
  renderKey = null;
917
973
  workerSent = new Map();
@@ -922,6 +978,7 @@ export function createBrowserBridge(options) {
922
978
  previewSelection = new Map();
923
979
  previewConformKey = null;
924
980
  absentProxies = new Set();
981
+ failedProxies = new Map();
925
982
  }
926
983
  scheduleSweep();
927
984
  scheduleTextReports();
@@ -1242,18 +1299,19 @@ export function createBrowserBridge(options) {
1242
1299
  * Gives up the preview worker after `error` (failed start, load or draw). Until the next binding
1243
1300
  * the main renderer, which loads every project the worker does, draws off screen and each frame
1244
1301
  * is copied to the bound surface. `onError` hears once why, unless the worker lost its GPU, which
1245
- * 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.
1246
1304
  */
1247
- async function abandonWorker(error) {
1305
+ async function abandonWorker(error, starting = false) {
1248
1306
  const failed = workerPreview;
1249
- if (!failed)
1307
+ if (!failed && !starting)
1250
1308
  return;
1251
1309
  workerPreview = null;
1252
1310
  workerSent = new Map();
1253
1311
  workerFonts = null;
1254
1312
  copySurface = true;
1255
- await failed.dispose().catch(() => { });
1256
- if (isGpuLoss(error))
1313
+ await failed?.dispose().catch(() => { });
1314
+ if (isGpuLoss(error) || disposed)
1257
1315
  return;
1258
1316
  workerGivenUp = true;
1259
1317
  const reason = error instanceof Error ? error.message : String(error ?? "");
@@ -1298,17 +1356,28 @@ export function createBrowserBridge(options) {
1298
1356
  // An audio start that missed its deadline and has not settled. A context that never resumes
1299
1357
  // (Firefox without usable output) or a stuck worklet would block Play, so video plays silent.
1300
1358
  let stalledAudio = null;
1301
- /** 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
+ */
1302
1363
  async function audioStarts(starting) {
1303
1364
  let timer = 0;
1304
1365
  const started = await Promise.race([
1305
- starting.then(() => true),
1366
+ starting.then(() => true, (error) => ({ error })),
1306
1367
  new Promise((resolve) => {
1307
1368
  timer = setTimeout(() => resolve(false), AUDIO_START_TIMEOUT_MS);
1308
1369
  }),
1309
1370
  ]).finally(() => clearTimeout(timer));
1310
- if (started)
1371
+ if (started === true)
1311
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
+ }
1312
1381
  stalledAudio = starting;
1313
1382
  const settle = () => {
1314
1383
  if (stalledAudio === starting)
@@ -1462,7 +1531,7 @@ export function createBrowserBridge(options) {
1462
1531
  mixer.setMasterVolume(monitorVolume);
1463
1532
  mixer.setLatencyOffset(audioOffsetMs);
1464
1533
  stalledAudio = null;
1465
- supplier = new AudioWindowSupplier(library);
1534
+ supplier = new AudioWindowSupplier(library, { onError });
1466
1535
  try {
1467
1536
  await engine.start();
1468
1537
  engine.setPreviewScale(previewScale);
@@ -1477,25 +1546,28 @@ export function createBrowserBridge(options) {
1477
1546
  : {}),
1478
1547
  extensionModuleUrls: extensionWasmUrls(runtimeAssets),
1479
1548
  };
1480
- workerPreview = createWorkerPreview(runtimeAssets.workerFactory(), {
1481
- runtimeAssets: workerRuntime,
1482
- bitmapOutput: true,
1483
- width: canvas.width,
1484
- height: canvas.height,
1485
- videoConversion,
1486
- opaqueEngineFrames,
1487
- // Match the main renderer: the CPU once recovery or `auto` moved there.
1488
- renderer: onCpu() ? "cpu" : rendererMode,
1489
- });
1490
- // 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.
1491
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
+ });
1492
1564
  await workerPreview.ready;
1493
1565
  await workerPreview.setPreviewScale(previewScale);
1494
1566
  if (effectDefinitions.size)
1495
1567
  await workerPreview.registerEffects(keptEffects());
1496
1568
  }
1497
1569
  catch (error) {
1498
- await abandonWorker(error);
1570
+ await abandonWorker(error, true);
1499
1571
  }
1500
1572
  }
1501
1573
  if (passTiming || traceUploads)
@@ -1762,6 +1834,24 @@ export function createBrowserBridge(options) {
1762
1834
  stage: (signal) => mediaAdapter.stageSequence(files, options, signal),
1763
1835
  };
1764
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
+ }
1765
1855
  /**
1766
1856
  * Stages `units` (at most {@link IMPORT_STAGE_CONCURRENCY} at once) and adds them to the document
1767
1857
  * in order as one undo step. A relink has exactly one unit.
@@ -1769,7 +1859,7 @@ export function createBrowserBridge(options) {
1769
1859
  async function importUnits(units, { signal, relinkId } = {}) {
1770
1860
  if (disposed)
1771
1861
  throw new EditorError("disposed", "Bridge is disposed", "import");
1772
- const generation = editor.generation, controller = new AbortController();
1862
+ const controller = new AbortController(), scope = projectScope(controller.signal), operation = relinkId ? "relink" : "import";
1773
1863
  pendingImports.add(controller);
1774
1864
  const abort = () => controller.abort(signal?.reason);
1775
1865
  signal?.addEventListener("abort", abort, { once: true });
@@ -1800,19 +1890,19 @@ export function createBrowserBridge(options) {
1800
1890
  await Promise.all(Array.from({ length: Math.min(limit, units.length) }, stageNext));
1801
1891
  if (failure)
1802
1892
  throw failure.error;
1893
+ // Loaded before the commit loop, which must not await.
1894
+ const binding = relinkId && staged[0]?.fingerprint ? await decisions() : null;
1803
1895
  for (const [index, unit] of units.entries()) {
1804
1896
  const item = staged[index];
1805
1897
  const fileName = unit.name ?? item.name ?? item.runtime.name;
1806
- controller.signal.throwIfAborted();
1807
- if (disposed || editor.disposed || editor.generation !== generation)
1808
- throw new EditorError("stale_import", "Project changed during import", "import");
1898
+ scope.assert(operation);
1809
1899
  const old = relinkId ? editor.document.assets[relinkId] : null;
1810
1900
  if (relinkId && !old)
1811
1901
  throw new EditorError("missing_asset", "Unknown relink target", "relink", relinkId);
1812
1902
  // Equal hashes match whatever else differs. Without hashes, any recorded part that differs
1813
1903
  // means other media.
1814
1904
  if (old?.fingerprint && item.fingerprint) {
1815
- const match = compareFingerprints(await decisions(), old.fingerprint, item.fingerprint);
1905
+ const match = compareFingerprints(binding, old.fingerprint, item.fingerprint);
1816
1906
  if (match.kind === "mismatch")
1817
1907
  throw new EditorError("relink_conflict", `${fileName} is not the saved media: its ${match.fields
1818
1908
  .map((field) => field.replace(/_/g, " "))
@@ -1846,8 +1936,16 @@ export function createBrowserBridge(options) {
1846
1936
  ...(item.fingerprint ? { fingerprint: item.fingerprint } : {}),
1847
1937
  authoring,
1848
1938
  };
1849
- // Call as a method, since a staged asset may be a class instance.
1850
- 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
+ }
1851
1949
  leases.push({ id, contentRevision, lease });
1852
1950
  commands.push({
1853
1951
  type: "asset.put",
@@ -1876,6 +1974,7 @@ export function createBrowserBridge(options) {
1876
1974
  lease: entry.lease,
1877
1975
  revision: entry.contentRevision,
1878
1976
  });
1977
+ scope.assert(operation);
1879
1978
  const result = editor.dispatch({ type: "transaction", commands });
1880
1979
  if (!result.ok)
1881
1980
  throw result.error;
@@ -1897,6 +1996,14 @@ export function createBrowserBridge(options) {
1897
1996
  signal?.removeEventListener("abort", abort);
1898
1997
  }
1899
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
+ }
1900
2007
  /** The running proxy conversion: `preempt` stops it for an export, `done` settles at its end. */
1901
2008
  let proxyRun = null;
1902
2009
  /**
@@ -1945,6 +2052,37 @@ export function createBrowserBridge(options) {
1945
2052
  cause: new PlanarDecodeUnavailableError(`${names}: no planar decode in this browser`, facts),
1946
2053
  });
1947
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
+ }
1948
2086
  let sweptExports = false;
1949
2087
  /** Settles when the running export does. */
1950
2088
  let exportSettled = Promise.resolve();
@@ -1963,6 +2101,9 @@ export function createBrowserBridge(options) {
1963
2101
  if (videoDecode !== "auto" && videoDecode !== "software")
1964
2102
  throw new EditorError("invalid_video_decode", `Export videoDecode must be "auto" or "software"; received ${JSON.stringify(videoDecode)}`, "export");
1965
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");
1966
2107
  materializeText(editor.document);
1967
2108
  const snapshot = editor.document, revision = editor.revision, effects = keptEffects();
1968
2109
  const compiled = compileEditorDocument(snapshot);
@@ -1999,6 +2140,11 @@ export function createBrowserBridge(options) {
1999
2140
  held.forEach((l) => l.release());
2000
2141
  throw error;
2001
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
+ }
2002
2148
  let fontsReported = false;
2003
2149
  const backend = {
2004
2150
  // Each attempt builds its own engine, device, decoders and output; nothing failed is reused.
@@ -2098,6 +2244,7 @@ export function createBrowserBridge(options) {
2098
2244
  videoDecode,
2099
2245
  videoConversion: exportConversion,
2100
2246
  decodeFallbacks: pixels.decodeFallbacks,
2247
+ silentAudioSources: silentAudio.map((source) => source.id),
2101
2248
  renderer: renderer.rendererChoice,
2102
2249
  },
2103
2250
  };
@@ -2156,11 +2303,18 @@ export function createBrowserBridge(options) {
2156
2303
  : clearTimeout)(refreshFrame);
2157
2304
  ++binding;
2158
2305
  for (const controller of pendingImports)
2159
- controller.abort();
2306
+ controller.abort(new EditorError("disposed", "Bridge is disposed", "import"));
2160
2307
  for (const controller of analyses.values())
2161
2308
  controller.abort();
2162
2309
  globalThis.document?.removeEventListener("visibilitychange", visibility);
2163
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();
2164
2318
  await queue;
2165
2319
  await mixer?.close();
2166
2320
  await supplier?.close();
@@ -2193,7 +2347,7 @@ export function createBrowserBridge(options) {
2193
2347
  async putProviderSource({ id, name, provider }, { signal } = {}) {
2194
2348
  if (providerReadsFile(provider))
2195
2349
  throw new EditorError("unsupported_media", "A provider source that reads a file is imported with importFiles", "provider", id);
2196
- const generation = editor.generation;
2350
+ const scope = projectScope(signal);
2197
2351
  let read;
2198
2352
  try {
2199
2353
  read = await describeProvider(provider, signal);
@@ -2203,8 +2357,7 @@ export function createBrowserBridge(options) {
2203
2357
  throw error;
2204
2358
  throw new EditorError("unreadable_media", String(error?.message ?? error), "provider", id);
2205
2359
  }
2206
- if (disposed || editor.disposed || editor.generation !== generation)
2207
- throw new EditorError("stale_import", "Project changed while the source opened", "provider", id);
2360
+ scope.assert("provider", id);
2208
2361
  const assetId = id ?? crypto.randomUUID();
2209
2362
  const descriptor = editor.document.assets[assetId];
2210
2363
  const previous = editor.document.project.sources.find((candidate) => candidate.id === assetId);
@@ -2276,7 +2429,9 @@ export function createBrowserBridge(options) {
2276
2429
  pause,
2277
2430
  startExport,
2278
2431
  async importCaptions(file) {
2279
- const generation = editor.generation;
2432
+ if (disposed)
2433
+ throw new EditorError("disposed", "Bridge is disposed", "import");
2434
+ const scope = projectScope();
2280
2435
  // A larger file holds more cues than a project can, so refuse it unread.
2281
2436
  if (file.size > MAX_CAPTION_FILE_BYTES)
2282
2437
  throw new EditorError("invalid_captions", `${file.name} is ${file.size} bytes; a subtitle file is read up to ${MAX_CAPTION_FILE_BYTES}`, "import");
@@ -2289,8 +2444,7 @@ export function createBrowserBridge(options) {
2289
2444
  catch (error) {
2290
2445
  throw new EditorError("invalid_captions", `${file.name}: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
2291
2446
  }
2292
- if (disposed || editor.generation !== generation)
2293
- throw Error("Project changed during caption import");
2447
+ scope.assert("import");
2294
2448
  const assetId = crypto.randomUUID();
2295
2449
  const result = editor.dispatch({
2296
2450
  type: "asset.put",
@@ -2326,7 +2480,64 @@ export function createBrowserBridge(options) {
2326
2480
  return JSON.parse(measurer.measureLayout(JSON.stringify(generator), width, height, time, width, height));
2327
2481
  },
2328
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
+ },
2329
2538
  async generateProxy(id, { signal } = {}) {
2539
+ if (disposed)
2540
+ throw new EditorError("disposed", "Bridge is disposed", "proxy", id);
2330
2541
  const descriptor = editor.document.assets[id];
2331
2542
  // No single video file for the proxy maker to read.
2332
2543
  const provider = editor.document.project.sources.find((source) => source.id === id)?.provider;
@@ -2340,20 +2551,23 @@ export function createBrowserBridge(options) {
2340
2551
  throw new EditorError("proxy_busy", "A proxy of this source is being made", "proxy", id);
2341
2552
  proxyJobs.set(id, 0);
2342
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;
2343
2559
  let hold = null;
2344
2560
  try {
2345
2561
  for (;;) {
2346
2562
  // One proxy at a time and none during an export; a starting export preempts it.
2347
- const turn = await proxyTurn(signal);
2563
+ const turn = await proxyTurn(stop);
2348
2564
  try {
2349
2565
  // Held until its runtime is released so no page removes it meanwhile.
2350
2566
  hold = await proxyStore.hold(hash);
2351
2567
  // Notify listeners once per whole percent.
2352
2568
  let percent = 0;
2353
2569
  const found = await proxyStore.generate(runtime.file, descriptor.fingerprint, {
2354
- signal: signal
2355
- ? AbortSignal.any([signal, turn.signal])
2356
- : turn.signal,
2570
+ signal: AbortSignal.any([stop, turn.signal]),
2357
2571
  onProgress: (fraction) => {
2358
2572
  proxyJobs.set(id, fraction);
2359
2573
  const next = Math.floor(fraction * 100);
@@ -2363,13 +2577,20 @@ export function createBrowserBridge(options) {
2363
2577
  notifyAssets();
2364
2578
  },
2365
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;
2366
2586
  const adopted = adoptProxy(hash, found, hold);
2367
2587
  hold = null;
2368
2588
  await adopted;
2589
+ failedProxies.delete(hash);
2369
2590
  break;
2370
2591
  }
2371
2592
  catch (error) {
2372
- if (!turn.signal.aborted || signal?.aborted)
2593
+ if (!turn.signal.aborted || stop.aborted)
2373
2594
  throw error;
2374
2595
  void hold?.release();
2375
2596
  hold = null;
@@ -2440,6 +2661,8 @@ export function createBrowserBridge(options) {
2440
2661
  async removeProxies(hashes) {
2441
2662
  const wanted = new Set(hashes);
2442
2663
  const unlocked = [];
2664
+ for (const hash of wanted)
2665
+ failedProxies.delete(hash);
2443
2666
  for (const [hash, proxy] of proxies)
2444
2667
  if (wanted.has(hash)) {
2445
2668
  proxies.delete(hash);
@@ -78,3 +78,20 @@ export declare class ExportJob {
78
78
  */
79
79
  cancel(): Promise<void>;
80
80
  }
81
+ /**
82
+ * One extraction running on the page. It stops when `signal` aborts, on {@link cancel}, or when
83
+ * the bridge is disposed; a stopped run rejects with `EditorError` `cancelled`.
84
+ */
85
+ export declare class ExtractionJob<T> {
86
+ #private;
87
+ /** What `run` resolves to. */
88
+ readonly result: Promise<T>;
89
+ /**
90
+ * Starts `run` with the job's own signal.
91
+ *
92
+ * @param release Called once when the job settles.
93
+ */
94
+ constructor(run: (signal: AbortSignal) => Promise<T>, signal: AbortSignal | undefined, release: () => void);
95
+ /** Stops the run; resolves once it has settled. */
96
+ cancel(): Promise<void>;
97
+ }