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
package/dist/media.js CHANGED
@@ -7,11 +7,9 @@ export const ROUNDING_SCAN_FRAMES = 64;
7
7
  /** Packet bytes (16 MiB) after which no more leading packets are read. */
8
8
  export const ROUNDING_SCAN_BYTES = 16 * 1024 * 1024;
9
9
  /**
10
- * The unit a stream's timestamps are rounded to, in units of its time resolution, or 0 when none
11
- * shows. A frame interval that is not a whole number of units rounds to two lengths a unit apart
12
- * (29.97 fps in ms gives 33 and 34), so the unit is the GCD of the interval differences. Returns 0
13
- * for uniform or variable frame rates and for fewer than three distinct timestamps.
14
- * Throws `RangeError` for a timestamp that is not a safe integer.
10
+ * The unit a stream's timestamps are rounded to, in units of its time resolution (1 for 29.97 fps
11
+ * in ms, whose frames last 33 and 34), or 0 when none shows. Mirrors the engine's
12
+ * `rounding_quantum`. Throws `RangeError` for a timestamp that is not a safe integer.
15
13
  */
16
14
  export function roundingQuantum(timestamps) {
17
15
  for (const timestamp of timestamps)
@@ -37,8 +35,48 @@ export function roundingQuantum(timestamps) {
37
35
  }
38
36
  if (quantum === 0n || quantum * 2n >= shortest)
39
37
  return 0;
38
+ if (!fitsOnePeriod(sorted.map(BigInt), intervals, shortest, quantum))
39
+ return 0;
40
40
  return Number(quantum);
41
41
  }
42
+ /** Mirrors `fits_one_period` of the engine's `rounding_quantum`. */
43
+ function fitsOnePeriod(sorted, intervals, shortest, unit) {
44
+ const first = sorted[0];
45
+ if (sorted.some((time) => (((time - first) % unit) + unit) % unit !== 0n))
46
+ return false;
47
+ let sum = 0n;
48
+ let count = 0n;
49
+ for (const interval of intervals) {
50
+ if (interval - shortest <= unit) {
51
+ sum += interval;
52
+ count += 1n;
53
+ }
54
+ }
55
+ const frames = [0n];
56
+ for (const interval of intervals) {
57
+ frames.push(frames[frames.length - 1] + (interval * 2n * count + sum) / (2n * sum));
58
+ }
59
+ let low;
60
+ let high;
61
+ const below = (a, b) => a[0] * b[1] < b[0] * a[1];
62
+ for (let j = 0; j < sorted.length; j++) {
63
+ for (let k = j + 1; k < sorted.length; k++) {
64
+ const span = sorted[k] - sorted[j];
65
+ const frameCount = frames[k] - frames[j];
66
+ if (frameCount <= 0n)
67
+ return false;
68
+ const from = [span - unit, frameCount];
69
+ const to = [span + unit, frameCount];
70
+ if (low === undefined || below(low, from))
71
+ low = from;
72
+ if (high === undefined || below(to, high))
73
+ high = to;
74
+ }
75
+ }
76
+ return low !== undefined && high !== undefined && !below(high, low);
77
+ }
78
+ /** Most whole-sample periods `audioFrameGrid` tries. Mirrors `audio_frame_grid`. */
79
+ const MAX_GRID_CANDIDATES = 4096n;
42
80
  /**
43
81
  * The frame grid an audio stream's first packet timestamps show at `sampleRate`, for timestamps in
44
82
  * whole units of `1 / timeResolution` seconds. Matches the engine's `audio_frame_grid`. Returns
@@ -76,6 +114,8 @@ export function audioFrameGrid(timestamps, timeResolution, sampleRate) {
76
114
  if (shortest < 2n * trimmed + 1n)
77
115
  shortest = 2n * trimmed + 1n;
78
116
  const longest = floorDiv(span + rounding, den * frames) + 1n;
117
+ if (longest - shortest >= MAX_GRID_CANDIDATES)
118
+ return undefined;
79
119
  let best;
80
120
  for (let period = shortest; period <= longest; period += 1n) {
81
121
  let low;
@@ -170,6 +210,8 @@ export const UPRIGHT = Object.freeze({
170
210
  mirror: false,
171
211
  });
172
212
  const MAX_HEADER_SCAN_BYTES = 64 * 1024 * 1024;
213
+ /** Boxes one level of an MP4 walk visits; each costs one 16-byte read, wherever it starts. */
214
+ const MAX_BOXES_PER_LEVEL = 4096;
173
215
  /**
174
216
  * Reads track `trackId`'s orientation, mirror included, from MP4/QuickTime `tkhd`/`mvhd` matrices
175
217
  * or the Matroska projection pose, as `FFmpeg` does. `trackId` is mediabunny's `InputTrack.id`.
@@ -215,7 +257,7 @@ function ascii(bytes, start, end) {
215
257
  }
216
258
  async function* isobmffBoxes(reader, start, end) {
217
259
  let at = start;
218
- while (at + 8 <= end && at < MAX_HEADER_SCAN_BYTES + start) {
260
+ for (let visited = 0; at + 8 <= end && visited < MAX_BOXES_PER_LEVEL; visited++) {
219
261
  const header = await reader.read(at, 16);
220
262
  if (header.length < 8)
221
263
  return;
@@ -348,14 +390,20 @@ function vint(bytes, at, keepMarker) {
348
390
  length,
349
391
  };
350
392
  }
393
+ // EBML integers are at most 8 bytes and floats 0, 4 or 8, so longer sizes are refused unread.
351
394
  async function ebmlUnsigned(reader, element) {
352
- const bytes = await reader.read(element.start, element.end - element.start);
395
+ const length = element.end - element.start;
396
+ if (length > 8)
397
+ return Number.NaN;
398
+ const bytes = await reader.read(element.start, length);
353
399
  return bytes.reduce((value, byte) => value * 256 + byte, 0);
354
400
  }
355
401
  async function ebmlFloat(reader, element) {
356
402
  const length = element.end - element.start;
357
403
  if (length === 0)
358
404
  return 0;
405
+ if (length !== 4 && length !== 8)
406
+ return Number.NaN;
359
407
  const bytes = await reader.read(element.start, length);
360
408
  const view = new DataView(bytes.buffer, bytes.byteOffset);
361
409
  if (length === 4)
@@ -438,7 +486,7 @@ async function matroskaOrientation(reader, trackId) {
438
486
  }
439
487
  /**
440
488
  * The `CodecDelay` a Matroska or WebM file declares for track `trackId` (mediabunny's
441
- * `InputTrack.id`), in nanoseconds; 0 when none. Readers should subtract it; mediabunny does not.
489
+ * `InputTrack.id`), in nanoseconds, or 0 when none or malformed. mediabunny does not subtract it.
442
490
  */
443
491
  export async function readMatroskaCodecDelay(container, trackId) {
444
492
  const reader = new ByteReader(container);
@@ -450,13 +498,13 @@ export async function readMatroskaCodecDelay(container, trackId) {
450
498
  continue;
451
499
  for await (const field of ebmlElements(reader, entry.start, entry.end))
452
500
  if (field.id === EBML.codecDelay)
453
- return ebmlUnsigned(reader, field);
501
+ return (await ebmlUnsigned(reader, field)) || 0;
454
502
  return 0;
455
503
  }
456
504
  return 0;
457
505
  }
458
506
  /** A 22.2 layout's 24; sources with more are refused. */
459
- export const MAX_AUDIO_CHANNELS = 24;
507
+ export { MAX_AUDIO_CHANNELS } from "./generated/project-schema.js";
460
508
  /** WebCodecs adapter for elementary chunks supplied by any demuxer. */
461
509
  export class WebCodecsVideoDecoder {
462
510
  #sourceId;
@@ -481,6 +529,7 @@ export class WebCodecsVideoDecoder {
481
529
  #readyBytes = 0;
482
530
  #activeTargetTicks;
483
531
  #reverseCacheHits = 0;
532
+ #openedSoftware;
484
533
  #software;
485
534
  #softwareFallback;
486
535
  #decodedAny = false;
@@ -504,7 +553,9 @@ export class WebCodecsVideoDecoder {
504
553
  this.#reorders = reordersOutput(source.config.codec);
505
554
  this.#chromaSiting = chromaSitingForStream(source.config.codec, source.config.description);
506
555
  this.#sitingFromKeyChunk = source.config.description === undefined;
507
- this.#software = source.config.hardwareAcceleration === "prefer-software";
556
+ this.#openedSoftware =
557
+ source.config.hardwareAcceleration === "prefer-software";
558
+ this.#software = this.#openedSoftware;
508
559
  }
509
560
  /** Why decoding moved to software after the browser's first pick failed, if it did. */
510
561
  get softwareFallback() {
@@ -529,22 +580,28 @@ export class WebCodecsVideoDecoder {
529
580
  }
530
581
  /**
531
582
  * A decoder failure retries once from the keyframe with `"prefer-software"`. If that fails too,
532
- * rejects with `DecodeUnavailableError` when no frame was ever decoded, else with the failure.
583
+ * rejects with `DecodeUnavailableError` when no frame was ever decoded, else with the failure,
584
+ * and the next request decodes with the configured acceleration. A `device-recovery` request
585
+ * also returns a decoder that fell back to that acceleration.
533
586
  */
534
587
  async refill(request, signal = new AbortController().signal) {
535
588
  if (request.sourceId !== this.#sourceId) {
536
589
  throw new Error(`decoder source mismatch: ${request.sourceId}`);
537
590
  }
591
+ if (request.reason === "device-recovery" &&
592
+ this.#software !== this.#openedSoftware)
593
+ this.#useSoftware(this.#openedSoftware);
538
594
  try {
539
595
  const frame = await withSoftwareFallback(() => this.#refillOnce(request, signal), this.#software || signal.aborted
540
596
  ? undefined
541
597
  : (cause) => {
542
- this.#software = true;
598
+ this.#useSoftware(true);
543
599
  this.#softwareFallback = `${cause.name}: ${cause.message}`;
544
- this.#resetCursor();
545
- this.#cache.clear();
546
600
  return Promise.resolve();
547
- });
601
+ }, () => {
602
+ this.#useSoftware(this.#openedSoftware);
603
+ return Promise.resolve();
604
+ });
548
605
  this.#decodedAny = true;
549
606
  return frame;
550
607
  }
@@ -554,6 +611,13 @@ export class WebCodecsVideoDecoder {
554
611
  throw decodeFailureOf(error, this.#sourceId, { kind: "video", codec: this.#source.config.codec }, false);
555
612
  }
556
613
  }
614
+ #useSoftware(software) {
615
+ this.#software = software;
616
+ if (software === this.#openedSoftware)
617
+ this.#softwareFallback = undefined;
618
+ this.#resetCursor();
619
+ this.#cache.clear();
620
+ }
557
621
  async #refillOnce(request, signal) {
558
622
  throwIfAborted(signal);
559
623
  if (this.#generation !== undefined &&
@@ -656,9 +720,9 @@ export class WebCodecsVideoDecoder {
656
720
  if (!(await this.#waitForOutput(signal))) {
657
721
  // Every surface is held. Closing queued frames would answer with a later frame.
658
722
  if (this.#cache.releaseAllButPresentedAt(target) === 0)
659
- throw new Error(`video decoder ${this.#sourceId} stalled: no output for ` +
723
+ throw decoderStalled(`video decoder ${this.#sourceId} stalled: no output for ` +
660
724
  `${this.#stallTimeoutMs} ms with ${decoder.decodeQueueSize} chunks queued; ` +
661
- "its surfaces are held by frames that were never closed");
725
+ "its surfaces are held by frames that were never closed", "video-decoder-stalled");
662
726
  }
663
727
  }
664
728
  else {
@@ -770,7 +834,7 @@ export class WebCodecsVideoDecoder {
770
834
  const interrupted = new Promise((_, reject) => {
771
835
  abort = () => reject(abortError(signal));
772
836
  signal.addEventListener("abort", abort, { once: true });
773
- void activeTimeout(this.#stallTimeoutMs, settled.signal).then(() => reject(new Error(`video decoder ${this.#sourceId} stalled during EOF flush after ${this.#stallTimeoutMs} ms`)));
837
+ void activeTimeout(this.#stallTimeoutMs, settled.signal).then(() => reject(decoderStalled(`video decoder ${this.#sourceId} stalled during EOF flush after ${this.#stallTimeoutMs} ms`, "video-decoder-flush-stalled")));
774
838
  });
775
839
  await Promise.race([decoder.flush(), interrupted]);
776
840
  this.#releaseArriving();
@@ -863,7 +927,8 @@ export class WebCodecsVideoDecoder {
863
927
  /**
864
928
  * Runs refills on decoders it opens, one per source and consumer (plus one for software), with
865
929
  * one refill per source at a time and at most `maxConcurrency` overall. A newer generation aborts
866
- * requests in flight and closes their frames instead of delivering them.
930
+ * requests in flight and closes their frames instead of delivering them. At most `maxCursors`
931
+ * decoders stay open across sources, and a cursor idle for `idleMs` releases its decoder's frames.
867
932
  */
868
933
  export class DecoderRefillCoordinator {
869
934
  #open;
@@ -871,30 +936,39 @@ export class DecoderRefillCoordinator {
871
936
  #generation = 0;
872
937
  #controller = new AbortController();
873
938
  #maxConcurrency;
874
- #maxCursorsPerSource;
939
+ #maxCursors;
940
+ #idleMs;
875
941
  #active = 0;
876
942
  #capacityWaiters = [];
877
943
  #sourceTails = new Map();
878
944
  #cursors = new Map();
945
+ // Refills queued or running per cursor key; a busy cursor is never closed or flushed.
946
+ #busy = new Map();
947
+ #retained = new Set();
948
+ #touches = 0;
949
+ #ticker;
950
+ #evictions = 0;
951
+ #idleFlushes = 0;
952
+ #overBudget = 0;
879
953
  #closed = false;
880
954
  /**
881
955
  * A rejected `open` rejects that refill; `software_decode_unavailable` becomes
882
956
  * `PlanarDecodeUnavailableError`. Throws `RangeError` for invalid options.
883
957
  */
884
958
  constructor(open, deliver, options = {}) {
885
- const maxConcurrency = options.maxConcurrency ?? 2;
886
- const maxCursorsPerSource = options.maxCursorsPerSource ?? 4;
887
- if (!Number.isSafeInteger(maxConcurrency) || maxConcurrency <= 0) {
888
- throw new RangeError("maxConcurrency must be a positive safe integer");
889
- }
890
- if (!Number.isSafeInteger(maxCursorsPerSource) ||
891
- maxCursorsPerSource <= 0) {
892
- throw new RangeError("maxCursorsPerSource must be a positive safe integer");
893
- }
959
+ const limits = {
960
+ maxConcurrency: options.maxConcurrency ?? 2,
961
+ maxCursors: options.maxCursors ?? DEFAULT_MAX_DECODER_CURSORS,
962
+ idleMs: options.idleMs ?? DEFAULT_DECODER_IDLE_MS,
963
+ };
964
+ for (const [name, value] of Object.entries(limits))
965
+ if (!Number.isSafeInteger(value) || value <= 0)
966
+ throw new RangeError(`${name} must be a positive safe integer`);
894
967
  this.#open = open;
895
968
  this.#deliver = deliver;
896
- this.#maxConcurrency = maxConcurrency;
897
- this.#maxCursorsPerSource = maxCursorsPerSource;
969
+ this.#maxConcurrency = limits.maxConcurrency;
970
+ this.#maxCursors = limits.maxCursors;
971
+ this.#idleMs = limits.idleMs;
898
972
  }
899
973
  /** Aborts requests in flight and returns the new generation number. */
900
974
  beginGeneration() {
@@ -902,6 +976,23 @@ export class DecoderRefillCoordinator {
902
976
  this.#controller = new AbortController();
903
977
  return ++this.#generation;
904
978
  }
979
+ /**
980
+ * Declares the cursors of the current round, replacing the previous set; retained cursors are
981
+ * never closed for the budget. A cursor is a source and a `consumerId` (absent is the source's
982
+ * own), in both decode kinds.
983
+ */
984
+ retain(cursors) {
985
+ this.#retained = new Set(Array.from(cursors, ({ sourceId, consumerId }) => retainKey(sourceId, consumerId ?? "")));
986
+ this.#enforceBudget();
987
+ }
988
+ get diagnostics() {
989
+ return {
990
+ openCursors: this.#cursors.size,
991
+ evictions: this.#evictions,
992
+ idleFlushes: this.#idleFlushes,
993
+ overBudget: this.#overBudget,
994
+ };
995
+ }
905
996
  /**
906
997
  * Resolves without delivering when the request's generation is superseded; rejects with the
907
998
  * decoder's, delivery's or abort's error, and once closed.
@@ -914,16 +1005,31 @@ export class DecoderRefillCoordinator {
914
1005
  this.#controller = new AbortController();
915
1006
  this.#generation = request.generation;
916
1007
  }
917
- const previous = this.#sourceTails.get(request.sourceId) ?? Promise.resolve();
918
- const task = previous.catch(() => { }).then(() => this.#refillNow(request));
919
- this.#sourceTails.set(request.sourceId, task);
1008
+ const key = cursorKey(request.sourceId, request.consumerId ?? "", request.decode === "software");
1009
+ this.#busy.set(key, (this.#busy.get(key) ?? 0) + 1);
1010
+ try {
1011
+ await this.#onSource(request.sourceId, () => this.#refillNow(request));
1012
+ }
1013
+ finally {
1014
+ const left = (this.#busy.get(key) ?? 1) - 1;
1015
+ if (left > 0)
1016
+ this.#busy.set(key, left);
1017
+ else
1018
+ this.#busy.delete(key);
1019
+ }
1020
+ }
1021
+ // Serializes `work` after everything queued on the source, so a close or flush never overlaps
1022
+ // a refill.
1023
+ async #onSource(sourceId, work) {
1024
+ const previous = this.#sourceTails.get(sourceId) ?? Promise.resolve();
1025
+ const task = previous.catch(() => { }).then(work);
1026
+ this.#sourceTails.set(sourceId, task);
920
1027
  try {
921
1028
  await task;
922
1029
  }
923
1030
  finally {
924
- if (this.#sourceTails.get(request.sourceId) === task) {
925
- this.#sourceTails.delete(request.sourceId);
926
- }
1031
+ if (this.#sourceTails.get(sourceId) === task)
1032
+ this.#sourceTails.delete(sourceId);
927
1033
  }
928
1034
  }
929
1035
  async #refillNow(request) {
@@ -935,8 +1041,18 @@ export class DecoderRefillCoordinator {
935
1041
  return;
936
1042
  throwIfAborted(this.#controller.signal);
937
1043
  const software = request.decode === "software";
938
- const decoder = await this.#cursor(request.sourceId, request.consumerId ?? "", software ? "software" : "default");
939
- const frame = await decoder.refill(request, this.#controller.signal);
1044
+ const key = cursorKey(request.sourceId, request.consumerId ?? "", software);
1045
+ const decoder = await this.#cursor(key, request.sourceId, request.consumerId ?? "", software ? "software" : "default");
1046
+ let frame;
1047
+ try {
1048
+ frame = await decoder.refill(request, this.#controller.signal);
1049
+ }
1050
+ catch (error) {
1051
+ // A failed decoder is not kept, as a failed open is not; aborts and stalls keep it.
1052
+ if (isDecoderFailure(error) || error instanceof DecodeUnavailableError)
1053
+ this.#forget(key);
1054
+ throw error;
1055
+ }
940
1056
  if (frame.generation !== this.#generation) {
941
1057
  frame.frame.close();
942
1058
  return;
@@ -947,38 +1063,99 @@ export class DecoderRefillCoordinator {
947
1063
  this.#release();
948
1064
  }
949
1065
  }
950
- // Runs inside the source's queue, so a decoder closed past the limit is not decoding.
951
- async #cursor(sourceId, consumer, decode) {
952
- let cursors = this.#cursors.get(sourceId);
953
- if (cursors === undefined) {
954
- cursors = new Map();
955
- this.#cursors.set(sourceId, cursors);
956
- }
957
- const consumerId = decode === "software" ? `${consumer}\u0000software` : consumer;
958
- let decoder = cursors.get(consumerId);
959
- if (decoder === undefined) {
960
- decoder = Promise.resolve()
1066
+ // Runs inside the source's queue, so the cursor it returns is not decoding for anyone else.
1067
+ #cursor(key, sourceId, consumer, decode) {
1068
+ let cursor = this.#cursors.get(key);
1069
+ if (cursor === undefined) {
1070
+ const decoder = Promise.resolve()
961
1071
  .then(() => this.#open(sourceId, { decode }))
962
1072
  .catch((error) => {
963
1073
  throw decode === "software"
964
1074
  ? softwareRefusal(sourceId, error)
965
1075
  : error;
966
1076
  });
1077
+ const opened = {
1078
+ sourceId,
1079
+ consumer,
1080
+ decoder,
1081
+ touched: 0,
1082
+ requestedAt: 0,
1083
+ flushed: false,
1084
+ };
1085
+ cursor = opened;
967
1086
  // A source that failed to open is opened again by the next request.
968
1087
  decoder.catch(() => {
969
- if (cursors.get(consumerId) === decoder)
970
- cursors.delete(consumerId);
1088
+ if (this.#cursors.get(key) === opened)
1089
+ this.#cursors.delete(key);
971
1090
  });
1091
+ this.#cursors.set(key, cursor);
972
1092
  }
973
- cursors.delete(consumerId);
974
- cursors.set(consumerId, decoder);
975
- for (const [consumer, evicted] of cursors) {
976
- if (cursors.size <= this.#maxCursorsPerSource)
977
- break;
978
- cursors.delete(consumer);
979
- evicted.then((closed) => closed.close(), () => { });
1093
+ cursor.touched = ++this.#touches;
1094
+ cursor.requestedAt = this.#startTicker().elapsed();
1095
+ cursor.flushed = false;
1096
+ this.#enforceBudget();
1097
+ return cursor.decoder;
1098
+ }
1099
+ #enforceBudget() {
1100
+ while (this.#cursors.size > this.#maxCursors) {
1101
+ let oldest;
1102
+ for (const entry of this.#cursors) {
1103
+ const [key, cursor] = entry;
1104
+ if ((this.#busy.get(key) ?? 0) > 0 ||
1105
+ this.#retained.has(retainKey(cursor.sourceId, cursor.consumer)))
1106
+ continue;
1107
+ if (oldest === undefined || cursor.touched < oldest[1].touched)
1108
+ oldest = entry;
1109
+ }
1110
+ if (oldest === undefined) {
1111
+ this.#overBudget += 1;
1112
+ return;
1113
+ }
1114
+ this.#evictions += 1;
1115
+ this.#forget(oldest[0]);
1116
+ }
1117
+ }
1118
+ #forget(key) {
1119
+ const cursor = this.#cursors.get(key);
1120
+ if (cursor === undefined)
1121
+ return;
1122
+ this.#cursors.delete(key);
1123
+ void this.#onSource(cursor.sourceId, async () => {
1124
+ (await cursor.decoder).close();
1125
+ }).catch(() => { });
1126
+ }
1127
+ #startTicker() {
1128
+ if (this.#ticker === undefined) {
1129
+ const ticker = new ActiveStopwatch();
1130
+ ticker.onTick(() => this.#flushIdle(ticker));
1131
+ this.#ticker = ticker;
1132
+ }
1133
+ return this.#ticker;
1134
+ }
1135
+ #flushIdle(ticker) {
1136
+ const now = ticker.elapsed();
1137
+ let waiting = false;
1138
+ for (const [key, cursor] of this.#cursors) {
1139
+ if (cursor.flushed || (this.#busy.get(key) ?? 0) > 0)
1140
+ continue;
1141
+ if (now - cursor.requestedAt < this.#idleMs) {
1142
+ waiting = true;
1143
+ continue;
1144
+ }
1145
+ cursor.flushed = true;
1146
+ this.#idleFlushes += 1;
1147
+ void this.#onSource(cursor.sourceId, async () => {
1148
+ if (!cursor.flushed)
1149
+ return;
1150
+ await (await cursor.decoder).flush();
1151
+ }).catch(() => { });
1152
+ }
1153
+ // Nothing left to flush stops the ticks until the next request.
1154
+ if (!waiting && ![...this.#busy.values()].some((count) => count > 0)) {
1155
+ ticker.dispose();
1156
+ if (this.#ticker === ticker)
1157
+ this.#ticker = undefined;
980
1158
  }
981
- return decoder;
982
1159
  }
983
1160
  async #acquire() {
984
1161
  if (this.#active < this.#maxConcurrency) {
@@ -995,14 +1172,25 @@ export class DecoderRefillCoordinator {
995
1172
  close() {
996
1173
  this.#closed = true;
997
1174
  this.#controller.abort();
1175
+ this.#ticker?.dispose();
1176
+ this.#ticker = undefined;
998
1177
  for (const wake of this.#capacityWaiters.splice(0))
999
1178
  wake();
1000
- for (const cursors of this.#cursors.values())
1001
- for (const decoder of cursors.values())
1002
- decoder.then((opened) => opened.close(), () => { });
1179
+ for (const cursor of this.#cursors.values())
1180
+ cursor.decoder.then((opened) => opened.close(), () => { });
1003
1181
  this.#cursors.clear();
1004
1182
  }
1005
1183
  }
1184
+ /** Decoder cursors a {@link DecoderRefillCoordinator} keeps open by default. */
1185
+ export const DEFAULT_MAX_DECODER_CURSORS = 16;
1186
+ /** Active milliseconds after which an unrequested cursor is flushed by default. */
1187
+ export const DEFAULT_DECODER_IDLE_MS = 2_000;
1188
+ function cursorKey(sourceId, consumer, software) {
1189
+ return `${sourceId}\u0000${consumer}${software ? "\u0000software" : ""}`;
1190
+ }
1191
+ function retainKey(sourceId, consumer) {
1192
+ return `${sourceId}\u0000${consumer}`;
1193
+ }
1006
1194
  function softwareRefusal(sourceId, error) {
1007
1195
  if (error?.code !== "software_decode_unavailable")
1008
1196
  return error;
@@ -1141,7 +1329,8 @@ function validatePositiveByteLimit(value, name) {
1141
1329
  }
1142
1330
  }
1143
1331
  import { abortError, throwIfAborted } from "./abort.js";
1144
- import { activeTimeout } from "./active-clock.js";
1332
+ import { ActiveStopwatch, activeTimeout } from "./active-clock.js";
1333
+ import { decoderStalled } from "./decoder-stall.js";
1145
1334
  import { chromaSitingForStream } from "./chroma-siting.js";
1146
- import { decodeRefusalMessage, PlanarDecodeUnavailableError, } from "./hdr-frames.js";
1147
- import { decodeFailureOf, withSoftwareFallback } from "./decoder-fallback.js";
1335
+ import { DecodeUnavailableError, decodeRefusalMessage, PlanarDecodeUnavailableError, } from "./hdr-frames.js";
1336
+ import { decodeFailureOf, isDecoderFailure, withSoftwareFallback, } from "./decoder-fallback.js";
@@ -1,6 +1,7 @@
1
+ import { type ChromaSiting } from "./chroma-siting.js";
1
2
  import type { AacEncoderProbe, VideoLatencyProbe } from "./export-metrics.js";
2
3
  export type { AacEncoderProbe, AacProbeOutcome, EncoderProbeOutcome, VideoLatencyProbe, } from "./export-metrics.js";
3
- import { type InputAudioTrack, type InputVideoTrack, Quality } from "mediabunny";
4
+ import { EncodedPacketSink, type InputAudioTrack, type InputVideoTrack, Quality } from "mediabunny";
4
5
  import type { AudioDecoderRefillRequest, AudioSpeaker, BrowserDecodedFrame, BrowserAudioBlock, BrowserAudioDecoder, BrowserVideoDecoder, BrowserVideoDecoderOptions, DecoderRefillRequest, OptionalMediaAdapterFactory } from "./media.js";
5
6
  import { type TrackDecodeFacts } from "./hdr-frames.js";
6
7
  import type { ColorMetadata } from "./generated/project-schema.js";
@@ -43,12 +44,15 @@ export declare class MediabunnyVideoDecoder implements BrowserVideoDecoder {
43
44
  /**
44
45
  * The frame presented at the request's time. A decoder failure (Chromium's VA-API decoders report
45
46
  * `EncodingError`) retries once with a software decoder; if that fails, rejects with
46
- * {@link DecodeUnavailableError} when no frame was ever decoded, else with the failure.
47
+ * {@link DecodeUnavailableError} when no frame was ever decoded, else with the failure, and the
48
+ * next request decodes with the acceleration the decoder was opened with. A `device-recovery`
49
+ * request also returns a decoder that fell back to that acceleration.
47
50
  */
48
51
  refill(request: DecoderRefillRequest, signal?: AbortSignal): Promise<BrowserDecodedFrame>;
49
52
  flush(): Promise<void>;
50
53
  close(): void;
51
54
  }
55
+ export declare function streamChromaSiting(track: InputVideoTrack, packets: EncodedPacketSink): Promise<ChromaSiting>;
52
56
  /** The part of `alpha2/wasm` the audio adapter resamples with. */
53
57
  export interface AudioResamplerBinding {
54
58
  readonly AudioResampler: new (sourceRate: number, targetRate: number) => AudioResampler;
@@ -125,19 +129,22 @@ export declare class MediabunnyAudioDecoder implements BrowserAudioDecoder {
125
129
  private constructor();
126
130
  /**
127
131
  * Opens `resource`'s primary audio track, or with `options.stream` the audio track at that
128
- * position among the file's audio tracks in container order (a clip's `audio.stream`). Rejects
129
- * when there is no such track, with `RangeError` for more than {@link MAX_AUDIO_CHANNELS}
130
- * channels or a rate outside 1 kHz to 768 kHz, and with {@link DecodeUnavailableError} when this
131
- * browser cannot decode it.
132
+ * position among the file's audio tracks in container order (a clip's `audio.stream`).
133
+ * `options.stallTimeoutMs` (default 5000) is the active time a refill waits for the next decoded
134
+ * samples. Rejects with code `AUDIO_STREAM_MISSING` when there is no such track, with
135
+ * `RangeError` for more than {@link MAX_AUDIO_CHANNELS} channels, a rate outside 1 kHz to
136
+ * 768 kHz or an invalid stall limit, and with {@link DecodeUnavailableError} when this browser
137
+ * cannot decode it.
132
138
  */
133
139
  static open(sourceId: string, resource: MediabunnyInput, binding: AudioResamplerBinding, options?: {
134
140
  readonly stream?: number;
141
+ readonly stallTimeoutMs?: number;
135
142
  }): Promise<MediabunnyAudioDecoder>;
136
143
  /**
137
144
  * Decodes the interval at `projectSampleRate`, plus two samples each side; silence outside the
138
- * stream. Rejects when closed, for another source or empty interval, on abort, or when the track
139
- * changes format mid-stream; with {@link DecodeUnavailableError} when the browser's decoder
140
- * fails.
145
+ * stream. Rejects when closed, for another source or empty interval, at once on abort, or when
146
+ * the track changes format mid-stream; with {@link DecodeUnavailableError} when the browser's
147
+ * decoder fails, and with `DECODE_STALLED` when it delivers nothing for the stall limit.
141
148
  */
142
149
  refill(request: AudioDecoderRefillRequest, projectSampleRate: number, signal?: AbortSignal): Promise<BrowserAudioBlock>;
143
150
  close(): void;
@@ -218,11 +225,16 @@ export interface VideoTrackEncoding {
218
225
  }
219
226
  /**
220
227
  * The H.264 profiles {@link canEncodeVideoTrack} tries, in order (High, Main, Constrained
221
- * Baseline), at the needed level. Empty for other codecs.
228
+ * Baseline), at the lowest level that holds the frame size at `frameRate` and the bitrate. Empty
229
+ * for other codecs.
222
230
  */
223
231
  export declare function videoEncoderProfiles(codec: "avc" | "hevc" | "vp9" | "av1", options: {
224
232
  readonly width: number;
225
233
  readonly height: number;
234
+ readonly frameRate: {
235
+ readonly num: number;
236
+ readonly den: number;
237
+ };
226
238
  readonly rate: VideoRateControl;
227
239
  }): readonly VideoEncoderProfile[];
228
240
  /**
@@ -233,6 +245,10 @@ export declare function videoEncoderProfiles(codec: "avc" | "hevc" | "vp9" | "av
233
245
  export declare function canEncodeVideoTrack(codec: "avc" | "hevc" | "vp9" | "av1", options: {
234
246
  readonly width: number;
235
247
  readonly height: number;
248
+ readonly frameRate: {
249
+ readonly num: number;
250
+ readonly den: number;
251
+ };
236
252
  readonly rate: VideoRateControl;
237
253
  }): Promise<VideoTrackEncoding | null>;
238
254
  /** Whether this browser has a software encoder for this configuration. */
@@ -344,10 +360,14 @@ export declare class MediabunnySink implements BrowserEncodeSink, BrowserAudioBl
344
360
  writeAudio(block: BrowserAudioBlock): Promise<void>;
345
361
  /**
346
362
  * Finalizes the file and commits a stream destination; idempotent once resolved. Rejects with
347
- * `RESOURCE_LIMIT`, `ENCODE_STALLED`, or the muxer's or destination's error, discarding a stream.
363
+ * `RESOURCE_LIMIT`, `ENCODE_STALLED` (no packet or write for the stall time), the muxer's or
364
+ * destination's error, or the reason of an `abort` that arrived meanwhile, discarding a stream.
348
365
  */
349
366
  finish(): Promise<void>;
350
- /** Discards the output unless already finished; rejects if the destination refuses. */
367
+ /**
368
+ * Discards the output unless already finished, also while `finish` is pending; rejects if the
369
+ * destination refuses.
370
+ */
351
371
  abort(reason: Error): Promise<void>;
352
372
  /** Null until {@link finish} resolves. */
353
373
  get output(): ExportOutput | null;