@alpha2-sh/editor 0.4.5 → 0.5.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 (81) hide show
  1. package/dist/browser/bridge.d.ts +15 -16
  2. package/dist/browser/bridge.js +533 -387
  3. package/dist/browser/extensions-worker.d.ts +12 -16
  4. package/dist/browser/extensions-worker.js +17 -24
  5. package/dist/browser/hash-worker.d.ts +4 -5
  6. package/dist/browser/hash-worker.js +7 -8
  7. package/dist/browser/jobs.d.ts +17 -19
  8. package/dist/browser/jobs.js +41 -28
  9. package/dist/browser/resources.d.ts +6 -11
  10. package/dist/browser/resources.js +5 -9
  11. package/dist/browser/runtime/assets.d.ts +52 -31
  12. package/dist/browser/runtime/assets.js +206 -47
  13. package/dist/browser/runtime/audio.d.ts +16 -11
  14. package/dist/browser/runtime/audio.js +58 -31
  15. package/dist/browser/runtime/budget.d.ts +4 -5
  16. package/dist/browser/runtime/budget.js +4 -5
  17. package/dist/browser/runtime/caption-fonts.d.ts +3 -7
  18. package/dist/browser/runtime/caption-fonts.js +4 -8
  19. package/dist/browser/runtime/engine.d.ts +40 -43
  20. package/dist/browser/runtime/engine.js +82 -63
  21. package/dist/browser/runtime/export-audio.d.ts +6 -6
  22. package/dist/browser/runtime/export-audio.js +8 -9
  23. package/dist/browser/runtime/exporter.d.ts +33 -66
  24. package/dist/browser/runtime/exporter.js +111 -137
  25. package/dist/browser/runtime/extension-import.d.ts +28 -35
  26. package/dist/browser/runtime/extension-import.js +36 -46
  27. package/dist/browser/runtime/fingerprint.d.ts +11 -14
  28. package/dist/browser/runtime/fingerprint.js +20 -24
  29. package/dist/browser/runtime/generators.d.ts +2 -3
  30. package/dist/browser/runtime/generators.js +5 -7
  31. package/dist/browser/runtime/locks.d.ts +5 -7
  32. package/dist/browser/runtime/locks.js +5 -7
  33. package/dist/browser/runtime/output.d.ts +7 -9
  34. package/dist/browser/runtime/output.js +17 -21
  35. package/dist/browser/runtime/preview-utils.js +10 -6
  36. package/dist/browser/runtime/proxies.d.ts +10 -17
  37. package/dist/browser/runtime/proxies.js +33 -45
  38. package/dist/browser/runtime/proxy-storage.d.ts +15 -19
  39. package/dist/browser/runtime/proxy-storage.js +20 -24
  40. package/dist/browser/runtime/sources.d.ts +23 -31
  41. package/dist/browser/runtime/sources.js +98 -105
  42. package/dist/browser/runtime/staging.d.ts +2 -6
  43. package/dist/browser/runtime/staging.js +7 -11
  44. package/dist/browser/runtime/still.d.ts +2 -6
  45. package/dist/browser/runtime/still.js +6 -12
  46. package/dist/browser/runtime/text.d.ts +14 -0
  47. package/dist/browser/runtime/text.js +27 -0
  48. package/dist/browser/runtime/wasm.d.ts +4 -5
  49. package/dist/browser/runtime/wasm.js +4 -5
  50. package/dist/browser/types.d.ts +243 -221
  51. package/dist/browser/worker.d.ts +8 -9
  52. package/dist/browser/worker.js +55 -22
  53. package/dist/core/captions.d.ts +8 -10
  54. package/dist/core/captions.js +10 -18
  55. package/dist/core/clip-time.d.ts +8 -10
  56. package/dist/core/clip-time.js +12 -15
  57. package/dist/core/commands.d.ts +46 -46
  58. package/dist/core/commands.js +38 -36
  59. package/dist/core/compositions.d.ts +78 -112
  60. package/dist/core/compositions.js +66 -94
  61. package/dist/core/document.d.ts +59 -92
  62. package/dist/core/document.js +65 -90
  63. package/dist/core/keyframes.d.ts +11 -12
  64. package/dist/core/keyframes.js +11 -13
  65. package/dist/core/presets.d.ts +14 -20
  66. package/dist/core/presets.js +12 -18
  67. package/dist/core/session.d.ts +26 -38
  68. package/dist/core/session.js +38 -53
  69. package/dist/core/text.d.ts +2 -3
  70. package/dist/core/text.js +2 -3
  71. package/dist/core/timeline-index.d.ts +2 -3
  72. package/dist/core/timeline-index.js +11 -7
  73. package/dist/core/transitions.js +4 -5
  74. package/dist/core/validated.d.ts +6 -7
  75. package/dist/core/validated.js +8 -11
  76. package/dist/native-client/index.d.ts +31 -32
  77. package/dist/native-client/index.js +40 -41
  78. package/dist/ports/index.d.ts +19 -19
  79. package/dist/react/index.d.ts +5 -6
  80. package/dist/react/index.js +5 -6
  81. package/package.json +4 -4
@@ -1,18 +1,27 @@
1
1
  /**
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.
2
+ * What a video container holds, read by the demuxer: its picture (`video`: size, frame rate, HDR
3
+ * declaration, and whether WebCodecs decodes it, or null without a video track) and whether it
4
+ * has audio. Null when the demuxer cannot read the container.
5
5
  */
6
6
  export function probeVideo(file: any): Promise<{
7
+ audioDecodeFacts?: import("alpha2/hdr-frames").TrackDecodeFacts | undefined;
7
8
  video: {
8
- colorMetadata: import("alpha2").ColorMetadata | null;
9
+ colorMetadata: import("alpha2/project").ColorMetadata | null;
9
10
  width: number;
10
11
  height: number;
11
12
  frameRate: number;
13
+ decodable: boolean;
14
+ facts: import("alpha2/hdr-frames").TrackDecodeFacts;
12
15
  } | null;
13
16
  hasAudio: boolean;
14
17
  audioDecodable: boolean;
15
18
  } | null>;
19
+ /**
20
+ * Why an import failed, in this editor's words. Browser error text (`MediaError`, decoder
21
+ * `DOMException`) exposes engine internals, so it is never shown and stays the error's cause.
22
+ * `facts` describe the video track when the probe read one.
23
+ */
24
+ export function importFailureReason(error: any, kind: any, facts: any): string;
16
25
  /**
17
26
  * Streams a file's primary audio track into per-bucket peak magnitudes (`bucketsPerSecond`, capped
18
27
  * at `maxBuckets`) with bounded memory. A bucket's peak is its loudest sample in any channel,
@@ -39,6 +48,15 @@ export const DEFAULT_TEXT: Readonly<{
39
48
  readonly lineHeight: 1.15;
40
49
  }>;
41
50
  export class AssetLibrary {
51
+ /**
52
+ * `hdrWithoutPlanes` handles HDR video this browser decodes only to frames without planes and has
53
+ * no software decoder for: `"refuse"` (the default) refuses its import with `unsupported_media`;
54
+ * `"preview-degraded"` imports it with `planarDecode: "unavailable"` for a tone-mapped preview
55
+ * that the bridge refuses to export.
56
+ */
57
+ constructor({ hdrWithoutPlanes }?: {
58
+ hdrWithoutPlanes?: string | undefined;
59
+ });
42
60
  get map(): Map<any, any>;
43
61
  get all(): any[];
44
62
  get(id: any): any;
@@ -71,13 +89,13 @@ export class AssetLibrary {
71
89
  name: any;
72
90
  locator: any;
73
91
  file: any;
74
- text: any;
92
+ text: string;
75
93
  }>;
76
94
  usedBy(doc: any): Set<any>;
77
95
  remove(id: any): void;
78
96
  /**
79
- * Imports browser files; each one that does not import is reported back with its name and why
80
- * (see {@link importFile}).
97
+ * Imports browser files; each failure is reported with its name and reason (see {@link
98
+ * importFile}).
81
99
  */
82
100
  importFiles(files: any, onProgress: any): Promise<{
83
101
  imported: ({
@@ -92,24 +110,29 @@ export class AssetLibrary {
92
110
  fit: string;
93
111
  thumbnail: HTMLCanvasElement;
94
112
  } | {
113
+ colorMetadata: any;
114
+ planarDecode: string;
115
+ fit: string;
116
+ thumbnail: null;
117
+ peaks: null;
118
+ audioDecodeFacts?: any;
95
119
  id: any;
96
120
  kind: string;
97
121
  name: any;
98
122
  locator: any;
99
123
  file: any;
100
124
  url: string;
101
- video: HTMLVideoElement;
125
+ video: HTMLVideoElement | null;
102
126
  width: any;
103
127
  height: any;
104
128
  frameRate: any;
105
129
  duration: number;
106
130
  hasAudio: any;
107
131
  audioDecodable: any;
108
- colorMetadata: any;
109
- fit: string;
110
- thumbnail: null;
111
- peaks: null;
112
132
  } | {
133
+ peaks: null;
134
+ thumbnail: null;
135
+ audioDecodeFacts?: import("alpha2/hdr-frames").TrackDecodeFacts | undefined;
113
136
  id: any;
114
137
  kind: string;
115
138
  name: any;
@@ -118,8 +141,6 @@ export class AssetLibrary {
118
141
  duration: number;
119
142
  hasAudio: boolean;
120
143
  audioDecodable: boolean;
121
- peaks: null;
122
- thumbnail: null;
123
144
  })[];
124
145
  rejected: {
125
146
  name: any;
@@ -129,11 +150,11 @@ export class AssetLibrary {
129
150
  }>;
130
151
  /**
131
152
  * Imports one browser file as an image, video or audio asset. Rejects with an `EditorError`:
132
- * `unsupported_media` for a file that is none of those, `unreadable_media` for one that is but
133
- * 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`.
153
+ * `unsupported_media` for a file that is none of those, `unreadable_media` when this browser
154
+ * cannot read it (with the decoder's or demuxer's reason as message and `cause`), or with
155
+ * `signal`'s reason once it aborts a decode.
135
156
  */
136
- importFile(file: any): Promise<{
157
+ importFile(file: any, { signal }?: {}): Promise<{
137
158
  id: any;
138
159
  kind: string;
139
160
  name: any;
@@ -145,24 +166,29 @@ export class AssetLibrary {
145
166
  fit: string;
146
167
  thumbnail: HTMLCanvasElement;
147
168
  } | {
169
+ colorMetadata: any;
170
+ planarDecode: string;
171
+ fit: string;
172
+ thumbnail: null;
173
+ peaks: null;
174
+ audioDecodeFacts?: any;
148
175
  id: any;
149
176
  kind: string;
150
177
  name: any;
151
178
  locator: any;
152
179
  file: any;
153
180
  url: string;
154
- video: HTMLVideoElement;
181
+ video: HTMLVideoElement | null;
155
182
  width: any;
156
183
  height: any;
157
184
  frameRate: any;
158
185
  duration: number;
159
186
  hasAudio: any;
160
187
  audioDecodable: any;
161
- colorMetadata: any;
162
- fit: string;
163
- thumbnail: null;
164
- peaks: null;
165
188
  } | {
189
+ peaks: null;
190
+ thumbnail: null;
191
+ audioDecodeFacts?: import("alpha2/hdr-frames").TrackDecodeFacts | undefined;
166
192
  id: any;
167
193
  kind: string;
168
194
  name: any;
@@ -171,8 +197,6 @@ export class AssetLibrary {
171
197
  duration: number;
172
198
  hasAudio: boolean;
173
199
  audioDecodable: boolean;
174
- peaks: null;
175
- thumbnail: null;
176
200
  }>;
177
201
  /** Registers a project-rate audio buffer synthesized in the page rather than read from a file. */
178
202
  addGeneratedAudio(name: any, audioBuffer: any): {
@@ -186,10 +210,7 @@ export class AssetLibrary {
186
210
  peaks: Float32Array<ArrayBuffer>;
187
211
  thumbnail: null;
188
212
  };
189
- /**
190
- * Creates a text source rasterized by the packaged `OffscreenTextRasterizer`, the browser host
191
- * for the engine's host-rasterized text contract.
192
- */
213
+ /** Creates a text source rasterized by the packaged `OffscreenTextRasterizer`. */
193
214
  createText(style?: {}, { id }?: {
194
215
  id?: string | undefined;
195
216
  }): {
@@ -211,8 +232,8 @@ export class AssetLibrary {
211
232
  thumbnail: null;
212
233
  };
213
234
  /**
214
- * Creates a source the engine draws itself from `generator` (see `generators.js`); it needs no
215
- * file and has no duration.
235
+ * Creates a source the engine draws from `generator` (see `generators.js`), with no file or
236
+ * duration.
216
237
  */
217
238
  createGenerated(generator: any, { id, name }?: {
218
239
  id?: string | undefined;
@@ -1,12 +1,15 @@
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
- import { colorMetadataFromVideoColorSpace } from "alpha2/hdr-frames";
3
+ import { codecName, colorMetadataFromVideoColorSpace, DecodeUnavailableError, decodeRefusalMessage, pictureDetails, PlanarDecodeUnavailableError, } from "alpha2/hdr-frames";
4
+ import { MediabunnyVideoDecoder, probeAudioSource, probePlanarDecode, videoTrackFacts, } 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()}`;
7
9
  import { drawGenerator, generatorLabel } from "./generators.js";
8
10
  import { seekVideoFrame } from "./preview-utils.js";
9
11
  import { decodeStill } from "./still.js";
12
+ import { readUserText } from "./text.js";
10
13
  import { EditorError } from "../../core/document.js";
11
14
  import { TEXT_DEFAULTS } from "../../core/text.js";
12
15
  import { displaySize } from "./fingerprint.js";
@@ -42,9 +45,22 @@ export const ACCEPTED_TYPES = [
42
45
  export const DEFAULT_TEXT = TEXT_DEFAULTS;
43
46
  export class AssetLibrary {
44
47
  #assets = new Map();
48
+ #hdrWithoutPlanes;
45
49
  #urls = [];
46
50
  #rasterizer = new OffscreenTextRasterizer();
47
51
  #textVersion = 1n;
52
+ /**
53
+ * `hdrWithoutPlanes` handles HDR video this browser decodes only to frames without planes and has
54
+ * no software decoder for: `"refuse"` (the default) refuses its import with `unsupported_media`;
55
+ * `"preview-degraded"` imports it with `planarDecode: "unavailable"` for a tone-mapped preview
56
+ * that the bridge refuses to export.
57
+ */
58
+ constructor({ hdrWithoutPlanes = "refuse" } = {}) {
59
+ if (hdrWithoutPlanes !== "refuse" &&
60
+ hdrWithoutPlanes !== "preview-degraded")
61
+ throw new RangeError('hdrWithoutPlanes must be "refuse" or "preview-degraded"');
62
+ this.#hdrWithoutPlanes = hdrWithoutPlanes;
63
+ }
48
64
  get map() {
49
65
  return this.#assets;
50
66
  }
@@ -115,7 +131,7 @@ export class AssetLibrary {
115
131
  name: reference?.name ?? file.name,
116
132
  locator: reference?.locator ?? localLocator(file, file.name),
117
133
  file,
118
- text: await file.text(),
134
+ text: await readUserText(file),
119
135
  };
120
136
  this.#assets.set(asset.id, asset);
121
137
  return asset;
@@ -131,8 +147,8 @@ export class AssetLibrary {
131
147
  this.#assets.delete(id);
132
148
  }
133
149
  /**
134
- * Imports browser files; each one that does not import is reported back with its name and why
135
- * (see {@link importFile}).
150
+ * Imports browser files; each failure is reported with its name and reason (see {@link
151
+ * importFile}).
136
152
  */
137
153
  async importFiles(files, onProgress) {
138
154
  const imported = [];
@@ -155,40 +171,41 @@ export class AssetLibrary {
155
171
  }
156
172
  /**
157
173
  * Imports one browser file as an image, video or audio asset. Rejects with an `EditorError`:
158
- * `unsupported_media` for a file that is none of those, `unreadable_media` for one that is but
159
- * 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`.
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
176
+ * `signal`'s reason once it aborts a decode.
161
177
  */
162
- async importFile(file) {
163
- return (await this.#import(file)).asset;
178
+ async importFile(file, { signal } = {}) {
179
+ return (await this.#import(file, signal)).asset;
164
180
  }
165
- async #import(file) {
181
+ async #import(file, signal) {
166
182
  const kind = mediaKindForFile(file);
167
183
  if (!kind)
168
184
  throw new EditorError("unsupported_media", `Cannot import ${file.name}: not an image, video or audio file`, "import");
169
185
  let as = kind;
186
+ let probe = null;
170
187
  try {
171
188
  // Probe the container first: browsers type by extension, so an audio-only .webm is `video/*`.
172
- const probe = kind === "video" ? await probeVideo(file) : null;
189
+ probe = kind === "video" ? await probeVideo(file) : null;
173
190
  if (probe && !probe.video && probe.hasAudio)
174
191
  as = "audio";
175
192
  const reference = this.#matchingReference(file, as);
176
193
  const asset = as === "image"
177
194
  ? await this.#importImage(file, reference)
178
195
  : as === "video"
179
- ? await this.#importVideo(file, reference, probe)
196
+ ? await this.#importVideo(file, reference, probe, signal)
180
197
  : await this.#importAudio(file, reference);
181
198
  return { asset, relinked: !!reference };
182
199
  }
183
200
  catch (error) {
184
- // A media element's MediaError is no Error, but says why in `message` too.
185
- const reason = typeof error?.message === "string"
186
- ? error.message
187
- : String(error ?? "");
188
- throw new EditorError("unreadable_media", `Cannot read ${file.name} as ${as}: ${reason || "this browser could not decode it"}`, "import", undefined, true, { cause: error });
201
+ if (signal?.aborted)
202
+ throw signal.reason;
203
+ if (error instanceof EditorError)
204
+ 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 });
189
206
  }
190
207
  }
191
- /** A still keeps its file, size, and thumbnail; `SourcePixels` decodes it again per frame. */
208
+ /** A still keeps its file, size and thumbnail; `SourcePixels` decodes it again per frame. */
192
209
  async #importImage(file, reference = null) {
193
210
  const bitmap = await decodeStill(file);
194
211
  let width, height, thumbnail;
@@ -214,10 +231,42 @@ export class AssetLibrary {
214
231
  this.#assets.set(asset.id, asset);
215
232
  return asset;
216
233
  }
217
- /** `probe` is null when the container was unreadable; an element with no picture is refused. */
218
- async #importVideo(file, reference = null, probe = null) {
234
+ /**
235
+ * `"available"` when this browser hands `file`'s HDR frames over as planes, `"unavailable"` when
236
+ * it decodes them only without planes and the library previews such tracks degraded. Rejects with
237
+ * `unsupported_media` otherwise.
238
+ */
239
+ async #planarDecode(file, probe) {
240
+ if (!probe?.video?.colorMetadata)
241
+ return "available";
242
+ try {
243
+ await probePlanarDecode(file, { declared: probe.video.colorMetadata });
244
+ return "available";
245
+ }
246
+ catch (error) {
247
+ // Only a track the browser can decode (to frames without planes) can preview degraded.
248
+ if (error instanceof PlanarDecodeUnavailableError &&
249
+ error.facts.softwareDecoder !== undefined &&
250
+ this.#hdrWithoutPlanes === "preview-degraded")
251
+ return "unavailable";
252
+ if (error instanceof PlanarDecodeUnavailableError ||
253
+ error instanceof DecodeUnavailableError)
254
+ throw new EditorError("unsupported_media", decodeRefusalMessage(file.name, error.facts), "import", undefined, true, { cause: error });
255
+ throw error;
256
+ }
257
+ }
258
+ /**
259
+ * `probe` is null when the container was unreadable; a file with no picture is refused. A file
260
+ * the media element cannot open still imports, with `video: null`, when the decoder can decode
261
+ * its picture.
262
+ */
263
+ async #importVideo(file, reference = null, probe = null, signal) {
219
264
  if (probe && !probe.video)
220
265
  throw new Error("the file has neither a picture nor sound");
266
+ // An HDR source must reach the engine as planes, which some browsers never hand over (opaque
267
+ // hardware frames and no software decoder). Refuse it here by name rather than at its first
268
+ // frame, unless the library takes it for a degraded preview.
269
+ const planarDecode = await this.#planarDecode(file, probe);
221
270
  const url = URL.createObjectURL(file);
222
271
  this.#urls.push(url);
223
272
  const video = document.createElement("video");
@@ -228,10 +277,18 @@ export class AssetLibrary {
228
277
  preload: "auto",
229
278
  loop: false,
230
279
  });
231
- await new Promise((resolve, reject) => {
232
- video.onloadeddata = resolve;
233
- video.onerror = () => reject(video.error ?? new Error("video decode failed"));
280
+ const failed = await new Promise((resolve) => {
281
+ video.onloadeddata = () => resolve(null);
282
+ video.onerror = () => resolve(video.error ?? new Error("video decode failed"));
234
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");
290
+ }
291
+ const element = failed ? null : video;
235
292
  if (!probe && !video.videoWidth)
236
293
  throw new Error("the browser found no picture in it");
237
294
  const read = probe?.video ?? {
@@ -241,8 +298,8 @@ export class AssetLibrary {
241
298
  colorMetadata: null,
242
299
  };
243
300
  // A chunked WebM (MediaRecorder timeslice) has no Duration and the element reports +Infinity.
244
- const duration = Number.isFinite(video.duration)
245
- ? video.duration
301
+ const duration = element && Number.isFinite(element.duration)
302
+ ? element.duration
246
303
  : ((await containerDuration(file)) ?? 0);
247
304
  const asset = {
248
305
  id: reference?.id ?? uid("src"),
@@ -251,25 +308,40 @@ export class AssetLibrary {
251
308
  locator: reference?.locator ?? localLocator(file, file.name),
252
309
  file,
253
310
  url,
254
- video,
311
+ video: element,
255
312
  width: read.width,
256
313
  height: read.height,
257
314
  frameRate: read.frameRate,
258
315
  duration,
259
- // Having audio is the document's fact; whether this browser decodes it is the session's.
316
+ // Having audio is a document fact; whether this browser decodes it is a session fact.
260
317
  hasAudio: probe?.hasAudio ?? false,
261
318
  audioDecodable: probe?.audioDecodable ?? false,
319
+ ...(probe?.audioDecodeFacts
320
+ ? { audioDecodeFacts: probe.audioDecodeFacts }
321
+ : {}),
262
322
  colorMetadata: read.colorMetadata,
323
+ // Whether this browser hands frames over as planes (a session fact). "unavailable" previews
324
+ // degraded and is never exported here.
325
+ planarDecode,
263
326
  fit: "contain",
264
327
  thumbnail: null,
265
328
  peaks: null,
266
329
  };
267
- asset.thumbnail = await videoThumbnail(video, read.width, read.height);
330
+ if (element)
331
+ asset.thumbnail = await videoThumbnail(element, read.width, read.height);
332
+ else {
333
+ try {
334
+ asset.thumbnail = await decodedThumbnail(asset, signal);
335
+ }
336
+ catch (error) {
337
+ throw new Error("the media element could not open it, and decoding it with WebCodecs failed too", { cause: error });
338
+ }
339
+ }
268
340
  this.#assets.set(asset.id, asset);
269
341
  return asset;
270
342
  }
271
343
  async #importAudio(file, reference = null) {
272
- const { duration, decodable } = await probeAudio(file);
344
+ const { duration, decodable, facts } = await probeAudio(file);
273
345
  const asset = {
274
346
  id: reference?.id ?? uid("src"),
275
347
  kind: "audio",
@@ -279,6 +351,7 @@ export class AssetLibrary {
279
351
  duration,
280
352
  hasAudio: true,
281
353
  audioDecodable: decodable,
354
+ ...(facts ? { audioDecodeFacts: facts } : {}),
282
355
  peaks: null,
283
356
  thumbnail: null,
284
357
  };
@@ -301,10 +374,7 @@ export class AssetLibrary {
301
374
  this.#assets.set(asset.id, asset);
302
375
  return asset;
303
376
  }
304
- /**
305
- * Creates a text source rasterized by the packaged `OffscreenTextRasterizer`, the browser host
306
- * for the engine's host-rasterized text contract.
307
- */
377
+ /** Creates a text source rasterized by the packaged `OffscreenTextRasterizer`. */
308
378
  createText(style = {}, { id = uid("src") } = {}) {
309
379
  const text = { ...DEFAULT_TEXT, ...style };
310
380
  const asset = {
@@ -322,8 +392,8 @@ export class AssetLibrary {
322
392
  return asset;
323
393
  }
324
394
  /**
325
- * Creates a source the engine draws itself from `generator` (see `generators.js`); it needs no
326
- * file and has no duration.
395
+ * Creates a source the engine draws from `generator` (see `generators.js`), with no file or
396
+ * duration.
327
397
  */
328
398
  createGenerated(generator, { id = uid("gen"), name = null } = {}) {
329
399
  const asset = {
@@ -420,9 +490,9 @@ function mediaKindForFile(file) {
420
490
  return null;
421
491
  }
422
492
  /**
423
- * 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.
493
+ * What a video container holds, read by the demuxer: its picture (`video`: size, frame rate, HDR
494
+ * declaration, and whether WebCodecs decodes it, or null without a video track) and whether it
495
+ * has audio. Null when the demuxer cannot read the container.
426
496
  */
427
497
  export async function probeVideo(file) {
428
498
  const input = new Input({
@@ -438,19 +508,23 @@ export async function probeVideo(file) {
438
508
  const space = await track.getColorSpace().catch(() => null);
439
509
  const shown = await displaySize(track);
440
510
  video = {
441
- // Only an HDR declaration is recorded, so the project knows the source needs the tone map.
511
+ // Only an HDR declaration is recorded, so the project knows the source needs tone mapping.
442
512
  colorMetadata: space?.transfer === "pq" || space?.transfer === "hlg"
443
513
  ? colorMetadataFromVideoColorSpace(space)
444
514
  : null,
445
515
  width: shown.width,
446
516
  height: shown.height,
447
517
  frameRate: stats?.averagePacketRate ?? 30,
518
+ decodable: await track.canDecode().catch(() => false),
519
+ facts: await videoTrackFacts(track),
448
520
  };
449
521
  }
522
+ const audioDecode = audio ? await audioDecoding(file) : null;
450
523
  return {
451
524
  video,
452
525
  hasAudio: audio !== null,
453
- audioDecodable: Boolean(audio && (await audio.canDecode().catch(() => false))),
526
+ audioDecodable: audioDecode?.decodable ?? false,
527
+ ...(audioDecode?.facts ? { audioDecodeFacts: audioDecode.facts } : {}),
454
528
  };
455
529
  }
456
530
  catch (error) {
@@ -461,6 +535,29 @@ export async function probeVideo(file) {
461
535
  input.dispose();
462
536
  }
463
537
  }
538
+ /** `MediaError` codes: the source is in a format the element does not read, or did not decode. */
539
+ const MEDIA_ERR_DECODE = 3;
540
+ const MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
541
+ /**
542
+ * Why an import failed, in this editor's words. Browser error text (`MediaError`, decoder
543
+ * `DOMException`) exposes engine internals, so it is never shown and stays the error's cause.
544
+ * `facts` describe the video track when the probe read one.
545
+ */
546
+ export function importFailureReason(error, kind, facts) {
547
+ const browserError = typeof DOMException !== "undefined" && error instanceof DOMException;
548
+ const mediaError = !(error instanceof Error) && typeof error?.code === "number";
549
+ if (!mediaError && !browserError && error instanceof Error)
550
+ return error.message;
551
+ const undecodable = browserError ||
552
+ error?.code === MEDIA_ERR_DECODE ||
553
+ error?.code === MEDIA_ERR_SRC_NOT_SUPPORTED;
554
+ if (!undecodable)
555
+ return `this browser could not read the ${kind}`;
556
+ if (kind !== "video" || !facts)
557
+ return `this browser cannot decode this ${kind}`;
558
+ const details = pictureDetails(facts);
559
+ return `this browser cannot decode ${codecName(facts.codec)} video${details.length > 0 ? ` (${details.join(", ")})` : ""}`;
560
+ }
464
561
  /** A container's length in seconds, as its last packet ends; null when it cannot be read. */
465
562
  async function containerDuration(file) {
466
563
  const input = new Input({
@@ -479,9 +576,23 @@ async function containerDuration(file) {
479
576
  }
480
577
  }
481
578
  /**
482
- * An audio file's duration, and whether this browser can decode it. A file this browser cannot
483
- * decode (Safari before 26 has no `AudioDecoder`) still imports: the document records the audio,
484
- * which a native host and another browser hear.
579
+ * Whether this browser decodes a file's primary audio, using the preview decoder's trial decode
580
+ * (`probeAudioSource`), and the refusal facts when not.
581
+ */
582
+ async function audioDecoding(file) {
583
+ try {
584
+ await probeAudioSource(file.name, file);
585
+ return { decodable: true, facts: null };
586
+ }
587
+ catch (error) {
588
+ if (error instanceof DecodeUnavailableError)
589
+ return { decodable: false, facts: error.facts };
590
+ throw error;
591
+ }
592
+ }
593
+ /**
594
+ * An audio file's duration and whether this browser can decode it (with facts when not). Files it
595
+ * cannot decode still import; the document records the audio for native hosts and other browsers.
485
596
  */
486
597
  async function probeAudio(file) {
487
598
  const input = new Input({
@@ -492,10 +603,10 @@ async function probeAudio(file) {
492
603
  const track = await input.getPrimaryAudioTrack();
493
604
  if (!track)
494
605
  throw new Error("media has no audio track");
495
- const decodable = await track.canDecode().catch(() => false);
606
+ const { decodable, facts } = await audioDecoding(file);
496
607
  const duration = (await track.getDurationFromMetadata().catch(() => null)) ??
497
608
  (decodable ? await track.computeDuration() : 0);
498
- return { duration, decodable };
609
+ return { duration, decodable, facts };
499
610
  }
500
611
  finally {
501
612
  input.dispose();
@@ -569,13 +680,31 @@ export function computePeaks(buffer, buckets = 1_200) {
569
680
  }
570
681
  return peaks;
571
682
  }
572
- function thumbnailFrom(image, width, height) {
683
+ /**
684
+ * A thumbnail of `image` shown at `width` x `height`. With `orientation`, `image` is a decoded
685
+ * frame that is mirrored left to right when `mirror` is set, then rotated `rotation` degrees
686
+ * clockwise to show upright.
687
+ */
688
+ function thumbnailFrom(image, width, height, orientation = null) {
573
689
  // Rendered once at import; the timeline re-reads `dataUrl` on every redraw.
574
690
  const scale = THUMBNAIL_WIDTH / Math.max(1, width);
575
691
  const canvas = document.createElement("canvas");
576
692
  canvas.width = THUMBNAIL_WIDTH;
577
693
  canvas.height = Math.max(1, Math.round(height * scale));
578
- canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
694
+ const context = canvas.getContext("2d");
695
+ if (orientation) {
696
+ const turned = orientation.rotation % 180 !== 0;
697
+ const drawn = turned
698
+ ? { width: canvas.height, height: canvas.width }
699
+ : { width: canvas.width, height: canvas.height };
700
+ context.translate(canvas.width / 2, canvas.height / 2);
701
+ context.rotate((orientation.rotation * Math.PI) / 180);
702
+ if (orientation.mirror)
703
+ context.scale(-1, 1);
704
+ context.drawImage(image, -drawn.width / 2, -drawn.height / 2, drawn.width, drawn.height);
705
+ }
706
+ else
707
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
579
708
  canvas.dataUrl = canvas.toDataURL("image/jpeg", 0.72);
580
709
  return canvas;
581
710
  }
@@ -598,6 +727,36 @@ async function videoThumbnail(video, width, height) {
598
727
  clone.removeAttribute("src");
599
728
  }
600
729
  }
730
+ /**
731
+ * A thumbnail of `asset` (a file the media element cannot open) from the preview decoder, whose
732
+ * stall limit bounds a decoder that never answers. Rejects when it decodes no picture, or with
733
+ * `signal`'s reason once it aborts.
734
+ */
735
+ async function decodedThumbnail(asset, signal) {
736
+ const decoder = await MediabunnyVideoDecoder.open(asset.id, asset.file);
737
+ try {
738
+ // Requests before the first frame present that frame, as preview shows it.
739
+ const seconds = Math.min(0.25 * (asset.duration || 1), 1);
740
+ const { frame, rotationDegrees, mirror } = await decoder.refill({
741
+ sourceId: asset.id,
742
+ mediaTimeTicks: BigInt(Math.round(seconds * TICKS_PER_SECOND)),
743
+ reason: "seek",
744
+ generation: 0,
745
+ }, signal);
746
+ try {
747
+ return thumbnailFrom(frame, asset.width, asset.height, {
748
+ rotation: rotationDegrees ?? 0,
749
+ mirror: mirror ?? false,
750
+ });
751
+ }
752
+ finally {
753
+ frame.close();
754
+ }
755
+ }
756
+ finally {
757
+ decoder.close();
758
+ }
759
+ }
601
760
  function generatedThumbnail(generator) {
602
761
  const canvas = document.createElement("canvas");
603
762
  canvas.width = THUMBNAIL_WIDTH;