@alpha2-sh/editor 0.6.1 → 0.7.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.
package/README.md CHANGED
@@ -90,7 +90,7 @@ const { dataSets } = await client.extract({ project, assets, request, plugin: {
90
90
  editor.applyExtraction({ dataSets, timings: {} }, { read });
91
91
  ```
92
92
 
93
- - In a page, `bridge.extract(run, { plugin, signal, onProgress })` reads the source's original media held by the bridge and resolves with `{ result, read }` for `applyExtraction`. It reads source input; timeline input is refused there.
93
+ - In a page, `bridge.extract(run, { plugin, signal, onProgress })` reads the source's original media held by the bridge and resolves with `{ result, read }` for `applyExtraction`. `plugin` is a plugin the app loaded with `loadPlugin`, shared by many runs, or `{ manifest, sha256, fetch? }` for the bridge to load; `onProgress` reports its files as they arrive (`phase: "load"`), then the extraction. `bridge.extractCapabilities()` says what it runs, for `pluginProblem` from `alpha2/plugins`. It reads a source or the timeline, whose frames it draws on a CPU renderer of its own as every surface reads them; timeline audio is not supplied.
94
94
  - `bridge.conform()` lists data sets made from media that has since changed in `stale_data`; their `made_by` says how to run them again.
95
95
 
96
96
  ## Browser bridge
@@ -140,8 +140,9 @@ await bridge.dispose();
140
140
  await editor.dispose();
141
141
  ```
142
142
 
143
- - Import checks each file with the engine (media, fonts, `.cube` LUTs, SRT and WebVTT captions through `importCaptions`) and adds it to the document in one undoable step. `importSequence` imports numbered PNG or OpenEXR files as one image sequence. A source whose provider reads no file, such as a LaTeX formula (`{ format: "latex", latex, font_size }`), is kept in the project itself: `putProviderSource` adds or edits one in one undoable step, and it draws in preview and both exports with no file to relink.
144
- - `bindPreview` draws on a canvas. With `runtimeAssets.workerFactory`, a worker running the `@alpha2-sh/editor/preview-worker` entry renders the preview off the main thread; without one, or when the worker fails, the main thread does. `hashWorkerFactory` (`@alpha2-sh/editor/hash-worker`) and `extensionsWorkerFactory` (`@alpha2-sh/editor/extensions-worker`, with `extensionsWasmUrl` and `extensionModuleUrls` such as `{ pdf }`) move file hashing and SVG, animated image, Lottie, OpenEXR and PDF reading into workers too.
143
+ - A file the application keeps on disk or a server can be imported, relinked or read as sequence frames without a `File`: pass a media reference `{ url, name, path? }` whose URL answers `Range` requests (`206` with `Content-Range`, readable from the page's workers, with CORS when cross-origin). The bridge reads it by range wherever it reads media (import probes, hashing, preview, proxies, extraction, browser export), and refuses a URL that does not answer ranges (`unreadable_media`).
144
+ - Import checks each file with the engine (media, fonts, `.cube` LUTs, SRT and WebVTT captions through `importCaptions`) and adds it to the document in one undoable step. `importSequence` imports numbered PNG or OpenEXR files as one image sequence. A source whose provider reads no file, such as a LaTeX formula (`{ format: "latex", latex, font_size }`), is kept in the project itself: `putProviderSource` adds or edits one in one undoable step, with `then` commands (such as the clip that shows it, sized from what the source opened at) in the same step, and it draws in preview and both exports with no file to relink.
145
+ - `bindPreview` draws on a canvas. With `runtimeAssets.workerFactory`, a worker running the `@alpha2-sh/editor/preview-worker` entry renders the preview off the main thread; without one, or when the worker fails, the main thread does. `extractWorkerFactory` (`@alpha2-sh/editor/extract-worker`) runs `bridge.extract`'s plugins off the main thread, one worker per run that a cancel terminates at once; `hashWorkerFactory` (`@alpha2-sh/editor/hash-worker`) and `extensionsWorkerFactory` (`@alpha2-sh/editor/extensions-worker`, with `extensionsWasmUrl` and `extensionModuleUrls` such as `{ pdf }`) move file hashing and SVG, animated image, Lottie, OpenEXR and PDF reading into workers too.
145
146
  - `seek`, `play` and `pause` move the playhead; with audio, playback follows the audio clock. Audio preview needs a cross-origin isolated page; editing and video preview do not.
146
147
  - `startExport` returns a job with `result`, progress (`subscribe`) and `cancel`. `container` (`mp4` by default, `mov`, `mkv` or `webm`) names the file and decides the codecs: an absent `videoCodec` or `audioCodec` is the container's default (H.264 and AAC, or VP9 and Opus for WebM, with Opus where a browser cannot encode AAC in MP4 or MKV), and one the container does not offer is refused. The output goes to a temporary file in the origin's private storage by default (`release()` deletes it), to a file the user picked (`output: { kind: "file", handle }`), or to memory (`output: { kind: "memory", maxBytes }`). Whether the browser encodes a codec is the browser's to say: `bridge.videoEncoders()` asks ahead, and an export with a codec the browser does not encode is refused before it renders.
147
148
 
@@ -159,7 +160,7 @@ The application owns the session: unmounting the provider does not dispose it.
159
160
 
160
161
  ## Native export
161
162
 
162
- `@alpha2-sh/editor/native-client` (`createNativeClient({ baseUrl })`) exports a document on an HTTP export service that the application runs, for example on top of [`@alpha2-sh/node`](https://github.com/alpha2-sh/alpha2/blob/main/packages/alpha2-node/README.md). It uploads the document's media (`bridge.nativeAssets`) and follows the job to a downloadable file.
163
+ `@alpha2-sh/editor/native-client` (`createNativeClient({ baseUrl })`) exports a document on an HTTP export service that the application runs, for example on top of [`@alpha2-sh/node`](https://github.com/alpha2-sh/alpha2/blob/main/packages/alpha2-node/README.md). It uploads the document's media (`bridge.nativeAssets`) and follows the job to a downloadable file. Media imported from a reference with a `path` is not uploaded: the render request carries it in `paths` (`{ [kind]: { [id]: path } }`, the kinds and ids of the upload URLs), for a service on the same machine to read in place of an upload. A service that takes `paths` should accept them only from pages it trusts and only under directories it allows. A job the service no longer has (an expired lease, a restarted service) is allocated and uploaded again by the next attempt, and an error status is classified by `failureClassOfHttpStatus` from `alpha2/export-failure`: a body past the service's limit (413) fails at once as `RESOURCE_LIMIT`, and 429 or 503 retries as `RESOURCE_BUSY` after `Retry-After`.
163
164
 
164
165
  ## License
165
166
 
@@ -18,11 +18,23 @@ import { registerCaptionFonts } from "./runtime/caption-fonts.js";
18
18
  import { AssetLibrary, audioDecoding, streamPeaks } from "./runtime/assets.js";
19
19
  import { SourcePixels, providerSettings, sameProviderSettings, } from "./runtime/sources.js";
20
20
  import { fingerprintFile } from "./runtime/fingerprint.js";
21
+ import { isRangeFile } from "./runtime/range-file.js";
22
+ import { openMediaReference } from "./runtime/media-reference.js";
21
23
  import { hashInWorker } from "./hash-worker.js";
24
+ import { extractInWorker } from "./extract-worker.js";
22
25
  import { callExtensions } from "./extensions-worker.js";
23
26
  import { keepProviderChoices, mayBeExtension, providerDocumentLimit, stageProviderFile, stageSequence, extensionWasmUrls, } from "./runtime/extension-import.js";
24
27
  import { ProxyStore } from "./runtime/proxies.js";
25
28
  import { blockingIssues, compareFingerprints, conformProject, sha256Blob, } from "alpha2/assets";
29
+ /** @type {import("alpha2/plugins").PluginCapabilities} */
30
+ const EXTRACT_CAPABILITIES = Object.freeze({
31
+ inputs: Object.freeze({
32
+ video: Object.freeze(["source", "timeline"]),
33
+ audio: Object.freeze(["source"]),
34
+ }),
35
+ artifacts: Object.freeze(["wasm"]),
36
+ slots: true,
37
+ });
26
38
  /**
27
39
  * An export refused before it rendered, with the engine's conform report. The message names sources
28
40
  * by `nameOf` (the document's asset names); the report and `entityId` use IDs.
@@ -1802,10 +1814,22 @@ export function createBrowserBridge(options) {
1802
1814
  },
1803
1815
  };
1804
1816
  }
1817
+ function openMedia(file, signal) {
1818
+ return file instanceof Blob || file?.url === undefined
1819
+ ? file
1820
+ : openMediaReference(file, signal);
1821
+ }
1822
+ async function nativeBytes(file) {
1823
+ if (!isRangeFile(file))
1824
+ return { blob: file };
1825
+ return file.path === undefined
1826
+ ? { blob: await file.blob() }
1827
+ : { path: file.path };
1828
+ }
1805
1829
  function importFiles(files, options = {}) {
1806
1830
  return importUnits(files.map((file) => ({
1807
1831
  name: file.name,
1808
- stage: (signal) => mediaAdapter.stage(file, signal),
1832
+ stage: async (signal) => mediaAdapter.stage(await openMedia(file, signal), signal),
1809
1833
  })), options);
1810
1834
  }
1811
1835
  function importSequence(files, { frameRate, missing = "reject", signal } = {}) {
@@ -1831,7 +1855,7 @@ export function createBrowserBridge(options) {
1831
1855
  throw new EditorError("unsupported_media", "This media adapter cannot import image sequences", "import");
1832
1856
  return {
1833
1857
  name: null,
1834
- stage: (signal) => mediaAdapter.stageSequence(files, options, signal),
1858
+ stage: async (signal) => mediaAdapter.stageSequence(await Promise.all(files.map((file) => openMedia(file, signal))), options, signal),
1835
1859
  };
1836
1860
  }
1837
1861
  /**
@@ -2035,11 +2059,90 @@ export function createBrowserBridge(options) {
2035
2059
  },
2036
2060
  };
2037
2061
  }
2062
+ function holdTimelineFrames(document, project) {
2063
+ requireShownText(document, project);
2064
+ const used = shownSources(project);
2065
+ const drawnResources = drawnEffectResources(project);
2066
+ refuseDegradedSources(document, project, used, "extract");
2067
+ const held = [];
2068
+ const map = new Map();
2069
+ const fonts = [];
2070
+ try {
2071
+ for (const source of [
2072
+ ...project.sources.filter((s) => used.has(s.id)),
2073
+ ...(project.effect_resources ?? []).filter((r) => drawnResources.has(r.id)),
2074
+ ]) {
2075
+ if (drawnByEngine(source))
2076
+ continue;
2077
+ const lease = acquireOwned(document, document.assets[source.id]);
2078
+ held.push(lease);
2079
+ map.set(source.id, sourceView(document, source.id, lease.value));
2080
+ }
2081
+ for (const font of heldFonts(document)) {
2082
+ const lease = acquireOwned(document, font);
2083
+ held.push(lease);
2084
+ fonts.push(lease.value);
2085
+ }
2086
+ fonts.push(...(runtimeAssets.fonts ?? []));
2087
+ }
2088
+ catch (error) {
2089
+ held.forEach((lease) => lease.release());
2090
+ throw error;
2091
+ }
2092
+ const effects = keptEffects();
2093
+ const lib = { get: (id) => map.get(id) };
2094
+ let started = null;
2095
+ const start = async () => {
2096
+ const { Engine } = await import("./runtime/engine.js");
2097
+ const pixels = new SourcePixels(lib, {
2098
+ extensionWasmUrls: extensionWasmUrls(runtimeAssets),
2099
+ videoDecode: "software",
2100
+ });
2101
+ const { width, height } = project.settings;
2102
+ const renderer = new Engine(new OffscreenCanvas(width, height), pixels, lib, runtimeAssets, { videoConversion, renderer: "cpu" });
2103
+ try {
2104
+ await renderer.start();
2105
+ await renderer.registerEffects(effects, "export");
2106
+ renderer.loadProject(project, "export");
2107
+ if (renderer.projectRuntimeEffects().length > 0)
2108
+ throw new EditorError("unsupported_media", "The timeline draws runtime effects, which the renderer that reads timeline frames for an extractor cannot draw", "extract");
2109
+ renderer.setCaptionFonts(fonts);
2110
+ pixels.setOutputSize(width, height);
2111
+ }
2112
+ catch (error) {
2113
+ await renderer.dispose();
2114
+ await pixels.dispose();
2115
+ throw error;
2116
+ }
2117
+ return { renderer, pixels };
2118
+ };
2119
+ return {
2120
+ async frame(time, width, height) {
2121
+ started ??= start();
2122
+ const { renderer } = await started;
2123
+ return {
2124
+ width,
2125
+ height,
2126
+ rgba: await renderer.readRgbaAt(time, width, height, {
2127
+ context: context(project, lib),
2128
+ }),
2129
+ };
2130
+ },
2131
+ async close() {
2132
+ held.forEach((lease) => lease.release());
2133
+ if (started === null)
2134
+ return;
2135
+ const { renderer, pixels } = await started.catch(() => ({}));
2136
+ await renderer?.dispose();
2137
+ await pixels?.dispose();
2138
+ },
2139
+ };
2140
+ }
2038
2141
  /**
2039
2142
  * Refuses an export up front when it shows a source imported for a degraded preview: the engine
2040
2143
  * would refuse its first frame, and browser tone mapping must not reach a file.
2041
2144
  */
2042
- function refuseDegradedSources(document, project, used) {
2145
+ function refuseDegradedSources(document, project, used, operation = "export") {
2043
2146
  const degraded = project.sources
2044
2147
  .filter((source) => used.has(source.id) &&
2045
2148
  originalOf(document, source.id)?.planarDecode === "unavailable")
@@ -2048,7 +2151,7 @@ export function createBrowserBridge(options) {
2048
2151
  return;
2049
2152
  const facts = { kind: "video", codec: null, softwareDecoder: "none" };
2050
2153
  const names = degraded.join(", ");
2051
- 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, {
2154
+ throw new EditorError("unsupported_media", `This browser cannot ${operation === "export" ? "export" : "read for an extractor"} ${names}: it decodes this HDR video only to frames the engine cannot read, so the preview shows it with the browser's tone mapping. Use the native host.`, operation, undefined, true, {
2052
2155
  cause: new PlanarDecodeUnavailableError(`${names}: no planar decode in this browser`, facts),
2053
2156
  });
2054
2157
  }
@@ -2344,7 +2447,7 @@ export function createBrowserBridge(options) {
2344
2447
  relink: (id, file, options) => importFiles([file], { ...options, relinkId: id }),
2345
2448
  importSequence,
2346
2449
  relinkSequence,
2347
- async putProviderSource({ id, name, provider }, { signal } = {}) {
2450
+ async putProviderSource({ id, name, provider }, { signal, then } = {}) {
2348
2451
  if (providerReadsFile(provider))
2349
2452
  throw new EditorError("unsupported_media", "A provider source that reads a file is imported with importFiles", "provider", id);
2350
2453
  const scope = projectScope(signal);
@@ -2362,7 +2465,7 @@ export function createBrowserBridge(options) {
2362
2465
  const descriptor = editor.document.assets[assetId];
2363
2466
  const previous = editor.document.project.sources.find((candidate) => candidate.id === assetId);
2364
2467
  const kind = providerKind(provider);
2365
- const result = editor.dispatch({
2468
+ const put = {
2366
2469
  type: "asset.put",
2367
2470
  asset: {
2368
2471
  ...(descriptor ?? { contentRevision: 0 }),
@@ -2378,7 +2481,17 @@ export function createBrowserBridge(options) {
2378
2481
  locator: "",
2379
2482
  provider,
2380
2483
  },
2381
- });
2484
+ };
2485
+ const following = typeof then === "function"
2486
+ ? then({
2487
+ assetId,
2488
+ width: read.report?.width ?? null,
2489
+ height: read.report?.height ?? null,
2490
+ })
2491
+ : (then ?? []);
2492
+ const result = editor.dispatch(following.length
2493
+ ? { type: "transaction", commands: [put, ...following] }
2494
+ : put);
2382
2495
  if (!result.ok)
2383
2496
  throw result.error;
2384
2497
  const runtime = filelessRuntime(editor.document, assetId);
@@ -2494,44 +2607,81 @@ export function createBrowserBridge(options) {
2494
2607
  throw result.error;
2495
2608
  return result.value;
2496
2609
  },
2610
+ extractCapabilities() {
2611
+ return EXTRACT_CAPABILITIES;
2612
+ },
2497
2613
  async extract(run, { plugin, extractor, signal, onProgress } = {}) {
2498
2614
  if (disposed)
2499
2615
  throw new EditorError("disposed", "Bridge is disposed", "extract");
2500
2616
  if ((plugin === undefined) === (extractor === undefined))
2501
2617
  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 ?? "";
2618
+ const timeline = run.input.from === "timeline";
2619
+ if (timeline)
2620
+ materializeText(editor.document);
2505
2621
  const { project, read } = editor.extractionProject();
2506
2622
  const document = editor.document;
2507
- const file = originalOf(document, id)?.file;
2508
- if (!file)
2623
+ const id = run.input.source_id ?? "";
2624
+ const file = timeline ? undefined : originalOf(document, id)?.file;
2625
+ if (!timeline && !file)
2509
2626
  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;
2627
+ const frames = timeline ? holdTimelineFrames(document, project) : null;
2628
+ const madeFrom = timeline
2629
+ ? undefined
2630
+ : (project.sources.find((source) => source.id === id)?.fingerprint ??
2631
+ document.assets[id]?.fingerprint);
2512
2632
  const job = new ExtractionJob(async (aborted) => {
2513
- const binding = await loadWasm();
2514
- const loaded = plugin
2515
- ? await loadPlugin(plugin.manifest, plugin.sha256, {
2633
+ const loaded = plugin === undefined || typeof plugin.extractor === "function"
2634
+ ? plugin
2635
+ : await loadPlugin(plugin.manifest, plugin.sha256, {
2516
2636
  ...(plugin.memoryBytes === undefined
2517
2637
  ? {}
2518
2638
  : { memoryBytes: plugin.memoryBytes }),
2639
+ ...(plugin.fetch === undefined
2640
+ ? {}
2641
+ : { fetch: plugin.fetch }),
2642
+ ...(plugin.supplied === undefined
2643
+ ? {}
2644
+ : { supplied: plugin.supplied }),
2645
+ ...(onProgress ? { onProgress } : {}),
2646
+ signal: aborted,
2647
+ });
2648
+ const factory = runtimeAssets.extractWorkerFactory;
2649
+ const inWorker = loaded && typeof factory === "function"
2650
+ ? await extractInWorker(factory, {
2651
+ ...(runtimeAssets.wasmUrl === undefined
2652
+ ? {}
2653
+ : {
2654
+ wasmUrl: new URL(runtimeAssets.wasmUrl, globalThis.location?.href).href,
2655
+ }),
2656
+ plugin: loaded,
2657
+ project,
2658
+ request: run,
2659
+ ...(file ? { media: { [id]: file } } : {}),
2660
+ ...(frames ? { timelineFrame: frames.frame } : {}),
2661
+ ...(madeFrom ? { madeFrom } : {}),
2662
+ ...(onProgress ? { onProgress } : {}),
2519
2663
  signal: aborted,
2520
2664
  })
2521
- : undefined;
2665
+ : null;
2666
+ if (inWorker !== null)
2667
+ return { result: inWorker, read };
2668
+ const binding = await loadWasm();
2522
2669
  const result = await runExtractor({
2523
2670
  binding,
2524
2671
  audioBinding: binding,
2525
2672
  project,
2526
2673
  request: run,
2527
- media: { [id]: file },
2674
+ ...(file ? { media: { [id]: file } } : {}),
2675
+ ...(frames ? { timelineFrame: frames.frame } : {}),
2528
2676
  ...(madeFrom ? { madeFrom } : {}),
2529
- ...(loaded ? { plugin: loaded } : {}),
2530
2677
  signal: aborted,
2531
2678
  ...(onProgress ? { onProgress } : {}),
2532
2679
  }, loaded ? loaded.extractor(run.params) : extractor);
2533
2680
  return { result, read };
2534
- }, signal, () => extractions.delete(job));
2681
+ }, signal, () => {
2682
+ extractions.delete(job);
2683
+ void frames?.close();
2684
+ });
2535
2685
  extractions.add(job);
2536
2686
  return job.result;
2537
2687
  },
@@ -2713,7 +2863,7 @@ export function createBrowserBridge(options) {
2713
2863
  result.push({
2714
2864
  id: `${asset.id}:${result.length}`,
2715
2865
  kind: "frames",
2716
- blob: file,
2866
+ ...(await nativeBytes(file)),
2717
2867
  name: file.name,
2718
2868
  locator,
2719
2869
  });
@@ -2729,6 +2879,20 @@ export function createBrowserBridge(options) {
2729
2879
  });
2730
2880
  continue;
2731
2881
  }
2882
+ const kind = asset.kind === "font"
2883
+ ? "caption-fonts"
2884
+ : asset.kind === "lut3d"
2885
+ ? "effect-assets"
2886
+ : "assets";
2887
+ if (isRangeFile(runtime.file)) {
2888
+ result.push({
2889
+ id: asset.id,
2890
+ kind,
2891
+ ...(await nativeBytes(runtime.file)),
2892
+ name: asset.name,
2893
+ });
2894
+ continue;
2895
+ }
2732
2896
  let blob = runtime.file;
2733
2897
  if (asset.kind === "font")
2734
2898
  blob = new Blob([runtime.bytes]);
@@ -2754,11 +2918,7 @@ export function createBrowserBridge(options) {
2754
2918
  throw Error(`Missing native bytes: ${asset.name}`);
2755
2919
  result.push({
2756
2920
  id: asset.id,
2757
- kind: asset.kind === "font"
2758
- ? "caption-fonts"
2759
- : asset.kind === "lut3d"
2760
- ? "effect-assets"
2761
- : "assets",
2921
+ kind,
2762
2922
  blob,
2763
2923
  name: asset.kind === "text" ? "text.png" : asset.name,
2764
2924
  });
@@ -3,6 +3,7 @@
3
3
  // `@alpha2-sh/editor/extensions-worker` entry pass `runtimeAssets.extensionsWorkerFactory`; each
4
4
  // call gets its own worker, terminated on cancel or past `EXTENSIONS_CALL_TIMEOUT_MS`.
5
5
  import { EditorError } from "../core/document.js";
6
+ import { reviveRangeFile } from "./runtime/range-file.js";
6
7
  import { exrFirstFrame, readProviderFile, readProviderSource, svgDiagnostics, } from "./runtime/extension-import.js";
7
8
  /**
8
9
  * How long one extensions worker call may run before the worker is terminated and the call fails as
@@ -32,7 +33,7 @@ async function run(request, wasmUrl, load, signal) {
32
33
  const extensions = await load(wasmUrl);
33
34
  signal?.throwIfAborted();
34
35
  const bytes = request.file
35
- ? new Uint8Array(await request.file.arrayBuffer())
36
+ ? new Uint8Array(await reviveRangeFile(request.file).arrayBuffer())
36
37
  : undefined;
37
38
  signal?.throwIfAborted();
38
39
  return call(extensions, bytes, request);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ // The `@alpha2-sh/editor/extract-worker` entry (see `runtimeAssets.extractWorkerFactory`).
2
+ import { installExtractWorker } from "./extract-worker.js";
3
+ installExtractWorker(self);
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Answers one `{ type: "run" }` posted to `scope` (a dedicated worker's global): runs the plugin
3
+ * with `runExtractor`, posting `{ type: "progress" }` as it goes and `{ type: "frame", id, time,
4
+ * width, height }` for each timeline frame, which the page answers with `{ type: "frame", id,
5
+ * rgba }` or `{ id, error }`; then `{ type: "done", result }` or `{ type: "failed", error }`.
6
+ * @param {{ onmessage: ((event: MessageEvent) => void) | null, postMessage(message: unknown, transfer?: Transferable[]): void }} scope
7
+ */
8
+ export function installExtractWorker(scope: {
9
+ onmessage: ((event: MessageEvent) => void) | null;
10
+ postMessage(message: unknown, transfer?: Transferable[]): void;
11
+ }): void;
12
+ /**
13
+ * Runs `plugin` (`loadPlugin`'s) in a worker from `factory` (running {@link installExtractWorker})
14
+ * over `run`, as `runExtractor` would on the page. `timelineFrame` draws the frames a timeline
15
+ * input asks for, on the page. Aborting `signal` terminates the worker at once, a plugin call in
16
+ * flight included, and rejects with its reason. Resolves with `null` when the worker does not
17
+ * start, so the caller can run on the page instead.
18
+ * @param {() => Worker} factory
19
+ * @param {{
20
+ * wasmUrl?: string,
21
+ * plugin: import("alpha2/plugins").LoadedPlugin,
22
+ * project: import("alpha2/project").Project,
23
+ * request: import("alpha2/extractor").ExtractRun,
24
+ * media?: Readonly<Record<string, Blob | import("./types.js").RangeFile>>,
25
+ * timelineFrame?: (time: bigint, width: number, height: number) => Promise<{ rgba: Uint8Array }>,
26
+ * madeFrom?: unknown,
27
+ * onProgress?: (progress: import("alpha2/extractor").ExtractProgress) => void,
28
+ * signal: AbortSignal,
29
+ * }} options
30
+ * @returns {Promise<import("alpha2/extractor").ExtractResult | null>}
31
+ */
32
+ export function extractInWorker(factory: () => Worker, options: {
33
+ wasmUrl?: string;
34
+ plugin: import("alpha2/plugins").LoadedPlugin;
35
+ project: import("alpha2/project").Project;
36
+ request: import("alpha2/extractor").ExtractRun;
37
+ media?: Readonly<Record<string, Blob | import("./types.js").RangeFile>>;
38
+ timelineFrame?: (time: bigint, width: number, height: number) => Promise<{
39
+ rgba: Uint8Array;
40
+ }>;
41
+ madeFrom?: unknown;
42
+ onProgress?: (progress: import("alpha2/extractor").ExtractProgress) => void;
43
+ signal: AbortSignal;
44
+ }): Promise<import("alpha2/extractor").ExtractResult | null>;
@@ -0,0 +1,172 @@
1
+ // Runs a plugin's extraction off the page's thread. Hosts bundling the
2
+ // `@alpha2-sh/editor/extract-worker` entry pass `runtimeAssets.extractWorkerFactory`; each run gets
3
+ // its own worker, terminated when it settles or is cancelled.
4
+ import { runExtractor } from "alpha2/extract";
5
+ import { restorePlugin } from "alpha2/plugins";
6
+ import { reviveRangeFile } from "./runtime/range-file.js";
7
+ import { loadEngineWasm } from "./runtime/wasm.js";
8
+ /** An error as it crosses to the page: its name, message, code and details. */
9
+ function wireError(error) {
10
+ return {
11
+ name: error?.name ?? "Error",
12
+ message: String(error?.message ?? error),
13
+ ...(typeof error?.code === "string" ? { code: error.code } : {}),
14
+ ...(error?.details === undefined ? {} : { details: error.details }),
15
+ };
16
+ }
17
+ /** The error the worker reported, with the code and details callers read. */
18
+ function pageError(wired) {
19
+ const error = new Error(wired.message);
20
+ error.name = wired.name;
21
+ if (wired.code !== undefined)
22
+ error.code = wired.code;
23
+ if (wired.details !== undefined)
24
+ error.details = wired.details;
25
+ return error;
26
+ }
27
+ /**
28
+ * Answers one `{ type: "run" }` posted to `scope` (a dedicated worker's global): runs the plugin
29
+ * with `runExtractor`, posting `{ type: "progress" }` as it goes and `{ type: "frame", id, time,
30
+ * width, height }` for each timeline frame, which the page answers with `{ type: "frame", id,
31
+ * rgba }` or `{ id, error }`; then `{ type: "done", result }` or `{ type: "failed", error }`.
32
+ * @param {{ onmessage: ((event: MessageEvent) => void) | null, postMessage(message: unknown, transfer?: Transferable[]): void }} scope
33
+ */
34
+ export function installExtractWorker(scope) {
35
+ const frames = new Map();
36
+ let nextFrame = 0;
37
+ scope.onmessage = async ({ data }) => {
38
+ if (data?.type === "frame") {
39
+ const pending = frames.get(data.id);
40
+ frames.delete(data.id);
41
+ if (data.error === undefined)
42
+ pending?.resolve(data.rgba);
43
+ else
44
+ pending?.reject(pageError(data.error));
45
+ return;
46
+ }
47
+ if (data?.type !== "run")
48
+ return;
49
+ try {
50
+ const binding = await loadEngineWasm(data.wasmUrl);
51
+ const plugin = restorePlugin(data.plugin);
52
+ const timelineFrame = data.timeline
53
+ ? (time, width, height) => new Promise((resolve, reject) => {
54
+ const id = nextFrame++;
55
+ frames.set(id, { resolve, reject });
56
+ scope.postMessage({ type: "frame", id, time, width, height });
57
+ }).then((rgba) => ({ width, height, rgba }))
58
+ : undefined;
59
+ const result = await runExtractor({
60
+ binding,
61
+ audioBinding: binding,
62
+ project: data.project,
63
+ request: data.request,
64
+ ...(data.media
65
+ ? {
66
+ media: Object.fromEntries(Object.entries(data.media).map(([id, file]) => [
67
+ id,
68
+ reviveRangeFile(file),
69
+ ])),
70
+ }
71
+ : {}),
72
+ ...(timelineFrame ? { timelineFrame } : {}),
73
+ ...(data.madeFrom ? { madeFrom: data.madeFrom } : {}),
74
+ onProgress: (progress) => scope.postMessage({ type: "progress", progress }),
75
+ }, plugin.extractor(data.request.params));
76
+ scope.postMessage({ type: "done", result });
77
+ }
78
+ catch (error) {
79
+ scope.postMessage({ type: "failed", error: wireError(error) });
80
+ }
81
+ };
82
+ }
83
+ /**
84
+ * Runs `plugin` (`loadPlugin`'s) in a worker from `factory` (running {@link installExtractWorker})
85
+ * over `run`, as `runExtractor` would on the page. `timelineFrame` draws the frames a timeline
86
+ * input asks for, on the page. Aborting `signal` terminates the worker at once, a plugin call in
87
+ * flight included, and rejects with its reason. Resolves with `null` when the worker does not
88
+ * start, so the caller can run on the page instead.
89
+ * @param {() => Worker} factory
90
+ * @param {{
91
+ * wasmUrl?: string,
92
+ * plugin: import("alpha2/plugins").LoadedPlugin,
93
+ * project: import("alpha2/project").Project,
94
+ * request: import("alpha2/extractor").ExtractRun,
95
+ * media?: Readonly<Record<string, Blob | import("./types.js").RangeFile>>,
96
+ * timelineFrame?: (time: bigint, width: number, height: number) => Promise<{ rgba: Uint8Array }>,
97
+ * madeFrom?: unknown,
98
+ * onProgress?: (progress: import("alpha2/extractor").ExtractProgress) => void,
99
+ * signal: AbortSignal,
100
+ * }} options
101
+ * @returns {Promise<import("alpha2/extractor").ExtractResult | null>}
102
+ */
103
+ export async function extractInWorker(factory, options) {
104
+ const { transferablePlugin } = await import("alpha2/plugins");
105
+ const { signal } = options;
106
+ signal.throwIfAborted();
107
+ let worker;
108
+ try {
109
+ worker = factory();
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ return new Promise((resolve, reject) => {
115
+ let started = false;
116
+ const end = () => {
117
+ signal.removeEventListener("abort", abort);
118
+ worker.terminate();
119
+ };
120
+ const abort = () => {
121
+ end();
122
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
123
+ };
124
+ signal.addEventListener("abort", abort, { once: true });
125
+ worker.onmessage = async ({ data }) => {
126
+ started = true;
127
+ if (data?.type === "progress")
128
+ options.onProgress?.(data.progress);
129
+ else if (data?.type === "frame") {
130
+ try {
131
+ const { rgba } = await options.timelineFrame(data.time, data.width, data.height);
132
+ worker.postMessage({ type: "frame", id: data.id, rgba }, [
133
+ rgba.buffer,
134
+ ]);
135
+ }
136
+ catch (error) {
137
+ worker.postMessage({
138
+ type: "frame",
139
+ id: data.id,
140
+ error: wireError(error),
141
+ });
142
+ }
143
+ }
144
+ else if (data?.type === "done") {
145
+ end();
146
+ resolve(data.result);
147
+ }
148
+ else if (data?.type === "failed") {
149
+ end();
150
+ reject(pageError(data.error));
151
+ }
152
+ };
153
+ worker.onerror = (event) => {
154
+ event?.preventDefault?.();
155
+ end();
156
+ if (started)
157
+ reject(new Error(`the extraction worker failed: ${event?.message}`));
158
+ else
159
+ resolve(null);
160
+ };
161
+ worker.postMessage({
162
+ type: "run",
163
+ ...(options.wasmUrl === undefined ? {} : { wasmUrl: options.wasmUrl }),
164
+ plugin: transferablePlugin(options.plugin),
165
+ project: options.project,
166
+ request: options.request,
167
+ timeline: options.timelineFrame !== undefined,
168
+ ...(options.media ? { media: options.media } : {}),
169
+ ...(options.madeFrom ? { madeFrom: options.madeFrom } : {}),
170
+ });
171
+ });
172
+ }
@@ -2,6 +2,7 @@
2
2
  // Hosts bundling the `@alpha2-sh/editor/hash-worker` entry pass `runtimeAssets.hashWorkerFactory`;
3
3
  // each file gets its own worker, terminated on cancel.
4
4
  import { sha256Blob } from "alpha2/assets";
5
+ import { reviveRangeFile } from "./runtime/range-file.js";
5
6
  /**
6
7
  * Answers hash requests posted to `scope` (a dedicated worker's global): `{ type: "hash", file }`
7
8
  * gets `{ type: "progress", bytes }` while reading, then `{ type: "hashed", sha256 }`, or
@@ -13,7 +14,7 @@ export function installHashWorker(scope) {
13
14
  if (data?.type !== "hash")
14
15
  return;
15
16
  try {
16
- const sha256 = await sha256Blob(data.file, {
17
+ const sha256 = await sha256Blob(reviveRangeFile(data.file), {
17
18
  onProgress: (bytes) => scope.postMessage({ type: "progress", bytes }),
18
19
  });
19
20
  scope.postMessage({ type: "hashed", sha256 });
@@ -134,7 +134,7 @@ export class AssetLibrary {
134
134
  name: any;
135
135
  locator: any;
136
136
  file: any;
137
- url: string;
137
+ url: any;
138
138
  video: HTMLVideoElement | null;
139
139
  width: any;
140
140
  height: any;
@@ -193,7 +193,7 @@ export class AssetLibrary {
193
193
  name: any;
194
194
  locator: any;
195
195
  file: any;
196
- url: string;
196
+ url: any;
197
197
  video: HTMLVideoElement | null;
198
198
  width: any;
199
199
  height: any;