@alpha2-sh/editor 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -302,3 +302,43 @@ function phaseOf(progress) {
302
302
  return "prepare";
303
303
  }
304
304
  }
305
+ /**
306
+ * One extraction running on the page. It stops when `signal` aborts, on {@link cancel}, or when
307
+ * the bridge is disposed; a stopped run rejects with `EditorError` `cancelled`.
308
+ */
309
+ export class ExtractionJob {
310
+ /** What `run` resolves to. */
311
+ result;
312
+ #controller = new AbortController();
313
+ /**
314
+ * Starts `run` with the job's own signal.
315
+ *
316
+ * @param release Called once when the job settles.
317
+ */
318
+ constructor(run, signal, release) {
319
+ const own = this.#controller.signal;
320
+ const abort = () => this.#controller.abort(signal?.reason);
321
+ if (signal?.aborted)
322
+ abort();
323
+ else
324
+ signal?.addEventListener("abort", abort, { once: true });
325
+ this.result = Promise.resolve()
326
+ .then(() => run(own))
327
+ .catch((cause) => {
328
+ if (!own.aborted)
329
+ throw cause;
330
+ throw new EditorError("cancelled", "Extraction cancelled", "extract", undefined, true, { cause });
331
+ })
332
+ .finally(() => {
333
+ signal?.removeEventListener("abort", abort);
334
+ release();
335
+ });
336
+ // A run cancelled before anyone awaits it is not an unhandled rejection.
337
+ void this.result.catch(() => { });
338
+ }
339
+ /** Stops the run; resolves once it has settled. */
340
+ cancel() {
341
+ this.#controller.abort();
342
+ return this.result.then(() => { }, () => { });
343
+ }
344
+ }
@@ -13,20 +13,25 @@ export interface Lease<T> {
13
13
  export declare class ResourceRegistry<T> {
14
14
  #private;
15
15
  readonly limit: number;
16
- /** @param limit Most entries held at once (default 128). */
16
+ /** @param limit Most counted entries held at once (default 128). */
17
17
  constructor(limit?: number);
18
18
  /**
19
19
  * Stores `value` under `id` at `revision` and returns its first lease. `dispose` runs once,
20
- * when the last lease is released or the registry is disposed.
20
+ * when the last lease is released or the registry is disposed. An entry put with
21
+ * `counted: false` is held whatever the limit and does not use its room.
21
22
  *
22
23
  * Throws `EditorError` `disposed` after {@link dispose}, `duplicate_resource` if that revision
23
- * is already stored, and `resource_budget` when `limit` entries are held.
24
+ * is already stored, and `resource_budget` when a counted entry finds `limit` counted entries.
24
25
  */
25
- put(id: string, revision: number, value: T, dispose: () => void): Lease<T>;
26
+ put(id: string, revision: number, value: T, dispose: () => void, { counted }?: {
27
+ counted?: boolean;
28
+ }): Lease<T>;
26
29
  /** Takes another lease on a stored entry. Throws `EditorError` `missing_asset` if absent. */
27
30
  acquire(id: string, revision: number): Lease<T>;
28
31
  /** Entries currently held. */
29
32
  get size(): number;
33
+ /** Entries currently held that count against `limit`. */
34
+ get counted(): number;
30
35
  /**
31
36
  * Disposes every entry regardless of outstanding leases and refuses later `put` calls.
32
37
  * Idempotent.
@@ -6,30 +6,35 @@ import { EditorError } from "../core/document.js";
6
6
  export class ResourceRegistry {
7
7
  limit;
8
8
  #entries = new Map();
9
+ #counted = 0;
9
10
  #closed = false;
10
- /** @param limit Most entries held at once (default 128). */
11
+ /** @param limit Most counted entries held at once (default 128). */
11
12
  constructor(limit = 128) {
12
13
  this.limit = limit;
13
14
  }
14
15
  /**
15
16
  * Stores `value` under `id` at `revision` and returns its first lease. `dispose` runs once,
16
- * when the last lease is released or the registry is disposed.
17
+ * when the last lease is released or the registry is disposed. An entry put with
18
+ * `counted: false` is held whatever the limit and does not use its room.
17
19
  *
18
20
  * Throws `EditorError` `disposed` after {@link dispose}, `duplicate_resource` if that revision
19
- * is already stored, and `resource_budget` when `limit` entries are held.
21
+ * is already stored, and `resource_budget` when a counted entry finds `limit` counted entries.
20
22
  */
21
- put(id, revision, value, dispose) {
23
+ put(id, revision, value, dispose, { counted = true } = {}) {
22
24
  if (this.#closed)
23
25
  throw new EditorError("disposed", "Resources are closed", "resource");
24
26
  const key = JSON.stringify([id, revision]);
25
27
  if (this.#entries.has(key))
26
28
  throw new EditorError("duplicate_resource", "Resource revision already exists", "resource", id);
27
- if (this.#entries.size >= this.limit)
29
+ if (counted && this.#counted >= this.limit)
28
30
  throw new EditorError("resource_budget", "Resource budget reached", "resource", id);
29
31
  let closed = false;
32
+ if (counted)
33
+ this.#counted++;
30
34
  this.#entries.set(key, {
31
35
  value,
32
36
  refs: 0,
37
+ counted,
33
38
  dispose: () => {
34
39
  if (!closed) {
35
40
  closed = true;
@@ -55,6 +60,8 @@ export class ResourceRegistry {
55
60
  released = true;
56
61
  if (--entry.refs === 0) {
57
62
  this.#entries.delete(key);
63
+ if (entry.counted)
64
+ this.#counted--;
58
65
  entry.dispose();
59
66
  }
60
67
  },
@@ -64,6 +71,10 @@ export class ResourceRegistry {
64
71
  get size() {
65
72
  return this.#entries.size;
66
73
  }
74
+ /** Entries currently held that count against `limit`. */
75
+ get counted() {
76
+ return this.#counted;
77
+ }
67
78
  /**
68
79
  * Disposes every entry regardless of outstanding leases and refuses later `put` calls.
69
80
  * Idempotent.
@@ -75,5 +86,6 @@ export class ResourceRegistry {
75
86
  for (const entry of this.#entries.values())
76
87
  entry.dispose();
77
88
  this.#entries.clear();
89
+ this.#counted = 0;
78
90
  }
79
91
  }
@@ -23,6 +23,17 @@ export function probeVideo(file: any): Promise<{
23
23
  * `facts` describe the video track when the probe read one.
24
24
  */
25
25
  export function importFailureReason(error: any, kind: any, facts: any): string;
26
+ /**
27
+ * Whether this browser decodes a file's primary audio, using the preview decoder's trial decode
28
+ * (`probeAudioSource`), and the refusal facts when not.
29
+ */
30
+ export function audioDecoding(file: any): Promise<{
31
+ decodable: boolean;
32
+ facts: null;
33
+ } | {
34
+ decodable: boolean;
35
+ facts: import("alpha2/hdr-frames").TrackDecodeFacts;
36
+ }>;
26
37
  /**
27
38
  * Streams a file's primary audio track into per-bucket peak magnitudes (`bucketsPerSecond`, capped
28
39
  * at `maxBuckets`) with bounded memory. A bucket's peak is its loudest sample in any channel,
@@ -153,8 +164,9 @@ export class AssetLibrary {
153
164
  }>;
154
165
  /**
155
166
  * Imports one browser file as an image, video or audio asset. Rejects with an `EditorError`:
156
- * `unsupported_media` for a file that is none of those, `unreadable_media` when this browser
157
- * cannot read it (with the decoder's or demuxer's reason as message and `cause`), or with
167
+ * `unsupported_media` for a file that is none of those or a video this browser decodes none of
168
+ * (its `cause` a `DecodeUnavailableError` with the track's `facts`), `unreadable_media` when this
169
+ * browser cannot read it (with the decoder's or demuxer's reason as message and `cause`), or with
158
170
  * `signal`'s reason once it aborts a decode.
159
171
  */
160
172
  importFile(file: any, { signal }?: {}): Promise<{
@@ -7,7 +7,7 @@ import { OffscreenTextRasterizer } from "alpha2/text";
7
7
  import { ALL_FORMATS, AudioSampleSink, BlobSource, Input } from "mediabunny";
8
8
  const uid = (prefix) => `${prefix}-${crypto.randomUUID()}`;
9
9
  import { drawGenerator, generatorLabel } from "./generators.js";
10
- import { seekVideoFrame } from "./preview-utils.js";
10
+ import { loadedOrFailed, seekVideoFrame, unloadVideo, } from "./preview-utils.js";
11
11
  import { decodeStill } from "./still.js";
12
12
  import { readUserText } from "./text.js";
13
13
  import { EditorError } from "../../core/document.js";
@@ -171,8 +171,9 @@ export class AssetLibrary {
171
171
  }
172
172
  /**
173
173
  * Imports one browser file as an image, video or audio asset. Rejects with an `EditorError`:
174
- * `unsupported_media` for a file that is none of those, `unreadable_media` when this browser
175
- * cannot read it (with the decoder's or demuxer's reason as message and `cause`), or with
174
+ * `unsupported_media` for a file that is none of those or a video this browser decodes none of
175
+ * (its `cause` a `DecodeUnavailableError` with the track's `facts`), `unreadable_media` when this
176
+ * browser cannot read it (with the decoder's or demuxer's reason as message and `cause`), or with
176
177
  * `signal`'s reason once it aborts a decode.
177
178
  */
178
179
  async importFile(file, { signal } = {}) {
@@ -202,7 +203,11 @@ export class AssetLibrary {
202
203
  throw signal.reason;
203
204
  if (error instanceof EditorError)
204
205
  throw error;
205
- throw new EditorError("unreadable_media", `Cannot read ${file.name} as ${as}: ${importFailureReason(error, as, probe?.video?.facts)}`, "import", undefined, true, { cause: error });
206
+ const facts = probe?.video?.facts;
207
+ const refused = as === "video" && facts && !probe.video.decodable && undecodable(error)
208
+ ? new DecodeUnavailableError(decodeRefusalMessage(file.name, facts), facts, { cause: error })
209
+ : null;
210
+ throw new EditorError(refused ? "unsupported_media" : "unreadable_media", `Cannot read ${file.name} as ${as}: ${importFailureReason(error, as, facts)}`, "import", undefined, true, { cause: refused ?? error });
206
211
  }
207
212
  }
208
213
  /** A still keeps its file, size and thumbnail; `SourcePixels` decodes it again per frame. */
@@ -277,17 +282,20 @@ export class AssetLibrary {
277
282
  preload: "auto",
278
283
  loop: false,
279
284
  });
280
- const failed = await new Promise((resolve) => {
281
- video.onloadeddata = () => resolve(null);
282
- video.onerror = () => resolve(video.error ?? new Error("video decode failed"));
283
- });
284
- // The element is a fallback reader, not the gate: Chrome's media pipeline refuses some files
285
- // WebCodecs decodes (a stream copy cut inside an open GOP).
286
- if (failed) {
287
- if (!probe?.video?.decodable)
288
- throw failed;
289
- video.removeAttribute("src");
285
+ let failed = null;
286
+ try {
287
+ await loadedOrFailed(video, { signal });
288
+ }
289
+ catch (error) {
290
+ unloadVideo(video);
291
+ if (signal?.aborted)
292
+ throw signal.reason;
293
+ failed = error;
290
294
  }
295
+ // The element is a fallback reader, not the gate: Chrome's media pipeline refuses some files
296
+ // WebCodecs decodes (a stream copy cut inside an open GOP), and some never finish loading.
297
+ if (failed && !probe?.video?.decodable)
298
+ throw failed;
291
299
  const element = failed ? null : video;
292
300
  if (!probe && !video.videoWidth)
293
301
  throw new Error("the browser found no picture in it");
@@ -545,20 +553,26 @@ export async function probeVideo(file) {
545
553
  /** `MediaError` codes: the source is in a format the element does not read, or did not decode. */
546
554
  const MEDIA_ERR_DECODE = 3;
547
555
  const MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
556
+ function mediaOrBrowserError(error) {
557
+ return ((typeof DOMException !== "undefined" && error instanceof DOMException) ||
558
+ (!(error instanceof Error) && typeof error?.code === "number"));
559
+ }
560
+ function undecodable(error) {
561
+ if (!mediaOrBrowserError(error))
562
+ return false;
563
+ return ((typeof DOMException !== "undefined" && error instanceof DOMException) ||
564
+ error?.code === MEDIA_ERR_DECODE ||
565
+ error?.code === MEDIA_ERR_SRC_NOT_SUPPORTED);
566
+ }
548
567
  /**
549
568
  * Why an import failed, in this editor's words. Browser error text (`MediaError`, decoder
550
569
  * `DOMException`) exposes engine internals, so it is never shown and stays the error's cause.
551
570
  * `facts` describe the video track when the probe read one.
552
571
  */
553
572
  export function importFailureReason(error, kind, facts) {
554
- const browserError = typeof DOMException !== "undefined" && error instanceof DOMException;
555
- const mediaError = !(error instanceof Error) && typeof error?.code === "number";
556
- if (!mediaError && !browserError && error instanceof Error)
573
+ if (!mediaOrBrowserError(error) && error instanceof Error)
557
574
  return error.message;
558
- const undecodable = browserError ||
559
- error?.code === MEDIA_ERR_DECODE ||
560
- error?.code === MEDIA_ERR_SRC_NOT_SUPPORTED;
561
- if (!undecodable)
575
+ if (!undecodable(error))
562
576
  return `this browser could not read the ${kind}`;
563
577
  if (kind !== "video" || !facts)
564
578
  return `this browser cannot decode this ${kind}`;
@@ -586,7 +600,7 @@ async function containerDuration(file) {
586
600
  * Whether this browser decodes a file's primary audio, using the preview decoder's trial decode
587
601
  * (`probeAudioSource`), and the refusal facts when not.
588
602
  */
589
- async function audioDecoding(file) {
603
+ export async function audioDecoding(file) {
590
604
  try {
591
605
  await probeAudioSource(file.name, file);
592
606
  return { decodable: true, facts: null };
@@ -719,11 +733,7 @@ async function videoThumbnail(video, width, height) {
719
733
  const clone = video.cloneNode(true);
720
734
  clone.muted = true;
721
735
  try {
722
- await new Promise((resolve, reject) => {
723
- clone.onloadeddata = resolve;
724
- clone.onerror = () => reject(clone.error);
725
- clone.load();
726
- });
736
+ await loadedOrFailed(clone);
727
737
  await seekVideoFrame(clone, Math.min(0.25 * (clone.duration || 1), 1));
728
738
  return thumbnailFrom(clone, width, height);
729
739
  }
@@ -18,12 +18,22 @@ export function playbackStartSample(tick: any, sampleRate: any): number;
18
18
  /**
19
19
  * Supplies bounded source windows requested by the engine. Page-synthesized audio keeps its
20
20
  * AudioBuffer, but only the requested slice enters wasm.
21
+ *
22
+ * With `onError` (preview), a stream this browser cannot decode or the file does not have plays
23
+ * silent for the rest of the session and is reported to it once; without it (export) its supply
24
+ * rejects.
21
25
  */
22
26
  export class AudioWindowSupplier {
23
- constructor(library: any);
27
+ constructor(library: any, { onError }?: {});
24
28
  configure(engine: any, project: any): void;
25
- supply(startSample: any, frames: any, { signal, forceSources }?: {
29
+ /**
30
+ * Uploads what the engine needs for `frames` samples from `startSample`. `forceSources` are
31
+ * uploaded again even where the engine holds a window; `silentSources` are uploaded as silence
32
+ * that covers any channel selection.
33
+ */
34
+ supply(startSample: any, frames: any, { signal, forceSources, silentSources }?: {
26
35
  forceSources?: never[] | undefined;
36
+ silentSources?: Set<any> | undefined;
27
37
  }): Promise<void>;
28
38
  close(): Promise<void>;
29
39
  #private;
@@ -6,8 +6,11 @@
6
6
  import { AudioPlaybackClock, AudioPump, AudioRingBuffer, canShareAudioMemory, } from "alpha2/audio-timeline";
7
7
  import { Alpha2AudioWorkletHost, configureEngineMixedAudio, disposeAudioWorklet, loadAlpha2AudioWorkletWasm, resetAudioWorklet, useAudioRing, } from "alpha2/audio-worklet";
8
8
  import { MediabunnyAudioDecoder } from "alpha2/mediabunny";
9
+ import { EditorError } from "../../core/document.js";
9
10
  import * as engineBinding from "alpha2/wasm";
10
11
  const TICKS_PER_SECOND = 120000n;
12
+ /** Most planes an audio upload carries (the engine's limit). */
13
+ const MAX_PLANES = 24;
11
14
  const PREFETCH_TICKS = 2n * TICKS_PER_SECOND;
12
15
  /** How much of a source is kept behind the earliest tick a mix reads (backward prefetch). */
13
16
  const KEEP_BEHIND_TICKS = PREFETCH_TICKS;
@@ -54,9 +57,16 @@ export function audibleSources(project, library) {
54
57
  /**
55
58
  * Supplies bounded source windows requested by the engine. Page-synthesized audio keeps its
56
59
  * AudioBuffer, but only the requested slice enters wasm.
60
+ *
61
+ * With `onError` (preview), a stream this browser cannot decode or the file does not have plays
62
+ * silent for the rest of the session and is reported to it once; without it (export) its supply
63
+ * rejects.
57
64
  */
58
65
  export class AudioWindowSupplier {
59
66
  #library;
67
+ #onError;
68
+ /** Silent streams by `laneKey`, each with the file found unplayable and the planes uploaded. */
69
+ #silentLanes = new Map();
60
70
  #engine = null;
61
71
  #sampleRate = 48_000;
62
72
  #generation = 0;
@@ -69,8 +79,9 @@ export class AudioWindowSupplier {
69
79
  #trimmed = new Map();
70
80
  /** The earliest tick each running `supply` needs, per source. */
71
81
  #inFlight = new Set();
72
- constructor(library) {
82
+ constructor(library, { onError } = {}) {
73
83
  this.#library = library;
84
+ this.#onError = onError ?? null;
74
85
  }
75
86
  configure(engine, project) {
76
87
  this.#controller.abort(new DOMException("Project reloaded", "AbortError"));
@@ -89,7 +100,12 @@ export class AudioWindowSupplier {
89
100
  this.#decoders.delete(lane);
90
101
  }
91
102
  }
92
- async supply(startSample, frames, { signal, forceSources = [] } = {}) {
103
+ /**
104
+ * Uploads what the engine needs for `frames` samples from `startSample`. `forceSources` are
105
+ * uploaded again even where the engine holds a window; `silentSources` are uploaded as silence
106
+ * that covers any channel selection.
107
+ */
108
+ async supply(startSample, frames, { signal, forceSources = [], silentSources = new Set() } = {}) {
93
109
  const engine = this.#engine;
94
110
  if (!engine)
95
111
  throw new Error("audio supplier has no loaded project");
@@ -149,6 +165,7 @@ export class AudioWindowSupplier {
149
165
  : { start, end: end + prefetch };
150
166
  await this.#supplyRange(sourceId, stream, start, end, window, {
151
167
  forced: forced.has(sourceId),
168
+ silent: silentSources.has(sourceId),
152
169
  generation,
153
170
  signal: combined.signal,
154
171
  });
@@ -185,11 +202,16 @@ export class AudioWindowSupplier {
185
202
  this.#engine.trimAudioBefore(sourceId, before);
186
203
  this.#trimmed.set(sourceId, before);
187
204
  }
188
- async #supplyRange(sourceId, stream, startTicks, endTicks, decodeWindow, { forced, generation, signal }) {
205
+ async #supplyRange(sourceId, stream, startTicks, endTicks, decodeWindow, { forced, silent, generation, signal }) {
189
206
  const engine = this.#engine;
190
207
  const requiredStart = Math.max(0, ticksToSampleFloor(startTicks, this.#sampleRate) - 2);
191
208
  const requiredEnd = ticksToSampleCeil(endTicks, this.#sampleRate) + 2;
192
209
  // The engine extends, replaces and drops windows itself, so ask what it holds.
210
+ const uploadSilence = (planes) => engine.uploadAudioBlock(sourceId, BigInt(requiredStart), this.#sampleRate, planes, new Float32Array(planes * Math.max(1, requiredEnd - requiredStart)), false, stream);
211
+ if (silent) {
212
+ uploadSilence(MAX_PLANES);
213
+ return;
214
+ }
193
215
  if (!forced &&
194
216
  JSON.parse(engine.audioRetainedWindows(sourceId, stream)).some((window) => window.startSample <= requiredStart &&
195
217
  window.endSample >= requiredEnd))
@@ -197,22 +219,60 @@ export class AudioWindowSupplier {
197
219
  const asset = this.#library.get(sourceId);
198
220
  if (!asset)
199
221
  throw new Error(`audio source ${sourceId} is unavailable`);
200
- // A page-made `AudioBuffer` is a single stream.
201
- const missingStream = asset.audioBuffer && (stream ?? 0) > 0;
202
- if ((asset.audioDecodable === false && !asset.audioBuffer) ||
203
- missingStream) {
222
+ // A page-made `AudioBuffer` is a single stream; another stream of it is covering silence.
223
+ if (asset.audioBuffer && (stream ?? 0) > 0) {
224
+ uploadSilence(MAX_PLANES);
225
+ return;
226
+ }
227
+ if (asset.audioDecodable === false && !asset.audioBuffer) {
204
228
  // Undecodable here (`RuntimeAsset.audioDecodable`): silent, though the document keeps it.
205
- engine.uploadAudioBlock(sourceId, BigInt(requiredStart), this.#sampleRate, 1, new Float32Array(Math.max(1, requiredEnd - requiredStart)), false, stream);
229
+ // As many planes as the stream has, so a clip's channel selection still finds its planes.
230
+ uploadSilence(streamPlanes(asset, stream));
231
+ return;
232
+ }
233
+ const lane = laneKey(sourceId, stream);
234
+ const silenced = this.#silentLanes.get(lane);
235
+ if (silenced && silenced.file === asset.file) {
236
+ uploadSilence(silenced.planes);
237
+ return;
238
+ }
239
+ let block;
240
+ try {
241
+ block = asset.audioBuffer
242
+ ? blockFromAudioBuffer(sourceId, asset.audioBuffer, decodeWindow.start, decodeWindow.end, this.#sampleRate, generation)
243
+ : await this.#decode(sourceId, stream, asset, decodeWindow.start, decodeWindow.end, generation, signal);
244
+ }
245
+ catch (error) {
246
+ const planes = this.#silence(lane, sourceId, stream, asset, error);
247
+ if (planes === null)
248
+ throw error;
249
+ uploadSilence(planes);
206
250
  return;
207
251
  }
208
- const block = asset.audioBuffer
209
- ? blockFromAudioBuffer(sourceId, asset.audioBuffer, decodeWindow.start, decodeWindow.end, this.#sampleRate, generation)
210
- : await this.#decode(sourceId, stream, asset, decodeWindow.start, decodeWindow.end, generation, signal);
211
252
  throwIfAborted(signal);
212
253
  if (generation !== this.#generation)
213
254
  return;
214
255
  engine.uploadAudioBlock(sourceId, block.startSample, block.sampleRate, block.speakers ?? block.channels.length, flattenPlanes(block.channels), false, stream);
215
256
  }
257
+ /**
258
+ * Marks `lane` silent when `error` says this browser cannot decode its stream or the file lacks
259
+ * it, reporting it once; returns the planes its silence takes, or null to let `error` through.
260
+ */
261
+ #silence(lane, sourceId, stream, asset, error) {
262
+ const code = error?.code;
263
+ if (!this.#onError ||
264
+ !asset.file ||
265
+ (code !== "DECODE_UNAVAILABLE" && code !== "AUDIO_STREAM_MISSING"))
266
+ return null;
267
+ // A stream the file lacks covers any channel selection; playing another stream would guess.
268
+ const planes = code === "AUDIO_STREAM_MISSING"
269
+ ? MAX_PLANES
270
+ : streamPlanes(asset, stream);
271
+ this.#silentLanes.set(lane, { file: asset.file, planes });
272
+ const which = stream === undefined ? "" : ` (audio stream ${stream})`;
273
+ this.#onError(new EditorError("audio_unavailable", `The sound of ${sourceId}${which} cannot be played here (${error.message}); it plays silent`, "play", sourceId, true, { cause: error }));
274
+ return planes;
275
+ }
216
276
  async close() {
217
277
  this.#controller.abort();
218
278
  this.#generation += 1;
@@ -235,6 +295,12 @@ export class AudioWindowSupplier {
235
295
  // The engine's own resampler, as on native; alpha2/wasm is loaded by now.
236
296
  promise: MediabunnyAudioDecoder.open(sourceId, asset.file, engineBinding, stream === undefined ? {} : { stream }),
237
297
  };
298
+ // A failed open is not kept, so the next supply opens again (or plays silent).
299
+ const opened = entry;
300
+ opened.promise.catch(() => {
301
+ if (this.#decoders.get(lane) === opened)
302
+ this.#decoders.delete(lane);
303
+ });
238
304
  this.#decoders.set(lane, entry);
239
305
  }
240
306
  const decoder = await entry.promise;
@@ -267,6 +333,8 @@ export function missingAudioSources(engine) {
267
333
  }
268
334
  const RING_SECONDS = 0.5;
269
335
  const PUMP_INTERVAL_MS = 40;
336
+ /** Mixes in a row that may wait for the same missing sources before they play silent. */
337
+ const MAX_WAITING_MIXES = 3;
270
338
  /**
271
339
  * Preview transport for engine-mixed audio. A timer keeps the shared ring ahead of the audio
272
340
  * thread; the worklet applies no second master chain.
@@ -440,6 +508,8 @@ export class EngineAudioMixer {
440
508
  // A stop or close during the first block's decode ends this start quietly.
441
509
  if (signal.aborted)
442
510
  return;
511
+ // Nothing may play from a ring this start filled in part.
512
+ this.stop();
443
513
  throw error;
444
514
  }
445
515
  finally {
@@ -488,24 +558,50 @@ export class EngineAudioMixer {
488
558
  #source(signal) {
489
559
  const engine = this.#engine;
490
560
  const supplier = this.#supplier;
561
+ const onError = this.#onError;
491
562
  const volume = () => this.volume;
563
+ // Sources still missing after a forced supply, mixes in a row they held up, and the sources
564
+ // that play silent for the rest of this start.
565
+ let waitingFor = "", waits = 0;
566
+ const silent = new Set();
492
567
  return {
493
568
  sampleRate: this.#sampleRate,
494
569
  channels: 2,
495
570
  mix: async (startSample, frames) => {
496
- await supplier.supply(startSample, frames, { signal });
571
+ await supplier.supply(startSample, frames, {
572
+ signal,
573
+ silentSources: silent,
574
+ });
497
575
  let planes = mixBlock(engine, startSample, frames, true);
498
576
  let missing = missingAudioSources(engine);
499
577
  if (missing.length > 0) {
500
578
  await supplier.supply(startSample, frames, {
501
579
  signal,
502
580
  forceSources: missing,
581
+ silentSources: silent,
503
582
  });
504
583
  planes = mixBlock(engine, startSample, frames, true);
505
584
  missing = missingAudioSources(engine);
506
585
  }
507
- if (missing.length > 0)
586
+ const key = JSON.stringify([...missing].sort());
587
+ waits = missing.length > 0 && key === waitingFor ? waits + 1 : 1;
588
+ waitingFor = missing.length > 0 ? key : "";
589
+ if (missing.length > 0 && waits <= MAX_WAITING_MIXES)
508
590
  return { kind: "waiting", missingSources: missing };
591
+ if (missing.length > 0) {
592
+ // A source that never arrives would hold the other lanes back forever.
593
+ for (const id of missing)
594
+ silent.add(id);
595
+ onError?.(new EditorError("audio_unavailable", `No sound arrives from ${missing.join(", ")}; ${missing.length === 1 ? "it plays" : "they play"} silent until playback starts again`, "play", missing[0]));
596
+ await supplier.supply(startSample, frames, {
597
+ signal,
598
+ forceSources: missing,
599
+ silentSources: silent,
600
+ });
601
+ planes = mixBlock(engine, startSample, frames, true);
602
+ waitingFor = "";
603
+ waits = 0;
604
+ }
509
605
  // Preview volume is a monitor control, not part of the project.
510
606
  const level = volume();
511
607
  if (level !== 1) {
@@ -524,7 +620,7 @@ function blockFromAudioBuffer(sourceId, buffer, startTicks, endTicks, sampleRate
524
620
  throw new Error(`generated audio ${sourceId} uses ${buffer.sampleRate} Hz, expected ${sampleRate} Hz`);
525
621
  const first = Math.max(0, ticksToSampleFloor(startTicks, sampleRate) - 2);
526
622
  const last = Math.max(first + 1, ticksToSampleCeil(endTicks, sampleRate) + 2);
527
- const channels = Array.from({ length: Math.min(2, buffer.numberOfChannels) }, (_, channel) => {
623
+ const channels = Array.from({ length: Math.min(MAX_PLANES, buffer.numberOfChannels) }, (_, channel) => {
528
624
  const output = new Float32Array(last - first);
529
625
  const sourceStart = Math.min(buffer.length, first);
530
626
  const sourceEnd = Math.min(buffer.length, last);
@@ -541,6 +637,20 @@ function blockFromAudioBuffer(sourceId, buffer, startTicks, endTicks, sampleRate
541
637
  channels,
542
638
  };
543
639
  }
640
+ /**
641
+ * Planes stream `stream` of `asset` decodes to (the default stream when undefined), from its
642
+ * recorded facts; 1 when they are unknown.
643
+ */
644
+ function streamPlanes(asset, stream) {
645
+ const streams = asset.audioStreams ?? [];
646
+ const facts = stream === undefined
647
+ ? (streams.find((each) => each.default) ?? streams[0])
648
+ : streams[stream];
649
+ const channels = facts?.channels;
650
+ return Number.isInteger(channels) && channels > 0
651
+ ? Math.min(MAX_PLANES, channels)
652
+ : 1;
653
+ }
544
654
  function flattenPlanes(channels) {
545
655
  const frames = channels[0]?.length ?? 0;
546
656
  const flat = new Float32Array(channels.length * frames);
@@ -298,7 +298,14 @@ export class Engine {
298
298
  return;
299
299
  this.canvas.width = width;
300
300
  this.canvas.height = height;
301
- this.#registry.resizeSurface?.(width, height);
301
+ try {
302
+ this.#registry.resizeSurface?.(width, height);
303
+ }
304
+ catch (error) {
305
+ // A lost renderer has no surface to size; the next render recovers and rebuilds it.
306
+ if (error?.code !== "GPU_DEVICE_LOST")
307
+ throw error;
308
+ }
302
309
  this.#sizeResultCache();
303
310
  this.#revision += 1;
304
311
  }
@@ -115,9 +115,10 @@ export function chooseAudioCodec(sampleRate: any, audioQuality: any, { container
115
115
  * Baseline it supports). Refuses before rendering, as `INVALID_INPUT`, when it cannot encode the
116
116
  * codec at the export's size and rate, since a retry would meet the same browser.
117
117
  */
118
- export function requireVideoEncoder(codec: any, { width, height }: {
118
+ export function requireVideoEncoder(codec: any, { width, height, frameRate }: {
119
119
  width: any;
120
120
  height: any;
121
+ frameRate: any;
121
122
  }, rate: any): Promise<import("alpha2/mediabunny").VideoTrackEncoding>;
122
123
  /** The video codecs a browser export may request, with display labels. */
123
124
  export const VIDEO_CODECS: {
@@ -55,6 +55,7 @@ export async function probeEncoders(width, height, { frameRate = { num: 30, den:
55
55
  (await canEncodeVideoTrack(codec.value, {
56
56
  width,
57
57
  height,
58
+ frameRate,
58
59
  rate: resolvedVideoRate({
59
60
  codec: engineVideoCodec(codec.value),
60
61
  width,
@@ -110,7 +111,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
110
111
  frameRate: rate,
111
112
  quality: videoQuality,
112
113
  });
113
- const videoEncoding = await requireVideoEncoder(videoCodec, settings, videoRateControl);
114
+ const videoEncoding = await requireVideoEncoder(videoCodec, { width: settings.width, height: settings.height, frameRate: rate }, videoRateControl);
114
115
  const softwareEncoder = await canEncodeInSoftware(videoCodec, {
115
116
  width: settings.width,
116
117
  height: settings.height,
@@ -770,12 +771,22 @@ export async function chooseAudioCodec(sampleRate, audioQuality, { container = "
770
771
  * Baseline it supports). Refuses before rendering, as `INVALID_INPUT`, when it cannot encode the
771
772
  * codec at the export's size and rate, since a retry would meet the same browser.
772
773
  */
773
- export async function requireVideoEncoder(codec, { width, height }, rate) {
774
- const encoding = await canEncodeVideoTrack(codec, { width, height, rate });
774
+ export async function requireVideoEncoder(codec, { width, height, frameRate }, rate) {
775
+ const encoding = await canEncodeVideoTrack(codec, {
776
+ width,
777
+ height,
778
+ frameRate,
779
+ rate,
780
+ });
775
781
  if (encoding !== null)
776
782
  return encoding;
777
783
  const label = VIDEO_CODECS.find((c) => c.value === codec)?.label ?? String(codec);
778
- const profiles = videoEncoderProfiles(codec, { width, height, rate });
784
+ const profiles = videoEncoderProfiles(codec, {
785
+ width,
786
+ height,
787
+ frameRate,
788
+ rate,
789
+ });
779
790
  const tried = profiles.length === 0
780
791
  ? ""
781
792
  : ` in any profile (tried ${profiles.map((p) => `${p.profile} ${p.codecString}`).join(", ")})`;