alpha2 0.4.6 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +51 -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 +125 -176
- 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/frames.d.ts +23 -0
- package/dist/frames.js +34 -0
- package/dist/generated/project-schema.d.ts +712 -485
- package/dist/generated/project-schema.js +55 -2
- package/dist/generated/project-shape.js +276 -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 +6 -0
- package/dist/index.js +6 -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 +178 -246
- package/dist/mediabunny.js +781 -583
- package/dist/paint.d.ts +23 -0
- package/dist/paint.js +37 -0
- 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 +74 -118
- 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 +501 -587
- package/wasm/alpha2_wasm.js +661 -616
- package/wasm/alpha2_wasm_bg.wasm +0 -0
- package/wasm/alpha2_wasm_bg.wasm.d.ts +22 -12
- package/wasm/rust-crate-licenses.md +2 -2
- package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline1.js +1 -0
- package/wasm/snippets/alpha2-wasm-070d94113471ef0a/inline2.js +82 -0
- package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
- /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline0.js +0 -0
- /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/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,313 @@ 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
|
+
/**
|
|
910
|
+
* Every audio stream of `resource` in container order, as an `AssetEntry.audio_streams` lists
|
|
911
|
+
* them: a clip's `audio.stream` counts over these, and `default` marks the primary track. Empty
|
|
912
|
+
* without audio.
|
|
913
|
+
*/
|
|
914
|
+
export async function probeAudioStreams(resource) {
|
|
915
|
+
const input = new Input({
|
|
916
|
+
source: resource instanceof Blob
|
|
917
|
+
? new BlobSource(resource)
|
|
918
|
+
: new BufferSource(resource),
|
|
919
|
+
formats: ALL_FORMATS,
|
|
920
|
+
});
|
|
921
|
+
try {
|
|
922
|
+
const tracks = await input.getAudioTracks();
|
|
923
|
+
const primary = await input.getPrimaryAudioTrack();
|
|
924
|
+
return await Promise.all(tracks.map(async (track) => {
|
|
925
|
+
const language = await track.getLanguageCode();
|
|
926
|
+
const title = await track.getName();
|
|
927
|
+
return {
|
|
928
|
+
channels: track.numberOfChannels,
|
|
929
|
+
default: track === primary,
|
|
930
|
+
...(track.codec === null ? {} : { codec: track.codec }),
|
|
931
|
+
...(language === "und" ? {} : { language }),
|
|
932
|
+
...(title ? { title } : {}),
|
|
933
|
+
};
|
|
934
|
+
}));
|
|
935
|
+
}
|
|
936
|
+
finally {
|
|
937
|
+
input.dispose();
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
/** {@link probeAudioDecode} on the primary audio track; rejects with `Error` when there is none. */
|
|
941
|
+
export async function probeAudioSource(name, resource) {
|
|
942
|
+
const input = new Input({
|
|
943
|
+
source: resource instanceof Blob
|
|
944
|
+
? new BlobSource(resource)
|
|
945
|
+
: new BufferSource(resource),
|
|
946
|
+
formats: ALL_FORMATS,
|
|
947
|
+
});
|
|
948
|
+
try {
|
|
949
|
+
const track = await input.getPrimaryAudioTrack();
|
|
950
|
+
if (track === null)
|
|
951
|
+
throw new Error("mediabunny input has no audio track");
|
|
952
|
+
const config = await track.getDecoderConfig();
|
|
953
|
+
const declared = await readAudioSpeakers(byteReader(resource), byteLength(resource), track, bufferBytes(config?.description), () => new EncodedPacketSink(track)
|
|
954
|
+
.getFirstPacket()
|
|
955
|
+
.then((packet) => packet?.data ?? null));
|
|
956
|
+
return await probeAudioDecode(name, track, declared);
|
|
957
|
+
}
|
|
958
|
+
finally {
|
|
959
|
+
input.dispose();
|
|
960
|
+
}
|
|
961
|
+
}
|
|
824
962
|
/**
|
|
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}).
|
|
963
|
+
* Optional mediabunny audio demux/decode adapter with project-rate resampling, placing samples as
|
|
964
|
+
* a native host does (including the {@link audioFrameGrid}). Keeps every channel, 1 to
|
|
965
|
+
* {@link MAX_AUDIO_CHANNELS}, reordered to `FFmpeg`'s plane order where a browser decoder differs
|
|
966
|
+
* (Safari's AAC).
|
|
843
967
|
*/
|
|
844
968
|
export class MediabunnyAudioDecoder {
|
|
845
969
|
#sourceId;
|
|
@@ -847,37 +971,24 @@ export class MediabunnyAudioDecoder {
|
|
|
847
971
|
#sink;
|
|
848
972
|
#channelCount;
|
|
849
973
|
/**
|
|
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.
|
|
974
|
+
* The speaker each plane feeds. `null` when the source declares no layout; the engine then
|
|
975
|
+
* assumes `FFmpeg`'s default for the channel count.
|
|
854
976
|
*/
|
|
855
977
|
speakers;
|
|
856
978
|
/**
|
|
857
|
-
*
|
|
858
|
-
* is not the same plane (measured, {@link decoderPlaneOrder}); `undefined` when every plane is
|
|
859
|
-
* where the speakers say.
|
|
979
|
+
* Delivered plane to speaker-order index ({@link decoderPlaneOrder}); `undefined` if identity.
|
|
860
980
|
*/
|
|
861
981
|
#planeOrder;
|
|
862
982
|
#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
983
|
#grid;
|
|
869
|
-
/** How far before what a window needs its decoding starts, in seconds: the codec's pre-roll. */
|
|
870
984
|
#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
|
-
*/
|
|
985
|
+
/** Matroska `CodecDelay` in seconds, which mediabunny does not subtract. */
|
|
876
986
|
#delay;
|
|
877
987
|
#binding;
|
|
988
|
+
#facts;
|
|
878
989
|
#resampler;
|
|
879
990
|
#closed = false;
|
|
880
|
-
constructor(sourceId, input, sink, channelCount, speakers, planeOrder, sourceRate, grid, preroll, delay, binding) {
|
|
991
|
+
constructor(sourceId, input, sink, channelCount, speakers, planeOrder, sourceRate, grid, preroll, delay, binding, facts) {
|
|
881
992
|
this.#sourceId = sourceId;
|
|
882
993
|
this.#input = input;
|
|
883
994
|
this.#sink = sink;
|
|
@@ -889,32 +1000,38 @@ export class MediabunnyAudioDecoder {
|
|
|
889
1000
|
this.#preroll = preroll;
|
|
890
1001
|
this.#delay = delay;
|
|
891
1002
|
this.#binding = binding;
|
|
1003
|
+
this.#facts = facts;
|
|
892
1004
|
}
|
|
893
1005
|
/**
|
|
894
|
-
* Opens `resource`'s primary audio track,
|
|
895
|
-
*
|
|
896
|
-
*
|
|
897
|
-
*
|
|
898
|
-
*
|
|
1006
|
+
* Opens `resource`'s primary audio track, or with `options.stream` the audio track at that
|
|
1007
|
+
* position among the file's audio tracks in container order (a clip's `audio.stream`). Rejects
|
|
1008
|
+
* when there is no such track, with `RangeError` for more than {@link MAX_AUDIO_CHANNELS}
|
|
1009
|
+
* channels or a rate outside 1 kHz to 768 kHz, and with {@link DecodeUnavailableError} when this
|
|
1010
|
+
* browser cannot decode it.
|
|
899
1011
|
*/
|
|
900
|
-
static async open(sourceId, resource, binding) {
|
|
1012
|
+
static async open(sourceId, resource, binding, options = {}) {
|
|
901
1013
|
const source = resource instanceof Blob
|
|
902
1014
|
? new BlobSource(resource)
|
|
903
1015
|
: new BufferSource(resource);
|
|
904
1016
|
const input = new Input({ source, formats: ALL_FORMATS });
|
|
905
|
-
const track =
|
|
1017
|
+
const track = options.stream === undefined
|
|
1018
|
+
? await input.getPrimaryAudioTrack()
|
|
1019
|
+
: ((await input.getAudioTracks())[options.stream] ?? null);
|
|
906
1020
|
if (track === null) {
|
|
907
1021
|
input.dispose();
|
|
908
|
-
throw new Error(
|
|
1022
|
+
throw new Error(options.stream === undefined
|
|
1023
|
+
? "mediabunny input has no audio track"
|
|
1024
|
+
: `mediabunny input has no audio stream ${options.stream}`);
|
|
909
1025
|
}
|
|
910
|
-
|
|
911
|
-
|
|
1026
|
+
if (track.numberOfChannels < 1 ||
|
|
1027
|
+
track.numberOfChannels > MAX_AUDIO_CHANNELS) {
|
|
912
1028
|
input.dispose();
|
|
913
|
-
throw new RangeError(`audio with ${
|
|
1029
|
+
throw new RangeError(`audio with ${track.numberOfChannels} channels is unsupported: the engine takes 1 to ${MAX_AUDIO_CHANNELS}`);
|
|
914
1030
|
}
|
|
915
1031
|
let speakers;
|
|
916
1032
|
let description;
|
|
917
1033
|
let planeOrder;
|
|
1034
|
+
let decodable;
|
|
918
1035
|
try {
|
|
919
1036
|
const config = await track.getDecoderConfig();
|
|
920
1037
|
description = bufferBytes(config?.description);
|
|
@@ -923,16 +1040,27 @@ export class MediabunnyAudioDecoder {
|
|
|
923
1040
|
const readFirstPacket = () => (firstPacket ??= new EncodedPacketSink(track)
|
|
924
1041
|
.getFirstPacket()
|
|
925
1042
|
.then((packet) => packet?.data ?? null));
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
1043
|
+
const declared = await readAudioSpeakers(byteReader(resource), byteLength(resource), track, description, readFirstPacket);
|
|
1044
|
+
decodable = await probeAudioDecode(sourceId, track, declared);
|
|
1045
|
+
speakers = decodable.speakers;
|
|
1046
|
+
// The measured order does not cover an added LFE, which the decoder puts in native order.
|
|
1047
|
+
planeOrder = decodable.addedLfe
|
|
1048
|
+
? null
|
|
1049
|
+
: await decoderPlaneOrder(decoderOrderKey(track.codec, description, track.numberOfChannels, track.codec === "ac3" || track.codec === "eac3"
|
|
1050
|
+
? await readFirstPacket()
|
|
1051
|
+
: null));
|
|
930
1052
|
}
|
|
931
1053
|
catch (error) {
|
|
932
1054
|
input.dispose();
|
|
933
1055
|
throw error;
|
|
934
1056
|
}
|
|
935
|
-
const
|
|
1057
|
+
const channelCount = decodable.channels;
|
|
1058
|
+
if (channelCount > MAX_AUDIO_CHANNELS) {
|
|
1059
|
+
input.dispose();
|
|
1060
|
+
throw new RangeError(`audio decoded to ${channelCount} channels is unsupported: the engine takes 1 to ${MAX_AUDIO_CHANNELS}`);
|
|
1061
|
+
}
|
|
1062
|
+
// An implicitly signalled AAC extension decodes at twice the header's rate.
|
|
1063
|
+
const sourceRate = decodable.sampleRate;
|
|
936
1064
|
if (!Number.isInteger(sourceRate) ||
|
|
937
1065
|
sourceRate < SOURCE_SAMPLE_RATES.min ||
|
|
938
1066
|
sourceRate > SOURCE_SAMPLE_RATES.max) {
|
|
@@ -943,8 +1071,7 @@ export class MediabunnyAudioDecoder {
|
|
|
943
1071
|
let delay;
|
|
944
1072
|
try {
|
|
945
1073
|
const first = await firstPacketTimes(track, new EncodedPacketSink(track));
|
|
946
|
-
//
|
|
947
|
-
// FFmpeg does, so the samples line up with the same encode's in MP4.
|
|
1074
|
+
// Native hosts subtract `CodecDelay`, so the samples line up with the same encode in MP4.
|
|
948
1075
|
const codecDelay = await readMatroskaCodecDelay(resource, track.id);
|
|
949
1076
|
let packetGrid;
|
|
950
1077
|
if (first === undefined)
|
|
@@ -954,8 +1081,7 @@ export class MediabunnyAudioDecoder {
|
|
|
954
1081
|
delay = delayUnits / first.resolution;
|
|
955
1082
|
packetGrid = audioFrameGrid(first.timestamps.map((timestamp) => timestamp - delayUnits), first.resolution, sourceRate);
|
|
956
1083
|
}
|
|
957
|
-
//
|
|
958
|
-
// each window's frames start the pre-skip before the packet grid.
|
|
1084
|
+
// WebCodecs Opus drops the pre-skip from the first frame after each configure.
|
|
959
1085
|
const preSkip = track.codec === "opus" ? opusPreSkip(description) : 0;
|
|
960
1086
|
grid =
|
|
961
1087
|
packetGrid === undefined
|
|
@@ -970,7 +1096,12 @@ export class MediabunnyAudioDecoder {
|
|
|
970
1096
|
planeOrder.length !== channelCount ||
|
|
971
1097
|
planeOrder.every((engine, plane) => engine === plane)
|
|
972
1098
|
? undefined
|
|
973
|
-
: planeOrder, sourceRate, grid, track.codec === "opus" ? OPUS_PREROLL_SECONDS : AUDIO_PREROLL_SECONDS, delay, binding
|
|
1099
|
+
: planeOrder, sourceRate, grid, track.codec === "opus" ? OPUS_PREROLL_SECONDS : AUDIO_PREROLL_SECONDS, delay, binding, {
|
|
1100
|
+
kind: "audio",
|
|
1101
|
+
codec: track.codec ?? null,
|
|
1102
|
+
channels: track.numberOfChannels,
|
|
1103
|
+
...(speakers === null ? {} : { layout: speakers }),
|
|
1104
|
+
});
|
|
974
1105
|
}
|
|
975
1106
|
#resamplerTo(targetRate) {
|
|
976
1107
|
if (this.#resampler?.targetRate !== targetRate) {
|
|
@@ -983,12 +1114,10 @@ export class MediabunnyAudioDecoder {
|
|
|
983
1114
|
return this.#resampler.resampler;
|
|
984
1115
|
}
|
|
985
1116
|
/**
|
|
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.
|
|
1117
|
+
* Decodes the interval at `projectSampleRate`, plus two samples each side; silence outside the
|
|
1118
|
+
* stream. Rejects when closed, for another source or empty interval, on abort, or when the track
|
|
1119
|
+
* changes format mid-stream; with {@link DecodeUnavailableError} when the browser's decoder
|
|
1120
|
+
* fails.
|
|
992
1121
|
*/
|
|
993
1122
|
async refill(request, projectSampleRate, signal) {
|
|
994
1123
|
if (this.#closed)
|
|
@@ -1000,7 +1129,6 @@ export class MediabunnyAudioDecoder {
|
|
|
1000
1129
|
if (!Number.isInteger(projectSampleRate) || projectSampleRate <= 0)
|
|
1001
1130
|
throw new RangeError("invalid project sample rate");
|
|
1002
1131
|
throwIfAborted(signal);
|
|
1003
|
-
// The two-sample margin lets the engine interpolate at either edge without the whole source.
|
|
1004
1132
|
const firstSample = Math.max(0, ticksToSampleFloor(request.startMediaTimeTicks, projectSampleRate) - 2);
|
|
1005
1133
|
const lastSample = ticksToSampleCeil(request.endMediaTimeTicks, projectSampleRate) + 2;
|
|
1006
1134
|
const frames = Math.max(1, lastSample - firstSample);
|
|
@@ -1011,61 +1139,66 @@ export class MediabunnyAudioDecoder {
|
|
|
1011
1139
|
const sourceEnd = resampler.sourceEnd(firstSample + frames);
|
|
1012
1140
|
const source = Array.from({ length: channelCount }, () => new Float32Array(sourceEnd - sourceStart));
|
|
1013
1141
|
const decodeFrom = sourceStart / rate - this.#preroll;
|
|
1014
|
-
/** The first sample decoded, when nothing comes before it in the stream. */
|
|
1015
1142
|
let streamStart;
|
|
1016
|
-
/** Where the next sample continues the last one placed. */
|
|
1017
1143
|
let expected;
|
|
1018
1144
|
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
|
-
|
|
1145
|
+
try {
|
|
1146
|
+
for await (const sample of this.#sink.samples(decodeFrom + delay, sourceEnd / rate + delay)) {
|
|
1147
|
+
try {
|
|
1148
|
+
throwIfAborted(signal);
|
|
1149
|
+
if (sample.numberOfChannels !== channelCount)
|
|
1150
|
+
throw new RangeError(`audio track changed from ${channelCount} to ${sample.numberOfChannels} channels`);
|
|
1151
|
+
if (sample.sampleRate !== rate)
|
|
1152
|
+
throw new RangeError(`audio track changed from ${rate} Hz to ${sample.sampleRate} Hz`);
|
|
1153
|
+
const length = sample.numberOfFrames;
|
|
1154
|
+
const timestamp = sample.timestamp - delay;
|
|
1155
|
+
let at = Math.round(timestamp * rate);
|
|
1156
|
+
let skip = 0;
|
|
1157
|
+
if (expected === undefined) {
|
|
1158
|
+
if (this.#grid !== undefined)
|
|
1159
|
+
at = placeOnAudioFrameGrid(this.#grid, at, length);
|
|
1160
|
+
// mediabunny starts at the packet holding the requested time, so a later first sample
|
|
1161
|
+
// is the stream's first.
|
|
1162
|
+
if (timestamp > decodeFrom)
|
|
1163
|
+
streamStart = at;
|
|
1164
|
+
}
|
|
1165
|
+
else {
|
|
1166
|
+
const ahead = at - expected;
|
|
1167
|
+
const tolerance = Math.max(length, Math.ceil(rate / 500));
|
|
1168
|
+
if (Math.abs(ahead) < tolerance)
|
|
1169
|
+
at = expected;
|
|
1170
|
+
else if (ahead < 0) {
|
|
1171
|
+
skip = Math.min(length, -ahead);
|
|
1172
|
+
at = expected;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
expected = at + length - skip;
|
|
1176
|
+
const from = Math.max(at, sourceStart);
|
|
1177
|
+
const to = Math.min(at + length - skip, sourceEnd);
|
|
1178
|
+
if (to <= from)
|
|
1179
|
+
continue;
|
|
1180
|
+
const data = new Float32Array(length);
|
|
1181
|
+
const order = this.#planeOrder;
|
|
1182
|
+
for (let plane = 0; plane < channelCount; plane += 1) {
|
|
1183
|
+
sample.copyTo(data, { planeIndex: plane, format: "f32-planar" });
|
|
1184
|
+
source[order === undefined ? plane : order[plane]].set(data.subarray(skip + from - at, skip + to - at), from - sourceStart);
|
|
1049
1185
|
}
|
|
1050
1186
|
}
|
|
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);
|
|
1187
|
+
finally {
|
|
1188
|
+
sample.close();
|
|
1061
1189
|
}
|
|
1062
1190
|
}
|
|
1063
|
-
|
|
1064
|
-
|
|
1191
|
+
}
|
|
1192
|
+
catch (error) {
|
|
1193
|
+
if (typeof DOMException !== "undefined" &&
|
|
1194
|
+
error instanceof DOMException &&
|
|
1195
|
+
error.name !== "AbortError") {
|
|
1196
|
+
const facts = { ...this.#facts, browserError: error.message };
|
|
1197
|
+
throw new DecodeUnavailableError(decodeRefusalMessage(this.#sourceId, facts), facts, { cause: error });
|
|
1065
1198
|
}
|
|
1199
|
+
throw error;
|
|
1066
1200
|
}
|
|
1067
|
-
//
|
|
1068
|
-
// stream's first and last samples rings past them.
|
|
1201
|
+
// A band-limited reading of the edge samples would ring past the stream.
|
|
1069
1202
|
const first = streamStart === undefined
|
|
1070
1203
|
? firstSample
|
|
1071
1204
|
: Math.max(firstSample, resampler.targetAtOrAfter(streamStart));
|
|
@@ -1089,7 +1222,6 @@ export class MediabunnyAudioDecoder {
|
|
|
1089
1222
|
channels,
|
|
1090
1223
|
};
|
|
1091
1224
|
}
|
|
1092
|
-
/** Frees the resampler and the input. A later `refill` rejects. */
|
|
1093
1225
|
close() {
|
|
1094
1226
|
if (!this.#closed) {
|
|
1095
1227
|
this.#closed = true;
|
|
@@ -1099,10 +1231,6 @@ export class MediabunnyAudioDecoder {
|
|
|
1099
1231
|
}
|
|
1100
1232
|
}
|
|
1101
1233
|
}
|
|
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
1234
|
export function videoEncoderQuality(rate) {
|
|
1107
1235
|
return new Quality({
|
|
1108
1236
|
bitrate: rate.bitrate,
|
|
@@ -1110,17 +1238,13 @@ export function videoEncoderQuality(rate) {
|
|
|
1110
1238
|
...(rate.quantizer === undefined ? {} : { quantizer: rate.quantizer }),
|
|
1111
1239
|
});
|
|
1112
1240
|
}
|
|
1113
|
-
/** The H.264 profiles in the order they are asked for, with `profile_idc` and constraint flags. */
|
|
1114
1241
|
const AVC_PROFILES = [
|
|
1115
1242
|
{ profile: "High", prefix: "6400" },
|
|
1116
1243
|
{ profile: "Main", prefix: "4d00" },
|
|
1117
1244
|
// constraint_set0, 1 and 2: decodable by Baseline, Main and Extended decoders.
|
|
1118
1245
|
{ profile: "Constrained Baseline", prefix: "42e0" },
|
|
1119
1246
|
];
|
|
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
|
-
*/
|
|
1247
|
+
/** H.264 levels by frame size in macroblocks and bitrate, as mediabunny picks them. */
|
|
1124
1248
|
const AVC_LEVELS = [
|
|
1125
1249
|
{ macroblocks: 99, bitrate: 64_000, level: 0x0a },
|
|
1126
1250
|
{ macroblocks: 396, bitrate: 192_000, level: 0x0b },
|
|
@@ -1143,10 +1267,8 @@ const AVC_LEVELS = [
|
|
|
1143
1267
|
{ macroblocks: 139_264, bitrate: 800_000_000, level: 0x3e },
|
|
1144
1268
|
];
|
|
1145
1269
|
/**
|
|
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.
|
|
1270
|
+
* The H.264 profiles {@link canEncodeVideoTrack} tries, in order (High, Main, Constrained
|
|
1271
|
+
* Baseline), at the needed level. Empty for other codecs.
|
|
1150
1272
|
*/
|
|
1151
1273
|
export function videoEncoderProfiles(codec, options) {
|
|
1152
1274
|
if (codec !== "avc")
|
|
@@ -1163,10 +1285,8 @@ export function videoEncoderProfiles(codec, options) {
|
|
|
1163
1285
|
}
|
|
1164
1286
|
/**
|
|
1165
1287
|
* 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`.
|
|
1288
|
+
* not. H.264 picks the first accepted of {@link videoEncoderProfiles}: pass its `codecString` to
|
|
1289
|
+
* the sink and report its `fallbacks`.
|
|
1170
1290
|
*/
|
|
1171
1291
|
export async function canEncodeVideoTrack(codec, options) {
|
|
1172
1292
|
const encodes = (fullCodecString) => canEncodeVideo(codec, {
|
|
@@ -1191,10 +1311,124 @@ export async function canEncodeVideoTrack(codec, options) {
|
|
|
1191
1311
|
}
|
|
1192
1312
|
return null;
|
|
1193
1313
|
}
|
|
1314
|
+
/** Whether this browser has a software encoder for this configuration. */
|
|
1315
|
+
export async function canEncodeInSoftware(codec, options) {
|
|
1316
|
+
return canEncodeVideo(codec, {
|
|
1317
|
+
width: options.width,
|
|
1318
|
+
height: options.height,
|
|
1319
|
+
quality: videoEncoderQuality(options.rate),
|
|
1320
|
+
hardwareAcceleration: "prefer-software",
|
|
1321
|
+
...(options.codecString === undefined
|
|
1322
|
+
? {}
|
|
1323
|
+
: { fullCodecString: options.codecString }),
|
|
1324
|
+
}).catch(() => false);
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* The 10-bit codec string for `codec`; `undefined` for H.264, which browsers do not encode at 10
|
|
1328
|
+
* bits.
|
|
1329
|
+
*/
|
|
1330
|
+
export function tenBitCodecString(codec) {
|
|
1331
|
+
switch (codec) {
|
|
1332
|
+
case "vp9":
|
|
1333
|
+
return "vp09.02.10.10";
|
|
1334
|
+
case "av1":
|
|
1335
|
+
return "av01.0.04M.10";
|
|
1336
|
+
case "hevc":
|
|
1337
|
+
return "hvc1.2.4.L123.B0";
|
|
1338
|
+
default:
|
|
1339
|
+
return undefined;
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
const PIXEL_PROBE_WIDTH = 64;
|
|
1343
|
+
const PIXEL_PROBE_HEIGHT = 64;
|
|
1344
|
+
const PIXEL_PROBE_TIMEOUT_MS = 3_000;
|
|
1194
1345
|
/**
|
|
1195
|
-
*
|
|
1196
|
-
*
|
|
1346
|
+
* Whether this browser encodes `codec` in `pixels` (alpha, 10 bits, or both). Encodes one real
|
|
1347
|
+
* frame, since `isConfigSupported` can claim alpha that is then dropped.
|
|
1197
1348
|
*/
|
|
1349
|
+
export async function canEncodePixels(codec, pixels) {
|
|
1350
|
+
if (pixels.bitDepth === 8 && !pixels.alpha)
|
|
1351
|
+
return true;
|
|
1352
|
+
if (typeof VideoEncoder === "undefined" || typeof VideoFrame === "undefined")
|
|
1353
|
+
return false;
|
|
1354
|
+
const codecString = pixels.bitDepth === 10
|
|
1355
|
+
? tenBitCodecString(codec)
|
|
1356
|
+
: LATENCY_PROBE_CODECS[codec];
|
|
1357
|
+
if (codecString === undefined)
|
|
1358
|
+
return false;
|
|
1359
|
+
const config = {
|
|
1360
|
+
codec: codecString,
|
|
1361
|
+
width: PIXEL_PROBE_WIDTH,
|
|
1362
|
+
height: PIXEL_PROBE_HEIGHT,
|
|
1363
|
+
bitrate: 500_000,
|
|
1364
|
+
framerate: 30,
|
|
1365
|
+
...(pixels.alpha ? { alpha: "keep" } : {}),
|
|
1366
|
+
};
|
|
1367
|
+
try {
|
|
1368
|
+
if (!(await VideoEncoder.isConfigSupported(config)).supported)
|
|
1369
|
+
return false;
|
|
1370
|
+
}
|
|
1371
|
+
catch {
|
|
1372
|
+
return false;
|
|
1373
|
+
}
|
|
1374
|
+
const format = `I420${pixels.alpha ? "A" : ""}${pixels.bitDepth === 10 ? "P10" : ""}`;
|
|
1375
|
+
const samples = PIXEL_PROBE_WIDTH * PIXEL_PROBE_HEIGHT;
|
|
1376
|
+
const bytes = pixels.bitDepth === 10 ? 2 : 1;
|
|
1377
|
+
const planes = (1.5 + (pixels.alpha ? 1 : 0)) * samples * bytes;
|
|
1378
|
+
let encoder;
|
|
1379
|
+
const probeDone = new AbortController();
|
|
1380
|
+
try {
|
|
1381
|
+
let kept = false;
|
|
1382
|
+
let failed = false;
|
|
1383
|
+
let settle = () => { };
|
|
1384
|
+
const output = new Promise((resolve) => (settle = resolve));
|
|
1385
|
+
encoder = new VideoEncoder({
|
|
1386
|
+
output: (_chunk, metadata) => {
|
|
1387
|
+
// `alphaSideData` is newer than the DOM types this package builds with.
|
|
1388
|
+
const alpha = metadata
|
|
1389
|
+
?.alphaSideData;
|
|
1390
|
+
kept = !pixels.alpha || alpha !== undefined;
|
|
1391
|
+
settle();
|
|
1392
|
+
},
|
|
1393
|
+
error: () => {
|
|
1394
|
+
failed = true;
|
|
1395
|
+
settle();
|
|
1396
|
+
},
|
|
1397
|
+
});
|
|
1398
|
+
encoder.configure(config);
|
|
1399
|
+
const frame = new VideoFrame(new Uint8Array(planes), {
|
|
1400
|
+
format: format,
|
|
1401
|
+
codedWidth: PIXEL_PROBE_WIDTH,
|
|
1402
|
+
codedHeight: PIXEL_PROBE_HEIGHT,
|
|
1403
|
+
timestamp: 0,
|
|
1404
|
+
});
|
|
1405
|
+
try {
|
|
1406
|
+
encoder.encode(frame, { keyFrame: true });
|
|
1407
|
+
}
|
|
1408
|
+
finally {
|
|
1409
|
+
frame.close();
|
|
1410
|
+
}
|
|
1411
|
+
await Promise.race([
|
|
1412
|
+
output,
|
|
1413
|
+
encoder.flush().catch(() => (failed = true)),
|
|
1414
|
+
activeTimeout(PIXEL_PROBE_TIMEOUT_MS, probeDone.signal),
|
|
1415
|
+
]);
|
|
1416
|
+
return kept && !failed;
|
|
1417
|
+
}
|
|
1418
|
+
catch {
|
|
1419
|
+
return false;
|
|
1420
|
+
}
|
|
1421
|
+
finally {
|
|
1422
|
+
probeDone.abort();
|
|
1423
|
+
try {
|
|
1424
|
+
if (encoder?.state !== "closed")
|
|
1425
|
+
encoder?.close();
|
|
1426
|
+
}
|
|
1427
|
+
catch {
|
|
1428
|
+
// Already closed by its own failure.
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1198
1432
|
const LATENCY_PROBE_CODECS = {
|
|
1199
1433
|
avc: "avc1.64001e",
|
|
1200
1434
|
hevc: "hev1.1.6.L93.B0",
|
|
@@ -1205,33 +1439,57 @@ const LATENCY_PROBE_WIDTH = 320;
|
|
|
1205
1439
|
const LATENCY_PROBE_HEIGHT = 240;
|
|
1206
1440
|
/** More frames than Safari's encoder takes in before it stops. */
|
|
1207
1441
|
const LATENCY_PROBE_FRAMES = 6;
|
|
1208
|
-
/** How long a probe encoder has to put out its first chunk. */
|
|
1209
1442
|
const LATENCY_PROBE_TIMEOUT_MS = 1_500;
|
|
1210
1443
|
const latencyModes = new Map();
|
|
1211
|
-
/**
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
*/
|
|
1216
|
-
export function
|
|
1217
|
-
|
|
1218
|
-
if (
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1444
|
+
/** `"realtime"` only where a quality-mode encoder outputs nothing (Safari 27's H.264). */
|
|
1445
|
+
export async function videoEncoderLatencyMode(codec) {
|
|
1446
|
+
return (await videoEncoderLatencyProbe(codec)).mode;
|
|
1447
|
+
}
|
|
1448
|
+
/** {@link videoEncoderLatencyMode} with how it was measured. */
|
|
1449
|
+
export async function videoEncoderLatencyProbe(codec) {
|
|
1450
|
+
const known = latencyModes.get(codec);
|
|
1451
|
+
if (known !== undefined) {
|
|
1452
|
+
const { probe, definitive } = await known;
|
|
1453
|
+
if (definitive)
|
|
1454
|
+
return { ...probe, cached: true };
|
|
1455
|
+
}
|
|
1456
|
+
const measuring = measureLatencyMode(codec);
|
|
1457
|
+
latencyModes.set(codec, measuring);
|
|
1458
|
+
const { probe, definitive } = await measuring;
|
|
1459
|
+
if (!definitive && latencyModes.get(codec) === measuring)
|
|
1460
|
+
latencyModes.delete(codec);
|
|
1461
|
+
return probe;
|
|
1223
1462
|
}
|
|
1224
1463
|
async function measureLatencyMode(codec) {
|
|
1464
|
+
const started = performance.now();
|
|
1465
|
+
const answer = (mode, outcome, definitive) => ({
|
|
1466
|
+
probe: { mode, ms: performance.now() - started, outcome, cached: false },
|
|
1467
|
+
definitive,
|
|
1468
|
+
});
|
|
1225
1469
|
if (typeof VideoEncoder === "undefined")
|
|
1226
|
-
return "quality";
|
|
1227
|
-
// One at a time: on Chrome a realtime encoder
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1470
|
+
return answer("quality", "unavailable", true);
|
|
1471
|
+
// One at a time: on Chrome a concurrent realtime encoder delays the quality one.
|
|
1472
|
+
const quality = await encoderPutsOut(codec, "quality");
|
|
1473
|
+
if (quality === "output")
|
|
1474
|
+
return answer("quality", quality, true);
|
|
1475
|
+
if (quality === "failed")
|
|
1476
|
+
return answer("quality", quality, false);
|
|
1477
|
+
const realtime = await encoderPutsOut(codec, "realtime");
|
|
1478
|
+
// A silent quality encoder never outputs, so use the realtime one even if it only timed out.
|
|
1479
|
+
if (quality === "silent" && realtime === "timed-out")
|
|
1480
|
+
return answer("realtime", realtime, false);
|
|
1481
|
+
if (realtime !== "output")
|
|
1482
|
+
return answer("quality", realtime, false);
|
|
1483
|
+
if (quality === "silent")
|
|
1484
|
+
return answer("realtime", realtime, true);
|
|
1485
|
+
// Retry the timed-out quality probe now that the encoder is warm.
|
|
1486
|
+
const warm = await encoderPutsOut(codec, "quality");
|
|
1487
|
+
if (warm === "output")
|
|
1488
|
+
return answer("quality", warm, true);
|
|
1489
|
+
if (warm === "timed-out" || warm === "silent")
|
|
1490
|
+
return answer("realtime", realtime, true);
|
|
1491
|
+
return answer("quality", warm, false);
|
|
1233
1492
|
}
|
|
1234
|
-
/** `true` once the encoder puts out a chunk, `false` if it puts out none, `undefined` if it failed. */
|
|
1235
1493
|
async function encoderPutsOut(codec, latencyMode) {
|
|
1236
1494
|
const config = {
|
|
1237
1495
|
codec: LATENCY_PROBE_CODECS[codec],
|
|
@@ -1244,15 +1502,16 @@ async function encoderPutsOut(codec, latencyMode) {
|
|
|
1244
1502
|
};
|
|
1245
1503
|
try {
|
|
1246
1504
|
if (!(await VideoEncoder.isConfigSupported(config)).supported)
|
|
1247
|
-
return
|
|
1505
|
+
return "failed";
|
|
1248
1506
|
}
|
|
1249
1507
|
catch {
|
|
1250
|
-
return
|
|
1508
|
+
return "failed";
|
|
1251
1509
|
}
|
|
1252
1510
|
let outputs = 0;
|
|
1253
1511
|
let failed = false;
|
|
1512
|
+
let flushed = false;
|
|
1254
1513
|
let encoder;
|
|
1255
|
-
|
|
1514
|
+
const probeDone = new AbortController();
|
|
1256
1515
|
let putOut = () => { };
|
|
1257
1516
|
const firstOutput = new Promise((resolve) => (putOut = resolve));
|
|
1258
1517
|
try {
|
|
@@ -1283,20 +1542,20 @@ async function encoderPutsOut(codec, latencyMode) {
|
|
|
1283
1542
|
}
|
|
1284
1543
|
await Promise.race([
|
|
1285
1544
|
firstOutput,
|
|
1286
|
-
encoder.flush().
|
|
1287
|
-
|
|
1288
|
-
timer = setTimeout(resolve, LATENCY_PROBE_TIMEOUT_MS);
|
|
1289
|
-
}),
|
|
1545
|
+
encoder.flush().then(() => (flushed = true), () => (failed = true)),
|
|
1546
|
+
activeTimeout(LATENCY_PROBE_TIMEOUT_MS, probeDone.signal),
|
|
1290
1547
|
]);
|
|
1291
1548
|
if (outputs > 0)
|
|
1292
|
-
return
|
|
1293
|
-
|
|
1549
|
+
return "output";
|
|
1550
|
+
if (failed)
|
|
1551
|
+
return "failed";
|
|
1552
|
+
return flushed ? "silent" : "timed-out";
|
|
1294
1553
|
}
|
|
1295
1554
|
catch {
|
|
1296
|
-
return
|
|
1555
|
+
return "failed";
|
|
1297
1556
|
}
|
|
1298
1557
|
finally {
|
|
1299
|
-
|
|
1558
|
+
probeDone.abort();
|
|
1300
1559
|
try {
|
|
1301
1560
|
if (encoder?.state !== "closed")
|
|
1302
1561
|
encoder?.close();
|
|
@@ -1306,10 +1565,6 @@ async function encoderPutsOut(codec, latencyMode) {
|
|
|
1306
1565
|
}
|
|
1307
1566
|
}
|
|
1308
1567
|
}
|
|
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
1568
|
const ENCODER_SAMPLE_RATES = {
|
|
1314
1569
|
aac: [
|
|
1315
1570
|
8_000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000,
|
|
@@ -1318,13 +1573,9 @@ const ENCODER_SAMPLE_RATES = {
|
|
|
1318
1573
|
opus: [8_000, 12_000, 16_000, 24_000, 48_000],
|
|
1319
1574
|
};
|
|
1320
1575
|
/**
|
|
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.
|
|
1576
|
+
* The rate to encode `codec` audio at for a project at `sampleRate`: the project rate if supported,
|
|
1577
|
+
* else the nearest higher supported rate, else the nearest lower; `null` for none. Pass it to
|
|
1578
|
+
* {@link MediabunnySink} as `audioSampleRate`.
|
|
1328
1579
|
*/
|
|
1329
1580
|
export async function audioEncoderSampleRate(codec, options) {
|
|
1330
1581
|
const rate = options.sampleRate;
|
|
@@ -1354,25 +1605,15 @@ export async function audioEncoderSampleRate(codec, options) {
|
|
|
1354
1605
|
}
|
|
1355
1606
|
return null;
|
|
1356
1607
|
}
|
|
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
|
-
*/
|
|
1608
|
+
/** AAC-LC, as native hosts encode; mediabunny would pick HE-AAC at 24 kHz and below. */
|
|
1361
1609
|
const AAC_CODEC_STRING = "mp4a.40.2";
|
|
1362
|
-
/** The frames in one AAC-LC frame. */
|
|
1363
1610
|
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
|
-
*/
|
|
1611
|
+
/** ISO/IEC 14496-3 `samplingFrequencyIndex` values. */
|
|
1368
1612
|
const AAC_SAMPLING_FREQUENCIES = [
|
|
1369
1613
|
96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000,
|
|
1370
1614
|
12_000, 11_025, 8_000, 7_350,
|
|
1371
1615
|
];
|
|
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
|
-
*/
|
|
1616
|
+
/** Undefined for a rate without an index or a channel count without a configuration. */
|
|
1376
1617
|
function aacLcAudioSpecificConfig(sampleRate, numberOfChannels) {
|
|
1377
1618
|
const frequency = AAC_SAMPLING_FREQUENCIES.indexOf(sampleRate);
|
|
1378
1619
|
const channels = numberOfChannels === 8 ? 7 : numberOfChannels <= 6 ? numberOfChannels : 0;
|
|
@@ -1383,30 +1624,22 @@ function aacLcAudioSpecificConfig(sampleRate, numberOfChannels) {
|
|
|
1383
1624
|
((frequency & 1) << 7) | (channels << 3),
|
|
1384
1625
|
]);
|
|
1385
1626
|
}
|
|
1386
|
-
/** The low-passed noise burst an AAC delay probe encodes, in frames. */
|
|
1387
1627
|
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
1628
|
const AAC_DELAY_MAX_FRAMES = 8_192;
|
|
1390
|
-
/** How long a delay probe has to encode and decode the burst. */
|
|
1391
1629
|
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
1630
|
const AAC_DELAY_MIN_CORRELATION = 0.5;
|
|
1394
1631
|
const aacProbes = new Map();
|
|
1395
1632
|
/**
|
|
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.
|
|
1633
|
+
* The priming frames this browser's AAC-LC encoder puts before its input, which WebCodecs does not
|
|
1634
|
+
* report. Measured once per configuration by finding an encoded noise burst; 0 on failure.
|
|
1402
1635
|
*/
|
|
1403
1636
|
export async function aacEncoderDelay(options) {
|
|
1404
1637
|
return (await probeAacEncoder(options)).delay;
|
|
1405
1638
|
}
|
|
1406
|
-
/**
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1639
|
+
/** {@link aacEncoderDelay} with its outcome. Timeouts are retried once and never cached. */
|
|
1640
|
+
export function aacEncoderPrimingProbe(options) {
|
|
1641
|
+
return probeAacEncoder(options);
|
|
1642
|
+
}
|
|
1410
1643
|
function probeAacEncoder(options) {
|
|
1411
1644
|
const config = {
|
|
1412
1645
|
codec: AAC_CODEC_STRING,
|
|
@@ -1415,17 +1648,30 @@ function probeAacEncoder(options) {
|
|
|
1415
1648
|
bitrate: options.bitrate,
|
|
1416
1649
|
};
|
|
1417
1650
|
const key = JSON.stringify(config);
|
|
1418
|
-
|
|
1419
|
-
if (
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1651
|
+
const known = aacProbes.get(key);
|
|
1652
|
+
if (known !== undefined)
|
|
1653
|
+
return known;
|
|
1654
|
+
const probe = (async () => {
|
|
1655
|
+
const started = performance.now();
|
|
1656
|
+
let measured = await measureAacEncoder(config);
|
|
1657
|
+
let attempts = 1;
|
|
1658
|
+
if (measured.outcome === "timed-out") {
|
|
1659
|
+
measured = await measureAacEncoder(config);
|
|
1660
|
+
attempts = 2;
|
|
1661
|
+
}
|
|
1662
|
+
return { ...measured, ms: performance.now() - started, attempts };
|
|
1663
|
+
})();
|
|
1664
|
+
aacProbes.set(key, probe);
|
|
1665
|
+
void probe.then((measured) => {
|
|
1666
|
+
if (measured.outcome === "timed-out" && aacProbes.get(key) === probe)
|
|
1667
|
+
aacProbes.delete(key);
|
|
1668
|
+
});
|
|
1423
1669
|
return probe;
|
|
1424
1670
|
}
|
|
1425
1671
|
async function measureAacEncoder(config) {
|
|
1426
1672
|
if (typeof AudioEncoder === "undefined" ||
|
|
1427
1673
|
typeof AudioDecoder === "undefined")
|
|
1428
|
-
return { delay: 0 };
|
|
1674
|
+
return { delay: 0, outcome: "unavailable" };
|
|
1429
1675
|
let encoder;
|
|
1430
1676
|
let decoder;
|
|
1431
1677
|
let timer;
|
|
@@ -1434,7 +1680,7 @@ async function measureAacEncoder(config) {
|
|
|
1434
1680
|
});
|
|
1435
1681
|
try {
|
|
1436
1682
|
if (!(await AudioEncoder.isConfigSupported(config)).supported)
|
|
1437
|
-
return { delay: 0 };
|
|
1683
|
+
return { delay: 0, outcome: "failed" };
|
|
1438
1684
|
let failed = false;
|
|
1439
1685
|
const chunks = [];
|
|
1440
1686
|
let decoderConfig;
|
|
@@ -1446,8 +1692,7 @@ async function measureAacEncoder(config) {
|
|
|
1446
1692
|
error: () => (failed = true),
|
|
1447
1693
|
});
|
|
1448
1694
|
encoder.configure(config);
|
|
1449
|
-
//
|
|
1450
|
-
// frame of any input (see `#encodeAudio`).
|
|
1695
|
+
// Safari's encoder drops the first input frame, so the burst follows a frame of silence.
|
|
1451
1696
|
const probe = aacDelayProbe();
|
|
1452
1697
|
const frames = AAC_FRAME_FRAMES + AAC_DELAY_PROBE_FRAMES + AAC_DELAY_MAX_FRAMES;
|
|
1453
1698
|
const planar = new Float32Array(frames * config.numberOfChannels);
|
|
@@ -1468,12 +1713,12 @@ async function measureAacEncoder(config) {
|
|
|
1468
1713
|
input.close();
|
|
1469
1714
|
}
|
|
1470
1715
|
if ((await Promise.race([encoder.flush(), timedOut])) === "timeout")
|
|
1471
|
-
return { delay: 0 };
|
|
1716
|
+
return { delay: 0, outcome: "timed-out" };
|
|
1472
1717
|
if (failed || decoderConfig === undefined)
|
|
1473
|
-
return { delay: 0 };
|
|
1718
|
+
return { delay: 0, outcome: "failed" };
|
|
1474
1719
|
const rate = decoderConfig.sampleRate;
|
|
1475
1720
|
if (rate !== config.sampleRate)
|
|
1476
|
-
return { rate, delay: 0 };
|
|
1721
|
+
return { rate, delay: 0, outcome: "output" };
|
|
1477
1722
|
const planes = [];
|
|
1478
1723
|
decoder = new AudioDecoder({
|
|
1479
1724
|
output: (audio) => {
|
|
@@ -1490,8 +1735,7 @@ async function measureAacEncoder(config) {
|
|
|
1490
1735
|
},
|
|
1491
1736
|
error: () => (failed = true),
|
|
1492
1737
|
});
|
|
1493
|
-
// Safari's
|
|
1494
|
-
// refuses (mediabunny rewrites it the same way in the file).
|
|
1738
|
+
// Safari's own decoder refuses its encoder's full `ES_Descriptor`.
|
|
1495
1739
|
const description = aacLcAudioSpecificConfig(config.sampleRate, config.numberOfChannels);
|
|
1496
1740
|
decoder.configure(description === undefined
|
|
1497
1741
|
? decoderConfig
|
|
@@ -1499,9 +1743,9 @@ async function measureAacEncoder(config) {
|
|
|
1499
1743
|
for (const chunk of chunks)
|
|
1500
1744
|
decoder.decode(chunk);
|
|
1501
1745
|
if ((await Promise.race([decoder.flush(), timedOut])) === "timeout")
|
|
1502
|
-
return { rate, delay: 0 };
|
|
1746
|
+
return { rate, delay: 0, outcome: "timed-out" };
|
|
1503
1747
|
if (failed)
|
|
1504
|
-
return { rate, delay: 0 };
|
|
1748
|
+
return { rate, delay: 0, outcome: "failed" };
|
|
1505
1749
|
const decoded = new Float32Array(planes.reduce((sum, plane) => sum + plane.length, 0));
|
|
1506
1750
|
let offset = 0;
|
|
1507
1751
|
for (const plane of planes) {
|
|
@@ -1512,10 +1756,11 @@ async function measureAacEncoder(config) {
|
|
|
1512
1756
|
return {
|
|
1513
1757
|
rate,
|
|
1514
1758
|
delay: lag === null ? 0 : Math.max(0, lag - AAC_FRAME_FRAMES),
|
|
1759
|
+
outcome: "output",
|
|
1515
1760
|
};
|
|
1516
1761
|
}
|
|
1517
1762
|
catch {
|
|
1518
|
-
return { delay: 0 };
|
|
1763
|
+
return { delay: 0, outcome: "failed" };
|
|
1519
1764
|
}
|
|
1520
1765
|
finally {
|
|
1521
1766
|
clearTimeout(timer);
|
|
@@ -1530,7 +1775,6 @@ async function measureAacEncoder(config) {
|
|
|
1530
1775
|
}
|
|
1531
1776
|
}
|
|
1532
1777
|
}
|
|
1533
|
-
/** The probe's burst: noise, low-passed so a lossy codec keeps most of it. */
|
|
1534
1778
|
function aacDelayProbe() {
|
|
1535
1779
|
const probe = new Float32Array(AAC_DELAY_PROBE_FRAMES);
|
|
1536
1780
|
let seed = 1;
|
|
@@ -1542,16 +1786,11 @@ function aacDelayProbe() {
|
|
|
1542
1786
|
}
|
|
1543
1787
|
return probe;
|
|
1544
1788
|
}
|
|
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
|
-
*/
|
|
1789
|
+
/** The lag where `decoded` best matches `probe`, or null when none matches closely enough. */
|
|
1550
1790
|
function strongestLag(decoded, probe) {
|
|
1551
1791
|
let probeEnergy = 0;
|
|
1552
1792
|
for (const value of probe)
|
|
1553
1793
|
probeEnergy += value * value;
|
|
1554
|
-
// Sum of squares of `decoded` before each index, for each window's energy.
|
|
1555
1794
|
const energy = new Float64Array(decoded.length + 1);
|
|
1556
1795
|
for (let index = 0; index < decoded.length; index += 1)
|
|
1557
1796
|
energy[index + 1] = energy[index] + decoded[index] * decoded[index];
|
|
@@ -1573,22 +1812,14 @@ function strongestLag(decoded, probe) {
|
|
|
1573
1812
|
}
|
|
1574
1813
|
return best;
|
|
1575
1814
|
}
|
|
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
|
-
*/
|
|
1815
|
+
/** Converts project-rate blocks to the encoder's rate with the engine's converter. */
|
|
1582
1816
|
class EncoderRateConverter {
|
|
1583
1817
|
targetRate;
|
|
1584
1818
|
#projectRate;
|
|
1585
1819
|
#resampler;
|
|
1586
|
-
/** The project samples from `#bufferStart` on that outputs still to be made may read. */
|
|
1587
1820
|
#buffer;
|
|
1588
1821
|
#bufferStart;
|
|
1589
|
-
/** The project sample the next block starts at. */
|
|
1590
1822
|
#received;
|
|
1591
|
-
/** The next output sample. */
|
|
1592
1823
|
#produced;
|
|
1593
1824
|
constructor(binding, first, targetRate) {
|
|
1594
1825
|
this.targetRate = targetRate;
|
|
@@ -1600,10 +1831,7 @@ class EncoderRateConverter {
|
|
|
1600
1831
|
this.#received = start;
|
|
1601
1832
|
this.#produced = this.#resampler.targetAtOrAfter(start);
|
|
1602
1833
|
}
|
|
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
|
-
*/
|
|
1834
|
+
/** Blocks must be contiguous at one rate and channel count. */
|
|
1607
1835
|
push(block) {
|
|
1608
1836
|
if (block.sampleRate !== this.#projectRate ||
|
|
1609
1837
|
block.channels.length !== this.#buffer.length)
|
|
@@ -1620,17 +1848,13 @@ class EncoderRateConverter {
|
|
|
1620
1848
|
this.#received += frames;
|
|
1621
1849
|
return this.#convert(this.#readyEnd());
|
|
1622
1850
|
}
|
|
1623
|
-
/** Ends the input: the outputs still to make, up to where the project's audio ends. */
|
|
1624
1851
|
finish() {
|
|
1625
1852
|
return this.#convert(this.#resampler.targetAtOrAfter(this.#received));
|
|
1626
1853
|
}
|
|
1627
|
-
/** Frees the engine's converter. */
|
|
1628
1854
|
free() {
|
|
1629
1855
|
this.#resampler.free?.();
|
|
1630
1856
|
}
|
|
1631
|
-
/** The end of the outputs whose samples have all arrived. */
|
|
1632
1857
|
#readyEnd() {
|
|
1633
|
-
// The output before `end` reads up to `sourceEnd(end)`, which grows with `end`.
|
|
1634
1858
|
let low = this.#produced;
|
|
1635
1859
|
let high = Math.max(low, this.#resampler.targetAtOrAfter(this.#received));
|
|
1636
1860
|
while (low < high) {
|
|
@@ -1656,11 +1880,7 @@ class EncoderRateConverter {
|
|
|
1656
1880
|
return { startSample: start, channels };
|
|
1657
1881
|
}
|
|
1658
1882
|
}
|
|
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
|
-
*/
|
|
1883
|
+
// No fast start and no append-only mode, so the muxer seeks back only to patch headers.
|
|
1664
1884
|
function outputFormat(container) {
|
|
1665
1885
|
switch (container) {
|
|
1666
1886
|
case "mp4":
|
|
@@ -1674,26 +1894,13 @@ function outputFormat(container) {
|
|
|
1674
1894
|
}
|
|
1675
1895
|
}
|
|
1676
1896
|
/**
|
|
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.
|
|
1897
|
+
* Optional mediabunny encoder/muxer implementing both public alpha2 sinks. When two runners share
|
|
1898
|
+
* the file, give each its own {@link MediabunnySink.videoTrack} or
|
|
1899
|
+
* {@link MediabunnySink.audioTrack}; the file is finalized once every configured track has ended,
|
|
1900
|
+
* and either `abort` discards it. The constructor throws `RangeError` for invalid options.
|
|
1690
1901
|
*/
|
|
1691
1902
|
export class MediabunnySink {
|
|
1692
1903
|
#target;
|
|
1693
|
-
/**
|
|
1694
|
-
* A stream destination, written through the muxer and committed or discarded by this sink alone:
|
|
1695
|
-
* see the constructor.
|
|
1696
|
-
*/
|
|
1697
1904
|
#file;
|
|
1698
1905
|
#discarded = false;
|
|
1699
1906
|
#output;
|
|
@@ -1702,17 +1909,20 @@ export class MediabunnySink {
|
|
|
1702
1909
|
#hasVideo;
|
|
1703
1910
|
#video;
|
|
1704
1911
|
#latencyMode;
|
|
1912
|
+
#latencyProbe;
|
|
1913
|
+
#acceleration;
|
|
1914
|
+
#addedAt = new Map();
|
|
1915
|
+
#encodeLatency = { totalMs: 0, maxMs: 0, count: 0 };
|
|
1916
|
+
#aacProbe;
|
|
1705
1917
|
#stallTimeoutMs;
|
|
1706
1918
|
#framesIn = 0;
|
|
1707
1919
|
#framesOut = 0;
|
|
1708
|
-
/**
|
|
1709
|
-
#
|
|
1920
|
+
/** Active time, so a frozen page does not count as a stall. */
|
|
1921
|
+
#progress;
|
|
1710
1922
|
#audio;
|
|
1711
1923
|
#audioCodec;
|
|
1712
1924
|
#audioBitrate;
|
|
1713
|
-
/** The AAC encoder's priming, in frames at the encoder's rate: see {@link aacEncoderDelay}. */
|
|
1714
1925
|
#audioDelay;
|
|
1715
|
-
/** Whether the AAC encoder was given its leading frame of silence: see `#encodeAudio`. */
|
|
1716
1926
|
#audioLeadWritten = false;
|
|
1717
1927
|
#audioRate;
|
|
1718
1928
|
#audioResampler;
|
|
@@ -1723,13 +1933,11 @@ export class MediabunnySink {
|
|
|
1723
1933
|
#finished = false;
|
|
1724
1934
|
#applied;
|
|
1725
1935
|
#codecString;
|
|
1726
|
-
/** Tracks whose runner finished, through {@link videoTrack} or {@link audioTrack}. */
|
|
1727
1936
|
#ended = new Set();
|
|
1728
1937
|
#videoTrack;
|
|
1729
1938
|
#audioTrack;
|
|
1730
1939
|
constructor(options) {
|
|
1731
|
-
//
|
|
1732
|
-
// mistake, not a failed export.
|
|
1940
|
+
// Validated before anything is opened, since an unsupported pair is a caller error.
|
|
1733
1941
|
resolveExportFormat({
|
|
1734
1942
|
container: options.container,
|
|
1735
1943
|
...(options.videoCodec === undefined
|
|
@@ -1745,8 +1953,7 @@ export class MediabunnySink {
|
|
|
1745
1953
|
destination.maxBytes <= 0)
|
|
1746
1954
|
throw new RangeError("memory destination maxBytes must be a positive safe integer");
|
|
1747
1955
|
this.#target = new BufferTarget();
|
|
1748
|
-
//
|
|
1749
|
-
// within what was budgeted for it.
|
|
1956
|
+
// Stopping at the reserved size keeps the output within its budget.
|
|
1750
1957
|
this.#target.onwrite = (_start, end) => {
|
|
1751
1958
|
this.#written = Math.max(this.#written, end);
|
|
1752
1959
|
if (end > destination.maxBytes)
|
|
@@ -1763,15 +1970,12 @@ export class MediabunnySink {
|
|
|
1763
1970
|
};
|
|
1764
1971
|
}
|
|
1765
1972
|
else {
|
|
1766
|
-
// mediabunny closes its stream on finish, failure and cancel alike, and
|
|
1767
|
-
//
|
|
1768
|
-
// discards it.
|
|
1973
|
+
// mediabunny closes its stream on finish, failure and cancel alike, and closing commits a
|
|
1974
|
+
// file, so the muxer gets its own stream and this sink commits or discards.
|
|
1769
1975
|
const file = destination.writable.getWriter();
|
|
1770
1976
|
this.#file = file;
|
|
1771
1977
|
const muxed = new WritableStream({
|
|
1772
1978
|
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
1979
|
await file.ready;
|
|
1776
1980
|
void file.write(chunk).catch(() => { });
|
|
1777
1981
|
},
|
|
@@ -1821,24 +2025,30 @@ export class MediabunnySink {
|
|
|
1821
2025
|
throw new RangeError("at least one output track is required");
|
|
1822
2026
|
this.#ready = this.#open(options);
|
|
1823
2027
|
}
|
|
1824
|
-
/** Adds the tracks once the video latency mode is known, and starts the file. */
|
|
1825
2028
|
async #open(options) {
|
|
1826
2029
|
const codec = options.videoCodec;
|
|
1827
2030
|
const rate = options.videoRateControl;
|
|
1828
2031
|
if (codec !== undefined && rate !== undefined) {
|
|
1829
|
-
|
|
2032
|
+
let latencyMode = options.videoLatencyMode;
|
|
2033
|
+
if (latencyMode === undefined) {
|
|
2034
|
+
this.#latencyProbe = await videoEncoderLatencyProbe(codec);
|
|
2035
|
+
latencyMode = this.#latencyProbe.mode;
|
|
2036
|
+
}
|
|
1830
2037
|
if (this.#output.state === "canceled")
|
|
1831
2038
|
return;
|
|
1832
2039
|
this.#latencyMode = latencyMode;
|
|
2040
|
+
const acceleration = options.videoHardwareAcceleration ?? "no-preference";
|
|
2041
|
+
this.#acceleration = acceleration;
|
|
2042
|
+
const codecString = options.videoCodecString ??
|
|
2043
|
+
(options.videoBitDepth === 10 ? tenBitCodecString(codec) : undefined);
|
|
1833
2044
|
this.#video = new VideoSampleSource({
|
|
1834
2045
|
codec,
|
|
1835
2046
|
quality: videoEncoderQuality(rate),
|
|
1836
2047
|
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.
|
|
2048
|
+
hardwareAcceleration: acceleration,
|
|
2049
|
+
...(options.videoAlpha === true ? { alpha: "keep" } : {}),
|
|
2050
|
+
...(codecString === undefined ? {} : { fullCodecString: codecString }),
|
|
2051
|
+
// mediabunny stops at the first supported candidate, so the last one reported runs.
|
|
1842
2052
|
onEncoderConfig: (config) => {
|
|
1843
2053
|
this.#codecString = config.codec;
|
|
1844
2054
|
const mode = config.bitrateMode;
|
|
@@ -1849,9 +2059,18 @@ export class MediabunnySink {
|
|
|
1849
2059
|
: { bitrate: config.bitrate }),
|
|
1850
2060
|
};
|
|
1851
2061
|
},
|
|
1852
|
-
onEncodedPacket: () => {
|
|
2062
|
+
onEncodedPacket: (packet) => {
|
|
1853
2063
|
this.#framesOut += 1;
|
|
1854
|
-
this.#
|
|
2064
|
+
this.#madeProgress();
|
|
2065
|
+
const key = Math.round(packet.timestamp * 1_000_000);
|
|
2066
|
+
const added = this.#addedAt.get(key);
|
|
2067
|
+
if (added !== undefined) {
|
|
2068
|
+
this.#addedAt.delete(key);
|
|
2069
|
+
const ms = performance.now() - added;
|
|
2070
|
+
this.#encodeLatency.totalMs += ms;
|
|
2071
|
+
this.#encodeLatency.maxMs = Math.max(this.#encodeLatency.maxMs, ms);
|
|
2072
|
+
this.#encodeLatency.count += 1;
|
|
2073
|
+
}
|
|
1855
2074
|
},
|
|
1856
2075
|
});
|
|
1857
2076
|
this.#output.addVideoTrack(this.#video, this.#frameDuration === undefined
|
|
@@ -1862,15 +2081,17 @@ export class MediabunnySink {
|
|
|
1862
2081
|
this.#output.addAudioTrack(this.#audio);
|
|
1863
2082
|
await this.#output.start();
|
|
1864
2083
|
}
|
|
1865
|
-
|
|
2084
|
+
#madeProgress() {
|
|
2085
|
+
(this.#progress ??= new ActiveStopwatch()).reset();
|
|
2086
|
+
}
|
|
1866
2087
|
#watched(work) {
|
|
2088
|
+
const progress = (this.#progress ??= new ActiveStopwatch());
|
|
1867
2089
|
return new Promise((resolve, reject) => {
|
|
1868
|
-
const
|
|
1869
|
-
const waited =
|
|
1870
|
-
if (this.#framesOut >= this.#framesIn ||
|
|
1871
|
-
waited < this.#stallTimeoutMs)
|
|
2090
|
+
const stop = progress.onTick(() => {
|
|
2091
|
+
const waited = progress.elapsed();
|
|
2092
|
+
if (this.#framesOut >= this.#framesIn || waited < this.#stallTimeoutMs)
|
|
1872
2093
|
return;
|
|
1873
|
-
|
|
2094
|
+
stop();
|
|
1874
2095
|
const held = this.#framesIn - this.#framesOut;
|
|
1875
2096
|
reject(Object.assign(new Error(`video encoder stalled: no output for ${Math.round(waited)} ms with ${held} frames queued`), {
|
|
1876
2097
|
code: "ENCODE_STALLED",
|
|
@@ -1881,18 +2102,33 @@ export class MediabunnySink {
|
|
|
1881
2102
|
resource: "unknown",
|
|
1882
2103
|
},
|
|
1883
2104
|
}));
|
|
1884
|
-
}
|
|
1885
|
-
void work.finally(
|
|
2105
|
+
});
|
|
2106
|
+
void work.finally(stop).then(resolve, reject);
|
|
1886
2107
|
});
|
|
1887
2108
|
}
|
|
1888
|
-
/**
|
|
2109
|
+
/** Undefined until the sink has started. */
|
|
1889
2110
|
get videoLatencyMode() {
|
|
1890
2111
|
return this.#latencyMode;
|
|
1891
2112
|
}
|
|
2113
|
+
/** Undefined until the sink has started, and when `videoLatencyMode` was given. */
|
|
2114
|
+
get videoLatencyProbe() {
|
|
2115
|
+
return this.#latencyProbe;
|
|
2116
|
+
}
|
|
2117
|
+
/** Undefined until the sink has started. */
|
|
2118
|
+
get videoEncoderAcceleration() {
|
|
2119
|
+
return this.#acceleration;
|
|
2120
|
+
}
|
|
2121
|
+
/** Hand-over to encoded packet, including queueing in the encoder. */
|
|
2122
|
+
get videoEncodeLatencyMs() {
|
|
2123
|
+
const { totalMs, maxMs, count } = this.#encodeLatency;
|
|
2124
|
+
return { mean: count === 0 ? 0 : totalMs / count, max: maxMs, count };
|
|
2125
|
+
}
|
|
2126
|
+
/** Undefined before the first AAC block. */
|
|
2127
|
+
get aacPrimingProbe() {
|
|
2128
|
+
return this.#aacProbe;
|
|
2129
|
+
}
|
|
1892
2130
|
/**
|
|
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.
|
|
2131
|
+
* The video track as its own sink, for runners sharing the file. Throws `RangeError` if absent.
|
|
1896
2132
|
*/
|
|
1897
2133
|
get videoTrack() {
|
|
1898
2134
|
if (!this.#hasVideo)
|
|
@@ -1904,10 +2140,7 @@ export class MediabunnySink {
|
|
|
1904
2140
|
};
|
|
1905
2141
|
return this.#videoTrack;
|
|
1906
2142
|
}
|
|
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
|
-
*/
|
|
2143
|
+
/** The audio track as its own sink; see {@link videoTrack}. Throws `RangeError` if absent. */
|
|
1911
2144
|
get audioTrack() {
|
|
1912
2145
|
if (this.#audio === undefined)
|
|
1913
2146
|
throw new RangeError("audio track is not configured");
|
|
@@ -1918,11 +2151,7 @@ export class MediabunnySink {
|
|
|
1918
2151
|
};
|
|
1919
2152
|
return this.#audioTrack;
|
|
1920
2153
|
}
|
|
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
|
-
*/
|
|
2154
|
+
/** The last configured track to end finishes the file; earlier ones resolve at once. */
|
|
1926
2155
|
async #endTrack(track) {
|
|
1927
2156
|
await this.#ready;
|
|
1928
2157
|
if (!this.#ended.has(track)) {
|
|
@@ -1935,25 +2164,17 @@ export class MediabunnySink {
|
|
|
1935
2164
|
(this.#audio === undefined || this.#ended.has("audio")))
|
|
1936
2165
|
await this.finish();
|
|
1937
2166
|
}
|
|
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
|
-
*/
|
|
2167
|
+
/** Undefined until the first frame has been written. */
|
|
1943
2168
|
get appliedVideoRateControl() {
|
|
1944
2169
|
return this.#applied;
|
|
1945
2170
|
}
|
|
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
|
-
*/
|
|
2171
|
+
/** Undefined until the first frame has been written. */
|
|
1950
2172
|
get videoCodecString() {
|
|
1951
2173
|
return this.#codecString;
|
|
1952
2174
|
}
|
|
1953
2175
|
/**
|
|
1954
|
-
* Encodes one frame at
|
|
1955
|
-
*
|
|
1956
|
-
* destination has passed `maxBytes`, with `ENCODE_STALLED` when the encoder stalls, or when no
|
|
2176
|
+
* Encodes one frame at `output.timeTicks` and always closes `output.frame`. Rejects with
|
|
2177
|
+
* `RESOURCE_LIMIT` past a memory destination's `maxBytes`, with `ENCODE_STALLED`, or when no
|
|
1957
2178
|
* video track is configured.
|
|
1958
2179
|
*/
|
|
1959
2180
|
async writeVideo(output) {
|
|
@@ -1974,14 +2195,14 @@ export class MediabunnySink {
|
|
|
1974
2195
|
? "the output was cancelled before its video track started"
|
|
1975
2196
|
: "video track is not configured");
|
|
1976
2197
|
}
|
|
1977
|
-
// Declaring the duration keeps sample durations uniform instead of inferred from float deltas.
|
|
1978
2198
|
const sample = new VideoSample(output.frame, {
|
|
1979
2199
|
timestamp: Number(output.timeTicks) / 120_000,
|
|
1980
2200
|
duration: this.#frameDuration,
|
|
1981
2201
|
});
|
|
1982
2202
|
if (this.#framesOut >= this.#framesIn)
|
|
1983
|
-
this.#
|
|
2203
|
+
this.#madeProgress();
|
|
1984
2204
|
this.#framesIn += 1;
|
|
2205
|
+
this.#addedAt.set(Math.round((Number(output.timeTicks) / 120_000) * 1_000_000), performance.now());
|
|
1985
2206
|
try {
|
|
1986
2207
|
await this.#watched(this.#video.add(sample));
|
|
1987
2208
|
}
|
|
@@ -1991,13 +2212,9 @@ export class MediabunnySink {
|
|
|
1991
2212
|
}
|
|
1992
2213
|
}
|
|
1993
2214
|
/**
|
|
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.
|
|
2215
|
+
* Encodes one block at `block.startSample`, from the output's zero. Blocks that need rate
|
|
2216
|
+
* conversion must be contiguous. Rejects with `RESOURCE_LIMIT`, when no audio track is
|
|
2217
|
+
* configured, for ragged channels, or with `RangeError` for a gap or a missing `audioResampler`.
|
|
2001
2218
|
*/
|
|
2002
2219
|
async writeAudio(block) {
|
|
2003
2220
|
await this.#ready;
|
|
@@ -2024,7 +2241,6 @@ export class MediabunnySink {
|
|
|
2024
2241
|
if (converted !== null)
|
|
2025
2242
|
await this.#encodeAudio(converted.channels, converted.startSample, this.#audioConverter.targetRate);
|
|
2026
2243
|
}
|
|
2027
|
-
/** Encodes the converted audio still held, once, before the audio track ends. */
|
|
2028
2244
|
async #flushAudio() {
|
|
2029
2245
|
const converter = this.#audioConverter;
|
|
2030
2246
|
if (converter === undefined || this.#audioFlushed)
|
|
@@ -2039,22 +2255,22 @@ export class MediabunnySink {
|
|
|
2039
2255
|
converter.free();
|
|
2040
2256
|
}
|
|
2041
2257
|
}
|
|
2042
|
-
/** Encodes planar `channels` starting at sample `startSample` of a `sampleRate` stream. */
|
|
2043
2258
|
async #encodeAudio(channels, startSample, sampleRate) {
|
|
2044
2259
|
if (this.#audio === undefined)
|
|
2045
2260
|
throw new Error("audio track is not configured");
|
|
2046
|
-
// AAC
|
|
2047
|
-
//
|
|
2048
|
-
// own in its header.
|
|
2261
|
+
// The muxer trims AAC priming placed before zero (edit list, negative Matroska block times);
|
|
2262
|
+
// Opus states its own in its header.
|
|
2049
2263
|
let delay = 0;
|
|
2050
2264
|
if (this.#audioCodec === "aac" && this.#audioBitrate !== undefined) {
|
|
2051
|
-
delay = await (this.#audioDelay ??=
|
|
2265
|
+
delay = await (this.#audioDelay ??= aacEncoderPrimingProbe({
|
|
2052
2266
|
sampleRate,
|
|
2053
2267
|
numberOfChannels: channels.length,
|
|
2054
2268
|
bitrate: this.#audioBitrate,
|
|
2269
|
+
}).then((probe) => {
|
|
2270
|
+
this.#aacProbe = probe;
|
|
2271
|
+
return probe.delay;
|
|
2055
2272
|
}));
|
|
2056
|
-
// Safari's encoder drops
|
|
2057
|
-
// zero with the priming, ahead of the audio.
|
|
2273
|
+
// Safari's encoder drops its first input frame, so lead with a frame of silence.
|
|
2058
2274
|
if (!this.#audioLeadWritten) {
|
|
2059
2275
|
this.#audioLeadWritten = true;
|
|
2060
2276
|
await this.#addAudio(channels.map(() => new Float32Array(AAC_FRAME_FRAMES)), startSample - AAC_FRAME_FRAMES - delay, sampleRate);
|
|
@@ -2062,7 +2278,6 @@ export class MediabunnySink {
|
|
|
2062
2278
|
}
|
|
2063
2279
|
await this.#addAudio(channels, startSample - delay, sampleRate);
|
|
2064
2280
|
}
|
|
2065
|
-
/** Gives the audio encoder planar `channels` at sample `startSample` of a `sampleRate` stream. */
|
|
2066
2281
|
async #addAudio(channels, startSample, sampleRate) {
|
|
2067
2282
|
if (this.#audio === undefined)
|
|
2068
2283
|
throw new Error("audio track is not configured");
|
|
@@ -2084,10 +2299,8 @@ export class MediabunnySink {
|
|
|
2084
2299
|
}
|
|
2085
2300
|
}
|
|
2086
2301
|
/**
|
|
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.
|
|
2302
|
+
* Finalizes the file and commits a stream destination; idempotent once resolved. Rejects with
|
|
2303
|
+
* `RESOURCE_LIMIT`, `ENCODE_STALLED`, or the muxer's or destination's error, discarding a stream.
|
|
2091
2304
|
*/
|
|
2092
2305
|
async finish() {
|
|
2093
2306
|
if (this.#finished)
|
|
@@ -2104,15 +2317,16 @@ export class MediabunnySink {
|
|
|
2104
2317
|
await this.#discard(error).catch(() => { });
|
|
2105
2318
|
throw error;
|
|
2106
2319
|
}
|
|
2320
|
+
finally {
|
|
2321
|
+
this.#progress?.dispose();
|
|
2322
|
+
}
|
|
2107
2323
|
this.#finished = true;
|
|
2108
2324
|
}
|
|
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
|
-
*/
|
|
2325
|
+
/** Discards the output unless already finished; rejects if the destination refuses. */
|
|
2113
2326
|
async abort(reason) {
|
|
2114
2327
|
if (this.#finished)
|
|
2115
2328
|
return;
|
|
2329
|
+
this.#progress?.dispose();
|
|
2116
2330
|
if (this.#audioConverter !== undefined && !this.#audioFlushed) {
|
|
2117
2331
|
this.#audioFlushed = true;
|
|
2118
2332
|
this.#audioConverter.free();
|
|
@@ -2125,17 +2339,13 @@ export class MediabunnySink {
|
|
|
2125
2339
|
await this.#discard(reason);
|
|
2126
2340
|
}
|
|
2127
2341
|
}
|
|
2128
|
-
/** Discards a stream destination once: writes still queued are dropped and nothing commits. */
|
|
2129
2342
|
async #discard(reason) {
|
|
2130
2343
|
if (this.#file === undefined || this.#discarded)
|
|
2131
2344
|
return;
|
|
2132
2345
|
this.#discarded = true;
|
|
2133
2346
|
await this.#file.abort(reason);
|
|
2134
2347
|
}
|
|
2135
|
-
/**
|
|
2136
|
-
* The finished output: its length for a stream, the bytes in memory. Null until {@link finish}
|
|
2137
|
-
* resolves.
|
|
2138
|
-
*/
|
|
2348
|
+
/** Null until {@link finish} resolves. */
|
|
2139
2349
|
get output() {
|
|
2140
2350
|
if (!this.#finished)
|
|
2141
2351
|
return null;
|
|
@@ -2145,24 +2355,18 @@ export class MediabunnySink {
|
|
|
2145
2355
|
}
|
|
2146
2356
|
return { kind: "stream", bytes: this.#written };
|
|
2147
2357
|
}
|
|
2148
|
-
/** Bytes muxed so far: the file's length as written. */
|
|
2149
2358
|
get bytesWritten() {
|
|
2150
2359
|
return this.#written;
|
|
2151
2360
|
}
|
|
2152
2361
|
}
|
|
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
|
-
*/
|
|
2362
|
+
/** Kept in an optional subpath so core APIs never load mediabunny. */
|
|
2157
2363
|
export class MediabunnyAdapterFactory {
|
|
2158
2364
|
#audioResampler;
|
|
2159
2365
|
constructor(audioResampler) {
|
|
2160
2366
|
this.#audioResampler = audioResampler;
|
|
2161
2367
|
}
|
|
2162
2368
|
/**
|
|
2163
|
-
*
|
|
2164
|
-
* `input` is a Blob, ArrayBuffer, or ArrayBuffer view, and as {@link MediabunnyVideoDecoder.open}
|
|
2165
|
-
* does.
|
|
2369
|
+
* Rejects with `TypeError` for an unsupported input, and as {@link MediabunnyVideoDecoder.open}.
|
|
2166
2370
|
*/
|
|
2167
2371
|
async openVideo(sourceId, input) {
|
|
2168
2372
|
if (!(input instanceof Blob) &&
|
|
@@ -2173,9 +2377,8 @@ export class MediabunnyAdapterFactory {
|
|
|
2173
2377
|
return MediabunnyVideoDecoder.open(sourceId, input);
|
|
2174
2378
|
}
|
|
2175
2379
|
/**
|
|
2176
|
-
*
|
|
2177
|
-
*
|
|
2178
|
-
* binding, and as {@link MediabunnyAudioDecoder.open} does.
|
|
2380
|
+
* Rejects with `TypeError` for an unsupported input or a missing resampler binding, and as
|
|
2381
|
+
* {@link MediabunnyAudioDecoder.open}.
|
|
2179
2382
|
*/
|
|
2180
2383
|
async openAudio(sourceId, input) {
|
|
2181
2384
|
if (!(input instanceof Blob) &&
|
|
@@ -2194,8 +2397,3 @@ function ticksToSampleCeil(ticks, sampleRate) {
|
|
|
2194
2397
|
const rate = BigInt(sampleRate);
|
|
2195
2398
|
return Number((ticks * rate + 119999n) / 120000n);
|
|
2196
2399
|
}
|
|
2197
|
-
function throwIfAborted(signal) {
|
|
2198
|
-
if (signal?.aborted === true) {
|
|
2199
|
-
throw signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
2200
|
-
}
|
|
2201
|
-
}
|