@mediabunny/truehd 0.0.0-stage → 0.1.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
package/src/decoder.ts ADDED
@@ -0,0 +1,104 @@
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
+ import {
10
+ CustomAudioDecoder,
11
+ AudioCodec,
12
+ AudioSample,
13
+ EncodedPacket,
14
+ registerDecoder,
15
+ } from 'mediabunny';
16
+ import { sendCommand, refWorker, unrefWorker } from './worker-client';
17
+ import { BATCH_SAMPLE_COUNT } from './shared';
18
+
19
+ class TrueHdDecoder extends CustomAudioDecoder {
20
+ private ctx = 0;
21
+ private samplesPerAccessUnit = 0;
22
+ private queuedPackets: EncodedPacket[] = [];
23
+
24
+ static override supports(codec: AudioCodec): boolean {
25
+ return codec === 'truehd';
26
+ }
27
+
28
+ async init() {
29
+ await refWorker();
30
+
31
+ const baseSampleRate = this.config.sampleRate % 44100 === 0 ? 44100 : 48000;
32
+ this.samplesPerAccessUnit = 40 * this.config.sampleRate / baseSampleRate;
33
+
34
+ const result = await sendCommand({
35
+ type: 'init-decoder',
36
+ data: {},
37
+ });
38
+ this.ctx = result.ctx;
39
+ }
40
+
41
+ async decode(packet: EncodedPacket) {
42
+ this.queuedPackets.push(packet);
43
+
44
+ if (this.samplesPerAccessUnit * this.queuedPackets.length >= BATCH_SAMPLE_COUNT) {
45
+ await this.decodeQueuedPackets();
46
+ }
47
+ }
48
+
49
+ async flush() {
50
+ if (this.queuedPackets.length > 0) {
51
+ await this.decodeQueuedPackets();
52
+ }
53
+
54
+ await sendCommand({ type: 'flush-decoder', data: { ctx: this.ctx } });
55
+ }
56
+
57
+ async close() {
58
+ // Close shouldn't throw
59
+ sendCommand({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => {});
60
+ await unrefWorker();
61
+ }
62
+
63
+ private async decodeQueuedPackets() {
64
+ const packets = this.queuedPackets.map(packet => ({
65
+ encodedData: packet.data.slice().buffer,
66
+ timestamp: Math.round(packet.timestamp * this.config.sampleRate),
67
+ }));
68
+ this.queuedPackets = [];
69
+
70
+ const result = await sendCommand({
71
+ type: 'decode',
72
+ data: { ctx: this.ctx, packets },
73
+ }, packets.map(x => x.encodedData));
74
+
75
+ for (const chunk of result.chunks) {
76
+ const sample = new AudioSample({
77
+ data: chunk.pcmData,
78
+ format: chunk.format,
79
+ numberOfChannels: chunk.channels,
80
+ sampleRate: chunk.sampleRate,
81
+ timestamp: chunk.pts / chunk.sampleRate,
82
+ });
83
+ this.onSample(sample);
84
+ }
85
+ }
86
+ }
87
+
88
+ let registered = false;
89
+
90
+ /**
91
+ * Registers a TrueHD audio decoder, which Mediabunny will then use automatically when applicable. Make sure to call
92
+ * this function before starting any decoding task.
93
+ *
94
+ * @group \@mediabunny/truehd
95
+ * @public
96
+ */
97
+ export const registerTrueHdDecoder = () => {
98
+ if (registered) {
99
+ return;
100
+ }
101
+ registered = true;
102
+
103
+ registerDecoder(TrueHdDecoder);
104
+ };
package/src/encoder.ts ADDED
@@ -0,0 +1,188 @@
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
+ import {
10
+ CustomAudioEncoder,
11
+ AudioCodec,
12
+ AudioSample,
13
+ EncodedPacket,
14
+ registerEncoder,
15
+ } from 'mediabunny';
16
+ import { sendCommand, refWorker, unrefWorker } from './worker-client';
17
+ import { assert, BATCH_SAMPLE_COUNT, EncodedChunk } from './shared';
18
+ import { TRUEHD_CHANNEL_COUNTS, TRUEHD_MAJOR_SYNC_WORD, TRUEHD_SAMPLE_RATES } from '../../../shared/truehd-misc';
19
+
20
+ class TrueHdEncoder extends CustomAudioEncoder {
21
+ private ctx = 0;
22
+ private encoderFrameSize = 0;
23
+ private sampleRate = 0;
24
+ private numberOfChannels = 0;
25
+ private chunkMetadata: EncodedAudioChunkMetadata = {};
26
+
27
+ // Accumulate interleaved f32 samples until we have a full batch
28
+ private pendingBuffer = new Float32Array(2 ** 16);
29
+ private pendingFrames = 0;
30
+ private nextSampleTimestampInSamples: number | null = null;
31
+
32
+ static override supports(codec: AudioCodec, config: AudioEncoderConfig): boolean {
33
+ return codec === 'truehd'
34
+ && TRUEHD_CHANNEL_COUNTS.includes(config.numberOfChannels)
35
+ && TRUEHD_SAMPLE_RATES.includes(config.sampleRate);
36
+ }
37
+
38
+ async init() {
39
+ await refWorker();
40
+
41
+ this.sampleRate = this.config.sampleRate;
42
+ this.numberOfChannels = this.config.numberOfChannels;
43
+
44
+ const result = await sendCommand({
45
+ type: 'init-encoder',
46
+ data: {
47
+ numberOfChannels: this.config.numberOfChannels,
48
+ sampleRate: this.config.sampleRate,
49
+ },
50
+ });
51
+
52
+ this.ctx = result.ctx;
53
+ this.encoderFrameSize = result.frameSize;
54
+
55
+ this.resetInternalState();
56
+ }
57
+
58
+ private resetInternalState() {
59
+ this.pendingFrames = 0;
60
+ this.nextSampleTimestampInSamples = null;
61
+
62
+ this.chunkMetadata = {
63
+ decoderConfig: {
64
+ codec: 'mlpa',
65
+ numberOfChannels: this.config.numberOfChannels,
66
+ sampleRate: this.config.sampleRate,
67
+ },
68
+ };
69
+ }
70
+
71
+ async encode(audioSample: AudioSample) {
72
+ if (this.nextSampleTimestampInSamples === null) {
73
+ this.nextSampleTimestampInSamples = Math.round(audioSample.timestamp * this.sampleRate);
74
+ }
75
+
76
+ const channels = this.numberOfChannels;
77
+ const incomingFrames = audioSample.numberOfFrames;
78
+
79
+ // Extract interleaved f32 data
80
+ const totalBytes = audioSample.allocationSize({ format: 'f32', planeIndex: 0 });
81
+ const audioBytes = new Uint8Array(totalBytes);
82
+ audioSample.copyTo(audioBytes, { format: 'f32', planeIndex: 0 });
83
+ const incomingData = new Float32Array(audioBytes.buffer);
84
+
85
+ const requiredSamples = (this.pendingFrames + incomingFrames) * channels;
86
+ if (requiredSamples > this.pendingBuffer.length) {
87
+ let newSize = this.pendingBuffer.length;
88
+ while (newSize < requiredSamples) {
89
+ newSize *= 2;
90
+ }
91
+ const newBuffer = new Float32Array(newSize);
92
+ newBuffer.set(this.pendingBuffer.subarray(0, this.pendingFrames * channels));
93
+ this.pendingBuffer = newBuffer;
94
+ }
95
+ this.pendingBuffer.set(incomingData, this.pendingFrames * channels);
96
+ this.pendingFrames += incomingFrames;
97
+
98
+ if (this.pendingFrames >= BATCH_SAMPLE_COUNT) {
99
+ // Only whole frames for now, since the encoder accepts a short frame only at the very end
100
+ await this.encodePendingFrames(this.pendingFrames - this.pendingFrames % this.encoderFrameSize);
101
+ }
102
+ }
103
+
104
+ async flush() {
105
+ if (this.pendingFrames > 0) {
106
+ await this.encodePendingFrames(this.pendingFrames);
107
+ }
108
+
109
+ const result = await sendCommand({ type: 'flush-encoder', data: { ctx: this.ctx } });
110
+ this.emitPackets(result.packets);
111
+
112
+ this.resetInternalState();
113
+ }
114
+
115
+ close() {
116
+ // Close shouldn't throw
117
+ sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {});
118
+ void unrefWorker();
119
+ }
120
+
121
+ private async encodePendingFrames(frameCount: number) {
122
+ assert(this.nextSampleTimestampInSamples !== null);
123
+
124
+ const channels = this.numberOfChannels;
125
+ const sampleCount = frameCount * channels;
126
+
127
+ const audioData = this.pendingBuffer.slice(0, sampleCount).buffer;
128
+
129
+ // Shift remaining using copyWithin
130
+ this.pendingFrames -= frameCount;
131
+ if (this.pendingFrames > 0) {
132
+ this.pendingBuffer.copyWithin(0, sampleCount, sampleCount + this.pendingFrames * channels);
133
+ }
134
+
135
+ const result = await sendCommand({
136
+ type: 'encode',
137
+ data: {
138
+ ctx: this.ctx,
139
+ audioData,
140
+ sampleCount: frameCount,
141
+ timestamp: this.nextSampleTimestampInSamples,
142
+ },
143
+ }, [audioData]);
144
+
145
+ this.nextSampleTimestampInSamples += frameCount;
146
+
147
+ this.emitPackets(result.packets);
148
+ }
149
+
150
+ private emitPackets(packets: EncodedChunk[]) {
151
+ for (const { encodedData, pts, duration } of packets) {
152
+ // Only access units carrying a major sync are restart points
153
+ const syncWord = encodedData.byteLength >= 8 ? new DataView(encodedData).getUint32(4) : null;
154
+
155
+ const packet = new EncodedPacket(
156
+ new Uint8Array(encodedData),
157
+ syncWord === TRUEHD_MAJOR_SYNC_WORD ? 'key' : 'delta',
158
+ pts / this.sampleRate,
159
+ duration / this.sampleRate,
160
+ );
161
+
162
+ this.onPacket(
163
+ packet,
164
+ this.chunkMetadata,
165
+ );
166
+
167
+ this.chunkMetadata = {};
168
+ }
169
+ }
170
+ }
171
+
172
+ let registered = false;
173
+
174
+ /**
175
+ * Registers a TrueHD audio encoder, which Mediabunny will then use automatically when applicable. Make sure to call
176
+ * this function before starting any encoding task.
177
+ *
178
+ * @group \@mediabunny/truehd
179
+ * @public
180
+ */
181
+ export const registerTrueHdEncoder = () => {
182
+ if (registered) {
183
+ return;
184
+ }
185
+ registered = true;
186
+
187
+ registerEncoder(TrueHdEncoder);
188
+ };
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
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
+ import { Logging } from 'mediabunny';
10
+
11
+ const TRUEHD_LOADED_SYMBOL = Symbol.for('@mediabunny/truehd loaded');
12
+ if ((globalThis as Record<symbol, unknown>)[TRUEHD_LOADED_SYMBOL]) {
13
+ Logging._error(
14
+ '[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
+ }
20
+ (globalThis as Record<symbol, unknown>)[TRUEHD_LOADED_SYMBOL] = true;
21
+
22
+ export { registerTrueHdDecoder } from './decoder';
23
+ export { registerTrueHdEncoder } from './encoder';
package/src/shared.ts ADDED
@@ -0,0 +1,115 @@
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
+ // TrueHD access units are tiny (40 samples at 48 kHz), so sending each one to the worker on its own would mean well
10
+ // over a thousand round trips per second. Instead, we make both sides batch until at least this many samples have
11
+ // been accumulated!
12
+ export const BATCH_SAMPLE_COUNT = 1024;
13
+
14
+ export type DecodedChunk = {
15
+ pcmData: ArrayBuffer;
16
+ format: AudioSampleFormat;
17
+ channels: number;
18
+ sampleRate: number;
19
+ sampleCount: number;
20
+ pts: number;
21
+ };
22
+
23
+ export type EncodedChunk = {
24
+ encodedData: ArrayBuffer;
25
+ pts: number;
26
+ duration: number;
27
+ };
28
+
29
+ export type WorkerCommand = {
30
+ type: 'init-decoder';
31
+ data: Record<string, never>;
32
+ } | {
33
+ type: 'decode';
34
+ data: {
35
+ ctx: number;
36
+ packets: {
37
+ encodedData: ArrayBuffer;
38
+ timestamp: number;
39
+ }[];
40
+ };
41
+ } | {
42
+ type: 'flush-decoder';
43
+ data: {
44
+ ctx: number;
45
+ };
46
+ } | {
47
+ type: 'close-decoder';
48
+ data: {
49
+ ctx: number;
50
+ };
51
+ } | {
52
+ type: 'init-encoder';
53
+ data: {
54
+ numberOfChannels: number;
55
+ sampleRate: number;
56
+ };
57
+ } | {
58
+ type: 'encode';
59
+ data: {
60
+ ctx: number;
61
+ audioData: ArrayBuffer;
62
+ sampleCount: number;
63
+ timestamp: number;
64
+ };
65
+ } | {
66
+ type: 'flush-encoder';
67
+ data: {
68
+ ctx: number;
69
+ };
70
+ } | {
71
+ type: 'close-encoder';
72
+ data: {
73
+ ctx: number;
74
+ };
75
+ };
76
+
77
+ export type WorkerResponseData = {
78
+ type: 'init-decoder';
79
+ ctx: number;
80
+ } | {
81
+ type: 'decode';
82
+ chunks: DecodedChunk[];
83
+ } | {
84
+ type: 'flush-decoder';
85
+ } | {
86
+ type: 'close-decoder';
87
+ } | {
88
+ type: 'init-encoder';
89
+ ctx: number;
90
+ frameSize: number;
91
+ } | {
92
+ type: 'encode';
93
+ packets: EncodedChunk[];
94
+ } | {
95
+ type: 'flush-encoder';
96
+ packets: EncodedChunk[];
97
+ } | {
98
+ type: 'close-encoder';
99
+ };
100
+
101
+ export type WorkerResponse = {
102
+ id: number;
103
+ } & ({
104
+ success: true;
105
+ data: WorkerResponseData;
106
+ } | {
107
+ success: false;
108
+ error: unknown;
109
+ });
110
+
111
+ export function assert(x: unknown): asserts x {
112
+ if (!x) {
113
+ throw new Error('Assertion failed.');
114
+ }
115
+ }
@@ -0,0 +1,132 @@
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
+ import { assert, type WorkerCommand, type WorkerResponse, type WorkerResponseData } from './shared';
10
+ // @ts-expect-error An esbuild plugin handles this, TypeScript doesn't need to understand
11
+ import createWorker from './codec.worker';
12
+
13
+ type ExtendedWorker = Worker & {
14
+ ref?: () => void;
15
+ unref?: () => void;
16
+ };
17
+
18
+ let workerPromise: Promise<ExtendedWorker> | null;
19
+ let workerError: Error | null = null;
20
+ let nextMessageId = 0;
21
+ const pendingMessages = new Map<number, {
22
+ resolve: (value: WorkerResponseData) => void;
23
+ reject: (reason?: unknown) => void;
24
+ }>();
25
+
26
+ let refCount = 0;
27
+ let keepAliveInterval: ReturnType<typeof setInterval> | null = null;
28
+
29
+ export const refWorker = async () => {
30
+ refCount++;
31
+ if (refCount === 1) {
32
+ keepAliveInterval = setInterval(() => {}, 2 ** 31 - 1);
33
+ const worker = await ensureWorker();
34
+ worker.ref?.();
35
+ }
36
+ };
37
+
38
+ export const unrefWorker = async () => {
39
+ refCount--;
40
+ if (refCount === 0) {
41
+ if (keepAliveInterval !== null) {
42
+ clearInterval(keepAliveInterval);
43
+ keepAliveInterval = null;
44
+ }
45
+
46
+ const worker = await workerPromise;
47
+ if (worker) {
48
+ if (workerError) {
49
+ // The failed worker was already terminated. With nobody using it anymore, the next ref can start fresh
50
+ workerPromise = null;
51
+ workerError = null;
52
+ } else if (worker.unref) {
53
+ worker.unref(); // If we don't do this, then the Node process never terminates by itself
54
+ // Keep the worker around tho
55
+ } else if (typeof window === 'undefined') {
56
+ // Non-browser environment without unref - terminate instead
57
+ worker.terminate();
58
+ workerPromise = null;
59
+ }
60
+ }
61
+ }
62
+ };
63
+
64
+ export const sendCommand = async <T extends string>(
65
+ command: WorkerCommand & { type: T },
66
+ transferables?: Transferable[],
67
+ ) => {
68
+ if (workerError) {
69
+ throw workerError;
70
+ }
71
+
72
+ const worker = await ensureWorker();
73
+
74
+ return new Promise<WorkerResponseData & { type: T }>((resolve, reject) => {
75
+ const id = nextMessageId++;
76
+ pendingMessages.set(id, {
77
+ resolve: resolve as (value: WorkerResponseData) => void,
78
+ reject,
79
+ });
80
+
81
+ if (transferables) {
82
+ worker.postMessage({ id, command }, transferables);
83
+ } else {
84
+ worker.postMessage({ id, command });
85
+ }
86
+ });
87
+ };
88
+
89
+ const ensureWorker = () => {
90
+ return workerPromise ??= (async () => {
91
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
92
+ const worker = (await createWorker()) as ExtendedWorker;
93
+ worker.unref?.(); // Start unreffed
94
+
95
+ const onMessage = (data: WorkerResponse) => {
96
+ const pending = pendingMessages.get(data.id);
97
+ assert(pending !== undefined);
98
+
99
+ pendingMessages.delete(data.id);
100
+ if (data.success) {
101
+ pending.resolve(data.data);
102
+ } else {
103
+ pending.reject(data.error);
104
+ }
105
+ };
106
+
107
+ // Treats any worker error (like CSP errors) as fatal, rejecting pending and future commands
108
+ const onError = (error: Error) => {
109
+ workerError = error;
110
+ for (const pending of pendingMessages.values()) {
111
+ pending.reject(error);
112
+ }
113
+ pendingMessages.clear();
114
+ worker.terminate();
115
+ };
116
+
117
+ if (worker.addEventListener) {
118
+ worker.addEventListener('message', event => onMessage(event.data as WorkerResponse));
119
+ worker.addEventListener('error', (event) => {
120
+ onError(new Error(event.message || 'TrueHD codec worker failed to load or crashed.'));
121
+ });
122
+ } else {
123
+ const nodeWorker = worker as unknown as {
124
+ on: (event: string, listener: (data: never) => void) => void;
125
+ };
126
+ nodeWorker.on('message', onMessage);
127
+ nodeWorker.on('error', onError);
128
+ }
129
+
130
+ return worker;
131
+ })();
132
+ };