alpha2 0.4.6 → 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 +108 -177
- 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 +96 -162
- package/dist/frame-supply.js +181 -171
- package/dist/generated/project-schema.d.ts +701 -485
- package/dist/generated/project-schema.js +55 -2
- package/dist/generated/project-shape.js +261 -16
- 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 +82 -67
- package/dist/hdr-frames.js +112 -49
- 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 +48 -63
- package/dist/layout.js +37 -37
- 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 +166 -245
- package/dist/mediabunny.js +741 -580
- 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 +73 -117
- package/dist/project.js +384 -445
- 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 +97 -71
- package/dist/text.js +33 -70
- 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 -95
- package/dist/worker.js +235 -143
- 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 +460 -567
- package/wasm/alpha2_wasm.js +594 -594
- package/wasm/alpha2_wasm_bg.wasm +0 -0
- package/wasm/alpha2_wasm_bg.wasm.d.ts +15 -8
- package/wasm/rust-crate-licenses.md +2 -2
- package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline1.js +1 -0
- package/wasm/snippets/alpha2-wasm-1313375d424845c0/inline2.js +82 -0
- package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
- /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline0.js +0 -0
- /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → 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
|
+
}
|
|
1289
|
+
/**
|
|
1290
|
+
* The 10-bit codec string for `codec`; `undefined` for H.264, which browsers do not encode at 10
|
|
1291
|
+
* bits.
|
|
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;
|
|
1194
1308
|
/**
|
|
1195
|
-
*
|
|
1196
|
-
*
|
|
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.
|
|
1197
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,13 +1536,9 @@ 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. AAC is encoded at the MPEG-4 rates only, the ones a native host's FFmpeg
|
|
1325
|
-
* `aac` encoder takes, and an AAC encoder that accepts a rate but puts out another (Safari's above
|
|
1326
|
-
* 48 kHz) does not take it. Pass it to {@link MediabunnySink} as `audioSampleRate`, so every
|
|
1327
|
-
* project 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`.
|
|
1328
1542
|
*/
|
|
1329
1543
|
export async function audioEncoderSampleRate(codec, options) {
|
|
1330
1544
|
const rate = options.sampleRate;
|
|
@@ -1354,25 +1568,15 @@ export async function audioEncoderSampleRate(codec, options) {
|
|
|
1354
1568
|
}
|
|
1355
1569
|
return null;
|
|
1356
1570
|
}
|
|
1357
|
-
/**
|
|
1358
|
-
* The AAC profile {@link MediabunnySink} encodes at every rate: AAC-LC, as a native host's FFmpeg
|
|
1359
|
-
* `aac` encoder does, where mediabunny would pick HE-AAC at 24 kHz and below.
|
|
1360
|
-
*/
|
|
1571
|
+
/** AAC-LC, as native hosts encode; mediabunny would pick HE-AAC at 24 kHz and below. */
|
|
1361
1572
|
const AAC_CODEC_STRING = "mp4a.40.2";
|
|
1362
|
-
/** The frames in one AAC-LC frame. */
|
|
1363
1573
|
const AAC_FRAME_FRAMES = 1_024;
|
|
1364
|
-
/**
|
|
1365
|
-
* The rates AAC's two-byte `AudioSpecificConfig` names by index (ISO/IEC 14496-3,
|
|
1366
|
-
* `samplingFrequencyIndex`).
|
|
1367
|
-
*/
|
|
1574
|
+
/** ISO/IEC 14496-3 `samplingFrequencyIndex` values. */
|
|
1368
1575
|
const AAC_SAMPLING_FREQUENCIES = [
|
|
1369
1576
|
96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000,
|
|
1370
1577
|
12_000, 11_025, 8_000, 7_350,
|
|
1371
1578
|
];
|
|
1372
|
-
/**
|
|
1373
|
-
* AAC-LC's two-byte `AudioSpecificConfig`; undefined for a rate without an index or a channel
|
|
1374
|
-
* count without a channel configuration (7, or more than 8).
|
|
1375
|
-
*/
|
|
1579
|
+
/** Undefined for a rate without an index or a channel count without a configuration. */
|
|
1376
1580
|
function aacLcAudioSpecificConfig(sampleRate, numberOfChannels) {
|
|
1377
1581
|
const frequency = AAC_SAMPLING_FREQUENCIES.indexOf(sampleRate);
|
|
1378
1582
|
const channels = numberOfChannels === 8 ? 7 : numberOfChannels <= 6 ? numberOfChannels : 0;
|
|
@@ -1383,30 +1587,22 @@ function aacLcAudioSpecificConfig(sampleRate, numberOfChannels) {
|
|
|
1383
1587
|
((frequency & 1) << 7) | (channels << 3),
|
|
1384
1588
|
]);
|
|
1385
1589
|
}
|
|
1386
|
-
/** The low-passed noise burst an AAC delay probe encodes, in frames. */
|
|
1387
1590
|
const AAC_DELAY_PROBE_FRAMES = 2_048;
|
|
1388
|
-
/** The longest delay a probe looks for, in frames; the silence after the burst is this long. */
|
|
1389
1591
|
const AAC_DELAY_MAX_FRAMES = 8_192;
|
|
1390
|
-
/** How long a delay probe has to encode and decode the burst. */
|
|
1391
1592
|
const AAC_DELAY_PROBE_TIMEOUT_MS = 1_500;
|
|
1392
|
-
/** How closely the decoded audio must match the burst at the lag found for it to count. */
|
|
1393
1593
|
const AAC_DELAY_MIN_CORRELATION = 0.5;
|
|
1394
1594
|
const aacProbes = new Map();
|
|
1395
1595
|
/**
|
|
1396
|
-
* The frames
|
|
1397
|
-
*
|
|
1398
|
-
* time although the decoded audio starts with the encoder's delay (2112 frames on Chrome's and
|
|
1399
|
-
* Safari's macOS encoders), and does not say how long that is. Measured once per configuration by
|
|
1400
|
-
* encoding a noise burst and finding it in what the browser's decoder makes of it; 0 where either
|
|
1401
|
-
* fails.
|
|
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.
|
|
1402
1598
|
*/
|
|
1403
1599
|
export async function aacEncoderDelay(options) {
|
|
1404
1600
|
return (await probeAacEncoder(options)).delay;
|
|
1405
1601
|
}
|
|
1406
|
-
/**
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1602
|
+
/** {@link aacEncoderDelay} with its outcome. Timeouts are retried once and never cached. */
|
|
1603
|
+
export function aacEncoderPrimingProbe(options) {
|
|
1604
|
+
return probeAacEncoder(options);
|
|
1605
|
+
}
|
|
1410
1606
|
function probeAacEncoder(options) {
|
|
1411
1607
|
const config = {
|
|
1412
1608
|
codec: AAC_CODEC_STRING,
|
|
@@ -1415,17 +1611,30 @@ function probeAacEncoder(options) {
|
|
|
1415
1611
|
bitrate: options.bitrate,
|
|
1416
1612
|
};
|
|
1417
1613
|
const key = JSON.stringify(config);
|
|
1418
|
-
|
|
1419
|
-
if (
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
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
|
+
});
|
|
1423
1632
|
return probe;
|
|
1424
1633
|
}
|
|
1425
1634
|
async function measureAacEncoder(config) {
|
|
1426
1635
|
if (typeof AudioEncoder === "undefined" ||
|
|
1427
1636
|
typeof AudioDecoder === "undefined")
|
|
1428
|
-
return { delay: 0 };
|
|
1637
|
+
return { delay: 0, outcome: "unavailable" };
|
|
1429
1638
|
let encoder;
|
|
1430
1639
|
let decoder;
|
|
1431
1640
|
let timer;
|
|
@@ -1434,7 +1643,7 @@ async function measureAacEncoder(config) {
|
|
|
1434
1643
|
});
|
|
1435
1644
|
try {
|
|
1436
1645
|
if (!(await AudioEncoder.isConfigSupported(config)).supported)
|
|
1437
|
-
return { delay: 0 };
|
|
1646
|
+
return { delay: 0, outcome: "failed" };
|
|
1438
1647
|
let failed = false;
|
|
1439
1648
|
const chunks = [];
|
|
1440
1649
|
let decoderConfig;
|
|
@@ -1446,8 +1655,7 @@ async function measureAacEncoder(config) {
|
|
|
1446
1655
|
error: () => (failed = true),
|
|
1447
1656
|
});
|
|
1448
1657
|
encoder.configure(config);
|
|
1449
|
-
//
|
|
1450
|
-
// frame of any input (see `#encodeAudio`).
|
|
1658
|
+
// Safari's encoder drops the first input frame, so the burst follows a frame of silence.
|
|
1451
1659
|
const probe = aacDelayProbe();
|
|
1452
1660
|
const frames = AAC_FRAME_FRAMES + AAC_DELAY_PROBE_FRAMES + AAC_DELAY_MAX_FRAMES;
|
|
1453
1661
|
const planar = new Float32Array(frames * config.numberOfChannels);
|
|
@@ -1468,12 +1676,12 @@ async function measureAacEncoder(config) {
|
|
|
1468
1676
|
input.close();
|
|
1469
1677
|
}
|
|
1470
1678
|
if ((await Promise.race([encoder.flush(), timedOut])) === "timeout")
|
|
1471
|
-
return { delay: 0 };
|
|
1679
|
+
return { delay: 0, outcome: "timed-out" };
|
|
1472
1680
|
if (failed || decoderConfig === undefined)
|
|
1473
|
-
return { delay: 0 };
|
|
1681
|
+
return { delay: 0, outcome: "failed" };
|
|
1474
1682
|
const rate = decoderConfig.sampleRate;
|
|
1475
1683
|
if (rate !== config.sampleRate)
|
|
1476
|
-
return { rate, delay: 0 };
|
|
1684
|
+
return { rate, delay: 0, outcome: "output" };
|
|
1477
1685
|
const planes = [];
|
|
1478
1686
|
decoder = new AudioDecoder({
|
|
1479
1687
|
output: (audio) => {
|
|
@@ -1490,8 +1698,7 @@ async function measureAacEncoder(config) {
|
|
|
1490
1698
|
},
|
|
1491
1699
|
error: () => (failed = true),
|
|
1492
1700
|
});
|
|
1493
|
-
// Safari's
|
|
1494
|
-
// refuses (mediabunny rewrites it the same way in the file).
|
|
1701
|
+
// Safari's own decoder refuses its encoder's full `ES_Descriptor`.
|
|
1495
1702
|
const description = aacLcAudioSpecificConfig(config.sampleRate, config.numberOfChannels);
|
|
1496
1703
|
decoder.configure(description === undefined
|
|
1497
1704
|
? decoderConfig
|
|
@@ -1499,9 +1706,9 @@ async function measureAacEncoder(config) {
|
|
|
1499
1706
|
for (const chunk of chunks)
|
|
1500
1707
|
decoder.decode(chunk);
|
|
1501
1708
|
if ((await Promise.race([decoder.flush(), timedOut])) === "timeout")
|
|
1502
|
-
return { rate, delay: 0 };
|
|
1709
|
+
return { rate, delay: 0, outcome: "timed-out" };
|
|
1503
1710
|
if (failed)
|
|
1504
|
-
return { rate, delay: 0 };
|
|
1711
|
+
return { rate, delay: 0, outcome: "failed" };
|
|
1505
1712
|
const decoded = new Float32Array(planes.reduce((sum, plane) => sum + plane.length, 0));
|
|
1506
1713
|
let offset = 0;
|
|
1507
1714
|
for (const plane of planes) {
|
|
@@ -1512,10 +1719,11 @@ async function measureAacEncoder(config) {
|
|
|
1512
1719
|
return {
|
|
1513
1720
|
rate,
|
|
1514
1721
|
delay: lag === null ? 0 : Math.max(0, lag - AAC_FRAME_FRAMES),
|
|
1722
|
+
outcome: "output",
|
|
1515
1723
|
};
|
|
1516
1724
|
}
|
|
1517
1725
|
catch {
|
|
1518
|
-
return { delay: 0 };
|
|
1726
|
+
return { delay: 0, outcome: "failed" };
|
|
1519
1727
|
}
|
|
1520
1728
|
finally {
|
|
1521
1729
|
clearTimeout(timer);
|
|
@@ -1530,7 +1738,6 @@ async function measureAacEncoder(config) {
|
|
|
1530
1738
|
}
|
|
1531
1739
|
}
|
|
1532
1740
|
}
|
|
1533
|
-
/** The probe's burst: noise, low-passed so a lossy codec keeps most of it. */
|
|
1534
1741
|
function aacDelayProbe() {
|
|
1535
1742
|
const probe = new Float32Array(AAC_DELAY_PROBE_FRAMES);
|
|
1536
1743
|
let seed = 1;
|
|
@@ -1542,16 +1749,11 @@ function aacDelayProbe() {
|
|
|
1542
1749
|
}
|
|
1543
1750
|
return probe;
|
|
1544
1751
|
}
|
|
1545
|
-
/**
|
|
1546
|
-
* The lag of `decoded` at which it matches `probe` best (normalized cross-correlation), up to the
|
|
1547
|
-
* probe's leading frame of silence and {@link AAC_DELAY_MAX_FRAMES}; null when no lag matches it
|
|
1548
|
-
* closely enough.
|
|
1549
|
-
*/
|
|
1752
|
+
/** The lag where `decoded` best matches `probe`, or null when none matches closely enough. */
|
|
1550
1753
|
function strongestLag(decoded, probe) {
|
|
1551
1754
|
let probeEnergy = 0;
|
|
1552
1755
|
for (const value of probe)
|
|
1553
1756
|
probeEnergy += value * value;
|
|
1554
|
-
// Sum of squares of `decoded` before each index, for each window's energy.
|
|
1555
1757
|
const energy = new Float64Array(decoded.length + 1);
|
|
1556
1758
|
for (let index = 0; index < decoded.length; index += 1)
|
|
1557
1759
|
energy[index + 1] = energy[index] + decoded[index] * decoded[index];
|
|
@@ -1573,22 +1775,14 @@ function strongestLag(decoded, probe) {
|
|
|
1573
1775
|
}
|
|
1574
1776
|
return best;
|
|
1575
1777
|
}
|
|
1576
|
-
/**
|
|
1577
|
-
* Project-rate blocks converted to an encoder's rate with the engine's converter, as a native
|
|
1578
|
-
* host's AAC input converts them: outputs from the first block's start on, each made once the
|
|
1579
|
-
* samples it reads have arrived, the source silent outside them, and ending where the project's
|
|
1580
|
-
* audio does (the first output at or after its end).
|
|
1581
|
-
*/
|
|
1778
|
+
/** Converts project-rate blocks to the encoder's rate with the engine's converter. */
|
|
1582
1779
|
class EncoderRateConverter {
|
|
1583
1780
|
targetRate;
|
|
1584
1781
|
#projectRate;
|
|
1585
1782
|
#resampler;
|
|
1586
|
-
/** The project samples from `#bufferStart` on that outputs still to be made may read. */
|
|
1587
1783
|
#buffer;
|
|
1588
1784
|
#bufferStart;
|
|
1589
|
-
/** The project sample the next block starts at. */
|
|
1590
1785
|
#received;
|
|
1591
|
-
/** The next output sample. */
|
|
1592
1786
|
#produced;
|
|
1593
1787
|
constructor(binding, first, targetRate) {
|
|
1594
1788
|
this.targetRate = targetRate;
|
|
@@ -1600,10 +1794,7 @@ class EncoderRateConverter {
|
|
|
1600
1794
|
this.#received = start;
|
|
1601
1795
|
this.#produced = this.#resampler.targetAtOrAfter(start);
|
|
1602
1796
|
}
|
|
1603
|
-
/**
|
|
1604
|
-
* Takes the next block, which must continue the last one at the same rate and channel count,
|
|
1605
|
-
* and returns the outputs it completes (`startSample` at the target rate), or null for none.
|
|
1606
|
-
*/
|
|
1797
|
+
/** Blocks must be contiguous at one rate and channel count. */
|
|
1607
1798
|
push(block) {
|
|
1608
1799
|
if (block.sampleRate !== this.#projectRate ||
|
|
1609
1800
|
block.channels.length !== this.#buffer.length)
|
|
@@ -1620,17 +1811,13 @@ class EncoderRateConverter {
|
|
|
1620
1811
|
this.#received += frames;
|
|
1621
1812
|
return this.#convert(this.#readyEnd());
|
|
1622
1813
|
}
|
|
1623
|
-
/** Ends the input: the outputs still to make, up to where the project's audio ends. */
|
|
1624
1814
|
finish() {
|
|
1625
1815
|
return this.#convert(this.#resampler.targetAtOrAfter(this.#received));
|
|
1626
1816
|
}
|
|
1627
|
-
/** Frees the engine's converter. */
|
|
1628
1817
|
free() {
|
|
1629
1818
|
this.#resampler.free?.();
|
|
1630
1819
|
}
|
|
1631
|
-
/** The end of the outputs whose samples have all arrived. */
|
|
1632
1820
|
#readyEnd() {
|
|
1633
|
-
// The output before `end` reads up to `sourceEnd(end)`, which grows with `end`.
|
|
1634
1821
|
let low = this.#produced;
|
|
1635
1822
|
let high = Math.max(low, this.#resampler.targetAtOrAfter(this.#received));
|
|
1636
1823
|
while (low < high) {
|
|
@@ -1656,11 +1843,7 @@ class EncoderRateConverter {
|
|
|
1656
1843
|
return { startSample: start, channels };
|
|
1657
1844
|
}
|
|
1658
1845
|
}
|
|
1659
|
-
|
|
1660
|
-
* The muxer for `container`. MP4 and MOV go without fast start and MKV and WebM are not
|
|
1661
|
-
* append-only, so the payload is never held in memory or rewritten: the muxer seeks back only to
|
|
1662
|
-
* patch headers.
|
|
1663
|
-
*/
|
|
1846
|
+
// No fast start and no append-only mode, so the muxer seeks back only to patch headers.
|
|
1664
1847
|
function outputFormat(container) {
|
|
1665
1848
|
switch (container) {
|
|
1666
1849
|
case "mp4":
|
|
@@ -1674,26 +1857,13 @@ function outputFormat(container) {
|
|
|
1674
1857
|
}
|
|
1675
1858
|
}
|
|
1676
1859
|
/**
|
|
1677
|
-
* Optional mediabunny encoder/muxer implementing both public alpha2 sinks.
|
|
1678
|
-
*
|
|
1679
|
-
*
|
|
1680
|
-
*
|
|
1681
|
-
* the video and `renderOfflineAudio` for the audio, at once or one after the other), give each its
|
|
1682
|
-
* track instead, {@link MediabunnySink.videoTrack} and {@link MediabunnySink.audioTrack}: a
|
|
1683
|
-
* runner's `finish` then ends its own track, and the file is finalized when every configured track
|
|
1684
|
-
* has ended. Either track's `abort` discards the whole file, and the other runner's next write
|
|
1685
|
-
* fails.
|
|
1686
|
-
*
|
|
1687
|
-
* The constructor throws `RangeError` when no track is configured, the container does not offer a
|
|
1688
|
-
* codec (an `ExportFormatError`), a codec lacks its rate, a memory destination's `maxBytes` is not
|
|
1689
|
-
* 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.
|
|
1690
1864
|
*/
|
|
1691
1865
|
export class MediabunnySink {
|
|
1692
1866
|
#target;
|
|
1693
|
-
/**
|
|
1694
|
-
* A stream destination, written through the muxer and committed or discarded by this sink alone:
|
|
1695
|
-
* see the constructor.
|
|
1696
|
-
*/
|
|
1697
1867
|
#file;
|
|
1698
1868
|
#discarded = false;
|
|
1699
1869
|
#output;
|
|
@@ -1702,17 +1872,20 @@ export class MediabunnySink {
|
|
|
1702
1872
|
#hasVideo;
|
|
1703
1873
|
#video;
|
|
1704
1874
|
#latencyMode;
|
|
1875
|
+
#latencyProbe;
|
|
1876
|
+
#acceleration;
|
|
1877
|
+
#addedAt = new Map();
|
|
1878
|
+
#encodeLatency = { totalMs: 0, maxMs: 0, count: 0 };
|
|
1879
|
+
#aacProbe;
|
|
1705
1880
|
#stallTimeoutMs;
|
|
1706
1881
|
#framesIn = 0;
|
|
1707
1882
|
#framesOut = 0;
|
|
1708
|
-
/**
|
|
1709
|
-
#
|
|
1883
|
+
/** Active time, so a frozen page does not count as a stall. */
|
|
1884
|
+
#progress;
|
|
1710
1885
|
#audio;
|
|
1711
1886
|
#audioCodec;
|
|
1712
1887
|
#audioBitrate;
|
|
1713
|
-
/** The AAC encoder's priming, in frames at the encoder's rate: see {@link aacEncoderDelay}. */
|
|
1714
1888
|
#audioDelay;
|
|
1715
|
-
/** Whether the AAC encoder was given its leading frame of silence: see `#encodeAudio`. */
|
|
1716
1889
|
#audioLeadWritten = false;
|
|
1717
1890
|
#audioRate;
|
|
1718
1891
|
#audioResampler;
|
|
@@ -1723,13 +1896,11 @@ export class MediabunnySink {
|
|
|
1723
1896
|
#finished = false;
|
|
1724
1897
|
#applied;
|
|
1725
1898
|
#codecString;
|
|
1726
|
-
/** Tracks whose runner finished, through {@link videoTrack} or {@link audioTrack}. */
|
|
1727
1899
|
#ended = new Set();
|
|
1728
1900
|
#videoTrack;
|
|
1729
1901
|
#audioTrack;
|
|
1730
1902
|
constructor(options) {
|
|
1731
|
-
//
|
|
1732
|
-
// mistake, not a failed export.
|
|
1903
|
+
// Validated before anything is opened, since an unsupported pair is a caller error.
|
|
1733
1904
|
resolveExportFormat({
|
|
1734
1905
|
container: options.container,
|
|
1735
1906
|
...(options.videoCodec === undefined
|
|
@@ -1745,8 +1916,7 @@ export class MediabunnySink {
|
|
|
1745
1916
|
destination.maxBytes <= 0)
|
|
1746
1917
|
throw new RangeError("memory destination maxBytes must be a positive safe integer");
|
|
1747
1918
|
this.#target = new BufferTarget();
|
|
1748
|
-
//
|
|
1749
|
-
// within what was budgeted for it.
|
|
1919
|
+
// Stopping at the reserved size keeps the output within its budget.
|
|
1750
1920
|
this.#target.onwrite = (_start, end) => {
|
|
1751
1921
|
this.#written = Math.max(this.#written, end);
|
|
1752
1922
|
if (end > destination.maxBytes)
|
|
@@ -1763,15 +1933,12 @@ export class MediabunnySink {
|
|
|
1763
1933
|
};
|
|
1764
1934
|
}
|
|
1765
1935
|
else {
|
|
1766
|
-
// mediabunny closes its stream on finish, failure and cancel alike, and
|
|
1767
|
-
//
|
|
1768
|
-
// 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.
|
|
1769
1938
|
const file = destination.writable.getWriter();
|
|
1770
1939
|
this.#file = file;
|
|
1771
1940
|
const muxed = new WritableStream({
|
|
1772
1941
|
write: async (chunk) => {
|
|
1773
|
-
// The destination's queue bounds the bytes in flight; a refused write errors it, which
|
|
1774
|
-
// the next write, or the commit, reports.
|
|
1775
1942
|
await file.ready;
|
|
1776
1943
|
void file.write(chunk).catch(() => { });
|
|
1777
1944
|
},
|
|
@@ -1821,24 +1988,30 @@ export class MediabunnySink {
|
|
|
1821
1988
|
throw new RangeError("at least one output track is required");
|
|
1822
1989
|
this.#ready = this.#open(options);
|
|
1823
1990
|
}
|
|
1824
|
-
/** Adds the tracks once the video latency mode is known, and starts the file. */
|
|
1825
1991
|
async #open(options) {
|
|
1826
1992
|
const codec = options.videoCodec;
|
|
1827
1993
|
const rate = options.videoRateControl;
|
|
1828
1994
|
if (codec !== undefined && rate !== undefined) {
|
|
1829
|
-
|
|
1995
|
+
let latencyMode = options.videoLatencyMode;
|
|
1996
|
+
if (latencyMode === undefined) {
|
|
1997
|
+
this.#latencyProbe = await videoEncoderLatencyProbe(codec);
|
|
1998
|
+
latencyMode = this.#latencyProbe.mode;
|
|
1999
|
+
}
|
|
1830
2000
|
if (this.#output.state === "canceled")
|
|
1831
2001
|
return;
|
|
1832
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);
|
|
1833
2007
|
this.#video = new VideoSampleSource({
|
|
1834
2008
|
codec,
|
|
1835
2009
|
quality: videoEncoderQuality(rate),
|
|
1836
2010
|
latencyMode,
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
// mediabunny
|
|
1841
|
-
// 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.
|
|
1842
2015
|
onEncoderConfig: (config) => {
|
|
1843
2016
|
this.#codecString = config.codec;
|
|
1844
2017
|
const mode = config.bitrateMode;
|
|
@@ -1849,9 +2022,18 @@ export class MediabunnySink {
|
|
|
1849
2022
|
: { bitrate: config.bitrate }),
|
|
1850
2023
|
};
|
|
1851
2024
|
},
|
|
1852
|
-
onEncodedPacket: () => {
|
|
2025
|
+
onEncodedPacket: (packet) => {
|
|
1853
2026
|
this.#framesOut += 1;
|
|
1854
|
-
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
|
+
}
|
|
1855
2037
|
},
|
|
1856
2038
|
});
|
|
1857
2039
|
this.#output.addVideoTrack(this.#video, this.#frameDuration === undefined
|
|
@@ -1862,15 +2044,17 @@ export class MediabunnySink {
|
|
|
1862
2044
|
this.#output.addAudioTrack(this.#audio);
|
|
1863
2045
|
await this.#output.start();
|
|
1864
2046
|
}
|
|
1865
|
-
|
|
2047
|
+
#madeProgress() {
|
|
2048
|
+
(this.#progress ??= new ActiveStopwatch()).reset();
|
|
2049
|
+
}
|
|
1866
2050
|
#watched(work) {
|
|
2051
|
+
const progress = (this.#progress ??= new ActiveStopwatch());
|
|
1867
2052
|
return new Promise((resolve, reject) => {
|
|
1868
|
-
const
|
|
1869
|
-
const waited =
|
|
1870
|
-
if (this.#framesOut >= this.#framesIn ||
|
|
1871
|
-
waited < this.#stallTimeoutMs)
|
|
2053
|
+
const stop = progress.onTick(() => {
|
|
2054
|
+
const waited = progress.elapsed();
|
|
2055
|
+
if (this.#framesOut >= this.#framesIn || waited < this.#stallTimeoutMs)
|
|
1872
2056
|
return;
|
|
1873
|
-
|
|
2057
|
+
stop();
|
|
1874
2058
|
const held = this.#framesIn - this.#framesOut;
|
|
1875
2059
|
reject(Object.assign(new Error(`video encoder stalled: no output for ${Math.round(waited)} ms with ${held} frames queued`), {
|
|
1876
2060
|
code: "ENCODE_STALLED",
|
|
@@ -1881,18 +2065,33 @@ export class MediabunnySink {
|
|
|
1881
2065
|
resource: "unknown",
|
|
1882
2066
|
},
|
|
1883
2067
|
}));
|
|
1884
|
-
}
|
|
1885
|
-
void work.finally(
|
|
2068
|
+
});
|
|
2069
|
+
void work.finally(stop).then(resolve, reject);
|
|
1886
2070
|
});
|
|
1887
2071
|
}
|
|
1888
|
-
/**
|
|
2072
|
+
/** Undefined until the sink has started. */
|
|
1889
2073
|
get videoLatencyMode() {
|
|
1890
2074
|
return this.#latencyMode;
|
|
1891
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
|
+
}
|
|
1892
2093
|
/**
|
|
1893
|
-
* The video track as
|
|
1894
|
-
* `finish` ends the video track and finalizes the file once every configured track has ended;
|
|
1895
|
-
* 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.
|
|
1896
2095
|
*/
|
|
1897
2096
|
get videoTrack() {
|
|
1898
2097
|
if (!this.#hasVideo)
|
|
@@ -1904,10 +2103,7 @@ export class MediabunnySink {
|
|
|
1904
2103
|
};
|
|
1905
2104
|
return this.#videoTrack;
|
|
1906
2105
|
}
|
|
1907
|
-
/**
|
|
1908
|
-
* The audio track as a sink of its own, for a runner that shares the file with another: see
|
|
1909
|
-
* {@link videoTrack}. Throws `RangeError` when no audio track is configured.
|
|
1910
|
-
*/
|
|
2106
|
+
/** The audio track as its own sink; see {@link videoTrack}. Throws `RangeError` if absent. */
|
|
1911
2107
|
get audioTrack() {
|
|
1912
2108
|
if (this.#audio === undefined)
|
|
1913
2109
|
throw new RangeError("audio track is not configured");
|
|
@@ -1918,11 +2114,7 @@ export class MediabunnySink {
|
|
|
1918
2114
|
};
|
|
1919
2115
|
return this.#audioTrack;
|
|
1920
2116
|
}
|
|
1921
|
-
/**
|
|
1922
|
-
* Ends one track: its encoder flushes and the muxer stops waiting for its samples. The last
|
|
1923
|
-
* configured track to end finishes the file; an earlier one resolves at once, so runners that
|
|
1924
|
-
* share the file in turn do not wait for each other.
|
|
1925
|
-
*/
|
|
2117
|
+
/** The last configured track to end finishes the file; earlier ones resolve at once. */
|
|
1926
2118
|
async #endTrack(track) {
|
|
1927
2119
|
await this.#ready;
|
|
1928
2120
|
if (!this.#ended.has(track)) {
|
|
@@ -1935,25 +2127,17 @@ export class MediabunnySink {
|
|
|
1935
2127
|
(this.#audio === undefined || this.#ended.has("audio")))
|
|
1936
2128
|
await this.finish();
|
|
1937
2129
|
}
|
|
1938
|
-
/**
|
|
1939
|
-
* The rate control the browser's encoder was configured with, once the first frame has been
|
|
1940
|
-
* written: whether the quantizer candidate was accepted or the bitrate fallback ran. Undefined
|
|
1941
|
-
* before then.
|
|
1942
|
-
*/
|
|
2130
|
+
/** Undefined until the first frame has been written. */
|
|
1943
2131
|
get appliedVideoRateControl() {
|
|
1944
2132
|
return this.#applied;
|
|
1945
2133
|
}
|
|
1946
|
-
/**
|
|
1947
|
-
* The WebCodecs codec string the video encoder was configured with (for H.264, its profile and
|
|
1948
|
-
* level), once the first frame has been written. Undefined before then.
|
|
1949
|
-
*/
|
|
2134
|
+
/** Undefined until the first frame has been written. */
|
|
1950
2135
|
get videoCodecString() {
|
|
1951
2136
|
return this.#codecString;
|
|
1952
2137
|
}
|
|
1953
2138
|
/**
|
|
1954
|
-
* Encodes one frame at
|
|
1955
|
-
*
|
|
1956
|
-
* 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
|
|
1957
2141
|
* video track is configured.
|
|
1958
2142
|
*/
|
|
1959
2143
|
async writeVideo(output) {
|
|
@@ -1974,14 +2158,14 @@ export class MediabunnySink {
|
|
|
1974
2158
|
? "the output was cancelled before its video track started"
|
|
1975
2159
|
: "video track is not configured");
|
|
1976
2160
|
}
|
|
1977
|
-
// Declaring the duration keeps sample durations uniform instead of inferred from float deltas.
|
|
1978
2161
|
const sample = new VideoSample(output.frame, {
|
|
1979
2162
|
timestamp: Number(output.timeTicks) / 120_000,
|
|
1980
2163
|
duration: this.#frameDuration,
|
|
1981
2164
|
});
|
|
1982
2165
|
if (this.#framesOut >= this.#framesIn)
|
|
1983
|
-
this.#
|
|
2166
|
+
this.#madeProgress();
|
|
1984
2167
|
this.#framesIn += 1;
|
|
2168
|
+
this.#addedAt.set(Math.round((Number(output.timeTicks) / 120_000) * 1_000_000), performance.now());
|
|
1985
2169
|
try {
|
|
1986
2170
|
await this.#watched(this.#video.add(sample));
|
|
1987
2171
|
}
|
|
@@ -1991,13 +2175,9 @@ export class MediabunnySink {
|
|
|
1991
2175
|
}
|
|
1992
2176
|
}
|
|
1993
2177
|
/**
|
|
1994
|
-
* Encodes one
|
|
1995
|
-
*
|
|
1996
|
-
*
|
|
1997
|
-
* rate and channel count. Rejects with `RESOURCE_LIMIT` once a memory destination has passed
|
|
1998
|
-
* `maxBytes`, when no audio track is configured, when the block's channels differ in length, or
|
|
1999
|
-
* (`RangeError`) when a block to convert does not continue the last or no `audioResampler` was
|
|
2000
|
-
* 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`.
|
|
2001
2181
|
*/
|
|
2002
2182
|
async writeAudio(block) {
|
|
2003
2183
|
await this.#ready;
|
|
@@ -2024,7 +2204,6 @@ export class MediabunnySink {
|
|
|
2024
2204
|
if (converted !== null)
|
|
2025
2205
|
await this.#encodeAudio(converted.channels, converted.startSample, this.#audioConverter.targetRate);
|
|
2026
2206
|
}
|
|
2027
|
-
/** Encodes the converted audio still held, once, before the audio track ends. */
|
|
2028
2207
|
async #flushAudio() {
|
|
2029
2208
|
const converter = this.#audioConverter;
|
|
2030
2209
|
if (converter === undefined || this.#audioFlushed)
|
|
@@ -2039,22 +2218,22 @@ export class MediabunnySink {
|
|
|
2039
2218
|
converter.free();
|
|
2040
2219
|
}
|
|
2041
2220
|
}
|
|
2042
|
-
/** Encodes planar `channels` starting at sample `startSample` of a `sampleRate` stream. */
|
|
2043
2221
|
async #encodeAudio(channels, startSample, sampleRate) {
|
|
2044
2222
|
if (this.#audio === undefined)
|
|
2045
2223
|
throw new Error("audio track is not configured");
|
|
2046
|
-
// AAC
|
|
2047
|
-
//
|
|
2048
|
-
// own in its header.
|
|
2224
|
+
// The muxer trims AAC priming placed before zero (edit list, negative Matroska block times);
|
|
2225
|
+
// Opus states its own in its header.
|
|
2049
2226
|
let delay = 0;
|
|
2050
2227
|
if (this.#audioCodec === "aac" && this.#audioBitrate !== undefined) {
|
|
2051
|
-
delay = await (this.#audioDelay ??=
|
|
2228
|
+
delay = await (this.#audioDelay ??= aacEncoderPrimingProbe({
|
|
2052
2229
|
sampleRate,
|
|
2053
2230
|
numberOfChannels: channels.length,
|
|
2054
2231
|
bitrate: this.#audioBitrate,
|
|
2232
|
+
}).then((probe) => {
|
|
2233
|
+
this.#aacProbe = probe;
|
|
2234
|
+
return probe.delay;
|
|
2055
2235
|
}));
|
|
2056
|
-
// Safari's encoder drops
|
|
2057
|
-
// zero with the priming, ahead of the audio.
|
|
2236
|
+
// Safari's encoder drops its first input frame, so lead with a frame of silence.
|
|
2058
2237
|
if (!this.#audioLeadWritten) {
|
|
2059
2238
|
this.#audioLeadWritten = true;
|
|
2060
2239
|
await this.#addAudio(channels.map(() => new Float32Array(AAC_FRAME_FRAMES)), startSample - AAC_FRAME_FRAMES - delay, sampleRate);
|
|
@@ -2062,7 +2241,6 @@ export class MediabunnySink {
|
|
|
2062
2241
|
}
|
|
2063
2242
|
await this.#addAudio(channels, startSample - delay, sampleRate);
|
|
2064
2243
|
}
|
|
2065
|
-
/** Gives the audio encoder planar `channels` at sample `startSample` of a `sampleRate` stream. */
|
|
2066
2244
|
async #addAudio(channels, startSample, sampleRate) {
|
|
2067
2245
|
if (this.#audio === undefined)
|
|
2068
2246
|
throw new Error("audio track is not configured");
|
|
@@ -2084,10 +2262,8 @@ export class MediabunnySink {
|
|
|
2084
2262
|
}
|
|
2085
2263
|
}
|
|
2086
2264
|
/**
|
|
2087
|
-
* Finalizes the file and commits a stream destination;
|
|
2088
|
-
*
|
|
2089
|
-
* `ENCODE_STALLED` when the encoder stalls, and with what the muxer or the destination refused; a
|
|
2090
|
-
* 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.
|
|
2091
2267
|
*/
|
|
2092
2268
|
async finish() {
|
|
2093
2269
|
if (this.#finished)
|
|
@@ -2104,15 +2280,16 @@ export class MediabunnySink {
|
|
|
2104
2280
|
await this.#discard(error).catch(() => { });
|
|
2105
2281
|
throw error;
|
|
2106
2282
|
}
|
|
2283
|
+
finally {
|
|
2284
|
+
this.#progress?.dispose();
|
|
2285
|
+
}
|
|
2107
2286
|
this.#finished = true;
|
|
2108
2287
|
}
|
|
2109
|
-
/**
|
|
2110
|
-
* Cancels the output and discards a stream destination, unless the file already finished.
|
|
2111
|
-
* Rejects when the destination refuses to be discarded.
|
|
2112
|
-
*/
|
|
2288
|
+
/** Discards the output unless already finished; rejects if the destination refuses. */
|
|
2113
2289
|
async abort(reason) {
|
|
2114
2290
|
if (this.#finished)
|
|
2115
2291
|
return;
|
|
2292
|
+
this.#progress?.dispose();
|
|
2116
2293
|
if (this.#audioConverter !== undefined && !this.#audioFlushed) {
|
|
2117
2294
|
this.#audioFlushed = true;
|
|
2118
2295
|
this.#audioConverter.free();
|
|
@@ -2125,17 +2302,13 @@ export class MediabunnySink {
|
|
|
2125
2302
|
await this.#discard(reason);
|
|
2126
2303
|
}
|
|
2127
2304
|
}
|
|
2128
|
-
/** Discards a stream destination once: writes still queued are dropped and nothing commits. */
|
|
2129
2305
|
async #discard(reason) {
|
|
2130
2306
|
if (this.#file === undefined || this.#discarded)
|
|
2131
2307
|
return;
|
|
2132
2308
|
this.#discarded = true;
|
|
2133
2309
|
await this.#file.abort(reason);
|
|
2134
2310
|
}
|
|
2135
|
-
/**
|
|
2136
|
-
* The finished output: its length for a stream, the bytes in memory. Null until {@link finish}
|
|
2137
|
-
* resolves.
|
|
2138
|
-
*/
|
|
2311
|
+
/** Null until {@link finish} resolves. */
|
|
2139
2312
|
get output() {
|
|
2140
2313
|
if (!this.#finished)
|
|
2141
2314
|
return null;
|
|
@@ -2145,24 +2318,18 @@ export class MediabunnySink {
|
|
|
2145
2318
|
}
|
|
2146
2319
|
return { kind: "stream", bytes: this.#written };
|
|
2147
2320
|
}
|
|
2148
|
-
/** Bytes muxed so far: the file's length as written. */
|
|
2149
2321
|
get bytesWritten() {
|
|
2150
2322
|
return this.#written;
|
|
2151
2323
|
}
|
|
2152
2324
|
}
|
|
2153
|
-
/**
|
|
2154
|
-
* Factory kept in the optional subpath so mediabunny is never loaded by core APIs. Audio needs
|
|
2155
|
-
* `alpha2/wasm`'s resampler: see {@link MediabunnyAudioDecoder}.
|
|
2156
|
-
*/
|
|
2325
|
+
/** Kept in an optional subpath so core APIs never load mediabunny. */
|
|
2157
2326
|
export class MediabunnyAdapterFactory {
|
|
2158
2327
|
#audioResampler;
|
|
2159
2328
|
constructor(audioResampler) {
|
|
2160
2329
|
this.#audioResampler = audioResampler;
|
|
2161
2330
|
}
|
|
2162
2331
|
/**
|
|
2163
|
-
*
|
|
2164
|
-
* `input` is a Blob, ArrayBuffer, or ArrayBuffer view, and as {@link MediabunnyVideoDecoder.open}
|
|
2165
|
-
* does.
|
|
2332
|
+
* Rejects with `TypeError` for an unsupported input, and as {@link MediabunnyVideoDecoder.open}.
|
|
2166
2333
|
*/
|
|
2167
2334
|
async openVideo(sourceId, input) {
|
|
2168
2335
|
if (!(input instanceof Blob) &&
|
|
@@ -2173,9 +2340,8 @@ export class MediabunnyAdapterFactory {
|
|
|
2173
2340
|
return MediabunnyVideoDecoder.open(sourceId, input);
|
|
2174
2341
|
}
|
|
2175
2342
|
/**
|
|
2176
|
-
*
|
|
2177
|
-
*
|
|
2178
|
-
* 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}.
|
|
2179
2345
|
*/
|
|
2180
2346
|
async openAudio(sourceId, input) {
|
|
2181
2347
|
if (!(input instanceof Blob) &&
|
|
@@ -2194,8 +2360,3 @@ function ticksToSampleCeil(ticks, sampleRate) {
|
|
|
2194
2360
|
const rate = BigInt(sampleRate);
|
|
2195
2361
|
return Number((ticks * rate + 119999n) / 120000n);
|
|
2196
2362
|
}
|
|
2197
|
-
function throwIfAborted(signal) {
|
|
2198
|
-
if (signal?.aborted === true) {
|
|
2199
|
-
throw signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
2200
|
-
}
|
|
2201
|
-
}
|