@mediabunny/truehd 1.65.2 → 1.66.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/src/bridge.c CHANGED
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  #include <emscripten.h>
10
+ #include <math.h>
10
11
  #include <stdint.h>
11
12
  #include <stdlib.h>
12
13
  #include <string.h>
@@ -284,10 +285,9 @@ int send_encode_frame(EncoderContext *ctx, int offset, int sample_count, int64_t
284
285
  for (int ch = 0; ch < channels; ch++) {
285
286
  int32_t *output = (int32_t *)ctx->frame->data[ch];
286
287
  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);
288
+ // The encoder only keeps the top 24 bits, so round to those, like Mediabunny's own sample conversions do
289
+ double sample = floor(8388608.0 * input[i * channels + ch] + 0.5);
290
+ output[i] = 256 * (int32_t)fmin(fmax(sample, -8388608.0), 8388607.0);
291
291
  }
292
292
  }
293
293
 
@@ -108,6 +108,8 @@ const AV_FORMAT_MAP: Record<number, { format: AudioSampleFormat; bytesPerSample:
108
108
  8: { format: 'f32-planar', bytesPerSample: 4, planar: true },
109
109
  };
110
110
 
111
+ const AV_NOPTS_VALUE = -(BigInt(2) ** BigInt(63));
112
+
111
113
  const decode = (ctx: number, packets: { encodedData: ArrayBuffer; timestamp: number }[]) => {
112
114
  const chunks: DecodedChunk[] = [];
113
115
 
@@ -144,7 +146,7 @@ const decode = (ctx: number, packets: { encodedData: ArrayBuffer; timestamp: num
144
146
  const channels = getDecodedChannels(ctx);
145
147
  const sampleRate = getDecodedSampleRate(ctx);
146
148
  const sampleCount = getDecodedSampleCount(ctx);
147
- const pts = Number(getDecodedPts(ctx));
149
+ const pts = getDecodedPts(ctx);
148
150
 
149
151
  let pcmData: ArrayBuffer;
150
152
  if (info.planar) {
@@ -169,7 +171,7 @@ const decode = (ctx: number, packets: { encodedData: ArrayBuffer; timestamp: num
169
171
  channels,
170
172
  sampleRate,
171
173
  sampleCount,
172
- pts,
174
+ pts: pts === AV_NOPTS_VALUE ? null : Number(pts),
173
175
  });
174
176
  }
175
177
  }
package/src/decoder.ts CHANGED
@@ -14,12 +14,14 @@ import {
14
14
  registerDecoder,
15
15
  } from 'mediabunny';
16
16
  import { sendCommand, refWorker, unrefWorker } from './worker-client';
17
- import { BATCH_SAMPLE_COUNT } from './shared';
17
+ import { assert, BATCH_SAMPLE_COUNT } from './shared';
18
18
 
19
19
  class TrueHdDecoder extends CustomAudioDecoder {
20
- private ctx = 0;
20
+ private ctx: number | null = null;
21
21
  private samplesPerAccessUnit = 0;
22
22
  private queuedPackets: EncodedPacket[] = [];
23
+ private nextTimestamp: number | null = null;
24
+ private inFlightDecode: Promise<void> | null = null;
23
25
 
24
26
  static override supports(codec: AudioCodec): boolean {
25
27
  return codec === 'truehd';
@@ -47,41 +49,68 @@ class TrueHdDecoder extends CustomAudioDecoder {
47
49
  }
48
50
 
49
51
  async flush() {
52
+ assert(this.ctx !== null);
53
+
50
54
  if (this.queuedPackets.length > 0) {
51
55
  await this.decodeQueuedPackets();
52
56
  }
53
57
 
58
+ await this.inFlightDecode;
59
+ this.inFlightDecode = null;
60
+
54
61
  await sendCommand({ type: 'flush-decoder', data: { ctx: this.ctx } });
55
62
  }
56
63
 
57
64
  async close() {
58
65
  // Close shouldn't throw
59
- sendCommand({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => {});
66
+ if (this.ctx !== null) {
67
+ sendCommand({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => {});
68
+ }
69
+
60
70
  await unrefWorker();
61
71
  }
62
72
 
63
73
  private async decodeQueuedPackets() {
74
+ assert(this.ctx !== null);
75
+
64
76
  const packets = this.queuedPackets.map(packet => ({
65
77
  encodedData: packet.data.slice().buffer,
66
78
  timestamp: Math.round(packet.timestamp * this.config.sampleRate),
67
79
  }));
68
80
  this.queuedPackets = [];
69
81
 
70
- const result = await sendCommand({
82
+ const decode = sendCommand({
71
83
  type: 'decode',
72
84
  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
+ }, packets.map(x => x.encodedData)).then((result) => {
86
+ for (const chunk of result.chunks) {
87
+ // The access units following the first one of a packet come without a timestamp, but they simply pick
88
+ // up where the previous one left off
89
+ let timestamp: number;
90
+ if (chunk.pts !== null) {
91
+ timestamp = chunk.pts / this.config.sampleRate;
92
+ } else {
93
+ assert(this.nextTimestamp !== null);
94
+ timestamp = this.nextTimestamp;
95
+ }
96
+
97
+ const sample = new AudioSample({
98
+ data: chunk.pcmData,
99
+ format: chunk.format,
100
+ numberOfChannels: chunk.channels,
101
+ sampleRate: chunk.sampleRate,
102
+ timestamp,
103
+ });
104
+ this.nextTimestamp = timestamp + sample.duration;
105
+ this.onSample(sample);
106
+ }
107
+ });
108
+ decode.catch(() => {}); // Surfaces through whoever awaits it next
109
+
110
+ // Keep one batch in flight, so the worker already has the next one by the time it's done with the current one
111
+ const previousDecode = this.inFlightDecode;
112
+ this.inFlightDecode = decode;
113
+ await previousDecode;
85
114
  }
86
115
  }
87
116
 
package/src/encoder.ts CHANGED
@@ -17,8 +17,10 @@ import { sendCommand, refWorker, unrefWorker } from './worker-client';
17
17
  import { assert, BATCH_SAMPLE_COUNT, EncodedChunk } from './shared';
18
18
  import { TRUEHD_CHANNEL_COUNTS, TRUEHD_MAJOR_SYNC_WORD, TRUEHD_SAMPLE_RATES } from '../../../shared/truehd-misc';
19
19
 
20
+ const MAJOR_SYNC_INTERVAL = 16; // In access units, as used by FFmpeg's encoder
21
+
20
22
  class TrueHdEncoder extends CustomAudioEncoder {
21
- private ctx = 0;
23
+ private ctx: number | null = null;
22
24
  private encoderFrameSize = 0;
23
25
  private sampleRate = 0;
24
26
  private numberOfChannels = 0;
@@ -27,7 +29,9 @@ class TrueHdEncoder extends CustomAudioEncoder {
27
29
  // Accumulate interleaved f32 samples until we have a full batch
28
30
  private pendingBuffer = new Float32Array(2 ** 16);
29
31
  private pendingFrames = 0;
32
+ private receivedFrames = 0;
30
33
  private nextSampleTimestampInSamples: number | null = null;
34
+ private inFlightEncode: Promise<void> | null = null;
31
35
 
32
36
  static override supports(codec: AudioCodec, config: AudioEncoderConfig): boolean {
33
37
  return codec === 'truehd'
@@ -57,6 +61,7 @@ class TrueHdEncoder extends CustomAudioEncoder {
57
61
 
58
62
  private resetInternalState() {
59
63
  this.pendingFrames = 0;
64
+ this.receivedFrames = 0;
60
65
  this.nextSampleTimestampInSamples = null;
61
66
 
62
67
  this.chunkMetadata = {
@@ -94,6 +99,7 @@ class TrueHdEncoder extends CustomAudioEncoder {
94
99
  }
95
100
  this.pendingBuffer.set(incomingData, this.pendingFrames * channels);
96
101
  this.pendingFrames += incomingFrames;
102
+ this.receivedFrames += incomingFrames;
97
103
 
98
104
  if (this.pendingFrames >= BATCH_SAMPLE_COUNT) {
99
105
  // Only whole frames for now, since the encoder accepts a short frame only at the very end
@@ -102,10 +108,28 @@ class TrueHdEncoder extends CustomAudioEncoder {
102
108
  }
103
109
 
104
110
  async flush() {
111
+ assert(this.ctx !== null);
112
+
113
+ // The encoder writes no major sync at all for streams shorter than one major sync interval, leaving them
114
+ // undecodable, so pad these with silence
115
+ if (
116
+ this.nextSampleTimestampInSamples !== null
117
+ && Math.ceil(this.receivedFrames / this.encoderFrameSize) < MAJOR_SYNC_INTERVAL
118
+ ) {
119
+ const channels = this.numberOfChannels;
120
+ const paddedFrames = this.pendingFrames + MAJOR_SYNC_INTERVAL * this.encoderFrameSize - this.receivedFrames;
121
+
122
+ this.pendingBuffer.fill(0, this.pendingFrames * channels, paddedFrames * channels);
123
+ this.pendingFrames = paddedFrames;
124
+ }
125
+
105
126
  if (this.pendingFrames > 0) {
106
127
  await this.encodePendingFrames(this.pendingFrames);
107
128
  }
108
129
 
130
+ await this.inFlightEncode;
131
+ this.inFlightEncode = null;
132
+
109
133
  const result = await sendCommand({ type: 'flush-encoder', data: { ctx: this.ctx } });
110
134
  this.emitPackets(result.packets);
111
135
 
@@ -114,11 +138,15 @@ class TrueHdEncoder extends CustomAudioEncoder {
114
138
 
115
139
  close() {
116
140
  // Close shouldn't throw
117
- sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {});
141
+ if (this.ctx !== null) {
142
+ sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {});
143
+ }
144
+
118
145
  void unrefWorker();
119
146
  }
120
147
 
121
148
  private async encodePendingFrames(frameCount: number) {
149
+ assert(this.ctx !== null);
122
150
  assert(this.nextSampleTimestampInSamples !== null);
123
151
 
124
152
  const channels = this.numberOfChannels;
@@ -132,7 +160,7 @@ class TrueHdEncoder extends CustomAudioEncoder {
132
160
  this.pendingBuffer.copyWithin(0, sampleCount, sampleCount + this.pendingFrames * channels);
133
161
  }
134
162
 
135
- const result = await sendCommand({
163
+ const encode = sendCommand({
136
164
  type: 'encode',
137
165
  data: {
138
166
  ctx: this.ctx,
@@ -140,11 +168,15 @@ class TrueHdEncoder extends CustomAudioEncoder {
140
168
  sampleCount: frameCount,
141
169
  timestamp: this.nextSampleTimestampInSamples,
142
170
  },
143
- }, [audioData]);
171
+ }, [audioData]).then(result => this.emitPackets(result.packets));
172
+ encode.catch(() => {}); // Surfaces through whoever awaits it next
144
173
 
145
174
  this.nextSampleTimestampInSamples += frameCount;
146
175
 
147
- this.emitPackets(result.packets);
176
+ // Keep one batch in flight, so the worker already has the next one by the time it's done with the current one
177
+ const previousEncode = this.inFlightEncode;
178
+ this.inFlightEncode = encode;
179
+ await previousEncode;
148
180
  }
149
181
 
150
182
  private emitPackets(packets: EncodedChunk[]) {
package/src/shared.ts CHANGED
@@ -17,7 +17,7 @@ export type DecodedChunk = {
17
17
  channels: number;
18
18
  sampleRate: number;
19
19
  sampleCount: number;
20
- pts: number;
20
+ pts: number | null;
21
21
  };
22
22
 
23
23
  export type EncodedChunk = {
@@ -43,7 +43,7 @@ export const unrefWorker = async () => {
43
43
  keepAliveInterval = null;
44
44
  }
45
45
 
46
- const worker = await workerPromise;
46
+ const worker = await workerPromise?.catch(() => null);
47
47
  if (worker) {
48
48
  if (workerError) {
49
49
  // The failed worker was already terminated. With nobody using it anymore, the next ref can start fresh
@@ -88,8 +88,14 @@ export const sendCommand = async <T extends string>(
88
88
 
89
89
  const ensureWorker = () => {
90
90
  return workerPromise ??= (async () => {
91
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
92
- const worker = (await createWorker()) as ExtendedWorker;
91
+ let worker: ExtendedWorker;
92
+ try {
93
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
94
+ worker = (await createWorker()) as ExtendedWorker;
95
+ } catch (error) {
96
+ workerPromise = null; // So that the next use tries again
97
+ throw error;
98
+ }
93
99
  worker.unref?.(); // Start unreffed
94
100
 
95
101
  const onMessage = (data: WorkerResponse) => {