@mediabunny/dts 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/encoder.ts CHANGED
@@ -15,10 +15,13 @@ import {
15
15
  } from 'mediabunny';
16
16
  import { sendCommand, refWorker, unrefWorker } from './worker-client';
17
17
  import { assert } from './shared';
18
- import { DTS_CHANNEL_COUNTS, DTS_SAMPLE_RATES, dtsBitrateFits } from '../../../shared/dts-misc';
18
+ import { clampDtsBitrate, DTS_CHANNEL_COUNTS, DTS_SAMPLE_RATES } from '../../../shared/dts-misc';
19
+
20
+ // FFmpeg's DTS encoder doesn't report it, but the decoded audio comes out this many samples late
21
+ const CODEC_DELAY = 512;
19
22
 
20
23
  class DtsEncoder extends CustomAudioEncoder {
21
- private ctx = 0;
24
+ private ctx: number | null = null;
22
25
  private encoderFrameSize = 0;
23
26
  private sampleRate = 0;
24
27
  private numberOfChannels = 0;
@@ -28,13 +31,13 @@ class DtsEncoder extends CustomAudioEncoder {
28
31
  private pendingBuffer = new Float32Array(2 ** 16);
29
32
  private pendingFrames = 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 === 'dts'
34
38
  && DTS_CHANNEL_COUNTS.includes(config.numberOfChannels)
35
39
  && DTS_SAMPLE_RATES.includes(config.sampleRate)
36
- && config.bitrate !== undefined
37
- && dtsBitrateFits(config.bitrate, config.sampleRate, config.numberOfChannels);
40
+ && config.bitrate !== undefined;
38
41
  }
39
42
 
40
43
  async init() {
@@ -49,7 +52,7 @@ class DtsEncoder extends CustomAudioEncoder {
49
52
  data: {
50
53
  numberOfChannels: this.config.numberOfChannels,
51
54
  sampleRate: this.config.sampleRate,
52
- bitrate: this.config.bitrate,
55
+ bitrate: clampDtsBitrate(this.config.bitrate, this.config.sampleRate, this.config.numberOfChannels),
53
56
  },
54
57
  });
55
58
 
@@ -99,77 +102,88 @@ class DtsEncoder extends CustomAudioEncoder {
99
102
  this.pendingBuffer.set(incomingData, this.pendingFrames * channels);
100
103
  this.pendingFrames += incomingFrames;
101
104
 
102
- while (this.pendingFrames >= this.encoderFrameSize) {
103
- await this.encodeOneFrame();
105
+ // Shift the remainder to the front only once at the end, as doing it per frame is quadratic for big samples
106
+ let encodedFrames = 0;
107
+ while (this.pendingFrames - encodedFrames >= this.encoderFrameSize) {
108
+ await this.encodeOneFrame(encodedFrames);
109
+ encodedFrames += this.encoderFrameSize;
104
110
  }
111
+
112
+ this.pendingBuffer.copyWithin(0, encodedFrames * channels, this.pendingFrames * channels);
113
+ this.pendingFrames -= encodedFrames;
105
114
  }
106
115
 
107
116
  async flush() {
108
- // Pad remaining samples with silence to fill a full frame
109
- if (this.pendingFrames > 0) {
117
+ // Pad with enough silence to push the remaining samples through the codec delay and to fill up the last frame
118
+ if (this.nextSampleTimestampInSamples !== null) {
110
119
  const channels = this.numberOfChannels;
111
120
  const frameSize = this.encoderFrameSize;
112
- const usedSamples = this.pendingFrames * channels;
113
- const frameSamples = frameSize * channels;
121
+ const paddedFrames = Math.ceil((this.pendingFrames + CODEC_DELAY) / frameSize) * frameSize;
114
122
 
115
- this.pendingBuffer.fill(0, usedSamples, frameSamples);
116
- this.pendingFrames = frameSize;
123
+ this.pendingBuffer.fill(0, this.pendingFrames * channels, paddedFrames * channels);
117
124
 
118
- await this.encodeOneFrame();
125
+ for (let startFrame = 0; startFrame < paddedFrames; startFrame += frameSize) {
126
+ await this.encodeOneFrame(startFrame);
127
+ }
119
128
  }
120
129
 
121
- await sendCommand({ type: 'flush-encoder', data: { ctx: this.ctx } });
130
+ // FFmpeg's DTS encoder doesn't hold back any frames, so there's nothing to flush out of it
131
+ await this.inFlightEncode;
132
+ this.inFlightEncode = null;
122
133
 
123
134
  this.resetInternalState();
124
135
  }
125
136
 
126
137
  close() {
127
138
  // Close shouldn't throw
128
- sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {});
139
+ if (this.ctx !== null) {
140
+ sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {});
141
+ }
142
+
129
143
  void unrefWorker();
130
144
  }
131
145
 
132
- private async encodeOneFrame() {
146
+ private async encodeOneFrame(startFrame: number) {
147
+ assert(this.ctx !== null);
133
148
  assert(this.nextSampleTimestampInSamples !== null);
134
149
 
135
150
  const channels = this.numberOfChannels;
136
151
  const frameSize = this.encoderFrameSize;
137
- const frameSamples = frameSize * channels;
138
-
139
- const frameData = this.pendingBuffer.slice(0, frameSamples);
140
-
141
- // Shift remaining using copyWithin
142
- this.pendingFrames -= frameSize;
143
- if (this.pendingFrames > 0) {
144
- this.pendingBuffer.copyWithin(0, frameSamples, frameSamples + this.pendingFrames * channels);
145
- }
152
+ const frameData = this.pendingBuffer.slice(startFrame * channels, (startFrame + frameSize) * channels);
146
153
 
147
154
  const audioData = frameData.buffer;
148
- const result = await sendCommand({
155
+ const encode = sendCommand({
149
156
  type: 'encode',
150
157
  data: {
151
158
  ctx: this.ctx,
152
159
  audioData,
153
- timestamp: this.nextSampleTimestampInSamples,
160
+ // Shifted back by the codec delay so that the decoded audio lines up with the input
161
+ timestamp: this.nextSampleTimestampInSamples - CODEC_DELAY,
154
162
  },
155
- }, [audioData]);
163
+ }, [audioData]).then((result) => {
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
+ );
171
+
172
+ this.onPacket(
173
+ packet,
174
+ this.chunkMetadata,
175
+ );
176
+
177
+ this.chunkMetadata = {};
178
+ });
179
+ encode.catch(() => {}); // Surfaces through whoever awaits it next
156
180
 
157
181
  this.nextSampleTimestampInSamples += frameSize;
158
182
 
159
- // We always get exactly one packet because we encode the correct frame size
160
- const packet = new EncodedPacket(
161
- new Uint8Array(result.encodedData),
162
- 'key',
163
- result.pts / this.sampleRate,
164
- result.duration / this.sampleRate,
165
- );
166
-
167
- this.onPacket(
168
- packet,
169
- this.chunkMetadata,
170
- );
171
-
172
- this.chunkMetadata = {};
183
+ // Keep one frame in flight, so the worker already has the next frame by the time it's done with the current one
184
+ const previousEncode = this.inFlightEncode;
185
+ this.inFlightEncode = encode;
186
+ await previousEncode;
173
187
  }
174
188
  }
175
189
 
package/src/shared.ts CHANGED
@@ -40,11 +40,6 @@ export type WorkerCommand = {
40
40
  audioData: ArrayBuffer;
41
41
  timestamp: number;
42
42
  };
43
- } | {
44
- type: 'flush-encoder';
45
- data: {
46
- ctx: number;
47
- };
48
43
  } | {
49
44
  type: 'close-encoder';
50
45
  data: {
@@ -77,8 +72,6 @@ export type WorkerResponseData = {
77
72
  encodedData: ArrayBuffer;
78
73
  pts: number;
79
74
  duration: number;
80
- } | {
81
- type: 'flush-encoder';
82
75
  } | {
83
76
  type: 'close-encoder';
84
77
  };
@@ -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) => {