@mediabunny/truehd 0.0.0-stage → 1.64.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.
Files changed (37) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +105 -2
  3. package/dist/bundles/mediabunny-truehd.js +404 -0
  4. package/dist/bundles/mediabunny-truehd.min.js +2234 -0
  5. package/dist/bundles/mediabunny-truehd.min.mjs +2233 -0
  6. package/dist/bundles/mediabunny-truehd.mjs +369 -0
  7. package/dist/mediabunny-truehd.d.ts +20 -0
  8. package/dist/modules/build/truehd.d.ts +3 -0
  9. package/dist/modules/build/truehd.d.ts.map +1 -0
  10. package/dist/modules/build/truehd.js +0 -0
  11. package/dist/modules/src/codec.worker.d.ts +9 -0
  12. package/dist/modules/src/codec.worker.d.ts.map +1 -0
  13. package/dist/modules/src/codec.worker.js +313 -0
  14. package/dist/modules/src/decoder.d.ts +16 -0
  15. package/dist/modules/src/decoder.d.ts.map +1 -0
  16. package/dist/modules/src/decoder.js +88 -0
  17. package/dist/modules/src/encoder.d.ts +16 -0
  18. package/dist/modules/src/encoder.d.ts.map +1 -0
  19. package/dist/modules/src/encoder.js +147 -0
  20. package/dist/modules/src/index.d.ts +10 -0
  21. package/dist/modules/src/index.d.ts.map +1 -0
  22. package/dist/modules/src/index.js +23 -0
  23. package/dist/modules/src/shared.d.ts +102 -0
  24. package/dist/modules/src/shared.d.ts.map +1 -0
  25. package/dist/modules/src/shared.js +20 -0
  26. package/dist/modules/src/worker-client.d.ts +16 -0
  27. package/dist/modules/src/worker-client.d.ts.map +1 -0
  28. package/dist/modules/src/worker-client.js +117 -0
  29. package/dist/modules/tsconfig.tsbuildinfo +1 -0
  30. package/package.json +57 -4
  31. package/src/bridge.c +337 -0
  32. package/src/codec.worker.ts +363 -0
  33. package/src/decoder.ts +104 -0
  34. package/src/encoder.ts +188 -0
  35. package/src/index.ts +23 -0
  36. package/src/shared.ts +115 -0
  37. package/src/worker-client.ts +132 -0
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Registers a TrueHD audio decoder, which Mediabunny will then use automatically when applicable. Make sure to call
3
+ * this function before starting any decoding task.
4
+ *
5
+ * @group \@mediabunny/truehd
6
+ * @public
7
+ */
8
+ export declare const registerTrueHdDecoder: () => void;
9
+
10
+ /**
11
+ * Registers a TrueHD audio encoder, which Mediabunny will then use automatically when applicable. Make sure to call
12
+ * this function before starting any encoding task.
13
+ *
14
+ * @group \@mediabunny/truehd
15
+ * @public
16
+ */
17
+ export declare const registerTrueHdEncoder: () => void;
18
+
19
+ export { }
20
+ export as namespace MediabunnyTrueHd;
@@ -0,0 +1,3 @@
1
+ export default Module;
2
+ declare function Module(moduleArg?: {}): Promise<{}>;
3
+ //# sourceMappingURL=truehd.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"truehd.d.ts","sourceRoot":"","sources":["../../../build/truehd.js"],"names":[],"mappings":";AAAA,qDACkB"}
Binary file
@@ -0,0 +1,9 @@
1
+ /*!
2
+ * Copyright (c) 2026-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+ export {};
9
+ //# sourceMappingURL=codec.worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec.worker.d.ts","sourceRoot":"","sources":["../../../src/codec.worker.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG"}
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) 2026-present, Vanilagy and contributors
4
+ *
5
+ * This Source Code Form is subject to the terms of the Mozilla Public
6
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
7
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
+ */
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ const truehd_1 = __importDefault(require("../build/truehd"));
14
+ let module;
15
+ let modulePromise = null;
16
+ let initDecoderFn;
17
+ let configureDecodePacket;
18
+ let sendDecodePacket;
19
+ let receiveDecodedFrame;
20
+ let getDecodedFormat;
21
+ let getDecodedPlanePtr;
22
+ let getDecodedChannels;
23
+ let getDecodedSampleRate;
24
+ let getDecodedSampleCount;
25
+ let getDecodedPts;
26
+ let flushDecoderFn;
27
+ let closeDecoderFn;
28
+ let initEncoderFn;
29
+ let getEncoderFrameSize;
30
+ let getEncodeInputPtr;
31
+ let sendEncodeFrame;
32
+ let sendEncodeFlush;
33
+ let receiveEncodedPacket;
34
+ let getEncodedData;
35
+ let getEncodedPts;
36
+ let getEncodedDuration;
37
+ let closeEncoderFn;
38
+ const ensureModule = async () => {
39
+ if (!module) {
40
+ if (modulePromise) {
41
+ // If we don't do this we can have a race condition
42
+ return modulePromise;
43
+ }
44
+ modulePromise = (0, truehd_1.default)();
45
+ module = await modulePromise;
46
+ modulePromise = null;
47
+ initDecoderFn = module.cwrap('init_decoder', 'number', []);
48
+ configureDecodePacket = module.cwrap('configure_decode_packet', 'number', ['number', 'number']);
49
+ sendDecodePacket = module.cwrap('send_decode_packet', 'number', ['number', 'number']);
50
+ receiveDecodedFrame = module.cwrap('receive_decoded_frame', 'number', ['number']);
51
+ getDecodedFormat = module.cwrap('get_decoded_format', 'number', ['number']);
52
+ getDecodedPlanePtr = module.cwrap('get_decoded_plane_ptr', 'number', ['number', 'number']);
53
+ getDecodedChannels = module.cwrap('get_decoded_channels', 'number', ['number']);
54
+ getDecodedSampleRate = module.cwrap('get_decoded_sample_rate', 'number', ['number']);
55
+ getDecodedSampleCount = module.cwrap('get_decoded_sample_count', 'number', ['number']);
56
+ getDecodedPts = module.cwrap('get_decoded_pts', 'number', ['number']);
57
+ flushDecoderFn = module.cwrap('flush_decoder', null, ['number']);
58
+ closeDecoderFn = module.cwrap('close_decoder', null, ['number']);
59
+ initEncoderFn = module.cwrap('init_encoder', 'number', ['number', 'number']);
60
+ getEncoderFrameSize = module.cwrap('get_encoder_frame_size', 'number', ['number']);
61
+ getEncodeInputPtr = module.cwrap('get_encode_input_ptr', 'number', ['number', 'number']);
62
+ sendEncodeFrame = module.cwrap('send_encode_frame', 'number', ['number', 'number', 'number', 'number']);
63
+ sendEncodeFlush = module.cwrap('send_encode_flush', 'number', ['number']);
64
+ receiveEncodedPacket = module.cwrap('receive_encoded_packet', 'number', ['number']);
65
+ getEncodedData = module.cwrap('get_encoded_data', 'number', ['number']);
66
+ getEncodedPts = module.cwrap('get_encoded_pts', 'number', ['number']);
67
+ getEncodedDuration = module.cwrap('get_encoded_duration', 'number', ['number']);
68
+ closeEncoderFn = module.cwrap('close_encoder', null, ['number']);
69
+ }
70
+ };
71
+ const initDecoder = async () => {
72
+ await ensureModule();
73
+ const ctx = initDecoderFn();
74
+ if (ctx === 0) {
75
+ throw new Error('Failed to initialize TrueHD decoder.');
76
+ }
77
+ return { ctx };
78
+ };
79
+ // Keys are AVSampleFormat enum values
80
+ const AV_FORMAT_MAP = {
81
+ 0: { format: 'u8', bytesPerSample: 1, planar: false },
82
+ 1: { format: 's16', bytesPerSample: 2, planar: false },
83
+ 2: { format: 's32', bytesPerSample: 4, planar: false },
84
+ 3: { format: 'f32', bytesPerSample: 4, planar: false },
85
+ 5: { format: 'u8-planar', bytesPerSample: 1, planar: true },
86
+ 6: { format: 's16-planar', bytesPerSample: 2, planar: true },
87
+ 7: { format: 's32-planar', bytesPerSample: 4, planar: true },
88
+ 8: { format: 'f32-planar', bytesPerSample: 4, planar: true },
89
+ };
90
+ const decode = (ctx, packets) => {
91
+ const chunks = [];
92
+ for (const packet of packets) {
93
+ const bytes = new Uint8Array(packet.encodedData);
94
+ const dataPtr = configureDecodePacket(ctx, bytes.length);
95
+ if (dataPtr === 0) {
96
+ throw new Error('Failed to configure decode packet.');
97
+ }
98
+ module.HEAPU8.set(bytes, dataPtr);
99
+ const sendRet = sendDecodePacket(ctx, BigInt(packet.timestamp));
100
+ if (sendRet < 0) {
101
+ throw new Error(`Decode failed with error code ${sendRet}.`);
102
+ }
103
+ while (true) {
104
+ const receiveRet = receiveDecodedFrame(ctx);
105
+ if (receiveRet < 0) {
106
+ throw new Error(`Decode failed with error code ${receiveRet}.`);
107
+ }
108
+ if (receiveRet === 0) {
109
+ break;
110
+ }
111
+ const avFormat = getDecodedFormat(ctx);
112
+ const info = AV_FORMAT_MAP[avFormat];
113
+ if (!info) {
114
+ throw new Error(`Unsupported AVSampleFormat: ${avFormat}`);
115
+ }
116
+ const channels = getDecodedChannels(ctx);
117
+ const sampleRate = getDecodedSampleRate(ctx);
118
+ const sampleCount = getDecodedSampleCount(ctx);
119
+ const pts = Number(getDecodedPts(ctx));
120
+ let pcmData;
121
+ if (info.planar) {
122
+ const planeSize = sampleCount * info.bytesPerSample;
123
+ const buffer = new Uint8Array(planeSize * channels);
124
+ for (let ch = 0; ch < channels; ch++) {
125
+ const ptr = getDecodedPlanePtr(ctx, ch);
126
+ buffer.set(module.HEAPU8.subarray(ptr, ptr + planeSize), ch * planeSize);
127
+ }
128
+ pcmData = buffer.buffer;
129
+ }
130
+ else {
131
+ const totalSize = sampleCount * channels * info.bytesPerSample;
132
+ const ptr = getDecodedPlanePtr(ctx, 0);
133
+ pcmData = module.HEAPU8.slice(ptr, ptr + totalSize).buffer;
134
+ }
135
+ chunks.push({
136
+ pcmData,
137
+ format: info.format,
138
+ channels,
139
+ sampleRate,
140
+ sampleCount,
141
+ pts,
142
+ });
143
+ }
144
+ }
145
+ return chunks;
146
+ };
147
+ const initEncoder = async (numberOfChannels, sampleRate) => {
148
+ await ensureModule();
149
+ const ctx = initEncoderFn(numberOfChannels, sampleRate);
150
+ if (ctx === 0) {
151
+ throw new Error('Failed to initialize TrueHD encoder.');
152
+ }
153
+ return { ctx, frameSize: getEncoderFrameSize(ctx) };
154
+ };
155
+ const encode = (ctx, audioData, sampleCount, timestamp) => {
156
+ const audioBytes = new Uint8Array(audioData);
157
+ const inputPtr = getEncodeInputPtr(ctx, audioBytes.length);
158
+ if (inputPtr === 0) {
159
+ throw new Error('Failed to allocate encoder input buffer.');
160
+ }
161
+ module.HEAPU8.set(audioBytes, inputPtr);
162
+ const frameSize = getEncoderFrameSize(ctx);
163
+ const packets = [];
164
+ for (let offset = 0; offset < sampleCount; offset += frameSize) {
165
+ const frameSampleCount = Math.min(frameSize, sampleCount - offset);
166
+ const ret = sendEncodeFrame(ctx, offset, frameSampleCount, BigInt(timestamp + offset));
167
+ if (ret < 0) {
168
+ throw new Error(`Encode failed with error code ${ret}.`);
169
+ }
170
+ receiveEncodedPackets(ctx, packets);
171
+ }
172
+ return packets;
173
+ };
174
+ const flushEncoder = (ctx) => {
175
+ const ret = sendEncodeFlush(ctx);
176
+ if (ret < 0) {
177
+ throw new Error(`Encoder flush failed with error code ${ret}.`);
178
+ }
179
+ // Unlike most encoders, this one holds back whole major frames, so draining it yields actual packets
180
+ const packets = [];
181
+ receiveEncodedPackets(ctx, packets);
182
+ return packets;
183
+ };
184
+ const receiveEncodedPackets = (ctx, packets) => {
185
+ while (true) {
186
+ const size = receiveEncodedPacket(ctx);
187
+ if (size < 0) {
188
+ throw new Error(`Encode failed with error code ${size}.`);
189
+ }
190
+ if (size === 0) {
191
+ break;
192
+ }
193
+ const ptr = getEncodedData(ctx);
194
+ packets.push({
195
+ encodedData: module.HEAPU8.slice(ptr, ptr + size).buffer,
196
+ pts: Number(getEncodedPts(ctx)),
197
+ duration: getEncodedDuration(ctx),
198
+ });
199
+ }
200
+ };
201
+ const onMessage = (data) => {
202
+ const { id, command } = data;
203
+ const handleCommand = async () => {
204
+ try {
205
+ let result;
206
+ const transferables = [];
207
+ switch (command.type) {
208
+ case 'init-decoder':
209
+ {
210
+ const { ctx } = await initDecoder();
211
+ result = { type: command.type, ctx };
212
+ }
213
+ ;
214
+ break;
215
+ case 'decode':
216
+ {
217
+ const chunks = decode(command.data.ctx, command.data.packets);
218
+ result = { type: command.type, chunks };
219
+ transferables.push(...chunks.map(x => x.pcmData));
220
+ }
221
+ ;
222
+ break;
223
+ case 'flush-decoder':
224
+ {
225
+ flushDecoderFn(command.data.ctx);
226
+ result = { type: command.type };
227
+ }
228
+ ;
229
+ break;
230
+ case 'close-decoder':
231
+ {
232
+ closeDecoderFn(command.data.ctx);
233
+ result = { type: command.type };
234
+ }
235
+ ;
236
+ break;
237
+ case 'init-encoder':
238
+ {
239
+ const { ctx, frameSize } = await initEncoder(command.data.numberOfChannels, command.data.sampleRate);
240
+ result = { type: command.type, ctx, frameSize };
241
+ }
242
+ ;
243
+ break;
244
+ case 'encode':
245
+ {
246
+ const packets = encode(command.data.ctx, command.data.audioData, command.data.sampleCount, command.data.timestamp);
247
+ result = { type: command.type, packets };
248
+ transferables.push(...packets.map(x => x.encodedData));
249
+ }
250
+ ;
251
+ break;
252
+ case 'flush-encoder':
253
+ {
254
+ const packets = flushEncoder(command.data.ctx);
255
+ result = { type: command.type, packets };
256
+ transferables.push(...packets.map(x => x.encodedData));
257
+ }
258
+ ;
259
+ break;
260
+ case 'close-encoder':
261
+ {
262
+ closeEncoderFn(command.data.ctx);
263
+ result = { type: command.type };
264
+ }
265
+ ;
266
+ break;
267
+ }
268
+ const response = {
269
+ id,
270
+ success: true,
271
+ data: result,
272
+ };
273
+ sendMessage(response, transferables);
274
+ }
275
+ catch (error) {
276
+ const response = {
277
+ id,
278
+ success: false,
279
+ error,
280
+ };
281
+ sendMessage(response);
282
+ }
283
+ };
284
+ void handleCommand();
285
+ };
286
+ const sendMessage = (data, transferables) => {
287
+ if (parentPort) {
288
+ parentPort.postMessage(data, transferables ?? []);
289
+ }
290
+ else {
291
+ self.postMessage(data, { transfer: transferables ?? [] });
292
+ }
293
+ };
294
+ let parentPort = null;
295
+ try {
296
+ // We're in Node.js (or a runtime that mimics it)
297
+ const workerModule = 'worker_threads';
298
+ // eslint-disable-next-line @stylistic/max-len
299
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-member-access
300
+ parentPort = require(workerModule).parentPort;
301
+ }
302
+ catch {
303
+ // Web worker (browser, Deno), no require available
304
+ }
305
+ if (parentPort) {
306
+ parentPort.on('message', onMessage);
307
+ }
308
+ else {
309
+ self.addEventListener('message', event => onMessage(event.data));
310
+ }
311
+ // Prevents the worker for being randomly closed by Firefox
312
+ // https://github.com/Vanilagy/mediabunny/issues/435
313
+ setInterval(() => { }, 1000);
@@ -0,0 +1,16 @@
1
+ /*!
2
+ * Copyright (c) 2026-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+ /**
9
+ * Registers a TrueHD audio decoder, which Mediabunny will then use automatically when applicable. Make sure to call
10
+ * this function before starting any decoding task.
11
+ *
12
+ * @group \@mediabunny/truehd
13
+ * @public
14
+ */
15
+ export declare const registerTrueHdDecoder: () => void;
16
+ //# sourceMappingURL=decoder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decoder.d.ts","sourceRoot":"","sources":["../../../src/decoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAmFH;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,YAOjC,CAAC"}
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) 2026-present, Vanilagy and contributors
4
+ *
5
+ * This Source Code Form is subject to the terms of the Mozilla Public
6
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
7
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.registerTrueHdDecoder = void 0;
11
+ const mediabunny_1 = require("mediabunny");
12
+ const worker_client_1 = require("./worker-client");
13
+ const shared_1 = require("./shared");
14
+ class TrueHdDecoder extends mediabunny_1.CustomAudioDecoder {
15
+ constructor() {
16
+ super(...arguments);
17
+ this.ctx = 0;
18
+ this.samplesPerAccessUnit = 0;
19
+ this.queuedPackets = [];
20
+ }
21
+ static supports(codec) {
22
+ return codec === 'truehd';
23
+ }
24
+ async init() {
25
+ await (0, worker_client_1.refWorker)();
26
+ const baseSampleRate = this.config.sampleRate % 44100 === 0 ? 44100 : 48000;
27
+ this.samplesPerAccessUnit = 40 * this.config.sampleRate / baseSampleRate;
28
+ const result = await (0, worker_client_1.sendCommand)({
29
+ type: 'init-decoder',
30
+ data: {},
31
+ });
32
+ this.ctx = result.ctx;
33
+ }
34
+ async decode(packet) {
35
+ this.queuedPackets.push(packet);
36
+ if (this.samplesPerAccessUnit * this.queuedPackets.length >= shared_1.BATCH_SAMPLE_COUNT) {
37
+ await this.decodeQueuedPackets();
38
+ }
39
+ }
40
+ async flush() {
41
+ if (this.queuedPackets.length > 0) {
42
+ await this.decodeQueuedPackets();
43
+ }
44
+ await (0, worker_client_1.sendCommand)({ type: 'flush-decoder', data: { ctx: this.ctx } });
45
+ }
46
+ async close() {
47
+ // Close shouldn't throw
48
+ (0, worker_client_1.sendCommand)({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => { });
49
+ await (0, worker_client_1.unrefWorker)();
50
+ }
51
+ async decodeQueuedPackets() {
52
+ const packets = this.queuedPackets.map(packet => ({
53
+ encodedData: packet.data.slice().buffer,
54
+ timestamp: Math.round(packet.timestamp * this.config.sampleRate),
55
+ }));
56
+ this.queuedPackets = [];
57
+ const result = await (0, worker_client_1.sendCommand)({
58
+ type: 'decode',
59
+ data: { ctx: this.ctx, packets },
60
+ }, packets.map(x => x.encodedData));
61
+ for (const chunk of result.chunks) {
62
+ const sample = new mediabunny_1.AudioSample({
63
+ data: chunk.pcmData,
64
+ format: chunk.format,
65
+ numberOfChannels: chunk.channels,
66
+ sampleRate: chunk.sampleRate,
67
+ timestamp: chunk.pts / chunk.sampleRate,
68
+ });
69
+ this.onSample(sample);
70
+ }
71
+ }
72
+ }
73
+ let registered = false;
74
+ /**
75
+ * Registers a TrueHD audio decoder, which Mediabunny will then use automatically when applicable. Make sure to call
76
+ * this function before starting any decoding task.
77
+ *
78
+ * @group \@mediabunny/truehd
79
+ * @public
80
+ */
81
+ const registerTrueHdDecoder = () => {
82
+ if (registered) {
83
+ return;
84
+ }
85
+ registered = true;
86
+ (0, mediabunny_1.registerDecoder)(TrueHdDecoder);
87
+ };
88
+ exports.registerTrueHdDecoder = registerTrueHdDecoder;
@@ -0,0 +1,16 @@
1
+ /*!
2
+ * Copyright (c) 2026-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+ /**
9
+ * Registers a TrueHD audio encoder, which Mediabunny will then use automatically when applicable. Make sure to call
10
+ * this function before starting any encoding task.
11
+ *
12
+ * @group \@mediabunny/truehd
13
+ * @public
14
+ */
15
+ export declare const registerTrueHdEncoder: () => void;
16
+ //# sourceMappingURL=encoder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encoder.d.ts","sourceRoot":"","sources":["../../../src/encoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAuKH;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,YAOjC,CAAC"}
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) 2026-present, Vanilagy and contributors
4
+ *
5
+ * This Source Code Form is subject to the terms of the Mozilla Public
6
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
7
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.registerTrueHdEncoder = void 0;
11
+ const mediabunny_1 = require("mediabunny");
12
+ const worker_client_1 = require("./worker-client");
13
+ const shared_1 = require("./shared");
14
+ const truehd_misc_1 = require("../../../shared/truehd-misc");
15
+ class TrueHdEncoder extends mediabunny_1.CustomAudioEncoder {
16
+ constructor() {
17
+ super(...arguments);
18
+ this.ctx = 0;
19
+ this.encoderFrameSize = 0;
20
+ this.sampleRate = 0;
21
+ this.numberOfChannels = 0;
22
+ this.chunkMetadata = {};
23
+ // Accumulate interleaved f32 samples until we have a full batch
24
+ this.pendingBuffer = new Float32Array(2 ** 16);
25
+ this.pendingFrames = 0;
26
+ this.nextSampleTimestampInSamples = null;
27
+ }
28
+ static supports(codec, config) {
29
+ return codec === 'truehd'
30
+ && truehd_misc_1.TRUEHD_CHANNEL_COUNTS.includes(config.numberOfChannels)
31
+ && truehd_misc_1.TRUEHD_SAMPLE_RATES.includes(config.sampleRate);
32
+ }
33
+ async init() {
34
+ await (0, worker_client_1.refWorker)();
35
+ this.sampleRate = this.config.sampleRate;
36
+ this.numberOfChannels = this.config.numberOfChannels;
37
+ const result = await (0, worker_client_1.sendCommand)({
38
+ type: 'init-encoder',
39
+ data: {
40
+ numberOfChannels: this.config.numberOfChannels,
41
+ sampleRate: this.config.sampleRate,
42
+ },
43
+ });
44
+ this.ctx = result.ctx;
45
+ this.encoderFrameSize = result.frameSize;
46
+ this.resetInternalState();
47
+ }
48
+ resetInternalState() {
49
+ this.pendingFrames = 0;
50
+ this.nextSampleTimestampInSamples = null;
51
+ this.chunkMetadata = {
52
+ decoderConfig: {
53
+ codec: 'mlpa',
54
+ numberOfChannels: this.config.numberOfChannels,
55
+ sampleRate: this.config.sampleRate,
56
+ },
57
+ };
58
+ }
59
+ async encode(audioSample) {
60
+ if (this.nextSampleTimestampInSamples === null) {
61
+ this.nextSampleTimestampInSamples = Math.round(audioSample.timestamp * this.sampleRate);
62
+ }
63
+ const channels = this.numberOfChannels;
64
+ const incomingFrames = audioSample.numberOfFrames;
65
+ // Extract interleaved f32 data
66
+ const totalBytes = audioSample.allocationSize({ format: 'f32', planeIndex: 0 });
67
+ const audioBytes = new Uint8Array(totalBytes);
68
+ audioSample.copyTo(audioBytes, { format: 'f32', planeIndex: 0 });
69
+ const incomingData = new Float32Array(audioBytes.buffer);
70
+ const requiredSamples = (this.pendingFrames + incomingFrames) * channels;
71
+ if (requiredSamples > this.pendingBuffer.length) {
72
+ let newSize = this.pendingBuffer.length;
73
+ while (newSize < requiredSamples) {
74
+ newSize *= 2;
75
+ }
76
+ const newBuffer = new Float32Array(newSize);
77
+ newBuffer.set(this.pendingBuffer.subarray(0, this.pendingFrames * channels));
78
+ this.pendingBuffer = newBuffer;
79
+ }
80
+ this.pendingBuffer.set(incomingData, this.pendingFrames * channels);
81
+ this.pendingFrames += incomingFrames;
82
+ if (this.pendingFrames >= shared_1.BATCH_SAMPLE_COUNT) {
83
+ // Only whole frames for now, since the encoder accepts a short frame only at the very end
84
+ await this.encodePendingFrames(this.pendingFrames - this.pendingFrames % this.encoderFrameSize);
85
+ }
86
+ }
87
+ async flush() {
88
+ if (this.pendingFrames > 0) {
89
+ await this.encodePendingFrames(this.pendingFrames);
90
+ }
91
+ const result = await (0, worker_client_1.sendCommand)({ type: 'flush-encoder', data: { ctx: this.ctx } });
92
+ this.emitPackets(result.packets);
93
+ this.resetInternalState();
94
+ }
95
+ close() {
96
+ // Close shouldn't throw
97
+ (0, worker_client_1.sendCommand)({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => { });
98
+ void (0, worker_client_1.unrefWorker)();
99
+ }
100
+ async encodePendingFrames(frameCount) {
101
+ (0, shared_1.assert)(this.nextSampleTimestampInSamples !== null);
102
+ const channels = this.numberOfChannels;
103
+ const sampleCount = frameCount * channels;
104
+ const audioData = this.pendingBuffer.slice(0, sampleCount).buffer;
105
+ // Shift remaining using copyWithin
106
+ this.pendingFrames -= frameCount;
107
+ if (this.pendingFrames > 0) {
108
+ this.pendingBuffer.copyWithin(0, sampleCount, sampleCount + this.pendingFrames * channels);
109
+ }
110
+ const result = await (0, worker_client_1.sendCommand)({
111
+ type: 'encode',
112
+ data: {
113
+ ctx: this.ctx,
114
+ audioData,
115
+ sampleCount: frameCount,
116
+ timestamp: this.nextSampleTimestampInSamples,
117
+ },
118
+ }, [audioData]);
119
+ this.nextSampleTimestampInSamples += frameCount;
120
+ this.emitPackets(result.packets);
121
+ }
122
+ emitPackets(packets) {
123
+ for (const { encodedData, pts, duration } of packets) {
124
+ // Only access units carrying a major sync are restart points
125
+ const syncWord = encodedData.byteLength >= 8 ? new DataView(encodedData).getUint32(4) : null;
126
+ const packet = new mediabunny_1.EncodedPacket(new Uint8Array(encodedData), syncWord === truehd_misc_1.TRUEHD_MAJOR_SYNC_WORD ? 'key' : 'delta', pts / this.sampleRate, duration / this.sampleRate);
127
+ this.onPacket(packet, this.chunkMetadata);
128
+ this.chunkMetadata = {};
129
+ }
130
+ }
131
+ }
132
+ let registered = false;
133
+ /**
134
+ * Registers a TrueHD audio encoder, which Mediabunny will then use automatically when applicable. Make sure to call
135
+ * this function before starting any encoding task.
136
+ *
137
+ * @group \@mediabunny/truehd
138
+ * @public
139
+ */
140
+ const registerTrueHdEncoder = () => {
141
+ if (registered) {
142
+ return;
143
+ }
144
+ registered = true;
145
+ (0, mediabunny_1.registerEncoder)(TrueHdEncoder);
146
+ };
147
+ exports.registerTrueHdEncoder = registerTrueHdEncoder;
@@ -0,0 +1,10 @@
1
+ /*!
2
+ * Copyright (c) 2026-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+ export { registerTrueHdDecoder } from './decoder';
9
+ export { registerTrueHdEncoder } from './encoder';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAeH,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) 2026-present, Vanilagy and contributors
4
+ *
5
+ * This Source Code Form is subject to the terms of the Mozilla Public
6
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
7
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.registerTrueHdEncoder = exports.registerTrueHdDecoder = void 0;
11
+ const mediabunny_1 = require("mediabunny");
12
+ const TRUEHD_LOADED_SYMBOL = Symbol.for('@mediabunny/truehd loaded');
13
+ if (globalThis[TRUEHD_LOADED_SYMBOL]) {
14
+ mediabunny_1.Logging._error('[WARNING]\n@mediabunny/truehd was loaded twice.'
15
+ + ' This will likely cause the encoder/decoder not to work correctly.'
16
+ + ' Check if multiple dependencies are importing different versions of @mediabunny/truehd,'
17
+ + ' or if something is being bundled incorrectly.');
18
+ }
19
+ globalThis[TRUEHD_LOADED_SYMBOL] = true;
20
+ var decoder_1 = require("./decoder");
21
+ Object.defineProperty(exports, "registerTrueHdDecoder", { enumerable: true, get: function () { return decoder_1.registerTrueHdDecoder; } });
22
+ var encoder_1 = require("./encoder");
23
+ Object.defineProperty(exports, "registerTrueHdEncoder", { enumerable: true, get: function () { return encoder_1.registerTrueHdEncoder; } });