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/media.js CHANGED
@@ -1,39 +1,17 @@
1
- /**
2
- * How far past the decode cursor a request may be (2 s) and still be reached by decoding forward;
3
- * a request further ahead seeks.
4
- */
1
+ // A request up to 2 s past the decode cursor decodes forward instead of seeking.
5
2
  const MAX_SEQUENTIAL_DECODE_GAP_TICKS = 240000n;
6
- /**
7
- * How much later than a requested time a decoded frame's timestamp may be and still be the frame
8
- * shown at it, for a stream whose time resolution is not known: 0.5 ms and one tick, a millisecond
9
- * time base's slack. It is also the most a stream whose timestamps show no rounding of their own is
10
- * given. The engine's `PRESENTATION_SLACK`.
11
- */
3
+ /** Presentation slack for an unknown time resolution (0.5 ms plus one tick); also the cap. */
12
4
  export const PRESENTATION_SLACK_TICKS = 61n;
13
- /**
14
- * How many of a stream's first packets {@link roundingQuantum} reads the timestamps of: at most
15
- * this many, and none once the packets read hold {@link ROUNDING_SCAN_BYTES}. The engine's
16
- * `ROUNDING_SCAN_FRAMES`.
17
- */
5
+ /** Most leading packets read for {@link roundingQuantum}. Matches the engine. */
18
6
  export const ROUNDING_SCAN_FRAMES = 64;
19
- /**
20
- * The packet bytes (16 MiB) past which no more of a stream's first packets are read for {@link
21
- * roundingQuantum}, as a native host stops. The engine's `ROUNDING_SCAN_BYTES`.
22
- */
7
+ /** Packet bytes (16 MiB) after which no more leading packets are read. */
23
8
  export const ROUNDING_SCAN_BYTES = 16 * 1024 * 1024;
24
9
  /**
25
- * The unit a stream's timestamps are rounded to, as their spacing shows, in units of its time
26
- * resolution; 0 when they show none. The engine's `rounding_quantum`, the binding's
27
- * `roundingQuantum`.
28
- *
29
- * `timestamps` are the stream's first packets' presentation times as whole units of its time
30
- * resolution, in any order: {@link ROUNDING_SCAN_FRAMES} of them, fewer when those before hold
31
- * {@link ROUNDING_SCAN_BYTES}. A frame interval that is not a whole number of a rounding unit comes
32
- * out of the rounding as two lengths a unit apart (29.97 fps in milliseconds is 33 and 34 ms), so
33
- * the unit is the greatest common divisor of the differences between the intervals. Intervals all
34
- * of one length show none, and so do intervals whose differences are as long as half the shortest
35
- * (a variable frame rate, such as 60 and 30 fps frames in an exact 1/90000 time base), and fewer
36
- * than three distinct timestamps. 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, 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.
37
15
  */
38
16
  export function roundingQuantum(timestamps) {
39
17
  for (const timestamp of timestamps)
@@ -62,21 +40,11 @@ export function roundingQuantum(timestamps) {
62
40
  return Number(quantum);
63
41
  }
64
42
  /**
65
- * The frame grid an audio stream's first packet timestamps show at `sampleRate`, for a stream
66
- * whose timestamps are whole units of `1 / timeResolution` seconds; `undefined` when they show
67
- * none to place frames on. The engine's `audio_frame_grid(timestamps, 1, timeResolution,
68
- * sampleRate)`.
69
- *
70
- * `timestamps` are the first packets' presentation times as whole units of the resolution, in any
71
- * order, read as for {@link roundingQuantum}. Their rounding unit is its quantum, or one unit when
72
- * they show none. The grid is one every timestamp is within half a unit of: of the whole-sample
73
- * periods within a unit over their count of their span over it, the one that leaves the most room,
74
- * the shortest of those that leave as much; and of the anchors it leaves, the middle one, rounded
75
- * to a sample. There is none when half the unit is under a sample (a time base of the sample rate),
76
- * when fewer than three distinct timestamps are given or no grid holds them all (frames of several
77
- * lengths, a missing packet), when no period longer than twice the trimmed tolerance holds them, or
78
- * when the resolution or the rate is not a positive integer. Throws `RangeError` for a timestamp
79
- * that is not a safe integer.
43
+ * The frame grid an audio stream's first packet timestamps show at `sampleRate`, for timestamps in
44
+ * whole units of `1 / timeResolution` seconds. Matches the engine's `audio_frame_grid`. Returns
45
+ * `undefined` when the timestamps do not fix a grid (too few, mixed frame lengths, a missing
46
+ * packet, sub-sample rounding) or the resolution or rate is not a positive integer.
47
+ * Throws `RangeError` for a timestamp that is not a safe integer.
80
48
  */
81
49
  export function audioFrameGrid(timestamps, timeResolution, sampleRate) {
82
50
  if (!Number.isSafeInteger(timeResolution) ||
@@ -134,10 +102,9 @@ export function audioFrameGrid(timestamps, timeResolution, sampleRate) {
134
102
  };
135
103
  }
136
104
  /**
137
- * Where a frame of `frames` samples whose timestamp puts it at source sample `at` starts: on
138
- * `grid` when its timestamp is within the grid's rounding of it, otherwise at `at`. A frame
139
- * shorter than the period is first taken as the end of one a decoder dropped the start of (Opus's
140
- * pre-skip): it ends on the grid. The engine's `AudioFrameGrid::place`.
105
+ * Where a frame of `frames` samples with timestamp sample `at` starts: on `grid` when within its
106
+ * tolerance, otherwise at `at`. A short frame is taken as start-trimmed (Opus pre-skip), so its end
107
+ * goes on the grid.
141
108
  */
142
109
  export function placeOnAudioFrameGrid(grid, at, frames) {
143
110
  const shiftOnto = (position) => {
@@ -154,21 +121,9 @@ export function placeOnAudioFrameGrid(grid, at, frames) {
154
121
  }
155
122
  /**
156
123
  * How much later than a requested time a decoded frame's timestamp may be and still be the frame
157
- * shown at it, for a stream whose timestamps are whole multiples of `1 / timeResolution` seconds
158
- * (mediabunny's `getTimeResolution()`) rounded to `quantum` of those units ({@link
159
- * roundingQuantum}; 0 for none shown). The engine's `presentation_slack`, the binding's
160
- * `presentationSlackTicks(1, timeResolution, quantum)`.
161
- *
162
- * A stream whose timestamps show a rounding is given half of it, rounded up to a tick, and one tick
163
- * more, however coarse (61 ticks for milliseconds, 101 for 29.97 fps in 1/600). One that shows none
164
- * is given half its unit, rounded up to a tick, and one tick more, at most {@link
165
- * PRESENTATION_SLACK_TICKS}: its frames are exact in the time base. A resolution not known is
166
- * {@link PRESENTATION_SLACK_TICKS}.
167
- *
168
- * The frame shown at a time is the last one at or before `time + slack`: a timestamp is rounded to
169
- * its time base (Matroska's millisecond) and to the nearest tick, while a project frame's time is
170
- * floored, so the frame truly shown can carry a timestamp a few ticks late. A native host decides
171
- * the same way.
124
+ * shown at it, in ticks: half the timestamp rounding unit, rounded up, plus one tick.
125
+ * `timeResolution` is mediabunny's `getTimeResolution()`, `quantum` from {@link roundingQuantum}
126
+ * (0 for none). Unknown resolutions get {@link PRESENTATION_SLACK_TICKS}.
172
127
  */
173
128
  export function presentationSlackTicks(timeResolution, quantum = 0) {
174
129
  if (timeResolution === undefined ||
@@ -187,35 +142,17 @@ export function presentationSlackTicks(timeResolution, quantum = 0) {
187
142
  : PRESENTATION_SLACK_TICKS;
188
143
  }
189
144
  const DEFAULT_MAX_DECODED_FRAME_BYTES = 64 * 1024 * 1024;
190
- /**
191
- * Decoded frames the reverse-window cache keeps at most: the frame presented at the last request
192
- * and the one after it.
193
- *
194
- * Each holds one of the decoder's output surfaces, and a hardware decoder has a fixed pool of them.
195
- * Chromium's Windows decoder allocates its DPB size plus six, and the DPB can occupy all of its own
196
- * share: a stream without a VUI is reordered by the whole DPB, and long-term references stay in it
197
- * for a whole GOP. That leaves about five surfaces for everything outside the decoder; a cache of
198
- * eight holds them all, and the decoder stops producing output every few frames.
199
- */
145
+ // The presented frame and the one after. Each holds a hardware decoder surface from a small fixed
146
+ // pool, and holding more stalls some Windows decoders.
200
147
  const DEFAULT_MAX_CACHED_FRAMES = 2;
201
- /**
202
- * The fewest frames the cache works with, and the fewest its byte limit evicts down to: the frame
203
- * at or before a time and the one after it, which proves that frame is still presented.
204
- */
205
148
  const MIN_CACHED_FRAMES = 2;
206
- /** How long a decoder may produce nothing before the refill gives up. */
207
149
  const DEFAULT_STALL_TIMEOUT_MS = 5_000;
208
- /**
209
- * The longest `stallTimeoutMs` a decoder takes, about 24.8 days: timers hold their delay in a
210
- * signed 32-bit integer, and a longer one fires at once (Node) or wraps (browsers), which would
211
- * fail every read as a stall.
212
- */
150
+ /** About 24.8 days; timers misfire past a signed 32-bit delay. */
213
151
  export const MAX_STALL_TIMEOUT_MS = 2_147_483_647;
214
152
  /**
215
- * Throws `RangeError` unless `value` is a whole number of milliseconds from 1 to
216
- * {@link MAX_STALL_TIMEOUT_MS}.
153
+ * Throws `RangeError` unless `value` is whole milliseconds in 1..{@link MAX_STALL_TIMEOUT_MS}.
217
154
  *
218
- * @internal Shared by the decoder adapters.
155
+ * @internal
219
156
  */
220
157
  export function validateStallTimeout(value) {
221
158
  if (!Number.isSafeInteger(value) ||
@@ -223,10 +160,7 @@ export function validateStallTimeout(value) {
223
160
  value > MAX_STALL_TIMEOUT_MS)
224
161
  throw new RangeError(`stallTimeoutMs must be a whole number of milliseconds from 1 to ${MAX_STALL_TIMEOUT_MS}`);
225
162
  }
226
- /**
227
- * The consumer that owns a decode cursor: the clip, or one composition step of it (`readerId`)
228
- * that reads a source on its own. A decoder shared by two of them would seek on every frame.
229
- */
163
+ /** The owner of a decode cursor: a clip, or a composition step that reads the source itself. */
230
164
  export function decoderConsumerId(clipId, readerId) {
231
165
  return readerId ? `${clipId}\u0000${readerId}` : clipId;
232
166
  }
@@ -235,17 +169,11 @@ export const UPRIGHT = Object.freeze({
235
169
  rotationDegrees: 0,
236
170
  mirror: false,
237
171
  });
238
- /** Bytes this reads before it gives up on a container's header. */
239
172
  const MAX_HEADER_SCAN_BYTES = 64 * 1024 * 1024;
240
173
  /**
241
- * How the container says track `trackId`'s pictures are shown upright, read as native decoding
242
- * (FFmpeg) reads it, mirror included: an MP4 or QuickTime track's `tkhd` matrix composed with the
243
- * movie's `mvhd` matrix, or a Matroska or WebM track's rectangular projection pose. `trackId` is
244
- * the `tkhd` track ID or the Matroska `TrackNumber`, which mediabunny reports as `InputTrack.id`. A
245
- * matrix that turns by other than a multiple of 90 degrees is shown upright, as natively.
246
- *
247
- * Resolves to `undefined` for any other container, or one whose header this cannot find; demuxers
248
- * report a rotation but not a mirror, so a caller then has only the rotation its demuxer reports.
174
+ * Reads track `trackId`'s orientation, mirror included, from MP4/QuickTime `tkhd`/`mvhd` matrices
175
+ * or the Matroska projection pose, as `FFmpeg` does. `trackId` is mediabunny's `InputTrack.id`.
176
+ * Resolves to `undefined` for other containers or when the header is not found.
249
177
  */
250
178
  export async function readVideoOrientation(container, trackId) {
251
179
  const reader = new ByteReader(container);
@@ -259,7 +187,6 @@ export async function readVideoOrientation(container, trackId) {
259
187
  }
260
188
  return undefined;
261
189
  }
262
- /** Ranged reads over a Blob or bytes in memory. */
263
190
  class ByteReader {
264
191
  #container;
265
192
  size;
@@ -314,7 +241,6 @@ async function child(reader, parent, type) {
314
241
  return box;
315
242
  return undefined;
316
243
  }
317
- /** The 2x2 part of the 3x3 matrix a `mvhd` or `tkhd` box stores at `offset`. */
318
244
  async function boxMatrix(reader, box, offset) {
319
245
  const bytes = await reader.read(box.start + offset, 20);
320
246
  if (bytes.length < 20 || box.start + offset + 36 > box.end)
@@ -333,8 +259,7 @@ async function isobmffOrientation(reader, trackId) {
333
259
  for await (const box of isobmffBoxes(reader, moov.start, moov.end)) {
334
260
  if (box.type === "mvhd") {
335
261
  const version = (await reader.read(box.start, 1))[0];
336
- // After version and flags: creation and modification time, timescale, duration, rate, volume,
337
- // and ten reserved bytes.
262
+ // Skips creation and modification time, timescale, duration, rate, volume, 10 reserved bytes.
338
263
  movie = (await boxMatrix(reader, box, version === 1 ? 48 : 36)) ?? movie;
339
264
  }
340
265
  else if (box.type === "trak") {
@@ -347,8 +272,7 @@ async function isobmffOrientation(reader, trackId) {
347
272
  const version = header[0];
348
273
  if (readU32(header, version === 1 ? 20 : 12) !== trackId)
349
274
  continue;
350
- // After the track ID: a reserved word, duration, eight reserved bytes, layer, alternate
351
- // group, volume, and two reserved bytes.
275
+ // Skips reserved, duration, 8 reserved, layer, alternate group, volume, 2 reserved bytes.
352
276
  track = await boxMatrix(reader, tkhd, version === 1 ? 52 : 40);
353
277
  }
354
278
  }
@@ -364,11 +288,7 @@ async function isobmffOrientation(reader, trackId) {
364
288
  c * f + d * h,
365
289
  ]);
366
290
  }
367
- /**
368
- * The orientation a display matrix shows, as `av_display_rotation_get` reads it. A matrix that
369
- * mirrors (its determinant is negative) is read as FFmpeg reads one: a rotation followed by a flip
370
- * of its first column, which is a mirror before the opposite rotation.
371
- */
291
+ /** Reads a display matrix as `av_display_rotation_get` does, a mirror as a flipped first column. */
372
292
  function matrixOrientation(matrix) {
373
293
  const [b, d] = [matrix[1], matrix[3]];
374
294
  const mirror = matrix[0] * d - b * matrix[2] < 0;
@@ -380,10 +300,6 @@ function matrixOrientation(matrix) {
380
300
  return UPRIGHT;
381
301
  return rotationOrientation(mirror ? counterClockwise : -counterClockwise, mirror);
382
302
  }
383
- /**
384
- * A clockwise angle that is a multiple of 90 degrees (within half a degree), as an orientation; any
385
- * other angle is shown upright.
386
- */
387
303
  function rotationOrientation(clockwise, mirror) {
388
304
  const normalized = ((clockwise % 360) + 360) % 360;
389
305
  const quarter = Math.round(normalized / 90) % 4;
@@ -412,10 +328,7 @@ async function* ebmlElements(reader, start, end) {
412
328
  at = elementEnd;
413
329
  }
414
330
  }
415
- /**
416
- * A variable-length integer at `at`: an ID keeps its length marker; a size of all ones is unknown
417
- * (`value` undefined).
418
- */
331
+ /** IDs keep their length marker; an all-ones size is unknown (`value` undefined). */
419
332
  function vint(bytes, at, keepMarker) {
420
333
  const first = bytes[at];
421
334
  if (first === undefined || first === 0)
@@ -465,10 +378,7 @@ const EBML = {
465
378
  pitch: 0x7674,
466
379
  roll: 0x7675,
467
380
  };
468
- /**
469
- * The track entries of a Matroska file's first `Tracks` element, each with its `TrackNumber`;
470
- * none when the file has no `Tracks` before its first cluster.
471
- */
381
+ /** Track entries of the first `Tracks` element before the first cluster. */
472
382
  async function* matroskaTrackEntries(reader) {
473
383
  for await (const top of ebmlElements(reader, 0, reader.size)) {
474
384
  if (top.id !== EBML.segment)
@@ -491,11 +401,7 @@ async function* matroskaTrackEntries(reader) {
491
401
  }
492
402
  }
493
403
  }
494
- /**
495
- * A Matroska track's orientation, as FFmpeg reads a rectangular projection's pose: a roll is a
496
- * counter-clockwise turn, and a yaw of 180 degrees mirrors. Any other pose is a spherical one,
497
- * shown upright.
498
- */
404
+ /** FFmpeg reads a roll as a counter-clockwise turn and a 180 degree yaw as a mirror. */
499
405
  async function matroskaOrientation(reader, trackId) {
500
406
  for await (const { number, entry } of matroskaTrackEntries(reader)) {
501
407
  if (number !== trackId)
@@ -531,13 +437,8 @@ async function matroskaOrientation(reader, trackId) {
531
437
  return undefined;
532
438
  }
533
439
  /**
534
- * The `CodecDelay` a Matroska or WebM file declares for track `trackId`, in nanoseconds: how far
535
- * each of the track's block times is after the time its samples are presented at. The
536
- * specification has a reader subtract it from every block time, and native decoding (FFmpeg) does,
537
- * rounded to the track's time base; mediabunny does not. `trackId` is the Matroska `TrackNumber`,
538
- * which mediabunny reports as `InputTrack.id`.
539
- *
540
- * Resolves to 0 for a track that declares none, and for any other container.
440
+ * 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.
541
442
  */
542
443
  export async function readMatroskaCodecDelay(container, trackId) {
543
444
  const reader = new ByteReader(container);
@@ -554,10 +455,7 @@ export async function readMatroskaCodecDelay(container, trackId) {
554
455
  }
555
456
  return 0;
556
457
  }
557
- /**
558
- * Most channels a decoded {@link BrowserAudioBlock} carries: a 22.2 layout's 24, the most of any
559
- * layout `FFmpeg` names. A source with more is refused by browser and native hosts alike.
560
- */
458
+ /** A 22.2 layout's 24; sources with more are refused. */
561
459
  export const MAX_AUDIO_CHANNELS = 24;
562
460
  /** WebCodecs adapter for elementary chunks supplied by any demuxer. */
563
461
  export class WebCodecsVideoDecoder {
@@ -566,46 +464,27 @@ export class WebCodecsVideoDecoder {
566
464
  #decoder;
567
465
  #iterator;
568
466
  #ready = [];
569
- /**
570
- * Decoded frames held back until a frame no earlier than all of them arrives: see {@link
571
- * #arrive}.
572
- */
573
467
  #arriving = [];
574
- /** Whether this codec's streams can output frames out of presentation order. */
575
468
  #reorders;
576
- /** Where the stream's chroma samples sit, read from its parameter sets. */
577
469
  #chromaSiting;
578
- /** Whether the configuration had no parameter sets, so the first key chunk is read for them. */
579
470
  #sitingFromKeyChunk;
580
471
  #outputWaiters = [];
581
472
  #generation;
582
- /**
583
- * The last time the decode cursor answered: the frames up to the one after it have been read. A
584
- * request at or before it, or far past it, seeks.
585
- */
586
473
  #cursorTicks;
587
- /**
588
- * When the stream's first frame is presented, once a seek has shown that the stream starts after
589
- * the time it sought.
590
- */
591
474
  #leadTicks;
592
- /** No frame has been taken since the cursor last sought. */
593
475
  #firstSinceSeek = false;
594
476
  #decoderError;
595
477
  #cache;
596
478
  #maxReadyFrameBytes;
597
479
  #stallTimeoutMs;
598
- /**
599
- * How late a frame may be and still be the one shown at a time ({@link presentationSlackTicks}).
600
- */
601
480
  #slack;
602
481
  #readyBytes = 0;
603
482
  #activeTargetTicks;
604
483
  #reverseCacheHits = 0;
605
- /**
606
- * Throws `RangeError` when an option is not a positive safe integer, `maxCachedFrames` is below
607
- * 2, or `stallTimeoutMs` is above {@link MAX_STALL_TIMEOUT_MS}.
608
- */
484
+ #software;
485
+ #softwareFallback;
486
+ #decodedAny = false;
487
+ /** Throws `RangeError` for invalid options (see {@link BrowserVideoDecoderOptions}). */
609
488
  constructor(sourceId, source, options = {}) {
610
489
  this.#sourceId = sourceId;
611
490
  this.#source = source;
@@ -625,15 +504,16 @@ export class WebCodecsVideoDecoder {
625
504
  this.#reorders = reordersOutput(source.config.codec);
626
505
  this.#chromaSiting = chromaSitingForStream(source.config.codec, source.config.description);
627
506
  this.#sitingFromKeyChunk = source.config.description === undefined;
507
+ this.#software = source.config.hardwareAcceleration === "prefer-software";
508
+ }
509
+ /** Why decoding moved to software after the browser's first pick failed, if it did. */
510
+ get softwareFallback() {
511
+ return this.#softwareFallback;
628
512
  }
629
- /** Bytes the frame cache holds. */
630
513
  get cachedFrameBytes() {
631
514
  return this.#cache.bytes;
632
515
  }
633
- /**
634
- * Reads the chroma siting from the first key chunk of a stream whose configuration carries no
635
- * parameter sets (Annex B, AV1 in MP4), which repeats them there.
636
- */
516
+ /** Annex B and AV1-in-MP4 streams carry their parameter sets in the first key chunk. */
637
517
  #readSitingFrom(chunk) {
638
518
  if (!this.#sitingFromKeyChunk || chunk.type !== "key")
639
519
  return;
@@ -644,27 +524,48 @@ export class WebCodecsVideoDecoder {
644
524
  chunk.copyTo(bytes);
645
525
  this.#chromaSiting = chromaSitingForStream(this.#source.config.codec, undefined, bytes);
646
526
  }
647
- /** Requests answered from the cache without decoding. */
648
527
  get reverseCacheHits() {
649
528
  return this.#reverseCacheHits;
650
529
  }
530
+ /**
531
+ * 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.
533
+ */
651
534
  async refill(request, signal = new AbortController().signal) {
652
535
  if (request.sourceId !== this.#sourceId) {
653
536
  throw new Error(`decoder source mismatch: ${request.sourceId}`);
654
537
  }
538
+ try {
539
+ const frame = await withSoftwareFallback(() => this.#refillOnce(request, signal), this.#software || signal.aborted
540
+ ? undefined
541
+ : (cause) => {
542
+ this.#software = true;
543
+ this.#softwareFallback = `${cause.name}: ${cause.message}`;
544
+ this.#resetCursor();
545
+ this.#cache.clear();
546
+ return Promise.resolve();
547
+ });
548
+ this.#decodedAny = true;
549
+ return frame;
550
+ }
551
+ catch (error) {
552
+ if (this.#decodedAny || signal.aborted)
553
+ throw error;
554
+ throw decodeFailureOf(error, this.#sourceId, { kind: "video", codec: this.#source.config.codec }, false);
555
+ }
556
+ }
557
+ async #refillOnce(request, signal) {
655
558
  throwIfAborted(signal);
656
559
  if (this.#generation !== undefined &&
657
560
  this.#generation !== request.generation) {
658
561
  this.#resetCursor();
659
562
  this.#cache.clear();
660
563
  }
661
- // Requests before the stream's first frame all present that frame.
662
564
  const target = this.#leadTicks !== undefined && request.mediaTimeTicks < this.#leadTicks
663
565
  ? this.#leadTicks
664
566
  : request.mediaTimeTicks;
665
567
  const cached = this.#cache.presentedAt(target);
666
568
  if (cached !== undefined) {
667
- // A hit moves no cursor: the decode is still where it last answered.
668
569
  this.#reverseCacheHits += 1;
669
570
  return {
670
571
  sourceId: this.#sourceId,
@@ -687,8 +588,7 @@ export class WebCodecsVideoDecoder {
687
588
  if (mustSeek) {
688
589
  this.#resetCursor();
689
590
  this.#cache.clear();
690
- // From the keyframe at or before the deadline, since the frame shown may lie up to the slack
691
- // later.
591
+ // The shown frame may be up to the slack late.
692
592
  const chunks = this.#source.chunksFrom(target + this.#slack, signal);
693
593
  this.#iterator = chunks[Symbol.asyncIterator]();
694
594
  this.#generation = request.generation;
@@ -700,8 +600,7 @@ export class WebCodecsVideoDecoder {
700
600
  return await this.#decodeTo(request, target, signal);
701
601
  }
702
602
  catch (error) {
703
- // A failed read may have consumed a chunk no decoder saw, and a broken decoder stays broken:
704
- // the next request seeks from a keyframe.
603
+ // A failed read may have consumed a chunk, so the next request seeks.
705
604
  this.#resetCursor();
706
605
  this.#cache.clear();
707
606
  throw error;
@@ -735,8 +634,6 @@ export class WebCodecsVideoDecoder {
735
634
  this.#iterator = undefined;
736
635
  await this.#flushAtEnd(decoder, signal);
737
636
  const finalFrame = this.#takeReady(target, true);
738
- // Unless frames after the target are still queued, the window's newest frame is the
739
- // stream's last.
740
637
  if (this.#ready.length === 0)
741
638
  this.#cache.markEnd();
742
639
  if (finalFrame !== undefined) {
@@ -757,8 +654,7 @@ export class WebCodecsVideoDecoder {
757
654
  decoder.decode(next.value);
758
655
  if (decoder.decodeQueueSize > 8) {
759
656
  if (!(await this.#waitForOutput(signal))) {
760
- // Output stopped with every surface held. Give back the cache's frames except the one the
761
- // target may need; closing queued frames would answer with a later frame.
657
+ // Every surface is held. Closing queued frames would answer with a later frame.
762
658
  if (this.#cache.releaseAllButPresentedAt(target) === 0)
763
659
  throw new Error(`video decoder ${this.#sourceId} stalled: no output for ` +
764
660
  `${this.#stallTimeoutMs} ms with ${decoder.decodeQueueSize} chunks queued; ` +
@@ -807,17 +703,15 @@ export class WebCodecsVideoDecoder {
807
703
  },
808
704
  });
809
705
  decoder.addEventListener("dequeue", () => this.#notifyOutput());
810
- decoder.configure(this.#source.config);
706
+ decoder.configure(this.#software
707
+ ? { ...this.#source.config, hardwareAcceleration: "prefer-software" }
708
+ : this.#source.config);
811
709
  this.#decoder = decoder;
812
710
  return decoder;
813
711
  }
814
712
  /**
815
- * Takes a decoded frame in. WebCodecs outputs in presentation order, but Safari 16.4 to 26.3
816
- * outputs H.264 B-frames in decode order, after the later reference frame that decides the frame
817
- * before them. A codec that can reorder therefore holds frames back, sorted, until one arrives
818
- * that is no earlier than all of them: that one cannot be a B-frame of the ones held, so every
819
- * earlier time is complete. It costs one frame of lookahead, and one more decoder surface, only
820
- * for codecs with B-frames.
713
+ * Safari 16.4 to 26.3 outputs H.264 B-frames in decode order, so reordering codecs hold frames
714
+ * back, sorted, until one arrives that is no earlier than all of them.
821
715
  */
822
716
  #arrive(frame) {
823
717
  if (!this.#reorders) {
@@ -830,10 +724,6 @@ export class WebCodecsVideoDecoder {
830
724
  const at = this.#arriving.findIndex((held) => held.timestamp > frame.timestamp);
831
725
  this.#arriving.splice(at < 0 ? this.#arriving.length : at, 0, frame);
832
726
  }
833
- /**
834
- * Every frame held back goes to the ready queue: the stream ended, or a later frame proved them
835
- * complete.
836
- */
837
727
  #releaseArriving() {
838
728
  for (const frame of this.#arriving.splice(0))
839
729
  this.#admit(frame);
@@ -857,8 +747,7 @@ export class WebCodecsVideoDecoder {
857
747
  }
858
748
  }
859
749
  #resetCursor() {
860
- // A generator's return can be queued behind a pending next that never settles. Detach it so
861
- // cancellation never blocks the next generation.
750
+ // A return can queue behind a next that never settles; detach so cancellation never blocks.
862
751
  const closing = this.#iterator?.return?.();
863
752
  void closing?.catch(() => { });
864
753
  this.#iterator = undefined;
@@ -874,14 +763,14 @@ export class WebCodecsVideoDecoder {
874
763
  this.#activeTargetTicks = undefined;
875
764
  }
876
765
  async #flushAtEnd(decoder, signal) {
877
- let timer;
766
+ const settled = new AbortController();
878
767
  let abort;
879
768
  try {
880
769
  throwIfAborted(signal);
881
770
  const interrupted = new Promise((_, reject) => {
882
771
  abort = () => reject(abortError(signal));
883
772
  signal.addEventListener("abort", abort, { once: true });
884
- timer = setTimeout(() => reject(new Error(`video decoder ${this.#sourceId} stalled during EOF flush after ${this.#stallTimeoutMs} ms`)), this.#stallTimeoutMs);
773
+ void activeTimeout(this.#stallTimeoutMs, settled.signal).then(() => reject(new Error(`video decoder ${this.#sourceId} stalled during EOF flush after ${this.#stallTimeoutMs} ms`)));
885
774
  });
886
775
  await Promise.race([decoder.flush(), interrupted]);
887
776
  this.#releaseArriving();
@@ -890,26 +779,19 @@ export class WebCodecsVideoDecoder {
890
779
  throw this.#decoderError;
891
780
  }
892
781
  catch (error) {
893
- // Closing rejects the native flush; Promise.race already observes that late rejection.
894
- // Callbacks also check decoder identity before retaining.
782
+ // Closing rejects the native flush, which Promise.race already observes.
895
783
  this.close();
896
784
  throw error;
897
785
  }
898
786
  finally {
899
- clearTimeout(timer);
787
+ settled.abort();
900
788
  if (abort !== undefined)
901
789
  signal.removeEventListener("abort", abort);
902
790
  }
903
791
  }
904
792
  /**
905
- * The decoded frame presented at `targetTicks`: the last one at or before its deadline, the
906
- * target plus the slack. Deciding that takes the frame after, which stays queued for the next
907
- * request. Frames before the target pass into the reverse window.
908
- *
909
- * `ended` answers with the last frame once the stream has no frame after it. A stream whose first
910
- * frame is after the target answers with that frame, and is known to start there from then on:
911
- * the first frame a seek decodes is the stream's first when it is later than the time sought,
912
- * since a source's chunks start at the keyframe at or before that time.
793
+ * The last frame at or before the target plus the slack; deciding it needs the next frame, which
794
+ * stays queued. A first frame after a seek that is later than the target is the stream's start.
913
795
  */
914
796
  #takeReady(targetTicks, ended = false) {
915
797
  const deadline = targetTicks + this.#slack;
@@ -933,7 +815,6 @@ export class WebCodecsVideoDecoder {
933
815
  }
934
816
  return ended ? this.#cache.presentedAt(targetTicks, true) : undefined;
935
817
  }
936
- /** Moves the first queued frame into the reverse window and returns it. */
937
818
  #takeFront() {
938
819
  const frame = this.#ready.shift();
939
820
  if (frame !== undefined) {
@@ -954,11 +835,11 @@ export class WebCodecsVideoDecoder {
954
835
  for (const wake of this.#outputWaiters.splice(0))
955
836
  wake();
956
837
  }
957
- /** Resolves true on output, false when none arrives within the stall timeout. */
958
838
  #waitForOutput(signal) {
959
839
  return new Promise((resolve, reject) => {
840
+ const timer = new AbortController();
960
841
  const settle = () => {
961
- clearTimeout(timer);
842
+ timer.abort();
962
843
  signal.removeEventListener("abort", abort);
963
844
  this.#outputWaiters = this.#outputWaiters.filter((candidate) => candidate !== wake);
964
845
  };
@@ -970,21 +851,19 @@ export class WebCodecsVideoDecoder {
970
851
  settle();
971
852
  reject(abortError(signal));
972
853
  };
973
- const timer = setTimeout(() => {
854
+ void activeTimeout(this.#stallTimeoutMs, timer.signal).then(() => {
974
855
  settle();
975
856
  resolve(false);
976
- }, this.#stallTimeoutMs);
857
+ });
977
858
  this.#outputWaiters.push(wake);
978
859
  signal.addEventListener("abort", abort, { once: true });
979
860
  });
980
861
  }
981
862
  }
982
863
  /**
983
- * Runs refills against decoders it opens: one per source and consumer
984
- * ({@link DecoderRefillRequest.consumerId}), so overlapping clips of one source each decode
985
- * forward from where they were. Refills of one source run one at a time, at most `maxConcurrency`
986
- * at once, delivering each frame through `deliver`. A newer generation aborts the requests in
987
- * flight; a frame decoded for an older one is closed instead of delivered.
864
+ * Runs refills on decoders it opens, one per source and consumer (plus one for software), with
865
+ * 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.
988
867
  */
989
868
  export class DecoderRefillCoordinator {
990
869
  #open;
@@ -996,13 +875,11 @@ export class DecoderRefillCoordinator {
996
875
  #active = 0;
997
876
  #capacityWaiters = [];
998
877
  #sourceTails = new Map();
999
- /** Each source's decoders by consumer, least recently used first. */
1000
878
  #cursors = new Map();
1001
879
  #closed = false;
1002
880
  /**
1003
- * `open` makes a decoder for a source, called once per consumer that reads it; it may reject for
1004
- * a source it cannot decode, which rejects that refill. Throws `RangeError` when an option is not
1005
- * a positive safe integer.
881
+ * A rejected `open` rejects that refill; `software_decode_unavailable` becomes
882
+ * `PlanarDecodeUnavailableError`. Throws `RangeError` for invalid options.
1006
883
  */
1007
884
  constructor(open, deliver, options = {}) {
1008
885
  const maxConcurrency = options.maxConcurrency ?? 2;
@@ -1019,16 +896,15 @@ export class DecoderRefillCoordinator {
1019
896
  this.#maxConcurrency = maxConcurrency;
1020
897
  this.#maxCursorsPerSource = maxCursorsPerSource;
1021
898
  }
1022
- /** Aborts the requests in flight and returns the new generation number for later requests. */
899
+ /** Aborts requests in flight and returns the new generation number. */
1023
900
  beginGeneration() {
1024
901
  this.#controller.abort(new DOMException("Superseded", "AbortError"));
1025
902
  this.#controller = new AbortController();
1026
903
  return ++this.#generation;
1027
904
  }
1028
905
  /**
1029
- * Decodes `request` and delivers its frame. Resolves without delivering when the request's
1030
- * generation is already superseded; rejects with the decoder's, the delivery's, or the abort's
1031
- * error, and once the coordinator is closed.
906
+ * Resolves without delivering when the request's generation is superseded; rejects with the
907
+ * decoder's, delivery's or abort's error, and once closed.
1032
908
  */
1033
909
  async refill(request) {
1034
910
  if (request.generation < this.#generation)
@@ -1058,31 +934,36 @@ export class DecoderRefillCoordinator {
1058
934
  if (request.generation !== this.#generation)
1059
935
  return;
1060
936
  throwIfAborted(this.#controller.signal);
1061
- const decoder = await this.#cursor(request.sourceId, request.consumerId ?? "");
937
+ const software = request.decode === "software";
938
+ const decoder = await this.#cursor(request.sourceId, request.consumerId ?? "", software ? "software" : "default");
1062
939
  const frame = await decoder.refill(request, this.#controller.signal);
1063
940
  if (frame.generation !== this.#generation) {
1064
941
  frame.frame.close();
1065
942
  return;
1066
943
  }
1067
- await this.#deliver(frame);
944
+ await this.#deliver(software ? { ...frame, decode: "software" } : frame);
1068
945
  }
1069
946
  finally {
1070
947
  this.#release();
1071
948
  }
1072
949
  }
1073
- /**
1074
- * The consumer's decoder for a source, opened on first use. Runs inside the source's queue, so
1075
- * the decoder it closes past the limit is not decoding.
1076
- */
1077
- async #cursor(sourceId, consumerId) {
950
+ // Runs inside the source's queue, so a decoder closed past the limit is not decoding.
951
+ async #cursor(sourceId, consumer, decode) {
1078
952
  let cursors = this.#cursors.get(sourceId);
1079
953
  if (cursors === undefined) {
1080
954
  cursors = new Map();
1081
955
  this.#cursors.set(sourceId, cursors);
1082
956
  }
957
+ const consumerId = decode === "software" ? `${consumer}\u0000software` : consumer;
1083
958
  let decoder = cursors.get(consumerId);
1084
959
  if (decoder === undefined) {
1085
- decoder = Promise.resolve().then(() => this.#open(sourceId));
960
+ decoder = Promise.resolve()
961
+ .then(() => this.#open(sourceId, { decode }))
962
+ .catch((error) => {
963
+ throw decode === "software"
964
+ ? softwareRefusal(sourceId, error)
965
+ : error;
966
+ });
1086
967
  // A source that failed to open is opened again by the next request.
1087
968
  decoder.catch(() => {
1088
969
  if (cursors.get(consumerId) === decoder)
@@ -1111,7 +992,6 @@ export class DecoderRefillCoordinator {
1111
992
  this.#active -= 1;
1112
993
  this.#capacityWaiters.shift()?.();
1113
994
  }
1114
- /** Aborts every request in flight and closes every decoder it opened. */
1115
995
  close() {
1116
996
  this.#closed = true;
1117
997
  this.#controller.abort();
@@ -1123,14 +1003,20 @@ export class DecoderRefillCoordinator {
1123
1003
  this.#cursors.clear();
1124
1004
  }
1125
1005
  }
1006
+ function softwareRefusal(sourceId, error) {
1007
+ if (error?.code !== "software_decode_unavailable")
1008
+ return error;
1009
+ const facts = {
1010
+ kind: "video",
1011
+ codec: null,
1012
+ softwareDecoder: "none",
1013
+ browserError: error instanceof Error ? error.message : String(error),
1014
+ };
1015
+ return new PlanarDecodeUnavailableError(decodeRefusalMessage(sourceId, facts), facts, { cause: error });
1016
+ }
1126
1017
  /**
1127
- * The tick nearest a WebCodecs microsecond timestamp.
1128
- *
1129
- * A tick is 1/120 000 s (8.33 microseconds), so a frame boundary that is a whole tick arrives from
1130
- * the container rounded to the microsecond: 30 fps frame one is 33 333 microseconds, or 3999.96
1131
- * ticks. Flooring would make it 3999, below its own tick, so a request for 4000 would skip it.
1132
- * Every decoder path converts through this one function, so a frame's tick never depends on which
1133
- * path produced it.
1018
+ * The tick nearest a WebCodecs microsecond timestamp. Rounds, not floors, because tick boundaries
1019
+ * arrive just below themselves (30 fps frame one is 3999.96 ticks).
1134
1020
  */
1135
1021
  export function microsecondsToTicks(microseconds) {
1136
1022
  const scaled = BigInt(Math.round(microseconds)) * 120000n;
@@ -1138,26 +1024,6 @@ export function microsecondsToTicks(microseconds) {
1138
1024
  const half = scaled < 0n ? -500000n : 500000n;
1139
1025
  return (scaled + half) / 1000000n;
1140
1026
  }
1141
- function throwIfAborted(signal) {
1142
- if (signal.aborted)
1143
- throw abortError(signal);
1144
- }
1145
- /**
1146
- * The reason a signal carries, as an `Error` a caller can reject with.
1147
- *
1148
- * `AbortSignal.reason` is typed `any` and a caller may abort with a value that is not an `Error`,
1149
- * which would reject without a stack. An `Error` passes through untouched, so an `AbortError` keeps
1150
- * its name.
1151
- */
1152
- function abortError(signal) {
1153
- const reason = signal.reason;
1154
- if (reason instanceof Error)
1155
- return reason;
1156
- // A string reason is the only non-Error form that carries readable text.
1157
- if (typeof reason === "string")
1158
- return new DOMException(reason, "AbortError");
1159
- return new DOMException("Aborted", "AbortError");
1160
- }
1161
1027
  async function nextOrAbort(iterator, signal) {
1162
1028
  let abort;
1163
1029
  const aborted = new Promise((_, reject) => {
@@ -1177,15 +1043,8 @@ async function nextOrAbort(iterator, signal) {
1177
1043
  class VideoFrameWindow {
1178
1044
  #limit;
1179
1045
  #maxFrames;
1180
- /**
1181
- * How late a frame may be and still be the one shown at a time ({@link presentationSlackTicks}).
1182
- */
1183
1046
  #slack;
1184
- /**
1185
- * The stream's last frame, once decoding reached the stream's end: past it no frame comes, so
1186
- * that frame answers every later time without a decode. A property of the stream, kept when the
1187
- * window is cleared; it applies while that frame is the newest one held.
1188
- */
1047
+ /** The stream's last frame once decoding reached the end; answers every later time. */
1189
1048
  #endTicks;
1190
1049
  #entries = [];
1191
1050
  #bytes = 0;
@@ -1221,17 +1080,10 @@ class VideoFrameWindow {
1221
1080
  evicted.frame.close();
1222
1081
  }
1223
1082
  }
1224
- /** Records that the newest frame held is the stream's last: see {@link #endTicks}. */
1225
1083
  markEnd() {
1226
1084
  this.#endTicks = this.#entries.at(-1)?.ticks;
1227
1085
  }
1228
- /**
1229
- * A clone of the frame presented at `target`, the last one at or before its deadline (the target
1230
- * plus the slack), or `undefined` when the window cannot tell: nothing at or before the deadline,
1231
- * or only the newest frame before the target with no later frame to show that it is still
1232
- * presented. `final` says no later frame is coming, which the window knows itself when its newest
1233
- * frame is the stream's last.
1234
- */
1086
+ /** A clone of the presented frame, or `undefined` when no later frame proves it yet. */
1235
1087
  presentedAt(target, final = false) {
1236
1088
  const deadline = target + this.#slack;
1237
1089
  let index = -1;
@@ -1243,8 +1095,6 @@ class VideoFrameWindow {
1243
1095
  const entry = this.#entries[index];
1244
1096
  if (entry === undefined)
1245
1097
  return undefined;
1246
- // A frame from the target to its deadline is the one shown; one before it is, unless a later
1247
- // frame still comes by the deadline.
1248
1098
  if (entry.ticks < target &&
1249
1099
  index === this.#entries.length - 1 &&
1250
1100
  !final &&
@@ -1252,11 +1102,7 @@ class VideoFrameWindow {
1252
1102
  return undefined;
1253
1103
  return entry.frame.clone();
1254
1104
  }
1255
- /**
1256
- * Closes every frame but the one presented at `target`, the last at or before its deadline (the
1257
- * target plus the slack), which answers `target` when the next frame decoded is later. Returns
1258
- * how many were closed.
1259
- */
1105
+ /** Closes every frame but the one presented at `target`. Returns how many were closed. */
1260
1106
  releaseAllButPresentedAt(target) {
1261
1107
  const deadline = target + this.#slack;
1262
1108
  let kept = -1;
@@ -1279,11 +1125,7 @@ class VideoFrameWindow {
1279
1125
  this.#bytes = 0;
1280
1126
  }
1281
1127
  }
1282
- /**
1283
- * Whether a codec's streams can have B-frames, which a decoder outputs out of presentation order
1284
- * when it does not follow WebCodecs: H.264 and HEVC. VP8, VP9, and AV1 output every shown frame in
1285
- * order.
1286
- */
1128
+ /** Codecs with B-frames, which Safari outputs out of presentation order. */
1287
1129
  function reordersOutput(codec) {
1288
1130
  const family = codec.split(".")[0]?.toLowerCase();
1289
1131
  return ["avc1", "avc3", "hvc1", "hev1"].includes(family ?? "");
@@ -1298,4 +1140,8 @@ function validatePositiveByteLimit(value, name) {
1298
1140
  throw new RangeError(`${name} must be a positive safe integer`);
1299
1141
  }
1300
1142
  }
1143
+ import { abortError, throwIfAborted } from "./abort.js";
1144
+ import { activeTimeout } from "./active-clock.js";
1301
1145
  import { chromaSitingForStream } from "./chroma-siting.js";
1146
+ import { decodeRefusalMessage, PlanarDecodeUnavailableError, } from "./hdr-frames.js";
1147
+ import { decodeFailureOf, withSoftwareFallback } from "./decoder-fallback.js";