@alpha2-sh/editor 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +60 -3
  2. package/dist/browser/bridge.d.ts +5 -4
  3. package/dist/browser/bridge.js +390 -67
  4. package/dist/browser/extensions-worker.d.ts +4 -3
  5. package/dist/browser/extensions-worker.js +13 -6
  6. package/dist/browser/jobs.d.ts +17 -0
  7. package/dist/browser/jobs.js +40 -0
  8. package/dist/browser/resources.d.ts +9 -4
  9. package/dist/browser/resources.js +17 -5
  10. package/dist/browser/runtime/assets.d.ts +14 -2
  11. package/dist/browser/runtime/assets.js +37 -27
  12. package/dist/browser/runtime/audio.d.ts +12 -2
  13. package/dist/browser/runtime/audio.js +124 -14
  14. package/dist/browser/runtime/engine.js +8 -1
  15. package/dist/browser/runtime/exporter.d.ts +2 -1
  16. package/dist/browser/runtime/exporter.js +15 -4
  17. package/dist/browser/runtime/extension-import.d.ts +30 -10
  18. package/dist/browser/runtime/extension-import.js +52 -9
  19. package/dist/browser/runtime/preview-utils.d.ts +12 -0
  20. package/dist/browser/runtime/preview-utils.js +45 -0
  21. package/dist/browser/runtime/sources.d.ts +2 -2
  22. package/dist/browser/runtime/sources.js +23 -40
  23. package/dist/browser/runtime/wasm.d.ts +5 -5
  24. package/dist/browser/runtime/wasm.js +6 -13
  25. package/dist/browser/types.d.ts +138 -26
  26. package/dist/browser/worker.d.ts +4 -2
  27. package/dist/browser/worker.js +75 -25
  28. package/dist/core/commands.d.ts +46 -3
  29. package/dist/core/commands.js +212 -40
  30. package/dist/core/compositions.d.ts +27 -0
  31. package/dist/core/compositions.js +43 -0
  32. package/dist/core/data.d.ts +34 -0
  33. package/dist/core/data.js +69 -0
  34. package/dist/core/document.d.ts +20 -1
  35. package/dist/core/document.js +138 -8
  36. package/dist/core/keyframes.d.ts +3 -2
  37. package/dist/core/keyframes.js +6 -2
  38. package/dist/core/sameness.d.ts +6 -0
  39. package/dist/core/sameness.js +42 -0
  40. package/dist/core/session.d.ts +85 -7
  41. package/dist/core/session.js +124 -13
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.js +1 -0
  44. package/dist/native-client/index.d.ts +2 -2
  45. package/dist/native-client/index.js +2 -2
  46. package/dist/ports/index.d.ts +5 -4
  47. package/package.json +3 -3
@@ -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(", ")})`;
@@ -1,10 +1,10 @@
1
- /** Whether a file's start could be SVG, GIF, animated WebP, APNG, Lottie, dotLottie or OpenEXR. */
1
+ /** Whether a file's start could be SVG, GIF, WebP, APNG, Lottie, dotLottie, OpenEXR or PDF. */
2
2
  export function mayBeExtension(head: any): boolean;
3
3
  /**
4
4
  * The byte limit for a file that could be a document format a provider parses whole, by its start:
5
- * dotLottie (ZIP, `MAX_PROVIDER_DOCUMENT_BYTES`), Lottie (JSON, `MAX_LOTTIE_DOCUMENT_BYTES`) or
6
- * SVG (XML, `MAX_SVG_DOCUMENT_BYTES`), with the format's name; `null` for other files. Larger
7
- * files are refused unread.
5
+ * dotLottie (ZIP, `MAX_PROVIDER_DOCUMENT_BYTES`), Lottie (JSON, `MAX_LOTTIE_DOCUMENT_BYTES`), SVG
6
+ * (XML, `MAX_SVG_DOCUMENT_BYTES`) or PDF (`MAX_PDF_DOCUMENT_BYTES`), with the format's name;
7
+ * `null` for other files. Larger files are refused unread.
8
8
  */
9
9
  export function providerDocumentLimit(head: any): {
10
10
  limit: number;
@@ -36,18 +36,28 @@ export function keepProviderChoices(recorded: any, staged: any, report: any): an
36
36
  */
37
37
  export function readProviderFile(extensions: any, bytes: any): Promise<{
38
38
  report: any;
39
- provider: {
40
- format: any;
41
- } | {
42
- animation?: any;
43
- format: string;
44
- };
39
+ provider: any;
45
40
  thumbnail: {
46
41
  dataUrl: any;
47
42
  width: number;
48
43
  height: number;
49
44
  };
50
45
  } | null>;
46
+ /**
47
+ * What a provider source shows: its report and a first-frame thumbnail. `bytes` are its file,
48
+ * absent for a provider that reads none.
49
+ *
50
+ * @throws When the source does not open.
51
+ */
52
+ export function readProviderSource(extensions: any, provider: any, bytes: any): Promise<{
53
+ report: any;
54
+ provider: any;
55
+ thumbnail: {
56
+ dataUrl: any;
57
+ width: number;
58
+ height: number;
59
+ };
60
+ }>;
51
61
  /**
52
62
  * An SVG's diagnostics when opened with font stack `fonts`, listing text no font draws
53
63
  * (`missing_font`).
@@ -187,3 +197,13 @@ export function exrFirstFrame(extensions: any, bytes: any): Promise<{
187
197
  };
188
198
  report: any;
189
199
  }>;
200
+ /**
201
+ * The provider modules' `.wasm` URLs by module name, as strings a worker can be sent. The core
202
+ * module's comes from `extensionsWasmUrl`, any other's from `extensionModuleUrls`.
203
+ * @param {{ extensionsWasmUrl?: string | URL, extensionModuleUrls?: import("alpha2/extensions").ExtensionWasmUrls } | undefined} assets
204
+ * @returns {Record<string, string>}
205
+ */
206
+ export function extensionWasmUrls(assets: {
207
+ extensionsWasmUrl?: string | URL;
208
+ extensionModuleUrls?: import("alpha2/extensions").ExtensionWasmUrls;
209
+ } | undefined): Record<string, string>;
@@ -1,12 +1,12 @@
1
1
  // Importing media an extension provider reads. The provider is chosen by probing bytes, never by
2
2
  // file name; the extensions wasm module loads only when the bytes could match one of its formats.
3
- import { MAX_LOTTIE_DOCUMENT_BYTES, MAX_PROVIDER_DOCUMENT_BYTES, MAX_SEQUENCE_FRAMES, MAX_SVG_DOCUMENT_BYTES, } from "alpha2/project";
3
+ import { MAX_LOTTIE_DOCUMENT_BYTES, MAX_PDF_DOCUMENT_BYTES, MAX_PROVIDER_DOCUMENT_BYTES, MAX_SEQUENCE_FRAMES, MAX_SVG_DOCUMENT_BYTES, } from "alpha2/project";
4
4
  import { EditorError } from "../../core/document.js";
5
5
  const TICKS_PER_SECOND = 120_000;
6
- /** Whether a file's start could be SVG, GIF, animated WebP, APNG, Lottie, dotLottie or OpenEXR. */
6
+ /** Whether a file's start could be SVG, GIF, WebP, APNG, Lottie, dotLottie, OpenEXR or PDF. */
7
7
  export function mayBeExtension(head) {
8
8
  const ascii = (at, text) => [...text].every((char, index) => head[at + index] === char.charCodeAt(0));
9
- if (ascii(0, "GIF8") || isExr(head))
9
+ if (ascii(0, "GIF8") || isExr(head) || isPdf(head))
10
10
  return true;
11
11
  if (ascii(0, "RIFF") && ascii(8, "WEBP"))
12
12
  return ascii(12, "VP8X") && (head[20] & 0x02) !== 0;
@@ -22,11 +22,13 @@ export function mayBeExtension(head) {
22
22
  }
23
23
  /**
24
24
  * The byte limit for a file that could be a document format a provider parses whole, by its start:
25
- * dotLottie (ZIP, `MAX_PROVIDER_DOCUMENT_BYTES`), Lottie (JSON, `MAX_LOTTIE_DOCUMENT_BYTES`) or
26
- * SVG (XML, `MAX_SVG_DOCUMENT_BYTES`), with the format's name; `null` for other files. Larger
27
- * files are refused unread.
25
+ * dotLottie (ZIP, `MAX_PROVIDER_DOCUMENT_BYTES`), Lottie (JSON, `MAX_LOTTIE_DOCUMENT_BYTES`), SVG
26
+ * (XML, `MAX_SVG_DOCUMENT_BYTES`) or PDF (`MAX_PDF_DOCUMENT_BYTES`), with the format's name;
27
+ * `null` for other files. Larger files are refused unread.
28
28
  */
29
29
  export function providerDocumentLimit(head) {
30
+ if (isPdf(head))
31
+ return { limit: MAX_PDF_DOCUMENT_BYTES, what: "PDF document" };
30
32
  if (head[0] === 0x50 &&
31
33
  head[1] === 0x4b &&
32
34
  head[2] === 0x03 &&
@@ -39,6 +41,16 @@ export function providerDocumentLimit(head) {
39
41
  return { limit: MAX_SVG_DOCUMENT_BYTES, what: "SVG document" };
40
42
  return null;
41
43
  }
44
+ /** Whether `%PDF-` starts within the first 1024 bytes, as PDF readers accept. */
45
+ function isPdf(head) {
46
+ const signature = [0x25, 0x50, 0x44, 0x46, 0x2d];
47
+ const end = Math.min(head.length, 1024) - signature.length;
48
+ for (let at = 0; at <= end; at++) {
49
+ if (signature.every((byte, index) => head[at + index] === byte))
50
+ return true;
51
+ }
52
+ return false;
53
+ }
42
54
  function isExr(head) {
43
55
  return (head[0] === 0x76 && head[1] === 0x2f && head[2] === 0x31 && head[3] === 0x01);
44
56
  }
@@ -141,12 +153,19 @@ export function keepProviderChoices(recorded, staged, report) {
141
153
  recorded.primaries !== undefined &&
142
154
  report?.color)
143
155
  return { ...staged, primaries: recorded.primaries };
156
+ if (staged.format === "pdf" &&
157
+ recorded.page !== undefined &&
158
+ report?.items?.includes(String(recorded.page)))
159
+ return { ...staged, page: recorded.page };
144
160
  return staged;
145
161
  }
146
162
  /** The provider source import records for a probed file. */
147
163
  function providerOf(report) {
148
164
  if (report.format === "svg" || report.format === "exr")
149
165
  return { format: report.format };
166
+ // The first page, until the user picks another.
167
+ if (report.format === "pdf")
168
+ return { format: "pdf", page: 1 };
150
169
  if (report.format === "lottie" || report.format === "dot_lottie")
151
170
  return {
152
171
  format: "lottie",
@@ -165,14 +184,24 @@ function providerOf(report) {
165
184
  * @throws When a provider claims the bytes and cannot read them.
166
185
  */
167
186
  export async function readProviderFile(extensions, bytes) {
168
- const found = extensions.probe(bytes);
187
+ const found = await extensions.probe(bytes);
169
188
  if (!found)
170
189
  return null;
171
- const provider = providerOf(found.report);
190
+ const read = await readProviderSource(extensions, providerOf(found.report), bytes);
191
+ return { ...read, report: found.report };
192
+ }
193
+ /**
194
+ * What a provider source shows: its report and a first-frame thumbnail. `bytes` are its file,
195
+ * absent for a provider that reads none.
196
+ *
197
+ * @throws When the source does not open.
198
+ */
199
+ export async function readProviderSource(extensions, provider, bytes) {
200
+ await extensions.prepare(provider);
172
201
  const source = extensions.open(provider, bytes);
173
202
  try {
174
203
  return {
175
- report: found.report,
204
+ report: source.report,
176
205
  provider,
177
206
  thumbnail: await thumbnailOf(source.render(0n, { width: 160, height: 90 })),
178
207
  };
@@ -509,3 +538,17 @@ export async function exrFirstFrame(extensions, bytes) {
509
538
  source.release();
510
539
  }
511
540
  }
541
+ /**
542
+ * The provider modules' `.wasm` URLs by module name, as strings a worker can be sent. The core
543
+ * module's comes from `extensionsWasmUrl`, any other's from `extensionModuleUrls`.
544
+ * @param {{ extensionsWasmUrl?: string | URL, extensionModuleUrls?: import("alpha2/extensions").ExtensionWasmUrls } | undefined} assets
545
+ * @returns {Record<string, string>}
546
+ */
547
+ export function extensionWasmUrls(assets) {
548
+ const urls = { ...assets?.extensionModuleUrls };
549
+ if (assets?.extensionsWasmUrl)
550
+ urls.core = assets.extensionsWasmUrl;
551
+ return Object.fromEntries(Object.entries(urls)
552
+ .filter(([, url]) => url)
553
+ .map(([name, url]) => [name, String(url)]));
554
+ }
@@ -1,3 +1,15 @@
1
1
  export function containRect(sourceWidth: any, sourceHeight: any, width: any, height: any): number[];
2
2
  export function previewFrameIndex(seconds: any, fps: any): number;
3
+ /**
4
+ * Loads `video` and resolves once its first frame is available. Rejects with the element's error,
5
+ * with a timeout after `timeoutMs` of active time (a frozen page does not count), or with
6
+ * `signal`'s reason once it aborts. Its listeners are removed on every path.
7
+ */
8
+ export function loadedOrFailed(video: any, { signal, timeoutMs }?: {
9
+ timeoutMs?: number | undefined;
10
+ }): Promise<any>;
11
+ /** Releases a media element's media. */
12
+ export function unloadVideo(video: any): void;
3
13
  export function seekVideoFrame(video: any, seconds: any, tolerance?: number): Promise<void>;
14
+ /** Active time a media element may take to load its first frame. */
15
+ export const MEDIA_LOAD_TIMEOUT_MS: 10000;
@@ -16,6 +16,51 @@ export function containRect(sourceWidth, sourceHeight, width, height) {
16
16
  export function previewFrameIndex(seconds, fps) {
17
17
  return Math.floor(seconds * fps + 1e-7);
18
18
  }
19
+ /** Active time a media element may take to load its first frame. */
20
+ export const MEDIA_LOAD_TIMEOUT_MS = 10_000;
21
+ /**
22
+ * Loads `video` and resolves once its first frame is available. Rejects with the element's error,
23
+ * with a timeout after `timeoutMs` of active time (a frozen page does not count), or with
24
+ * `signal`'s reason once it aborts. Its listeners are removed on every path.
25
+ */
26
+ export function loadedOrFailed(video, { signal, timeoutMs = MEDIA_LOAD_TIMEOUT_MS } = {}) {
27
+ return new Promise((resolve, reject) => {
28
+ const timer = new AbortController();
29
+ const cleanup = () => {
30
+ timer.abort();
31
+ video.removeEventListener("loadeddata", ready);
32
+ video.removeEventListener("error", failed);
33
+ signal?.removeEventListener("abort", aborted);
34
+ };
35
+ const ready = () => {
36
+ cleanup();
37
+ resolve();
38
+ };
39
+ const failed = () => {
40
+ cleanup();
41
+ reject(video.error ?? new Error("video load failed"));
42
+ };
43
+ const aborted = () => {
44
+ cleanup();
45
+ reject(signal.reason);
46
+ };
47
+ if (signal?.aborted)
48
+ return reject(signal.reason);
49
+ void activeTimeout(timeoutMs, timer.signal).then(() => {
50
+ cleanup();
51
+ reject(new Error("video load timed out"));
52
+ });
53
+ video.addEventListener("loadeddata", ready, { once: true });
54
+ video.addEventListener("error", failed, { once: true });
55
+ signal?.addEventListener("abort", aborted, { once: true });
56
+ video.load();
57
+ });
58
+ }
59
+ /** Releases a media element's media. */
60
+ export function unloadVideo(video) {
61
+ video.removeAttribute("src");
62
+ video.load();
63
+ }
19
64
  export async function seekVideoFrame(video, seconds, tolerance = 0.001) {
20
65
  if (!video.seeking &&
21
66
  Math.abs(video.currentTime - seconds) <= tolerance &&
@@ -14,7 +14,7 @@ export const DEFAULT_RASTER_BUDGET_BYTES: number;
14
14
  export const DEFAULT_PROVIDER_SOURCE_BYTES: number;
15
15
  /** The host side of the engine's per-frame source requests for one renderer (preview or export). */
16
16
  export class SourcePixels {
17
- constructor(library: any, { decoderLimit, rasterBudgetBytes, providerSourceBytes, extensionsWasmUrl, videoDecode, }?: {
17
+ constructor(library: any, { decoderLimit, rasterBudgetBytes, providerSourceBytes, extensionWasmUrls, videoDecode, }?: {
18
18
  decoderLimit?: number | undefined;
19
19
  rasterBudgetBytes?: number | undefined;
20
20
  providerSourceBytes?: number | undefined;
@@ -24,7 +24,7 @@ export class SourcePixels {
24
24
  rasterBudgetBytes: number;
25
25
  providerSourceBytes: number;
26
26
  library: any;
27
- extensionsWasmUrl: any;
27
+ extensionWasmUrls: any;
28
28
  /**
29
29
  * `"auto"` lets the browser pick, hardware where available; `"software"` decodes on the CPU so
30
30
  * no frame needs a GPU readback. Sources without a software decoder decode as `"auto"` and are