@alpha2-sh/editor 0.2.2 → 0.3.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.
@@ -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";
@@ -108,17 +110,27 @@ export function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engin
108
110
  };
109
111
  };
110
112
  }>;
113
+ /**
114
+ * The export's container and video codec, with the container's defaults for what `options` leave
115
+ * out: `mp4` and its `avc`. A container that does not offer a requested codec (`webm` with `avc`,
116
+ * `mov` with `opus`) is refused before anything renders, as `INVALID_INPUT`.
117
+ */
118
+ export function exportFormat(options: any): import("alpha2/containers").ExportFormat;
111
119
  /**
112
120
  * 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.
121
+ * `codec` when one is asked for, else the first of the container's codecs this browser encodes, in
122
+ * the container's order (AAC, then Opus, in MP4 and MKV; AAC only in MOV; Opus only in WebM), each
123
+ * at the project rate where the encoder takes it and otherwise at the rate a native host would
124
+ * convert to (`audioEncoderSampleRate` in `alpha2/mediabunny`), so every project rate exports. A
125
+ * browser that encodes none of them at any rate (Safari before 26 has a VideoEncoder but no
126
+ * AudioEncoder; Firefox on Linux has no AAC encoder for a MOV) is refused here, before anything
127
+ * renders, as `INVALID_INPUT`: a retry would meet the same browser.
118
128
  *
119
129
  * @returns {Promise<{ codec: "aac" | "opus", sampleRate: number }>}
120
130
  */
121
- export function chooseAudioCodec(sampleRate: any, audioQuality: any): Promise<{
131
+ export function chooseAudioCodec(sampleRate: any, audioQuality: any, { container, codec: requested }?: {
132
+ container?: string | undefined;
133
+ }): Promise<{
122
134
  codec: "aac" | "opus";
123
135
  sampleRate: number;
124
136
  }>;
@@ -137,5 +149,5 @@ export const VIDEO_CODECS: {
137
149
  label: string;
138
150
  }[];
139
151
  export { engineVideoCodec };
140
- import { MediabunnyMp4Sink } from "alpha2/mediabunny";
152
+ import { MediabunnySink } from "alpha2/mediabunny";
141
153
  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,
@@ -375,6 +386,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
375
386
  renderMs,
376
387
  frames: produced,
377
388
  audio: wantsAudio,
389
+ container,
378
390
  videoCodec,
379
391
  // Named like the native host's result for native-versus-Wasm comparison.
380
392
  videoRateControl: {
@@ -689,20 +701,54 @@ async function i420VideoFrame(step, timestamp, duration) {
689
701
  colorSpace: step.colorSpace,
690
702
  });
691
703
  }
692
- /** The audio codecs an export may write, in the order they are preferred, with their names. */
704
+ /** The audio codecs an export may write, with their names. */
693
705
  const AUDIO_CODECS = { aac: "AAC", opus: "Opus" };
706
+ /**
707
+ * The export's container and video codec, with the container's defaults for what `options` leave
708
+ * out: `mp4` and its `avc`. A container that does not offer a requested codec (`webm` with `avc`,
709
+ * `mov` with `opus`) is refused before anything renders, as `INVALID_INPUT`.
710
+ */
711
+ export function exportFormat(options) {
712
+ try {
713
+ return resolveExportFormat({
714
+ container: options.container ?? "mp4",
715
+ ...(options.videoCodec === undefined
716
+ ? {}
717
+ : { videoCodec: options.videoCodec }),
718
+ ...(options.audioCodec === undefined
719
+ ? {}
720
+ : { audioCodec: options.audioCodec }),
721
+ });
722
+ }
723
+ catch (error) {
724
+ if (!(error instanceof ExportFormatError))
725
+ throw error;
726
+ throw new ExportFailureError({
727
+ code: "INVALID_INPUT",
728
+ message: `${error.message}.`,
729
+ origin: "browser",
730
+ operation: "export",
731
+ backend: "unknown",
732
+ phase: "prepare",
733
+ resource: "unknown",
734
+ });
735
+ }
736
+ }
694
737
  /**
695
738
  * 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.
739
+ * `codec` when one is asked for, else the first of the container's codecs this browser encodes, in
740
+ * the container's order (AAC, then Opus, in MP4 and MKV; AAC only in MOV; Opus only in WebM), each
741
+ * at the project rate where the encoder takes it and otherwise at the rate a native host would
742
+ * convert to (`audioEncoderSampleRate` in `alpha2/mediabunny`), so every project rate exports. A
743
+ * browser that encodes none of them at any rate (Safari before 26 has a VideoEncoder but no
744
+ * AudioEncoder; Firefox on Linux has no AAC encoder for a MOV) is refused here, before anything
745
+ * renders, as `INVALID_INPUT`: a retry would meet the same browser.
701
746
  *
702
747
  * @returns {Promise<{ codec: "aac" | "opus", sampleRate: number }>}
703
748
  */
704
- export async function chooseAudioCodec(sampleRate, audioQuality) {
705
- for (const codec of /** @type {("aac" | "opus")[]} */ (Object.keys(AUDIO_CODECS))) {
749
+ export async function chooseAudioCodec(sampleRate, audioQuality, { container = "mp4", codec: requested } = {}) {
750
+ const candidates = requested === undefined ? offeredAudioCodecs(container) : [requested];
751
+ for (const codec of candidates) {
706
752
  const encoderRate = await audioEncoderSampleRate(codec, {
707
753
  sampleRate,
708
754
  numberOfChannels: 2,
@@ -713,7 +759,7 @@ export async function chooseAudioCodec(sampleRate, audioQuality) {
713
759
  }
714
760
  throw new ExportFailureError({
715
761
  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.`,
762
+ 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
763
  origin: "browser",
718
764
  operation: "export",
719
765
  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;
@@ -2,6 +2,7 @@
2
2
  // so encoded video never accumulates in memory. In-memory output is for small outputs sized up
3
3
  // front, never a silent fallback for a large one.
4
4
  import { estimatedOutputBytes, memoryOutputPeakBytes, MEMORY_OUTPUT_COPIES, MEMORY_OUTPUT_MARGIN, WritableFileDestination, } from "alpha2/export-destination";
5
+ import { containerPolicy } from "alpha2/containers";
5
6
  import { ExportFailureError } from "alpha2/export-failure";
6
7
  import { holdShared, whenUnheld } from "./locks.js";
7
8
  /** The most an in-memory output may hold at its peak unless asked otherwise. */
@@ -35,26 +36,30 @@ export function storageSupport() {
35
36
  * counts every write since its last disk scan, so `quota - usage` can be near zero on an empty
36
37
  * disk. A full disk fails at the write (`STORAGE_QUOTA_EXCEEDED`); the estimate is only reported.
37
38
  *
39
+ * `container` (default `mp4`) gives the temporary file its extension and the artifact its MIME
40
+ * type.
38
41
  * Returns `{ mode, destination, storageEstimate, abort, finish }`: `destination` is the sink's,
39
42
  * `abort` discards the file, and `finish(sinkOutput)` turns the finished output into the artifact's
40
43
  * fields.
41
44
  */
42
- export async function openExportOutput({ jobId, name, target, durationSeconds, videoBitrate, audioBitrate, }) {
45
+ export async function openExportOutput({ jobId, name, container = "mp4", target, durationSeconds, videoBitrate, audioBitrate, }) {
43
46
  const estimate = estimatedOutputBytes({
44
47
  durationSeconds,
45
48
  videoBitrate,
46
49
  audioBitrate,
47
50
  });
51
+ const policy = containerPolicy(container);
48
52
  const kind = target?.kind ?? "opfs";
49
53
  if (kind === "file")
50
54
  return openPickedFile(target.handle, estimate);
51
55
  if (kind === "opfs") {
52
- const opened = await openOriginPrivateFile(jobId, name, estimate);
56
+ const opened = await openOriginPrivateFile(jobId, name, policy, estimate);
53
57
  if (opened)
54
58
  return opened;
55
59
  }
56
60
  return openMemory(target?.maxBytes ?? DEFAULT_MEMORY_OUTPUT_LIMIT, estimate, {
57
61
  name,
62
+ mimeType: policy.mimeType,
58
63
  fellBack: kind !== "memory",
59
64
  });
60
65
  }
@@ -79,14 +84,14 @@ async function openPickedFile(handle, estimate) {
79
84
  }),
80
85
  };
81
86
  }
82
- async function openOriginPrivateFile(jobId, name, estimate) {
87
+ async function openOriginPrivateFile(jobId, name, policy, estimate) {
83
88
  const storage = globalThis.navigator?.storage;
84
89
  if (typeof storage?.getDirectory !== "function")
85
90
  return null;
86
91
  let directory;
87
92
  let handle;
88
93
  let writable;
89
- const fileName = `${Date.now()}-${jobId}.mp4`;
94
+ const fileName = `${Date.now()}-${jobId}.${policy.extensions[0]}`;
90
95
  // Held from before the file exists until it is removed, so another page's sweep leaves it alone.
91
96
  const lease = await holdShared(exportLock(fileName));
92
97
  try {
@@ -138,7 +143,7 @@ async function openOriginPrivateFile(jobId, name, estimate) {
138
143
  const file = await handle.getFile();
139
144
  return {
140
145
  kind: "file",
141
- file: new File([file], name, { type: "video/mp4" }),
146
+ file: new File([file], name, { type: policy.mimeType }),
142
147
  name,
143
148
  bytes: output.bytes,
144
149
  release: remove,
@@ -165,7 +170,7 @@ async function reportedStorage(storage, estimate) {
165
170
  belowEstimate: quota - usage < needed,
166
171
  };
167
172
  }
168
- function openMemory(limit, estimate, { name, fellBack }) {
173
+ function openMemory(limit, estimate, { name, mimeType, fellBack }) {
169
174
  const peak = memoryOutputPeakBytes(estimate);
170
175
  if (peak > limit)
171
176
  throw refused("RESOURCE_LIMIT", `${fellBack ? "This browser cannot write the export to disk, and an" : "An"} output of about ${megabytes(estimate)} needs up to ${megabytes(peak)} of memory while it is kept in memory, over the ${megabytes(limit)} limit. Export a shorter range or use the native exporter.`, { requestedBytes: peak, resource: "js" });
@@ -181,7 +186,7 @@ function openMemory(limit, estimate, { name, fellBack }) {
181
186
  abort: async () => { },
182
187
  finish: async (output) => ({
183
188
  kind: "blob",
184
- blob: new Blob([output.buffer], { type: "video/mp4" }),
189
+ blob: new Blob([output.buffer], { type: mimeType }),
185
190
  name,
186
191
  bytes: output.buffer.byteLength,
187
192
  }),