@alpha2-sh/editor 0.4.6 → 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 +396 -312
  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 +47 -28
  12. package/dist/browser/runtime/assets.js +129 -45
  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 +39 -44
  20. package/dist/browser/runtime/engine.js +78 -64
  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 +85 -103
  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 +233 -238
  51. package/dist/browser/worker.d.ts +8 -9
  52. package/dist/browser/worker.js +50 -21
  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 +64 -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 -20
  79. package/dist/react/index.d.ts +5 -6
  80. package/dist/react/index.js +5 -6
  81. package/package.json +4 -4
@@ -1,7 +1,7 @@
1
- // Deterministic export: the engine renders offscreen at export quality on its own exact rational
2
- // frame schedule, so no swapchain race can duplicate a frame and a missing source retries in place.
1
+ // Deterministic export: the engine renders offscreen at export quality on its exact rational frame
2
+ // schedule, so no swapchain race can duplicate a frame and a missing source retries in place.
3
3
  import { ExportFormatError, offeredAudioCodecs, resolveExportFormat, } from "alpha2/containers";
4
- import { audioEncoderSampleRate, canEncodeVideoTrack, MediabunnySink, videoEncoderProfiles, } from "alpha2/mediabunny";
4
+ import { audioEncoderSampleRate, canEncodeInSoftware, canEncodeVideoTrack, MediabunnySink, videoEncoderProfiles, } from "alpha2/mediabunny";
5
5
  import { engineVideoCodec, qualityLevels, resolveAudioBitrate, resolveVideoRateControl, } from "alpha2/rate-control";
6
6
  import { videoFrameFromI420, videoFrameRepackedBytes, } from "alpha2/video-frames";
7
7
  import * as engineBinding from "alpha2/wasm";
@@ -12,8 +12,9 @@ import { storageSupport } from "./output.js";
12
12
  import { estimatedStagingBytes, minimumExportWorkingSet } from "./staging.js";
13
13
  import { DEFAULT_IN_FLIGHT_BYTES } from "./budget.js";
14
14
  import { secondsToTicks } from "alpha2/project";
15
- // Upper bounds on frames in each stage. Within them the byte budget decides: a frame is submitted
16
- // only when its bytes fit.
15
+ import { raceAbort } from "alpha2/abort";
16
+ import { ExportMetrics } from "alpha2/export-metrics";
17
+ // Upper bounds on frames per stage; within them the byte budget decides.
17
18
  const MAX_IN_FLIGHT_READBACKS = 3;
18
19
  const MAX_PENDING_VIDEO_WRITES = 3;
19
20
  /** The video codecs a browser export may request, with display labels. */
@@ -28,8 +29,7 @@ export function qualityLevelNames() {
28
29
  return qualityLevels(engineBinding);
29
30
  }
30
31
  /**
31
- * Resolves the video rate an export at `quality` will encode at, through the engine: the same
32
- * function the native host calls.
32
+ * The video rate an export at `quality` encodes at, resolved by the engine as on the native host.
33
33
  */
34
34
  export function resolvedVideoRate({ codec, width, height, frameRate, quality, }) {
35
35
  return resolveVideoRateControl(engineBinding, {
@@ -43,10 +43,10 @@ export function resolvedVideoRate({ codec, width, height, frameRate, quality, })
43
43
  /** Maps the browser codec names onto the engine's. */
44
44
  export { engineVideoCodec };
45
45
  /**
46
- * Which video codecs this browser encodes for an export at `width`x`height`, `frameRate`, and
47
- * `videoQuality` (default `high`), asked with the configurations that export would open its encoder
48
- * with (for H.264, High, Main or Constrained Baseline): a codec answered `false` is refused when
49
- * such an export starts.
46
+ * Which video codecs this browser encodes for an export at `width`x`height`, `frameRate` and
47
+ * `videoQuality` (default `high`), probed with the configurations the export would open (for H.264:
48
+ * High, Main or Constrained Baseline). A codec answered `false` is refused when such an export
49
+ * starts.
50
50
  */
51
51
  export async function probeEncoders(width, height, { frameRate = { num: 30, den: 1 }, videoQuality = "high" } = {}) {
52
52
  const results = {};
@@ -66,19 +66,20 @@ export async function probeEncoders(width, height, { frameRate = { num: 30, den:
66
66
  return results;
67
67
  }
68
68
  /**
69
- * Renders `range` (seconds) of the loaded project through the engine's export schedule and writes
70
- * it, with its mixed audio, to the output `openOutput` opens. Resolves to the sink's output, the
71
- * opened output (not yet finished), and the export report. Any failure discards the output and is
72
- * rethrown as an `ExportFailureError` with the phase it happened in; a cancellation rethrows the
73
- * abort reason. `createSink(options)` makes the muxer the frames and audio are written to, a
74
- * `MediabunnySink` unless a test supplies another. `openOutput` receives the export's container
75
- * beside the size estimate, so the file is named and typed for it.
69
+ * Renders `range` (seconds) of the loaded project on the engine's export schedule and writes it
70
+ * with its mixed audio to the output `openOutput` opens (given the container and a size estimate).
71
+ * Resolves to the sink's output, the opened output (not yet finished) and the export report. Any
72
+ * failure discards the output and is rethrown as an `ExportFailureError` with its phase; a
73
+ * cancellation rethrows the abort reason. `createSink(options)` makes the muxer (a `MediabunnySink`
74
+ * unless a test supplies another). `videoEncoder: "software"` asks for a software video encoder
75
+ * where available, and `onSoftwareEncoder(available)` reports before rendering whether there is
76
+ * one.
76
77
  */
77
- export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engine, project, doc, library, audioSupplier, range, options, openOutput, onProgress, signal, createSink = (sinkOptions) => new MediabunnySink(sinkOptions), }) {
78
+ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer, engine, project, doc, library, audioSupplier, range, options, openOutput, onProgress, signal, createSink = (sinkOptions) => new MediabunnySink(sinkOptions), videoEncoder = "default", onSoftwareEncoder, }) {
78
79
  const started = performance.now();
79
80
  const diagnosticsBefore = rendererDiagnostics(engine);
80
81
  const transferBefore = sourceTransfer?.();
81
- const metrics = browserExportMetrics();
82
+ const metrics = browserExportMetrics(options.memory?.inFlightBytes ?? DEFAULT_IN_FLIGHT_BYTES);
82
83
  const settings = doc.settings;
83
84
  const rate = exportFrameRate(options.frameRate, settings);
84
85
  const fps = rate.num / rate.den;
@@ -87,8 +88,8 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
87
88
  let frameCount = Math.max(1, Math.round((end - start) * fps));
88
89
  const audio = project ? audibleSources(project, library) : [];
89
90
  const wantsAudio = options.includeAudio !== false && audio.length > 0 && engine != null;
90
- // The container's defaults fill what the options leave out; the audio codec is settled below,
91
- // by what this browser encodes.
91
+ // Container defaults fill what the options omit; the audio codec depends on what this browser
92
+ // encodes.
92
93
  const format = exportFormat(options);
93
94
  const container = format.container;
94
95
  const audioQuality = options.audioQuality ?? "high";
@@ -101,7 +102,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
101
102
  const audioCodec = audioEncoding?.codec;
102
103
  const videoCodec = format.videoCodec;
103
104
  const videoQuality = options.videoQuality ?? "high";
104
- // Resolved by the engine, so `high` costs the same here as on the native path.
105
+ // Resolved by the engine, so `high` costs the same as on the native path.
105
106
  const videoRateControl = resolvedVideoRate({
106
107
  codec: engineVideoCodec(videoCodec),
107
108
  width: settings.width,
@@ -110,16 +111,25 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
110
111
  quality: videoQuality,
111
112
  });
112
113
  const videoEncoding = await requireVideoEncoder(videoCodec, settings, videoRateControl);
114
+ const softwareEncoder = await canEncodeInSoftware(videoCodec, {
115
+ width: settings.width,
116
+ height: settings.height,
117
+ rate: videoRateControl,
118
+ ...(videoEncoding.codecString === undefined
119
+ ? {}
120
+ : { codecString: videoEncoding.codecString }),
121
+ });
122
+ onSoftwareEncoder?.(softwareEncoder);
113
123
  const audioBitrate = audioCodec === undefined
114
124
  ? undefined
115
125
  : resolveAudioBitrate(engineBinding, audioCodec, audioQuality);
116
- // Pipelined steps carry their own phase (`inPhase`); this is only the main loop's.
126
+ // Pipelined steps carry their own phase (`inPhase`); this is the main loop's.
117
127
  const position = { phase: "prepare", frameIndex: undefined };
118
128
  const enter = (phase, frameIndex) => {
119
129
  position.phase = phase;
120
130
  position.frameIndex = frameIndex;
121
131
  };
122
- // Before anything renders: refused here when the destination cannot hold the estimated file.
132
+ // Refused before rendering when the destination cannot hold the estimated file.
123
133
  const output = await openOutput({
124
134
  container,
125
135
  durationSeconds: end - start,
@@ -137,11 +147,14 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
137
147
  audioBitrate,
138
148
  audioSampleRate: audioEncoding?.sampleRate,
139
149
  audioResampler: engineBinding,
140
- // Snapping to the exact rate is what keeps the written track CFR.
150
+ // Snapping to the exact rate keeps the written track CFR.
141
151
  frameRate: rate,
142
152
  destination: output.destination,
153
+ ...(videoEncoder === "software" && softwareEncoder
154
+ ? { videoHardwareAcceleration: "prefer-software" }
155
+ : {}),
143
156
  });
144
- // Audio is written a window ahead of the video so the file comes out interleaved.
157
+ // Audio is written a window ahead of video so the file comes out interleaved.
145
158
  let writeAudioThrough = async () => { };
146
159
  // Staged readbacks and queued encoder frames share one byte budget that must fit one of each.
147
160
  const budget = options.memory?.inFlightBytes ?? DEFAULT_IN_FLIGHT_BYTES;
@@ -171,7 +184,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
171
184
  try {
172
185
  const videoShare = FRAMES_SHARE;
173
186
  engine.beginExport(BigInt(secondsToTicks(start)), BigInt(secondsToTicks(end)), rate.num, rate.den, engineVideoCodec(videoCodec));
174
- // The engine's schedule, not the request's, decides the frames and the audio start.
187
+ // The engine's schedule, not the request, decides the frames and the audio start.
175
188
  frameCount = JSON.parse(engine.exportProgress()).total;
176
189
  if (wantsAudio)
177
190
  writeAudioThrough = exportAudioWriter({
@@ -186,6 +199,8 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
186
199
  const pendingReadbacks = [];
187
200
  const pendingWrites = [];
188
201
  let writeTail = Promise.resolve();
202
+ // A cancel ends a wait at once, whatever the awaited work does.
203
+ const cancellable = (work) => raceAbort(work, signal, undefined, abortReason);
189
204
  let pendingReadbackBytes = 0;
190
205
  let pendingEncodeBytes = 0;
191
206
  let produced = 0;
@@ -194,7 +209,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
194
209
  let waits = 0;
195
210
  let exportComplete = false;
196
211
  // The first scheduled frame starts at or before the range start, so it is the time origin;
197
- // the raw range start would make the first sample's timestamp negative.
212
+ // the raw range start would give the first sample a negative timestamp.
198
213
  let originTicks = null;
199
214
  // Idle renderer memory is released once per pressure episode, which ends when all drains.
200
215
  let pressured = false;
@@ -225,7 +240,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
225
240
  waits = ticket.timeTicks === waitingAt ? waits + 1 : 0;
226
241
  waitingAt = ticket.timeTicks;
227
242
  if (waits >= 4) {
228
- // Like the SDK's export runner: a source not uploaded will not upload on retry.
243
+ // As in the SDK's export runner: a source not uploaded will not upload on retry.
229
244
  throw new ExportFailureError({
230
245
  code: "RESOURCE_LIMIT",
231
246
  message: `export stalled at ${(Number(ticket.timeTicks) / 120_000).toFixed(3)}s waiting for ${ticket.missingSources.join(", ")} after ${waits} refills: the supply does not upload them`,
@@ -246,7 +261,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
246
261
  const supplyStarted = performance.now();
247
262
  enter("decode", produced + pendingReadbacks.length);
248
263
  await supplyFrame(Number(ticket.timeTicks) / 120_000, ticket.missingSources);
249
- metrics.sourceConvertUploadMs += performance.now() - supplyStarted;
264
+ metrics.sourceSupplyMs += performance.now() - supplyStarted;
250
265
  continue;
251
266
  }
252
267
  waitingAt = null;
@@ -264,14 +279,14 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
264
279
  readback,
265
280
  retainedBytes: ticket.retainedBytes,
266
281
  });
267
- metrics.maxInFlightReadbacks = Math.max(metrics.maxInFlightReadbacks, pendingReadbacks.length);
282
+ metrics.peakInFlightReadbacks = Math.max(metrics.peakInFlightReadbacks, pendingReadbacks.length);
268
283
  if (pendingWrites.length > 0)
269
284
  metrics.pipelineOverlapFrames += 1;
270
285
  }
271
286
  if (pendingReadbacks.length === 0) {
272
287
  if (exportComplete)
273
288
  continue;
274
- // Only encoder frames hold the budget: wait for the oldest to be encoded.
289
+ // Only encoder frames hold the budget, so wait for the oldest to be encoded.
275
290
  const oldest = pendingWrites.shift();
276
291
  if (oldest === undefined)
277
292
  throw new ExportFailureError({
@@ -285,18 +300,15 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
285
300
  resource: "unknown",
286
301
  requestedBytes: frameCost,
287
302
  });
288
- await oldest.write;
303
+ await cancellable(oldest.write);
289
304
  pendingEncodeBytes -= oldest.bytes;
290
305
  continue;
291
306
  }
292
- const pendingDepth = pendingReadbacks.length + pendingWrites.length;
293
- metrics.maxPendingMediaEvents = Math.max(metrics.maxPendingMediaEvents, pendingDepth);
294
- metrics.pendingDepthTotal += pendingDepth;
295
- metrics.pendingDepthSamples += 1;
307
+ metrics.samplePending(pendingReadbacks.length + pendingWrites.length);
296
308
  const pendingReadback = pendingReadbacks.shift();
297
309
  const readbackWaitStarted = performance.now();
298
310
  enter("readback", produced);
299
- const step = await pendingReadback.readback;
311
+ const step = await cancellable(pendingReadback.readback);
300
312
  metrics.readbackWaitMs += performance.now() - readbackWaitStarted;
301
313
  pendingReadbackBytes -= pendingReadback.retainedBytes;
302
314
  metrics.outputReadbackBytes += pendingReadback.retainedBytes;
@@ -318,12 +330,12 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
318
330
  metrics.encodeBackpressureCount += 1;
319
331
  const write = writeTail.then(async () => {
320
332
  metrics.encodeQueueWaitMs += performance.now() - encodeQueued;
321
- const encodeStarted = performance.now();
333
+ const writeStarted = performance.now();
322
334
  try {
323
335
  await inPhase("encode", Number(output.index), () => sink.writeVideo(output));
324
336
  }
325
337
  finally {
326
- metrics.videoEncodeMs += performance.now() - encodeStarted;
338
+ metrics.videoWriteWaitMs += performance.now() - writeStarted;
327
339
  }
328
340
  }, (error) => {
329
341
  frame.close();
@@ -339,7 +351,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
339
351
  while (pendingWrites.length >= MAX_PENDING_VIDEO_WRITES ||
340
352
  (pendingWrites.length > 1 && inFlight() > budget)) {
341
353
  const pendingWrite = pendingWrites.shift();
342
- await pendingWrite.write;
354
+ await cancellable(pendingWrite.write);
343
355
  pendingEncodeBytes -= pendingWrite.bytes;
344
356
  }
345
357
  produced += 1;
@@ -351,12 +363,16 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
351
363
  frameCount,
352
364
  });
353
365
  }
354
- await writeTail;
366
+ await cancellable(writeTail);
355
367
  pendingWrites.length = 0;
356
368
  }
357
369
  finally {
358
- await Promise.allSettled(pendingReadbacks.map(({ readback }) => readback));
359
- await Promise.allSettled(pendingWrites.map(({ write }) => write));
370
+ // A cancel waits for nothing that may never settle (a readback on a stopped GPU, a write the
371
+ // encoder holds).
372
+ if (!signal?.aborted) {
373
+ await Promise.allSettled(pendingReadbacks.map(({ readback }) => readback));
374
+ await Promise.allSettled(pendingWrites.map(({ write }) => write));
375
+ }
360
376
  engine.endExport();
361
377
  }
362
378
  await writeAudioThrough(Infinity);
@@ -364,7 +380,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
364
380
  onProgress?.({ phase: "finalizing", ratio: FRAMES_SHARE });
365
381
  const finishStarted = performance.now();
366
382
  await sink.finish();
367
- metrics.muxFinishMs = performance.now() - finishStarted;
383
+ metrics.finishMs = performance.now() - finishStarted;
368
384
  const written = sink.output;
369
385
  if (written === null || sink.bytesWritten === 0)
370
386
  throw new Error("the encoder returned an empty result");
@@ -376,7 +392,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
376
392
  peakQueuedBytes: destinationStats?.peakQueuedBytes ?? null,
377
393
  maxQueuedBytes: destinationStats?.maxQueuedBytes ?? null,
378
394
  storage: storageSupport(),
379
- // A report, not a check (`openExportOutput`).
395
+ // Informational; the check is in `openExportOutput`.
380
396
  storageEstimate: output.storageEstimate ?? null,
381
397
  };
382
398
  const renderMs = performance.now() - started;
@@ -399,7 +415,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
399
415
  audio: wantsAudio,
400
416
  container,
401
417
  videoCodec,
402
- // Named like the native host's result for native-versus-Wasm comparison.
418
+ // Named like the native host's result for comparison.
403
419
  videoRateControl: {
404
420
  bitrate: videoRateControl.bitrate,
405
421
  mode: videoRateControl.bitrateMode,
@@ -410,8 +426,13 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
410
426
  // `quantizer` when the encoder accepted constant-quantizer encoding, else the bitrate path.
411
427
  appliedVideoRateControl: sink.appliedVideoRateControl ?? null,
412
428
  videoLatencyMode: sink.videoLatencyMode ?? null,
413
- // The codec string the encoder opened (for H.264, its profile and level), and the H.264
414
- // profiles this browser refused before it: a lower profile of the same codec, not a switch.
429
+ // How latency mode and AAC priming were measured, and which video encoder was requested. A
430
+ // timed-out probe is reported, not kept.
431
+ videoLatencyProbe: sink.videoLatencyProbe ?? null,
432
+ aacPrimingProbe: sink.aacPrimingProbe ?? null,
433
+ videoEncoderAcceleration: sink.videoEncoderAcceleration ?? null,
434
+ // The codec string the encoder opened (H.264 profile and level), and H.264 profiles this
435
+ // browser refused first (a lower profile of the same codec, not a codec switch).
415
436
  videoCodecString: sink.videoCodecString ?? videoEncoding.codecString ?? null,
416
437
  videoCodecProfile: videoEncoding.profile ?? null,
417
438
  videoEncoderFallbacks: videoEncoding.fallbacks,
@@ -423,20 +444,20 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
423
444
  level: typeof audioQuality === "string" ? audioQuality : null,
424
445
  },
425
446
  fps: produced / Math.max(renderMs / 1_000, Number.EPSILON),
426
- // A retry renders from the first frame: nothing of a failed attempt is kept.
447
+ // A retry renders from the first frame; nothing of a failed attempt is kept.
427
448
  resume: {
428
449
  status: "unavailable",
429
450
  reason: "browser exports keep no frames between attempts; a retry renders from the first frame",
430
451
  },
431
- performance: finishBrowserExportMetrics(metrics, diagnosticsBefore, rendererDiagnostics(engine)),
452
+ performance: finishBrowserExportMetrics(metrics, sink.videoEncodeLatencyMs, diagnosticsBefore, rendererDiagnostics(engine)),
432
453
  };
433
- // One JSON object, so DevTools users can copy it without expanding a live console object.
454
+ // One JSON string so DevTools users can copy it without expanding a live object.
434
455
  console.log(JSON.stringify(result));
435
456
  throwIfAborted(signal);
436
457
  return { written, output, result };
437
458
  }
438
459
  catch (error) {
439
- // Discard first, so a muxer that closes its stream on cancel cannot commit a partial file.
460
+ // Discard first so a muxer that closes its stream on cancel cannot commit a partial file.
440
461
  const discarded = output.abort(error).then(() => null, (abortError) => abortError);
441
462
  if (signal?.aborted) {
442
463
  await discarded;
@@ -471,7 +492,7 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
471
492
  peakReadbackBytes: metrics.peakReadbackBytes,
472
493
  peakEncodeQueueBytes: metrics.peakEncodeQueueBytes,
473
494
  stagingBytesPerFrame: metrics.stagingBytesPerFrame,
474
- maxInFlightReadbacks: metrics.maxInFlightReadbacks,
495
+ peakInFlightReadbacks: metrics.peakInFlightReadbacks,
475
496
  jsHeap: jsHeap(),
476
497
  },
477
498
  ...deviceDiagnostics(engine),
@@ -498,15 +519,11 @@ export async function exportTimeline({ supplyFrame, renderFrame, sourceTransfer,
498
519
  throw new ExportFailureError(failure, { cause: error });
499
520
  }
500
521
  }
501
- /** How far the audio is written ahead of the video. */
502
522
  const AUDIO_LEAD_SECONDS = 0.25;
503
- /** Share of the job the frames stand for; finalizing the file is the rest. */
523
+ /** Share of the job progress the frames account for; finalizing is the rest. */
504
524
  const FRAMES_SHARE = 0.97;
505
525
  const errorPhases = new WeakMap();
506
- /**
507
- * Runs `step`, marking an error it throws with the phase and frame it came from, unless an earlier
508
- * step already marked it.
509
- */
526
+ /** Runs `step`, tagging a thrown error with its phase and frame unless already tagged. */
510
527
  async function inPhase(phase, frameIndex, step) {
511
528
  try {
512
529
  return await step();
@@ -550,10 +567,7 @@ function rendererBackend(engine) {
550
567
  return "browser-webgl";
551
568
  return "unknown";
552
569
  }
553
- /**
554
- * Chrome's JS heap figures, where it reports them; they do not include ArrayBuffers, wasm, or GPU
555
- * memory.
556
- */
570
+ /** Chrome's JS heap figures where reported; they exclude ArrayBuffers, wasm and GPU memory. */
557
571
  function jsHeap() {
558
572
  const memory = globalThis.performance?.memory;
559
573
  return memory
@@ -573,81 +587,43 @@ function browserEnvironment() {
573
587
  webgpu: typeof navigator?.gpu === "object" && navigator.gpu !== null,
574
588
  };
575
589
  }
576
- function browserExportMetrics() {
577
- return {
578
- pipelineEnabled: true,
579
- sourceConvertUploadMs: 0,
580
- frameSubmitMs: 0,
581
- readbackMapLatencyMs: 0,
582
- readbackWaitMs: 0,
583
- encodeQueueWaitMs: 0,
584
- videoEncodeMs: 0,
590
+ /**
591
+ * The shared browser export metrics (`ExportMetrics` in `alpha2/export-metrics`) plus the editor's
592
+ * own: audio, source transfer, memory and output.
593
+ */
594
+ function browserExportMetrics(inFlightByteBudget) {
595
+ return Object.assign(new ExportMetrics({
596
+ maxInFlightReadbacks: MAX_IN_FLIGHT_READBACKS,
597
+ maxPendingVideoWrites: MAX_PENDING_VIDEO_WRITES,
598
+ inFlightByteBudget,
599
+ }), {
585
600
  audioDecodeMs: 0,
586
601
  audioMixMs: 0,
587
602
  audioEncodeMs: 0,
588
- muxFinishMs: 0,
589
- stagingBytesPerFrame: 0,
590
603
  packedBytesPerFrame: 0,
591
- peakReadbackBytes: 0,
592
- outputReadbackBytes: 0,
593
- outputRepackBytes: 0,
594
604
  sourcePlanarCopyFrames: 0,
595
605
  sourcePlanarCopyBytes: 0,
596
606
  sourceUnreadableFrames: 0,
597
607
  sourceReadbackRetries: 0,
598
608
  sourceRedecodedFrames: 0,
599
- peakEncodeQueueBytes: 0,
600
- maxPendingMediaEvents: 0,
601
- pendingDepthTotal: 0,
602
- pendingDepthSamples: 0,
603
- maxInFlightReadbacks: 0,
604
- maxEncodeQueueEvents: 0,
605
- encodeBackpressureCount: 0,
606
- pipelineOverlapFrames: 0,
607
609
  audioBlocksInterleaved: 0,
608
610
  output: null,
609
611
  memory: null,
610
- };
612
+ });
611
613
  }
612
- function finishBrowserExportMetrics(metrics, before, after) {
614
+ function finishBrowserExportMetrics(metrics, encodeLatency, before, after) {
613
615
  const result = {
614
- pipelineEnabled: metrics.pipelineEnabled,
615
- sourceConvertUploadMs: metrics.sourceConvertUploadMs,
616
- frameSubmitMs: metrics.frameSubmitMs,
617
- readbackMapLatencyMs: metrics.readbackMapLatencyMs,
618
- readbackWaitMs: metrics.readbackWaitMs,
619
- readbackBlockingMs: metrics.readbackWaitMs,
620
- encodeQueueWaitMs: metrics.encodeQueueWaitMs,
621
- videoEncodeMs: metrics.videoEncodeMs,
616
+ ...metrics.finish(encodeLatency),
622
617
  audioDecodeMs: metrics.audioDecodeMs,
623
618
  audioMixMs: metrics.audioMixMs,
624
619
  audioEncodeMs: metrics.audioEncodeMs,
625
- muxFinishMs: metrics.muxFinishMs,
626
- inFlightDepth: MAX_IN_FLIGHT_READBACKS,
627
- encodeChannelDepth: MAX_PENDING_VIDEO_WRITES,
628
- stagingBytesPerFrame: metrics.stagingBytesPerFrame,
629
620
  packedBytesPerFrame: metrics.packedBytesPerFrame,
630
- peakReadbackBytes: metrics.peakReadbackBytes,
631
- // Mapped output readbacks plus HDR source frames copied out planar for the tone map.
632
- outputReadbackBytes: metrics.outputReadbackBytes,
633
- // Copies made to pack planes tight where VideoFrame ignores `layout`; 0 elsewhere.
634
- outputRepackBytes: metrics.outputRepackBytes,
635
621
  sourcePlanarCopyFrames: metrics.sourcePlanarCopyFrames,
636
622
  sourcePlanarCopyBytes: metrics.sourcePlanarCopyBytes,
637
- // Source frames the browser could not read back, the reads repeated, and the frames decoded
638
- // again in software for it.
623
+ // Source frames the browser could not read back, repeated reads, and software re-decodes.
639
624
  sourceUnreadableFrames: metrics.sourceUnreadableFrames,
640
625
  sourceReadbackRetries: metrics.sourceReadbackRetries,
641
626
  sourceRedecodedFrames: metrics.sourceRedecodedFrames,
642
- peakEncodeQueueBytes: metrics.peakEncodeQueueBytes,
643
- maxPendingMediaEvents: metrics.maxPendingMediaEvents,
644
- averagePendingMediaEvents: metrics.pendingDepthSamples === 0
645
- ? 0
646
- : metrics.pendingDepthTotal / metrics.pendingDepthSamples,
647
- maxInFlightReadbacks: metrics.maxInFlightReadbacks,
648
- maxEncodeQueueEvents: metrics.maxEncodeQueueEvents,
649
- encodeBackpressureCount: metrics.encodeBackpressureCount,
650
- pipelineOverlapFrames: metrics.pipelineOverlapFrames,
651
627
  audioBlocksInterleaved: metrics.audioBlocksInterleaved,
652
628
  memory: metrics.memory,
653
629
  output: metrics.output,
@@ -721,16 +697,16 @@ async function i420VideoFrame(step, timestamp, duration) {
721
697
  timestamp,
722
698
  duration,
723
699
  layout: [...step.layout],
724
- // Without it the browser tags the stream with its own default for a buffer-backed I420 frame.
700
+ // Without it the browser tags a buffer-backed I420 frame with its own default.
725
701
  colorSpace: step.colorSpace,
726
702
  });
727
703
  }
728
- /** The audio codecs an export may write, with their names. */
729
704
  const AUDIO_CODECS = { aac: "AAC", opus: "Opus" };
730
705
  /**
731
- * The export's container and video codec, with the container's defaults for what `options` leave
732
- * out: `mp4` and its `avc`. A container that does not offer a requested codec (`webm` with `avc`,
733
- * `mov` with `opus`) is refused before anything renders, as `INVALID_INPUT`.
706
+ * The export's container and video codec, defaulting to `mp4` and its `avc`. A container that does
707
+ * not offer a requested codec (`webm` with `avc`, `mov` with `opus`) is refused before rendering,
708
+ * as
709
+ * `INVALID_INPUT`.
734
710
  */
735
711
  export function exportFormat(options) {
736
712
  try {
@@ -759,14 +735,12 @@ export function exportFormat(options) {
759
735
  }
760
736
  }
761
737
  /**
762
- * The audio codec this browser encodes the export's audio with, and the rate its encoder is given:
763
- * `codec` when one is asked for, else the first of the container's codecs this browser encodes, in
764
- * the container's order (AAC, then Opus, in MP4 and MKV; AAC only in MOV; Opus only in WebM), each
765
- * at the project rate where the encoder takes it and otherwise at the rate a native host would
766
- * convert to (`audioEncoderSampleRate` in `alpha2/mediabunny`), so every project rate exports. A
767
- * browser that encodes none of them at any rate (Safari before 26 has a VideoEncoder but no
768
- * AudioEncoder; Firefox on Linux has no AAC encoder for a MOV) is refused here, before anything
769
- * renders, as `INVALID_INPUT`: a retry would meet the same browser.
738
+ * The audio codec and encoder sample rate for the export: `codec` when given, else the first of the
739
+ * container's codecs this browser encodes (AAC then Opus in MP4 and MKV, AAC in MOV, Opus in WebM).
740
+ * Each runs at the project rate where the encoder accepts it, else at the rate a native host would
741
+ * convert to (`audioEncoderSampleRate`), so every project rate exports. A browser that encodes none
742
+ * of them (Safari before 26 has no AudioEncoder; Firefox on Linux has no AAC encoder for MOV) is
743
+ * refused before rendering as `INVALID_INPUT`, since a retry would meet the same browser.
770
744
  *
771
745
  * @returns {Promise<{ codec: "aac" | "opus", sampleRate: number }>}
772
746
  */
@@ -792,11 +766,9 @@ export async function chooseAudioCodec(sampleRate, audioQuality, { container = "
792
766
  });
793
767
  }
794
768
  /**
795
- * How this browser encodes the export's video (`canEncodeVideoTrack` in `alpha2/mediabunny`: for
796
- * H.264, the first of High, Main and Constrained Baseline it encodes). Refuses an export whose
797
- * video codec this browser does not encode at the export's size and rate in any of them, before
798
- * anything renders, as `INVALID_INPUT`: WebCodecs leaves the codecs to the browser, and a retry
799
- * would meet the same browser.
769
+ * How this browser encodes the export's video (for H.264, the first of High, Main and Constrained
770
+ * Baseline it supports). Refuses before rendering, as `INVALID_INPUT`, when it cannot encode the
771
+ * codec at the export's size and rate, since a retry would meet the same browser.
800
772
  */
801
773
  export async function requireVideoEncoder(codec, { width, height }, rate) {
802
774
  const encoding = await canEncodeVideoTrack(codec, { width, height, rate });
@@ -817,13 +789,15 @@ export async function requireVideoEncoder(codec, { width, height }, rate) {
817
789
  resource: "unknown",
818
790
  });
819
791
  }
820
- /** The exact rational export rate: the override as given, else the project's own. */
821
792
  function exportFrameRate(override, settings) {
822
793
  return override
823
794
  ? { num: override.num, den: override.den }
824
795
  : { num: settings.fpsNum, den: settings.fpsDen };
825
796
  }
797
+ function abortReason(signal) {
798
+ return signal.reason ?? new DOMException("Export cancelled", "AbortError");
799
+ }
826
800
  function throwIfAborted(signal) {
827
801
  if (signal?.aborted)
828
- throw signal.reason ?? new DOMException("Export cancelled", "AbortError");
802
+ throw abortReason(signal);
829
803
  }