alpha2 0.4.6 → 0.5.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.
Files changed (123) hide show
  1. package/README.md +5 -4
  2. package/THIRD_PARTY_NOTICES.md +4 -0
  3. package/dist/abort.d.ts +12 -0
  4. package/dist/abort.js +48 -0
  5. package/dist/active-clock.d.ts +35 -0
  6. package/dist/active-clock.js +99 -0
  7. package/dist/assets.d.ts +51 -22
  8. package/dist/assets.js +8 -12
  9. package/dist/audio-layout.d.ts +52 -74
  10. package/dist/audio-layout.js +114 -148
  11. package/dist/audio-timeline.d.ts +89 -117
  12. package/dist/audio-timeline.js +102 -118
  13. package/dist/audio-worker.d.ts +12 -21
  14. package/dist/audio-worker.js +8 -13
  15. package/dist/audio-worklet-processor.js +45 -58
  16. package/dist/audio-worklet.d.ts +45 -76
  17. package/dist/audio-worklet.js +44 -79
  18. package/dist/audio.d.ts +15 -23
  19. package/dist/audio.js +9 -13
  20. package/dist/builder.d.ts +45 -63
  21. package/dist/builder.js +49 -45
  22. package/dist/capabilities.d.ts +99 -16
  23. package/dist/capabilities.js +2 -2
  24. package/dist/captions.d.ts +45 -22
  25. package/dist/captions.js +60 -15
  26. package/dist/chroma-siting.d.ts +24 -41
  27. package/dist/chroma-siting.js +38 -71
  28. package/dist/containers.d.ts +41 -30
  29. package/dist/containers.js +59 -27
  30. package/dist/decoder-fallback.d.ts +13 -0
  31. package/dist/decoder-fallback.js +38 -0
  32. package/dist/decoder-order.d.ts +24 -39
  33. package/dist/decoder-order.js +28 -42
  34. package/dist/edit.d.ts +77 -154
  35. package/dist/edit.js +98 -180
  36. package/dist/effects.d.ts +125 -176
  37. package/dist/effects.js +7 -9
  38. package/dist/export-destination.d.ts +25 -41
  39. package/dist/export-destination.js +20 -32
  40. package/dist/export-failure.d.ts +34 -59
  41. package/dist/export-failure.js +54 -48
  42. package/dist/export-metrics.d.ts +116 -0
  43. package/dist/export-metrics.js +74 -0
  44. package/dist/export-retry.d.ts +46 -29
  45. package/dist/export-retry.js +86 -51
  46. package/dist/exporter.d.ts +67 -116
  47. package/dist/exporter.js +133 -133
  48. package/dist/extensions.d.ts +69 -115
  49. package/dist/extensions.js +55 -82
  50. package/dist/frame-intake.d.ts +92 -0
  51. package/dist/frame-intake.js +114 -0
  52. package/dist/frame-supply.d.ts +96 -162
  53. package/dist/frame-supply.js +181 -171
  54. package/dist/frames.d.ts +23 -0
  55. package/dist/frames.js +34 -0
  56. package/dist/generated/project-schema.d.ts +712 -485
  57. package/dist/generated/project-schema.js +55 -2
  58. package/dist/generated/project-shape.js +276 -16
  59. package/dist/geometry.d.ts +28 -34
  60. package/dist/geometry.js +18 -23
  61. package/dist/gpu-recovery.d.ts +92 -0
  62. package/dist/gpu-recovery.js +135 -0
  63. package/dist/hdr-frames.d.ts +82 -67
  64. package/dist/hdr-frames.js +112 -49
  65. package/dist/index.d.ts +6 -0
  66. package/dist/index.js +6 -0
  67. package/dist/json-text.d.ts +13 -23
  68. package/dist/json-text.js +10 -20
  69. package/dist/layout-values.d.ts +14 -22
  70. package/dist/layout-values.js +18 -21
  71. package/dist/layout.d.ts +48 -63
  72. package/dist/layout.js +37 -37
  73. package/dist/loudness.d.ts +27 -32
  74. package/dist/loudness.js +19 -23
  75. package/dist/media.d.ts +85 -237
  76. package/dist/media.js +133 -287
  77. package/dist/mediabunny.d.ts +178 -246
  78. package/dist/mediabunny.js +781 -583
  79. package/dist/paint.d.ts +23 -0
  80. package/dist/paint.js +37 -0
  81. package/dist/physical-frames.d.ts +5 -17
  82. package/dist/physical-frames.js +4 -11
  83. package/dist/player.d.ts +56 -47
  84. package/dist/player.js +155 -40
  85. package/dist/presented-frames.d.ts +2 -7
  86. package/dist/presented-frames.js +3 -8
  87. package/dist/project.d.ts +74 -118
  88. package/dist/project.js +384 -445
  89. package/dist/rate-control.d.ts +9 -23
  90. package/dist/rate-control.js +7 -18
  91. package/dist/renderer-choice.d.ts +41 -0
  92. package/dist/renderer-choice.js +82 -0
  93. package/dist/repacked-bytes.d.ts +0 -2
  94. package/dist/repacked-bytes.js +2 -5
  95. package/dist/robustness.d.ts +25 -37
  96. package/dist/robustness.js +71 -54
  97. package/dist/sha256.d.ts +5 -13
  98. package/dist/sha256.js +9 -24
  99. package/dist/text.d.ts +97 -71
  100. package/dist/text.js +33 -70
  101. package/dist/video-frames.d.ts +7 -25
  102. package/dist/video-frames.js +12 -29
  103. package/dist/waveform.d.ts +5 -11
  104. package/dist/waveform.js +4 -9
  105. package/dist/worker-error.d.ts +5 -20
  106. package/dist/worker-error.js +8 -25
  107. package/dist/worker.d.ts +82 -95
  108. package/dist/worker.js +235 -143
  109. package/package.json +26 -2
  110. package/wasm/alpha2_audio_worklet.wasm +0 -0
  111. package/wasm/alpha2_extensions.d.ts +26 -47
  112. package/wasm/alpha2_extensions.js +26 -47
  113. package/wasm/alpha2_extensions_bg.wasm +0 -0
  114. package/wasm/alpha2_wasm.d.ts +501 -587
  115. package/wasm/alpha2_wasm.js +661 -616
  116. package/wasm/alpha2_wasm_bg.wasm +0 -0
  117. package/wasm/alpha2_wasm_bg.wasm.d.ts +22 -12
  118. package/wasm/rust-crate-licenses.md +2 -2
  119. package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline1.js +1 -0
  120. package/wasm/snippets/alpha2-wasm-070d94113471ef0a/inline2.js +82 -0
  121. package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
  122. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline0.js +0 -0
  123. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline3.js +0 -0
package/dist/exporter.js CHANGED
@@ -1,13 +1,16 @@
1
+ import { raceAbort } from "./abort.js";
1
2
  import { videoFrameRepackedBytes } from "./video-frames.js";
2
3
  import { ExportFailureError, recordCleanupFailure } from "./export-failure.js";
4
+ import { softwareDecodeRequest } from "./frame-intake.js";
5
+ import { ExportMetrics, } from "./export-metrics.js";
3
6
  const TICKS_PER_SECOND = 120000n;
4
7
  const DEFAULT_MAX_IN_FLIGHT_VIDEO_FRAMES = 3;
5
8
  const DEFAULT_MAX_IN_FLIGHT_VIDEO_BYTES = 128 * 1024 * 1024;
6
- // Refills one frame may take before a further `waiting` answer fails the export.
9
+ // Refills allowed per frame before another `waiting` answer fails the export.
7
10
  const MAX_REFILLS_PER_FRAME = 4;
8
11
  /**
9
12
  * An export stopped by cancellation (`cancelled`), a lost GPU device (`device-lost`) or a sink that
10
- * threw a non-`Error` value (`adapter`). Each may be restarted cleanly.
13
+ * threw a non-`Error` value (`adapter`). The export can be restarted cleanly.
11
14
  */
12
15
  export class ExportAbortedError extends Error {
13
16
  code;
@@ -18,8 +21,8 @@ export class ExportAbortedError extends Error {
18
21
  }
19
22
  }
20
23
  /**
21
- * Exact, retryable browser export scheduler. It walks the frame grid of `rate` over a timeline
22
- * range; encoding and muxing stay host-owned.
24
+ * Browser export scheduler that walks the frame grid of `rate` over a timeline range. Encoding and
25
+ * muxing stay with the host.
23
26
  */
24
27
  export class Alpha2Exporter {
25
28
  #backend;
@@ -55,9 +58,8 @@ export class Alpha2Exporter {
55
58
  this.#totalFrames = this.#endFrame - this.#nextFrame;
56
59
  }
57
60
  /**
58
- * The timeline range this export covers: the requested range widened to the frame grid,
59
- * `[floor(start), ceil(end))`. Its start is the output's zero, which is where a host starts the
60
- * export's audio.
61
+ * The requested range widened to the frame grid, `[floor(start), ceil(end))`. Its start is
62
+ * output time zero, where the host should also start the audio.
61
63
  */
62
64
  get effectiveRange() {
63
65
  return {
@@ -66,10 +68,9 @@ export class Alpha2Exporter {
66
68
  };
67
69
  }
68
70
  /**
69
- * The project-rate samples this export's audio covers at `sampleRate`: from the sample nearest
70
- * {@link effectiveRange}'s start to the one nearest its end, as the engine's
71
- * `export_audio_window` places audio on every host. `startSample` is the mix position written at
72
- * the output's zero.
71
+ * The audio samples this export covers at `sampleRate`, from the sample nearest
72
+ * {@link effectiveRange}'s start to the one nearest its end, matching the engine's
73
+ * `export_audio_window`. `startSample` is the mix position at output time zero.
73
74
  *
74
75
  * @throws RangeError when `sampleRate` is not a positive safe integer.
75
76
  */
@@ -83,7 +84,7 @@ export class Alpha2Exporter {
83
84
  frames: nearestSample(endTicks, rate) - startSample,
84
85
  };
85
86
  }
86
- /** Frames whose readback has resolved, out of the frames the range holds. */
87
+ /** Frames whose readback has resolved, out of the total. */
87
88
  get progress() {
88
89
  return {
89
90
  completed: this.#completed,
@@ -91,12 +92,11 @@ export class Alpha2Exporter {
91
92
  };
92
93
  }
93
94
  /**
94
- * Submits the next frame. Calls are serialized, so frames are submitted in order even when
95
- * several calls are pending. A `waiting` answer leaves the frame unsubmitted; call again after
96
- * uploading the missing sources.
95
+ * Submits the next frame. Calls are serialized. A `waiting` result leaves the frame unsubmitted;
96
+ * call again after uploading the missing sources.
97
97
  *
98
98
  * Rejects with an {@link ExportAbortedError} coded `device-lost` (after aborting the backend)
99
- * when the GPU device is lost, and with whatever the backend rejects with.
99
+ * when the GPU device is lost, or with the backend's error.
100
100
  */
101
101
  next() {
102
102
  const next = this.#beginTail.then(() => this.#beginNext());
@@ -141,30 +141,28 @@ export class Alpha2Exporter {
141
141
  }
142
142
  }
143
143
  /**
144
- * Runs an exporter into any WebCodecs/mediabunny-compatible public sink, keeping at most
145
- * `maxInFlightFrames` frames and `maxInFlightBytes` readback bytes in flight. `refill` uploads the
146
- * source frames a frame is waiting for, which its `missingFrames` name with the source time to
147
- * decode, before the same frame is asked for again; a frame still waiting after four refills fails
148
- * the export with an `ExportFailureError` coded `RESOURCE_LIMIT` at step `upload`, stage
149
- * `sources-not-held`, naming the sources: the refill does not upload them. A frame whose sources
150
- * outgrow the binding's uploaded-frame budget fails sooner: the binding refuses the upload that
151
- * would overflow it (`RESOURCE_LIMIT`, stage `working-set-over-budget`), and `refill` rejects with
152
- * that. Neither is retried by `decideRetry`.
144
+ * Runs an exporter into a WebCodecs or mediabunny-compatible sink, keeping at most
145
+ * `maxInFlightFrames` frames and `maxInFlightBytes` readback bytes in flight.
153
146
  *
154
- * `refill` must deliver through a decoder refill of the export's own, not the preview's: a
155
- * `DecoderRefillCoordinator` made for the export, whose `deliver` uploads to the backend the
156
- * export renders with and whose requests carry generation 0 (an {@link ExportWaiting} has none).
157
- * A coordinator resolves a request from a generation older than its own without delivering it,
158
- * so the preview's, past generation 0 after its first seek, would drop the export's refills
159
- * silently and the frame would fail at `sources-not-held`.
147
+ * `refill` uploads the source frames named in `missingFrames` before the frame is requested again.
148
+ * A frame still waiting after four refills fails with `RESOURCE_LIMIT` at stage
149
+ * `sources-not-held`; an upload over the binding's frame budget fails with `RESOURCE_LIMIT` at
150
+ * stage `working-set-over-budget`. `decideRetry` retries neither.
160
151
  *
161
- * Resolves after `sink.finish()` with timing and memory metrics; a `signal` that aborts before
162
- * then, during `finish()` included, rejects instead. On any failure it closes the
163
- * frames it still holds, waits for pending writes, calls `sink.abort` once and rejects with the
164
- * failure: an {@link ExportAbortedError} for cancellation or a lost device, an
165
- * `ExportFailureError` coded `RESOURCE_LIMIT` when one frame exceeds `maxInFlightBytes`, a
166
- * `RangeError` for an invalid option, or the error the backend, `refill` or the sink raised. An
167
- * `abort` that throws does not replace that failure ({@link recordCleanupFailure}).
152
+ * A refill rejected with `SOFTWARE_DECODE_REQUIRED` is retried once with `decode: "software"` on
153
+ * that `missingFrames` entry, and a `non-planar` source is requested in software from then on.
154
+ * `refill` must honor `decode`.
155
+ *
156
+ * `refill` must use a `DecoderRefillCoordinator` created for this export (requests at generation
157
+ * 0), not the preview's. The preview's coordinator moves past generation 0 after its first seek
158
+ * and would silently drop the export's requests.
159
+ *
160
+ * Resolves after `sink.finish()` with timing and memory metrics. Aborting `signal`, even during
161
+ * `finish()`, rejects immediately; late results are closed. On other failures, held frames are
162
+ * closed and pending writes awaited. In both cases `sink.abort` is called once and the promise
163
+ * rejects with an {@link ExportAbortedError}, a `RESOURCE_LIMIT` `ExportFailureError`, a
164
+ * `RangeError` for an invalid option, or the error from the backend, `refill` or sink. An error
165
+ * thrown by `sink.abort` does not replace it.
168
166
  */
169
167
  export async function exportToSink(exporter, sink, refill, options = {}) {
170
168
  const started = performance.now();
@@ -181,26 +179,19 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
181
179
  let frameRetainedBytes;
182
180
  let exportComplete = false;
183
181
  let refills = 0;
184
- let sourceConvertUploadMs = 0;
185
- let frameSubmitMs = 0;
186
- let readbackMapLatencyMs = 0;
187
- let readbackWaitMs = 0;
188
- let encodeQueueWaitMs = 0;
189
- let videoEncodeMs = 0;
190
- let muxFinishMs;
191
- let peakReadbackBytes = 0;
192
- let outputReadbackBytes = 0;
193
- let outputRepackBytes = 0;
194
- let peakEncodeQueueBytes = 0;
195
- let maxPendingMediaEvents = 0;
196
- let pendingDepthTotal = 0;
197
- let pendingDepthSamples = 0;
198
- let maxInFlightReadbacks = 0;
199
- let maxEncodeQueueEvents = 0;
200
- let encodeBackpressureCount = 0;
201
- let pipelineOverlapFrames = 0;
202
- // Writes settle in order. A settled write frees its slot and bytes for the next frame at once;
203
- // a failed one fails the export.
182
+ const metrics = new ExportMetrics({
183
+ maxInFlightReadbacks: maxInFlightFrames,
184
+ maxPendingVideoWrites: maxInFlightFrames,
185
+ inFlightByteBudget: maxInFlightBytes,
186
+ });
187
+ // Sources needing software decode, and individual frames already retried in software.
188
+ const softwareSources = new Set();
189
+ const softwareFrames = new Set();
190
+ const inSoftware = (missing) => softwareSources.has(missing.sourceId) ||
191
+ softwareFrames.has(`${missing.sourceId}\u0000${missing.mediaTimeTicks}`)
192
+ ? { ...missing, decode: "software" }
193
+ : missing;
194
+ // Writes settle in order; a failed write fails the export.
204
195
  const retireSettledWrites = () => {
205
196
  for (;;) {
206
197
  const settled = pendingWrites[0]?.settled;
@@ -215,19 +206,21 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
215
206
  encodeQueueBytes -= write.retainedBytes;
216
207
  }
217
208
  };
218
- // Checked before each submission and each frame handed to the sink, and once more on each side of
219
- // finish(), so a cancel after the last submission still cancels: nothing then reports success.
209
+ // Also checked around finish(), so a cancel after the last submission still wins.
210
+ const cancelledError = (signal) => new ExportAbortedError("cancelled", "browser export cancelled", {
211
+ cause: signal.reason,
212
+ });
220
213
  const throwIfCancelled = () => {
221
214
  if (options.signal?.aborted === true)
222
- throw new ExportAbortedError("cancelled", "browser export cancelled", {
223
- cause: options.signal.reason,
224
- });
215
+ throw cancelledError(options.signal);
225
216
  };
217
+ // A cancel ends any wait at once, even on work that never settles; late results are released.
218
+ const cancellable = (work, onLate) => raceAbort(work, options.signal, onLate, cancelledError);
226
219
  try {
227
220
  while (!exportComplete || pendingReadbacks.length > 0) {
228
221
  throwIfCancelled();
229
- // A frame is submitted only when the budget holds it. The first frame's cost is learned from
230
- // the first submission, which is refused below if even it does not fit.
222
+ // The per-frame cost is learned from the first submission, which is refused below if it
223
+ // alone exceeds the budget.
231
224
  for (;;) {
232
225
  retireSettledWrites();
233
226
  if (exportComplete ||
@@ -237,8 +230,11 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
237
230
  break;
238
231
  throwIfCancelled();
239
232
  const submitStarted = performance.now();
240
- const step = await exporter.next();
241
- frameSubmitMs += performance.now() - submitStarted;
233
+ const step = await cancellable(exporter.next(), (late) => {
234
+ if (late.kind === "rendered")
235
+ void late.output.then(({ frame }) => frame.close(), () => { });
236
+ });
237
+ metrics.frameSubmitMs += performance.now() - submitStarted;
242
238
  if (step.kind === "complete") {
243
239
  exportComplete = true;
244
240
  break;
@@ -248,8 +244,26 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
248
244
  throw sourcesNotHeld(step, refills);
249
245
  refills += 1;
250
246
  const refillStarted = performance.now();
251
- await refill(step);
252
- sourceConvertUploadMs += performance.now() - refillStarted;
247
+ try {
248
+ await cancellable(refill({
249
+ ...step,
250
+ missingFrames: step.missingFrames.map(inSoftware),
251
+ }));
252
+ }
253
+ catch (error) {
254
+ const request = softwareDecodeRequest(error);
255
+ const key = request && `${request.sourceId}\u0000${request.mediaTimeTicks}`;
256
+ if (key === undefined || softwareFrames.has(key))
257
+ throw error;
258
+ softwareFrames.add(key);
259
+ if (request?.reason === "non-planar")
260
+ softwareSources.add(request.sourceId);
261
+ // A software retry does not count as another refill.
262
+ refills -= 1;
263
+ }
264
+ finally {
265
+ metrics.sourceSupplyMs += performance.now() - refillStarted;
266
+ }
253
267
  continue;
254
268
  }
255
269
  refills = 0;
@@ -275,13 +289,13 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
275
289
  frameRetainedBytes = step.retainedBytes;
276
290
  retainedBytes += step.retainedBytes;
277
291
  readbackBytes += step.retainedBytes;
278
- peakReadbackBytes = Math.max(peakReadbackBytes, readbackBytes);
292
+ metrics.peakReadbackBytes = Math.max(metrics.peakReadbackBytes, readbackBytes);
279
293
  const mappingStarted = performance.now();
280
294
  const measuredOutput = step.output.then((output) => {
281
- readbackMapLatencyMs += performance.now() - mappingStarted;
295
+ metrics.readbackMapLatencyMs += performance.now() - mappingStarted;
282
296
  return output;
283
297
  }, (error) => {
284
- readbackMapLatencyMs += performance.now() - mappingStarted;
298
+ metrics.readbackMapLatencyMs += performance.now() - mappingStarted;
285
299
  throw error;
286
300
  });
287
301
  void measuredOutput.catch(() => { });
@@ -289,18 +303,15 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
289
303
  output: measuredOutput,
290
304
  retainedBytes: step.retainedBytes,
291
305
  });
292
- maxInFlightReadbacks = Math.max(maxInFlightReadbacks, pendingReadbacks.length);
306
+ metrics.peakInFlightReadbacks = Math.max(metrics.peakInFlightReadbacks, pendingReadbacks.length);
293
307
  if (pendingWrites.length > 0)
294
- pipelineOverlapFrames += 1;
308
+ metrics.pipelineOverlapFrames += 1;
295
309
  }
296
- const pendingDepth = pendingReadbacks.length + pendingWrites.length;
297
- maxPendingMediaEvents = Math.max(maxPendingMediaEvents, pendingDepth);
298
- pendingDepthTotal += pendingDepth;
299
- pendingDepthSamples += 1;
310
+ metrics.samplePending(pendingReadbacks.length + pendingWrites.length);
300
311
  if (pendingReadbacks.length === 0) {
301
312
  const oldestWrite = pendingWrites.shift();
302
313
  if (oldestWrite !== undefined) {
303
- await oldestWrite.completion;
314
+ await cancellable(oldestWrite.completion);
304
315
  retainedBytes -= oldestWrite.retainedBytes;
305
316
  encodeQueueBytes -= oldestWrite.retainedBytes;
306
317
  }
@@ -310,29 +321,28 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
310
321
  if (oldestReadback === undefined)
311
322
  continue;
312
323
  const readbackWaitStarted = performance.now();
313
- const output = await oldestReadback.output;
314
- readbackWaitMs += performance.now() - readbackWaitStarted;
324
+ const output = await cancellable(oldestReadback.output, ({ frame }) => frame.close());
325
+ metrics.readbackWaitMs += performance.now() - readbackWaitStarted;
315
326
  readbackBytes -= oldestReadback.retainedBytes;
316
- outputReadbackBytes += oldestReadback.retainedBytes;
317
- outputRepackBytes += videoFrameRepackedBytes(output.frame);
327
+ metrics.outputReadbackBytes += oldestReadback.retainedBytes;
328
+ metrics.outputRepackBytes += videoFrameRepackedBytes(output.frame);
318
329
  const encodeQueued = performance.now();
319
330
  if (pendingWrites.length > 0)
320
- encodeBackpressureCount += 1;
331
+ metrics.encodeBackpressureCount += 1;
321
332
  const write = writeTail.then(async () => {
322
- encodeQueueWaitMs += performance.now() - encodeQueued;
323
- const encodeStarted = performance.now();
333
+ metrics.encodeQueueWaitMs += performance.now() - encodeQueued;
334
+ const writeStarted = performance.now();
324
335
  try {
325
336
  await sink.writeVideo(output);
326
337
  }
327
338
  finally {
328
- videoEncodeMs += performance.now() - encodeStarted;
339
+ metrics.videoWriteWaitMs += performance.now() - writeStarted;
329
340
  }
330
341
  }, (error) => {
331
342
  output.frame.close();
332
343
  throw error;
333
344
  });
334
- // Keep one serial consumer for sinks that require ordered calls, while the render worker
335
- // produces the next bounded set of frames.
345
+ // Writes stay serialized while the render worker produces the next frames.
336
346
  writeTail = write;
337
347
  const pendingWrite = {
338
348
  completion: write,
@@ -346,16 +356,16 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
346
356
  });
347
357
  pendingWrites.push(pendingWrite);
348
358
  encodeQueueBytes += oldestReadback.retainedBytes;
349
- peakEncodeQueueBytes = Math.max(peakEncodeQueueBytes, encodeQueueBytes);
350
- maxEncodeQueueEvents = Math.max(maxEncodeQueueEvents, pendingWrites.length);
359
+ metrics.peakEncodeQueueBytes = Math.max(metrics.peakEncodeQueueBytes, encodeQueueBytes);
360
+ metrics.maxEncodeQueueEvents = Math.max(metrics.maxEncodeQueueEvents, pendingWrites.length);
351
361
  void write.catch(() => { });
352
362
  }
353
- await writeTail;
363
+ await cancellable(writeTail);
354
364
  pendingWrites.length = 0;
355
365
  throwIfCancelled();
356
366
  const finishStarted = performance.now();
357
367
  await sink.finish();
358
- muxFinishMs = performance.now() - finishStarted;
368
+ metrics.finishMs = performance.now() - finishStarted;
359
369
  throwIfCancelled();
360
370
  const renderMs = performance.now() - started;
361
371
  const completed = exporter.progress.completed;
@@ -367,42 +377,35 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
367
377
  renderMs,
368
378
  frames,
369
379
  fps: frames / Math.max(renderMs / 1_000, Number.EPSILON),
370
- performance: {
371
- pipelineEnabled: true,
372
- sourceConvertUploadMs,
373
- frameSubmitMs,
374
- readbackMapLatencyMs,
375
- readbackWaitMs,
376
- readbackBlockingMs: readbackWaitMs,
377
- encodeQueueWaitMs,
378
- videoEncodeMs,
379
- muxFinishMs,
380
- inFlightDepth: maxInFlightFrames,
381
- encodeChannelDepth: maxInFlightFrames,
382
- inFlightByteBudget: maxInFlightBytes,
383
- stagingBytesPerFrame: frameRetainedBytes ?? 0,
384
- peakReadbackBytes,
385
- outputReadbackBytes,
386
- outputRepackBytes,
387
- peakEncodeQueueBytes,
388
- maxPendingMediaEvents,
389
- averagePendingMediaEvents: pendingDepthSamples === 0
390
- ? 0
391
- : pendingDepthTotal / pendingDepthSamples,
392
- maxInFlightReadbacks,
393
- maxEncodeQueueEvents,
394
- encodeBackpressureCount,
395
- pipelineOverlapFrames,
396
- },
380
+ performance: (() => {
381
+ metrics.stagingBytesPerFrame = frameRetainedBytes ?? 0;
382
+ return metrics.finish(sink.videoEncodeLatencyMs);
383
+ })(),
384
+ ...(sink.videoLatencyProbe === undefined
385
+ ? {}
386
+ : { videoLatencyProbe: sink.videoLatencyProbe }),
387
+ ...(sink.aacPrimingProbe === undefined
388
+ ? {}
389
+ : { aacPrimingProbe: sink.aacPrimingProbe }),
390
+ ...(sink.videoEncoderAcceleration === undefined
391
+ ? {}
392
+ : { videoEncoderAcceleration: sink.videoEncoderAcceleration }),
397
393
  };
398
394
  }
399
395
  catch (error) {
400
- const abandoned = await Promise.allSettled(pendingReadbacks.map(({ output }) => output));
401
- for (const result of abandoned) {
402
- if (result.status === "fulfilled")
403
- result.value.frame.close();
396
+ if (error instanceof ExportAbortedError && error.code === "cancelled") {
397
+ // Do not wait on work that may never settle; close late frames instead.
398
+ for (const { output } of pendingReadbacks)
399
+ void output.then(({ frame }) => frame.close(), () => { });
400
+ }
401
+ else {
402
+ const abandoned = await Promise.allSettled(pendingReadbacks.map(({ output }) => output));
403
+ for (const result of abandoned) {
404
+ if (result.status === "fulfilled")
405
+ result.value.frame.close();
406
+ }
407
+ await Promise.allSettled(pendingWrites.map(({ completion }) => completion));
404
408
  }
405
- await Promise.allSettled(pendingWrites.map(({ completion }) => completion));
406
409
  const failure = error instanceof Error
407
410
  ? error
408
411
  : new ExportAbortedError("adapter", String(error));
@@ -416,9 +419,8 @@ export async function exportToSink(exporter, sink, refill, options = {}) {
416
419
  }
417
420
  }
418
421
  /**
419
- * The failure for a frame that refills did not fill: a refusal (`RESOURCE_LIMIT`), as the frame's
420
- * refill allowance ran out, and the cause is the host's refill, which another attempt runs alike,
421
- * so `decideRetry` does not retry it.
422
+ * `RESOURCE_LIMIT` for a frame the refills never satisfied. A retry would run the same refill, so
423
+ * `decideRetry` does not retry it.
422
424
  */
423
425
  function sourcesNotHeld(step, refills) {
424
426
  return new ExportFailureError({
@@ -452,15 +454,13 @@ function firstFrameAtOrAfter(rate, ticks) {
452
454
  return (numerator + denominator - 1n) / denominator;
453
455
  }
454
456
  /**
455
- * The frame whose half-open interval `[frameStart(k), frameStart(k + 1))` holds `ticks`
456
- * (non-negative): the inverse of the floored frame start, as the engine's
457
- * `FrameRate::frame_at_or_before`. Where a frame lasts a fractional number of ticks, its floored
458
- * start belongs to it, not to the frame before.
457
+ * The frame `k` whose `[frameStart(k), frameStart(k + 1))` holds non-negative `ticks`, matching
458
+ * the engine's `FrameRate::frame_at_or_before`.
459
459
  */
460
460
  function frameAtOrBefore(rate, ticks) {
461
461
  return ((ticks + 1n) * rate.num - 1n) / (TICKS_PER_SECOND * rate.den);
462
462
  }
463
- /** The sample nearest `ticks` (non-negative) at `sampleRate`, half a sample rounding up. */
463
+ /** The sample nearest non-negative `ticks`, rounding half up. */
464
464
  function nearestSample(ticks, sampleRate) {
465
465
  return (ticks * sampleRate * 2n + TICKS_PER_SECOND) / (TICKS_PER_SECOND * 2n);
466
466
  }