@driftengine/media 3.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Drift Technologies
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ DriftEngine
2
+ Copyright 2026 Drift Technologies
3
+
4
+ This product includes software developed at Drift Technologies
5
+ (https://github.com/drftrun/driftengine).
6
+
7
+ Licensed under the Apache License, Version 2.0. Section 4(d) of that licence
8
+ requires this NOTICE to be reproduced in any derivative work you distribute,
9
+ in the source, the documentation, or a display generated by the work.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # @driftengine/media
2
+
3
+ Clip encoding and frame delivery. Carries the `mp4-muxer` dependency so core does not.
4
+
5
+ **Not size-gated, and this once claim it was.** There is no media fixture, so no floor moves when
6
+ this package does. The encoder it carries — `mp4-muxer`, behind a dynamic import — is only fetched by
7
+ a consumer that records a clip, which is the whole reason it lives here rather than in core.
8
+
9
+ A claim to be measured is worth less than no claim when nothing measures it: a reader trusts the
10
+ number precisely because the sentence says something checks it. `scripts/packages.test.mjs` now
11
+ refuses that sentence in a package with no fixture.
12
+
13
+ Part of [DriftEngine](../../README.md). See [`docs/ARCHITECTURE.md`](../../docs/ARCHITECTURE.md)
14
+ for how the packages divide, and why some features are compiled into core on demand instead.
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Encoding frames and samples into a file, on a timeline we choose.
3
+ *
4
+ * The difference between this and a screen recorder is one word: **timestamps.** A
5
+ * recorder stamps a frame with the instant it happened to arrive, so the file's cadence
6
+ * is a measurement of how busy the machine was. Here every frame is stamped with where
7
+ * it *belongs*, so a slow machine produces a slower export rather than a worse file.
8
+ *
9
+ * That was not a preference. Measured with `ffprobe` on real `MediaRecorder` output: a
10
+ * clip's audio led its picture by 51 ms in one run and 85 ms in the next, and the
11
+ * `outputLatency` it would have to be corrected by reported 0.048 then 0.024 — so the
12
+ * error is real, varies, and cannot be calibrated out from inside the page. Nothing
13
+ * below asks the browser what time it is.
14
+ *
15
+ * Game-agnostic on purpose (AGENTS.md): frames, samples, sizes and rates. A second game
16
+ * uses it unchanged.
17
+ */
18
+ import type { FrameOverlay } from '@driftengine/core';
19
+ import type { ClipEncodeRequest } from './clipSupport.ts';
20
+ /**
21
+ * Everything an encode needs: the frame, the rate, the bitrate, and the score's sample rate.
22
+ *
23
+ * The first four are `ClipEncodeRequest`, which is what `clipEncodingSupported` asks about, so a
24
+ * caller can hand the same object to the gate and to `open` and know they asked one question.
25
+ */
26
+ export interface ClipEncoderOptions extends ClipEncodeRequest {
27
+ /** Audio sample rate, so the score and the encoder agree. */
28
+ readonly sampleRate?: number;
29
+ }
30
+ /**
31
+ * Microseconds for frame `index` at `fps`.
32
+ *
33
+ * **The product is rounded, never a per-frame constant accumulated.** A 60 fps frame is
34
+ * 16666.67 µs and the nearest integer is 16667, which is a third of a microsecond long
35
+ * — trivial once and 20 ms over a minute, which is more than a frame of drift by the
36
+ * end of a clip. Deriving each stamp from its own index cannot drift at all.
37
+ */
38
+ export declare function frameTimestampUs(index: number, fps: number): number;
39
+ /** Which audio codec a file ended up carrying. See `ClipEncoder.audioCodec`. */
40
+ export type ClipAudioCodec = 'aac' | 'opus';
41
+ export declare class ClipEncoder {
42
+ private readonly options;
43
+ private video;
44
+ private audio;
45
+ private muxer;
46
+ private target;
47
+ /**
48
+ * The audio codec this file carries, once configured.
49
+ *
50
+ * Reported rather than kept private because the two answers are not equivalent to
51
+ * whoever receives the file, and the difference is invisible in it: an MP4 is an
52
+ * MP4 either way. AAC is what every share target ingests. Opus in MP4 is legal ISO
53
+ * and almost nothing consumer-side reads it — Android's MediaCodec decodes Opus
54
+ * only in Matroska, WebM and Ogg, so the TikTok app cannot open the file at all.
55
+ *
56
+ * A caller that knows which one it got can say so. One that cannot know hands over
57
+ * a file that fails somewhere it will never see, which is what happened.
58
+ */
59
+ private chosenAudio;
60
+ /** The first error either encoder reported. Read by the caller; never thrown at it. */
61
+ private failure;
62
+ private closed;
63
+ private constructor();
64
+ /**
65
+ * Configure the encoders and the container.
66
+ *
67
+ * The muxer is imported here rather than at the top of the module, so a player who
68
+ * never exports never downloads it. Rejects when the browser cannot encode, which the
69
+ * caller answers by recording instead.
70
+ */
71
+ static open(options: ClipEncoderOptions): Promise<ClipEncoder>;
72
+ /** The error that ended the encode, or null while it is going well. */
73
+ get error(): string | null;
74
+ /**
75
+ * The audio codec the file carries, or null before `open` has configured one.
76
+ *
77
+ * Survives `finish`, deliberately: the caller asks *after* it has a blob.
78
+ */
79
+ get audioCodec(): ClipAudioCodec | null;
80
+ private configure;
81
+ /**
82
+ * One frame, at its own index.
83
+ *
84
+ * Awaits while the encoder is behind, which is the only backpressure in the pipeline:
85
+ * a render loop with nothing to wait for will queue a thousand 1080x1920 frames and
86
+ * run the tab out of memory long before the encoder catches up.
87
+ */
88
+ addFrame(source: CanvasImageSource, index: number): Promise<void>;
89
+ /**
90
+ * The whole score, in order.
91
+ *
92
+ * Interleaved into the encoder's f32 planar layout by hand rather than handed the
93
+ * `AudioBuffer`, because `AudioData` takes a flat buffer and the two channels of an
94
+ * `AudioBuffer` are separate arrays.
95
+ */
96
+ addAudio(buffer: AudioBuffer): Promise<void>;
97
+ /** Flush both encoders, close the container, and hand back the file. */
98
+ finish(): Promise<Blob | null>;
99
+ /** Give everything back without producing a file. Safe at any point. */
100
+ abort(): void;
101
+ private release;
102
+ /** First failure wins: the later ones are consequences of it. */
103
+ private fail;
104
+ }
105
+ /** Re-exported so a caller can composite a mark without importing two modules. */
106
+ export type { FrameOverlay };
@@ -0,0 +1,283 @@
1
+ import { clipCodecs } from './clipSupport.js';
2
+ /**
3
+ * Microseconds for frame `index` at `fps`.
4
+ *
5
+ * **The product is rounded, never a per-frame constant accumulated.** A 60 fps frame is
6
+ * 16666.67 µs and the nearest integer is 16667, which is a third of a microsecond long
7
+ * — trivial once and 20 ms over a minute, which is more than a frame of drift by the
8
+ * end of a clip. Deriving each stamp from its own index cannot drift at all.
9
+ */
10
+ export function frameTimestampUs(index, fps) {
11
+ return Math.round((index * 1_000_000) / Math.max(fps, 1));
12
+ }
13
+ /** How many frames may be in flight before the loop waits for the encoder. */
14
+ const QUEUE_LIMIT = 8;
15
+ /** Samples per encoded audio chunk. A power of two the encoders all accept. */
16
+ const AUDIO_CHUNK = 1024;
17
+ /** Seconds between key frames. Two is what every platform's transcoder expects. */
18
+ const KEYFRAME_SEC = 2;
19
+ export class ClipEncoder {
20
+ options;
21
+ video = null;
22
+ audio = null;
23
+ muxer = null;
24
+ target = null;
25
+ /**
26
+ * The audio codec this file carries, once configured.
27
+ *
28
+ * Reported rather than kept private because the two answers are not equivalent to
29
+ * whoever receives the file, and the difference is invisible in it: an MP4 is an
30
+ * MP4 either way. AAC is what every share target ingests. Opus in MP4 is legal ISO
31
+ * and almost nothing consumer-side reads it — Android's MediaCodec decodes Opus
32
+ * only in Matroska, WebM and Ogg, so the TikTok app cannot open the file at all.
33
+ *
34
+ * A caller that knows which one it got can say so. One that cannot know hands over
35
+ * a file that fails somewhere it will never see, which is what happened.
36
+ */
37
+ chosenAudio = null;
38
+ /** The first error either encoder reported. Read by the caller; never thrown at it. */
39
+ failure = null;
40
+ closed = false;
41
+ constructor(options) {
42
+ this.options = options;
43
+ }
44
+ /**
45
+ * Configure the encoders and the container.
46
+ *
47
+ * The muxer is imported here rather than at the top of the module, so a player who
48
+ * never exports never downloads it. Rejects when the browser cannot encode, which the
49
+ * caller answers by recording instead.
50
+ */
51
+ static async open(options) {
52
+ const encoder = new ClipEncoder(options);
53
+ await encoder.configure();
54
+ return encoder;
55
+ }
56
+ /** The error that ended the encode, or null while it is going well. */
57
+ get error() {
58
+ return this.failure;
59
+ }
60
+ /**
61
+ * The audio codec the file carries, or null before `open` has configured one.
62
+ *
63
+ * Survives `finish`, deliberately: the caller asks *after* it has a blob.
64
+ */
65
+ get audioCodec() {
66
+ return this.chosenAudio;
67
+ }
68
+ async configure() {
69
+ const { width, height, fps, bitrate, sampleRate = 48000 } = this.options;
70
+ /*
71
+ * The audio codec is *asked about* before anything is built, and that omission is
72
+ * what broke the first export. AAC was configured without checking, and Chrome on
73
+ * Linux has no AAC encoder — so `configure` accepted it, the codec errored
74
+ * internally on the first frame, closed itself, and the loop's next call reported
75
+ * "Cannot call 'encode' on a closed codec". Which is a true statement about a
76
+ * consequence and says nothing about the cause.
77
+ *
78
+ * AAC first because it is what every share target ingests without transcoding.
79
+ * Opus second because Chrome muxes Opus into MP4 happily — its own `MediaRecorder`
80
+ * does, as `ffprobe` showed on a probe file earlier — so it is a real fallback
81
+ * rather than a theoretical one.
82
+ */
83
+ const audioCandidates = [
84
+ { codec: 'mp4a.40.2', muxed: 'aac' },
85
+ { codec: 'opus', muxed: 'opus' },
86
+ ];
87
+ let audioChoice = null;
88
+ for (const candidate of audioCandidates) {
89
+ const config = {
90
+ codec: candidate.codec,
91
+ sampleRate,
92
+ numberOfChannels: 2,
93
+ bitrate: 192_000,
94
+ };
95
+ try {
96
+ const support = await AudioEncoder.isConfigSupported(config);
97
+ if (support.supported === true) {
98
+ audioChoice = candidate;
99
+ break;
100
+ }
101
+ }
102
+ catch {
103
+ // A codec string this build does not recognise. Try the next.
104
+ }
105
+ }
106
+ if (audioChoice === null)
107
+ throw new Error('This browser cannot encode clip audio.');
108
+ this.chosenAudio = audioChoice.muxed;
109
+ const { Muxer, ArrayBufferTarget } = await import('mp4-muxer');
110
+ const target = new ArrayBufferTarget();
111
+ const muxer = new Muxer({
112
+ target,
113
+ fastStart: 'in-memory',
114
+ video: { codec: 'avc', width, height },
115
+ audio: { codec: audioChoice.muxed, numberOfChannels: 2, sampleRate },
116
+ });
117
+ this.target = target;
118
+ this.muxer = muxer;
119
+ /*
120
+ * The ladder is derived from the frame rather than written down here — see `clipCodecs`,
121
+ * which is also what `clipEncodingSupported` walks, so a gate and an export cannot answer
122
+ * differently.
123
+ *
124
+ * **Both rungs used to be level 4.0 spelled out as literals, and that is what stopped 4K.**
125
+ * A level is a promise about frame size: 4.0's 8192 macroblocks holds 1920x1080 and nothing
126
+ * larger, so `isConfigSupported` said no at 2560x1440 and above and `configure` below was
127
+ * never reached at those sizes. The comment that stood here reasoned that the level is a
128
+ * floor and that Chrome raises it, which is true of every file this produces and is not a
129
+ * thing that can happen to a config the browser refused first.
130
+ */
131
+ const video = new VideoEncoder({
132
+ output: (chunk, meta) => this.muxer?.addVideoChunk(chunk, meta),
133
+ error: (error) => this.fail(error.message),
134
+ });
135
+ const codecs = clipCodecs(width, height);
136
+ let configured = false;
137
+ for (const codec of codecs) {
138
+ const config = { codec, width, height, bitrate, framerate: fps };
139
+ const support = await VideoEncoder.isConfigSupported(config);
140
+ if (support.supported !== true)
141
+ continue;
142
+ video.configure(config);
143
+ configured = true;
144
+ break;
145
+ }
146
+ if (!configured)
147
+ throw new Error('This browser cannot encode video at that size.');
148
+ this.video = video;
149
+ const audio = new AudioEncoder({
150
+ output: (chunk, meta) => this.muxer?.addAudioChunk(chunk, meta),
151
+ error: (error) => this.fail(error.message),
152
+ });
153
+ audio.configure({
154
+ codec: audioChoice.codec,
155
+ sampleRate,
156
+ numberOfChannels: 2,
157
+ bitrate: 192_000,
158
+ });
159
+ this.audio = audio;
160
+ }
161
+ /**
162
+ * One frame, at its own index.
163
+ *
164
+ * Awaits while the encoder is behind, which is the only backpressure in the pipeline:
165
+ * a render loop with nothing to wait for will queue a thousand 1080x1920 frames and
166
+ * run the tab out of memory long before the encoder catches up.
167
+ */
168
+ async addFrame(source, index) {
169
+ const video = this.video;
170
+ // `state`, not just the failure flag: a codec that hit an internal error closes
171
+ // itself, and the error callback that would set the flag may not have run yet.
172
+ // Encoding into it then throws a message about the closure and hides the cause.
173
+ if (video === null || video.state !== 'configured' || this.failure !== null)
174
+ return;
175
+ const { fps } = this.options;
176
+ const frame = new VideoFrame(source, {
177
+ timestamp: frameTimestampUs(index, fps),
178
+ duration: Math.round(1_000_000 / fps),
179
+ });
180
+ try {
181
+ video.encode(frame, { keyFrame: index % Math.round(fps * KEYFRAME_SEC) === 0 });
182
+ }
183
+ finally {
184
+ // Closed whatever happened: a `VideoFrame` holds a GPU surface, and leaking one a
185
+ // frame is how a long export becomes an out-of-memory crash.
186
+ frame.close();
187
+ }
188
+ while (video.encodeQueueSize > QUEUE_LIMIT &&
189
+ this.failure === null &&
190
+ video.state === 'configured') {
191
+ await new Promise((resolve) => setTimeout(resolve, 1));
192
+ }
193
+ }
194
+ /**
195
+ * The whole score, in order.
196
+ *
197
+ * Interleaved into the encoder's f32 planar layout by hand rather than handed the
198
+ * `AudioBuffer`, because `AudioData` takes a flat buffer and the two channels of an
199
+ * `AudioBuffer` are separate arrays.
200
+ */
201
+ async addAudio(buffer) {
202
+ const audio = this.audio;
203
+ if (audio === null || audio.state !== 'configured' || this.failure !== null)
204
+ return;
205
+ const channels = Math.min(buffer.numberOfChannels, 2);
206
+ const left = buffer.getChannelData(0);
207
+ const right = channels > 1 ? buffer.getChannelData(1) : left;
208
+ const rate = buffer.sampleRate;
209
+ const scratch = new Float32Array(AUDIO_CHUNK * 2);
210
+ for (let start = 0; start < buffer.length; start += AUDIO_CHUNK) {
211
+ const count = Math.min(AUDIO_CHUNK, buffer.length - start);
212
+ // Planar: all of the left channel, then all of the right.
213
+ for (let i = 0; i < count; i++) {
214
+ scratch[i] = left[start + i] ?? 0;
215
+ scratch[count + i] = right[start + i] ?? 0;
216
+ }
217
+ const data = new AudioData({
218
+ format: 'f32-planar',
219
+ sampleRate: rate,
220
+ numberOfFrames: count,
221
+ numberOfChannels: 2,
222
+ timestamp: Math.round((start / rate) * 1_000_000),
223
+ data: scratch.subarray(0, count * 2),
224
+ });
225
+ if (audio.state !== 'configured' || this.failure !== null) {
226
+ data.close();
227
+ return;
228
+ }
229
+ try {
230
+ audio.encode(data);
231
+ }
232
+ finally {
233
+ data.close();
234
+ }
235
+ if (this.failure !== null)
236
+ return;
237
+ while (audio.encodeQueueSize > QUEUE_LIMIT * 4) {
238
+ await new Promise((resolve) => setTimeout(resolve, 1));
239
+ }
240
+ }
241
+ }
242
+ /** Flush both encoders, close the container, and hand back the file. */
243
+ async finish() {
244
+ if (this.closed)
245
+ return null;
246
+ this.closed = true;
247
+ try {
248
+ await this.video?.flush();
249
+ await this.audio?.flush();
250
+ this.muxer?.finalize();
251
+ }
252
+ catch (error) {
253
+ this.fail(error instanceof Error ? error.message : 'the encoder gave up');
254
+ }
255
+ this.release();
256
+ const buffer = this.target?.buffer ?? null;
257
+ if (this.failure !== null || buffer === null)
258
+ return null;
259
+ return new Blob([buffer], { type: 'video/mp4' });
260
+ }
261
+ /** Give everything back without producing a file. Safe at any point. */
262
+ abort() {
263
+ this.closed = true;
264
+ this.release();
265
+ }
266
+ release() {
267
+ try {
268
+ if (this.video?.state === 'configured')
269
+ this.video.close();
270
+ if (this.audio?.state === 'configured')
271
+ this.audio.close();
272
+ }
273
+ catch {
274
+ // Already closed. Nothing to do about an encoder we were discarding.
275
+ }
276
+ this.video = null;
277
+ this.audio = null;
278
+ }
279
+ /** First failure wins: the later ones are consequences of it. */
280
+ fail(message) {
281
+ this.failure ??= message;
282
+ }
283
+ }