@mediabunny/dts 1.65.1 → 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.
Binary file
@@ -28,7 +28,6 @@ let initEncoderFn;
28
28
  let getEncoderFrameSize;
29
29
  let getEncodeInputPtr;
30
30
  let encodeFrameFn;
31
- let flushEncoderFn;
32
31
  let getEncodedData;
33
32
  let getEncodedPts;
34
33
  let getEncodedDuration;
@@ -57,7 +56,6 @@ const ensureModule = async () => {
57
56
  getEncoderFrameSize = module.cwrap('get_encoder_frame_size', 'number', ['number']);
58
57
  getEncodeInputPtr = module.cwrap('get_encode_input_ptr', 'number', ['number', 'number']);
59
58
  encodeFrameFn = module.cwrap('encode_frame', 'number', ['number', 'number']);
60
- flushEncoderFn = module.cwrap('flush_encoder', null, ['number']);
61
59
  getEncodedData = module.cwrap('get_encoded_data', 'number', ['number']);
62
60
  getEncodedPts = module.cwrap('get_encoded_pts', 'number', ['number']);
63
61
  getEncodedDuration = module.cwrap('get_encoded_duration', 'number', ['number']);
@@ -145,9 +143,6 @@ const encode = (ctx, audioData, timestamp) => {
145
143
  const duration = getEncodedDuration(ctx);
146
144
  return { encodedData, pts, duration };
147
145
  };
148
- const flushEncoder = (ctx) => {
149
- flushEncoderFn(ctx);
150
- };
151
146
  const onMessage = (data) => {
152
147
  const { id, command } = data;
153
148
  const handleCommand = async () => {
@@ -212,13 +207,6 @@ const onMessage = (data) => {
212
207
  }
213
208
  ;
214
209
  break;
215
- case 'flush-encoder':
216
- {
217
- flushEncoder(command.data.ctx);
218
- result = { type: command.type };
219
- }
220
- ;
221
- break;
222
210
  case 'close-encoder':
223
211
  {
224
212
  closeEncoderFn(command.data.ctx);
@@ -1 +1 @@
1
- {"version":3,"file":"decoder.d.ts","sourceRoot":"","sources":["../../../src/decoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA4DH;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,YAO9B,CAAC"}
1
+ {"version":3,"file":"decoder.d.ts","sourceRoot":"","sources":["../../../src/decoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA8EH;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,YAO9B,CAAC"}
@@ -10,10 +10,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.registerDtsDecoder = void 0;
11
11
  const mediabunny_1 = require("mediabunny");
12
12
  const worker_client_1 = require("./worker-client");
13
+ const shared_1 = require("./shared");
13
14
  class DtsDecoder extends mediabunny_1.CustomAudioDecoder {
14
15
  constructor() {
15
16
  super(...arguments);
16
- this.ctx = 0;
17
+ this.ctx = null;
18
+ this.inFlightDecode = null;
17
19
  }
18
20
  static supports(codec) {
19
21
  return codec === 'dts';
@@ -27,27 +29,39 @@ class DtsDecoder extends mediabunny_1.CustomAudioDecoder {
27
29
  this.ctx = result.ctx;
28
30
  }
29
31
  async decode(packet) {
32
+ (0, shared_1.assert)(this.ctx !== null);
30
33
  const encodedData = packet.data.slice().buffer;
31
34
  const timestamp = Math.round(packet.timestamp * this.config.sampleRate);
32
- const result = await (0, worker_client_1.sendCommand)({
35
+ const decode = (0, worker_client_1.sendCommand)({
33
36
  type: 'decode',
34
37
  data: { ctx: this.ctx, encodedData, timestamp },
35
- }, [encodedData]);
36
- const sample = new mediabunny_1.AudioSample({
37
- data: result.pcmData,
38
- format: result.format,
39
- numberOfChannels: result.channels,
40
- sampleRate: result.sampleRate,
41
- timestamp: result.pts / result.sampleRate,
38
+ }, [encodedData]).then((result) => {
39
+ const sample = new mediabunny_1.AudioSample({
40
+ data: result.pcmData,
41
+ format: result.format,
42
+ numberOfChannels: result.channels,
43
+ sampleRate: result.sampleRate,
44
+ timestamp: result.pts / this.config.sampleRate,
45
+ });
46
+ this.onSample(sample);
42
47
  });
43
- this.onSample(sample);
48
+ decode.catch(() => { }); // Surfaces through whoever awaits it next
49
+ // Keep one packet in flight, so the worker already has the next one by the time it's done with the current one
50
+ const previousDecode = this.inFlightDecode;
51
+ this.inFlightDecode = decode;
52
+ await previousDecode;
44
53
  }
45
54
  async flush() {
55
+ (0, shared_1.assert)(this.ctx !== null);
56
+ await this.inFlightDecode;
57
+ this.inFlightDecode = null;
46
58
  await (0, worker_client_1.sendCommand)({ type: 'flush-decoder', data: { ctx: this.ctx } });
47
59
  }
48
60
  async close() {
49
61
  // Close shouldn't throw
50
- (0, worker_client_1.sendCommand)({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => { });
62
+ if (this.ctx !== null) {
63
+ (0, worker_client_1.sendCommand)({ type: 'close-decoder', data: { ctx: this.ctx } }).catch(() => { });
64
+ }
51
65
  await (0, worker_client_1.unrefWorker)();
52
66
  }
53
67
  }
@@ -1 +1 @@
1
- {"version":3,"file":"encoder.d.ts","sourceRoot":"","sources":["../../../src/encoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA2KH;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,YAO9B,CAAC"}
1
+ {"version":3,"file":"encoder.d.ts","sourceRoot":"","sources":["../../../src/encoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAyLH;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,YAO9B,CAAC"}
@@ -12,10 +12,12 @@ const mediabunny_1 = require("mediabunny");
12
12
  const worker_client_1 = require("./worker-client");
13
13
  const shared_1 = require("./shared");
14
14
  const dts_misc_1 = require("../../../shared/dts-misc");
15
+ // FFmpeg's DTS encoder doesn't report it, but the decoded audio comes out this many samples late
16
+ const CODEC_DELAY = 512;
15
17
  class DtsEncoder extends mediabunny_1.CustomAudioEncoder {
16
18
  constructor() {
17
19
  super(...arguments);
18
- this.ctx = 0;
20
+ this.ctx = null;
19
21
  this.encoderFrameSize = 0;
20
22
  this.sampleRate = 0;
21
23
  this.numberOfChannels = 0;
@@ -24,13 +26,13 @@ class DtsEncoder extends mediabunny_1.CustomAudioEncoder {
24
26
  this.pendingBuffer = new Float32Array(2 ** 16);
25
27
  this.pendingFrames = 0;
26
28
  this.nextSampleTimestampInSamples = null;
29
+ this.inFlightEncode = null;
27
30
  }
28
31
  static supports(codec, config) {
29
32
  return codec === 'dts'
30
33
  && dts_misc_1.DTS_CHANNEL_COUNTS.includes(config.numberOfChannels)
31
34
  && dts_misc_1.DTS_SAMPLE_RATES.includes(config.sampleRate)
32
- && config.bitrate !== undefined
33
- && (0, dts_misc_1.dtsBitrateFits)(config.bitrate, config.sampleRate, config.numberOfChannels);
35
+ && config.bitrate !== undefined;
34
36
  }
35
37
  async init() {
36
38
  await (0, worker_client_1.refWorker)();
@@ -42,7 +44,7 @@ class DtsEncoder extends mediabunny_1.CustomAudioEncoder {
42
44
  data: {
43
45
  numberOfChannels: this.config.numberOfChannels,
44
46
  sampleRate: this.config.sampleRate,
45
- bitrate: this.config.bitrate,
47
+ bitrate: (0, dts_misc_1.clampDtsBitrate)(this.config.bitrate, this.config.sampleRate, this.config.numberOfChannels),
46
48
  },
47
49
  });
48
50
  this.ctx = result.ctx;
@@ -83,54 +85,65 @@ class DtsEncoder extends mediabunny_1.CustomAudioEncoder {
83
85
  }
84
86
  this.pendingBuffer.set(incomingData, this.pendingFrames * channels);
85
87
  this.pendingFrames += incomingFrames;
86
- while (this.pendingFrames >= this.encoderFrameSize) {
87
- await this.encodeOneFrame();
88
+ // Shift the remainder to the front only once at the end, as doing it per frame is quadratic for big samples
89
+ let encodedFrames = 0;
90
+ while (this.pendingFrames - encodedFrames >= this.encoderFrameSize) {
91
+ await this.encodeOneFrame(encodedFrames);
92
+ encodedFrames += this.encoderFrameSize;
88
93
  }
94
+ this.pendingBuffer.copyWithin(0, encodedFrames * channels, this.pendingFrames * channels);
95
+ this.pendingFrames -= encodedFrames;
89
96
  }
90
97
  async flush() {
91
- // Pad remaining samples with silence to fill a full frame
92
- if (this.pendingFrames > 0) {
98
+ // Pad with enough silence to push the remaining samples through the codec delay and to fill up the last frame
99
+ if (this.nextSampleTimestampInSamples !== null) {
93
100
  const channels = this.numberOfChannels;
94
101
  const frameSize = this.encoderFrameSize;
95
- const usedSamples = this.pendingFrames * channels;
96
- const frameSamples = frameSize * channels;
97
- this.pendingBuffer.fill(0, usedSamples, frameSamples);
98
- this.pendingFrames = frameSize;
99
- await this.encodeOneFrame();
102
+ const paddedFrames = Math.ceil((this.pendingFrames + CODEC_DELAY) / frameSize) * frameSize;
103
+ this.pendingBuffer.fill(0, this.pendingFrames * channels, paddedFrames * channels);
104
+ for (let startFrame = 0; startFrame < paddedFrames; startFrame += frameSize) {
105
+ await this.encodeOneFrame(startFrame);
106
+ }
100
107
  }
101
- await (0, worker_client_1.sendCommand)({ type: 'flush-encoder', data: { ctx: this.ctx } });
108
+ // FFmpeg's DTS encoder doesn't hold back any frames, so there's nothing to flush out of it
109
+ await this.inFlightEncode;
110
+ this.inFlightEncode = null;
102
111
  this.resetInternalState();
103
112
  }
104
113
  close() {
105
114
  // Close shouldn't throw
106
- (0, worker_client_1.sendCommand)({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => { });
115
+ if (this.ctx !== null) {
116
+ (0, worker_client_1.sendCommand)({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => { });
117
+ }
107
118
  void (0, worker_client_1.unrefWorker)();
108
119
  }
109
- async encodeOneFrame() {
120
+ async encodeOneFrame(startFrame) {
121
+ (0, shared_1.assert)(this.ctx !== null);
110
122
  (0, shared_1.assert)(this.nextSampleTimestampInSamples !== null);
111
123
  const channels = this.numberOfChannels;
112
124
  const frameSize = this.encoderFrameSize;
113
- const frameSamples = frameSize * channels;
114
- const frameData = this.pendingBuffer.slice(0, frameSamples);
115
- // Shift remaining using copyWithin
116
- this.pendingFrames -= frameSize;
117
- if (this.pendingFrames > 0) {
118
- this.pendingBuffer.copyWithin(0, frameSamples, frameSamples + this.pendingFrames * channels);
119
- }
125
+ const frameData = this.pendingBuffer.slice(startFrame * channels, (startFrame + frameSize) * channels);
120
126
  const audioData = frameData.buffer;
121
- const result = await (0, worker_client_1.sendCommand)({
127
+ const encode = (0, worker_client_1.sendCommand)({
122
128
  type: 'encode',
123
129
  data: {
124
130
  ctx: this.ctx,
125
131
  audioData,
126
- timestamp: this.nextSampleTimestampInSamples,
132
+ // Shifted back by the codec delay so that the decoded audio lines up with the input
133
+ timestamp: this.nextSampleTimestampInSamples - CODEC_DELAY,
127
134
  },
128
- }, [audioData]);
135
+ }, [audioData]).then((result) => {
136
+ // We always get exactly one packet because we encode the correct frame size
137
+ const packet = new mediabunny_1.EncodedPacket(new Uint8Array(result.encodedData), 'key', result.pts / this.sampleRate, result.duration / this.sampleRate);
138
+ this.onPacket(packet, this.chunkMetadata);
139
+ this.chunkMetadata = {};
140
+ });
141
+ encode.catch(() => { }); // Surfaces through whoever awaits it next
129
142
  this.nextSampleTimestampInSamples += frameSize;
130
- // We always get exactly one packet because we encode the correct frame size
131
- const packet = new mediabunny_1.EncodedPacket(new Uint8Array(result.encodedData), 'key', result.pts / this.sampleRate, result.duration / this.sampleRate);
132
- this.onPacket(packet, this.chunkMetadata);
133
- this.chunkMetadata = {};
143
+ // Keep one frame in flight, so the worker already has the next frame by the time it's done with the current one
144
+ const previousEncode = this.inFlightEncode;
145
+ this.inFlightEncode = encode;
146
+ await previousEncode;
134
147
  }
135
148
  }
136
149
  let registered = false;
@@ -39,11 +39,6 @@ export type WorkerCommand = {
39
39
  audioData: ArrayBuffer;
40
40
  timestamp: number;
41
41
  };
42
- } | {
43
- type: 'flush-encoder';
44
- data: {
45
- ctx: number;
46
- };
47
42
  } | {
48
43
  type: 'close-encoder';
49
44
  data: {
@@ -75,8 +70,6 @@ export type WorkerResponseData = {
75
70
  encodedData: ArrayBuffer;
76
71
  pts: number;
77
72
  duration: number;
78
- } | {
79
- type: 'flush-encoder';
80
73
  } | {
81
74
  type: 'close-encoder';
82
75
  };
@@ -1 +1 @@
1
- {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../../src/shared.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,MAAM,aAAa,GAAG;IA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AC;CACjB,GAAG;IACH,IAAI,EAAE,eAAe,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC5B,EAAE,EAAE,MAAM,CAAC;CACX,GAAG,CAAC;IACJ,OAAO,EAAE,IAAI,CAAC;IACd,IAAI,EAAE,kBAAkB,CAAC;CACzB,GAAG;IACH,OAAO,EAAE,KAAK,CAAC;IACf,KAAK,EAAE,OAAO,CAAC;CACf,CAAC,CAAC;AAEH,wBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAI5C"}
@@ -36,7 +36,7 @@ const unrefWorker = async () => {
36
36
  clearInterval(keepAliveInterval);
37
37
  keepAliveInterval = null;
38
38
  }
39
- const worker = await workerPromise;
39
+ const worker = await workerPromise?.catch(() => null);
40
40
  if (worker) {
41
41
  if (workerError) {
42
42
  // The failed worker was already terminated. With nobody using it anymore, the next ref can start fresh
@@ -78,8 +78,15 @@ const sendCommand = async (command, transferables) => {
78
78
  exports.sendCommand = sendCommand;
79
79
  const ensureWorker = () => {
80
80
  return workerPromise ??= (async () => {
81
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
82
- const worker = (await (0, codec_worker_1.default)());
81
+ let worker;
82
+ try {
83
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
84
+ worker = (await (0, codec_worker_1.default)());
85
+ }
86
+ catch (error) {
87
+ workerPromise = null; // So that the next use tries again
88
+ throw error;
89
+ }
83
90
  worker.unref?.(); // Start unreffed
84
91
  const onMessage = (data) => {
85
92
  const pending = pendingMessages.get(data.id);