@mediabunny/ac3 1.65.2 → 1.66.1

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.
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  import createModule from '../build/ac3';
10
- import type { WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
10
+ import type { DecodedChunk, WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
11
11
 
12
12
  type ExtendedEmscriptenModule = EmscriptenModule & {
13
13
  cwrap: typeof cwrap;
@@ -18,14 +18,16 @@ let modulePromise: Promise<ExtendedEmscriptenModule> | null = null;
18
18
 
19
19
  let initDecoderFn: (codecId: number) => number;
20
20
  let configureDecodePacket: (ctx: number, size: number) => number;
21
- let decodePacket: (ctx: number, pts: bigint) => number;
21
+ let sendDecodePacket: (ctx: number, pts: bigint) => number;
22
+ let sendDecodeFlush: (ctx: number) => number;
23
+ let receiveDecodedFrame: (ctx: number) => number;
22
24
  let getDecodedFormat: (ctx: number) => number;
23
25
  let getDecodedPlanePtr: (ctx: number, plane: number) => number;
24
26
  let getDecodedChannels: (ctx: number) => number;
25
27
  let getDecodedSampleRate: (ctx: number) => number;
26
28
  let getDecodedSampleCount: (ctx: number) => number;
27
29
  let getDecodedPts: (ctx: number) => bigint;
28
- let flushDecoderFn: (ctx: number) => void;
30
+ let resetDecoder: (ctx: number) => void;
29
31
  let closeDecoderFn: (ctx: number) => void;
30
32
 
31
33
  let initEncoderFn: (codecId: number, channels: number, sampleRate: number, bitrate: number) => number;
@@ -53,14 +55,20 @@ const ensureModule = async () => {
53
55
 
54
56
  initDecoderFn = module.cwrap('init_decoder', 'number', ['number']);
55
57
  configureDecodePacket = module.cwrap('configure_decode_packet', 'number', ['number', 'number']);
56
- decodePacket = module.cwrap('decode_packet', 'number', ['number', 'number']) as unknown as typeof decodePacket;
58
+ sendDecodePacket = module.cwrap(
59
+ 'send_decode_packet',
60
+ 'number',
61
+ ['number', 'number'],
62
+ ) as unknown as typeof sendDecodePacket;
63
+ sendDecodeFlush = module.cwrap('send_decode_flush', 'number', ['number']);
64
+ receiveDecodedFrame = module.cwrap('receive_decoded_frame', 'number', ['number']);
57
65
  getDecodedFormat = module.cwrap('get_decoded_format', 'number', ['number']);
58
66
  getDecodedPlanePtr = module.cwrap('get_decoded_plane_ptr', 'number', ['number', 'number']);
59
67
  getDecodedChannels = module.cwrap('get_decoded_channels', 'number', ['number']);
60
68
  getDecodedSampleRate = module.cwrap('get_decoded_sample_rate', 'number', ['number']);
61
69
  getDecodedSampleCount = module.cwrap('get_decoded_sample_count', 'number', ['number']);
62
70
  getDecodedPts = module.cwrap('get_decoded_pts', 'number', ['number']) as unknown as typeof getDecodedPts;
63
- flushDecoderFn = module.cwrap('flush_decoder', null, ['number']);
71
+ resetDecoder = module.cwrap('reset_decoder', null, ['number']);
64
72
  closeDecoderFn = module.cwrap('close_decoder', null, ['number']);
65
73
 
66
74
  initEncoderFn = module.cwrap('init_encoder', 'number', ['number', 'number', 'number', 'number']);
@@ -98,6 +106,8 @@ const AV_FORMAT_MAP: Record<number, { format: AudioSampleFormat; bytesPerSample:
98
106
  8: { format: 'f32-planar', bytesPerSample: 4, planar: true },
99
107
  };
100
108
 
109
+ const AV_NOPTS_VALUE = -(BigInt(2) ** BigInt(63));
110
+
101
111
  const decode = (ctx: number, encodedData: ArrayBuffer, timestamp: number) => {
102
112
  const bytes = new Uint8Array(encodedData);
103
113
 
@@ -108,40 +118,77 @@ const decode = (ctx: number, encodedData: ArrayBuffer, timestamp: number) => {
108
118
 
109
119
  module.HEAPU8.set(bytes, dataPtr);
110
120
 
111
- const ret = decodePacket(ctx, BigInt(timestamp));
121
+ const ret = sendDecodePacket(ctx, BigInt(timestamp));
112
122
  if (ret < 0) {
113
123
  throw new Error(`Decode failed with error code ${ret}.`);
114
124
  }
115
125
 
116
- const avFormat = getDecodedFormat(ctx);
117
- const info = AV_FORMAT_MAP[avFormat];
118
- if (!info) {
119
- throw new Error(`Unsupported AVSampleFormat: ${avFormat}`);
126
+ return receiveDecodedChunks(ctx);
127
+ };
128
+
129
+ const flushDecoder = (ctx: number) => {
130
+ const ret = sendDecodeFlush(ctx);
131
+ if (ret < 0) {
132
+ throw new Error(`Decoder flush failed with error code ${ret}.`);
120
133
  }
121
134
 
122
- const channels = getDecodedChannels(ctx);
123
- const sampleRate = getDecodedSampleRate(ctx);
124
- const sampleCount = getDecodedSampleCount(ctx);
125
- const pts = Number(getDecodedPts(ctx));
135
+ const chunks = receiveDecodedChunks(ctx);
136
+ resetDecoder(ctx);
137
+
138
+ return chunks;
139
+ };
126
140
 
127
- let pcmData: ArrayBuffer;
128
- if (info.planar) {
129
- const planeSize = sampleCount * info.bytesPerSample;
130
- const buffer = new Uint8Array(planeSize * channels);
141
+ const receiveDecodedChunks = (ctx: number) => {
142
+ const chunks: DecodedChunk[] = [];
131
143
 
132
- for (let ch = 0; ch < channels; ch++) {
133
- const ptr = getDecodedPlanePtr(ctx, ch);
134
- buffer.set(module.HEAPU8.subarray(ptr, ptr + planeSize), ch * planeSize);
144
+ while (true) {
145
+ const ret = receiveDecodedFrame(ctx);
146
+ if (ret < 0) {
147
+ throw new Error(`Decode failed with error code ${ret}.`);
148
+ }
149
+ if (ret === 0) {
150
+ break;
135
151
  }
136
152
 
137
- pcmData = buffer.buffer;
138
- } else {
139
- const totalSize = sampleCount * channels * info.bytesPerSample;
140
- const ptr = getDecodedPlanePtr(ctx, 0);
141
- pcmData = module.HEAPU8.slice(ptr, ptr + totalSize).buffer;
153
+ const avFormat = getDecodedFormat(ctx);
154
+ const info = AV_FORMAT_MAP[avFormat];
155
+ if (!info) {
156
+ throw new Error(`Unsupported AVSampleFormat: ${avFormat}`);
157
+ }
158
+
159
+ const channels = getDecodedChannels(ctx);
160
+ const sampleRate = getDecodedSampleRate(ctx);
161
+ const sampleCount = getDecodedSampleCount(ctx);
162
+ const pts = getDecodedPts(ctx);
163
+
164
+ let pcmData: ArrayBuffer;
165
+ if (info.planar) {
166
+ const planeSize = sampleCount * info.bytesPerSample;
167
+ const buffer = new Uint8Array(planeSize * channels);
168
+
169
+ for (let ch = 0; ch < channels; ch++) {
170
+ const ptr = getDecodedPlanePtr(ctx, ch);
171
+ buffer.set(module.HEAPU8.subarray(ptr, ptr + planeSize), ch * planeSize);
172
+ }
173
+
174
+ pcmData = buffer.buffer;
175
+ } else {
176
+ const totalSize = sampleCount * channels * info.bytesPerSample;
177
+ const ptr = getDecodedPlanePtr(ctx, 0);
178
+ pcmData = module.HEAPU8.slice(ptr, ptr + totalSize).buffer;
179
+ }
180
+
181
+ chunks.push({
182
+ pcmData,
183
+ format: info.format,
184
+ channels,
185
+ sampleRate,
186
+ sampleCount,
187
+ pts: pts === AV_NOPTS_VALUE ? null : Number(pts),
188
+ });
142
189
  }
143
190
 
144
- return { pcmData, format: info.format, channels, sampleRate, sampleCount, pts };
191
+ return chunks;
145
192
  };
146
193
 
147
194
  const initEncoder = async (
@@ -201,22 +248,15 @@ const onMessage = (data: { id: number; command: WorkerCommand }) => {
201
248
  }; break;
202
249
 
203
250
  case 'decode': {
204
- const decoded = decode(command.data.ctx, command.data.encodedData, command.data.timestamp);
205
- result = {
206
- type: command.type,
207
- pcmData: decoded.pcmData,
208
- format: decoded.format,
209
- channels: decoded.channels,
210
- sampleRate: decoded.sampleRate,
211
- sampleCount: decoded.sampleCount,
212
- pts: decoded.pts,
213
- };
214
- transferables.push(decoded.pcmData);
251
+ const chunks = decode(command.data.ctx, command.data.encodedData, command.data.timestamp);
252
+ result = { type: command.type, chunks };
253
+ transferables.push(...chunks.map(x => x.pcmData));
215
254
  }; break;
216
255
 
217
256
  case 'flush-decoder': {
218
- flushDecoderFn(command.data.ctx);
219
- result = { type: command.type };
257
+ const chunks = flushDecoder(command.data.ctx);
258
+ result = { type: command.type, chunks };
259
+ transferables.push(...chunks.map(x => x.pcmData));
220
260
  }; break;
221
261
 
222
262
  case 'close-decoder': {
package/src/decoder.ts CHANGED
@@ -14,9 +14,12 @@ import {
14
14
  registerDecoder,
15
15
  } from 'mediabunny';
16
16
  import { sendCommand, refWorker, unrefWorker } from './worker-client';
17
+ import { assert, type DecodedChunk } from './shared';
17
18
 
18
19
  class Ac3Decoder extends CustomAudioDecoder {
19
- private ctx = 0;
20
+ private ctx: number | null = null;
21
+ private nextTimestamp: number | null = null;
22
+ private inFlightDecode: Promise<void> | null = null;
20
23
 
21
24
  static override supports(codec: AudioCodec): boolean {
22
25
  return codec === 'ac3' || codec === 'eac3';
@@ -33,33 +36,63 @@ class Ac3Decoder extends CustomAudioDecoder {
33
36
  }
34
37
 
35
38
  async decode(packet: EncodedPacket) {
39
+ assert(this.ctx !== null);
40
+
36
41
  const encodedData = packet.data.slice().buffer;
37
42
  const timestamp = Math.round(packet.timestamp * this.config.sampleRate);
38
43
 
39
- const result = await sendCommand({
44
+ const decode = sendCommand({
40
45
  type: 'decode',
41
46
  data: { ctx: this.ctx, encodedData, timestamp },
42
- }, [encodedData]);
43
-
44
- const sample = new AudioSample({
45
- data: result.pcmData,
46
- format: result.format,
47
- numberOfChannels: result.channels,
48
- sampleRate: result.sampleRate,
49
- timestamp: result.pts / result.sampleRate,
50
- });
51
- this.onSample(sample);
47
+ }, [encodedData]).then(result => this.emitSamples(result.chunks));
48
+ decode.catch(() => {}); // Surfaces through whoever awaits it next
49
+
50
+ // Keep one packet in flight, so the worker already has the next one by the time it's done with the current one
51
+ const previousDecode = this.inFlightDecode;
52
+ this.inFlightDecode = decode;
53
+ await previousDecode;
52
54
  }
53
55
 
54
56
  async flush() {
55
- await sendCommand({ type: 'flush-decoder', data: { ctx: this.ctx } });
57
+ assert(this.ctx !== null);
58
+
59
+ await this.inFlightDecode;
60
+ this.inFlightDecode = null;
61
+
62
+ const result = await sendCommand({ type: 'flush-decoder', data: { ctx: this.ctx } });
63
+ this.emitSamples(result.chunks);
56
64
  }
57
65
 
58
66
  async close() {
59
67
  // Close shouldn't throw
60
- sendCommand({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => {});
68
+ if (this.ctx !== null) {
69
+ sendCommand({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => {});
70
+ }
71
+
61
72
  await unrefWorker();
62
73
  }
74
+
75
+ private emitSamples(chunks: DecodedChunk[]) {
76
+ for (const chunk of chunks) {
77
+ let timestamp: number;
78
+ if (chunk.pts !== null) {
79
+ timestamp = chunk.pts / this.config.sampleRate;
80
+ } else {
81
+ assert(this.nextTimestamp !== null);
82
+ timestamp = this.nextTimestamp;
83
+ }
84
+
85
+ const sample = new AudioSample({
86
+ data: chunk.pcmData,
87
+ format: chunk.format,
88
+ numberOfChannels: chunk.channels,
89
+ sampleRate: chunk.sampleRate,
90
+ timestamp,
91
+ });
92
+ this.nextTimestamp = timestamp + sample.duration;
93
+ this.onSample(sample);
94
+ }
95
+ }
63
96
  }
64
97
 
65
98
  let registered = false;
package/src/encoder.ts CHANGED
@@ -15,10 +15,10 @@ import {
15
15
  } from 'mediabunny';
16
16
  import { sendCommand, refWorker, unrefWorker } from './worker-client';
17
17
  import { assert } from './shared';
18
- import { AC3_SAMPLE_RATES, EAC3_REDUCED_SAMPLE_RATES } from '../../../shared/ac3-misc';
18
+ import { AC3_SAMPLE_RATES } from '../../../shared/ac3-misc';
19
19
 
20
20
  class Ac3Encoder extends CustomAudioEncoder {
21
- private ctx = 0;
21
+ private ctx: number | null = null;
22
22
  private encoderFrameSize = 0;
23
23
  private sampleRate = 0;
24
24
  private numberOfChannels = 0;
@@ -28,17 +28,25 @@ class Ac3Encoder extends CustomAudioEncoder {
28
28
  private pendingBuffer = new Float32Array(2 ** 16);
29
29
  private pendingFrames = 0;
30
30
  private nextSampleTimestampInSamples: number | null = null;
31
+ private encodedEndTimestampInSamples = 0;
32
+ private inFlightEncode: Promise<void> | null = null;
31
33
 
32
34
  static override supports(codec: AudioCodec, config: AudioEncoderConfig): boolean {
33
- const sampleRates = codec === 'eac3'
34
- ? [...AC3_SAMPLE_RATES, ...EAC3_REDUCED_SAMPLE_RATES]
35
- : AC3_SAMPLE_RATES;
36
-
35
+ // FFmpeg's encoders top out at 5.1 and can't do E-AC-3's reduced sample rates
37
36
  return (codec === 'ac3' || codec === 'eac3')
38
37
  && config.numberOfChannels >= 1
39
- && config.numberOfChannels <= 8
40
- && sampleRates.includes(config.sampleRate)
41
- && config.bitrate !== undefined;
38
+ && config.numberOfChannels <= 6
39
+ && AC3_SAMPLE_RATES.includes(config.sampleRate)
40
+ && config.bitrate !== undefined
41
+ // FFmpeg snaps AC-3 bitrates to the closest valid one, but rejects E-AC-3 bitrates outside of what
42
+ // six-block and single-block syncframes can hold
43
+ && (
44
+ codec === 'ac3'
45
+ || (
46
+ config.bitrate >= 16 * Math.ceil(config.sampleRate / 1536)
47
+ && config.bitrate <= 16 * Math.floor(2048 * config.sampleRate / 256)
48
+ )
49
+ );
42
50
  }
43
51
 
44
52
  async init() {
@@ -80,6 +88,7 @@ class Ac3Encoder extends CustomAudioEncoder {
80
88
  async encode(audioSample: AudioSample) {
81
89
  if (this.nextSampleTimestampInSamples === null) {
82
90
  this.nextSampleTimestampInSamples = Math.round(audioSample.timestamp * this.sampleRate);
91
+ this.encodedEndTimestampInSamples = this.nextSampleTimestampInSamples;
83
92
  }
84
93
 
85
94
  const channels = this.numberOfChannels;
@@ -104,25 +113,38 @@ class Ac3Encoder extends CustomAudioEncoder {
104
113
  this.pendingBuffer.set(incomingData, this.pendingFrames * channels);
105
114
  this.pendingFrames += incomingFrames;
106
115
 
107
- while (this.pendingFrames >= this.encoderFrameSize) {
108
- await this.encodeOneFrame();
116
+ let encodedFrames = 0;
117
+ while (this.pendingFrames - encodedFrames >= this.encoderFrameSize) {
118
+ await this.encodeOneFrame(encodedFrames);
119
+ encodedFrames += this.encoderFrameSize;
109
120
  }
121
+
122
+ this.pendingBuffer.copyWithin(0, encodedFrames * channels, this.pendingFrames * channels);
123
+ this.pendingFrames -= encodedFrames;
110
124
  }
111
125
 
112
126
  async flush() {
113
- // Pad remaining samples with silence to fill a full frame
114
- if (this.pendingFrames > 0) {
127
+ assert(this.ctx !== null);
128
+
129
+ await this.inFlightEncode;
130
+
131
+ if (this.nextSampleTimestampInSamples !== null) {
115
132
  const channels = this.numberOfChannels;
116
133
  const frameSize = this.encoderFrameSize;
117
- const usedSamples = this.pendingFrames * channels;
118
- const frameSamples = frameSize * channels;
134
+ const endTimestampInSamples = this.nextSampleTimestampInSamples + this.pendingFrames;
119
135
 
120
- this.pendingBuffer.fill(0, usedSamples, frameSamples);
121
- this.pendingFrames = frameSize;
136
+ // Pad with silence until every sample has made it out
137
+ while (this.encodedEndTimestampInSamples < endTimestampInSamples) {
138
+ this.pendingBuffer.fill(0, this.pendingFrames * channels, frameSize * channels);
139
+ this.pendingFrames = 0;
122
140
 
123
- await this.encodeOneFrame();
141
+ await this.encodeOneFrame(0);
142
+ await this.inFlightEncode;
143
+ }
124
144
  }
125
145
 
146
+ this.inFlightEncode = null;
147
+
126
148
  await sendCommand({ type: 'flush-encoder', data: { ctx: this.ctx } });
127
149
 
128
150
  this.resetInternalState();
@@ -130,51 +152,57 @@ class Ac3Encoder extends CustomAudioEncoder {
130
152
 
131
153
  close() {
132
154
  // Close shouldn't throw
133
- sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {});
155
+ if (this.ctx !== null) {
156
+ sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {});
157
+ }
158
+
134
159
  void unrefWorker();
135
160
  }
136
161
 
137
- private async encodeOneFrame() {
162
+ private async encodeOneFrame(startFrame: number) {
163
+ assert(this.ctx !== null);
138
164
  assert(this.nextSampleTimestampInSamples !== null);
139
165
 
140
166
  const channels = this.numberOfChannels;
141
- const frameSize = this.encoderFrameSize;
142
- const frameSamples = frameSize * channels;
143
-
144
- const frameData = this.pendingBuffer.slice(0, frameSamples);
145
-
146
- // Shift remaining using copyWithin
147
- this.pendingFrames -= frameSize;
148
- if (this.pendingFrames > 0) {
149
- this.pendingBuffer.copyWithin(0, frameSamples, frameSamples + this.pendingFrames * channels);
150
- }
167
+ const frameData = this.pendingBuffer.slice(
168
+ startFrame * channels,
169
+ (startFrame + this.encoderFrameSize) * channels,
170
+ );
151
171
 
152
172
  const audioData = frameData.buffer;
153
- const result = await sendCommand({
173
+ const encode = sendCommand({
154
174
  type: 'encode',
155
175
  data: {
156
176
  ctx: this.ctx,
157
177
  audioData,
158
178
  timestamp: this.nextSampleTimestampInSamples,
159
179
  },
160
- }, [audioData]);
161
-
162
- this.nextSampleTimestampInSamples += frameSize;
163
-
164
- // We always get exactly one packet because we encode the correct frame size
165
- const packet = new EncodedPacket(
166
- new Uint8Array(result.encodedData),
167
- 'key',
168
- result.pts / this.sampleRate,
169
- result.duration / this.sampleRate,
170
- );
180
+ }, [audioData]).then((result) => {
181
+ this.encodedEndTimestampInSamples = result.pts + result.duration;
182
+
183
+ // We always get exactly one packet because we encode the correct frame size
184
+ const packet = new EncodedPacket(
185
+ new Uint8Array(result.encodedData),
186
+ 'key',
187
+ result.pts / this.sampleRate,
188
+ result.duration / this.sampleRate,
189
+ );
190
+
191
+ this.onPacket(
192
+ packet,
193
+ this.chunkMetadata,
194
+ );
195
+
196
+ this.chunkMetadata = {};
197
+ });
198
+ encode.catch(() => {}); // Surfaces through whoever awaits it next
171
199
 
172
- this.onPacket(
173
- packet,
174
- this.chunkMetadata,
175
- );
200
+ this.nextSampleTimestampInSamples += this.encoderFrameSize;
176
201
 
177
- this.chunkMetadata = {};
202
+ // Keep one frame in flight, so the worker already has the next frame by the time it's done with the current one
203
+ const previousEncode = this.inFlightEncode;
204
+ this.inFlightEncode = encode;
205
+ await previousEncode;
178
206
  }
179
207
  }
180
208
 
package/src/shared.ts CHANGED
@@ -6,6 +6,15 @@
6
6
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
  */
8
8
 
9
+ export type DecodedChunk = {
10
+ pcmData: ArrayBuffer;
11
+ format: AudioSampleFormat;
12
+ channels: number;
13
+ sampleRate: number;
14
+ sampleCount: number;
15
+ pts: number | null;
16
+ };
17
+
9
18
  export type WorkerCommand = {
10
19
  type: 'init-decoder';
11
20
  data: {
@@ -61,14 +70,10 @@ export type WorkerResponseData = {
61
70
  frameSize: number;
62
71
  } | {
63
72
  type: 'decode';
64
- pcmData: ArrayBuffer;
65
- format: AudioSampleFormat;
66
- channels: number;
67
- sampleRate: number;
68
- sampleCount: number;
69
- pts: number;
73
+ chunks: DecodedChunk[];
70
74
  } | {
71
75
  type: 'flush-decoder';
76
+ chunks: DecodedChunk[];
72
77
  } | {
73
78
  type: 'close-decoder';
74
79
  } | {
@@ -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) => {