alpha2 0.5.2 → 0.6.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 (91) hide show
  1. package/README.md +71 -5
  2. package/THIRD_PARTY_NOTICES.md +191 -1
  3. package/dist/apply-edit.d.ts +124 -0
  4. package/dist/apply-edit.js +15 -0
  5. package/dist/assets.d.ts +12 -0
  6. package/dist/audio-layout.js +6 -3
  7. package/dist/audio-worklet-processor.js +27 -33
  8. package/dist/audio.d.ts +5 -4
  9. package/dist/audio.js +8 -6
  10. package/dist/compose.d.ts +105 -0
  11. package/dist/compose.js +63 -0
  12. package/dist/decoder-fallback.d.ts +3 -2
  13. package/dist/decoder-fallback.js +11 -3
  14. package/dist/decoder-stall.d.ts +15 -0
  15. package/dist/decoder-stall.js +52 -0
  16. package/dist/edit-data.d.ts +24 -0
  17. package/dist/edit-data.js +224 -0
  18. package/dist/edit-keys.d.ts +16 -0
  19. package/dist/edit-keys.js +233 -0
  20. package/dist/edit.d.ts +41 -8
  21. package/dist/edit.js +123 -30
  22. package/dist/export-failure.d.ts +10 -2
  23. package/dist/export-failure.js +55 -4
  24. package/dist/export-retry.d.ts +6 -1
  25. package/dist/export-retry.js +12 -1
  26. package/dist/exporter.d.ts +11 -7
  27. package/dist/exporter.js +10 -9
  28. package/dist/extensions.d.ts +86 -28
  29. package/dist/extensions.js +204 -61
  30. package/dist/extract.d.ts +65 -0
  31. package/dist/extract.js +291 -0
  32. package/dist/extractor.d.ts +151 -0
  33. package/dist/extractor.js +141 -0
  34. package/dist/float32.d.ts +2 -0
  35. package/dist/float32.js +10 -0
  36. package/dist/frame-intake.d.ts +5 -0
  37. package/dist/frame-intake.js +10 -3
  38. package/dist/generated/builtin-effects.d.ts +3 -0
  39. package/dist/generated/builtin-effects.js +1804 -0
  40. package/dist/generated/project-schema.d.ts +696 -41
  41. package/dist/generated/project-schema.js +67 -0
  42. package/dist/generated/project-shape.js +986 -383
  43. package/dist/index.d.ts +1 -0
  44. package/dist/index.js +1 -0
  45. package/dist/json-text.js +14 -2
  46. package/dist/layout-values.js +7 -1
  47. package/dist/layout.d.ts +12 -4
  48. package/dist/media.d.ts +44 -11
  49. package/dist/media.js +256 -67
  50. package/dist/mediabunny.d.ts +32 -12
  51. package/dist/mediabunny.js +276 -90
  52. package/dist/player.d.ts +9 -3
  53. package/dist/player.js +114 -18
  54. package/dist/plugins.d.ts +62 -0
  55. package/dist/plugins.js +506 -0
  56. package/dist/project-data.d.ts +56 -0
  57. package/dist/project-data.js +765 -0
  58. package/dist/project.d.ts +36 -1
  59. package/dist/project.js +515 -42
  60. package/dist/robustness.d.ts +6 -33
  61. package/dist/robustness.js +2 -63
  62. package/dist/sha256.d.ts +3 -2
  63. package/dist/sha256.js +14 -6
  64. package/dist/wasm-module.d.ts +37 -0
  65. package/dist/wasm-module.js +47 -0
  66. package/dist/worker-error.d.ts +3 -2
  67. package/dist/worker-error.js +3 -1
  68. package/dist/worker.d.ts +13 -3
  69. package/dist/worker.js +36 -9
  70. package/package.json +36 -2
  71. package/wasm/alpha2_compose.d.ts +92 -0
  72. package/wasm/alpha2_compose.js +445 -0
  73. package/wasm/alpha2_compose_bg.wasm +0 -0
  74. package/wasm/alpha2_compose_bg.wasm.d.ts +17 -0
  75. package/wasm/alpha2_extensions.d.ts +4 -4
  76. package/wasm/alpha2_extensions.js +16 -4
  77. package/wasm/alpha2_extensions_bg.wasm +0 -0
  78. package/wasm/alpha2_extensions_pdf.d.ts +227 -0
  79. package/wasm/alpha2_extensions_pdf.js +841 -0
  80. package/wasm/alpha2_extensions_pdf_bg.wasm +0 -0
  81. package/wasm/alpha2_extensions_pdf_bg.wasm.d.ts +38 -0
  82. package/wasm/alpha2_wasm.d.ts +151 -18
  83. package/wasm/alpha2_wasm.js +403 -59
  84. package/wasm/alpha2_wasm_bg.wasm +0 -0
  85. package/wasm/alpha2_wasm_bg.wasm.d.ts +21 -6
  86. package/wasm/rust-crate-licenses.md +493 -54
  87. package/wasm/snippets/alpha2-wasm-1b02e9f302d283ba/inline3.js +7 -0
  88. /package/wasm/snippets/{alpha2-wasm-a21734ffde826659/inline1.js → alpha2-wasm-1b02e9f302d283ba/inline0.js} +0 -0
  89. /package/wasm/snippets/{alpha2-wasm-a21734ffde826659/inline2.js → alpha2-wasm-1b02e9f302d283ba/inline1.js} +0 -0
  90. /package/wasm/snippets/{alpha2-wasm-a21734ffde826659/inline3.js → alpha2-wasm-1b02e9f302d283ba/inline2.js} +0 -0
  91. /package/wasm/snippets/{alpha2-wasm-a21734ffde826659/inline0.js → alpha2-wasm-1b02e9f302d283ba/inline4.js} +0 -0
@@ -4,11 +4,13 @@ import { readAudioSpeakers, speakersWithLfe, } from "./audio-layout.js";
4
4
  import { chromaSitingForStream } from "./chroma-siting.js";
5
5
  import { decoderOrderKey, decoderPlaneOrder } from "./decoder-order.js";
6
6
  import { decodeFailureOf, withSoftwareFallback } from "./decoder-fallback.js";
7
+ import { isUnreadableFrame, withReadbackRetries } from "./frame-intake.js";
7
8
  import { ALL_FORMATS, AudioSample, AudioSampleSink, AudioSampleSource, BlobSource, BufferTarget, BufferSource, canEncodeAudio, canEncodeVideo, StreamTarget, EncodedPacketSink, Input, MkvOutputFormat, MovOutputFormat, Mp4OutputFormat, Output, Quality, VideoSample, VideoSampleSink, VideoSampleSource, WebMOutputFormat, } from "mediabunny";
8
9
  import { audioFrameGrid, MAX_AUDIO_CHANNELS, microsecondsToTicks, placeOnAudioFrameGrid, presentationSlackTicks, readMatroskaCodecDelay, readVideoOrientation, roundingQuantum, ROUNDING_SCAN_BYTES, ROUNDING_SCAN_FRAMES, validateStallTimeout, } from "./media.js";
9
10
  import { DecodeUnavailableError, decodeRefusalMessage, isPlanarVideoFrame, PlanarDecodeUnavailableError, } from "./hdr-frames.js";
10
11
  import { resolveExportFormat } from "./containers.js";
11
12
  import { ExportFailureError } from "./export-failure.js";
13
+ import { nextSampleOrStall } from "./decoder-stall.js";
12
14
  // Up to 2 s ahead decodes forward instead of seeking; also the longest step of a backward run.
13
15
  const MAX_SEQUENTIAL_DECODE_GAP_TICKS = 240000n;
14
16
  const DEFAULT_MAX_DECODED_FRAME_BYTES = 64 * 1024 * 1024;
@@ -29,6 +31,7 @@ export class MediabunnyVideoDecoder {
29
31
  #input;
30
32
  #track;
31
33
  #sink;
34
+ #openedAcceleration;
32
35
  #hardwareAcceleration;
33
36
  #softwareFallback;
34
37
  #decodedAny = false;
@@ -53,6 +56,7 @@ export class MediabunnyVideoDecoder {
53
56
  this.#sourceId = sourceId;
54
57
  this.#input = input;
55
58
  this.#track = track;
59
+ this.#openedAcceleration = hardwareAcceleration;
56
60
  this.#hardwareAcceleration = hardwareAcceleration;
57
61
  this.#sink = new VideoSampleSink(track, { hardwareAcceleration });
58
62
  this.#packets = packets;
@@ -137,25 +141,24 @@ export class MediabunnyVideoDecoder {
137
141
  /**
138
142
  * The frame presented at the request's time. A decoder failure (Chromium's VA-API decoders report
139
143
  * `EncodingError`) retries once with a software decoder; if that fails, rejects with
140
- * {@link DecodeUnavailableError} when no frame was ever decoded, else with the failure.
144
+ * {@link DecodeUnavailableError} when no frame was ever decoded, else with the failure, and the
145
+ * next request decodes with the acceleration the decoder was opened with. A `device-recovery`
146
+ * request also returns a decoder that fell back to that acceleration.
141
147
  */
142
148
  async refill(request, signal) {
149
+ if (request.reason === "device-recovery" &&
150
+ !this.#closed &&
151
+ this.#hardwareAcceleration !== this.#openedAcceleration)
152
+ await this.#useAcceleration(this.#openedAcceleration);
143
153
  try {
144
154
  const frame = await withSoftwareFallback(() => this.#refill(request, signal), this.#closed ||
145
155
  this.#hardwareAcceleration === "prefer-software" ||
146
156
  signal?.aborted === true
147
157
  ? undefined
148
158
  : async (cause) => {
149
- await this.#resetIterator();
150
- this.#cache.clear();
151
- this.#reverse.clear();
152
- this.#backwardSteps = 0;
153
- this.#hardwareAcceleration = "prefer-software";
159
+ await this.#useAcceleration("prefer-software");
154
160
  this.#softwareFallback = `${cause.name}: ${cause.message}`;
155
- this.#sink = new VideoSampleSink(this.#track, {
156
- hardwareAcceleration: "prefer-software",
157
- });
158
- });
161
+ }, () => this.#useAcceleration(this.#openedAcceleration));
159
162
  this.#decodedAny = true;
160
163
  return frame;
161
164
  }
@@ -165,6 +168,18 @@ export class MediabunnyVideoDecoder {
165
168
  throw decodeFailureOf(error, this.#sourceId, await videoTrackFacts(this.#track), false);
166
169
  }
167
170
  }
171
+ async #useAcceleration(acceleration) {
172
+ await this.#resetIterator();
173
+ this.#cache.clear();
174
+ this.#reverse.clear();
175
+ this.#backwardSteps = 0;
176
+ this.#hardwareAcceleration = acceleration;
177
+ if (acceleration === this.#openedAcceleration)
178
+ this.#softwareFallback = undefined;
179
+ this.#sink = new VideoSampleSink(this.#track, {
180
+ hardwareAcceleration: acceleration,
181
+ });
182
+ }
168
183
  async #refill(request, signal) {
169
184
  if (this.#closed)
170
185
  throw new Error("mediabunny decoder is closed");
@@ -335,45 +350,27 @@ export class MediabunnyVideoDecoder {
335
350
  }
336
351
  }
337
352
  }
353
+ catch (error) {
354
+ if (!(error instanceof UnreadableFrameError))
355
+ throw error;
356
+ // The forward path answers this request; it decodes and reads frames again.
357
+ this.#reverse.clear();
358
+ this.#backwardSteps = 0;
359
+ return;
360
+ }
338
361
  finally {
339
362
  await iterator.return?.();
340
363
  }
341
364
  this.#reverseWindowsBuilt += 1;
342
365
  }
343
- /**
344
- * Rejects when the decoder produces nothing within the stall timeout, since a hardware decoder
345
- * with all surfaces held waits silently. The iterator is then ended and a late frame closed.
346
- */
347
- async #nextSample(iterator, signal) {
348
- const pending = iterator.next();
349
- const settled = new AbortController();
350
- let abort;
351
- const interrupted = new Promise((_, reject) => {
352
- // Active time, so a frozen page does not count as a stalled decoder.
353
- void activeTimeout(this.#stallTimeoutMs, settled.signal).then(() => reject(new Error(`video decoder ${this.#sourceId} stalled: no frame for ${this.#stallTimeoutMs} ms`)));
354
- if (signal === undefined)
355
- return;
356
- abort = () => reject(signal.reason instanceof Error
357
- ? signal.reason
358
- : new DOMException("Aborted", "AbortError"));
359
- signal.addEventListener("abort", abort, { once: true });
366
+ /** A hardware decoder with all surfaces held waits silently, so every read has a stall limit. */
367
+ #nextSample(iterator, signal) {
368
+ return nextSampleOrStall(iterator, {
369
+ stallMs: this.#stallTimeoutMs,
370
+ signal,
371
+ sourceId: this.#sourceId,
372
+ kind: "video",
360
373
  });
361
- try {
362
- return await Promise.race([pending, interrupted]);
363
- }
364
- catch (error) {
365
- void pending.then((late) => {
366
- if (!late.done)
367
- late.value.close();
368
- }, () => { });
369
- void iterator.return?.()?.catch(() => { });
370
- throw error;
371
- }
372
- finally {
373
- settled.abort();
374
- if (abort !== undefined)
375
- signal?.removeEventListener("abort", abort);
376
- }
377
374
  }
378
375
  async #keyframeSeconds(target) {
379
376
  return (await this.#keyframeStart(target)).seconds;
@@ -568,7 +565,7 @@ async function firstPacketTimes(track, packets) {
568
565
  }
569
566
  return { resolution, timestamps };
570
567
  }
571
- async function streamChromaSiting(track, packets) {
568
+ export async function streamChromaSiting(track, packets) {
572
569
  const config = await track.getDecoderConfig().catch(() => null);
573
570
  const description = config?.description ?? undefined;
574
571
  const first = description === undefined
@@ -576,7 +573,14 @@ async function streamChromaSiting(track, packets) {
576
573
  : null;
577
574
  return chromaSitingForStream(config?.codec ?? track.codec, description, first?.data);
578
575
  }
579
- /** A copy that holds no decoder resources; opaque (GPU) frames are drawn into a bitmap. */
576
+ /** A planar frame whose planes the browser would not copy out, even after retries. */
577
+ class UnreadableFrameError extends Error {
578
+ }
579
+ /**
580
+ * A copy that holds no decoder resources. Opaque (GPU) frames and layouts the copy cannot express
581
+ * are drawn into a bitmap; a planar frame the browser refuses to copy is retried, then rejected
582
+ * with {@link UnreadableFrameError}, since the drawn conversion would differ from a decoded frame.
583
+ */
580
584
  async function detachVideoFrame(frame) {
581
585
  const format = frame.format;
582
586
  if (format !== null) {
@@ -588,7 +592,7 @@ async function detachVideoFrame(frame) {
588
592
  height: frame.codedHeight,
589
593
  };
590
594
  const buffer = new ArrayBuffer(frame.allocationSize());
591
- const layout = await frame.copyTo(buffer);
595
+ const layout = await withReadbackRetries(() => frame.copyTo(buffer));
592
596
  // `transfer` is missing from the DOM typings.
593
597
  const init = {
594
598
  format,
@@ -604,7 +608,11 @@ async function detachVideoFrame(frame) {
604
608
  };
605
609
  return new VideoFrame(buffer, init);
606
610
  }
607
- catch {
611
+ catch (error) {
612
+ if (isUnreadableFrame(error))
613
+ throw new UnreadableFrameError("the browser could not read a frame", {
614
+ cause: error,
615
+ });
608
616
  // A layout the copy cannot express falls through to a drawn copy.
609
617
  }
610
618
  }
@@ -986,9 +994,11 @@ export class MediabunnyAudioDecoder {
986
994
  #delay;
987
995
  #binding;
988
996
  #facts;
997
+ #stallTimeoutMs;
989
998
  #resampler;
990
999
  #closed = false;
991
- constructor(sourceId, input, sink, channelCount, speakers, planeOrder, sourceRate, grid, preroll, delay, binding, facts) {
1000
+ constructor(sourceId, input, sink, channelCount, speakers, planeOrder, sourceRate, grid, preroll, delay, binding, facts, stallTimeoutMs) {
1001
+ this.#stallTimeoutMs = stallTimeoutMs;
992
1002
  this.#sourceId = sourceId;
993
1003
  this.#input = input;
994
1004
  this.#sink = sink;
@@ -1004,12 +1014,16 @@ export class MediabunnyAudioDecoder {
1004
1014
  }
1005
1015
  /**
1006
1016
  * Opens `resource`'s primary audio track, or with `options.stream` the audio track at that
1007
- * position among the file's audio tracks in container order (a clip's `audio.stream`). Rejects
1008
- * when there is no such track, with `RangeError` for more than {@link MAX_AUDIO_CHANNELS}
1009
- * channels or a rate outside 1 kHz to 768 kHz, and with {@link DecodeUnavailableError} when this
1010
- * browser cannot decode it.
1017
+ * position among the file's audio tracks in container order (a clip's `audio.stream`).
1018
+ * `options.stallTimeoutMs` (default 5000) is the active time a refill waits for the next decoded
1019
+ * samples. Rejects with code `AUDIO_STREAM_MISSING` when there is no such track, with
1020
+ * `RangeError` for more than {@link MAX_AUDIO_CHANNELS} channels, a rate outside 1 kHz to
1021
+ * 768 kHz or an invalid stall limit, and with {@link DecodeUnavailableError} when this browser
1022
+ * cannot decode it.
1011
1023
  */
1012
1024
  static async open(sourceId, resource, binding, options = {}) {
1025
+ const stallTimeoutMs = options.stallTimeoutMs ?? DEFAULT_STALL_TIMEOUT_MS;
1026
+ validateStallTimeout(stallTimeoutMs);
1013
1027
  const source = resource instanceof Blob
1014
1028
  ? new BlobSource(resource)
1015
1029
  : new BufferSource(resource);
@@ -1019,9 +1033,9 @@ export class MediabunnyAudioDecoder {
1019
1033
  : ((await input.getAudioTracks())[options.stream] ?? null);
1020
1034
  if (track === null) {
1021
1035
  input.dispose();
1022
- throw new Error(options.stream === undefined
1036
+ throw Object.assign(new Error(options.stream === undefined
1023
1037
  ? "mediabunny input has no audio track"
1024
- : `mediabunny input has no audio stream ${options.stream}`);
1038
+ : `mediabunny input has no audio stream ${options.stream}`), { code: "AUDIO_STREAM_MISSING" });
1025
1039
  }
1026
1040
  if (track.numberOfChannels < 1 ||
1027
1041
  track.numberOfChannels > MAX_AUDIO_CHANNELS) {
@@ -1101,7 +1115,7 @@ export class MediabunnyAudioDecoder {
1101
1115
  codec: track.codec ?? null,
1102
1116
  channels: track.numberOfChannels,
1103
1117
  ...(speakers === null ? {} : { layout: speakers }),
1104
- });
1118
+ }, stallTimeoutMs);
1105
1119
  }
1106
1120
  #resamplerTo(targetRate) {
1107
1121
  if (this.#resampler?.targetRate !== targetRate) {
@@ -1115,9 +1129,9 @@ export class MediabunnyAudioDecoder {
1115
1129
  }
1116
1130
  /**
1117
1131
  * Decodes the interval at `projectSampleRate`, plus two samples each side; silence outside the
1118
- * stream. Rejects when closed, for another source or empty interval, on abort, or when the track
1119
- * changes format mid-stream; with {@link DecodeUnavailableError} when the browser's decoder
1120
- * fails.
1132
+ * stream. Rejects when closed, for another source or empty interval, at once on abort, or when
1133
+ * the track changes format mid-stream; with {@link DecodeUnavailableError} when the browser's
1134
+ * decoder fails, and with `DECODE_STALLED` when it delivers nothing for the stall limit.
1121
1135
  */
1122
1136
  async refill(request, projectSampleRate, signal) {
1123
1137
  if (this.#closed)
@@ -1142,8 +1156,23 @@ export class MediabunnyAudioDecoder {
1142
1156
  let streamStart;
1143
1157
  let expected;
1144
1158
  const delay = this.#delay;
1159
+ const iterator = this.#sink
1160
+ .samples(decodeFrom + delay, sourceEnd / rate + delay)[Symbol.asyncIterator]();
1161
+ let ended = false;
1145
1162
  try {
1146
- for await (const sample of this.#sink.samples(decodeFrom + delay, sourceEnd / rate + delay)) {
1163
+ for (;;) {
1164
+ // A decoder that stops delivering would otherwise hold the refill, and a cancel, forever.
1165
+ const next = await nextSampleOrStall(iterator, {
1166
+ stallMs: this.#stallTimeoutMs,
1167
+ signal,
1168
+ sourceId: this.#sourceId,
1169
+ kind: "audio",
1170
+ });
1171
+ if (next.done) {
1172
+ ended = true;
1173
+ break;
1174
+ }
1175
+ const sample = next.value;
1147
1176
  try {
1148
1177
  throwIfAborted(signal);
1149
1178
  if (sample.numberOfChannels !== channelCount)
@@ -1190,6 +1219,8 @@ export class MediabunnyAudioDecoder {
1190
1219
  }
1191
1220
  }
1192
1221
  catch (error) {
1222
+ if (!ended)
1223
+ void iterator.return?.()?.catch(() => { });
1193
1224
  if (typeof DOMException !== "undefined" &&
1194
1225
  error instanceof DOMException &&
1195
1226
  error.name !== "AbortError") {
@@ -1244,37 +1275,138 @@ const AVC_PROFILES = [
1244
1275
  // constraint_set0, 1 and 2: decodable by Baseline, Main and Extended decoders.
1245
1276
  { profile: "Constrained Baseline", prefix: "42e0" },
1246
1277
  ];
1247
- /** H.264 levels by frame size in macroblocks and bitrate, as mediabunny picks them. */
1278
+ /**
1279
+ * H.264 levels by macroblocks per frame (MaxFS), macroblocks per second (MaxMBPS) and bitrate
1280
+ * (MaxBR), ITU-T H.264 Table A-1. Mirrors `avc_level` in alpha2-host-core.
1281
+ */
1248
1282
  const AVC_LEVELS = [
1249
- { macroblocks: 99, bitrate: 64_000, level: 0x0a },
1250
- { macroblocks: 396, bitrate: 192_000, level: 0x0b },
1251
- { macroblocks: 396, bitrate: 384_000, level: 0x0c },
1252
- { macroblocks: 396, bitrate: 768_000, level: 0x0d },
1253
- { macroblocks: 396, bitrate: 2_000_000, level: 0x14 },
1254
- { macroblocks: 792, bitrate: 4_000_000, level: 0x15 },
1255
- { macroblocks: 1_620, bitrate: 4_000_000, level: 0x16 },
1256
- { macroblocks: 1_620, bitrate: 10_000_000, level: 0x1e },
1257
- { macroblocks: 3_600, bitrate: 14_000_000, level: 0x1f },
1258
- { macroblocks: 5_120, bitrate: 20_000_000, level: 0x20 },
1259
- { macroblocks: 8_192, bitrate: 20_000_000, level: 0x28 },
1260
- { macroblocks: 8_192, bitrate: 50_000_000, level: 0x29 },
1261
- { macroblocks: 8_704, bitrate: 50_000_000, level: 0x2a },
1262
- { macroblocks: 22_080, bitrate: 135_000_000, level: 0x32 },
1263
- { macroblocks: 36_864, bitrate: 240_000_000, level: 0x33 },
1264
- { macroblocks: 36_864, bitrate: 240_000_000, level: 0x34 },
1265
- { macroblocks: 139_264, bitrate: 240_000_000, level: 0x3c },
1266
- { macroblocks: 139_264, bitrate: 480_000_000, level: 0x3d },
1267
- { macroblocks: 139_264, bitrate: 800_000_000, level: 0x3e },
1283
+ {
1284
+ macroblocks: 99,
1285
+ macroblocksPerSecond: 1_485,
1286
+ bitrate: 64_000,
1287
+ level: 0x0a,
1288
+ },
1289
+ {
1290
+ macroblocks: 396,
1291
+ macroblocksPerSecond: 3_000,
1292
+ bitrate: 192_000,
1293
+ level: 0x0b,
1294
+ },
1295
+ {
1296
+ macroblocks: 396,
1297
+ macroblocksPerSecond: 6_000,
1298
+ bitrate: 384_000,
1299
+ level: 0x0c,
1300
+ },
1301
+ {
1302
+ macroblocks: 396,
1303
+ macroblocksPerSecond: 11_880,
1304
+ bitrate: 768_000,
1305
+ level: 0x0d,
1306
+ },
1307
+ {
1308
+ macroblocks: 396,
1309
+ macroblocksPerSecond: 11_880,
1310
+ bitrate: 2_000_000,
1311
+ level: 0x14,
1312
+ },
1313
+ {
1314
+ macroblocks: 792,
1315
+ macroblocksPerSecond: 19_800,
1316
+ bitrate: 4_000_000,
1317
+ level: 0x15,
1318
+ },
1319
+ {
1320
+ macroblocks: 1_620,
1321
+ macroblocksPerSecond: 20_250,
1322
+ bitrate: 4_000_000,
1323
+ level: 0x16,
1324
+ },
1325
+ {
1326
+ macroblocks: 1_620,
1327
+ macroblocksPerSecond: 40_500,
1328
+ bitrate: 10_000_000,
1329
+ level: 0x1e,
1330
+ },
1331
+ {
1332
+ macroblocks: 3_600,
1333
+ macroblocksPerSecond: 108_000,
1334
+ bitrate: 14_000_000,
1335
+ level: 0x1f,
1336
+ },
1337
+ {
1338
+ macroblocks: 5_120,
1339
+ macroblocksPerSecond: 216_000,
1340
+ bitrate: 20_000_000,
1341
+ level: 0x20,
1342
+ },
1343
+ {
1344
+ macroblocks: 8_192,
1345
+ macroblocksPerSecond: 245_760,
1346
+ bitrate: 20_000_000,
1347
+ level: 0x28,
1348
+ },
1349
+ {
1350
+ macroblocks: 8_192,
1351
+ macroblocksPerSecond: 245_760,
1352
+ bitrate: 50_000_000,
1353
+ level: 0x29,
1354
+ },
1355
+ {
1356
+ macroblocks: 8_704,
1357
+ macroblocksPerSecond: 522_240,
1358
+ bitrate: 50_000_000,
1359
+ level: 0x2a,
1360
+ },
1361
+ {
1362
+ macroblocks: 22_080,
1363
+ macroblocksPerSecond: 589_824,
1364
+ bitrate: 135_000_000,
1365
+ level: 0x32,
1366
+ },
1367
+ {
1368
+ macroblocks: 36_864,
1369
+ macroblocksPerSecond: 983_040,
1370
+ bitrate: 240_000_000,
1371
+ level: 0x33,
1372
+ },
1373
+ {
1374
+ macroblocks: 36_864,
1375
+ macroblocksPerSecond: 2_073_600,
1376
+ bitrate: 240_000_000,
1377
+ level: 0x34,
1378
+ },
1379
+ {
1380
+ macroblocks: 139_264,
1381
+ macroblocksPerSecond: 4_177_920,
1382
+ bitrate: 240_000_000,
1383
+ level: 0x3c,
1384
+ },
1385
+ {
1386
+ macroblocks: 139_264,
1387
+ macroblocksPerSecond: 8_355_840,
1388
+ bitrate: 480_000_000,
1389
+ level: 0x3d,
1390
+ },
1391
+ {
1392
+ macroblocks: 139_264,
1393
+ macroblocksPerSecond: 16_711_680,
1394
+ bitrate: 800_000_000,
1395
+ level: 0x3e,
1396
+ },
1268
1397
  ];
1269
1398
  /**
1270
1399
  * The H.264 profiles {@link canEncodeVideoTrack} tries, in order (High, Main, Constrained
1271
- * Baseline), at the needed level. Empty for other codecs.
1400
+ * Baseline), at the lowest level that holds the frame size at `frameRate` and the bitrate. Empty
1401
+ * for other codecs.
1272
1402
  */
1273
1403
  export function videoEncoderProfiles(codec, options) {
1274
1404
  if (codec !== "avc")
1275
1405
  return [];
1276
1406
  const macroblocks = Math.ceil(options.width / 16) * Math.ceil(options.height / 16);
1407
+ const { num, den } = options.frameRate;
1277
1408
  const level = (AVC_LEVELS.find((entry) => macroblocks <= entry.macroblocks &&
1409
+ macroblocks * num <= entry.macroblocksPerSecond * den &&
1278
1410
  options.rate.bitrate <= entry.bitrate) ?? AVC_LEVELS[AVC_LEVELS.length - 1]).level
1279
1411
  .toString(16)
1280
1412
  .padStart(2, "0");
@@ -1919,6 +2051,9 @@ export class MediabunnySink {
1919
2051
  #framesOut = 0;
1920
2052
  /** Active time, so a frozen page does not count as a stall. */
1921
2053
  #progress;
2054
+ /** Active time since the last packet or write while `finish` runs. */
2055
+ #finishing;
2056
+ #aborted;
1922
2057
  #audio;
1923
2058
  #audioCodec;
1924
2059
  #audioBitrate;
@@ -1955,6 +2090,7 @@ export class MediabunnySink {
1955
2090
  this.#target = new BufferTarget();
1956
2091
  // Stopping at the reserved size keeps the output within its budget.
1957
2092
  this.#target.onwrite = (_start, end) => {
2093
+ this.#finishing?.reset();
1958
2094
  this.#written = Math.max(this.#written, end);
1959
2095
  if (end > destination.maxBytes)
1960
2096
  this.#overflow ??= new ExportFailureError({
@@ -1977,11 +2113,12 @@ export class MediabunnySink {
1977
2113
  const muxed = new WritableStream({
1978
2114
  write: async (chunk) => {
1979
2115
  await file.ready;
1980
- void file.write(chunk).catch(() => { });
2116
+ void file.write(chunk).then(() => this.#finishing?.reset(), () => { });
1981
2117
  },
1982
2118
  });
1983
2119
  this.#target = new StreamTarget(muxed, { chunked: false });
1984
2120
  this.#target.onwrite = (_start, end) => {
2121
+ this.#finishing?.reset();
1985
2122
  this.#written = Math.max(this.#written, end);
1986
2123
  };
1987
2124
  }
@@ -2083,6 +2220,7 @@ export class MediabunnySink {
2083
2220
  }
2084
2221
  #madeProgress() {
2085
2222
  (this.#progress ??= new ActiveStopwatch()).reset();
2223
+ this.#finishing?.reset();
2086
2224
  }
2087
2225
  #watched(work) {
2088
2226
  const progress = (this.#progress ??= new ActiveStopwatch());
@@ -2300,39 +2438,87 @@ export class MediabunnySink {
2300
2438
  }
2301
2439
  /**
2302
2440
  * Finalizes the file and commits a stream destination; idempotent once resolved. Rejects with
2303
- * `RESOURCE_LIMIT`, `ENCODE_STALLED`, or the muxer's or destination's error, discarding a stream.
2441
+ * `RESOURCE_LIMIT`, `ENCODE_STALLED` (no packet or write for the stall time), the muxer's or
2442
+ * destination's error, or the reason of an `abort` that arrived meanwhile, discarding a stream.
2304
2443
  */
2305
2444
  async finish() {
2306
2445
  if (this.#finished)
2307
2446
  return;
2308
2447
  await this.#ready;
2448
+ const finishing = (this.#finishing = new ActiveStopwatch());
2309
2449
  try {
2310
- await this.#flushAudio();
2311
- await this.#watched(this.#output.finalize());
2312
- if (this.#overflow)
2313
- throw this.#overflow;
2314
- await this.#file?.close();
2450
+ await this.#finishWatched((async () => {
2451
+ await this.#flushAudio();
2452
+ await this.#output.finalize();
2453
+ if (this.#overflow)
2454
+ throw this.#overflow;
2455
+ if (this.#aborted !== undefined)
2456
+ throw this.#aborted;
2457
+ await this.#file?.close();
2458
+ })(), finishing);
2315
2459
  }
2316
2460
  catch (error) {
2317
- await this.#discard(error).catch(() => { });
2461
+ const discarded = this.#discard(error).catch(() => { });
2462
+ // A stalled destination may never take the abort either.
2463
+ if (error.code !== "ENCODE_STALLED")
2464
+ await discarded;
2318
2465
  throw error;
2319
2466
  }
2320
2467
  finally {
2468
+ finishing.dispose();
2321
2469
  this.#progress?.dispose();
2322
2470
  }
2471
+ if (this.#aborted !== undefined)
2472
+ throw this.#aborted;
2323
2473
  this.#finished = true;
2324
2474
  }
2325
- /** Discards the output unless already finished; rejects if the destination refuses. */
2475
+ // Fails when neither a packet nor a write arrived for the stall time.
2476
+ #finishWatched(work, finishing) {
2477
+ return new Promise((resolve, reject) => {
2478
+ const stop = finishing.onTick(() => {
2479
+ const waited = finishing.elapsed();
2480
+ if (waited < this.#stallTimeoutMs)
2481
+ return;
2482
+ stop();
2483
+ const held = this.#framesIn - this.#framesOut;
2484
+ reject(Object.assign(new Error(held > 0
2485
+ ? `video encoder stalled: no output for ${Math.round(waited)} ms with ${held} frames queued`
2486
+ : `export finalize stalled: no packet or write for ${Math.round(waited)} ms`), {
2487
+ code: "ENCODE_STALLED",
2488
+ failure: held > 0
2489
+ ? {
2490
+ code: "GPU_TIMEOUT",
2491
+ phase: "encode",
2492
+ stage: "encoder-stalled",
2493
+ resource: "unknown",
2494
+ }
2495
+ : {
2496
+ code: "GPU_TIMEOUT",
2497
+ phase: "mux",
2498
+ stage: "finalize-stalled",
2499
+ resource: "unknown",
2500
+ },
2501
+ }));
2502
+ });
2503
+ void work.finally(stop).then(resolve, reject);
2504
+ });
2505
+ }
2506
+ /**
2507
+ * Discards the output unless already finished, also while `finish` is pending; rejects if the
2508
+ * destination refuses.
2509
+ */
2326
2510
  async abort(reason) {
2327
2511
  if (this.#finished)
2328
2512
  return;
2513
+ this.#aborted ??= reason;
2329
2514
  this.#progress?.dispose();
2330
2515
  if (this.#audioConverter !== undefined && !this.#audioFlushed) {
2331
2516
  this.#audioFlushed = true;
2332
2517
  this.#audioConverter.free();
2333
2518
  }
2334
2519
  try {
2335
- if (this.#output.state !== "canceled")
2520
+ // mediabunny ignores a cancel while finalizing; `finish` then refuses to commit.
2521
+ if (this.#output.state === "started" || this.#output.state === "pending")
2336
2522
  await this.#output.cancel();
2337
2523
  }
2338
2524
  finally {
package/dist/player.d.ts CHANGED
@@ -88,6 +88,10 @@ export interface Alpha2PlayerOptions {
88
88
  * It keeps no clock: `present` shows the time it is given. For playback with audio, pass
89
89
  * `AudioPlaybackClock.timelineTicks` so the picture follows the audio device.
90
90
  *
91
+ * At most one presentation runs on the backend at a time, and at most one waits: a `present` or
92
+ * `seek` that arrives while another is waiting replaces it, so a caller may present on every
93
+ * animation frame without building a backlog.
94
+ *
91
95
  * A presentation that lacks source frames asks `onRefill` for them, then presents the same time
92
96
  * again. Frames uploaded after `onRefill` resolves show only on the next presentation.
93
97
  *
@@ -113,7 +117,8 @@ export declare class Alpha2Player {
113
117
  uploadVideoFrame(frame: DecodedVideoFrame): Promise<void>;
114
118
  /**
115
119
  * Presents `timeTicks`, recovering a lost device first and refilling missing frames through
116
- * `onRefill`. Resolves `undefined` when a later `present` or `seek` superseded this one.
120
+ * `onRefill`. Resolves `undefined` when a later `present` or `seek` superseded this one, whether
121
+ * it was still waiting (then the backend never saw it) or already running.
117
122
  *
118
123
  * Rejects with a fatal `GPU_DEVICE_LOST` when no renderer can be made (or a fresh surface was
119
124
  * needed without `replaceSurface`); every later presentation rejects the same way.
@@ -123,11 +128,12 @@ export declare class Alpha2Player {
123
128
  present(timeTicks: bigint): Promise<PresentedFrame | undefined>;
124
129
  /**
125
130
  * Seeks to `timeTicks`, dropping frames decoded for earlier requests, and presents the target
126
- * once `onRefill` has delivered. Resolves `undefined` when a later request superseded it.
131
+ * once `onRefill` has delivered, recovering a lost device first as `present` does. Resolves
132
+ * `undefined` when a later request superseded it.
127
133
  *
128
134
  * @throws Before {@link Alpha2Player.initialize} has resolved.
129
135
  */
130
136
  seek(timeTicks: bigint): Promise<PresentedFrame | undefined>;
131
- /** Disposes the backend; a presentation in flight resolves `undefined`. */
137
+ /** Disposes the backend; presentations waiting or in flight resolve `undefined`. */
132
138
  dispose(): void;
133
139
  }