@alpha2-sh/editor 0.2.2 → 0.3.1

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.
@@ -9,6 +9,8 @@ import { EditorError } from "../../core/document.js";
9
9
  const RESULT_CACHE_FRAMES = 6;
10
10
  /** The diagnostics panel refreshes at this rate, not at the render rate. */
11
11
  const DIAGNOSTICS_INTERVAL_MS = 250;
12
+ /** A runtime effect definition's identity, `id@version`, as the engine names it. */
13
+ const effectKey = (definition) => `${definition.id}@${definition.version}`;
12
14
  /**
13
15
  * The wasm renderer of one preview or export: owns the engine instance, its frame supply, and a
14
16
  * render queue that collapses to the newest request.
@@ -25,15 +27,24 @@ export class Engine {
25
27
  #lastDiagnosticsAt = 0;
26
28
  #fps = [];
27
29
  #effectResources = new Map();
30
+ /** The runtime effects registered on this renderer, as `id@version`. */
31
+ #effects = new Set();
32
+ /** Frames the player drew, and frames it found equal to the one shown; cumulative. */
33
+ #renders = 0;
34
+ #unchanged = 0;
28
35
  /** What `supply` uploaded for the export frame the engine has not rendered yet. */
29
36
  #exportUploads = [];
30
- constructor(canvas, sources, library, runtimeAssets = {}) {
37
+ constructor(canvas, sources, library, runtimeAssets = {}, { unreadableFrames } = {}) {
31
38
  this.runtimeAssets = runtimeAssets;
39
+ /** What the frame supply does with a frame the browser cannot read back (`FrameSupply`). */
40
+ this.unreadableFrames = unreadableFrames;
32
41
  this.canvas = canvas;
33
42
  this.sources = sources;
34
43
  this.library = library;
35
44
  this.kind = "wasm";
36
45
  this.traceUploads = false;
46
+ /** Which preview draws with this renderer, as its diagnostics report it. */
47
+ this.backend = "main-thread";
37
48
  this.lastDiagnostics = null;
38
49
  this.lastRenderMs = 0;
39
50
  this.onDiagnostics = null;
@@ -49,7 +60,11 @@ export class Engine {
49
60
  : await WebEffectRegistry.createForHtmlCanvas(this.canvas);
50
61
  this.#effectResources = new Map();
51
62
  this.#sizeResultCache();
52
- this.#supply = new FrameSupply(this.#registry);
63
+ this.#supply = new FrameSupply(this.#registry, {
64
+ ...(this.unreadableFrames === undefined
65
+ ? {}
66
+ : { unreadableFrames: this.unreadableFrames }),
67
+ });
53
68
  // `engine.traceUploads = true` in the console logs every source upload, to tell a host decode
54
69
  // bug from an engine one when a clip shows another clip's picture.
55
70
  this.#supply.onUpload = (entry) => {
@@ -71,6 +86,31 @@ export class Engine {
71
86
  #sizeResultCache() {
72
87
  this.#registry.setResultCacheBudget(RESULT_CACHE_FRAMES * this.canvas.width * this.canvas.height * 8);
73
88
  }
89
+ /**
90
+ * Turns per-pass GPU and CPU timing on or off; the passes then appear in `lastDiagnostics`.
91
+ * Off by default: timing is profiling cost, not rendering work.
92
+ */
93
+ setPassTiming(enabled) {
94
+ this.#registry?.setPassTiming(enabled);
95
+ }
96
+ /**
97
+ * Sets the preview resolution scale (the engine's `QualityProfile` resolution scale; 1 renders
98
+ * at the document's size) and returns the loaded project's render size as `[width, height]`, or
99
+ * null with no project loaded. Throws for a scale the engine refuses.
100
+ */
101
+ setPreviewScale(scale) {
102
+ if (!this.#registry)
103
+ throw new Error("the renderer is not initialized");
104
+ this.#registry.setPreviewScale(scale);
105
+ this.#revision += 1;
106
+ return this.previewSize;
107
+ }
108
+ /** The loaded project's render size at the preview scale, `[width, height]`, or null. */
109
+ get previewSize() {
110
+ if (!this.#registry || !this.#project)
111
+ return null;
112
+ return Array.from(this.#registry.previewSize);
113
+ }
74
114
  /** The renderer's part of the capability report: GPU, color, and playback. */
75
115
  capabilityReport() {
76
116
  return this.#registry
@@ -91,11 +131,25 @@ export class Engine {
91
131
  get deviceLost() {
92
132
  return this.#registry?.deviceLost ?? false;
93
133
  }
94
- /** Raw source video the frame supply copied through script memory, cumulative. */
134
+ /**
135
+ * Raw source video the frame supply copied through script memory, and the frames it could not
136
+ * read back and how it recovered them; cumulative.
137
+ */
95
138
  get sourceTransfer() {
96
- return (this.#supply?.sourceTransfer ?? {
97
- planarCopyFrames: 0,
98
- planarCopyBytes: 0,
139
+ return {
140
+ ...(this.#supply?.sourceTransfer ?? {
141
+ planarCopyFrames: 0,
142
+ planarCopyBytes: 0,
143
+ }),
144
+ ...this.#readbackRecovery(),
145
+ };
146
+ }
147
+ #readbackRecovery() {
148
+ return (this.#supply?.readbackRecovery ?? {
149
+ unreadableFrames: 0,
150
+ readbackRetries: 0,
151
+ redecodedFrames: 0,
152
+ presentedFrames: 0,
99
153
  });
100
154
  }
101
155
  /** The wasm object, for callers that drive audio directly. */
@@ -154,6 +208,46 @@ export class Engine {
154
208
  this.#revision += 1;
155
209
  this.#registry.resetPlayer();
156
210
  }
211
+ /**
212
+ * Compiles runtime effect definitions (`alpha2/effects` `EffectDefinition`s) on this renderer's
213
+ * device and registers them, all or none. An `id@version` this renderer holds already is skipped:
214
+ * a definition never changes under its version.
215
+ *
216
+ * Throws `invalid_effect` naming the first definition the engine refuses, with its diagnostics;
217
+ * then none of the call's definitions is registered.
218
+ */
219
+ async registerEffects(definitions, operation = "preview") {
220
+ if (!this.#registry)
221
+ throw new Error("the renderer is not initialized");
222
+ const fresh = definitions.filter((definition) => !this.#effects.has(effectKey(definition)));
223
+ const refusal = (definition, error) => new EditorError("invalid_effect", `Effect ${effectKey(definition)} is not one the engine runs: ${error instanceof Error ? error.message : String(error)}`, operation, effectKey(definition), true, { cause: error });
224
+ // `compileEffect` throws for a definition it refuses before compiling, else its promise
225
+ // rejects with the shader's diagnostics.
226
+ const compiled = await Promise.allSettled(fresh.map(async (definition) => this.#registry.compileEffect(JSON.stringify(definition))));
227
+ const failed = compiled.findIndex(({ status }) => status === "rejected");
228
+ if (failed !== -1) {
229
+ for (const result of compiled)
230
+ if (result.status === "fulfilled")
231
+ result.value.free?.();
232
+ throw refusal(fresh[failed], compiled[failed].reason);
233
+ }
234
+ const registered = [];
235
+ for (const [index, definition] of fresh.entries()) {
236
+ try {
237
+ this.#registry.registerCompiledEffect(compiled[index].value);
238
+ }
239
+ catch (error) {
240
+ for (const later of compiled.slice(index + 1))
241
+ later.value.free?.();
242
+ for (const done of registered)
243
+ this.#registry.unregisterEffect(done.id, done.version);
244
+ throw refusal(definition, error);
245
+ }
246
+ registered.push(definition);
247
+ }
248
+ for (const definition of registered)
249
+ this.#effects.add(effectKey(definition));
250
+ }
157
251
  /**
158
252
  * Registers the fonts caption tracks draw with, in fallback order. An SVG's text draws with the
159
253
  * same fonts, as the native host draws it with its caption fonts. Returns the fonts the engine
@@ -239,7 +333,9 @@ export class Engine {
239
333
  }
240
334
  /**
241
335
  * Requests one frame. Concurrent requests collapse to the most recent one so that scrubbing never
242
- * queues a backlog of stale frames.
336
+ * queues a backlog of stale frames. Resolves `{ rendered, unchanged }`: `rendered` is false when
337
+ * the request was superseded, and `unchanged` says the frame equals the one already shown, so
338
+ * nothing was drawn or presented and the surface still shows it.
243
339
  */
244
340
  render(seconds, { generation = null, context } = {}) {
245
341
  if (!this.#registry)
@@ -288,7 +384,7 @@ export class Engine {
288
384
  const isCurrent = () => revision === this.#revision &&
289
385
  (generation === null || generation === this.#generation);
290
386
  if (!isCurrent())
291
- return false;
387
+ return { rendered: false, unchanged: false };
292
388
  await this.sources.release(context.liveSourceIds);
293
389
  const started = performance.now();
294
390
  const playback = await this.#supply.render(BigInt(secondsToTicks(seconds)), {
@@ -302,10 +398,15 @@ export class Engine {
302
398
  isCurrent,
303
399
  });
304
400
  if (!playback)
305
- return false;
401
+ return { rendered: false, unchanged: false };
402
+ const unchanged = playback.unchanged === true;
403
+ if (unchanged)
404
+ this.#unchanged += 1;
405
+ else
406
+ this.#renders += 1;
306
407
  this.lastRenderMs = performance.now() - started;
307
408
  this.#sampleDiagnostics();
308
- return true;
409
+ return { rendered: true, unchanged };
309
410
  }
310
411
  #sampleDiagnostics() {
311
412
  const now = performance.now();
@@ -326,6 +427,11 @@ export class Engine {
326
427
  fps: Number(this.fps.toFixed(1)),
327
428
  renderMs: Number(this.lastRenderMs.toFixed(2)),
328
429
  uploadedFrames: this.#registry.uploadedFrameCount,
430
+ renders: this.#renders,
431
+ unchanged: this.#unchanged,
432
+ renderSize: [this.canvas.width, this.canvas.height],
433
+ backend: this.backend,
434
+ readbackRecovery: this.#readbackRecovery(),
329
435
  };
330
436
  this.lastDiagnostics = diagnostics;
331
437
  this.onDiagnostics?.(diagnostics);
@@ -29,7 +29,8 @@ export function probeEncoders(width: any, height: any, { frameRate, videoQuality
29
29
  * opened output (not yet finished), and the export report. Any failure discards the output and is
30
30
  * rethrown as an `ExportFailureError` with the phase it happened in; a cancellation rethrows the
31
31
  * abort reason. `createSink(options)` makes the muxer the frames and audio are written to, a
32
- * `MediabunnyMp4Sink` unless a test supplies another.
32
+ * `MediabunnySink` unless a test supplies another. `openOutput` receives the export's container
33
+ * beside the size estimate, so the file is named and typed for it.
33
34
  */
34
35
  export function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engine, project, doc, library, audioSupplier, range, options, openOutput, onProgress, signal, createSink, }: {
35
36
  supplyFrame: any;
@@ -45,15 +46,16 @@ export function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engin
45
46
  openOutput: any;
46
47
  onProgress: any;
47
48
  signal: any;
48
- createSink?: ((sinkOptions: any) => MediabunnyMp4Sink) | undefined;
49
+ createSink?: ((sinkOptions: any) => MediabunnySink) | undefined;
49
50
  }): Promise<{
50
- written: import("alpha2/mediabunny").Mp4Output;
51
+ written: import("alpha2/mediabunny").ExportOutput;
51
52
  output: any;
52
53
  result: {
53
54
  renderMs: number;
54
55
  frames: number;
55
56
  audio: boolean;
56
- videoCodec: any;
57
+ container: import("alpha2/containers").ExportContainer;
58
+ videoCodec: import("alpha2/rate-control").BrowserVideoCodec;
57
59
  videoRateControl: {
58
60
  bitrate: number;
59
61
  mode: "constant" | "variable";
@@ -95,6 +97,9 @@ export function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engin
95
97
  outputRepackBytes: any;
96
98
  sourcePlanarCopyFrames: any;
97
99
  sourcePlanarCopyBytes: any;
100
+ sourceUnreadableFrames: any;
101
+ sourceReadbackRetries: any;
102
+ sourceRedecodedFrames: any;
98
103
  peakEncodeQueueBytes: any;
99
104
  maxPendingMediaEvents: any;
100
105
  averagePendingMediaEvents: number;
@@ -108,17 +113,27 @@ export function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engin
108
113
  };
109
114
  };
110
115
  }>;
116
+ /**
117
+ * The export's container and video codec, with the container's defaults for what `options` leave
118
+ * out: `mp4` and its `avc`. A container that does not offer a requested codec (`webm` with `avc`,
119
+ * `mov` with `opus`) is refused before anything renders, as `INVALID_INPUT`.
120
+ */
121
+ export function exportFormat(options: any): import("alpha2/containers").ExportFormat;
111
122
  /**
112
123
  * The audio codec this browser encodes the export's audio with, and the rate its encoder is given:
113
- * AAC where it can, else Opus, each at the project rate where the encoder takes it and otherwise at
114
- * the rate a native host would convert to (`audioEncoderSampleRate` in `alpha2/mediabunny`), so
115
- * every project rate exports. A browser that encodes neither at any rate (Safari before 26 has a
116
- * VideoEncoder but no AudioEncoder) is refused here, before anything renders, as `INVALID_INPUT`:
117
- * a retry would meet the same browser.
124
+ * `codec` when one is asked for, else the first of the container's codecs this browser encodes, in
125
+ * the container's order (AAC, then Opus, in MP4 and MKV; AAC only in MOV; Opus only in WebM), each
126
+ * at the project rate where the encoder takes it and otherwise at the rate a native host would
127
+ * convert to (`audioEncoderSampleRate` in `alpha2/mediabunny`), so every project rate exports. A
128
+ * browser that encodes none of them at any rate (Safari before 26 has a VideoEncoder but no
129
+ * AudioEncoder; Firefox on Linux has no AAC encoder for a MOV) is refused here, before anything
130
+ * renders, as `INVALID_INPUT`: a retry would meet the same browser.
118
131
  *
119
132
  * @returns {Promise<{ codec: "aac" | "opus", sampleRate: number }>}
120
133
  */
121
- export function chooseAudioCodec(sampleRate: any, audioQuality: any): Promise<{
134
+ export function chooseAudioCodec(sampleRate: any, audioQuality: any, { container, codec: requested }?: {
135
+ container?: string | undefined;
136
+ }): Promise<{
122
137
  codec: "aac" | "opus";
123
138
  sampleRate: number;
124
139
  }>;
@@ -137,5 +152,5 @@ export const VIDEO_CODECS: {
137
152
  label: string;
138
153
  }[];
139
154
  export { engineVideoCodec };
140
- import { MediabunnyMp4Sink } from "alpha2/mediabunny";
155
+ import { MediabunnySink } from "alpha2/mediabunny";
141
156
  import { engineVideoCodec } from "alpha2/rate-control";
@@ -1,6 +1,7 @@
1
1
  // Deterministic export: the engine renders offscreen at export quality on its own exact rational
2
2
  // frame schedule, so no swapchain race can duplicate a frame and a missing source retries in place.
3
- import { audioEncoderSampleRate, canEncodeVideoTrack, MediabunnyMp4Sink, } from "alpha2/mediabunny";
3
+ import { ExportFormatError, offeredAudioCodecs, resolveExportFormat, } from "alpha2/containers";
4
+ import { audioEncoderSampleRate, canEncodeVideoTrack, MediabunnySink, } from "alpha2/mediabunny";
4
5
  import { engineVideoCodec, qualityLevels, resolveAudioBitrate, resolveVideoRateControl, } from "alpha2/rate-control";
5
6
  import { videoFrameFromI420, videoFrameRepackedBytes, } from "alpha2/video-frames";
6
7
  import * as engineBinding from "alpha2/wasm";
@@ -68,9 +69,10 @@ export async function probeEncoders(width, height, { frameRate = { num: 30, den:
68
69
  * opened output (not yet finished), and the export report. Any failure discards the output and is
69
70
  * rethrown as an `ExportFailureError` with the phase it happened in; a cancellation rethrows the
70
71
  * abort reason. `createSink(options)` makes the muxer the frames and audio are written to, a
71
- * `MediabunnyMp4Sink` unless a test supplies another.
72
+ * `MediabunnySink` unless a test supplies another. `openOutput` receives the export's container
73
+ * beside the size estimate, so the file is named and typed for it.
72
74
  */
73
- export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engine, project, doc, library, audioSupplier, range, options, openOutput, onProgress, signal, createSink = (sinkOptions) => new MediabunnyMp4Sink(sinkOptions), }) {
75
+ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engine, project, doc, library, audioSupplier, range, options, openOutput, onProgress, signal, createSink = (sinkOptions) => new MediabunnySink(sinkOptions), }) {
74
76
  const started = performance.now();
75
77
  const diagnosticsBefore = rendererDiagnostics(engine);
76
78
  const transferBefore = sourceTransfer?.();
@@ -83,12 +85,19 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
83
85
  let frameCount = Math.max(1, Math.round((end - start) * fps));
84
86
  const audio = project ? audibleSources(project, library) : [];
85
87
  const wantsAudio = options.includeAudio !== false && audio.length > 0 && engine != null;
88
+ // The container's defaults fill what the options leave out; the audio codec is settled below,
89
+ // by what this browser encodes.
90
+ const format = exportFormat(options);
91
+ const container = format.container;
86
92
  const audioQuality = options.audioQuality ?? "high";
87
93
  const audioEncoding = wantsAudio
88
- ? await chooseAudioCodec(settings.sampleRate, audioQuality)
94
+ ? await chooseAudioCodec(settings.sampleRate, audioQuality, {
95
+ container,
96
+ codec: options.audioCodec,
97
+ })
89
98
  : undefined;
90
99
  const audioCodec = audioEncoding?.codec;
91
- const videoCodec = options.videoCodec ?? "avc";
100
+ const videoCodec = format.videoCodec;
92
101
  const videoQuality = options.videoQuality ?? "high";
93
102
  // Resolved by the engine, so `high` costs the same here as on the native path.
94
103
  const videoRateControl = resolvedVideoRate({
@@ -110,11 +119,13 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
110
119
  };
111
120
  // Before anything renders: refused here when the destination cannot hold the estimated file.
112
121
  const output = await openOutput({
122
+ container,
113
123
  durationSeconds: end - start,
114
124
  videoBitrate: videoRateControl.bitrate,
115
125
  audioBitrate: audioBitrate ?? 0,
116
126
  });
117
127
  const sink = createSink({
128
+ container,
118
129
  videoCodec,
119
130
  audioCodec,
120
131
  videoRateControl,
@@ -370,11 +381,18 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
370
381
  transferAfter.planarCopyFrames - transferBefore.planarCopyFrames;
371
382
  metrics.sourcePlanarCopyBytes =
372
383
  transferAfter.planarCopyBytes - transferBefore.planarCopyBytes;
384
+ metrics.sourceUnreadableFrames =
385
+ transferAfter.unreadableFrames - transferBefore.unreadableFrames;
386
+ metrics.sourceReadbackRetries =
387
+ transferAfter.readbackRetries - transferBefore.readbackRetries;
388
+ metrics.sourceRedecodedFrames =
389
+ transferAfter.redecodedFrames - transferBefore.redecodedFrames;
373
390
  }
374
391
  const result = {
375
392
  renderMs,
376
393
  frames: produced,
377
394
  audio: wantsAudio,
395
+ container,
378
396
  videoCodec,
379
397
  // Named like the native host's result for native-versus-Wasm comparison.
380
398
  videoRateControl: {
@@ -565,6 +583,9 @@ function browserExportMetrics() {
565
583
  outputRepackBytes: 0,
566
584
  sourcePlanarCopyFrames: 0,
567
585
  sourcePlanarCopyBytes: 0,
586
+ sourceUnreadableFrames: 0,
587
+ sourceReadbackRetries: 0,
588
+ sourceRedecodedFrames: 0,
568
589
  peakEncodeQueueBytes: 0,
569
590
  maxPendingMediaEvents: 0,
570
591
  pendingDepthTotal: 0,
@@ -603,6 +624,11 @@ function finishBrowserExportMetrics(metrics, before, after) {
603
624
  outputRepackBytes: metrics.outputRepackBytes,
604
625
  sourcePlanarCopyFrames: metrics.sourcePlanarCopyFrames,
605
626
  sourcePlanarCopyBytes: metrics.sourcePlanarCopyBytes,
627
+ // Source frames the browser could not read back, the reads repeated, and the frames decoded
628
+ // again in software for it.
629
+ sourceUnreadableFrames: metrics.sourceUnreadableFrames,
630
+ sourceReadbackRetries: metrics.sourceReadbackRetries,
631
+ sourceRedecodedFrames: metrics.sourceRedecodedFrames,
606
632
  peakEncodeQueueBytes: metrics.peakEncodeQueueBytes,
607
633
  maxPendingMediaEvents: metrics.maxPendingMediaEvents,
608
634
  averagePendingMediaEvents: metrics.pendingDepthSamples === 0
@@ -689,20 +715,54 @@ async function i420VideoFrame(step, timestamp, duration) {
689
715
  colorSpace: step.colorSpace,
690
716
  });
691
717
  }
692
- /** The audio codecs an export may write, in the order they are preferred, with their names. */
718
+ /** The audio codecs an export may write, with their names. */
693
719
  const AUDIO_CODECS = { aac: "AAC", opus: "Opus" };
720
+ /**
721
+ * The export's container and video codec, with the container's defaults for what `options` leave
722
+ * out: `mp4` and its `avc`. A container that does not offer a requested codec (`webm` with `avc`,
723
+ * `mov` with `opus`) is refused before anything renders, as `INVALID_INPUT`.
724
+ */
725
+ export function exportFormat(options) {
726
+ try {
727
+ return resolveExportFormat({
728
+ container: options.container ?? "mp4",
729
+ ...(options.videoCodec === undefined
730
+ ? {}
731
+ : { videoCodec: options.videoCodec }),
732
+ ...(options.audioCodec === undefined
733
+ ? {}
734
+ : { audioCodec: options.audioCodec }),
735
+ });
736
+ }
737
+ catch (error) {
738
+ if (!(error instanceof ExportFormatError))
739
+ throw error;
740
+ throw new ExportFailureError({
741
+ code: "INVALID_INPUT",
742
+ message: `${error.message}.`,
743
+ origin: "browser",
744
+ operation: "export",
745
+ backend: "unknown",
746
+ phase: "prepare",
747
+ resource: "unknown",
748
+ });
749
+ }
750
+ }
694
751
  /**
695
752
  * The audio codec this browser encodes the export's audio with, and the rate its encoder is given:
696
- * AAC where it can, else Opus, each at the project rate where the encoder takes it and otherwise at
697
- * the rate a native host would convert to (`audioEncoderSampleRate` in `alpha2/mediabunny`), so
698
- * every project rate exports. A browser that encodes neither at any rate (Safari before 26 has a
699
- * VideoEncoder but no AudioEncoder) is refused here, before anything renders, as `INVALID_INPUT`:
700
- * a retry would meet the same browser.
753
+ * `codec` when one is asked for, else the first of the container's codecs this browser encodes, in
754
+ * the container's order (AAC, then Opus, in MP4 and MKV; AAC only in MOV; Opus only in WebM), each
755
+ * at the project rate where the encoder takes it and otherwise at the rate a native host would
756
+ * convert to (`audioEncoderSampleRate` in `alpha2/mediabunny`), so every project rate exports. A
757
+ * browser that encodes none of them at any rate (Safari before 26 has a VideoEncoder but no
758
+ * AudioEncoder; Firefox on Linux has no AAC encoder for a MOV) is refused here, before anything
759
+ * renders, as `INVALID_INPUT`: a retry would meet the same browser.
701
760
  *
702
761
  * @returns {Promise<{ codec: "aac" | "opus", sampleRate: number }>}
703
762
  */
704
- export async function chooseAudioCodec(sampleRate, audioQuality) {
705
- for (const codec of /** @type {("aac" | "opus")[]} */ (Object.keys(AUDIO_CODECS))) {
763
+ export async function chooseAudioCodec(sampleRate, audioQuality, { container = "mp4", codec: requested } = {}) {
764
+ const candidates = requested === undefined ? offeredAudioCodecs(container) : [requested];
765
+ for (const codec of candidates) {
706
766
  const encoderRate = await audioEncoderSampleRate(codec, {
707
767
  sampleRate,
708
768
  numberOfChannels: 2,
@@ -713,7 +773,7 @@ export async function chooseAudioCodec(sampleRate, audioQuality) {
713
773
  }
714
774
  throw new ExportFailureError({
715
775
  code: "INVALID_INPUT",
716
- message: `This browser cannot encode audio (${Object.values(AUDIO_CODECS).join(" or ")}, stereo) at ${sampleRate} Hz or at any rate it could be converted to. Export without audio, or use the native exporter.`,
776
+ message: `This browser cannot encode audio for ${container} (${candidates.map((codec) => AUDIO_CODECS[codec]).join(" or ")}, stereo) at ${sampleRate} Hz or at any rate it could be converted to. ${requested === undefined ? "Export without audio, choose another container" : "Choose another audio codec, export without audio"}, or use the native exporter.`,
717
777
  origin: "browser",
718
778
  operation: "export",
719
779
  backend: "unknown",
@@ -34,12 +34,7 @@ export function encodeGenerator(generator: any): {
34
34
  radius?: undefined;
35
35
  angle_degrees?: undefined;
36
36
  };
37
- shape?: undefined;
38
- center?: undefined;
39
- size?: undefined;
40
- rotation_degrees?: undefined;
41
- fill?: undefined;
42
- stroke?: undefined;
37
+ items?: undefined;
43
38
  } | {
44
39
  type: string;
45
40
  paint: {
@@ -66,12 +61,7 @@ export function encodeGenerator(generator: any): {
66
61
  radius?: undefined;
67
62
  angle_degrees?: undefined;
68
63
  };
69
- shape?: undefined;
70
- center?: undefined;
71
- size?: undefined;
72
- rotation_degrees?: undefined;
73
- fill?: undefined;
74
- stroke?: undefined;
64
+ items?: undefined;
75
65
  } | {
76
66
  type: string;
77
67
  paint: {
@@ -95,12 +85,7 @@ export function encodeGenerator(generator: any): {
95
85
  end?: undefined;
96
86
  angle_degrees?: undefined;
97
87
  };
98
- shape?: undefined;
99
- center?: undefined;
100
- size?: undefined;
101
- rotation_degrees?: undefined;
102
- fill?: undefined;
103
- stroke?: undefined;
88
+ items?: undefined;
104
89
  } | {
105
90
  type: string;
106
91
  paint: {
@@ -124,51 +109,45 @@ export function encodeGenerator(generator: any): {
124
109
  end?: undefined;
125
110
  radius?: undefined;
126
111
  };
127
- shape?: undefined;
128
- center?: undefined;
129
- size?: undefined;
130
- rotation_degrees?: undefined;
131
- fill?: undefined;
132
- stroke?: undefined;
112
+ items?: undefined;
133
113
  } | {
134
114
  type: string;
135
- shape: {
115
+ items: ({
116
+ rotation_degrees: {
117
+ mode: string;
118
+ value: any;
119
+ };
120
+ corner_radius?: {
121
+ mode: string;
122
+ value: any;
123
+ } | undefined;
136
124
  type: string;
137
- corner_radius: number;
125
+ center: {
126
+ mode: string;
127
+ value: any;
128
+ };
129
+ size: {
130
+ mode: string;
131
+ value: any;
132
+ };
138
133
  } | {
139
134
  type: string;
140
- corner_radius?: undefined;
141
- };
142
- center: {
143
- x: number;
144
- y: number;
145
- };
146
- size: {
147
- x: number;
148
- y: number;
149
- };
150
- rotation_degrees: any;
151
- fill: {
152
- type: string;
153
- color: {
154
- red: number;
155
- green: number;
156
- blue: number;
157
- alpha: number;
135
+ width: {
136
+ mode: string;
137
+ value: any;
158
138
  };
159
- } | null;
160
- stroke: {
161
- width: number;
162
139
  paint: {
163
- type: string;
164
- color: {
165
- red: number;
166
- green: number;
167
- blue: number;
168
- alpha: number;
169
- };
140
+ mode: string;
141
+ value: any;
142
+ };
143
+ } | {
144
+ type: string;
145
+ paint: {
146
+ mode: string;
147
+ value: any;
170
148
  };
171
- } | null;
149
+ width?: undefined;
150
+ })[];
172
151
  paint?: undefined;
173
152
  };
174
153
  /**
@@ -75,27 +75,45 @@ export function encodeGenerator(generator) {
75
75
  default: {
76
76
  const stroked = generator.stroke.enabled;
77
77
  const filled = generator.fill || !stroked;
78
- return {
79
- type: "shape",
80
- shape: generator.kind === "rectangle"
81
- ? {
82
- type: "rectangle",
83
- corner_radius: Math.max(0, generator.cornerRadius),
84
- }
85
- : { type: "ellipse" },
86
- center,
87
- size: {
78
+ const constant = (value) => ({ mode: "constant", value });
79
+ const geometry = {
80
+ type: generator.kind === "rectangle" ? "rectangle" : "ellipse",
81
+ center: constant(center),
82
+ size: constant({
88
83
  x: Math.max(0, generator.size.x),
89
84
  y: Math.max(0, generator.size.y),
90
- },
91
- rotation_degrees: generator.rotation,
92
- fill: filled ? { type: "solid", color: rgba(first) } : null,
93
- stroke: stroked
94
- ? {
95
- width: Math.max(0.001, generator.stroke.width),
96
- paint: { type: "solid", color: rgba(generator.stroke.color) },
97
- }
98
- : null,
85
+ }),
86
+ ...(generator.kind === "rectangle"
87
+ ? { corner_radius: constant(Math.max(0, generator.cornerRadius)) }
88
+ : {}),
89
+ rotation_degrees: constant(generator.rotation),
90
+ };
91
+ // The stroke is listed first, so it is drawn over the fill.
92
+ return {
93
+ type: "shapes",
94
+ items: [
95
+ geometry,
96
+ ...(stroked
97
+ ? [
98
+ {
99
+ type: "stroke",
100
+ width: constant(Math.max(0.001, generator.stroke.width)),
101
+ paint: constant({
102
+ type: "solid",
103
+ color: rgba(generator.stroke.color),
104
+ }),
105
+ },
106
+ ]
107
+ : []),
108
+ ...(filled
109
+ ? [
110
+ {
111
+ type: "fill",
112
+ paint: constant({ type: "solid", color: rgba(first) }),
113
+ },
114
+ ]
115
+ : []),
116
+ ],
99
117
  };
100
118
  }
101
119
  }
@@ -12,13 +12,16 @@ export function storageSupport(): {
12
12
  * counts every write since its last disk scan, so `quota - usage` can be near zero on an empty
13
13
  * disk. A full disk fails at the write (`STORAGE_QUOTA_EXCEEDED`); the estimate is only reported.
14
14
  *
15
+ * `container` (default `mp4`) gives the temporary file its extension and the artifact its MIME
16
+ * type.
15
17
  * Returns `{ mode, destination, storageEstimate, abort, finish }`: `destination` is the sink's,
16
18
  * `abort` discards the file, and `finish(sinkOutput)` turns the finished output into the artifact's
17
19
  * fields.
18
20
  */
19
- export function openExportOutput({ jobId, name, target, durationSeconds, videoBitrate, audioBitrate, }: {
21
+ export function openExportOutput({ jobId, name, container, target, durationSeconds, videoBitrate, audioBitrate, }: {
20
22
  jobId: any;
21
23
  name: any;
24
+ container?: string | undefined;
22
25
  target: any;
23
26
  durationSeconds: any;
24
27
  videoBitrate: any;