@alpha2-sh/editor 0.4.5 → 0.4.6

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.
@@ -16,7 +16,7 @@ import { hashInWorker } from "./hash-worker.js";
16
16
  import { callExtensions } from "./extensions-worker.js";
17
17
  import { keepProviderChoices, mayBeExtension, providerDocumentLimit, stageProviderFile, stageSequence, } from "./runtime/extension-import.js";
18
18
  import { ProxyStore } from "./runtime/proxies.js";
19
- import { blockingIssues, compareFingerprints, conformProject, } from "alpha2/assets";
19
+ import { blockingIssues, compareFingerprints, conformProject, sha256Blob, } from "alpha2/assets";
20
20
  /**
21
21
  * An export refused before it rendered: the engine's conform report says why. The message names
22
22
  * each source as `nameOf` does (the document's asset names), the report and `entityId` by ID.
@@ -43,6 +43,11 @@ const PLAYBACK_POLICIES = Object.freeze([
43
43
  "silent_scrub",
44
44
  "offline_exact",
45
45
  ]);
46
+ /**
47
+ * Files of one import staged at once. Each hashes its whole file in its own worker, at about
48
+ * 200 MB/s: four read about 800 MB/s, below a local SSD, and one core stays with the page.
49
+ */
50
+ const IMPORT_STAGE_CONCURRENCY = 4;
46
51
  /**
47
52
  * How long Play waits for sound to start before playing the picture without it. A first start loads
48
53
  * and compiles the audio worklet and decodes the first block, about 1.5 s on Firefox.
@@ -64,7 +69,7 @@ const AUDIO_START_TIMEOUT_MS = 3000;
64
69
  export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFactory, extensionsWorkerFactory, } = {}) {
65
70
  const hash = hashWorkerFactory
66
71
  ? (file, options) => hashInWorker(hashWorkerFactory, file, options)
67
- : undefined;
72
+ : sha256Blob;
68
73
  const module = {
69
74
  factory: extensionsWorkerFactory,
70
75
  wasmUrl: extensionsWasmUrl,
@@ -96,98 +101,121 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
96
101
  },
97
102
  async stage(file, signal, { fingerprint: wanted = true } = {}) {
98
103
  signal.throwIfAborted();
104
+ // The hash reads the whole file, so it starts now and runs while the file is probed.
105
+ const hashing = new AbortController();
106
+ const stop = () => hashing.abort(signal.reason);
107
+ signal.addEventListener("abort", stop, { once: true });
108
+ const started = wanted ? hash(file, { signal: hashing.signal }) : null;
109
+ started?.catch(() => { }); // awaited below when used; a failed stage aborts it
99
110
  /** The file's fingerprint, unless the caller has no use for it (a proxy being adopted). */
100
111
  const fingerprintOf = (kind, options) => wanted
101
- ? fingerprintFile(file, kind, { signal, hash, ...options })
112
+ ? fingerprintFile(file, kind, {
113
+ signal,
114
+ hash: () => started,
115
+ ...options,
116
+ })
102
117
  : undefined;
103
- // Recognized by its bytes; the provider module loads only for bytes that could be one.
104
- const head = new Uint8Array(await file.slice(0, 4096).arrayBuffer());
105
- if (mayBeExtension(head)) {
106
- // Parsed whole in provider memory that never shrinks, so an oversize file is refused unread.
107
- const document = providerDocumentLimit(head);
108
- if (document !== null && file.size > document.limit)
109
- throw new EditorError("too_large", `${file.name} is ${file.size} bytes; a ${document.what} is read up to ${document.limit}`, "import");
110
- const found = await read("read", file, signal);
111
- signal.throwIfAborted();
112
- if (found)
113
- return stageProviderFile(file, found, await fingerprintOf("image"));
118
+ try {
119
+ return await stageFile(file, signal, fingerprintOf);
120
+ }
121
+ catch (error) {
122
+ hashing.abort(error);
123
+ throw error;
124
+ }
125
+ finally {
126
+ signal.removeEventListener("abort", stop);
127
+ }
128
+ },
129
+ };
130
+ /** Stages `file` as the media its bytes or name say it is; `fingerprintOf` gives its evidence. */
131
+ async function stageFile(file, signal, fingerprintOf) {
132
+ // Recognized by its bytes; the provider module loads only for bytes that could be one.
133
+ const head = new Uint8Array(await file.slice(0, 4096).arrayBuffer());
134
+ if (mayBeExtension(head)) {
135
+ // Parsed whole in provider memory that never shrinks, so an oversize file is refused unread.
136
+ const document = providerDocumentLimit(head);
137
+ if (document !== null && file.size > document.limit)
138
+ throw new EditorError("too_large", `${file.name} is ${file.size} bytes; a ${document.what} is read up to ${document.limit}`, "import");
139
+ const found = await read("read", file, signal);
140
+ signal.throwIfAborted();
141
+ if (found)
142
+ return stageProviderFile(file, found, await fingerprintOf("image"));
143
+ }
144
+ if (/\.(ttf|otf|ttc|otc)$/i.test(file.name)) {
145
+ const bytes = new Uint8Array(await file.arrayBuffer());
146
+ signal.throwIfAborted();
147
+ // The engine's parser decides: FontFace also loads WOFF and WOFF2, which the engine refuses.
148
+ const { loadEngineWasm } = await import("./runtime/wasm.js");
149
+ const { checkFont } = await loadEngineWasm(wasmUrl);
150
+ signal.throwIfAborted();
151
+ try {
152
+ checkFont(bytes, 0);
114
153
  }
115
- if (/\.(ttf|otf|ttc|otc)$/i.test(file.name)) {
116
- const bytes = new Uint8Array(await file.arrayBuffer());
154
+ catch (error) {
155
+ throw new EditorError("unreadable_media", `Cannot read ${file.name} as a font: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
156
+ }
157
+ const id = crypto.randomUUID();
158
+ let face;
159
+ if (typeof FontFace !== "undefined") {
160
+ face = new FontFace(`alpha2-font-${id}`, bytes);
161
+ await face.load();
117
162
  signal.throwIfAborted();
118
- // The engine's parser decides: FontFace also loads WOFF and WOFF2, which the engine refuses.
163
+ globalThis.document?.fonts.add(face);
164
+ }
165
+ return {
166
+ runtime: {
167
+ id,
168
+ kind: "font",
169
+ name: file.name,
170
+ bytes,
171
+ faceIndex: 0,
172
+ family: `alpha2-font-${id}`,
173
+ },
174
+ description: { id, kind: "font", name: file.name },
175
+ fingerprint: await fingerprintOf("font"),
176
+ dispose() {
177
+ if (face)
178
+ globalThis.document?.fonts.delete(face);
179
+ },
180
+ };
181
+ }
182
+ const library = new AssetLibrary();
183
+ try {
184
+ const runtime = file.name.toLowerCase().endsWith(".cube")
185
+ ? await library.importEffectResource(file, "lut3d")
186
+ : await library.importFile(file, { signal });
187
+ signal.throwIfAborted();
188
+ if (runtime.kind === "lut3d") {
189
+ // The engine's parser validates the LUT once here rather than at every load.
119
190
  const { loadEngineWasm } = await import("./runtime/wasm.js");
120
- const { checkFont } = await loadEngineWasm(wasmUrl);
191
+ const { checkLut3d } = await loadEngineWasm(wasmUrl);
121
192
  signal.throwIfAborted();
122
193
  try {
123
- checkFont(bytes, 0);
194
+ checkLut3d(runtime.text);
124
195
  }
125
196
  catch (error) {
126
- throw new EditorError("unreadable_media", `Cannot read ${file.name} as a font: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
127
- }
128
- const id = crypto.randomUUID();
129
- let face;
130
- if (typeof FontFace !== "undefined") {
131
- face = new FontFace(`alpha2-font-${id}`, bytes);
132
- await face.load();
133
- signal.throwIfAborted();
134
- globalThis.document?.fonts.add(face);
135
- }
136
- return {
137
- runtime: {
138
- id,
139
- kind: "font",
140
- name: file.name,
141
- bytes,
142
- faceIndex: 0,
143
- family: `alpha2-font-${id}`,
144
- },
145
- description: { id, kind: "font", name: file.name },
146
- fingerprint: await fingerprintOf("font"),
147
- dispose() {
148
- if (face)
149
- globalThis.document?.fonts.delete(face);
150
- },
151
- };
152
- }
153
- const library = new AssetLibrary();
154
- try {
155
- const runtime = file.name.toLowerCase().endsWith(".cube")
156
- ? await library.importEffectResource(file, "lut3d")
157
- : await library.importFile(file);
158
- signal.throwIfAborted();
159
- if (runtime.kind === "lut3d") {
160
- // The engine's parser validates the LUT once here rather than at every load.
161
- const { loadEngineWasm } = await import("./runtime/wasm.js");
162
- const { checkLut3d } = await loadEngineWasm(wasmUrl);
163
- signal.throwIfAborted();
164
- try {
165
- checkLut3d(runtime.text);
166
- }
167
- catch (error) {
168
- throw new EditorError("unreadable_media", `Cannot read ${file.name} as a 3D LUT: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
169
- }
197
+ throw new EditorError("unreadable_media", `Cannot read ${file.name} as a 3D LUT: ${error instanceof Error ? error.message : String(error)}`, "import", undefined, true, { cause: error });
170
198
  }
171
- const description = library.projectManifest()[0];
172
- const fingerprint = await fingerprintOf(runtime.kind, {
173
- size: runtime.width
174
- ? { width: runtime.width, height: runtime.height }
175
- : undefined,
176
- });
177
- signal.throwIfAborted();
178
- return {
179
- runtime,
180
- description,
181
- fingerprint,
182
- dispose: () => library.dispose(),
183
- };
184
- }
185
- catch (error) {
186
- library.dispose();
187
- throw error;
188
199
  }
189
- },
190
- };
200
+ const description = library.projectManifest()[0];
201
+ const fingerprint = await fingerprintOf(runtime.kind, {
202
+ size: runtime.width
203
+ ? { width: runtime.width, height: runtime.height }
204
+ : undefined,
205
+ });
206
+ signal.throwIfAborted();
207
+ return {
208
+ runtime,
209
+ description,
210
+ fingerprint,
211
+ dispose: () => library.dispose(),
212
+ };
213
+ }
214
+ catch (error) {
215
+ library.dispose();
216
+ throw error;
217
+ }
218
+ }
191
219
  }
192
220
  /**
193
221
  * Creates the browser runtime for an editor session: preview, playback, import, proxies and
@@ -198,8 +226,9 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
198
226
  * @returns {import("./types.js").BrowserBridge}
199
227
  */
200
228
  export function createBrowserBridge(options) {
201
- const { editor, runtimeAssets = {}, mediaAdapter = createMediaAdapter(runtimeAssets), resourceLimit = 128, audio = true, onError = () => { }, assetDecisions, previewScale: initialPreviewScale = 0.5, } = options;
229
+ const { editor, runtimeAssets = {}, mediaAdapter = createMediaAdapter(runtimeAssets), resourceLimit = 128, audio = true, onError = () => { }, assetDecisions, previewScale: initialPreviewScale = 0.5, videoConversion: initialVideoConversion = "engine", } = options;
202
230
  let previewScale = checkedPreviewScale(initialPreviewScale);
231
+ const videoConversion = checkedVideoConversion(initialVideoConversion, "bridge");
203
232
  // A test's stand-in for origin storage, kept out of the public options.
204
233
  const proxyStore =
205
234
  /** @type {{ proxyStore?: ProxyStore }} */ (options).proxyStore ??
@@ -1325,7 +1354,7 @@ export function createBrowserBridge(options) {
1325
1354
  const useWorker = features.worker.available && typeof canvas.getContext === "function";
1326
1355
  engine = new Engine(useWorker ? new OffscreenCanvas(canvas.width, canvas.height) : canvas, sources, library, runtimeAssets,
1327
1356
  // A frame shown at once matters more in a preview than the engine's conversion of it.
1328
- { unreadableFrames: "present" });
1357
+ { unreadableFrames: "present", videoConversion });
1329
1358
  mixer = new EngineAudioMixer(runtimeAssets, { enabled: audio });
1330
1359
  mixer.setMasterVolume(monitorVolume);
1331
1360
  stalledAudio = null;
@@ -1352,6 +1381,7 @@ export function createBrowserBridge(options) {
1352
1381
  bitmapOutput: true,
1353
1382
  width: canvas.width,
1354
1383
  height: canvas.height,
1384
+ videoConversion,
1355
1385
  });
1356
1386
  // A worker that cannot start leaves the surface to the main renderer.
1357
1387
  try {
@@ -1601,6 +1631,10 @@ export function createBrowserBridge(options) {
1601
1631
  stage: (signal) => mediaAdapter.stageSequence(files, options, signal),
1602
1632
  };
1603
1633
  }
1634
+ /**
1635
+ * Stages `units` (at most {@link IMPORT_STAGE_CONCURRENCY} at once) and adds them to the document
1636
+ * in their order, as one undo step; a relink has exactly one.
1637
+ */
1604
1638
  async function importUnits(units, { signal, relinkId } = {}) {
1605
1639
  if (disposed)
1606
1640
  throw new EditorError("disposed", "Bridge is disposed", "import");
@@ -1610,14 +1644,34 @@ export function createBrowserBridge(options) {
1610
1644
  signal?.addEventListener("abort", abort, { once: true });
1611
1645
  if (signal?.aborted)
1612
1646
  abort();
1613
- const staged = [], leases = [], commands = [];
1647
+ // Index `i` is unit `i`'s staged asset; a unit never started leaves its slot empty.
1648
+ const staged = new Array(units.length), leases = [], commands = [];
1614
1649
  try {
1615
1650
  if (relinkId && units.length !== 1)
1616
1651
  throw new EditorError("relink_conflict", "Relink accepts exactly one file", "relink", relinkId);
1617
- for (const unit of units) {
1618
- const item = await unit.stage(controller.signal);
1652
+ // Staged together, committed in order. The first file that fails stops the rest, and its
1653
+ // error is the import's, not the cancellation the others then see.
1654
+ let failure = null;
1655
+ let next = 0;
1656
+ const stageNext = async () => {
1657
+ while (next < units.length && failure === null) {
1658
+ const index = next++;
1659
+ try {
1660
+ staged[index] = await units[index].stage(controller.signal);
1661
+ }
1662
+ catch (error) {
1663
+ failure ??= { error };
1664
+ controller.abort(error);
1665
+ }
1666
+ }
1667
+ };
1668
+ const limit = Math.max(1, Math.min(IMPORT_STAGE_CONCURRENCY, (globalThis.navigator?.hardwareConcurrency ?? 2) - 1));
1669
+ await Promise.all(Array.from({ length: Math.min(limit, units.length) }, stageNext));
1670
+ if (failure)
1671
+ throw failure.error;
1672
+ for (const [index, unit] of units.entries()) {
1673
+ const item = staged[index];
1619
1674
  const fileName = unit.name ?? item.name ?? item.runtime.name;
1620
- staged.push(item);
1621
1675
  controller.signal.throwIfAborted();
1622
1676
  if (disposed || editor.disposed || editor.generation !== generation)
1623
1677
  throw new EditorError("stale_import", "Project changed during import", "import");
@@ -1704,7 +1758,7 @@ export function createBrowserBridge(options) {
1704
1758
  entry.lease.release();
1705
1759
  }
1706
1760
  for (const item of staged.slice(leases.length))
1707
- item.dispose();
1761
+ item?.dispose();
1708
1762
  throw error;
1709
1763
  }
1710
1764
  finally {
@@ -1763,6 +1817,7 @@ export function createBrowserBridge(options) {
1763
1817
  const videoDecode = options.videoDecode ?? "auto";
1764
1818
  if (videoDecode !== "auto" && videoDecode !== "software")
1765
1819
  throw new EditorError("invalid_video_decode", `Export videoDecode must be "auto" or "software"; received ${JSON.stringify(videoDecode)}`, "export");
1820
+ const exportConversion = checkedVideoConversion(options.videoConversion ?? videoConversion, "export");
1766
1821
  materializeText(editor.document);
1767
1822
  const snapshot = editor.document, revision = editor.revision, effects = keptEffects();
1768
1823
  const compiled = compileEditorDocument(snapshot);
@@ -1810,7 +1865,7 @@ export function createBrowserBridge(options) {
1810
1865
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1811
1866
  videoDecode,
1812
1867
  });
1813
- const renderer = new Engine(new OffscreenCanvas(project.settings.width, project.settings.height), pixels, lib, runtimeAssets);
1868
+ const renderer = new Engine(new OffscreenCanvas(project.settings.width, project.settings.height), pixels, lib, runtimeAssets, { videoConversion: exportConversion });
1814
1869
  const audio = new AudioWindowSupplier(lib);
1815
1870
  try {
1816
1871
  signal.throwIfAborted();
@@ -1884,6 +1939,7 @@ export function createBrowserBridge(options) {
1884
1939
  report: {
1885
1940
  ...result,
1886
1941
  videoDecode,
1942
+ videoConversion: exportConversion,
1887
1943
  decodeFallbacks: pixels.decodeFallbacks,
1888
1944
  },
1889
1945
  };
@@ -2403,6 +2459,12 @@ function checkedPreviewScale(scale) {
2403
2459
  throw new EditorError("invalid_preview_scale", "The preview scale must be a number above 0 and at most 8", "preview");
2404
2460
  return scale;
2405
2461
  }
2462
+ /** `value` as who converts decoded SDR frames: `engine` or `browser`. */
2463
+ function checkedVideoConversion(value, operation) {
2464
+ if (value !== "engine" && value !== "browser")
2465
+ throw new EditorError("invalid_video_conversion", `videoConversion must be "engine" or "browser"; received ${JSON.stringify(value)}`, operation);
2466
+ return value;
2467
+ }
2406
2468
  /**
2407
2469
  * Whether the engine draws a source itself, so no file backs it: a generated source or a
2408
2470
  * composition.
@@ -1,14 +1,15 @@
1
1
  /**
2
2
  * What a video container holds, read by the demuxer: its picture (`video`: size, frame rate, an HDR
3
- * declaration), or null when it has no video track, and whether it has an audio stream. Null when
4
- * the demuxer cannot read the container.
3
+ * declaration, and whether WebCodecs decodes it), or null when it has no video track, and whether
4
+ * it has an audio stream. Null when the demuxer cannot read the container.
5
5
  */
6
6
  export function probeVideo(file: any): Promise<{
7
7
  video: {
8
- colorMetadata: import("alpha2").ColorMetadata | null;
8
+ colorMetadata: import("alpha2/project").ColorMetadata | null;
9
9
  width: number;
10
10
  height: number;
11
11
  frameRate: number;
12
+ decodable: boolean;
12
13
  } | null;
13
14
  hasAudio: boolean;
14
15
  audioDecodable: boolean;
@@ -98,7 +99,7 @@ export class AssetLibrary {
98
99
  locator: any;
99
100
  file: any;
100
101
  url: string;
101
- video: HTMLVideoElement;
102
+ video: HTMLVideoElement | null;
102
103
  width: any;
103
104
  height: any;
104
105
  frameRate: any;
@@ -131,9 +132,10 @@ export class AssetLibrary {
131
132
  * Imports one browser file as an image, video or audio asset. Rejects with an `EditorError`:
132
133
  * `unsupported_media` for a file that is none of those, `unreadable_media` for one that is but
133
134
  * that this browser could not read (a codec it does not decode, a damaged file), with the
134
- * decoder's or demuxer's reason in the message and as the `cause`.
135
+ * decoder's or demuxer's reason in the message and as the `cause`. Rejects with `signal`'s
136
+ * reason once it aborts a decode.
135
137
  */
136
- importFile(file: any): Promise<{
138
+ importFile(file: any, { signal }?: {}): Promise<{
137
139
  id: any;
138
140
  kind: string;
139
141
  name: any;
@@ -151,7 +153,7 @@ export class AssetLibrary {
151
153
  locator: any;
152
154
  file: any;
153
155
  url: string;
154
- video: HTMLVideoElement;
156
+ video: HTMLVideoElement | null;
155
157
  width: any;
156
158
  height: any;
157
159
  frameRate: any;
@@ -1,6 +1,8 @@
1
1
  // Media library: import, probe, and keep browser-side resources for each source. The engine only
2
2
  // learns that a source exists (`browser://<id>`); this module answers its per-frame requests.
3
3
  import { colorMetadataFromVideoColorSpace } from "alpha2/hdr-frames";
4
+ import { MediabunnyVideoDecoder } from "alpha2/mediabunny";
5
+ import { TICKS_PER_SECOND } from "alpha2/project";
4
6
  import { OffscreenTextRasterizer } from "alpha2/text";
5
7
  import { ALL_FORMATS, AudioSampleSink, BlobSource, Input } from "mediabunny";
6
8
  const uid = (prefix) => `${prefix}-${crypto.randomUUID()}`;
@@ -157,12 +159,13 @@ export class AssetLibrary {
157
159
  * Imports one browser file as an image, video or audio asset. Rejects with an `EditorError`:
158
160
  * `unsupported_media` for a file that is none of those, `unreadable_media` for one that is but
159
161
  * that this browser could not read (a codec it does not decode, a damaged file), with the
160
- * decoder's or demuxer's reason in the message and as the `cause`.
162
+ * decoder's or demuxer's reason in the message and as the `cause`. Rejects with `signal`'s
163
+ * reason once it aborts a decode.
161
164
  */
162
- async importFile(file) {
163
- return (await this.#import(file)).asset;
165
+ async importFile(file, { signal } = {}) {
166
+ return (await this.#import(file, signal)).asset;
164
167
  }
165
- async #import(file) {
168
+ async #import(file, signal) {
166
169
  const kind = mediaKindForFile(file);
167
170
  if (!kind)
168
171
  throw new EditorError("unsupported_media", `Cannot import ${file.name}: not an image, video or audio file`, "import");
@@ -176,11 +179,13 @@ export class AssetLibrary {
176
179
  const asset = as === "image"
177
180
  ? await this.#importImage(file, reference)
178
181
  : as === "video"
179
- ? await this.#importVideo(file, reference, probe)
182
+ ? await this.#importVideo(file, reference, probe, signal)
180
183
  : await this.#importAudio(file, reference);
181
184
  return { asset, relinked: !!reference };
182
185
  }
183
186
  catch (error) {
187
+ if (signal?.aborted)
188
+ throw signal.reason;
184
189
  // A media element's MediaError is no Error, but says why in `message` too.
185
190
  const reason = typeof error?.message === "string"
186
191
  ? error.message
@@ -214,8 +219,12 @@ export class AssetLibrary {
214
219
  this.#assets.set(asset.id, asset);
215
220
  return asset;
216
221
  }
217
- /** `probe` is null when the container was unreadable; an element with no picture is refused. */
218
- async #importVideo(file, reference = null, probe = null) {
222
+ /**
223
+ * `probe` is null when the container was unreadable; an element with no picture is refused. A
224
+ * file the media element cannot open still imports, with no element (`video: null`), when the
225
+ * decoder preview and export read it with decodes its picture.
226
+ */
227
+ async #importVideo(file, reference = null, probe = null, signal) {
219
228
  if (probe && !probe.video)
220
229
  throw new Error("the file has neither a picture nor sound");
221
230
  const url = URL.createObjectURL(file);
@@ -228,10 +237,18 @@ export class AssetLibrary {
228
237
  preload: "auto",
229
238
  loop: false,
230
239
  });
231
- await new Promise((resolve, reject) => {
232
- video.onloadeddata = resolve;
233
- video.onerror = () => reject(video.error ?? new Error("video decode failed"));
240
+ const failed = await new Promise((resolve) => {
241
+ video.onloadeddata = () => resolve(null);
242
+ video.onerror = () => resolve(video.error ?? new Error("video decode failed"));
234
243
  });
244
+ // The element is a fallback reader, not the gate: Chrome's media pipeline refuses some files
245
+ // WebCodecs decodes (a stream copy cut inside an open GOP), which preview and export read.
246
+ if (failed) {
247
+ if (!probe?.video?.decodable)
248
+ throw failed;
249
+ video.removeAttribute("src");
250
+ }
251
+ const element = failed ? null : video;
235
252
  if (!probe && !video.videoWidth)
236
253
  throw new Error("the browser found no picture in it");
237
254
  const read = probe?.video ?? {
@@ -241,8 +258,8 @@ export class AssetLibrary {
241
258
  colorMetadata: null,
242
259
  };
243
260
  // A chunked WebM (MediaRecorder timeslice) has no Duration and the element reports +Infinity.
244
- const duration = Number.isFinite(video.duration)
245
- ? video.duration
261
+ const duration = element && Number.isFinite(element.duration)
262
+ ? element.duration
246
263
  : ((await containerDuration(file)) ?? 0);
247
264
  const asset = {
248
265
  id: reference?.id ?? uid("src"),
@@ -251,7 +268,7 @@ export class AssetLibrary {
251
268
  locator: reference?.locator ?? localLocator(file, file.name),
252
269
  file,
253
270
  url,
254
- video,
271
+ video: element,
255
272
  width: read.width,
256
273
  height: read.height,
257
274
  frameRate: read.frameRate,
@@ -264,7 +281,16 @@ export class AssetLibrary {
264
281
  thumbnail: null,
265
282
  peaks: null,
266
283
  };
267
- asset.thumbnail = await videoThumbnail(video, read.width, read.height);
284
+ if (element)
285
+ asset.thumbnail = await videoThumbnail(element, read.width, read.height);
286
+ else {
287
+ try {
288
+ asset.thumbnail = await decodedThumbnail(asset, signal);
289
+ }
290
+ catch (error) {
291
+ throw new Error(`${failed.message || "the media element could not open it"}; decoding it with WebCodecs failed too: ${error?.message ?? error}`, { cause: error });
292
+ }
293
+ }
268
294
  this.#assets.set(asset.id, asset);
269
295
  return asset;
270
296
  }
@@ -421,8 +447,8 @@ function mediaKindForFile(file) {
421
447
  }
422
448
  /**
423
449
  * What a video container holds, read by the demuxer: its picture (`video`: size, frame rate, an HDR
424
- * declaration), or null when it has no video track, and whether it has an audio stream. Null when
425
- * the demuxer cannot read the container.
450
+ * declaration, and whether WebCodecs decodes it), or null when it has no video track, and whether
451
+ * it has an audio stream. Null when the demuxer cannot read the container.
426
452
  */
427
453
  export async function probeVideo(file) {
428
454
  const input = new Input({
@@ -445,6 +471,7 @@ export async function probeVideo(file) {
445
471
  width: shown.width,
446
472
  height: shown.height,
447
473
  frameRate: stats?.averagePacketRate ?? 30,
474
+ decodable: await track.canDecode().catch(() => false),
448
475
  };
449
476
  }
450
477
  return {
@@ -569,13 +596,31 @@ export function computePeaks(buffer, buckets = 1_200) {
569
596
  }
570
597
  return peaks;
571
598
  }
572
- function thumbnailFrom(image, width, height) {
599
+ /**
600
+ * A thumbnail of `image` shown at `width` x `height`. With `orientation`, `image` is a decoded
601
+ * frame that shows upright mirrored left to right when `mirror` is set, then turned `rotation`
602
+ * degrees clockwise.
603
+ */
604
+ function thumbnailFrom(image, width, height, orientation = null) {
573
605
  // Rendered once at import; the timeline re-reads `dataUrl` on every redraw.
574
606
  const scale = THUMBNAIL_WIDTH / Math.max(1, width);
575
607
  const canvas = document.createElement("canvas");
576
608
  canvas.width = THUMBNAIL_WIDTH;
577
609
  canvas.height = Math.max(1, Math.round(height * scale));
578
- canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
610
+ const context = canvas.getContext("2d");
611
+ if (orientation) {
612
+ const turned = orientation.rotation % 180 !== 0;
613
+ const drawn = turned
614
+ ? { width: canvas.height, height: canvas.width }
615
+ : { width: canvas.width, height: canvas.height };
616
+ context.translate(canvas.width / 2, canvas.height / 2);
617
+ context.rotate((orientation.rotation * Math.PI) / 180);
618
+ if (orientation.mirror)
619
+ context.scale(-1, 1);
620
+ context.drawImage(image, -drawn.width / 2, -drawn.height / 2, drawn.width, drawn.height);
621
+ }
622
+ else
623
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
579
624
  canvas.dataUrl = canvas.toDataURL("image/jpeg", 0.72);
580
625
  return canvas;
581
626
  }
@@ -598,6 +643,36 @@ async function videoThumbnail(video, width, height) {
598
643
  clone.removeAttribute("src");
599
644
  }
600
645
  }
646
+ /**
647
+ * A thumbnail of `asset`, a file the media element cannot open, decoded by the decoder preview and
648
+ * export read it with: its stall limit bounds a decoder that never answers. Rejects when it decodes
649
+ * no picture, or with `signal`'s reason once it aborts.
650
+ */
651
+ async function decodedThumbnail(asset, signal) {
652
+ const decoder = await MediabunnyVideoDecoder.open(asset.id, asset.file);
653
+ try {
654
+ // Requests before the stream's first frame present that frame, as preview shows it.
655
+ const seconds = Math.min(0.25 * (asset.duration || 1), 1);
656
+ const { frame, rotationDegrees, mirror } = await decoder.refill({
657
+ sourceId: asset.id,
658
+ mediaTimeTicks: BigInt(Math.round(seconds * TICKS_PER_SECOND)),
659
+ reason: "seek",
660
+ generation: 0,
661
+ }, signal);
662
+ try {
663
+ return thumbnailFrom(frame, asset.width, asset.height, {
664
+ rotation: rotationDegrees ?? 0,
665
+ mirror: mirror ?? false,
666
+ });
667
+ }
668
+ finally {
669
+ frame.close();
670
+ }
671
+ }
672
+ finally {
673
+ decoder.close();
674
+ }
675
+ }
601
676
  function generatedThumbnail(generator) {
602
677
  const canvas = document.createElement("canvas");
603
678
  canvas.width = THUMBNAIL_WIDTH;
@@ -3,10 +3,12 @@
3
3
  * render queue that collapses to the newest request.
4
4
  */
5
5
  export class Engine {
6
- constructor(canvas: any, sources: any, library: any, runtimeAssets?: {}, { unreadableFrames }?: {});
6
+ constructor(canvas: any, sources: any, library: any, runtimeAssets?: {}, { unreadableFrames, videoConversion }?: {});
7
7
  runtimeAssets: {};
8
8
  /** What the frame supply does with a frame the browser cannot read back (`FrameSupply`). */
9
9
  unreadableFrames: any;
10
+ /** Who converts decoded SDR frames, the engine or the browser (`FrameSupply`). */
11
+ videoConversion: any;
10
12
  canvas: any;
11
13
  sources: any;
12
14
  library: any;
@@ -34,10 +34,12 @@ export class Engine {
34
34
  #unchanged = 0;
35
35
  /** What `supply` uploaded for the export frame the engine has not rendered yet. */
36
36
  #exportUploads = [];
37
- constructor(canvas, sources, library, runtimeAssets = {}, { unreadableFrames } = {}) {
37
+ constructor(canvas, sources, library, runtimeAssets = {}, { unreadableFrames, videoConversion } = {}) {
38
38
  this.runtimeAssets = runtimeAssets;
39
39
  /** What the frame supply does with a frame the browser cannot read back (`FrameSupply`). */
40
40
  this.unreadableFrames = unreadableFrames;
41
+ /** Who converts decoded SDR frames, the engine or the browser (`FrameSupply`). */
42
+ this.videoConversion = videoConversion;
41
43
  this.canvas = canvas;
42
44
  this.sources = sources;
43
45
  this.library = library;
@@ -64,6 +66,9 @@ export class Engine {
64
66
  ...(this.unreadableFrames === undefined
65
67
  ? {}
66
68
  : { unreadableFrames: this.unreadableFrames }),
69
+ ...(this.videoConversion === undefined
70
+ ? {}
71
+ : { videoConversion: this.videoConversion }),
67
72
  });
68
73
  // `engine.traceUploads = true` in the console logs every source upload, to tell a host decode
69
74
  // bug from an engine one when a clip shows another clip's picture.
@@ -556,13 +556,15 @@ export class SourcePixels {
556
556
  chromaSiting: decoded.chromaSiting,
557
557
  };
558
558
  }
559
- /** Decoder cursors the budget counts: the software cursors of recovered frames are not. */
559
+ /**
560
+ * Decoder cursors the budget counts, one per consumer: a software cursor beside its consumer's
561
+ * own cursor is not counted again.
562
+ */
560
563
  #cursorCount() {
561
- let count = 0;
564
+ const consumers = new Set();
562
565
  for (const decoder of this.#decoders.values())
563
- if (!decoder.software)
564
- count += 1;
565
- return count;
566
+ consumers.add(decoderCursorKey(decoder.sourceId, decoder.consumerId));
567
+ return consumers.size;
566
568
  }
567
569
  /**
568
570
  * Opens `decoder`'s source as `videoDecode` says. A source the browser has no software decoder
@@ -600,12 +602,14 @@ export class SourcePixels {
600
602
  *
601
603
  * The cursor shares the consumer's source and consumer IDs, so `retainConsumers` and `release`
602
604
  * close it with the consumer's; it stays open between frames, as readback failures come in runs
603
- * and the next one then decodes on from it.
605
+ * and the next one then decodes on from it. A consumer whose frames all decode here (a source
606
+ * the browser decodes to opaque frames) has no other cursor, so this one opens within the budget.
604
607
  */
605
608
  async #softwareFrame(asset, seconds, consumerId, sourceId) {
606
609
  if (!asset.file)
607
610
  throw new Error(`${asset.id} has no file to decode in software`);
608
- const cursor = `${decoderCursorKey(sourceId, consumerId)}\u0000software`;
611
+ const primary = decoderCursorKey(sourceId, consumerId);
612
+ const cursor = `${primary}\u0000software`;
609
613
  let decoder = this.#decoders.get(cursor);
610
614
  if (decoder && decoder.asset !== asset) {
611
615
  await closeDecoder(decoder);
@@ -613,6 +617,11 @@ export class SourcePixels {
613
617
  decoder = undefined;
614
618
  }
615
619
  if (!decoder) {
620
+ if (!this.#decoders.has(primary) &&
621
+ this.#cursorCount() >= this.decoderLimit)
622
+ throw Object.assign(new Error("Video decoder budget reached"), {
623
+ code: "resource_budget",
624
+ });
616
625
  decoder = {
617
626
  sourceId,
618
627
  asset,
@@ -679,7 +688,9 @@ export class SourcePixels {
679
688
  }
680
689
  async #seekFallback(asset, seconds, consumerId, sourceId) {
681
690
  if (!asset.video)
682
- throw Object.assign(new Error(`No worker decoder for ${asset.id}; use the main-thread media fallback`), { code: "unsupported_codec" });
691
+ throw Object.assign(new Error(asset.video === null
692
+ ? `${asset.id} has no media element to seek (the browser's media pipeline could not open it)`
693
+ : `No worker decoder for ${asset.id}; use the main-thread media fallback`), { code: "unsupported_codec" });
683
694
  const cursor = decoderCursorKey(sourceId, consumerId);
684
695
  let fallback = this.#seekVideos.get(cursor);
685
696
  if (fallback && fallback.asset !== asset) {
@@ -112,14 +112,15 @@ export interface StagedAsset {
112
112
  /** Decodes and probes files for import. `createMediaAdapter` makes the default one. */
113
113
  export interface BrowserMediaAdapter {
114
114
  /**
115
- * Stages one file. Rejects with an `EditorError`: `unsupported_media` for a file that is no media
116
- * the adapter imports, `unreadable_media` for media this browser could not read (a codec it does
117
- * not decode, a damaged file, or one an extension provider refuses, such as one whose drawing is
118
- * past its budgets; the decoder's or provider's reason is in the message and is the `cause`),
119
- * `too_large` for a Lottie, dotLottie or SVG file larger than the engine parses
120
- * (`MAX_LOTTIE_DOCUMENT_BYTES`, `MAX_PROVIDER_DOCUMENT_BYTES` for a dotLottie package,
121
- * `MAX_SVG_DOCUMENT_BYTES`), `provider_stalled` for one the extensions worker read past
122
- * `EXTENSIONS_CALL_TIMEOUT_MS`, and when `signal` aborts.
115
+ * Stages one file. The bridge may stage several files of one import at once, at most four.
116
+ * Rejects with an `EditorError`: `unsupported_media` for a file that is no media the adapter
117
+ * imports, `unreadable_media` for media this browser could not read (a codec it does not decode,
118
+ * a damaged file, or one an extension provider refuses, such as one whose drawing is past its
119
+ * budgets; the decoder's or provider's reason is in the message and is the `cause`), `too_large`
120
+ * for a Lottie, dotLottie or SVG file larger than the engine parses (`MAX_LOTTIE_DOCUMENT_BYTES`,
121
+ * `MAX_PROVIDER_DOCUMENT_BYTES` for a dotLottie package, `MAX_SVG_DOCUMENT_BYTES`),
122
+ * `provider_stalled` for one the extensions worker read past `EXTENSIONS_CALL_TIMEOUT_MS`, and
123
+ * when `signal` aborts.
123
124
  */
124
125
  stage(file: File, signal: AbortSignal, options?: {
125
126
  /**
@@ -188,6 +189,19 @@ export interface BrowserBridgeOptions {
188
189
  * `BrowserBridge.setPreviewScale`.
189
190
  */
190
191
  readonly previewScale?: number;
192
+ /**
193
+ * Who converts decoded SDR video frames to the engine's pixels, in the preview and in exports
194
+ * (an export may choose otherwise, see `BrowserExportOptions.videoConversion`). `engine` (the
195
+ * default) copies each frame's planes out and converts them with the engine's shader, as a
196
+ * native export converts the same stream. `browser` hands the frame to the browser instead,
197
+ * which saves that copy (1 to 4 ms a frame per video layer) but leaves the conversion to the
198
+ * browser, which does not read the stream's chroma siting: Chrome places H.264 and HEVC chroma
199
+ * half a sample off (27 codes on a chroma stripe), so sharp chroma edges differ from a native
200
+ * export's. HDR frames, and frames of a source whose color the project declares, are the
201
+ * engine's either way. Another value is refused when the bridge is made, with an `EditorError`
202
+ * `invalid_video_conversion`.
203
+ */
204
+ readonly videoConversion?: "engine" | "browser";
191
205
  }
192
206
  /** Options of `BrowserBridge.startExport`. */
193
207
  export interface BrowserExportOptions {
@@ -270,6 +284,13 @@ export interface BrowserExportOptions {
270
284
  * `invalid_video_decode`.
271
285
  */
272
286
  readonly videoDecode?: "auto" | "software";
287
+ /**
288
+ * Who converts decoded SDR video frames for this export, `engine` or `browser`; default the
289
+ * bridge's (see `BrowserBridgeOptions.videoConversion`). The result's `report.videoConversion`
290
+ * says which ran. Another value is refused when the export starts, with an `EditorError`
291
+ * `invalid_video_conversion`.
292
+ */
293
+ readonly videoConversion?: "engine" | "browser";
273
294
  }
274
295
  /** Where a browser export writes its file. */
275
296
  export type ExportOutputTarget = {
@@ -644,7 +665,8 @@ export interface BrowserBridge {
644
665
  *
645
666
  * Throws synchronously when the bridge is disposed (`disposed`), another export runs
646
667
  * (`export_busy`), `frameRate` is not one the engine reads (`invalid_frame_rate`), `videoDecode`
647
- * is not `auto` or `software` (`invalid_video_decode`), the asset
668
+ * is not `auto` or `software` (`invalid_video_decode`), `videoConversion` is not `engine` or
669
+ * `browser` (`invalid_video_conversion`), the asset
648
670
  * decisions are not loaded (`conform_pending`), the media is not ready (`ConformError`), or the
649
671
  * document does not compile. Everything later is reported through the job's `result`.
650
672
  */
@@ -667,6 +689,11 @@ export interface WorkerPreviewOptions {
667
689
  readonly runtimeAssets?: RuntimeAssets;
668
690
  /** A canvas to render into, transferred to the worker. */
669
691
  readonly canvas?: OffscreenCanvas;
692
+ /**
693
+ * Who converts decoded SDR video frames, `engine` (the default) or `browser`; see
694
+ * `BrowserBridgeOptions.videoConversion`.
695
+ */
696
+ readonly videoConversion?: "engine" | "browser";
670
697
  }
671
698
  /** The main-thread side of a preview renderer running in a worker. */
672
699
  export interface WorkerPreview {
@@ -21,4 +21,4 @@ export function installEditorWorker(scope: import("./types.js").EditorWorkerScop
21
21
  * @param {import("./types.js").WorkerPreviewOptions} [options]
22
22
  * @returns {import("./types.js").WorkerPreview}
23
23
  */
24
- export function createWorkerPreview(worker: Worker, { sessionId, runtimeAssets, canvas, bitmapOutput, width, height, }?: import("./types.js").WorkerPreviewOptions): import("./types.js").WorkerPreview;
24
+ export function createWorkerPreview(worker: Worker, { sessionId, runtimeAssets, canvas, bitmapOutput, width, height, videoConversion, }?: import("./types.js").WorkerPreviewOptions): import("./types.js").WorkerPreview;
@@ -61,7 +61,10 @@ export function installEditorWorker(scope) {
61
61
  });
62
62
  const { Engine } = await import("./runtime/engine.js");
63
63
  engine = new Engine(request.canvas ??
64
- new OffscreenCanvas(request.width ?? 16, request.height ?? 16), pixels, library, request.runtimeAssets, { unreadableFrames: "present" });
64
+ new OffscreenCanvas(request.width ?? 16, request.height ?? 16), pixels, library, request.runtimeAssets, {
65
+ unreadableFrames: "present",
66
+ videoConversion: request.videoConversion,
67
+ });
65
68
  audio = new AudioWindowSupplier(library);
66
69
  engine.backend = "worker";
67
70
  await engine.start();
@@ -192,7 +195,7 @@ export function installEditorWorker(scope) {
192
195
  * @param {import("./types.js").WorkerPreviewOptions} [options]
193
196
  * @returns {import("./types.js").WorkerPreview}
194
197
  */
195
- export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), runtimeAssets = {}, canvas, bitmapOutput = false, width = 16, height = 16, } = {}) {
198
+ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), runtimeAssets = {}, canvas, bitmapOutput = false, width = 16, height = 16, videoConversion, } = {}) {
196
199
  let nextId = 0, revision = 0, disposed = false;
197
200
  const pending = new Map();
198
201
  const rejectAll = (error) => {
@@ -237,6 +240,7 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
237
240
  bitmapOutput,
238
241
  width,
239
242
  height,
243
+ ...(videoConversion === undefined ? {} : { videoConversion }),
240
244
  ...(canvas ? { canvas } : {}),
241
245
  }, canvas ? [canvas] : []);
242
246
  return {
@@ -35,6 +35,7 @@ const EDITOR_FAILURE_CODES = Object.freeze({
35
35
  invalid_rate: "INVALID_INPUT",
36
36
  invalid_time: "INVALID_INPUT",
37
37
  invalid_transition: "INVALID_INPUT",
38
+ invalid_video_conversion: "INVALID_INPUT",
38
39
  invalid_video_decode: "INVALID_INPUT",
39
40
  locked: "INVALID_INPUT",
40
41
  missing_asset: "INVALID_INPUT",
@@ -96,7 +96,8 @@ export type ExportArtifact = ({
96
96
  readonly bytes?: number;
97
97
  /**
98
98
  * What the exporter reported about the run: timings, `performance` (with `memory` and `output`),
99
- * rates. A browser export adds `videoDecode`, the decode mode it ran with, and `decodeFallbacks`:
99
+ * rates. A browser export adds `videoDecode`, the decode mode it ran with, `videoConversion`, who
100
+ * converted decoded SDR frames (`engine` or `browser`), and `decodeFallbacks`:
100
101
  * per source, frames read by element seeks rather than decoded (`kind: "element-seek"`), with
101
102
  * why, how many frames, and whether for good, and sources `videoDecode: "software"` could not
102
103
  * decode in software (`kind: "software-unavailable"`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alpha2-sh/editor",
3
- "version": "0.4.5",
3
+ "version": "0.4.6",
4
4
  "description": "Headless Project-based editing sessions and browser adapters for alpha2.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -60,11 +60,11 @@
60
60
  "build": "rm -rf dist && tsc -p tsconfig.json"
61
61
  },
62
62
  "peerDependencies": {
63
- "alpha2": "0.4.5",
63
+ "alpha2": "0.4.6",
64
64
  "react": "^19.3.0"
65
65
  },
66
66
  "devDependencies": {
67
- "alpha2": "0.4.5",
67
+ "alpha2": "0.4.6",
68
68
  "react": "19.3.0",
69
69
  "react-dom": "19.3.0",
70
70
  "@types/react": "19.3.0",