alpha2 0.4.5 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/THIRD_PARTY_NOTICES.md +4 -0
- package/dist/abort.d.ts +12 -0
- package/dist/abort.js +48 -0
- package/dist/active-clock.d.ts +35 -0
- package/dist/active-clock.js +99 -0
- package/dist/assets.d.ts +28 -22
- package/dist/assets.js +8 -12
- package/dist/audio-layout.d.ts +52 -74
- package/dist/audio-layout.js +114 -148
- package/dist/audio-timeline.d.ts +89 -117
- package/dist/audio-timeline.js +102 -118
- package/dist/audio-worker.d.ts +12 -21
- package/dist/audio-worker.js +8 -13
- package/dist/audio-worklet-processor.js +45 -58
- package/dist/audio-worklet.d.ts +45 -76
- package/dist/audio-worklet.js +44 -79
- package/dist/audio.d.ts +15 -23
- package/dist/audio.js +9 -13
- package/dist/builder.d.ts +45 -63
- package/dist/builder.js +49 -45
- package/dist/capabilities.d.ts +99 -16
- package/dist/capabilities.js +2 -2
- package/dist/captions.d.ts +45 -22
- package/dist/captions.js +60 -15
- package/dist/chroma-siting.d.ts +24 -41
- package/dist/chroma-siting.js +38 -71
- package/dist/containers.d.ts +41 -30
- package/dist/containers.js +59 -27
- package/dist/decoder-fallback.d.ts +13 -0
- package/dist/decoder-fallback.js +38 -0
- package/dist/decoder-order.d.ts +24 -39
- package/dist/decoder-order.js +28 -42
- package/dist/edit.d.ts +77 -154
- package/dist/edit.js +98 -180
- package/dist/effects.d.ts +109 -173
- package/dist/effects.js +7 -9
- package/dist/export-destination.d.ts +25 -41
- package/dist/export-destination.js +20 -32
- package/dist/export-failure.d.ts +34 -59
- package/dist/export-failure.js +54 -48
- package/dist/export-metrics.d.ts +116 -0
- package/dist/export-metrics.js +74 -0
- package/dist/export-retry.d.ts +46 -29
- package/dist/export-retry.js +86 -51
- package/dist/exporter.d.ts +67 -116
- package/dist/exporter.js +133 -133
- package/dist/extensions.d.ts +69 -115
- package/dist/extensions.js +55 -82
- package/dist/frame-intake.d.ts +92 -0
- package/dist/frame-intake.js +114 -0
- package/dist/frame-supply.d.ts +98 -157
- package/dist/frame-supply.js +191 -162
- package/dist/generated/project-schema.d.ts +742 -464
- package/dist/generated/project-schema.js +63 -2
- package/dist/generated/project-shape.js +663 -118
- package/dist/geometry.d.ts +28 -34
- package/dist/geometry.js +18 -23
- package/dist/gpu-recovery.d.ts +92 -0
- package/dist/gpu-recovery.js +135 -0
- package/dist/hdr-frames.d.ts +88 -62
- package/dist/hdr-frames.js +123 -46
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/json-text.d.ts +13 -23
- package/dist/json-text.js +10 -20
- package/dist/layout-values.d.ts +14 -22
- package/dist/layout-values.js +18 -21
- package/dist/layout.d.ts +55 -55
- package/dist/layout.js +37 -36
- package/dist/loudness.d.ts +27 -32
- package/dist/loudness.js +19 -23
- package/dist/media.d.ts +85 -237
- package/dist/media.js +133 -287
- package/dist/mediabunny.d.ts +173 -237
- package/dist/mediabunny.js +943 -518
- package/dist/physical-frames.d.ts +5 -17
- package/dist/physical-frames.js +4 -11
- package/dist/player.d.ts +56 -47
- package/dist/player.js +155 -40
- package/dist/presented-frames.d.ts +2 -7
- package/dist/presented-frames.js +3 -8
- package/dist/project.d.ts +83 -110
- package/dist/project.js +421 -447
- package/dist/rate-control.d.ts +9 -23
- package/dist/rate-control.js +7 -18
- package/dist/renderer-choice.d.ts +41 -0
- package/dist/renderer-choice.js +82 -0
- package/dist/repacked-bytes.d.ts +0 -2
- package/dist/repacked-bytes.js +2 -5
- package/dist/robustness.d.ts +25 -37
- package/dist/robustness.js +71 -54
- package/dist/sha256.d.ts +5 -13
- package/dist/sha256.js +9 -24
- package/dist/text.d.ts +106 -63
- package/dist/text.js +44 -69
- package/dist/video-frames.d.ts +7 -25
- package/dist/video-frames.js +12 -29
- package/dist/waveform.d.ts +5 -11
- package/dist/waveform.js +4 -9
- package/dist/worker-error.d.ts +5 -20
- package/dist/worker-error.js +8 -25
- package/dist/worker.d.ts +82 -92
- package/dist/worker.js +239 -144
- package/package.json +26 -2
- package/wasm/alpha2_audio_worklet.wasm +0 -0
- package/wasm/alpha2_extensions.d.ts +26 -47
- package/wasm/alpha2_extensions.js +26 -47
- package/wasm/alpha2_extensions_bg.wasm +0 -0
- package/wasm/alpha2_wasm.d.ts +487 -543
- package/wasm/alpha2_wasm.js +669 -572
- package/wasm/alpha2_wasm_bg.wasm +0 -0
- package/wasm/alpha2_wasm_bg.wasm.d.ts +20 -8
- package/wasm/rust-crate-licenses.md +2 -2
- package/wasm/snippets/{alpha2-wasm-57b04ecc6db57e1f → alpha2-wasm-1313375d424845c0}/inline1.js +1 -0
- package/wasm/snippets/alpha2-wasm-1313375d424845c0/inline2.js +82 -0
- package/wasm/snippets/alpha2-wasm-57b04ecc6db57e1f/inline2.js +0 -52
- /package/wasm/snippets/{alpha2-wasm-57b04ecc6db57e1f → alpha2-wasm-1313375d424845c0}/inline0.js +0 -0
- /package/wasm/snippets/{alpha2-wasm-57b04ecc6db57e1f → alpha2-wasm-1313375d424845c0}/inline3.js +0 -0
package/dist/mediabunny.js
CHANGED
|
@@ -1,59 +1,28 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { throwIfAborted } from "./abort.js";
|
|
2
|
+
import { ActiveStopwatch, activeTimeout, withinActiveTime, } from "./active-clock.js";
|
|
3
|
+
import { readAudioSpeakers, speakersWithLfe, } from "./audio-layout.js";
|
|
2
4
|
import { chromaSitingForStream } from "./chroma-siting.js";
|
|
3
5
|
import { decoderOrderKey, decoderPlaneOrder } from "./decoder-order.js";
|
|
6
|
+
import { decodeFailureOf, withSoftwareFallback } from "./decoder-fallback.js";
|
|
4
7
|
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";
|
|
5
8
|
import { audioFrameGrid, MAX_AUDIO_CHANNELS, microsecondsToTicks, placeOnAudioFrameGrid, presentationSlackTicks, readMatroskaCodecDelay, readVideoOrientation, roundingQuantum, ROUNDING_SCAN_BYTES, ROUNDING_SCAN_FRAMES, validateStallTimeout, } from "./media.js";
|
|
9
|
+
import { DecodeUnavailableError, decodeRefusalMessage, isPlanarVideoFrame, PlanarDecodeUnavailableError, } from "./hdr-frames.js";
|
|
6
10
|
import { resolveExportFormat } from "./containers.js";
|
|
7
11
|
import { ExportFailureError } from "./export-failure.js";
|
|
8
|
-
|
|
9
|
-
* How far past the decode cursor a request may be (2 s) and still be reached by decoding forward;
|
|
10
|
-
* a request further ahead seeks. Also the longest step back that continues a backward run.
|
|
11
|
-
*/
|
|
12
|
+
// Up to 2 s ahead decodes forward instead of seeking; also the longest step of a backward run.
|
|
12
13
|
const MAX_SEQUENTIAL_DECODE_GAP_TICKS = 240000n;
|
|
13
14
|
const DEFAULT_MAX_DECODED_FRAME_BYTES = 64 * 1024 * 1024;
|
|
14
|
-
|
|
15
|
-
* Decoded frames the forward window keeps at most: the two that answering a time takes, the frame
|
|
16
|
-
* shown at it (the last at or before its deadline, the time plus the slack) and the one after.
|
|
17
|
-
*
|
|
18
|
-
* Each holds one of the decoder's output surfaces, and a hardware decoder has a fixed pool of them.
|
|
19
|
-
* Chromium's Windows decoder allocates its DPB size plus six, and the DPB can occupy all of its own
|
|
20
|
-
* share: a stream without a VUI is reordered by the whole DPB, and long-term references stay in it
|
|
21
|
-
* for a whole GOP. That leaves about five surfaces for everything outside the decoder; a window of
|
|
22
|
-
* eight holds them all, and the decoder waits, without an error, for one to come back.
|
|
23
|
-
*/
|
|
15
|
+
// See the same limit in media.ts: each frame holds a decoder surface from a small fixed pool.
|
|
24
16
|
const DEFAULT_MAX_CACHED_FRAMES = 2;
|
|
25
|
-
/**
|
|
26
|
-
* The fewest frames the forward window works with, and the fewest its byte limit evicts down to:
|
|
27
|
-
* the frame at or before a time and the one after it, which proves that frame is still presented.
|
|
28
|
-
*/
|
|
29
17
|
const MIN_CACHED_FRAMES = 2;
|
|
30
|
-
/** How long reading one frame may take before the decoder is taken to be stuck. */
|
|
31
18
|
const DEFAULT_STALL_TIMEOUT_MS = 5_000;
|
|
32
|
-
/** How long the video encoder may hold frames without output before it is taken to be stuck. */
|
|
33
19
|
const DEFAULT_ENCODER_STALL_TIMEOUT_MS = 10_000;
|
|
34
|
-
/** Bytes of copied frames the reverse window keeps by default: about forty 1080p frames. */
|
|
35
20
|
const DEFAULT_MAX_REVERSE_FRAME_BYTES = 128 * 1024 * 1024;
|
|
36
21
|
const TICKS_PER_SECOND = 120_000;
|
|
37
22
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
|
|
41
|
-
function isDecoderFailure(error) {
|
|
42
|
-
return (error instanceof DOMException &&
|
|
43
|
-
["EncodingError", "NotSupportedError", "OperationError"].includes(error.name));
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Optional demux/decode adapter implementing alpha2's public decoder contract.
|
|
47
|
-
*
|
|
48
|
-
* Forward requests share one sequential decode. A request earlier than the last one, or far past
|
|
49
|
-
* it, seeks: decoding restarts at the keyframe before it, and the frames it passes go through a
|
|
50
|
-
* window of the last two decoder frames. A decoder that produces no frame for the stall timeout
|
|
51
|
-
* fails the request instead of holding it, and every request after it, forever. When requests keep
|
|
52
|
-
* stepping back (a reversed clip, a ping-pong loop's backward pass), the next miss decodes a
|
|
53
|
-
* reverse window instead: the frames up to the requested time, from the keyframe before it, copied
|
|
54
|
-
* out of the decoder so that dozens can be kept without stalling it. The run then plays from that
|
|
55
|
-
* window, and each keyframe interval is decoded about `interval / window` times rather than once
|
|
56
|
-
* per frame.
|
|
23
|
+
* Optional mediabunny demux/decode adapter for alpha2's decoder contract. Forward requests share
|
|
24
|
+
* one sequential decode; a backward run (reversed clip, ping-pong loop) decodes windows of frames
|
|
25
|
+
* copied out of the decoder, so each keyframe interval is decoded a few times instead of per frame.
|
|
57
26
|
*/
|
|
58
27
|
export class MediabunnyVideoDecoder {
|
|
59
28
|
#sourceId;
|
|
@@ -62,38 +31,21 @@ export class MediabunnyVideoDecoder {
|
|
|
62
31
|
#sink;
|
|
63
32
|
#hardwareAcceleration;
|
|
64
33
|
#softwareFallback;
|
|
34
|
+
#decodedAny = false;
|
|
65
35
|
#packets;
|
|
66
36
|
#chromaSiting;
|
|
67
37
|
#stallTimeoutMs;
|
|
68
38
|
#iterator;
|
|
69
39
|
#generation;
|
|
70
|
-
/**
|
|
71
|
-
* The last time answered, from a window or by decoding: where a backward run is measured from.
|
|
72
|
-
*/
|
|
73
40
|
#lastTargetTicks;
|
|
74
|
-
/**
|
|
75
|
-
* The last time the forward decode answered: the iterator has read up to the frame after it. A
|
|
76
|
-
* request at or before it, or far past it, seeks.
|
|
77
|
-
*/
|
|
78
41
|
#cursorTicks;
|
|
79
|
-
/**
|
|
80
|
-
* When the stream's first frame is presented, once a seek from the first keyframe has shown it to
|
|
81
|
-
* be later than the time sought.
|
|
82
|
-
*/
|
|
83
42
|
#leadTicks;
|
|
84
|
-
/** The cursor sought from the stream's first keyframe and has read no frame since. */
|
|
85
43
|
#headSinceSeek = false;
|
|
86
|
-
/** Requests in a row that were each earlier than the one before. */
|
|
87
44
|
#backwardSteps = 0;
|
|
88
45
|
#closed = false;
|
|
89
|
-
/** How the track is shown upright, as the container says. */
|
|
90
46
|
#orientation;
|
|
91
47
|
#cache;
|
|
92
48
|
#reverse;
|
|
93
|
-
/**
|
|
94
|
-
* How late a frame may be and still be the one shown at a time, from the track's time resolution
|
|
95
|
-
* ({@link presentationSlackTicks}).
|
|
96
|
-
*/
|
|
97
49
|
#slack;
|
|
98
50
|
#reverseCacheHits = 0;
|
|
99
51
|
#reverseWindowsBuilt = 0;
|
|
@@ -112,9 +64,8 @@ export class MediabunnyVideoDecoder {
|
|
|
112
64
|
this.#reverse = new ReverseFrameWindow(limits.maxReverseFrameBytes, slack);
|
|
113
65
|
}
|
|
114
66
|
/**
|
|
115
|
-
* Opens `resource`'s primary video track. Rejects when it has none
|
|
116
|
-
*
|
|
117
|
-
* "prefer-software"`, a track the browser has no software decoder for rejects with `code:
|
|
67
|
+
* Opens `resource`'s primary video track. Rejects when it has none or this browser cannot decode
|
|
68
|
+
* it; with `"prefer-software"` and no software decoder, with `code:
|
|
118
69
|
* "software_decode_unavailable"`.
|
|
119
70
|
*/
|
|
120
71
|
static async open(sourceId, resource, options = {}) {
|
|
@@ -139,10 +90,12 @@ export class MediabunnyVideoDecoder {
|
|
|
139
90
|
const track = await input.getPrimaryVideoTrack();
|
|
140
91
|
if (track === null)
|
|
141
92
|
throw new Error("mediabunny input has no video track");
|
|
142
|
-
if (!(await track.canDecode()))
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
93
|
+
if (!(await track.canDecode())) {
|
|
94
|
+
const facts = await videoTrackFacts(track);
|
|
95
|
+
throw new DecodeUnavailableError(decodeRefusalMessage(sourceId, facts), facts);
|
|
96
|
+
}
|
|
97
|
+
// `canDecode` does not ask for a software decoder, so a hardware-only codec would open and
|
|
98
|
+
// then fail on its first read.
|
|
146
99
|
if (options.hardwareAcceleration === "prefer-software" &&
|
|
147
100
|
typeof VideoDecoder !== "undefined") {
|
|
148
101
|
const config = await track.getDecoderConfig();
|
|
@@ -155,8 +108,7 @@ export class MediabunnyVideoDecoder {
|
|
|
155
108
|
if (support.supported !== true)
|
|
156
109
|
throw Object.assign(new Error(`this browser has no software decoder for ${config?.codec ?? track.codec ?? "the video track"}`), { code: "software_decode_unavailable" });
|
|
157
110
|
}
|
|
158
|
-
// mediabunny reports
|
|
159
|
-
// than native decoding does.
|
|
111
|
+
// mediabunny reports no mirroring and reads mirrored matrices differently from `FFmpeg`.
|
|
160
112
|
const orientation = (await readVideoOrientation(resource, track.id)) ?? {
|
|
161
113
|
rotationDegrees: track.rotation,
|
|
162
114
|
mirror: false,
|
|
@@ -169,53 +121,48 @@ export class MediabunnyVideoDecoder {
|
|
|
169
121
|
throw error;
|
|
170
122
|
}
|
|
171
123
|
}
|
|
172
|
-
/** Bytes both windows hold: decoder frames and reverse copies. */
|
|
173
124
|
get cachedFrameBytes() {
|
|
174
125
|
return this.#cache.bytes + this.#reverse.bytes;
|
|
175
126
|
}
|
|
176
|
-
/** Requests answered from a window without decoding. */
|
|
177
127
|
get reverseCacheHits() {
|
|
178
128
|
return this.#reverseCacheHits;
|
|
179
129
|
}
|
|
180
|
-
/** Reverse windows decoded: one per stretch of a backward run. */
|
|
181
130
|
get reverseWindowsBuilt() {
|
|
182
131
|
return this.#reverseWindowsBuilt;
|
|
183
132
|
}
|
|
184
|
-
/**
|
|
185
|
-
* Why the decoder moved to software decoding, when the one the browser picked first failed;
|
|
186
|
-
* `undefined` while that one serves.
|
|
187
|
-
*/
|
|
133
|
+
/** Why decoding moved to software after the browser's first pick failed, if it did. */
|
|
188
134
|
get softwareFallback() {
|
|
189
135
|
return this.#softwareFallback;
|
|
190
136
|
}
|
|
191
137
|
/**
|
|
192
|
-
* The frame presented at the request's time.
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
* on Linux report `EncodingError: Decoding error.`), so a decoder failure replaces it, once, with
|
|
196
|
-
* a software decoder, which decodes the request again from its keyframe. A software decoder that
|
|
197
|
-
* fails too rejects the request.
|
|
138
|
+
* The frame presented at the request's time. A decoder failure (Chromium's VA-API decoders report
|
|
139
|
+
* `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.
|
|
198
141
|
*/
|
|
199
142
|
async refill(request, signal) {
|
|
200
143
|
try {
|
|
201
|
-
|
|
144
|
+
const frame = await withSoftwareFallback(() => this.#refill(request, signal), this.#closed ||
|
|
145
|
+
this.#hardwareAcceleration === "prefer-software" ||
|
|
146
|
+
signal?.aborted === true
|
|
147
|
+
? undefined
|
|
148
|
+
: async (cause) => {
|
|
149
|
+
await this.#resetIterator();
|
|
150
|
+
this.#cache.clear();
|
|
151
|
+
this.#reverse.clear();
|
|
152
|
+
this.#backwardSteps = 0;
|
|
153
|
+
this.#hardwareAcceleration = "prefer-software";
|
|
154
|
+
this.#softwareFallback = `${cause.name}: ${cause.message}`;
|
|
155
|
+
this.#sink = new VideoSampleSink(this.#track, {
|
|
156
|
+
hardwareAcceleration: "prefer-software",
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
this.#decodedAny = true;
|
|
160
|
+
return frame;
|
|
202
161
|
}
|
|
203
162
|
catch (error) {
|
|
204
|
-
if (this.#closed ||
|
|
205
|
-
this.#hardwareAcceleration === "prefer-software" ||
|
|
206
|
-
signal?.aborted === true ||
|
|
207
|
-
!isDecoderFailure(error))
|
|
163
|
+
if (this.#decodedAny || this.#closed || signal?.aborted === true)
|
|
208
164
|
throw error;
|
|
209
|
-
await this.#
|
|
210
|
-
this.#cache.clear();
|
|
211
|
-
this.#reverse.clear();
|
|
212
|
-
this.#backwardSteps = 0;
|
|
213
|
-
this.#hardwareAcceleration = "prefer-software";
|
|
214
|
-
this.#softwareFallback = `${error.name}: ${error.message}`;
|
|
215
|
-
this.#sink = new VideoSampleSink(this.#track, {
|
|
216
|
-
hardwareAcceleration: "prefer-software",
|
|
217
|
-
});
|
|
218
|
-
return this.#refill(request, signal);
|
|
165
|
+
throw decodeFailureOf(error, this.#sourceId, await videoTrackFacts(this.#track), false);
|
|
219
166
|
}
|
|
220
167
|
}
|
|
221
168
|
async #refill(request, signal) {
|
|
@@ -232,14 +179,12 @@ export class MediabunnyVideoDecoder {
|
|
|
232
179
|
this.#reverse.clear();
|
|
233
180
|
this.#backwardSteps = 0;
|
|
234
181
|
}
|
|
235
|
-
// Requests before the stream's first frame all present that frame.
|
|
236
182
|
const target = this.#leadTicks !== undefined && request.mediaTimeTicks < this.#leadTicks
|
|
237
183
|
? this.#leadTicks
|
|
238
184
|
: request.mediaTimeTicks;
|
|
239
185
|
const last = this.#lastTargetTicks;
|
|
240
186
|
const backward = last !== undefined && target < last;
|
|
241
|
-
//
|
|
242
|
-
// as scrubbing, lands beyond any window the last one left.
|
|
187
|
+
// A longer jump back (scrubbing) lands beyond any window the last one left.
|
|
243
188
|
if (last !== undefined && target !== last)
|
|
244
189
|
this.#backwardSteps =
|
|
245
190
|
backward && last - target <= MAX_SEQUENTIAL_DECODE_GAP_TICKS
|
|
@@ -257,14 +202,12 @@ export class MediabunnyVideoDecoder {
|
|
|
257
202
|
});
|
|
258
203
|
const windowed = this.#reverse.presentedAt(target) ?? this.#cache.presentedAt(target);
|
|
259
204
|
if (windowed !== undefined) {
|
|
260
|
-
// A hit moves no cursor: the forward decode is still where it last answered, and a step past
|
|
261
|
-
// this time from there may have to seek.
|
|
262
205
|
this.#lastTargetTicks = target;
|
|
263
206
|
this.#reverseCacheHits += 1;
|
|
264
207
|
return answer(windowed);
|
|
265
208
|
}
|
|
266
209
|
const seek = request.reason === "seek" || request.reason === "device-recovery";
|
|
267
|
-
//
|
|
210
|
+
// One step back is a seek (a loop's wrap); two in a row is a backward run.
|
|
268
211
|
if (!seek && this.#backwardSteps >= 2) {
|
|
269
212
|
await this.#fillReverseWindow(target, signal);
|
|
270
213
|
this.#generation = request.generation;
|
|
@@ -282,8 +225,7 @@ export class MediabunnyVideoDecoder {
|
|
|
282
225
|
if (mustSeek) {
|
|
283
226
|
await this.#resetIterator();
|
|
284
227
|
this.#cache.clear();
|
|
285
|
-
//
|
|
286
|
-
// the stall timeout measures the decoder rather than the GOP length.
|
|
228
|
+
// Starting at the keyframe makes the stall timeout measure the decoder, not the GOP length.
|
|
287
229
|
const start = await this.#keyframeStart(target + this.#slack);
|
|
288
230
|
this.#iterator = this.#sink
|
|
289
231
|
.samples(start.seconds)[Symbol.asyncIterator]();
|
|
@@ -292,8 +234,6 @@ export class MediabunnyVideoDecoder {
|
|
|
292
234
|
}
|
|
293
235
|
this.#lastTargetTicks = target;
|
|
294
236
|
this.#cursorTicks = target;
|
|
295
|
-
// The frame shown is the last one at or before the deadline; knowing it takes the frame after,
|
|
296
|
-
// which the window keeps for the next request.
|
|
297
237
|
for (;;) {
|
|
298
238
|
const iterator = this.#iterator;
|
|
299
239
|
if (iterator === undefined) {
|
|
@@ -313,7 +253,6 @@ export class MediabunnyVideoDecoder {
|
|
|
313
253
|
}
|
|
314
254
|
if (next.done) {
|
|
315
255
|
this.#iterator = undefined;
|
|
316
|
-
// Every decoded frame is in the window, so its newest is the stream's last.
|
|
317
256
|
this.#cache.markEnd();
|
|
318
257
|
const presented = this.#cache.presentedAt(target, true);
|
|
319
258
|
if (presented !== undefined)
|
|
@@ -333,9 +272,8 @@ export class MediabunnyVideoDecoder {
|
|
|
333
272
|
if (presented !== undefined)
|
|
334
273
|
return answer(presented);
|
|
335
274
|
if (ticks > target + this.#slack) {
|
|
336
|
-
//
|
|
337
|
-
//
|
|
338
|
-
// this request only.
|
|
275
|
+
// From the first keyframe, a late first frame means the stream starts there; from any
|
|
276
|
+
// other keyframe it is a bad key index and answers this request only.
|
|
339
277
|
if (head)
|
|
340
278
|
this.#leadTicks = ticks;
|
|
341
279
|
const first = this.#cache.presentedAt(ticks);
|
|
@@ -348,14 +286,12 @@ export class MediabunnyVideoDecoder {
|
|
|
348
286
|
}
|
|
349
287
|
}
|
|
350
288
|
}
|
|
351
|
-
/** Drops the decode cursor and both windows; the next request seeks. */
|
|
352
289
|
async flush() {
|
|
353
290
|
await this.#resetIterator();
|
|
354
291
|
this.#cache.clear();
|
|
355
292
|
this.#reverse.clear();
|
|
356
293
|
this.#backwardSteps = 0;
|
|
357
294
|
}
|
|
358
|
-
/** Releases the decoder, both windows, and the input. A later `refill` rejects. */
|
|
359
295
|
close() {
|
|
360
296
|
if (this.#closed)
|
|
361
297
|
return;
|
|
@@ -367,21 +303,13 @@ export class MediabunnyVideoDecoder {
|
|
|
367
303
|
this.#reverse.clear();
|
|
368
304
|
this.#input.dispose();
|
|
369
305
|
}
|
|
370
|
-
/**
|
|
371
|
-
* Decodes the reverse window for `target`: from the keyframe before it, forward to the first
|
|
372
|
-
* frame after its deadline (`target` plus the presentation slack), copying the frames the window
|
|
373
|
-
* can hold and releasing every decoder frame as soon as it is read.
|
|
374
|
-
*
|
|
375
|
-
* The previous window goes first: its frames are later than the target, and a backward run has
|
|
376
|
-
* passed them. The forward cursor goes too; a later forward request seeks.
|
|
377
|
-
*/
|
|
306
|
+
/** Drops the previous window and the forward cursor, then decodes and copies a new window. */
|
|
378
307
|
async #fillReverseWindow(target, signal) {
|
|
379
308
|
await this.#resetIterator();
|
|
380
309
|
this.#cache.clear();
|
|
381
310
|
this.#reverse.clear();
|
|
382
311
|
const iterator = this.#sink
|
|
383
312
|
.samples(await this.#keyframeSeconds(target))[Symbol.asyncIterator]();
|
|
384
|
-
// Frames before this time are decoded but not copied: the window could not keep them.
|
|
385
313
|
let floor;
|
|
386
314
|
try {
|
|
387
315
|
for (;;) {
|
|
@@ -413,20 +341,16 @@ export class MediabunnyVideoDecoder {
|
|
|
413
341
|
this.#reverseWindowsBuilt += 1;
|
|
414
342
|
}
|
|
415
343
|
/**
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
*
|
|
419
|
-
* A hardware decoder whose output surfaces are all held waits for one to come back and reports
|
|
420
|
-
* nothing, so without a limit the read, and every request queued behind it, waits forever. On
|
|
421
|
-
* either rejection the iterator is ended, which stops its decoder and releases what it holds; a
|
|
422
|
-
* frame the read delivers after that is closed.
|
|
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.
|
|
423
346
|
*/
|
|
424
347
|
async #nextSample(iterator, signal) {
|
|
425
348
|
const pending = iterator.next();
|
|
426
|
-
|
|
349
|
+
const settled = new AbortController();
|
|
427
350
|
let abort;
|
|
428
351
|
const interrupted = new Promise((_, reject) => {
|
|
429
|
-
|
|
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`)));
|
|
430
354
|
if (signal === undefined)
|
|
431
355
|
return;
|
|
432
356
|
abort = () => reject(signal.reason instanceof Error
|
|
@@ -446,19 +370,14 @@ export class MediabunnyVideoDecoder {
|
|
|
446
370
|
throw error;
|
|
447
371
|
}
|
|
448
372
|
finally {
|
|
449
|
-
|
|
373
|
+
settled.abort();
|
|
450
374
|
if (abort !== undefined)
|
|
451
375
|
signal?.removeEventListener("abort", abort);
|
|
452
376
|
}
|
|
453
377
|
}
|
|
454
|
-
/** The time of the keyframe decoding must start from to reach `target`. */
|
|
455
378
|
async #keyframeSeconds(target) {
|
|
456
379
|
return (await this.#keyframeStart(target)).seconds;
|
|
457
380
|
}
|
|
458
|
-
/**
|
|
459
|
-
* {@link #keyframeSeconds}, and whether that keyframe is the stream's first because none is at or
|
|
460
|
-
* before `target`.
|
|
461
|
-
*/
|
|
462
381
|
async #keyframeStart(target) {
|
|
463
382
|
const seconds = Number(target) / TICKS_PER_SECOND;
|
|
464
383
|
const key = await this.#packets.getKeyPacket(seconds, {
|
|
@@ -487,11 +406,7 @@ class MediabunnyFrameWindow {
|
|
|
487
406
|
#limit;
|
|
488
407
|
#maxFrames;
|
|
489
408
|
#slack;
|
|
490
|
-
/**
|
|
491
|
-
* The stream's last frame, once decoding reached the stream's end: past it no frame comes, so
|
|
492
|
-
* that frame answers every later time without a decode. A property of the stream, kept when the
|
|
493
|
-
* window is cleared; it applies while that frame is the newest one held.
|
|
494
|
-
*/
|
|
409
|
+
/** The stream's last frame once decoding reached the end; answers every later time. */
|
|
495
410
|
#endTicks;
|
|
496
411
|
#entries = [];
|
|
497
412
|
#bytes = 0;
|
|
@@ -527,17 +442,10 @@ class MediabunnyFrameWindow {
|
|
|
527
442
|
evicted.frame.close();
|
|
528
443
|
}
|
|
529
444
|
}
|
|
530
|
-
/** Records that the newest frame held is the stream's last: see {@link #endTicks}. */
|
|
531
445
|
markEnd() {
|
|
532
446
|
this.#endTicks = this.#entries.at(-1)?.ticks;
|
|
533
447
|
}
|
|
534
|
-
/**
|
|
535
|
-
* A clone of the frame presented at `target`, the last one at or before its deadline (the target
|
|
536
|
-
* plus the slack), or `undefined` when the window cannot tell: nothing at or before the deadline,
|
|
537
|
-
* or only the newest frame before the target with no later frame to show that it is still
|
|
538
|
-
* presented. `final` says no later frame is coming, which the window knows itself when its newest
|
|
539
|
-
* frame is the stream's last.
|
|
540
|
-
*/
|
|
448
|
+
/** A clone of the presented frame, or `undefined` when no later frame proves it yet. */
|
|
541
449
|
presentedAt(target, final = false) {
|
|
542
450
|
const deadline = target + this.#slack;
|
|
543
451
|
let index = -1;
|
|
@@ -549,8 +457,6 @@ class MediabunnyFrameWindow {
|
|
|
549
457
|
const entry = this.#entries[index];
|
|
550
458
|
if (entry === undefined)
|
|
551
459
|
return undefined;
|
|
552
|
-
// A frame from the target to its deadline is the one shown; one before it is, unless a later
|
|
553
|
-
// frame still comes by the deadline.
|
|
554
460
|
if (entry.ticks < target &&
|
|
555
461
|
index === this.#entries.length - 1 &&
|
|
556
462
|
!final &&
|
|
@@ -564,13 +470,7 @@ class MediabunnyFrameWindow {
|
|
|
564
470
|
this.#bytes = 0;
|
|
565
471
|
}
|
|
566
472
|
}
|
|
567
|
-
/**
|
|
568
|
-
* Copies of consecutive decoded frames, each answering for its presentation interval.
|
|
569
|
-
*
|
|
570
|
-
* Unlike the forward window, it answers from intervals it has proven rather than from neighbours,
|
|
571
|
-
* and its frames belong to it rather than to the decoder. It evicts the earliest frames first: a
|
|
572
|
-
* backward run reaches them last.
|
|
573
|
-
*/
|
|
473
|
+
/** Owned copies of consecutive decoded frames; evicts the earliest first. */
|
|
574
474
|
class ReverseFrameWindow {
|
|
575
475
|
#limit;
|
|
576
476
|
#slack;
|
|
@@ -583,23 +483,13 @@ class ReverseFrameWindow {
|
|
|
583
483
|
get bytes() {
|
|
584
484
|
return this.#bytes;
|
|
585
485
|
}
|
|
586
|
-
/**
|
|
587
|
-
* How far before the requested time the window can reach from frames like `sample`: its byte
|
|
588
|
-
* limit in frames, times the frame's duration. Frames earlier than that would be evicted before
|
|
589
|
-
* the window is filled.
|
|
590
|
-
*/
|
|
591
486
|
span(sample) {
|
|
592
487
|
const bytes = sampleBytes(sample);
|
|
593
488
|
const frames = Math.max(1, Math.floor(this.#limit / bytes));
|
|
594
|
-
//
|
|
595
|
-
// copies or windows, never a wrong frame.
|
|
489
|
+
// Unknown durations count as 30 fps; a wrong guess costs copies, never a wrong frame.
|
|
596
490
|
const duration = sample.microsecondDuration > 0 ? sample.microsecondDuration : 33_333;
|
|
597
491
|
return microsecondsToTicks(frames * duration);
|
|
598
492
|
}
|
|
599
|
-
/**
|
|
600
|
-
* Keeps a copy of `sample`, presented from `ticks` until a later frame is added, ended, or
|
|
601
|
-
* sealed.
|
|
602
|
-
*/
|
|
603
493
|
async add(sample, ticks) {
|
|
604
494
|
const decoded = sample.toVideoFrame();
|
|
605
495
|
let frame;
|
|
@@ -626,22 +516,16 @@ class ReverseFrameWindow {
|
|
|
626
516
|
evicted.frame.close();
|
|
627
517
|
}
|
|
628
518
|
}
|
|
629
|
-
/** The frame after the newest one is presented from `ticks`. */
|
|
630
519
|
end(ticks) {
|
|
631
520
|
const newest = this.#entries.at(-1);
|
|
632
521
|
if (newest !== undefined && newest.end === undefined)
|
|
633
522
|
newest.end = ticks;
|
|
634
523
|
}
|
|
635
|
-
/** No frame follows the newest: it answers however late a time is. */
|
|
636
524
|
seal() {
|
|
637
525
|
const newest = this.#entries.at(-1);
|
|
638
526
|
if (newest !== undefined && newest.end === undefined)
|
|
639
527
|
newest.end = null;
|
|
640
528
|
}
|
|
641
|
-
/**
|
|
642
|
-
* A clone of the frame whose presentation interval holds `target`'s deadline: the frame shown at
|
|
643
|
-
* `target`.
|
|
644
|
-
*/
|
|
645
529
|
presentedAt(target) {
|
|
646
530
|
const deadline = target + this.#slack;
|
|
647
531
|
const entry = this.#entries.find((candidate) => candidate.start <= deadline &&
|
|
@@ -655,19 +539,12 @@ class ReverseFrameWindow {
|
|
|
655
539
|
this.#bytes = 0;
|
|
656
540
|
}
|
|
657
541
|
}
|
|
658
|
-
/**
|
|
659
|
-
* How late a frame of `track` may be and still be the one shown at a time ({@link
|
|
660
|
-
* presentationSlackTicks}): from its time resolution and the rounding its first packets' times
|
|
661
|
-
* show, as a native host reads the same file. A track whose resolution mediabunny cannot say is
|
|
662
|
-
* held to {@link PRESENTATION_SLACK_TICKS}.
|
|
663
|
-
*/
|
|
664
542
|
async function trackPresentationSlack(track, packets) {
|
|
665
543
|
const first = await firstPacketTimes(track, packets);
|
|
666
544
|
if (first === undefined)
|
|
667
545
|
return presentationSlackTicks();
|
|
668
546
|
return presentationSlackTicks(first.resolution, roundingQuantum(first.timestamps));
|
|
669
547
|
}
|
|
670
|
-
/** The pre-skip, in 48 kHz samples, an `OpusHead` decoder configuration declares; 0 for none. */
|
|
671
548
|
function opusPreSkip(description) {
|
|
672
549
|
if (description === null ||
|
|
673
550
|
description.length < 12 ||
|
|
@@ -675,11 +552,6 @@ function opusPreSkip(description) {
|
|
|
675
552
|
return 0;
|
|
676
553
|
return description[10] | (description[11] << 8);
|
|
677
554
|
}
|
|
678
|
-
/**
|
|
679
|
-
* `track`'s time resolution and its first packets' timestamps in whole units of it, up to {@link
|
|
680
|
-
* ROUNDING_SCAN_FRAMES} of them or {@link ROUNDING_SCAN_BYTES}, as a native host reads the same
|
|
681
|
-
* file; `undefined` when mediabunny cannot say the resolution.
|
|
682
|
-
*/
|
|
683
555
|
async function firstPacketTimes(track, packets) {
|
|
684
556
|
const resolution = await track.getTimeResolution().catch(() => undefined);
|
|
685
557
|
if (resolution === undefined)
|
|
@@ -696,10 +568,6 @@ async function firstPacketTimes(track, packets) {
|
|
|
696
568
|
}
|
|
697
569
|
return { resolution, timestamps };
|
|
698
570
|
}
|
|
699
|
-
/**
|
|
700
|
-
* Where `track`'s chroma samples sit, from its decoder configuration's parameter sets or, when it
|
|
701
|
-
* carries none, its first packet's.
|
|
702
|
-
*/
|
|
703
571
|
async function streamChromaSiting(track, packets) {
|
|
704
572
|
const config = await track.getDecoderConfig().catch(() => null);
|
|
705
573
|
const description = config?.description ?? undefined;
|
|
@@ -708,12 +576,7 @@ async function streamChromaSiting(track, packets) {
|
|
|
708
576
|
: null;
|
|
709
577
|
return chromaSitingForStream(config?.codec ?? track.codec, description, first?.data);
|
|
710
578
|
}
|
|
711
|
-
/**
|
|
712
|
-
* A copy of `frame` that holds none of the decoder's resources.
|
|
713
|
-
*
|
|
714
|
-
* A frame with a pixel format is copied into memory the copy owns; an opaque one (a GPU texture
|
|
715
|
-
* some platforms decode to) is drawn into a bitmap instead.
|
|
716
|
-
*/
|
|
579
|
+
/** A copy that holds no decoder resources; opaque (GPU) frames are drawn into a bitmap. */
|
|
717
580
|
async function detachVideoFrame(frame) {
|
|
718
581
|
const format = frame.format;
|
|
719
582
|
if (format !== null) {
|
|
@@ -726,8 +589,7 @@ async function detachVideoFrame(frame) {
|
|
|
726
589
|
};
|
|
727
590
|
const buffer = new ArrayBuffer(frame.allocationSize());
|
|
728
591
|
const layout = await frame.copyTo(buffer);
|
|
729
|
-
// `transfer`
|
|
730
|
-
// the DOM typings do not know it yet.
|
|
592
|
+
// `transfer` is missing from the DOM typings.
|
|
731
593
|
const init = {
|
|
732
594
|
format,
|
|
733
595
|
codedWidth: rect.width,
|
|
@@ -757,7 +619,6 @@ async function detachVideoFrame(frame) {
|
|
|
757
619
|
bitmap.close();
|
|
758
620
|
}
|
|
759
621
|
}
|
|
760
|
-
/** What a copy of `sample` will hold: its pixel data, or RGBA where it has no pixel format. */
|
|
761
622
|
function sampleBytes(sample) {
|
|
762
623
|
try {
|
|
763
624
|
return Math.max(1, sample.allocationSize());
|
|
@@ -766,7 +627,6 @@ function sampleBytes(sample) {
|
|
|
766
627
|
return Math.max(1, sample.codedWidth * sample.codedHeight * 4);
|
|
767
628
|
}
|
|
768
629
|
}
|
|
769
|
-
/** What a frame the reverse window owns holds. */
|
|
770
630
|
function ownedFrameBytes(frame) {
|
|
771
631
|
try {
|
|
772
632
|
return Math.max(1, frame.allocationSize());
|
|
@@ -783,7 +643,6 @@ function mediabunnyVideoFrameBytes(frame) {
|
|
|
783
643
|
const height = Math.max(1, frame.codedHeight || frame.displayHeight || 1);
|
|
784
644
|
return width * height * 4;
|
|
785
645
|
}
|
|
786
|
-
/** Reads byte ranges of a mediabunny input, for what its demuxers do not report. */
|
|
787
646
|
function byteReader(resource) {
|
|
788
647
|
if (resource instanceof Blob)
|
|
789
648
|
return async (offset, length) => new Uint8Array(await resource.slice(offset, offset + length).arrayBuffer());
|
|
@@ -798,48 +657,282 @@ function byteLength(resource) {
|
|
|
798
657
|
function bufferBytes(source) {
|
|
799
658
|
if (source === undefined)
|
|
800
659
|
return null;
|
|
801
|
-
// `SharedArrayBuffer` is
|
|
802
|
-
// told apart from a buffer, not a shared buffer from a plain one.
|
|
660
|
+
// `SharedArrayBuffer` is undefined without cross-origin isolation.
|
|
803
661
|
if (ArrayBuffer.isView(source))
|
|
804
662
|
return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
|
|
805
663
|
return new Uint8Array(source);
|
|
806
664
|
}
|
|
807
|
-
/** The source rates the audio adapter reads, as a native host does. */
|
|
808
665
|
const SOURCE_SAMPLE_RATES = { min: 1_000, max: 768_000 };
|
|
666
|
+
// Decoding starts this early because each mediabunny iteration starts a fresh decoder without
|
|
667
|
+
// history (AAC's first frame lacks the previous frame's overlap).
|
|
668
|
+
const AUDIO_PREROLL_SECONDS = 0.1;
|
|
669
|
+
// Opus converges slowly after a seek: 100 ms early is still 2e-2 off, 400 ms is under 1e-6.
|
|
670
|
+
const OPUS_PREROLL_SECONDS = 0.4;
|
|
671
|
+
const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
|
|
672
|
+
function codecBitDepth(codec) {
|
|
673
|
+
if (codec === null)
|
|
674
|
+
return undefined;
|
|
675
|
+
const parts = codec.split(".");
|
|
676
|
+
const family = parts[0]?.toLowerCase();
|
|
677
|
+
if (family === "av01" || family === "vp09") {
|
|
678
|
+
const depth = Number(parts[3]?.replace(/\D/g, ""));
|
|
679
|
+
return Number.isInteger(depth) && depth > 0 ? depth : undefined;
|
|
680
|
+
}
|
|
681
|
+
if (family === "hvc1" || family === "hev1")
|
|
682
|
+
return parts[1]?.replace(/\D/g, "") === "2" ? 10 : 8;
|
|
683
|
+
if (family === "avc1" || family === "avc3") {
|
|
684
|
+
const profile = Number.parseInt(parts[1]?.slice(0, 2) ?? "", 16);
|
|
685
|
+
return profile === 110 || profile === 122 || profile === 244 ? 10 : 8;
|
|
686
|
+
}
|
|
687
|
+
return undefined;
|
|
688
|
+
}
|
|
689
|
+
/** The facts a refusal message names ({@link decodeRefusalMessage}), with `extra` over them. */
|
|
690
|
+
export async function videoTrackFacts(track, extra = {}) {
|
|
691
|
+
const codec = (await track.getCodecParameterString().catch(() => null)) ??
|
|
692
|
+
track.codec ??
|
|
693
|
+
null;
|
|
694
|
+
const space = await track.getColorSpace().catch(() => undefined);
|
|
695
|
+
const bitDepth = codecBitDepth(codec);
|
|
696
|
+
return {
|
|
697
|
+
kind: "video",
|
|
698
|
+
codec,
|
|
699
|
+
...(bitDepth === undefined ? {} : { bitDepth }),
|
|
700
|
+
transfer: space?.transfer ?? null,
|
|
701
|
+
...extra,
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
/** Rejects after `timeoutMs` of active time; a late value from `work` goes to `onLate`. */
|
|
705
|
+
async function withinProbeTime(work, timeoutMs, what, onLate) {
|
|
706
|
+
let timedOut = false;
|
|
707
|
+
work.then((value) => {
|
|
708
|
+
if (timedOut)
|
|
709
|
+
onLate(value);
|
|
710
|
+
}, () => { });
|
|
711
|
+
return withinActiveTime(work, timeoutMs, () => {
|
|
712
|
+
timedOut = true;
|
|
713
|
+
return new Error(`${what} did not answer within ${timeoutMs} ms`);
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
async function firstFramePlanes(track, hardwareAcceleration, timeoutMs) {
|
|
717
|
+
const first = await new EncodedPacketSink(track).getFirstPacket({
|
|
718
|
+
metadataOnly: true,
|
|
719
|
+
});
|
|
720
|
+
if (first === null)
|
|
721
|
+
throw new Error("the video track has no packets");
|
|
722
|
+
const sink = new VideoSampleSink(track, { hardwareAcceleration });
|
|
723
|
+
const sample = await withinProbeTime(sink.getSample(first.timestamp), timeoutMs, "the video decoder", (late) => late?.close());
|
|
724
|
+
if (sample === null)
|
|
725
|
+
throw new Error("the video decoder gave no frame");
|
|
726
|
+
try {
|
|
727
|
+
const frame = sample.toVideoFrame();
|
|
728
|
+
try {
|
|
729
|
+
let planar = isPlanarVideoFrame(frame);
|
|
730
|
+
if (planar) {
|
|
731
|
+
try {
|
|
732
|
+
frame.allocationSize();
|
|
733
|
+
}
|
|
734
|
+
catch {
|
|
735
|
+
planar = false;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return { planar, format: frame.format };
|
|
739
|
+
}
|
|
740
|
+
finally {
|
|
741
|
+
frame.close();
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
finally {
|
|
745
|
+
sample.close();
|
|
746
|
+
}
|
|
747
|
+
}
|
|
809
748
|
/**
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
*
|
|
814
|
-
*
|
|
815
|
-
* time, so each window starts a tenth of a second early and discards up to what it needs.
|
|
749
|
+
* Whether this browser hands `resource`'s video over as planes the engine reads, for sources that
|
|
750
|
+
* need them (HDR, or a `declared` color). Resolves `"not-required"`, `"decoder"`, or `"software"`
|
|
751
|
+
* when only a software decoder gives planar frames. Each decode waits at most `timeoutMs`
|
|
752
|
+
* (default 5000). Rejects with {@link PlanarDecodeUnavailableError} when no readable frames
|
|
753
|
+
* decode, and with {@link DecodeUnavailableError} when there is no video track.
|
|
816
754
|
*/
|
|
817
|
-
|
|
755
|
+
export async function probePlanarDecode(resource, options) {
|
|
756
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
|
|
757
|
+
const name = resource instanceof File ? resource.name : "the video";
|
|
758
|
+
const source = resource instanceof Blob
|
|
759
|
+
? new BlobSource(resource)
|
|
760
|
+
: new BufferSource(resource);
|
|
761
|
+
const input = new Input({ source, formats: ALL_FORMATS });
|
|
762
|
+
try {
|
|
763
|
+
const track = await input.getPrimaryVideoTrack();
|
|
764
|
+
if (track === null) {
|
|
765
|
+
const facts = { kind: "video", codec: null };
|
|
766
|
+
throw new DecodeUnavailableError(`${name} has no video track`, facts);
|
|
767
|
+
}
|
|
768
|
+
const facts = await videoTrackFacts(track);
|
|
769
|
+
const hdr = facts.transfer === "pq" || facts.transfer === "hlg";
|
|
770
|
+
if (!hdr && options.declared === null)
|
|
771
|
+
return { planes: "not-required" };
|
|
772
|
+
if (!(await track.canDecode()))
|
|
773
|
+
throw new PlanarDecodeUnavailableError(decodeRefusalMessage(name, facts), facts);
|
|
774
|
+
let decoded;
|
|
775
|
+
try {
|
|
776
|
+
decoded = await firstFramePlanes(track, "no-preference", timeoutMs);
|
|
777
|
+
}
|
|
778
|
+
catch (cause) {
|
|
779
|
+
const refused = {
|
|
780
|
+
...facts,
|
|
781
|
+
browserError: cause instanceof Error ? cause.message : String(cause),
|
|
782
|
+
};
|
|
783
|
+
throw new PlanarDecodeUnavailableError(decodeRefusalMessage(name, refused), refused, { cause });
|
|
784
|
+
}
|
|
785
|
+
if (decoded.planar)
|
|
786
|
+
return { planes: "decoder" };
|
|
787
|
+
const config = await track.getDecoderConfig();
|
|
788
|
+
const software = typeof VideoDecoder !== "undefined" &&
|
|
789
|
+
config !== null &&
|
|
790
|
+
(await VideoDecoder.isConfigSupported({
|
|
791
|
+
...config,
|
|
792
|
+
hardwareAcceleration: "prefer-software",
|
|
793
|
+
})).supported === true;
|
|
794
|
+
if (software) {
|
|
795
|
+
const again = await firstFramePlanes(track, "prefer-software", timeoutMs).catch(() => undefined);
|
|
796
|
+
if (again?.planar === true)
|
|
797
|
+
return { planes: "software" };
|
|
798
|
+
}
|
|
799
|
+
const refused = {
|
|
800
|
+
...facts,
|
|
801
|
+
frameFormat: decoded.format,
|
|
802
|
+
softwareDecoder: software ? "opaque" : "none",
|
|
803
|
+
};
|
|
804
|
+
throw new PlanarDecodeUnavailableError(decodeRefusalMessage(name, refused), refused);
|
|
805
|
+
}
|
|
806
|
+
finally {
|
|
807
|
+
input.dispose();
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
const AUDIO_TRIAL_DECODE_MS = 2_000;
|
|
811
|
+
/** -80 dBFS. */
|
|
812
|
+
const SILENT_PLANE_RMS = 1e-4;
|
|
813
|
+
/** Resolves to null for a track with no packet; rejects on decoder error or timeout. */
|
|
814
|
+
async function trialAudioDecode(track) {
|
|
815
|
+
const samples = new AudioSampleSink(track).samples();
|
|
816
|
+
let settled = false;
|
|
817
|
+
try {
|
|
818
|
+
const first = await withinActiveTime(samples.next(), AUDIO_TRIAL_DECODE_MS, () => new DOMException(`the audio decoder gave nothing within ${AUDIO_TRIAL_DECODE_MS / 1000} s`, "TimeoutError"));
|
|
819
|
+
settled = true;
|
|
820
|
+
if (first.done === true)
|
|
821
|
+
return null;
|
|
822
|
+
const sample = first.value;
|
|
823
|
+
try {
|
|
824
|
+
const plane = new Float32Array(sample.numberOfFrames);
|
|
825
|
+
const planeRms = Array.from({ length: sample.numberOfChannels }, (_, index) => {
|
|
826
|
+
sample.copyTo(plane, { planeIndex: index, format: "f32-planar" });
|
|
827
|
+
let sum = 0;
|
|
828
|
+
for (const value of plane)
|
|
829
|
+
sum += value * value;
|
|
830
|
+
return Math.sqrt(sum / Math.max(1, plane.length));
|
|
831
|
+
});
|
|
832
|
+
return {
|
|
833
|
+
channels: sample.numberOfChannels,
|
|
834
|
+
sampleRate: sample.sampleRate,
|
|
835
|
+
planeRms,
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
finally {
|
|
839
|
+
sample.close();
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
finally {
|
|
843
|
+
// A decoder that never answered may never let the iterator end; leave it to input disposal.
|
|
844
|
+
if (settled)
|
|
845
|
+
await samples.return(undefined);
|
|
846
|
+
else
|
|
847
|
+
void samples.return(undefined).catch(() => { });
|
|
848
|
+
}
|
|
849
|
+
}
|
|
818
850
|
/**
|
|
819
|
-
*
|
|
820
|
-
*
|
|
821
|
-
*
|
|
851
|
+
* Whether this browser decodes `track`, by a trial decode of its first packet (Firefox's
|
|
852
|
+
* `canDecode()` says true for AAC layouts it then rejects), and the channel count, rate and
|
|
853
|
+
* speakers it delivers. A silent extra plane is taken as an added LFE (Edge decodes E-AC-3 5.0 as
|
|
854
|
+
* 5.1). Rejects with {@link DecodeUnavailableError} when the track does not decode as declared.
|
|
822
855
|
*/
|
|
823
|
-
|
|
856
|
+
export async function probeAudioDecode(name, track, declared) {
|
|
857
|
+
const codec = (await track.getCodecParameterString().catch(() => null)) ??
|
|
858
|
+
track.codec ??
|
|
859
|
+
null;
|
|
860
|
+
const facts = {
|
|
861
|
+
kind: "audio",
|
|
862
|
+
codec,
|
|
863
|
+
channels: track.numberOfChannels,
|
|
864
|
+
...(declared === null ? {} : { layout: [...declared] }),
|
|
865
|
+
};
|
|
866
|
+
const refuse = (detail, cause) => new DecodeUnavailableError(decodeRefusalMessage(name, { ...facts, browserError: detail }), { ...facts, browserError: detail }, cause === undefined ? undefined : { cause });
|
|
867
|
+
if (!(await track.canDecode().catch(() => false)))
|
|
868
|
+
throw refuse("the browser has no decoder for this audio");
|
|
869
|
+
let trial;
|
|
870
|
+
try {
|
|
871
|
+
trial = await trialAudioDecode(track);
|
|
872
|
+
}
|
|
873
|
+
catch (error) {
|
|
874
|
+
throw refuse(`the trial decode failed: ${String(error?.message ?? error)}`, error);
|
|
875
|
+
}
|
|
876
|
+
if (trial === null)
|
|
877
|
+
return {
|
|
878
|
+
channels: track.numberOfChannels,
|
|
879
|
+
sampleRate: track.sampleRate,
|
|
880
|
+
speakers: declared === null ? null : [...declared],
|
|
881
|
+
addedLfe: false,
|
|
882
|
+
trial: {
|
|
883
|
+
channels: track.numberOfChannels,
|
|
884
|
+
sampleRate: track.sampleRate,
|
|
885
|
+
planeRms: [],
|
|
886
|
+
},
|
|
887
|
+
};
|
|
888
|
+
if (trial.channels === track.numberOfChannels)
|
|
889
|
+
return {
|
|
890
|
+
channels: trial.channels,
|
|
891
|
+
sampleRate: trial.sampleRate,
|
|
892
|
+
speakers: declared === null ? null : [...declared],
|
|
893
|
+
addedLfe: false,
|
|
894
|
+
trial,
|
|
895
|
+
};
|
|
896
|
+
const withLfe = declared !== null && trial.channels === declared.length + 1
|
|
897
|
+
? speakersWithLfe(declared)
|
|
898
|
+
: null;
|
|
899
|
+
if (withLfe !== null && trial.planeRms[withLfe.lfePlane] <= SILENT_PLANE_RMS)
|
|
900
|
+
return {
|
|
901
|
+
channels: trial.channels,
|
|
902
|
+
sampleRate: trial.sampleRate,
|
|
903
|
+
speakers: withLfe.speakers,
|
|
904
|
+
addedLfe: true,
|
|
905
|
+
trial,
|
|
906
|
+
};
|
|
907
|
+
throw refuse(`the decoder delivers ${trial.channels} channels for a source that declares ${track.numberOfChannels}`);
|
|
908
|
+
}
|
|
909
|
+
/** {@link probeAudioDecode} on the primary audio track; rejects with `Error` when there is none. */
|
|
910
|
+
export async function probeAudioSource(name, resource) {
|
|
911
|
+
const input = new Input({
|
|
912
|
+
source: resource instanceof Blob
|
|
913
|
+
? new BlobSource(resource)
|
|
914
|
+
: new BufferSource(resource),
|
|
915
|
+
formats: ALL_FORMATS,
|
|
916
|
+
});
|
|
917
|
+
try {
|
|
918
|
+
const track = await input.getPrimaryAudioTrack();
|
|
919
|
+
if (track === null)
|
|
920
|
+
throw new Error("mediabunny input has no audio track");
|
|
921
|
+
const config = await track.getDecoderConfig();
|
|
922
|
+
const declared = await readAudioSpeakers(byteReader(resource), byteLength(resource), track, bufferBytes(config?.description), () => new EncodedPacketSink(track)
|
|
923
|
+
.getFirstPacket()
|
|
924
|
+
.then((packet) => packet?.data ?? null));
|
|
925
|
+
return await probeAudioDecode(name, track, declared);
|
|
926
|
+
}
|
|
927
|
+
finally {
|
|
928
|
+
input.dispose();
|
|
929
|
+
}
|
|
930
|
+
}
|
|
824
931
|
/**
|
|
825
|
-
* Optional mediabunny audio demux/decode adapter with project-rate resampling
|
|
826
|
-
*
|
|
827
|
-
*
|
|
828
|
-
*
|
|
829
|
-
* silence, one further back drops what it repeats. A window's first sample goes on the frame grid
|
|
830
|
-
* the stream's first timestamps show ({@link audioFrameGrid}), so in a file that rounds them
|
|
831
|
-
* (Matroska, WebM) every window holds its samples where a decode from the start puts them. A
|
|
832
|
-
* window's source samples are then resampled together by the engine's `AudioResampler`, so a window
|
|
833
|
-
* holds the samples a native decode of the same source holds.
|
|
834
|
-
*
|
|
835
|
-
* Every channel is kept, 1 to {@link MAX_AUDIO_CHANNELS}, and each block names the speaker each
|
|
836
|
-
* feeds ({@link MediabunnyAudioDecoder.speakers}), read from the file as a native host reads it: a
|
|
837
|
-
* WAVE channel mask, a QuickTime `chan` box, or the codec's channel configuration (AAC, Opus
|
|
838
|
-
* mapping family 1, Vorbis, FLAC). The engine folds them by speaker. Those speakers are in the
|
|
839
|
-
* order `FFmpeg`'s decoder delivers; a browser decoder that delivers another (Safari's AAC decoder
|
|
840
|
-
* keeps the bitstream's) has its planes put back in that order, as measured once per kind of
|
|
841
|
-
* stream: an AAC channel configuration or program config element, an Opus or Vorbis channel
|
|
842
|
-
* count, an AC-3 or E-AC-3 layout ({@link decoderPlaneOrder}).
|
|
932
|
+
* Optional mediabunny audio demux/decode adapter with project-rate resampling, placing samples as
|
|
933
|
+
* a native host does (including the {@link audioFrameGrid}). Keeps every channel, 1 to
|
|
934
|
+
* {@link MAX_AUDIO_CHANNELS}, reordered to `FFmpeg`'s plane order where a browser decoder differs
|
|
935
|
+
* (Safari's AAC).
|
|
843
936
|
*/
|
|
844
937
|
export class MediabunnyAudioDecoder {
|
|
845
938
|
#sourceId;
|
|
@@ -847,37 +940,24 @@ export class MediabunnyAudioDecoder {
|
|
|
847
940
|
#sink;
|
|
848
941
|
#channelCount;
|
|
849
942
|
/**
|
|
850
|
-
* The speaker each plane
|
|
851
|
-
* `
|
|
852
|
-
* no `speakers`, and the engine assumes `FFmpeg`'s default for the channel count, as a native
|
|
853
|
-
* host does. A host may report a `null` layout of more than two channels as a guess.
|
|
943
|
+
* The speaker each plane feeds. `null` when the source declares no layout; the engine then
|
|
944
|
+
* assumes `FFmpeg`'s default for the channel count.
|
|
854
945
|
*/
|
|
855
946
|
speakers;
|
|
856
947
|
/**
|
|
857
|
-
*
|
|
858
|
-
* is not the same plane (measured, {@link decoderPlaneOrder}); `undefined` when every plane is
|
|
859
|
-
* where the speakers say.
|
|
948
|
+
* Delivered plane to speaker-order index ({@link decoderPlaneOrder}); `undefined` if identity.
|
|
860
949
|
*/
|
|
861
950
|
#planeOrder;
|
|
862
951
|
#sourceRate;
|
|
863
|
-
/**
|
|
864
|
-
* Where the stream's frames start, as its first timestamps show ({@link audioFrameGrid}): the
|
|
865
|
-
* first sample a window decodes is placed on it, as a native host places the first frame after
|
|
866
|
-
* a seek.
|
|
867
|
-
*/
|
|
868
952
|
#grid;
|
|
869
|
-
/** How far before what a window needs its decoding starts, in seconds: the codec's pre-roll. */
|
|
870
953
|
#preroll;
|
|
871
|
-
/**
|
|
872
|
-
* How far the demuxer's timestamps are after the samples' presentation times, in seconds: a
|
|
873
|
-
* Matroska track's `CodecDelay` in its time base ({@link readMatroskaCodecDelay}), which
|
|
874
|
-
* mediabunny does not subtract; 0 in any other container.
|
|
875
|
-
*/
|
|
954
|
+
/** Matroska `CodecDelay` in seconds, which mediabunny does not subtract. */
|
|
876
955
|
#delay;
|
|
877
956
|
#binding;
|
|
957
|
+
#facts;
|
|
878
958
|
#resampler;
|
|
879
959
|
#closed = false;
|
|
880
|
-
constructor(sourceId, input, sink, channelCount, speakers, planeOrder, sourceRate, grid, preroll, delay, binding) {
|
|
960
|
+
constructor(sourceId, input, sink, channelCount, speakers, planeOrder, sourceRate, grid, preroll, delay, binding, facts) {
|
|
881
961
|
this.#sourceId = sourceId;
|
|
882
962
|
this.#input = input;
|
|
883
963
|
this.#sink = sink;
|
|
@@ -889,13 +969,12 @@ export class MediabunnyAudioDecoder {
|
|
|
889
969
|
this.#preroll = preroll;
|
|
890
970
|
this.#delay = delay;
|
|
891
971
|
this.#binding = binding;
|
|
972
|
+
this.#facts = facts;
|
|
892
973
|
}
|
|
893
974
|
/**
|
|
894
|
-
* Opens `resource`'s primary audio track,
|
|
895
|
-
*
|
|
896
|
-
*
|
|
897
|
-
* {@link MAX_AUDIO_CHANNELS} or its sample rate outside 1 kHz to 768 kHz (`RangeError`), or when
|
|
898
|
-
* its decoder configuration or channel layout cannot be read.
|
|
975
|
+
* Opens `resource`'s primary audio track. Rejects when there is none, with `RangeError` for more
|
|
976
|
+
* than {@link MAX_AUDIO_CHANNELS} channels or a rate outside 1 kHz to 768 kHz, and with
|
|
977
|
+
* {@link DecodeUnavailableError} when this browser cannot decode it.
|
|
899
978
|
*/
|
|
900
979
|
static async open(sourceId, resource, binding) {
|
|
901
980
|
const source = resource instanceof Blob
|
|
@@ -907,14 +986,15 @@ export class MediabunnyAudioDecoder {
|
|
|
907
986
|
input.dispose();
|
|
908
987
|
throw new Error("mediabunny input has no audio track");
|
|
909
988
|
}
|
|
910
|
-
|
|
911
|
-
|
|
989
|
+
if (track.numberOfChannels < 1 ||
|
|
990
|
+
track.numberOfChannels > MAX_AUDIO_CHANNELS) {
|
|
912
991
|
input.dispose();
|
|
913
|
-
throw new RangeError(`audio with ${
|
|
992
|
+
throw new RangeError(`audio with ${track.numberOfChannels} channels is unsupported: the engine takes 1 to ${MAX_AUDIO_CHANNELS}`);
|
|
914
993
|
}
|
|
915
994
|
let speakers;
|
|
916
995
|
let description;
|
|
917
996
|
let planeOrder;
|
|
997
|
+
let decodable;
|
|
918
998
|
try {
|
|
919
999
|
const config = await track.getDecoderConfig();
|
|
920
1000
|
description = bufferBytes(config?.description);
|
|
@@ -923,16 +1003,27 @@ export class MediabunnyAudioDecoder {
|
|
|
923
1003
|
const readFirstPacket = () => (firstPacket ??= new EncodedPacketSink(track)
|
|
924
1004
|
.getFirstPacket()
|
|
925
1005
|
.then((packet) => packet?.data ?? null));
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
1006
|
+
const declared = await readAudioSpeakers(byteReader(resource), byteLength(resource), track, description, readFirstPacket);
|
|
1007
|
+
decodable = await probeAudioDecode(sourceId, track, declared);
|
|
1008
|
+
speakers = decodable.speakers;
|
|
1009
|
+
// The measured order does not cover an added LFE, which the decoder puts in native order.
|
|
1010
|
+
planeOrder = decodable.addedLfe
|
|
1011
|
+
? null
|
|
1012
|
+
: await decoderPlaneOrder(decoderOrderKey(track.codec, description, track.numberOfChannels, track.codec === "ac3" || track.codec === "eac3"
|
|
1013
|
+
? await readFirstPacket()
|
|
1014
|
+
: null));
|
|
930
1015
|
}
|
|
931
1016
|
catch (error) {
|
|
932
1017
|
input.dispose();
|
|
933
1018
|
throw error;
|
|
934
1019
|
}
|
|
935
|
-
const
|
|
1020
|
+
const channelCount = decodable.channels;
|
|
1021
|
+
if (channelCount > MAX_AUDIO_CHANNELS) {
|
|
1022
|
+
input.dispose();
|
|
1023
|
+
throw new RangeError(`audio decoded to ${channelCount} channels is unsupported: the engine takes 1 to ${MAX_AUDIO_CHANNELS}`);
|
|
1024
|
+
}
|
|
1025
|
+
// An implicitly signalled AAC extension decodes at twice the header's rate.
|
|
1026
|
+
const sourceRate = decodable.sampleRate;
|
|
936
1027
|
if (!Number.isInteger(sourceRate) ||
|
|
937
1028
|
sourceRate < SOURCE_SAMPLE_RATES.min ||
|
|
938
1029
|
sourceRate > SOURCE_SAMPLE_RATES.max) {
|
|
@@ -943,8 +1034,7 @@ export class MediabunnyAudioDecoder {
|
|
|
943
1034
|
let delay;
|
|
944
1035
|
try {
|
|
945
1036
|
const first = await firstPacketTimes(track, new EncodedPacketSink(track));
|
|
946
|
-
//
|
|
947
|
-
// FFmpeg does, so the samples line up with the same encode's in MP4.
|
|
1037
|
+
// Native hosts subtract `CodecDelay`, so the samples line up with the same encode in MP4.
|
|
948
1038
|
const codecDelay = await readMatroskaCodecDelay(resource, track.id);
|
|
949
1039
|
let packetGrid;
|
|
950
1040
|
if (first === undefined)
|
|
@@ -954,8 +1044,7 @@ export class MediabunnyAudioDecoder {
|
|
|
954
1044
|
delay = delayUnits / first.resolution;
|
|
955
1045
|
packetGrid = audioFrameGrid(first.timestamps.map((timestamp) => timestamp - delayUnits), first.resolution, sourceRate);
|
|
956
1046
|
}
|
|
957
|
-
//
|
|
958
|
-
// each window's frames start the pre-skip before the packet grid.
|
|
1047
|
+
// WebCodecs Opus drops the pre-skip from the first frame after each configure.
|
|
959
1048
|
const preSkip = track.codec === "opus" ? opusPreSkip(description) : 0;
|
|
960
1049
|
grid =
|
|
961
1050
|
packetGrid === undefined
|
|
@@ -970,7 +1059,12 @@ export class MediabunnyAudioDecoder {
|
|
|
970
1059
|
planeOrder.length !== channelCount ||
|
|
971
1060
|
planeOrder.every((engine, plane) => engine === plane)
|
|
972
1061
|
? undefined
|
|
973
|
-
: planeOrder, sourceRate, grid, track.codec === "opus" ? OPUS_PREROLL_SECONDS : AUDIO_PREROLL_SECONDS, delay, binding
|
|
1062
|
+
: planeOrder, sourceRate, grid, track.codec === "opus" ? OPUS_PREROLL_SECONDS : AUDIO_PREROLL_SECONDS, delay, binding, {
|
|
1063
|
+
kind: "audio",
|
|
1064
|
+
codec: track.codec ?? null,
|
|
1065
|
+
channels: track.numberOfChannels,
|
|
1066
|
+
...(speakers === null ? {} : { layout: speakers }),
|
|
1067
|
+
});
|
|
974
1068
|
}
|
|
975
1069
|
#resamplerTo(targetRate) {
|
|
976
1070
|
if (this.#resampler?.targetRate !== targetRate) {
|
|
@@ -983,12 +1077,10 @@ export class MediabunnyAudioDecoder {
|
|
|
983
1077
|
return this.#resampler.resampler;
|
|
984
1078
|
}
|
|
985
1079
|
/**
|
|
986
|
-
*
|
|
987
|
-
*
|
|
988
|
-
*
|
|
989
|
-
*
|
|
990
|
-
* the rate is not a positive integer, `signal` aborts, or the track changes channel count or
|
|
991
|
-
* sample rate mid-stream.
|
|
1080
|
+
* Decodes the interval at `projectSampleRate`, plus two samples each side; silence outside the
|
|
1081
|
+
* stream. Rejects when closed, for another source or empty interval, on abort, or when the track
|
|
1082
|
+
* changes format mid-stream; with {@link DecodeUnavailableError} when the browser's decoder
|
|
1083
|
+
* fails.
|
|
992
1084
|
*/
|
|
993
1085
|
async refill(request, projectSampleRate, signal) {
|
|
994
1086
|
if (this.#closed)
|
|
@@ -1000,7 +1092,6 @@ export class MediabunnyAudioDecoder {
|
|
|
1000
1092
|
if (!Number.isInteger(projectSampleRate) || projectSampleRate <= 0)
|
|
1001
1093
|
throw new RangeError("invalid project sample rate");
|
|
1002
1094
|
throwIfAborted(signal);
|
|
1003
|
-
// The two-sample margin lets the engine interpolate at either edge without the whole source.
|
|
1004
1095
|
const firstSample = Math.max(0, ticksToSampleFloor(request.startMediaTimeTicks, projectSampleRate) - 2);
|
|
1005
1096
|
const lastSample = ticksToSampleCeil(request.endMediaTimeTicks, projectSampleRate) + 2;
|
|
1006
1097
|
const frames = Math.max(1, lastSample - firstSample);
|
|
@@ -1011,61 +1102,66 @@ export class MediabunnyAudioDecoder {
|
|
|
1011
1102
|
const sourceEnd = resampler.sourceEnd(firstSample + frames);
|
|
1012
1103
|
const source = Array.from({ length: channelCount }, () => new Float32Array(sourceEnd - sourceStart));
|
|
1013
1104
|
const decodeFrom = sourceStart / rate - this.#preroll;
|
|
1014
|
-
/** The first sample decoded, when nothing comes before it in the stream. */
|
|
1015
1105
|
let streamStart;
|
|
1016
|
-
/** Where the next sample continues the last one placed. */
|
|
1017
1106
|
let expected;
|
|
1018
1107
|
const delay = this.#delay;
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1108
|
+
try {
|
|
1109
|
+
for await (const sample of this.#sink.samples(decodeFrom + delay, sourceEnd / rate + delay)) {
|
|
1110
|
+
try {
|
|
1111
|
+
throwIfAborted(signal);
|
|
1112
|
+
if (sample.numberOfChannels !== channelCount)
|
|
1113
|
+
throw new RangeError(`audio track changed from ${channelCount} to ${sample.numberOfChannels} channels`);
|
|
1114
|
+
if (sample.sampleRate !== rate)
|
|
1115
|
+
throw new RangeError(`audio track changed from ${rate} Hz to ${sample.sampleRate} Hz`);
|
|
1116
|
+
const length = sample.numberOfFrames;
|
|
1117
|
+
const timestamp = sample.timestamp - delay;
|
|
1118
|
+
let at = Math.round(timestamp * rate);
|
|
1119
|
+
let skip = 0;
|
|
1120
|
+
if (expected === undefined) {
|
|
1121
|
+
if (this.#grid !== undefined)
|
|
1122
|
+
at = placeOnAudioFrameGrid(this.#grid, at, length);
|
|
1123
|
+
// mediabunny starts at the packet holding the requested time, so a later first sample
|
|
1124
|
+
// is the stream's first.
|
|
1125
|
+
if (timestamp > decodeFrom)
|
|
1126
|
+
streamStart = at;
|
|
1127
|
+
}
|
|
1128
|
+
else {
|
|
1129
|
+
const ahead = at - expected;
|
|
1130
|
+
const tolerance = Math.max(length, Math.ceil(rate / 500));
|
|
1131
|
+
if (Math.abs(ahead) < tolerance)
|
|
1132
|
+
at = expected;
|
|
1133
|
+
else if (ahead < 0) {
|
|
1134
|
+
skip = Math.min(length, -ahead);
|
|
1135
|
+
at = expected;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
expected = at + length - skip;
|
|
1139
|
+
const from = Math.max(at, sourceStart);
|
|
1140
|
+
const to = Math.min(at + length - skip, sourceEnd);
|
|
1141
|
+
if (to <= from)
|
|
1142
|
+
continue;
|
|
1143
|
+
const data = new Float32Array(length);
|
|
1144
|
+
const order = this.#planeOrder;
|
|
1145
|
+
for (let plane = 0; plane < channelCount; plane += 1) {
|
|
1146
|
+
sample.copyTo(data, { planeIndex: plane, format: "f32-planar" });
|
|
1147
|
+
source[order === undefined ? plane : order[plane]].set(data.subarray(skip + from - at, skip + to - at), from - sourceStart);
|
|
1049
1148
|
}
|
|
1050
1149
|
}
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
const to = Math.min(at + length - skip, sourceEnd);
|
|
1054
|
-
if (to <= from)
|
|
1055
|
-
continue;
|
|
1056
|
-
const data = new Float32Array(length);
|
|
1057
|
-
const order = this.#planeOrder;
|
|
1058
|
-
for (let plane = 0; plane < channelCount; plane += 1) {
|
|
1059
|
-
sample.copyTo(data, { planeIndex: plane, format: "f32-planar" });
|
|
1060
|
-
source[order === undefined ? plane : order[plane]].set(data.subarray(skip + from - at, skip + to - at), from - sourceStart);
|
|
1150
|
+
finally {
|
|
1151
|
+
sample.close();
|
|
1061
1152
|
}
|
|
1062
1153
|
}
|
|
1063
|
-
|
|
1064
|
-
|
|
1154
|
+
}
|
|
1155
|
+
catch (error) {
|
|
1156
|
+
if (typeof DOMException !== "undefined" &&
|
|
1157
|
+
error instanceof DOMException &&
|
|
1158
|
+
error.name !== "AbortError") {
|
|
1159
|
+
const facts = { ...this.#facts, browserError: error.message };
|
|
1160
|
+
throw new DecodeUnavailableError(decodeRefusalMessage(this.#sourceId, facts), facts, { cause: error });
|
|
1065
1161
|
}
|
|
1162
|
+
throw error;
|
|
1066
1163
|
}
|
|
1067
|
-
//
|
|
1068
|
-
// stream's first and last samples rings past them.
|
|
1164
|
+
// A band-limited reading of the edge samples would ring past the stream.
|
|
1069
1165
|
const first = streamStart === undefined
|
|
1070
1166
|
? firstSample
|
|
1071
1167
|
: Math.max(firstSample, resampler.targetAtOrAfter(streamStart));
|
|
@@ -1089,7 +1185,6 @@ export class MediabunnyAudioDecoder {
|
|
|
1089
1185
|
channels,
|
|
1090
1186
|
};
|
|
1091
1187
|
}
|
|
1092
|
-
/** Frees the resampler and the input. A later `refill` rejects. */
|
|
1093
1188
|
close() {
|
|
1094
1189
|
if (!this.#closed) {
|
|
1095
1190
|
this.#closed = true;
|
|
@@ -1099,10 +1194,6 @@ export class MediabunnyAudioDecoder {
|
|
|
1099
1194
|
}
|
|
1100
1195
|
}
|
|
1101
1196
|
}
|
|
1102
|
-
/**
|
|
1103
|
-
* The mediabunny quality a video track encodes at for the engine's rate control: what
|
|
1104
|
-
* {@link MediabunnySink} configures its encoder with.
|
|
1105
|
-
*/
|
|
1106
1197
|
export function videoEncoderQuality(rate) {
|
|
1107
1198
|
return new Quality({
|
|
1108
1199
|
bitrate: rate.bitrate,
|
|
@@ -1110,17 +1201,13 @@ export function videoEncoderQuality(rate) {
|
|
|
1110
1201
|
...(rate.quantizer === undefined ? {} : { quantizer: rate.quantizer }),
|
|
1111
1202
|
});
|
|
1112
1203
|
}
|
|
1113
|
-
/** The H.264 profiles in the order they are asked for, with `profile_idc` and constraint flags. */
|
|
1114
1204
|
const AVC_PROFILES = [
|
|
1115
1205
|
{ profile: "High", prefix: "6400" },
|
|
1116
1206
|
{ profile: "Main", prefix: "4d00" },
|
|
1117
1207
|
// constraint_set0, 1 and 2: decodable by Baseline, Main and Extended decoders.
|
|
1118
1208
|
{ profile: "Constrained Baseline", prefix: "42e0" },
|
|
1119
1209
|
];
|
|
1120
|
-
/**
|
|
1121
|
-
* H.264 levels (`level_idc`) by frame size in macroblocks and bitrate: the table mediabunny picks
|
|
1122
|
-
* its own High profile level from, so the High string asked for here is the one it would build.
|
|
1123
|
-
*/
|
|
1210
|
+
/** H.264 levels by frame size in macroblocks and bitrate, as mediabunny picks them. */
|
|
1124
1211
|
const AVC_LEVELS = [
|
|
1125
1212
|
{ macroblocks: 99, bitrate: 64_000, level: 0x0a },
|
|
1126
1213
|
{ macroblocks: 396, bitrate: 192_000, level: 0x0b },
|
|
@@ -1143,10 +1230,8 @@ const AVC_LEVELS = [
|
|
|
1143
1230
|
{ macroblocks: 139_264, bitrate: 800_000_000, level: 0x3e },
|
|
1144
1231
|
];
|
|
1145
1232
|
/**
|
|
1146
|
-
* The profiles {@link canEncodeVideoTrack}
|
|
1147
|
-
*
|
|
1148
|
-
* encoder may take only the lower ones. Empty for the other codecs, which have one profile each
|
|
1149
|
-
* (HEVC Main, VP9 profile 0, AV1 Main) at the level mediabunny picks.
|
|
1233
|
+
* The H.264 profiles {@link canEncodeVideoTrack} tries, in order (High, Main, Constrained
|
|
1234
|
+
* Baseline), at the needed level. Empty for other codecs.
|
|
1150
1235
|
*/
|
|
1151
1236
|
export function videoEncoderProfiles(codec, options) {
|
|
1152
1237
|
if (codec !== "avc")
|
|
@@ -1163,10 +1248,8 @@ export function videoEncoderProfiles(codec, options) {
|
|
|
1163
1248
|
}
|
|
1164
1249
|
/**
|
|
1165
1250
|
* How this browser encodes `codec` video at `width`x`height` with `rate`, or `null` when it does
|
|
1166
|
-
* not
|
|
1167
|
-
*
|
|
1168
|
-
* encoder. H.264 is asked for in each of {@link videoEncoderProfiles} in turn, and the first one
|
|
1169
|
-
* encoded is chosen: pass its `codecString` to the sink, and report its `fallbacks`.
|
|
1251
|
+
* not. H.264 picks the first accepted of {@link videoEncoderProfiles}: pass its `codecString` to
|
|
1252
|
+
* the sink and report its `fallbacks`.
|
|
1170
1253
|
*/
|
|
1171
1254
|
export async function canEncodeVideoTrack(codec, options) {
|
|
1172
1255
|
const encodes = (fullCodecString) => canEncodeVideo(codec, {
|
|
@@ -1191,10 +1274,124 @@ export async function canEncodeVideoTrack(codec, options) {
|
|
|
1191
1274
|
}
|
|
1192
1275
|
return null;
|
|
1193
1276
|
}
|
|
1277
|
+
/** Whether this browser has a software encoder for this configuration. */
|
|
1278
|
+
export async function canEncodeInSoftware(codec, options) {
|
|
1279
|
+
return canEncodeVideo(codec, {
|
|
1280
|
+
width: options.width,
|
|
1281
|
+
height: options.height,
|
|
1282
|
+
quality: videoEncoderQuality(options.rate),
|
|
1283
|
+
hardwareAcceleration: "prefer-software",
|
|
1284
|
+
...(options.codecString === undefined
|
|
1285
|
+
? {}
|
|
1286
|
+
: { fullCodecString: options.codecString }),
|
|
1287
|
+
}).catch(() => false);
|
|
1288
|
+
}
|
|
1194
1289
|
/**
|
|
1195
|
-
* The
|
|
1196
|
-
*
|
|
1290
|
+
* The 10-bit codec string for `codec`; `undefined` for H.264, which browsers do not encode at 10
|
|
1291
|
+
* bits.
|
|
1197
1292
|
*/
|
|
1293
|
+
export function tenBitCodecString(codec) {
|
|
1294
|
+
switch (codec) {
|
|
1295
|
+
case "vp9":
|
|
1296
|
+
return "vp09.02.10.10";
|
|
1297
|
+
case "av1":
|
|
1298
|
+
return "av01.0.04M.10";
|
|
1299
|
+
case "hevc":
|
|
1300
|
+
return "hvc1.2.4.L123.B0";
|
|
1301
|
+
default:
|
|
1302
|
+
return undefined;
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
const PIXEL_PROBE_WIDTH = 64;
|
|
1306
|
+
const PIXEL_PROBE_HEIGHT = 64;
|
|
1307
|
+
const PIXEL_PROBE_TIMEOUT_MS = 3_000;
|
|
1308
|
+
/**
|
|
1309
|
+
* Whether this browser encodes `codec` in `pixels` (alpha, 10 bits, or both). Encodes one real
|
|
1310
|
+
* frame, since `isConfigSupported` can claim alpha that is then dropped.
|
|
1311
|
+
*/
|
|
1312
|
+
export async function canEncodePixels(codec, pixels) {
|
|
1313
|
+
if (pixels.bitDepth === 8 && !pixels.alpha)
|
|
1314
|
+
return true;
|
|
1315
|
+
if (typeof VideoEncoder === "undefined" || typeof VideoFrame === "undefined")
|
|
1316
|
+
return false;
|
|
1317
|
+
const codecString = pixels.bitDepth === 10
|
|
1318
|
+
? tenBitCodecString(codec)
|
|
1319
|
+
: LATENCY_PROBE_CODECS[codec];
|
|
1320
|
+
if (codecString === undefined)
|
|
1321
|
+
return false;
|
|
1322
|
+
const config = {
|
|
1323
|
+
codec: codecString,
|
|
1324
|
+
width: PIXEL_PROBE_WIDTH,
|
|
1325
|
+
height: PIXEL_PROBE_HEIGHT,
|
|
1326
|
+
bitrate: 500_000,
|
|
1327
|
+
framerate: 30,
|
|
1328
|
+
...(pixels.alpha ? { alpha: "keep" } : {}),
|
|
1329
|
+
};
|
|
1330
|
+
try {
|
|
1331
|
+
if (!(await VideoEncoder.isConfigSupported(config)).supported)
|
|
1332
|
+
return false;
|
|
1333
|
+
}
|
|
1334
|
+
catch {
|
|
1335
|
+
return false;
|
|
1336
|
+
}
|
|
1337
|
+
const format = `I420${pixels.alpha ? "A" : ""}${pixels.bitDepth === 10 ? "P10" : ""}`;
|
|
1338
|
+
const samples = PIXEL_PROBE_WIDTH * PIXEL_PROBE_HEIGHT;
|
|
1339
|
+
const bytes = pixels.bitDepth === 10 ? 2 : 1;
|
|
1340
|
+
const planes = (1.5 + (pixels.alpha ? 1 : 0)) * samples * bytes;
|
|
1341
|
+
let encoder;
|
|
1342
|
+
const probeDone = new AbortController();
|
|
1343
|
+
try {
|
|
1344
|
+
let kept = false;
|
|
1345
|
+
let failed = false;
|
|
1346
|
+
let settle = () => { };
|
|
1347
|
+
const output = new Promise((resolve) => (settle = resolve));
|
|
1348
|
+
encoder = new VideoEncoder({
|
|
1349
|
+
output: (_chunk, metadata) => {
|
|
1350
|
+
// `alphaSideData` is newer than the DOM types this package builds with.
|
|
1351
|
+
const alpha = metadata
|
|
1352
|
+
?.alphaSideData;
|
|
1353
|
+
kept = !pixels.alpha || alpha !== undefined;
|
|
1354
|
+
settle();
|
|
1355
|
+
},
|
|
1356
|
+
error: () => {
|
|
1357
|
+
failed = true;
|
|
1358
|
+
settle();
|
|
1359
|
+
},
|
|
1360
|
+
});
|
|
1361
|
+
encoder.configure(config);
|
|
1362
|
+
const frame = new VideoFrame(new Uint8Array(planes), {
|
|
1363
|
+
format: format,
|
|
1364
|
+
codedWidth: PIXEL_PROBE_WIDTH,
|
|
1365
|
+
codedHeight: PIXEL_PROBE_HEIGHT,
|
|
1366
|
+
timestamp: 0,
|
|
1367
|
+
});
|
|
1368
|
+
try {
|
|
1369
|
+
encoder.encode(frame, { keyFrame: true });
|
|
1370
|
+
}
|
|
1371
|
+
finally {
|
|
1372
|
+
frame.close();
|
|
1373
|
+
}
|
|
1374
|
+
await Promise.race([
|
|
1375
|
+
output,
|
|
1376
|
+
encoder.flush().catch(() => (failed = true)),
|
|
1377
|
+
activeTimeout(PIXEL_PROBE_TIMEOUT_MS, probeDone.signal),
|
|
1378
|
+
]);
|
|
1379
|
+
return kept && !failed;
|
|
1380
|
+
}
|
|
1381
|
+
catch {
|
|
1382
|
+
return false;
|
|
1383
|
+
}
|
|
1384
|
+
finally {
|
|
1385
|
+
probeDone.abort();
|
|
1386
|
+
try {
|
|
1387
|
+
if (encoder?.state !== "closed")
|
|
1388
|
+
encoder?.close();
|
|
1389
|
+
}
|
|
1390
|
+
catch {
|
|
1391
|
+
// Already closed by its own failure.
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1198
1395
|
const LATENCY_PROBE_CODECS = {
|
|
1199
1396
|
avc: "avc1.64001e",
|
|
1200
1397
|
hevc: "hev1.1.6.L93.B0",
|
|
@@ -1205,33 +1402,57 @@ const LATENCY_PROBE_WIDTH = 320;
|
|
|
1205
1402
|
const LATENCY_PROBE_HEIGHT = 240;
|
|
1206
1403
|
/** More frames than Safari's encoder takes in before it stops. */
|
|
1207
1404
|
const LATENCY_PROBE_FRAMES = 6;
|
|
1208
|
-
/** How long a probe encoder has to put out its first chunk. */
|
|
1209
1405
|
const LATENCY_PROBE_TIMEOUT_MS = 1_500;
|
|
1210
1406
|
const latencyModes = new Map();
|
|
1211
|
-
/**
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
*/
|
|
1216
|
-
export function
|
|
1217
|
-
|
|
1218
|
-
if (
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1407
|
+
/** `"realtime"` only where a quality-mode encoder outputs nothing (Safari 27's H.264). */
|
|
1408
|
+
export async function videoEncoderLatencyMode(codec) {
|
|
1409
|
+
return (await videoEncoderLatencyProbe(codec)).mode;
|
|
1410
|
+
}
|
|
1411
|
+
/** {@link videoEncoderLatencyMode} with how it was measured. */
|
|
1412
|
+
export async function videoEncoderLatencyProbe(codec) {
|
|
1413
|
+
const known = latencyModes.get(codec);
|
|
1414
|
+
if (known !== undefined) {
|
|
1415
|
+
const { probe, definitive } = await known;
|
|
1416
|
+
if (definitive)
|
|
1417
|
+
return { ...probe, cached: true };
|
|
1418
|
+
}
|
|
1419
|
+
const measuring = measureLatencyMode(codec);
|
|
1420
|
+
latencyModes.set(codec, measuring);
|
|
1421
|
+
const { probe, definitive } = await measuring;
|
|
1422
|
+
if (!definitive && latencyModes.get(codec) === measuring)
|
|
1423
|
+
latencyModes.delete(codec);
|
|
1424
|
+
return probe;
|
|
1223
1425
|
}
|
|
1224
1426
|
async function measureLatencyMode(codec) {
|
|
1427
|
+
const started = performance.now();
|
|
1428
|
+
const answer = (mode, outcome, definitive) => ({
|
|
1429
|
+
probe: { mode, ms: performance.now() - started, outcome, cached: false },
|
|
1430
|
+
definitive,
|
|
1431
|
+
});
|
|
1225
1432
|
if (typeof VideoEncoder === "undefined")
|
|
1226
|
-
return "quality";
|
|
1227
|
-
// One at a time: on Chrome a realtime encoder
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1433
|
+
return answer("quality", "unavailable", true);
|
|
1434
|
+
// One at a time: on Chrome a concurrent realtime encoder delays the quality one.
|
|
1435
|
+
const quality = await encoderPutsOut(codec, "quality");
|
|
1436
|
+
if (quality === "output")
|
|
1437
|
+
return answer("quality", quality, true);
|
|
1438
|
+
if (quality === "failed")
|
|
1439
|
+
return answer("quality", quality, false);
|
|
1440
|
+
const realtime = await encoderPutsOut(codec, "realtime");
|
|
1441
|
+
// A silent quality encoder never outputs, so use the realtime one even if it only timed out.
|
|
1442
|
+
if (quality === "silent" && realtime === "timed-out")
|
|
1443
|
+
return answer("realtime", realtime, false);
|
|
1444
|
+
if (realtime !== "output")
|
|
1445
|
+
return answer("quality", realtime, false);
|
|
1446
|
+
if (quality === "silent")
|
|
1447
|
+
return answer("realtime", realtime, true);
|
|
1448
|
+
// Retry the timed-out quality probe now that the encoder is warm.
|
|
1449
|
+
const warm = await encoderPutsOut(codec, "quality");
|
|
1450
|
+
if (warm === "output")
|
|
1451
|
+
return answer("quality", warm, true);
|
|
1452
|
+
if (warm === "timed-out" || warm === "silent")
|
|
1453
|
+
return answer("realtime", realtime, true);
|
|
1454
|
+
return answer("quality", warm, false);
|
|
1233
1455
|
}
|
|
1234
|
-
/** `true` once the encoder puts out a chunk, `false` if it puts out none, `undefined` if it failed. */
|
|
1235
1456
|
async function encoderPutsOut(codec, latencyMode) {
|
|
1236
1457
|
const config = {
|
|
1237
1458
|
codec: LATENCY_PROBE_CODECS[codec],
|
|
@@ -1244,15 +1465,16 @@ async function encoderPutsOut(codec, latencyMode) {
|
|
|
1244
1465
|
};
|
|
1245
1466
|
try {
|
|
1246
1467
|
if (!(await VideoEncoder.isConfigSupported(config)).supported)
|
|
1247
|
-
return
|
|
1468
|
+
return "failed";
|
|
1248
1469
|
}
|
|
1249
1470
|
catch {
|
|
1250
|
-
return
|
|
1471
|
+
return "failed";
|
|
1251
1472
|
}
|
|
1252
1473
|
let outputs = 0;
|
|
1253
1474
|
let failed = false;
|
|
1475
|
+
let flushed = false;
|
|
1254
1476
|
let encoder;
|
|
1255
|
-
|
|
1477
|
+
const probeDone = new AbortController();
|
|
1256
1478
|
let putOut = () => { };
|
|
1257
1479
|
const firstOutput = new Promise((resolve) => (putOut = resolve));
|
|
1258
1480
|
try {
|
|
@@ -1283,20 +1505,20 @@ async function encoderPutsOut(codec, latencyMode) {
|
|
|
1283
1505
|
}
|
|
1284
1506
|
await Promise.race([
|
|
1285
1507
|
firstOutput,
|
|
1286
|
-
encoder.flush().
|
|
1287
|
-
|
|
1288
|
-
timer = setTimeout(resolve, LATENCY_PROBE_TIMEOUT_MS);
|
|
1289
|
-
}),
|
|
1508
|
+
encoder.flush().then(() => (flushed = true), () => (failed = true)),
|
|
1509
|
+
activeTimeout(LATENCY_PROBE_TIMEOUT_MS, probeDone.signal),
|
|
1290
1510
|
]);
|
|
1291
1511
|
if (outputs > 0)
|
|
1292
|
-
return
|
|
1293
|
-
|
|
1512
|
+
return "output";
|
|
1513
|
+
if (failed)
|
|
1514
|
+
return "failed";
|
|
1515
|
+
return flushed ? "silent" : "timed-out";
|
|
1294
1516
|
}
|
|
1295
1517
|
catch {
|
|
1296
|
-
return
|
|
1518
|
+
return "failed";
|
|
1297
1519
|
}
|
|
1298
1520
|
finally {
|
|
1299
|
-
|
|
1521
|
+
probeDone.abort();
|
|
1300
1522
|
try {
|
|
1301
1523
|
if (encoder?.state !== "closed")
|
|
1302
1524
|
encoder?.close();
|
|
@@ -1306,10 +1528,6 @@ async function encoderPutsOut(codec, latencyMode) {
|
|
|
1306
1528
|
}
|
|
1307
1529
|
}
|
|
1308
1530
|
}
|
|
1309
|
-
/**
|
|
1310
|
-
* The sample rates each audio codec a {@link MediabunnySink} writes can carry, lowest first:
|
|
1311
|
-
* AAC's MPEG-4 rates up to the project limit, and Opus's.
|
|
1312
|
-
*/
|
|
1313
1531
|
const ENCODER_SAMPLE_RATES = {
|
|
1314
1532
|
aac: [
|
|
1315
1533
|
8_000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000,
|
|
@@ -1318,17 +1536,15 @@ const ENCODER_SAMPLE_RATES = {
|
|
|
1318
1536
|
opus: [8_000, 12_000, 16_000, 24_000, 48_000],
|
|
1319
1537
|
};
|
|
1320
1538
|
/**
|
|
1321
|
-
* The rate
|
|
1322
|
-
*
|
|
1323
|
-
*
|
|
1324
|
-
* encoder takes none. Pass it to {@link MediabunnySink} as `audioSampleRate`, so every project
|
|
1325
|
-
* rate exports where the browser encodes the codec at all.
|
|
1539
|
+
* The rate to encode `codec` audio at for a project at `sampleRate`: the project rate if supported,
|
|
1540
|
+
* else the nearest higher supported rate, else the nearest lower; `null` for none. Pass it to
|
|
1541
|
+
* {@link MediabunnySink} as `audioSampleRate`.
|
|
1326
1542
|
*/
|
|
1327
1543
|
export async function audioEncoderSampleRate(codec, options) {
|
|
1328
1544
|
const rate = options.sampleRate;
|
|
1329
1545
|
const carried = ENCODER_SAMPLE_RATES[codec];
|
|
1330
1546
|
const candidates = new Set([
|
|
1331
|
-
rate,
|
|
1547
|
+
...(codec === "opus" || carried.includes(rate) ? [rate] : []),
|
|
1332
1548
|
...carried.filter((candidate) => candidate > rate),
|
|
1333
1549
|
...carried.filter((candidate) => candidate < rate).reverse(),
|
|
1334
1550
|
]);
|
|
@@ -1337,28 +1553,236 @@ export async function audioEncoderSampleRate(codec, options) {
|
|
|
1337
1553
|
numberOfChannels: options.numberOfChannels,
|
|
1338
1554
|
sampleRate: candidate,
|
|
1339
1555
|
quality: new Quality({ bitrate: options.bitrate }),
|
|
1556
|
+
...(codec === "aac" ? { fullCodecString: AAC_CODEC_STRING } : {}),
|
|
1340
1557
|
}).catch(() => false);
|
|
1341
|
-
if (supported)
|
|
1558
|
+
if (!supported)
|
|
1559
|
+
continue;
|
|
1560
|
+
if (codec === "opus")
|
|
1561
|
+
return candidate;
|
|
1562
|
+
const { rate: putOut } = await probeAacEncoder({
|
|
1563
|
+
...options,
|
|
1564
|
+
sampleRate: candidate,
|
|
1565
|
+
});
|
|
1566
|
+
if (putOut === undefined || putOut === candidate)
|
|
1342
1567
|
return candidate;
|
|
1343
1568
|
}
|
|
1344
1569
|
return null;
|
|
1345
1570
|
}
|
|
1571
|
+
/** AAC-LC, as native hosts encode; mediabunny would pick HE-AAC at 24 kHz and below. */
|
|
1572
|
+
const AAC_CODEC_STRING = "mp4a.40.2";
|
|
1573
|
+
const AAC_FRAME_FRAMES = 1_024;
|
|
1574
|
+
/** ISO/IEC 14496-3 `samplingFrequencyIndex` values. */
|
|
1575
|
+
const AAC_SAMPLING_FREQUENCIES = [
|
|
1576
|
+
96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000,
|
|
1577
|
+
12_000, 11_025, 8_000, 7_350,
|
|
1578
|
+
];
|
|
1579
|
+
/** Undefined for a rate without an index or a channel count without a configuration. */
|
|
1580
|
+
function aacLcAudioSpecificConfig(sampleRate, numberOfChannels) {
|
|
1581
|
+
const frequency = AAC_SAMPLING_FREQUENCIES.indexOf(sampleRate);
|
|
1582
|
+
const channels = numberOfChannels === 8 ? 7 : numberOfChannels <= 6 ? numberOfChannels : 0;
|
|
1583
|
+
if (frequency < 0 || channels < 1)
|
|
1584
|
+
return undefined;
|
|
1585
|
+
return new Uint8Array([
|
|
1586
|
+
(2 << 3) | (frequency >> 1),
|
|
1587
|
+
((frequency & 1) << 7) | (channels << 3),
|
|
1588
|
+
]);
|
|
1589
|
+
}
|
|
1590
|
+
const AAC_DELAY_PROBE_FRAMES = 2_048;
|
|
1591
|
+
const AAC_DELAY_MAX_FRAMES = 8_192;
|
|
1592
|
+
const AAC_DELAY_PROBE_TIMEOUT_MS = 1_500;
|
|
1593
|
+
const AAC_DELAY_MIN_CORRELATION = 0.5;
|
|
1594
|
+
const aacProbes = new Map();
|
|
1346
1595
|
/**
|
|
1347
|
-
*
|
|
1348
|
-
*
|
|
1349
|
-
* samples it reads have arrived, the source silent outside them, and ending where the project's
|
|
1350
|
-
* audio does (the first output at or after its end).
|
|
1596
|
+
* The priming frames this browser's AAC-LC encoder puts before its input, which WebCodecs does not
|
|
1597
|
+
* report. Measured once per configuration by finding an encoded noise burst; 0 on failure.
|
|
1351
1598
|
*/
|
|
1599
|
+
export async function aacEncoderDelay(options) {
|
|
1600
|
+
return (await probeAacEncoder(options)).delay;
|
|
1601
|
+
}
|
|
1602
|
+
/** {@link aacEncoderDelay} with its outcome. Timeouts are retried once and never cached. */
|
|
1603
|
+
export function aacEncoderPrimingProbe(options) {
|
|
1604
|
+
return probeAacEncoder(options);
|
|
1605
|
+
}
|
|
1606
|
+
function probeAacEncoder(options) {
|
|
1607
|
+
const config = {
|
|
1608
|
+
codec: AAC_CODEC_STRING,
|
|
1609
|
+
sampleRate: options.sampleRate,
|
|
1610
|
+
numberOfChannels: options.numberOfChannels,
|
|
1611
|
+
bitrate: options.bitrate,
|
|
1612
|
+
};
|
|
1613
|
+
const key = JSON.stringify(config);
|
|
1614
|
+
const known = aacProbes.get(key);
|
|
1615
|
+
if (known !== undefined)
|
|
1616
|
+
return known;
|
|
1617
|
+
const probe = (async () => {
|
|
1618
|
+
const started = performance.now();
|
|
1619
|
+
let measured = await measureAacEncoder(config);
|
|
1620
|
+
let attempts = 1;
|
|
1621
|
+
if (measured.outcome === "timed-out") {
|
|
1622
|
+
measured = await measureAacEncoder(config);
|
|
1623
|
+
attempts = 2;
|
|
1624
|
+
}
|
|
1625
|
+
return { ...measured, ms: performance.now() - started, attempts };
|
|
1626
|
+
})();
|
|
1627
|
+
aacProbes.set(key, probe);
|
|
1628
|
+
void probe.then((measured) => {
|
|
1629
|
+
if (measured.outcome === "timed-out" && aacProbes.get(key) === probe)
|
|
1630
|
+
aacProbes.delete(key);
|
|
1631
|
+
});
|
|
1632
|
+
return probe;
|
|
1633
|
+
}
|
|
1634
|
+
async function measureAacEncoder(config) {
|
|
1635
|
+
if (typeof AudioEncoder === "undefined" ||
|
|
1636
|
+
typeof AudioDecoder === "undefined")
|
|
1637
|
+
return { delay: 0, outcome: "unavailable" };
|
|
1638
|
+
let encoder;
|
|
1639
|
+
let decoder;
|
|
1640
|
+
let timer;
|
|
1641
|
+
const timedOut = new Promise((resolve) => {
|
|
1642
|
+
timer = setTimeout(() => resolve("timeout"), AAC_DELAY_PROBE_TIMEOUT_MS);
|
|
1643
|
+
});
|
|
1644
|
+
try {
|
|
1645
|
+
if (!(await AudioEncoder.isConfigSupported(config)).supported)
|
|
1646
|
+
return { delay: 0, outcome: "failed" };
|
|
1647
|
+
let failed = false;
|
|
1648
|
+
const chunks = [];
|
|
1649
|
+
let decoderConfig;
|
|
1650
|
+
encoder = new AudioEncoder({
|
|
1651
|
+
output: (chunk, metadata) => {
|
|
1652
|
+
chunks.push(chunk);
|
|
1653
|
+
decoderConfig ??= metadata?.decoderConfig;
|
|
1654
|
+
},
|
|
1655
|
+
error: () => (failed = true),
|
|
1656
|
+
});
|
|
1657
|
+
encoder.configure(config);
|
|
1658
|
+
// Safari's encoder drops the first input frame, so the burst follows a frame of silence.
|
|
1659
|
+
const probe = aacDelayProbe();
|
|
1660
|
+
const frames = AAC_FRAME_FRAMES + AAC_DELAY_PROBE_FRAMES + AAC_DELAY_MAX_FRAMES;
|
|
1661
|
+
const planar = new Float32Array(frames * config.numberOfChannels);
|
|
1662
|
+
for (let channel = 0; channel < config.numberOfChannels; channel += 1)
|
|
1663
|
+
planar.set(probe, channel * frames + AAC_FRAME_FRAMES);
|
|
1664
|
+
const input = new AudioData({
|
|
1665
|
+
format: "f32-planar",
|
|
1666
|
+
sampleRate: config.sampleRate,
|
|
1667
|
+
numberOfFrames: frames,
|
|
1668
|
+
numberOfChannels: config.numberOfChannels,
|
|
1669
|
+
timestamp: 0,
|
|
1670
|
+
data: planar,
|
|
1671
|
+
});
|
|
1672
|
+
try {
|
|
1673
|
+
encoder.encode(input);
|
|
1674
|
+
}
|
|
1675
|
+
finally {
|
|
1676
|
+
input.close();
|
|
1677
|
+
}
|
|
1678
|
+
if ((await Promise.race([encoder.flush(), timedOut])) === "timeout")
|
|
1679
|
+
return { delay: 0, outcome: "timed-out" };
|
|
1680
|
+
if (failed || decoderConfig === undefined)
|
|
1681
|
+
return { delay: 0, outcome: "failed" };
|
|
1682
|
+
const rate = decoderConfig.sampleRate;
|
|
1683
|
+
if (rate !== config.sampleRate)
|
|
1684
|
+
return { rate, delay: 0, outcome: "output" };
|
|
1685
|
+
const planes = [];
|
|
1686
|
+
decoder = new AudioDecoder({
|
|
1687
|
+
output: (audio) => {
|
|
1688
|
+
try {
|
|
1689
|
+
if (audio.sampleRate !== config.sampleRate)
|
|
1690
|
+
failed = true;
|
|
1691
|
+
const plane = new Float32Array(audio.numberOfFrames);
|
|
1692
|
+
audio.copyTo(plane, { planeIndex: 0, format: "f32-planar" });
|
|
1693
|
+
planes.push(plane);
|
|
1694
|
+
}
|
|
1695
|
+
finally {
|
|
1696
|
+
audio.close();
|
|
1697
|
+
}
|
|
1698
|
+
},
|
|
1699
|
+
error: () => (failed = true),
|
|
1700
|
+
});
|
|
1701
|
+
// Safari's own decoder refuses its encoder's full `ES_Descriptor`.
|
|
1702
|
+
const description = aacLcAudioSpecificConfig(config.sampleRate, config.numberOfChannels);
|
|
1703
|
+
decoder.configure(description === undefined
|
|
1704
|
+
? decoderConfig
|
|
1705
|
+
: { ...decoderConfig, codec: AAC_CODEC_STRING, description });
|
|
1706
|
+
for (const chunk of chunks)
|
|
1707
|
+
decoder.decode(chunk);
|
|
1708
|
+
if ((await Promise.race([decoder.flush(), timedOut])) === "timeout")
|
|
1709
|
+
return { rate, delay: 0, outcome: "timed-out" };
|
|
1710
|
+
if (failed)
|
|
1711
|
+
return { rate, delay: 0, outcome: "failed" };
|
|
1712
|
+
const decoded = new Float32Array(planes.reduce((sum, plane) => sum + plane.length, 0));
|
|
1713
|
+
let offset = 0;
|
|
1714
|
+
for (const plane of planes) {
|
|
1715
|
+
decoded.set(plane, offset);
|
|
1716
|
+
offset += plane.length;
|
|
1717
|
+
}
|
|
1718
|
+
const lag = strongestLag(decoded, probe);
|
|
1719
|
+
return {
|
|
1720
|
+
rate,
|
|
1721
|
+
delay: lag === null ? 0 : Math.max(0, lag - AAC_FRAME_FRAMES),
|
|
1722
|
+
outcome: "output",
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
catch {
|
|
1726
|
+
return { delay: 0, outcome: "failed" };
|
|
1727
|
+
}
|
|
1728
|
+
finally {
|
|
1729
|
+
clearTimeout(timer);
|
|
1730
|
+
for (const coder of [encoder, decoder]) {
|
|
1731
|
+
try {
|
|
1732
|
+
if (coder?.state !== "closed")
|
|
1733
|
+
coder?.close();
|
|
1734
|
+
}
|
|
1735
|
+
catch {
|
|
1736
|
+
// Already closed by its own failure.
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
function aacDelayProbe() {
|
|
1742
|
+
const probe = new Float32Array(AAC_DELAY_PROBE_FRAMES);
|
|
1743
|
+
let seed = 1;
|
|
1744
|
+
let smoothed = 0;
|
|
1745
|
+
for (let index = 0; index < probe.length; index += 1) {
|
|
1746
|
+
seed = (Math.imul(seed, 1_103_515_245) + 12_345) >>> 0;
|
|
1747
|
+
smoothed += 0.5 * ((seed / 2 ** 32) * 2 - 1 - smoothed);
|
|
1748
|
+
probe[index] = 0.5 * smoothed;
|
|
1749
|
+
}
|
|
1750
|
+
return probe;
|
|
1751
|
+
}
|
|
1752
|
+
/** The lag where `decoded` best matches `probe`, or null when none matches closely enough. */
|
|
1753
|
+
function strongestLag(decoded, probe) {
|
|
1754
|
+
let probeEnergy = 0;
|
|
1755
|
+
for (const value of probe)
|
|
1756
|
+
probeEnergy += value * value;
|
|
1757
|
+
const energy = new Float64Array(decoded.length + 1);
|
|
1758
|
+
for (let index = 0; index < decoded.length; index += 1)
|
|
1759
|
+
energy[index + 1] = energy[index] + decoded[index] * decoded[index];
|
|
1760
|
+
const lags = Math.min(AAC_FRAME_FRAMES + AAC_DELAY_MAX_FRAMES, decoded.length - probe.length);
|
|
1761
|
+
let best = null;
|
|
1762
|
+
let bestCorrelation = AAC_DELAY_MIN_CORRELATION;
|
|
1763
|
+
for (let lag = 0; lag <= lags; lag += 1) {
|
|
1764
|
+
const windowEnergy = energy[lag + probe.length] - energy[lag];
|
|
1765
|
+
if (windowEnergy <= 0)
|
|
1766
|
+
continue;
|
|
1767
|
+
let sum = 0;
|
|
1768
|
+
for (let index = 0; index < probe.length; index += 1)
|
|
1769
|
+
sum += decoded[lag + index] * probe[index];
|
|
1770
|
+
const correlation = sum / Math.sqrt(probeEnergy * windowEnergy);
|
|
1771
|
+
if (correlation > bestCorrelation) {
|
|
1772
|
+
bestCorrelation = correlation;
|
|
1773
|
+
best = lag;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
return best;
|
|
1777
|
+
}
|
|
1778
|
+
/** Converts project-rate blocks to the encoder's rate with the engine's converter. */
|
|
1352
1779
|
class EncoderRateConverter {
|
|
1353
1780
|
targetRate;
|
|
1354
1781
|
#projectRate;
|
|
1355
1782
|
#resampler;
|
|
1356
|
-
/** The project samples from `#bufferStart` on that outputs still to be made may read. */
|
|
1357
1783
|
#buffer;
|
|
1358
1784
|
#bufferStart;
|
|
1359
|
-
/** The project sample the next block starts at. */
|
|
1360
1785
|
#received;
|
|
1361
|
-
/** The next output sample. */
|
|
1362
1786
|
#produced;
|
|
1363
1787
|
constructor(binding, first, targetRate) {
|
|
1364
1788
|
this.targetRate = targetRate;
|
|
@@ -1370,10 +1794,7 @@ class EncoderRateConverter {
|
|
|
1370
1794
|
this.#received = start;
|
|
1371
1795
|
this.#produced = this.#resampler.targetAtOrAfter(start);
|
|
1372
1796
|
}
|
|
1373
|
-
/**
|
|
1374
|
-
* Takes the next block, which must continue the last one at the same rate and channel count,
|
|
1375
|
-
* and returns the outputs it completes (`startSample` at the target rate), or null for none.
|
|
1376
|
-
*/
|
|
1797
|
+
/** Blocks must be contiguous at one rate and channel count. */
|
|
1377
1798
|
push(block) {
|
|
1378
1799
|
if (block.sampleRate !== this.#projectRate ||
|
|
1379
1800
|
block.channels.length !== this.#buffer.length)
|
|
@@ -1390,17 +1811,13 @@ class EncoderRateConverter {
|
|
|
1390
1811
|
this.#received += frames;
|
|
1391
1812
|
return this.#convert(this.#readyEnd());
|
|
1392
1813
|
}
|
|
1393
|
-
/** Ends the input: the outputs still to make, up to where the project's audio ends. */
|
|
1394
1814
|
finish() {
|
|
1395
1815
|
return this.#convert(this.#resampler.targetAtOrAfter(this.#received));
|
|
1396
1816
|
}
|
|
1397
|
-
/** Frees the engine's converter. */
|
|
1398
1817
|
free() {
|
|
1399
1818
|
this.#resampler.free?.();
|
|
1400
1819
|
}
|
|
1401
|
-
/** The end of the outputs whose samples have all arrived. */
|
|
1402
1820
|
#readyEnd() {
|
|
1403
|
-
// The output before `end` reads up to `sourceEnd(end)`, which grows with `end`.
|
|
1404
1821
|
let low = this.#produced;
|
|
1405
1822
|
let high = Math.max(low, this.#resampler.targetAtOrAfter(this.#received));
|
|
1406
1823
|
while (low < high) {
|
|
@@ -1426,11 +1843,7 @@ class EncoderRateConverter {
|
|
|
1426
1843
|
return { startSample: start, channels };
|
|
1427
1844
|
}
|
|
1428
1845
|
}
|
|
1429
|
-
|
|
1430
|
-
* The muxer for `container`. MP4 and MOV go without fast start and MKV and WebM are not
|
|
1431
|
-
* append-only, so the payload is never held in memory or rewritten: the muxer seeks back only to
|
|
1432
|
-
* patch headers.
|
|
1433
|
-
*/
|
|
1846
|
+
// No fast start and no append-only mode, so the muxer seeks back only to patch headers.
|
|
1434
1847
|
function outputFormat(container) {
|
|
1435
1848
|
switch (container) {
|
|
1436
1849
|
case "mp4":
|
|
@@ -1444,26 +1857,13 @@ function outputFormat(container) {
|
|
|
1444
1857
|
}
|
|
1445
1858
|
}
|
|
1446
1859
|
/**
|
|
1447
|
-
* Optional mediabunny encoder/muxer implementing both public alpha2 sinks.
|
|
1448
|
-
*
|
|
1449
|
-
*
|
|
1450
|
-
*
|
|
1451
|
-
* the video and `renderOfflineAudio` for the audio, at once or one after the other), give each its
|
|
1452
|
-
* track instead, {@link MediabunnySink.videoTrack} and {@link MediabunnySink.audioTrack}: a
|
|
1453
|
-
* runner's `finish` then ends its own track, and the file is finalized when every configured track
|
|
1454
|
-
* has ended. Either track's `abort` discards the whole file, and the other runner's next write
|
|
1455
|
-
* fails.
|
|
1456
|
-
*
|
|
1457
|
-
* The constructor throws `RangeError` when no track is configured, the container does not offer a
|
|
1458
|
-
* codec (an `ExportFormatError`), a codec lacks its rate, a memory destination's `maxBytes` is not
|
|
1459
|
-
* a positive safe integer, or `stallTimeoutMs` is out of range.
|
|
1860
|
+
* Optional mediabunny encoder/muxer implementing both public alpha2 sinks. When two runners share
|
|
1861
|
+
* the file, give each its own {@link MediabunnySink.videoTrack} or
|
|
1862
|
+
* {@link MediabunnySink.audioTrack}; the file is finalized once every configured track has ended,
|
|
1863
|
+
* and either `abort` discards it. The constructor throws `RangeError` for invalid options.
|
|
1460
1864
|
*/
|
|
1461
1865
|
export class MediabunnySink {
|
|
1462
1866
|
#target;
|
|
1463
|
-
/**
|
|
1464
|
-
* A stream destination, written through the muxer and committed or discarded by this sink alone:
|
|
1465
|
-
* see the constructor.
|
|
1466
|
-
*/
|
|
1467
1867
|
#file;
|
|
1468
1868
|
#discarded = false;
|
|
1469
1869
|
#output;
|
|
@@ -1472,12 +1872,21 @@ export class MediabunnySink {
|
|
|
1472
1872
|
#hasVideo;
|
|
1473
1873
|
#video;
|
|
1474
1874
|
#latencyMode;
|
|
1875
|
+
#latencyProbe;
|
|
1876
|
+
#acceleration;
|
|
1877
|
+
#addedAt = new Map();
|
|
1878
|
+
#encodeLatency = { totalMs: 0, maxMs: 0, count: 0 };
|
|
1879
|
+
#aacProbe;
|
|
1475
1880
|
#stallTimeoutMs;
|
|
1476
1881
|
#framesIn = 0;
|
|
1477
1882
|
#framesOut = 0;
|
|
1478
|
-
/**
|
|
1479
|
-
#
|
|
1883
|
+
/** Active time, so a frozen page does not count as a stall. */
|
|
1884
|
+
#progress;
|
|
1480
1885
|
#audio;
|
|
1886
|
+
#audioCodec;
|
|
1887
|
+
#audioBitrate;
|
|
1888
|
+
#audioDelay;
|
|
1889
|
+
#audioLeadWritten = false;
|
|
1481
1890
|
#audioRate;
|
|
1482
1891
|
#audioResampler;
|
|
1483
1892
|
#audioConverter;
|
|
@@ -1487,13 +1896,11 @@ export class MediabunnySink {
|
|
|
1487
1896
|
#finished = false;
|
|
1488
1897
|
#applied;
|
|
1489
1898
|
#codecString;
|
|
1490
|
-
/** Tracks whose runner finished, through {@link videoTrack} or {@link audioTrack}. */
|
|
1491
1899
|
#ended = new Set();
|
|
1492
1900
|
#videoTrack;
|
|
1493
1901
|
#audioTrack;
|
|
1494
1902
|
constructor(options) {
|
|
1495
|
-
//
|
|
1496
|
-
// mistake, not a failed export.
|
|
1903
|
+
// Validated before anything is opened, since an unsupported pair is a caller error.
|
|
1497
1904
|
resolveExportFormat({
|
|
1498
1905
|
container: options.container,
|
|
1499
1906
|
...(options.videoCodec === undefined
|
|
@@ -1509,8 +1916,7 @@ export class MediabunnySink {
|
|
|
1509
1916
|
destination.maxBytes <= 0)
|
|
1510
1917
|
throw new RangeError("memory destination maxBytes must be a positive safe integer");
|
|
1511
1918
|
this.#target = new BufferTarget();
|
|
1512
|
-
//
|
|
1513
|
-
// within what was budgeted for it.
|
|
1919
|
+
// Stopping at the reserved size keeps the output within its budget.
|
|
1514
1920
|
this.#target.onwrite = (_start, end) => {
|
|
1515
1921
|
this.#written = Math.max(this.#written, end);
|
|
1516
1922
|
if (end > destination.maxBytes)
|
|
@@ -1527,15 +1933,12 @@ export class MediabunnySink {
|
|
|
1527
1933
|
};
|
|
1528
1934
|
}
|
|
1529
1935
|
else {
|
|
1530
|
-
// mediabunny closes its stream on finish, failure and cancel alike, and
|
|
1531
|
-
//
|
|
1532
|
-
// discards it.
|
|
1936
|
+
// mediabunny closes its stream on finish, failure and cancel alike, and closing commits a
|
|
1937
|
+
// file, so the muxer gets its own stream and this sink commits or discards.
|
|
1533
1938
|
const file = destination.writable.getWriter();
|
|
1534
1939
|
this.#file = file;
|
|
1535
1940
|
const muxed = new WritableStream({
|
|
1536
1941
|
write: async (chunk) => {
|
|
1537
|
-
// The destination's queue bounds the bytes in flight; a refused write errors it, which
|
|
1538
|
-
// the next write, or the commit, reports.
|
|
1539
1942
|
await file.ready;
|
|
1540
1943
|
void file.write(chunk).catch(() => { });
|
|
1541
1944
|
},
|
|
@@ -1570,34 +1973,45 @@ export class MediabunnySink {
|
|
|
1570
1973
|
if (rate !== undefined && (!Number.isSafeInteger(rate) || rate <= 0))
|
|
1571
1974
|
throw new RangeError("audioSampleRate must be a positive integer");
|
|
1572
1975
|
this.#audioRate = rate;
|
|
1976
|
+
this.#audioCodec = options.audioCodec;
|
|
1977
|
+
this.#audioBitrate = options.audioBitrate;
|
|
1573
1978
|
this.#audioResampler = options.audioResampler;
|
|
1574
1979
|
this.#audio = new AudioSampleSource({
|
|
1575
1980
|
codec: options.audioCodec,
|
|
1576
1981
|
quality: new Quality({ bitrate: options.audioBitrate }),
|
|
1982
|
+
...(options.audioCodec === "aac"
|
|
1983
|
+
? { fullCodecString: AAC_CODEC_STRING }
|
|
1984
|
+
: {}),
|
|
1577
1985
|
});
|
|
1578
1986
|
}
|
|
1579
1987
|
if (!this.#hasVideo && this.#audio === undefined)
|
|
1580
1988
|
throw new RangeError("at least one output track is required");
|
|
1581
1989
|
this.#ready = this.#open(options);
|
|
1582
1990
|
}
|
|
1583
|
-
/** Adds the tracks once the video latency mode is known, and starts the file. */
|
|
1584
1991
|
async #open(options) {
|
|
1585
1992
|
const codec = options.videoCodec;
|
|
1586
1993
|
const rate = options.videoRateControl;
|
|
1587
1994
|
if (codec !== undefined && rate !== undefined) {
|
|
1588
|
-
|
|
1995
|
+
let latencyMode = options.videoLatencyMode;
|
|
1996
|
+
if (latencyMode === undefined) {
|
|
1997
|
+
this.#latencyProbe = await videoEncoderLatencyProbe(codec);
|
|
1998
|
+
latencyMode = this.#latencyProbe.mode;
|
|
1999
|
+
}
|
|
1589
2000
|
if (this.#output.state === "canceled")
|
|
1590
2001
|
return;
|
|
1591
2002
|
this.#latencyMode = latencyMode;
|
|
2003
|
+
const acceleration = options.videoHardwareAcceleration ?? "no-preference";
|
|
2004
|
+
this.#acceleration = acceleration;
|
|
2005
|
+
const codecString = options.videoCodecString ??
|
|
2006
|
+
(options.videoBitDepth === 10 ? tenBitCodecString(codec) : undefined);
|
|
1592
2007
|
this.#video = new VideoSampleSource({
|
|
1593
2008
|
codec,
|
|
1594
2009
|
quality: videoEncoderQuality(rate),
|
|
1595
2010
|
latencyMode,
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
// mediabunny
|
|
1600
|
-
// supported and stops at the first that is, so the last one reported is the one that runs.
|
|
2011
|
+
hardwareAcceleration: acceleration,
|
|
2012
|
+
...(options.videoAlpha === true ? { alpha: "keep" } : {}),
|
|
2013
|
+
...(codecString === undefined ? {} : { fullCodecString: codecString }),
|
|
2014
|
+
// mediabunny stops at the first supported candidate, so the last one reported runs.
|
|
1601
2015
|
onEncoderConfig: (config) => {
|
|
1602
2016
|
this.#codecString = config.codec;
|
|
1603
2017
|
const mode = config.bitrateMode;
|
|
@@ -1608,9 +2022,18 @@ export class MediabunnySink {
|
|
|
1608
2022
|
: { bitrate: config.bitrate }),
|
|
1609
2023
|
};
|
|
1610
2024
|
},
|
|
1611
|
-
onEncodedPacket: () => {
|
|
2025
|
+
onEncodedPacket: (packet) => {
|
|
1612
2026
|
this.#framesOut += 1;
|
|
1613
|
-
this.#
|
|
2027
|
+
this.#madeProgress();
|
|
2028
|
+
const key = Math.round(packet.timestamp * 1_000_000);
|
|
2029
|
+
const added = this.#addedAt.get(key);
|
|
2030
|
+
if (added !== undefined) {
|
|
2031
|
+
this.#addedAt.delete(key);
|
|
2032
|
+
const ms = performance.now() - added;
|
|
2033
|
+
this.#encodeLatency.totalMs += ms;
|
|
2034
|
+
this.#encodeLatency.maxMs = Math.max(this.#encodeLatency.maxMs, ms);
|
|
2035
|
+
this.#encodeLatency.count += 1;
|
|
2036
|
+
}
|
|
1614
2037
|
},
|
|
1615
2038
|
});
|
|
1616
2039
|
this.#output.addVideoTrack(this.#video, this.#frameDuration === undefined
|
|
@@ -1621,15 +2044,17 @@ export class MediabunnySink {
|
|
|
1621
2044
|
this.#output.addAudioTrack(this.#audio);
|
|
1622
2045
|
await this.#output.start();
|
|
1623
2046
|
}
|
|
1624
|
-
|
|
2047
|
+
#madeProgress() {
|
|
2048
|
+
(this.#progress ??= new ActiveStopwatch()).reset();
|
|
2049
|
+
}
|
|
1625
2050
|
#watched(work) {
|
|
2051
|
+
const progress = (this.#progress ??= new ActiveStopwatch());
|
|
1626
2052
|
return new Promise((resolve, reject) => {
|
|
1627
|
-
const
|
|
1628
|
-
const waited =
|
|
1629
|
-
if (this.#framesOut >= this.#framesIn ||
|
|
1630
|
-
waited < this.#stallTimeoutMs)
|
|
2053
|
+
const stop = progress.onTick(() => {
|
|
2054
|
+
const waited = progress.elapsed();
|
|
2055
|
+
if (this.#framesOut >= this.#framesIn || waited < this.#stallTimeoutMs)
|
|
1631
2056
|
return;
|
|
1632
|
-
|
|
2057
|
+
stop();
|
|
1633
2058
|
const held = this.#framesIn - this.#framesOut;
|
|
1634
2059
|
reject(Object.assign(new Error(`video encoder stalled: no output for ${Math.round(waited)} ms with ${held} frames queued`), {
|
|
1635
2060
|
code: "ENCODE_STALLED",
|
|
@@ -1640,18 +2065,33 @@ export class MediabunnySink {
|
|
|
1640
2065
|
resource: "unknown",
|
|
1641
2066
|
},
|
|
1642
2067
|
}));
|
|
1643
|
-
}
|
|
1644
|
-
void work.finally(
|
|
2068
|
+
});
|
|
2069
|
+
void work.finally(stop).then(resolve, reject);
|
|
1645
2070
|
});
|
|
1646
2071
|
}
|
|
1647
|
-
/**
|
|
2072
|
+
/** Undefined until the sink has started. */
|
|
1648
2073
|
get videoLatencyMode() {
|
|
1649
2074
|
return this.#latencyMode;
|
|
1650
2075
|
}
|
|
2076
|
+
/** Undefined until the sink has started, and when `videoLatencyMode` was given. */
|
|
2077
|
+
get videoLatencyProbe() {
|
|
2078
|
+
return this.#latencyProbe;
|
|
2079
|
+
}
|
|
2080
|
+
/** Undefined until the sink has started. */
|
|
2081
|
+
get videoEncoderAcceleration() {
|
|
2082
|
+
return this.#acceleration;
|
|
2083
|
+
}
|
|
2084
|
+
/** Hand-over to encoded packet, including queueing in the encoder. */
|
|
2085
|
+
get videoEncodeLatencyMs() {
|
|
2086
|
+
const { totalMs, maxMs, count } = this.#encodeLatency;
|
|
2087
|
+
return { mean: count === 0 ? 0 : totalMs / count, max: maxMs, count };
|
|
2088
|
+
}
|
|
2089
|
+
/** Undefined before the first AAC block. */
|
|
2090
|
+
get aacPrimingProbe() {
|
|
2091
|
+
return this.#aacProbe;
|
|
2092
|
+
}
|
|
1651
2093
|
/**
|
|
1652
|
-
* The video track as
|
|
1653
|
-
* `finish` ends the video track and finalizes the file once every configured track has ended;
|
|
1654
|
-
* its `abort` discards the file. Throws `RangeError` when no video track is configured.
|
|
2094
|
+
* The video track as its own sink, for runners sharing the file. Throws `RangeError` if absent.
|
|
1655
2095
|
*/
|
|
1656
2096
|
get videoTrack() {
|
|
1657
2097
|
if (!this.#hasVideo)
|
|
@@ -1663,10 +2103,7 @@ export class MediabunnySink {
|
|
|
1663
2103
|
};
|
|
1664
2104
|
return this.#videoTrack;
|
|
1665
2105
|
}
|
|
1666
|
-
/**
|
|
1667
|
-
* The audio track as a sink of its own, for a runner that shares the file with another: see
|
|
1668
|
-
* {@link videoTrack}. Throws `RangeError` when no audio track is configured.
|
|
1669
|
-
*/
|
|
2106
|
+
/** The audio track as its own sink; see {@link videoTrack}. Throws `RangeError` if absent. */
|
|
1670
2107
|
get audioTrack() {
|
|
1671
2108
|
if (this.#audio === undefined)
|
|
1672
2109
|
throw new RangeError("audio track is not configured");
|
|
@@ -1677,11 +2114,7 @@ export class MediabunnySink {
|
|
|
1677
2114
|
};
|
|
1678
2115
|
return this.#audioTrack;
|
|
1679
2116
|
}
|
|
1680
|
-
/**
|
|
1681
|
-
* Ends one track: its encoder flushes and the muxer stops waiting for its samples. The last
|
|
1682
|
-
* configured track to end finishes the file; an earlier one resolves at once, so runners that
|
|
1683
|
-
* share the file in turn do not wait for each other.
|
|
1684
|
-
*/
|
|
2117
|
+
/** The last configured track to end finishes the file; earlier ones resolve at once. */
|
|
1685
2118
|
async #endTrack(track) {
|
|
1686
2119
|
await this.#ready;
|
|
1687
2120
|
if (!this.#ended.has(track)) {
|
|
@@ -1694,25 +2127,17 @@ export class MediabunnySink {
|
|
|
1694
2127
|
(this.#audio === undefined || this.#ended.has("audio")))
|
|
1695
2128
|
await this.finish();
|
|
1696
2129
|
}
|
|
1697
|
-
/**
|
|
1698
|
-
* The rate control the browser's encoder was configured with, once the first frame has been
|
|
1699
|
-
* written: whether the quantizer candidate was accepted or the bitrate fallback ran. Undefined
|
|
1700
|
-
* before then.
|
|
1701
|
-
*/
|
|
2130
|
+
/** Undefined until the first frame has been written. */
|
|
1702
2131
|
get appliedVideoRateControl() {
|
|
1703
2132
|
return this.#applied;
|
|
1704
2133
|
}
|
|
1705
|
-
/**
|
|
1706
|
-
* The WebCodecs codec string the video encoder was configured with (for H.264, its profile and
|
|
1707
|
-
* level), once the first frame has been written. Undefined before then.
|
|
1708
|
-
*/
|
|
2134
|
+
/** Undefined until the first frame has been written. */
|
|
1709
2135
|
get videoCodecString() {
|
|
1710
2136
|
return this.#codecString;
|
|
1711
2137
|
}
|
|
1712
2138
|
/**
|
|
1713
|
-
* Encodes one frame at
|
|
1714
|
-
*
|
|
1715
|
-
* destination has passed `maxBytes`, with `ENCODE_STALLED` when the encoder stalls, or when no
|
|
2139
|
+
* Encodes one frame at `output.timeTicks` and always closes `output.frame`. Rejects with
|
|
2140
|
+
* `RESOURCE_LIMIT` past a memory destination's `maxBytes`, with `ENCODE_STALLED`, or when no
|
|
1716
2141
|
* video track is configured.
|
|
1717
2142
|
*/
|
|
1718
2143
|
async writeVideo(output) {
|
|
@@ -1733,14 +2158,14 @@ export class MediabunnySink {
|
|
|
1733
2158
|
? "the output was cancelled before its video track started"
|
|
1734
2159
|
: "video track is not configured");
|
|
1735
2160
|
}
|
|
1736
|
-
// Declaring the duration keeps sample durations uniform instead of inferred from float deltas.
|
|
1737
2161
|
const sample = new VideoSample(output.frame, {
|
|
1738
2162
|
timestamp: Number(output.timeTicks) / 120_000,
|
|
1739
2163
|
duration: this.#frameDuration,
|
|
1740
2164
|
});
|
|
1741
2165
|
if (this.#framesOut >= this.#framesIn)
|
|
1742
|
-
this.#
|
|
2166
|
+
this.#madeProgress();
|
|
1743
2167
|
this.#framesIn += 1;
|
|
2168
|
+
this.#addedAt.set(Math.round((Number(output.timeTicks) / 120_000) * 1_000_000), performance.now());
|
|
1744
2169
|
try {
|
|
1745
2170
|
await this.#watched(this.#video.add(sample));
|
|
1746
2171
|
}
|
|
@@ -1750,13 +2175,9 @@ export class MediabunnySink {
|
|
|
1750
2175
|
}
|
|
1751
2176
|
}
|
|
1752
2177
|
/**
|
|
1753
|
-
* Encodes one
|
|
1754
|
-
*
|
|
1755
|
-
*
|
|
1756
|
-
* rate and channel count. Rejects with `RESOURCE_LIMIT` once a memory destination has passed
|
|
1757
|
-
* `maxBytes`, when no audio track is configured, when the block's channels differ in length, or
|
|
1758
|
-
* (`RangeError`) when a block to convert does not continue the last or no `audioResampler` was
|
|
1759
|
-
* given.
|
|
2178
|
+
* Encodes one block at `block.startSample`, from the output's zero. Blocks that need rate
|
|
2179
|
+
* conversion must be contiguous. Rejects with `RESOURCE_LIMIT`, when no audio track is
|
|
2180
|
+
* configured, for ragged channels, or with `RangeError` for a gap or a missing `audioResampler`.
|
|
1760
2181
|
*/
|
|
1761
2182
|
async writeAudio(block) {
|
|
1762
2183
|
await this.#ready;
|
|
@@ -1783,7 +2204,6 @@ export class MediabunnySink {
|
|
|
1783
2204
|
if (converted !== null)
|
|
1784
2205
|
await this.#encodeAudio(converted.channels, converted.startSample, this.#audioConverter.targetRate);
|
|
1785
2206
|
}
|
|
1786
|
-
/** Encodes the converted audio still held, once, before the audio track ends. */
|
|
1787
2207
|
async #flushAudio() {
|
|
1788
2208
|
const converter = this.#audioConverter;
|
|
1789
2209
|
if (converter === undefined || this.#audioFlushed)
|
|
@@ -1798,8 +2218,30 @@ export class MediabunnySink {
|
|
|
1798
2218
|
converter.free();
|
|
1799
2219
|
}
|
|
1800
2220
|
}
|
|
1801
|
-
/** Encodes planar `channels` starting at sample `startSample` of a `sampleRate` stream. */
|
|
1802
2221
|
async #encodeAudio(channels, startSample, sampleRate) {
|
|
2222
|
+
if (this.#audio === undefined)
|
|
2223
|
+
throw new Error("audio track is not configured");
|
|
2224
|
+
// The muxer trims AAC priming placed before zero (edit list, negative Matroska block times);
|
|
2225
|
+
// Opus states its own in its header.
|
|
2226
|
+
let delay = 0;
|
|
2227
|
+
if (this.#audioCodec === "aac" && this.#audioBitrate !== undefined) {
|
|
2228
|
+
delay = await (this.#audioDelay ??= aacEncoderPrimingProbe({
|
|
2229
|
+
sampleRate,
|
|
2230
|
+
numberOfChannels: channels.length,
|
|
2231
|
+
bitrate: this.#audioBitrate,
|
|
2232
|
+
}).then((probe) => {
|
|
2233
|
+
this.#aacProbe = probe;
|
|
2234
|
+
return probe.delay;
|
|
2235
|
+
}));
|
|
2236
|
+
// Safari's encoder drops its first input frame, so lead with a frame of silence.
|
|
2237
|
+
if (!this.#audioLeadWritten) {
|
|
2238
|
+
this.#audioLeadWritten = true;
|
|
2239
|
+
await this.#addAudio(channels.map(() => new Float32Array(AAC_FRAME_FRAMES)), startSample - AAC_FRAME_FRAMES - delay, sampleRate);
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
await this.#addAudio(channels, startSample - delay, sampleRate);
|
|
2243
|
+
}
|
|
2244
|
+
async #addAudio(channels, startSample, sampleRate) {
|
|
1803
2245
|
if (this.#audio === undefined)
|
|
1804
2246
|
throw new Error("audio track is not configured");
|
|
1805
2247
|
const frames = channels[0]?.length ?? 0;
|
|
@@ -1820,10 +2262,8 @@ export class MediabunnySink {
|
|
|
1820
2262
|
}
|
|
1821
2263
|
}
|
|
1822
2264
|
/**
|
|
1823
|
-
* Finalizes the file and commits a stream destination;
|
|
1824
|
-
*
|
|
1825
|
-
* `ENCODE_STALLED` when the encoder stalls, and with what the muxer or the destination refused; a
|
|
1826
|
-
* stream destination is then discarded.
|
|
2265
|
+
* Finalizes the file and commits a stream destination; idempotent once resolved. Rejects with
|
|
2266
|
+
* `RESOURCE_LIMIT`, `ENCODE_STALLED`, or the muxer's or destination's error, discarding a stream.
|
|
1827
2267
|
*/
|
|
1828
2268
|
async finish() {
|
|
1829
2269
|
if (this.#finished)
|
|
@@ -1840,15 +2280,16 @@ export class MediabunnySink {
|
|
|
1840
2280
|
await this.#discard(error).catch(() => { });
|
|
1841
2281
|
throw error;
|
|
1842
2282
|
}
|
|
2283
|
+
finally {
|
|
2284
|
+
this.#progress?.dispose();
|
|
2285
|
+
}
|
|
1843
2286
|
this.#finished = true;
|
|
1844
2287
|
}
|
|
1845
|
-
/**
|
|
1846
|
-
* Cancels the output and discards a stream destination, unless the file already finished.
|
|
1847
|
-
* Rejects when the destination refuses to be discarded.
|
|
1848
|
-
*/
|
|
2288
|
+
/** Discards the output unless already finished; rejects if the destination refuses. */
|
|
1849
2289
|
async abort(reason) {
|
|
1850
2290
|
if (this.#finished)
|
|
1851
2291
|
return;
|
|
2292
|
+
this.#progress?.dispose();
|
|
1852
2293
|
if (this.#audioConverter !== undefined && !this.#audioFlushed) {
|
|
1853
2294
|
this.#audioFlushed = true;
|
|
1854
2295
|
this.#audioConverter.free();
|
|
@@ -1861,17 +2302,13 @@ export class MediabunnySink {
|
|
|
1861
2302
|
await this.#discard(reason);
|
|
1862
2303
|
}
|
|
1863
2304
|
}
|
|
1864
|
-
/** Discards a stream destination once: writes still queued are dropped and nothing commits. */
|
|
1865
2305
|
async #discard(reason) {
|
|
1866
2306
|
if (this.#file === undefined || this.#discarded)
|
|
1867
2307
|
return;
|
|
1868
2308
|
this.#discarded = true;
|
|
1869
2309
|
await this.#file.abort(reason);
|
|
1870
2310
|
}
|
|
1871
|
-
/**
|
|
1872
|
-
* The finished output: its length for a stream, the bytes in memory. Null until {@link finish}
|
|
1873
|
-
* resolves.
|
|
1874
|
-
*/
|
|
2311
|
+
/** Null until {@link finish} resolves. */
|
|
1875
2312
|
get output() {
|
|
1876
2313
|
if (!this.#finished)
|
|
1877
2314
|
return null;
|
|
@@ -1881,24 +2318,18 @@ export class MediabunnySink {
|
|
|
1881
2318
|
}
|
|
1882
2319
|
return { kind: "stream", bytes: this.#written };
|
|
1883
2320
|
}
|
|
1884
|
-
/** Bytes muxed so far: the file's length as written. */
|
|
1885
2321
|
get bytesWritten() {
|
|
1886
2322
|
return this.#written;
|
|
1887
2323
|
}
|
|
1888
2324
|
}
|
|
1889
|
-
/**
|
|
1890
|
-
* Factory kept in the optional subpath so mediabunny is never loaded by core APIs. Audio needs
|
|
1891
|
-
* `alpha2/wasm`'s resampler: see {@link MediabunnyAudioDecoder}.
|
|
1892
|
-
*/
|
|
2325
|
+
/** Kept in an optional subpath so core APIs never load mediabunny. */
|
|
1893
2326
|
export class MediabunnyAdapterFactory {
|
|
1894
2327
|
#audioResampler;
|
|
1895
2328
|
constructor(audioResampler) {
|
|
1896
2329
|
this.#audioResampler = audioResampler;
|
|
1897
2330
|
}
|
|
1898
2331
|
/**
|
|
1899
|
-
*
|
|
1900
|
-
* `input` is a Blob, ArrayBuffer, or ArrayBuffer view, and as {@link MediabunnyVideoDecoder.open}
|
|
1901
|
-
* does.
|
|
2332
|
+
* Rejects with `TypeError` for an unsupported input, and as {@link MediabunnyVideoDecoder.open}.
|
|
1902
2333
|
*/
|
|
1903
2334
|
async openVideo(sourceId, input) {
|
|
1904
2335
|
if (!(input instanceof Blob) &&
|
|
@@ -1909,9 +2340,8 @@ export class MediabunnyAdapterFactory {
|
|
|
1909
2340
|
return MediabunnyVideoDecoder.open(sourceId, input);
|
|
1910
2341
|
}
|
|
1911
2342
|
/**
|
|
1912
|
-
*
|
|
1913
|
-
*
|
|
1914
|
-
* binding, and as {@link MediabunnyAudioDecoder.open} does.
|
|
2343
|
+
* Rejects with `TypeError` for an unsupported input or a missing resampler binding, and as
|
|
2344
|
+
* {@link MediabunnyAudioDecoder.open}.
|
|
1915
2345
|
*/
|
|
1916
2346
|
async openAudio(sourceId, input) {
|
|
1917
2347
|
if (!(input instanceof Blob) &&
|
|
@@ -1930,8 +2360,3 @@ function ticksToSampleCeil(ticks, sampleRate) {
|
|
|
1930
2360
|
const rate = BigInt(sampleRate);
|
|
1931
2361
|
return Number((ticks * rate + 119999n) / 120000n);
|
|
1932
2362
|
}
|
|
1933
|
-
function throwIfAborted(signal) {
|
|
1934
|
-
if (signal?.aborted === true) {
|
|
1935
|
-
throw signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
1936
|
-
}
|
|
1937
|
-
}
|