@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/bridge.c ADDED
@@ -0,0 +1,337 @@
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
+ #include <emscripten.h>
10
+ #include <stdint.h>
11
+ #include <stdlib.h>
12
+ #include <string.h>
13
+ #include "libavcodec/avcodec.h"
14
+ #include "libavutil/opt.h"
15
+ #include "libavutil/channel_layout.h"
16
+
17
+ typedef struct {
18
+ AVCodecContext *codec_ctx;
19
+ AVPacket *packet;
20
+ AVFrame *frame;
21
+ } DecoderContext;
22
+
23
+ EMSCRIPTEN_KEEPALIVE
24
+ DecoderContext *init_decoder() {
25
+ const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_TRUEHD);
26
+ if (!codec) return NULL;
27
+
28
+ AVCodecContext *codec_ctx = avcodec_alloc_context3(codec);
29
+ if (!codec_ctx) return NULL;
30
+
31
+ if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
32
+ avcodec_free_context(&codec_ctx);
33
+ return NULL;
34
+ }
35
+
36
+ AVPacket *packet = av_packet_alloc();
37
+ if (!packet) {
38
+ avcodec_free_context(&codec_ctx);
39
+ return NULL;
40
+ }
41
+
42
+ AVFrame *frame = av_frame_alloc();
43
+ if (!frame) {
44
+ av_packet_free(&packet);
45
+ avcodec_free_context(&codec_ctx);
46
+ return NULL;
47
+ }
48
+
49
+ DecoderContext *ctx = malloc(sizeof(DecoderContext));
50
+ if (!ctx) {
51
+ av_frame_free(&frame);
52
+ av_packet_free(&packet);
53
+ avcodec_free_context(&codec_ctx);
54
+ return NULL;
55
+ }
56
+
57
+ ctx->codec_ctx = codec_ctx;
58
+ ctx->packet = packet;
59
+ ctx->frame = frame;
60
+
61
+ return ctx;
62
+ }
63
+
64
+ EMSCRIPTEN_KEEPALIVE
65
+ uint8_t *configure_decode_packet(DecoderContext *ctx, int size) {
66
+ if (av_new_packet(ctx->packet, size) < 0) {
67
+ return NULL;
68
+ }
69
+
70
+ return ctx->packet->data;
71
+ }
72
+
73
+ EMSCRIPTEN_KEEPALIVE
74
+ int send_decode_packet(DecoderContext *ctx, int64_t pts) {
75
+ ctx->packet->pts = pts;
76
+ int ret = avcodec_send_packet(ctx->codec_ctx, ctx->packet);
77
+ av_packet_unref(ctx->packet);
78
+
79
+ return ret;
80
+ }
81
+
82
+ /**
83
+ * Returns 1 if a frame was received, 0 if the decoder has nothing more to output for now, and a negative error code
84
+ * otherwise. TrueHD only produces output once it has seen a major sync, so a packet may well yield no frame at all.
85
+ */
86
+ EMSCRIPTEN_KEEPALIVE
87
+ int receive_decoded_frame(DecoderContext *ctx) {
88
+ int ret = avcodec_receive_frame(ctx->codec_ctx, ctx->frame);
89
+ if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return 0;
90
+ if (ret < 0) return ret;
91
+
92
+ return 1;
93
+ }
94
+
95
+ EMSCRIPTEN_KEEPALIVE
96
+ int get_decoded_format(DecoderContext *ctx) {
97
+ return ctx->frame->format;
98
+ }
99
+
100
+ EMSCRIPTEN_KEEPALIVE
101
+ uint8_t *get_decoded_plane_ptr(DecoderContext *ctx, int plane) {
102
+ return ctx->frame->data[plane];
103
+ }
104
+
105
+ EMSCRIPTEN_KEEPALIVE
106
+ int get_decoded_channels(DecoderContext *ctx) {
107
+ return ctx->frame->ch_layout.nb_channels;
108
+ }
109
+
110
+ EMSCRIPTEN_KEEPALIVE
111
+ int get_decoded_sample_rate(DecoderContext *ctx) {
112
+ return ctx->frame->sample_rate;
113
+ }
114
+
115
+ EMSCRIPTEN_KEEPALIVE
116
+ int get_decoded_sample_count(DecoderContext *ctx) {
117
+ return ctx->frame->nb_samples;
118
+ }
119
+
120
+ EMSCRIPTEN_KEEPALIVE
121
+ int64_t get_decoded_pts(DecoderContext *ctx) {
122
+ return ctx->frame->pts;
123
+ }
124
+
125
+ EMSCRIPTEN_KEEPALIVE
126
+ void flush_decoder(DecoderContext *ctx) {
127
+ avcodec_send_packet(ctx->codec_ctx, NULL);
128
+ while (avcodec_receive_frame(ctx->codec_ctx, ctx->frame) == 0) {}
129
+ avcodec_flush_buffers(ctx->codec_ctx);
130
+ }
131
+
132
+ EMSCRIPTEN_KEEPALIVE
133
+ void close_decoder(DecoderContext *ctx) {
134
+ av_frame_free(&ctx->frame);
135
+ av_packet_free(&ctx->packet);
136
+ avcodec_free_context(&ctx->codec_ctx);
137
+ free(ctx);
138
+ }
139
+
140
+ typedef struct {
141
+ AVCodecContext *codec_ctx;
142
+ AVPacket *packet;
143
+ AVFrame *frame;
144
+ float *input_buffer;
145
+ int input_buffer_size;
146
+ } EncoderContext;
147
+
148
+ // The TrueHD encoder only accepts a fixed set of layouts, so we pick one per channel count
149
+ static int set_truehd_channel_layout(AVChannelLayout *layout, int channels) {
150
+ switch (channels) {
151
+ case 1: {
152
+ AVChannelLayout mono = AV_CHANNEL_LAYOUT_MONO;
153
+ return av_channel_layout_copy(layout, &mono);
154
+ }
155
+ case 2: {
156
+ AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO;
157
+ return av_channel_layout_copy(layout, &stereo);
158
+ }
159
+ case 3: {
160
+ AVChannelLayout surround = AV_CHANNEL_LAYOUT_SURROUND;
161
+ return av_channel_layout_copy(layout, &surround);
162
+ }
163
+ case 4: {
164
+ AVChannelLayout four_zero = AV_CHANNEL_LAYOUT_4POINT0;
165
+ return av_channel_layout_copy(layout, &four_zero);
166
+ }
167
+ case 5: {
168
+ AVChannelLayout five_zero = AV_CHANNEL_LAYOUT_5POINT0;
169
+ return av_channel_layout_copy(layout, &five_zero);
170
+ }
171
+ case 6: {
172
+ AVChannelLayout five_one = AV_CHANNEL_LAYOUT_5POINT1;
173
+ return av_channel_layout_copy(layout, &five_one);
174
+ }
175
+ default:
176
+ return -1;
177
+ }
178
+ }
179
+
180
+ EMSCRIPTEN_KEEPALIVE
181
+ EncoderContext *init_encoder(int channels, int sample_rate) {
182
+ const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_TRUEHD);
183
+ if (!codec) return NULL;
184
+
185
+ AVCodecContext *codec_ctx = avcodec_alloc_context3(codec);
186
+ if (!codec_ctx) return NULL;
187
+
188
+ codec_ctx->sample_fmt = AV_SAMPLE_FMT_S32P;
189
+ codec_ctx->sample_rate = sample_rate;
190
+ codec_ctx->time_base = (AVRational){1, sample_rate};
191
+
192
+ // FFmpeg marks its TrueHD encoder experimental, so it refuses to open at the default compliance level
193
+ codec_ctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
194
+
195
+ if (set_truehd_channel_layout(&codec_ctx->ch_layout, channels) < 0) {
196
+ avcodec_free_context(&codec_ctx);
197
+ return NULL;
198
+ }
199
+
200
+ if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
201
+ avcodec_free_context(&codec_ctx);
202
+ return NULL;
203
+ }
204
+
205
+ AVPacket *packet = av_packet_alloc();
206
+ if (!packet) {
207
+ avcodec_free_context(&codec_ctx);
208
+ return NULL;
209
+ }
210
+
211
+ AVFrame *frame = av_frame_alloc();
212
+ if (!frame) {
213
+ av_packet_free(&packet);
214
+ avcodec_free_context(&codec_ctx);
215
+ return NULL;
216
+ }
217
+
218
+ // The frame has a fixed format, so let's create it now:
219
+ frame->format = AV_SAMPLE_FMT_S32P;
220
+ frame->sample_rate = sample_rate;
221
+ frame->nb_samples = codec_ctx->frame_size;
222
+ av_channel_layout_copy(&frame->ch_layout, &codec_ctx->ch_layout);
223
+
224
+ if (av_frame_get_buffer(frame, 0) < 0) {
225
+ av_frame_free(&frame);
226
+ av_packet_free(&packet);
227
+ avcodec_free_context(&codec_ctx);
228
+ return NULL;
229
+ }
230
+
231
+ EncoderContext *ctx = malloc(sizeof(EncoderContext));
232
+ if (!ctx) {
233
+ av_frame_free(&frame);
234
+ av_packet_free(&packet);
235
+ avcodec_free_context(&codec_ctx);
236
+ return NULL;
237
+ }
238
+
239
+ ctx->codec_ctx = codec_ctx;
240
+ ctx->packet = packet;
241
+ ctx->frame = frame;
242
+ ctx->input_buffer = NULL;
243
+ ctx->input_buffer_size = 0;
244
+
245
+ return ctx;
246
+ }
247
+
248
+ EMSCRIPTEN_KEEPALIVE
249
+ int get_encoder_frame_size(EncoderContext *ctx) {
250
+ return ctx->codec_ctx->frame_size;
251
+ }
252
+
253
+ EMSCRIPTEN_KEEPALIVE
254
+ float *get_encode_input_ptr(EncoderContext *ctx, int size) {
255
+ if (ctx->input_buffer_size < size) {
256
+ free(ctx->input_buffer);
257
+ ctx->input_buffer = malloc(size);
258
+ if (!ctx->input_buffer) {
259
+ ctx->input_buffer_size = 0;
260
+ return NULL;
261
+ }
262
+ ctx->input_buffer_size = size;
263
+ }
264
+ return ctx->input_buffer;
265
+ }
266
+
267
+ /**
268
+ * Sends the interleaved samples starting at the given sample offset of the input buffer to the encoder. Only the last
269
+ * frame may be shorter than the encoder's frame size.
270
+ */
271
+ EMSCRIPTEN_KEEPALIVE
272
+ int send_encode_frame(EncoderContext *ctx, int offset, int sample_count, int64_t pts) {
273
+ int channels = ctx->codec_ctx->ch_layout.nb_channels;
274
+
275
+ // The encoder may still hold a reference to the frame we sent last
276
+ int ret = av_frame_make_writable(ctx->frame);
277
+ if (ret < 0) return ret;
278
+
279
+ ctx->frame->nb_samples = sample_count;
280
+ ctx->frame->pts = pts;
281
+
282
+ // The encoder wants planar s32, so deinterleave while converting
283
+ float *input = ctx->input_buffer + offset * channels;
284
+ for (int ch = 0; ch < channels; ch++) {
285
+ int32_t *output = (int32_t *)ctx->frame->data[ch];
286
+ for (int i = 0; i < sample_count; i++) {
287
+ float sample = input[i * channels + ch];
288
+ if (sample > 1.0f) sample = 1.0f;
289
+ if (sample < -1.0f) sample = -1.0f;
290
+ output[i] = (int32_t)(sample * 2147483647.0f);
291
+ }
292
+ }
293
+
294
+ return avcodec_send_frame(ctx->codec_ctx, ctx->frame);
295
+ }
296
+
297
+ EMSCRIPTEN_KEEPALIVE
298
+ int send_encode_flush(EncoderContext *ctx) {
299
+ return avcodec_send_frame(ctx->codec_ctx, NULL);
300
+ }
301
+
302
+ /**
303
+ * Returns the size of the received packet, 0 if the encoder has nothing more to output for now, and a negative error
304
+ * code otherwise. The encoder buffers whole major frames internally, so packets come out in bursts.
305
+ */
306
+ EMSCRIPTEN_KEEPALIVE
307
+ int receive_encoded_packet(EncoderContext *ctx) {
308
+ int ret = avcodec_receive_packet(ctx->codec_ctx, ctx->packet);
309
+ if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return 0;
310
+ if (ret < 0) return ret;
311
+
312
+ return ctx->packet->size;
313
+ }
314
+
315
+ EMSCRIPTEN_KEEPALIVE
316
+ uint8_t *get_encoded_data(EncoderContext *ctx) {
317
+ return ctx->packet->data;
318
+ }
319
+
320
+ EMSCRIPTEN_KEEPALIVE
321
+ int64_t get_encoded_pts(EncoderContext *ctx) {
322
+ return ctx->packet->pts;
323
+ }
324
+
325
+ EMSCRIPTEN_KEEPALIVE
326
+ int get_encoded_duration(EncoderContext *ctx) {
327
+ return ctx->packet->duration;
328
+ }
329
+
330
+ EMSCRIPTEN_KEEPALIVE
331
+ void close_encoder(EncoderContext *ctx) {
332
+ free(ctx->input_buffer);
333
+ av_frame_free(&ctx->frame);
334
+ av_packet_free(&ctx->packet);
335
+ avcodec_free_context(&ctx->codec_ctx);
336
+ free(ctx);
337
+ }
@@ -0,0 +1,363 @@
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 createModule from '../build/truehd';
10
+ import type { DecodedChunk, EncodedChunk, WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
11
+
12
+ type ExtendedEmscriptenModule = EmscriptenModule & {
13
+ cwrap: typeof cwrap;
14
+ };
15
+
16
+ let module: ExtendedEmscriptenModule;
17
+ let modulePromise: Promise<ExtendedEmscriptenModule> | null = null;
18
+
19
+ let initDecoderFn: () => number;
20
+ let configureDecodePacket: (ctx: number, size: number) => number;
21
+ let sendDecodePacket: (ctx: number, pts: bigint) => number;
22
+ let receiveDecodedFrame: (ctx: number) => number;
23
+ let getDecodedFormat: (ctx: number) => number;
24
+ let getDecodedPlanePtr: (ctx: number, plane: number) => number;
25
+ let getDecodedChannels: (ctx: number) => number;
26
+ let getDecodedSampleRate: (ctx: number) => number;
27
+ let getDecodedSampleCount: (ctx: number) => number;
28
+ let getDecodedPts: (ctx: number) => bigint;
29
+ let flushDecoderFn: (ctx: number) => void;
30
+ let closeDecoderFn: (ctx: number) => void;
31
+
32
+ let initEncoderFn: (channels: number, sampleRate: number) => number;
33
+ let getEncoderFrameSize: (ctx: number) => number;
34
+ let getEncodeInputPtr: (ctx: number, size: number) => number;
35
+ let sendEncodeFrame: (ctx: number, offset: number, sampleCount: number, pts: bigint) => number;
36
+ let sendEncodeFlush: (ctx: number) => number;
37
+ let receiveEncodedPacket: (ctx: number) => number;
38
+ let getEncodedData: (ctx: number) => number;
39
+ let getEncodedPts: (ctx: number) => bigint;
40
+ let getEncodedDuration: (ctx: number) => number;
41
+ let closeEncoderFn: (ctx: number) => void;
42
+
43
+ const ensureModule = async () => {
44
+ if (!module) {
45
+ if (modulePromise) {
46
+ // If we don't do this we can have a race condition
47
+ return modulePromise;
48
+ }
49
+
50
+ modulePromise = createModule() as Promise<ExtendedEmscriptenModule>;
51
+ module = await modulePromise;
52
+ modulePromise = null;
53
+
54
+ initDecoderFn = module.cwrap('init_decoder', 'number', []);
55
+ configureDecodePacket = module.cwrap('configure_decode_packet', 'number', ['number', 'number']);
56
+ sendDecodePacket = module.cwrap(
57
+ 'send_decode_packet',
58
+ 'number',
59
+ ['number', 'number'],
60
+ ) as unknown as typeof sendDecodePacket;
61
+ receiveDecodedFrame = module.cwrap('receive_decoded_frame', 'number', ['number']);
62
+ getDecodedFormat = module.cwrap('get_decoded_format', 'number', ['number']);
63
+ getDecodedPlanePtr = module.cwrap('get_decoded_plane_ptr', 'number', ['number', 'number']);
64
+ getDecodedChannels = module.cwrap('get_decoded_channels', 'number', ['number']);
65
+ getDecodedSampleRate = module.cwrap('get_decoded_sample_rate', 'number', ['number']);
66
+ getDecodedSampleCount = module.cwrap('get_decoded_sample_count', 'number', ['number']);
67
+ getDecodedPts = module.cwrap('get_decoded_pts', 'number', ['number']) as unknown as typeof getDecodedPts;
68
+ flushDecoderFn = module.cwrap('flush_decoder', null, ['number']);
69
+ closeDecoderFn = module.cwrap('close_decoder', null, ['number']);
70
+
71
+ initEncoderFn = module.cwrap('init_encoder', 'number', ['number', 'number']);
72
+ getEncoderFrameSize = module.cwrap('get_encoder_frame_size', 'number', ['number']);
73
+ getEncodeInputPtr = module.cwrap('get_encode_input_ptr', 'number', ['number', 'number']);
74
+ sendEncodeFrame = module.cwrap(
75
+ 'send_encode_frame',
76
+ 'number',
77
+ ['number', 'number', 'number', 'number'],
78
+ ) as unknown as typeof sendEncodeFrame;
79
+ sendEncodeFlush = module.cwrap('send_encode_flush', 'number', ['number']);
80
+ receiveEncodedPacket = module.cwrap('receive_encoded_packet', 'number', ['number']);
81
+ getEncodedData = module.cwrap('get_encoded_data', 'number', ['number']);
82
+ getEncodedPts = module.cwrap('get_encoded_pts', 'number', ['number']) as unknown as typeof getEncodedPts;
83
+ getEncodedDuration = module.cwrap('get_encoded_duration', 'number', ['number']);
84
+ closeEncoderFn = module.cwrap('close_encoder', null, ['number']);
85
+ }
86
+ };
87
+
88
+ const initDecoder = async () => {
89
+ await ensureModule();
90
+
91
+ const ctx = initDecoderFn();
92
+ if (ctx === 0) {
93
+ throw new Error('Failed to initialize TrueHD decoder.');
94
+ }
95
+
96
+ return { ctx };
97
+ };
98
+
99
+ // Keys are AVSampleFormat enum values
100
+ const AV_FORMAT_MAP: Record<number, { format: AudioSampleFormat; bytesPerSample: number; planar: boolean }> = {
101
+ 0: { format: 'u8', bytesPerSample: 1, planar: false },
102
+ 1: { format: 's16', bytesPerSample: 2, planar: false },
103
+ 2: { format: 's32', bytesPerSample: 4, planar: false },
104
+ 3: { format: 'f32', bytesPerSample: 4, planar: false },
105
+ 5: { format: 'u8-planar', bytesPerSample: 1, planar: true },
106
+ 6: { format: 's16-planar', bytesPerSample: 2, planar: true },
107
+ 7: { format: 's32-planar', bytesPerSample: 4, planar: true },
108
+ 8: { format: 'f32-planar', bytesPerSample: 4, planar: true },
109
+ };
110
+
111
+ const decode = (ctx: number, packets: { encodedData: ArrayBuffer; timestamp: number }[]) => {
112
+ const chunks: DecodedChunk[] = [];
113
+
114
+ for (const packet of packets) {
115
+ const bytes = new Uint8Array(packet.encodedData);
116
+
117
+ const dataPtr = configureDecodePacket(ctx, bytes.length);
118
+ if (dataPtr === 0) {
119
+ throw new Error('Failed to configure decode packet.');
120
+ }
121
+
122
+ module.HEAPU8.set(bytes, dataPtr);
123
+
124
+ const sendRet = sendDecodePacket(ctx, BigInt(packet.timestamp));
125
+ if (sendRet < 0) {
126
+ throw new Error(`Decode failed with error code ${sendRet}.`);
127
+ }
128
+
129
+ while (true) {
130
+ const receiveRet = receiveDecodedFrame(ctx);
131
+ if (receiveRet < 0) {
132
+ throw new Error(`Decode failed with error code ${receiveRet}.`);
133
+ }
134
+ if (receiveRet === 0) {
135
+ break;
136
+ }
137
+
138
+ const avFormat = getDecodedFormat(ctx);
139
+ const info = AV_FORMAT_MAP[avFormat];
140
+ if (!info) {
141
+ throw new Error(`Unsupported AVSampleFormat: ${avFormat}`);
142
+ }
143
+
144
+ const channels = getDecodedChannels(ctx);
145
+ const sampleRate = getDecodedSampleRate(ctx);
146
+ const sampleCount = getDecodedSampleCount(ctx);
147
+ const pts = Number(getDecodedPts(ctx));
148
+
149
+ let pcmData: ArrayBuffer;
150
+ if (info.planar) {
151
+ const planeSize = sampleCount * info.bytesPerSample;
152
+ const buffer = new Uint8Array(planeSize * channels);
153
+
154
+ for (let ch = 0; ch < channels; ch++) {
155
+ const ptr = getDecodedPlanePtr(ctx, ch);
156
+ buffer.set(module.HEAPU8.subarray(ptr, ptr + planeSize), ch * planeSize);
157
+ }
158
+
159
+ pcmData = buffer.buffer;
160
+ } else {
161
+ const totalSize = sampleCount * channels * info.bytesPerSample;
162
+ const ptr = getDecodedPlanePtr(ctx, 0);
163
+ pcmData = module.HEAPU8.slice(ptr, ptr + totalSize).buffer;
164
+ }
165
+
166
+ chunks.push({
167
+ pcmData,
168
+ format: info.format,
169
+ channels,
170
+ sampleRate,
171
+ sampleCount,
172
+ pts,
173
+ });
174
+ }
175
+ }
176
+
177
+ return chunks;
178
+ };
179
+
180
+ const initEncoder = async (
181
+ numberOfChannels: number,
182
+ sampleRate: number,
183
+ ) => {
184
+ await ensureModule();
185
+
186
+ const ctx = initEncoderFn(numberOfChannels, sampleRate);
187
+ if (ctx === 0) {
188
+ throw new Error('Failed to initialize TrueHD encoder.');
189
+ }
190
+
191
+ return { ctx, frameSize: getEncoderFrameSize(ctx) };
192
+ };
193
+
194
+ const encode = (ctx: number, audioData: ArrayBuffer, sampleCount: number, timestamp: number) => {
195
+ const audioBytes = new Uint8Array(audioData);
196
+
197
+ const inputPtr = getEncodeInputPtr(ctx, audioBytes.length);
198
+ if (inputPtr === 0) {
199
+ throw new Error('Failed to allocate encoder input buffer.');
200
+ }
201
+ module.HEAPU8.set(audioBytes, inputPtr);
202
+
203
+ const frameSize = getEncoderFrameSize(ctx);
204
+ const packets: EncodedChunk[] = [];
205
+
206
+ for (let offset = 0; offset < sampleCount; offset += frameSize) {
207
+ const frameSampleCount = Math.min(frameSize, sampleCount - offset);
208
+
209
+ const ret = sendEncodeFrame(ctx, offset, frameSampleCount, BigInt(timestamp + offset));
210
+ if (ret < 0) {
211
+ throw new Error(`Encode failed with error code ${ret}.`);
212
+ }
213
+
214
+ receiveEncodedPackets(ctx, packets);
215
+ }
216
+
217
+ return packets;
218
+ };
219
+
220
+ const flushEncoder = (ctx: number) => {
221
+ const ret = sendEncodeFlush(ctx);
222
+ if (ret < 0) {
223
+ throw new Error(`Encoder flush failed with error code ${ret}.`);
224
+ }
225
+
226
+ // Unlike most encoders, this one holds back whole major frames, so draining it yields actual packets
227
+ const packets: EncodedChunk[] = [];
228
+ receiveEncodedPackets(ctx, packets);
229
+
230
+ return packets;
231
+ };
232
+
233
+ const receiveEncodedPackets = (ctx: number, packets: EncodedChunk[]) => {
234
+ while (true) {
235
+ const size = receiveEncodedPacket(ctx);
236
+ if (size < 0) {
237
+ throw new Error(`Encode failed with error code ${size}.`);
238
+ }
239
+ if (size === 0) {
240
+ break;
241
+ }
242
+
243
+ const ptr = getEncodedData(ctx);
244
+ packets.push({
245
+ encodedData: module.HEAPU8.slice(ptr, ptr + size).buffer,
246
+ pts: Number(getEncodedPts(ctx)),
247
+ duration: getEncodedDuration(ctx),
248
+ });
249
+ }
250
+ };
251
+
252
+ const onMessage = (data: { id: number; command: WorkerCommand }) => {
253
+ const { id, command } = data;
254
+
255
+ const handleCommand = async (): Promise<void> => {
256
+ try {
257
+ let result: WorkerResponseData;
258
+ const transferables: Transferable[] = [];
259
+
260
+ switch (command.type) {
261
+ case 'init-decoder': {
262
+ const { ctx } = await initDecoder();
263
+ result = { type: command.type, ctx };
264
+ }; break;
265
+
266
+ case 'decode': {
267
+ const chunks = decode(command.data.ctx, command.data.packets);
268
+ result = { type: command.type, chunks };
269
+ transferables.push(...chunks.map(x => x.pcmData));
270
+ }; break;
271
+
272
+ case 'flush-decoder': {
273
+ flushDecoderFn(command.data.ctx);
274
+ result = { type: command.type };
275
+ }; break;
276
+
277
+ case 'close-decoder': {
278
+ closeDecoderFn(command.data.ctx);
279
+ result = { type: command.type };
280
+ }; break;
281
+
282
+ case 'init-encoder': {
283
+ const { ctx, frameSize } = await initEncoder(
284
+ command.data.numberOfChannels,
285
+ command.data.sampleRate,
286
+ );
287
+ result = { type: command.type, ctx, frameSize };
288
+ }; break;
289
+
290
+ case 'encode': {
291
+ const packets = encode(
292
+ command.data.ctx,
293
+ command.data.audioData,
294
+ command.data.sampleCount,
295
+ command.data.timestamp,
296
+ );
297
+ result = { type: command.type, packets };
298
+ transferables.push(...packets.map(x => x.encodedData));
299
+ }; break;
300
+
301
+ case 'flush-encoder': {
302
+ const packets = flushEncoder(command.data.ctx);
303
+ result = { type: command.type, packets };
304
+ transferables.push(...packets.map(x => x.encodedData));
305
+ }; break;
306
+
307
+ case 'close-encoder': {
308
+ closeEncoderFn(command.data.ctx);
309
+ result = { type: command.type };
310
+ }; break;
311
+ }
312
+
313
+ const response: WorkerResponse = {
314
+ id,
315
+ success: true,
316
+ data: result,
317
+ };
318
+ sendMessage(response, transferables);
319
+ } catch (error: unknown) {
320
+ const response: WorkerResponse = {
321
+ id,
322
+ success: false,
323
+ error,
324
+ };
325
+ sendMessage(response);
326
+ }
327
+ };
328
+
329
+ void handleCommand();
330
+ };
331
+
332
+ const sendMessage = (data: unknown, transferables?: Transferable[]) => {
333
+ if (parentPort) {
334
+ parentPort.postMessage(data, transferables ?? []);
335
+ } else {
336
+ self.postMessage(data, { transfer: transferables ?? [] });
337
+ }
338
+ };
339
+
340
+ let parentPort: {
341
+ postMessage: (data: unknown, transferables?: Transferable[]) => void;
342
+ on: (event: string, listener: (data: never) => void) => void;
343
+ } | null = null;
344
+
345
+ try {
346
+ // We're in Node.js (or a runtime that mimics it)
347
+ const workerModule = 'worker_threads';
348
+ // eslint-disable-next-line @stylistic/max-len
349
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-member-access
350
+ parentPort = require(workerModule).parentPort;
351
+ } catch {
352
+ // Web worker (browser, Deno), no require available
353
+ }
354
+
355
+ if (parentPort) {
356
+ parentPort.on('message', onMessage);
357
+ } else {
358
+ self.addEventListener('message', event => onMessage(event.data as { id: number; command: WorkerCommand }));
359
+ }
360
+
361
+ // Prevents the worker for being randomly closed by Firefox
362
+ // https://github.com/Vanilagy/mediabunny/issues/435
363
+ setInterval(() => {}, 1000);