libopus-wasm 0.4.1 → 0.5.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,25 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.5.1 - 2026-12-05
6
+
7
+ **Highlights:** Keep encoder application state accurate and reject empty batches on freed codecs, with clearer browser capture diagnostics.
8
+
9
+ - Keep `encoder.application` in sync with successful raw application changes.
10
+ - Empty PCM and packet batches now reject calls on a freed codec handle, matching single-frame operations.
11
+ - Report silent capture in the browser tone example when the decoded packets contain no audible signal.
12
+ - Correct the numeric Opus bandwidth constants in the encoder tuning guide.
13
+ - Retry GitHub Pages deployments using the site artifact from the successful build. A full rebuild uploads a new artifact for that attempt.
14
+ - Pin the reusable npm release workflow so retries find existing drafts and validate every release/asset listing page before writing.
15
+
16
+ ## 0.5.0 - 2026-11-03
17
+
18
+ - Add encoder/decoder `reset()` for independent streams without reallocating codec handles; preserve configured settings.
19
+ - Support module Workers explicitly in the WASM build, with a Chromium-tested AudioWorklet capture/Worker example and a Prism demux-to-PCM example.
20
+ - Add zero-dependency and browser bundle size guards, plus an allocation/latency profiling command. Clarify asynchronous Discord compatibility.
21
+ - Resolve canonical URLs relative to each generated page when building nested documentation without a CNAME.
22
+ - Bound encoder scratch capacity to libopus's effective packet budget so large `maxPacketBytes` ceilings cannot exhaust the WebAssembly stack on long frames.
23
+
5
24
  ## 0.4.1 - 2026-09-24
6
25
 
7
26
  **Highlights:** Safer numeric settings and codec initialization, with accurate guidance for decoder output formats.
package/README.md CHANGED
@@ -16,7 +16,7 @@ packets, no Ogg/WebM container layer.
16
16
  - **Int16 and Float32 PCM** — use whatever your pipeline already speaks.
17
17
  - **Loss-resilient** — in-band FEC and packet-loss concealment.
18
18
  - **Tunable** — bitrate, VBR/CBR, complexity, signal, bandwidth, DTX, plus a curated CTL passthrough.
19
- - **Drop-in `@discordjs/opus` adapter** — same method shape, no node-gyp.
19
+ - **Async `@discordjs/opus`-style adapter** — familiar methods, no node-gyp.
20
20
 
21
21
  📖 **Full documentation: [libopus-wasm.dev](https://libopus-wasm.dev)**
22
22
 
@@ -1 +1 @@
1
- {"version":3,"file":"discordjs.d.ts","sourceRoot":"","sources":["../src/discordjs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIrC,qBAAa,WAAW;;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAM9B,YAAY,IAAI,SAAS,EAAE,QAAQ,SAAI,EAqCtC;IAED,OAAa,MAAM,CAAC,IAAI,SAAS,EAAE,QAAQ,SAAI,GAAG,OAAO,CAAC,WAAW,CAAC,CAIrE;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAIvC;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAIvC;IAED,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAEhD;IAED,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAEhD;IAED,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAEhC;IAED,UAAU,IAAI,MAAM,CAEnB;IAED,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAE7B;IAED,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAE/B;IAED,IAAI,IAAI,IAAI,CAOX;IAED,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,CAEvB;CAwBF"}
1
+ {"version":3,"file":"discordjs.d.ts","sourceRoot":"","sources":["../src/discordjs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIrC,qBAAa,WAAW;;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAM9B,YAAY,IAAI,SAAS,EAAE,QAAQ,SAAI,EAqCtC;IAED,OAAa,MAAM,CAAC,IAAI,SAAS,EAAE,QAAQ,SAAI,GAAG,OAAO,CAAC,WAAW,CAAC,CAIrE;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAKvC;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAIvC;IAED,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAEhD;IAED,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAEhD;IAED,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAEhC;IAED,UAAU,IAAI,MAAM,CAEnB;IAED,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAE7B;IAED,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAE/B;IAED,IAAI,IAAI,IAAI,CAOX;IAED,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,CAEvB;CAWF"}
package/dist/discordjs.js CHANGED
@@ -52,32 +52,33 @@ export class OpusEncoder {
52
52
  return encoder;
53
53
  }
54
54
  encode(buf) {
55
- const encoder = this.#requireEncoder();
55
+ const encoder = this.#requireCodec(this.#encoder);
56
56
  const frameSize = inferFrameSize(buf.byteLength, this.channels);
57
- return Buffer.from(encoder.encode(buf, { frameSize }));
57
+ const packet = encoder.encode(buf, { frameSize });
58
+ return Buffer.from(packet.buffer, packet.byteOffset, packet.byteLength);
58
59
  }
59
60
  decode(buf) {
60
- const decoder = this.#requireDecoder();
61
+ const decoder = this.#requireCodec(this.#decoder);
61
62
  const pcm = decoder.decode(buf);
62
63
  return Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength);
63
64
  }
64
65
  applyEncoderCTL(ctl, value) {
65
- this.#requireEncoder().encoderCtl(ctl, value);
66
+ this.#requireCodec(this.#encoder).encoderCtl(ctl, value);
66
67
  }
67
68
  applyDecoderCTL(ctl, value) {
68
- this.#requireDecoder().decoderCtl(ctl, value);
69
+ this.#requireCodec(this.#decoder).decoderCtl(ctl, value);
69
70
  }
70
71
  setBitrate(bitrate) {
71
- this.#requireEncoder().setBitrate(bitrate);
72
+ this.#requireCodec(this.#encoder).setBitrate(bitrate);
72
73
  }
73
74
  getBitrate() {
74
- return this.#requireEncoder().getBitrate();
75
+ return this.#requireCodec(this.#encoder).getBitrate();
75
76
  }
76
77
  setFEC(enabled) {
77
- this.#requireEncoder().setFec(enabled);
78
+ this.#requireCodec(this.#encoder).setFec(enabled);
78
79
  }
79
80
  setPLP(percentage) {
80
- this.#requireEncoder().setPacketLossPercent(percentage);
81
+ this.#requireCodec(this.#encoder).setPacketLossPercent(percentage);
81
82
  }
82
83
  free() {
83
84
  if (this.#freed) {
@@ -90,25 +91,14 @@ export class OpusEncoder {
90
91
  [Symbol.dispose]() {
91
92
  this.free();
92
93
  }
93
- #requireEncoder() {
94
- this.#throwInitErrorIfAny();
95
- if (!this.#encoder || this.#freed) {
96
- throw new Error("OpusEncoder is not ready; await encoder.ready or use OpusEncoder.create()");
94
+ #requireCodec(codec) {
95
+ if (this.#initError) {
96
+ throw new Error("OpusEncoder failed to initialize", { cause: this.#initError });
97
97
  }
98
- return this.#encoder;
99
- }
100
- #requireDecoder() {
101
- this.#throwInitErrorIfAny();
102
- if (!this.#decoder || this.#freed) {
98
+ if (!codec || this.#freed) {
103
99
  throw new Error("OpusEncoder is not ready; await encoder.ready or use OpusEncoder.create()");
104
100
  }
105
- return this.#decoder;
106
- }
107
- #throwInitErrorIfAny() {
108
- if (!this.#initError) {
109
- return;
110
- }
111
- throw new Error("OpusEncoder failed to initialize", { cause: this.#initError });
101
+ return codec;
112
102
  }
113
103
  }
114
104
  function inferFrameSize(byteLength, channels) {
package/dist/index.d.ts CHANGED
@@ -98,6 +98,8 @@ export type OpusEncoderHandle = {
98
98
  encodeFrames(frames: readonly (Int16Array | Uint8Array)[], options?: EncodeOptions): Uint8Array[];
99
99
  encodeFloatFrames(frames: readonly Float32Array[], options?: EncodeOptions): Uint8Array[];
100
100
  encoderCtl(request: number, value: number): void;
101
+ /** Clear stream history while preserving the configured encoder settings. */
102
+ reset(): void;
101
103
  free(): void;
102
104
  getBitrate(): number;
103
105
  getInDtx(): boolean;
@@ -124,6 +126,8 @@ export type OpusDecoderHandle = {
124
126
  decodePacketLoss(frameSize?: number): Int16Array;
125
127
  decodePacketLossFloat(frameSize?: number): Float32Array;
126
128
  decoderCtl(request: number, value: number): void;
129
+ /** Clear stream history before decoding an independent stream. */
130
+ reset(): void;
127
131
  free(): void;
128
132
  [Symbol.dispose](): void;
129
133
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,WAAW;aACtB,IAAI,EAAE,IAAI;aACV,KAAK,EAAE,IAAI;aACX,kBAAkB,EAAE,IAAI;CAChB,CAAC;AAEX,eAAO,MAAM,MAAM;aACjB,IAAI,EAAE,CAAC,IAAI;aACX,KAAK,EAAE,IAAI;aACX,KAAK,EAAE,IAAI;CACH,CAAC;AAEX,eAAO,MAAM,OAAO;aAClB,IAAI,EAAE,CAAC,IAAI;aACX,GAAG,EAAE,CAAC,CAAC;CACC,CAAC;AAEX,eAAO,MAAM,SAAS;aACpB,UAAU,EAAE,IAAI;aAChB,UAAU,EAAE,IAAI;aAChB,QAAQ,EAAE,IAAI;aACd,aAAa,EAAE,IAAI;aACnB,QAAQ,EAAE,IAAI;CACN,CAAC;AA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;AAED,wBAAsB,aAAa,CAAC,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAG5F;AAED,wBAAsB,aAAa,CAAC,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAG5F;AAED,wBAAsB,aAAa,CACjC,MAAM,EAAE,UAAU,EAClB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,cAAc,CAAC,CA8BzB;AAmXD,qBAAa,SAAU,SAAQ,KAAK;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACjD,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAEvC,YAAY,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,EAM5D;CACF;AAED,eAAO,MAAM,aAAa;aACxB,MAAM,EAAE,CAAC,CAAC;aACV,cAAc,EAAE,CAAC,CAAC;aAClB,aAAa,EAAE,CAAC,CAAC;aACjB,aAAa,EAAE,CAAC,CAAC;aACjB,aAAa,EAAE,CAAC,CAAC;aACjB,YAAY,EAAE,CAAC,CAAC;aAChB,SAAS,EAAE,CAAC,CAAC;CACL,CAAC;AAEX,MAAM,MAAM,iBAAiB,GAAG,MAAM,OAAO,aAAa,CAAC;AAE3D,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAoB9D"}
package/dist/index.js CHANGED
@@ -46,6 +46,7 @@ const DEFAULT_CHANNELS = 2;
46
46
  const DEFAULT_FRAME_DURATION_MS = 20;
47
47
  const MAX_PACKET_DURATION_MS = 120;
48
48
  const DEFAULT_MAX_PACKET_BYTES = 4000;
49
+ const MAX_ENCODER_PACKET_BYTES = 1276 * 6;
49
50
  const MIN_I32 = -0x8000_0000;
50
51
  const MAX_I32 = 0x7fff_ffff;
51
52
  const DEFAULT_SAMPLE_RATE = 48_000;
@@ -56,7 +57,7 @@ const VALID_SAMPLE_RATES = [8000, 12000, 16000, 24000, 48000];
56
57
  let modulePromise;
57
58
  export async function loadLibopus() {
58
59
  const module = await getModule();
59
- return { version: module.UTF8ToString(module._oc_get_version_string()) };
60
+ return { version: module.UTF8ToString(module._opus_get_version_string()) };
60
61
  }
61
62
  export async function createEncoder(options = {}) {
62
63
  const module = await getModule();
@@ -76,34 +77,21 @@ export async function getPacketInfo(packet, options = {}) {
76
77
  const packetPtr = checkedMalloc(module, packet.byteLength);
77
78
  try {
78
79
  module.HEAPU8.set(packet, packetPtr);
79
- const decodedSamples = module._oc_packet_validate_decode(packetPtr, packet.byteLength, sampleRate);
80
- if (decodedSamples < 0) {
81
- throw createOpusError(module, decodedSamples, "getPacketInfo");
82
- }
83
- const frames = module._oc_packet_parse(packetPtr, packet.byteLength);
84
- if (frames < 0) {
85
- throw createOpusError(module, frames, "getPacketInfo");
86
- }
87
- const samples = module._oc_packet_get_nb_samples(packetPtr, packet.byteLength, sampleRate);
88
- if (samples < 0) {
89
- throw createOpusError(module, samples, "getPacketInfo");
90
- }
91
- const channels = module._oc_packet_get_nb_channels(packetPtr);
80
+ const samples = checkOpusResult(module, module._oc_packet_validate_decode(packetPtr, packet.byteLength, sampleRate), "getPacketInfo");
81
+ const samplesPerFrame = module._opus_packet_get_samples_per_frame(packetPtr, sampleRate);
82
+ const channels = module._opus_packet_get_nb_channels(packetPtr);
92
83
  if (channels !== 1 && channels !== 2) {
93
84
  throw new OpusError(channels, `libopus getPacketInfo failed (${channels}): invalid channel count`);
94
85
  }
95
- const bandwidth = module._oc_packet_get_bandwidth(packetPtr);
96
- if (bandwidth < 0) {
97
- throw createOpusError(module, bandwidth, "getPacketInfo");
98
- }
86
+ const bandwidth = checkOpusResult(module, module._opus_packet_get_bandwidth(packetPtr), "getPacketInfo");
99
87
  validateBandwidth(bandwidth, "packet bandwidth");
100
88
  return {
101
89
  bandwidth: bandwidth,
102
90
  channels,
103
91
  durationMs: (samples / sampleRate) * 1000,
104
- frames,
92
+ frames: samples / samplesPerFrame,
105
93
  samples,
106
- samplesPerFrame: module._oc_packet_get_samples_per_frame(packetPtr, sampleRate),
94
+ samplesPerFrame,
107
95
  sampleRate,
108
96
  };
109
97
  }
@@ -154,19 +142,7 @@ class WasmOpusEncoder {
154
142
  this.channels = options.channels;
155
143
  this.frameSize = options.frameSize;
156
144
  this.sampleRate = options.sampleRate;
157
- const errorPtr = checkedMalloc(module, 4);
158
- try {
159
- const ptr = module._oc_create_encoder(options.sampleRate, options.channels, options.application, errorPtr);
160
- const error = module.HEAP32[errorPtr >> 2] ?? 0;
161
- if (!ptr || error !== 0) {
162
- throw createOpusError(module, error, "createEncoder");
163
- }
164
- this.#ptr = ptr;
165
- }
166
- finally {
167
- module._free(errorPtr);
168
- }
169
- let configured = false;
145
+ this.#ptr = createCodecHandle(module, "createEncoder", (errorPtr) => module._opus_encoder_create(options.sampleRate, options.channels, options.application, errorPtr));
170
146
  try {
171
147
  this.setBitrate(options.bitrate);
172
148
  this.setComplexity(options.complexity);
@@ -183,57 +159,55 @@ class WasmOpusEncoder {
183
159
  if (options.vbrConstraint !== undefined) {
184
160
  this.setVbrConstraint(options.vbrConstraint);
185
161
  }
186
- configured = true;
187
162
  }
188
- finally {
189
- if (!configured) {
190
- this.free();
191
- }
163
+ catch (error) {
164
+ this.free();
165
+ throw error;
192
166
  }
193
167
  }
194
168
  encode(pcm, options = {}) {
195
- this.#assertLive();
196
- const frameSize = options.frameSize ?? this.frameSize;
197
- validateEncodeFrameSize(frameSize, this.sampleRate, "frameSize");
198
- const pcmBytes = toUint8Array(pcm);
199
- const expectedBytes = frameSize * this.channels * 2;
200
- if (pcmBytes.byteLength !== expectedBytes) {
201
- throw new RangeError(`PCM frame has ${pcmBytes.byteLength} bytes; expected ${expectedBytes} for ${frameSize} samples and ${this.channels} channel(s)`);
202
- }
203
- const maxPacketBytes = options.maxPacketBytes ?? DEFAULT_MAX_PACKET_BYTES;
204
- validateIntegerRange(maxPacketBytes, 1, MAX_I32, "maxPacketBytes");
205
- const pcmPtr = this.#pcm.ensure(pcmBytes.byteLength);
206
- const packetPtr = this.#packet.ensure(maxPacketBytes);
207
- this.#module.HEAPU8.set(pcmBytes, pcmPtr);
208
- const encodedBytes = this.#module._oc_encode(this.#ptr, pcmPtr, frameSize, packetPtr, maxPacketBytes);
209
- if (encodedBytes < 0) {
210
- throw createOpusError(this.#module, encodedBytes, "encode");
211
- }
212
- return this.#module.HEAPU8.slice(packetPtr, packetPtr + encodedBytes);
169
+ return this.#encode(pcm, options, false);
213
170
  }
214
171
  encodeFloat(pcm, options = {}) {
172
+ return this.#encode(pcm, options, true);
173
+ }
174
+ #encode(pcm, options, float) {
215
175
  this.#assertLive();
216
176
  const frameSize = options.frameSize ?? this.frameSize;
217
- validateEncodeFrameSize(frameSize, this.sampleRate, "frameSize");
177
+ validateEncodeFrameSize(frameSize, this.sampleRate);
178
+ const input = float ? pcm : toUint8Array(pcm);
218
179
  const expectedSamples = frameSize * this.channels;
219
- if (pcm.length !== expectedSamples) {
220
- throw new RangeError(`Float32 PCM frame has ${pcm.length} samples; expected ${expectedSamples} for ${frameSize} samples and ${this.channels} channel(s)`);
180
+ if (float) {
181
+ if (input.length !== expectedSamples) {
182
+ throw new RangeError(`Float32 PCM frame has ${input.length} samples; expected ${expectedSamples} for ${frameSize} samples and ${this.channels} channel(s)`);
183
+ }
184
+ }
185
+ else if (input.byteLength !== expectedSamples * 2) {
186
+ throw new RangeError(`PCM frame has ${input.byteLength} bytes; expected ${expectedSamples * 2} for ${frameSize} samples and ${this.channels} channel(s)`);
221
187
  }
222
188
  const maxPacketBytes = options.maxPacketBytes ?? DEFAULT_MAX_PACKET_BYTES;
223
189
  validateIntegerRange(maxPacketBytes, 1, MAX_I32, "maxPacketBytes");
224
- const pcmPtr = this.#pcm.ensure(pcm.byteLength);
225
- const packetPtr = this.#packet.ensure(maxPacketBytes);
226
- this.#module.HEAPF32.set(pcm, pcmPtr >> 2);
227
- const encodedBytes = this.#module._oc_encode_float(this.#ptr, pcmPtr, frameSize, packetPtr, maxPacketBytes);
228
- if (encodedBytes < 0) {
229
- throw createOpusError(this.#module, encodedBytes, "encodeFloat");
230
- }
190
+ // libopus 1.6.1 caps its effective budget at 1276 * 6, but long-frame
191
+ // repacketization allocates stack scratch from the supplied capacity.
192
+ const packetCapacity = Math.min(maxPacketBytes, MAX_ENCODER_PACKET_BYTES);
193
+ const pcmPtr = this.#pcm.ensure(input.byteLength);
194
+ const packetPtr = this.#packet.ensure(packetCapacity);
195
+ // Allocations can replace heap views; keep format-specific writes after both.
196
+ if (float) {
197
+ this.#module.HEAPF32.set(input, pcmPtr >> 2);
198
+ }
199
+ else {
200
+ this.#module.HEAPU8.set(input, pcmPtr);
201
+ }
202
+ const encodedBytes = checkOpusResult(this.#module, this.#module[float ? "_opus_encode_float" : "_opus_encode"](this.#ptr, pcmPtr, frameSize, packetPtr, packetCapacity), float ? "encodeFloat" : "encode");
231
203
  return this.#module.HEAPU8.slice(packetPtr, packetPtr + encodedBytes);
232
204
  }
233
205
  encodeFrames(frames, options = {}) {
206
+ this.#assertLive();
234
207
  return frames.map((frame) => this.encode(frame, options));
235
208
  }
236
209
  encodeFloatFrames(frames, options = {}) {
210
+ this.#assertLive();
237
211
  return frames.map((frame) => this.encodeFloat(frame, options));
238
212
  }
239
213
  encoderCtl(request, value) {
@@ -243,33 +217,25 @@ class WasmOpusEncoder {
243
217
  if (!ENCODER_INTEGER_CTL_REQUESTS.has(request)) {
244
218
  throw new RangeError("encoderCtl only supports integer setter requests");
245
219
  }
246
- this.#check(this.#module._oc_encoder_ctl(this.#ptr, request, value), "encoderCtl");
220
+ checkOpusResult(this.#module, this.#module._oc_encoder_ctl(this.#ptr, request, value), "encoderCtl");
221
+ if (request === EncoderCtl.SetApplication && isApplication(value)) {
222
+ this.application = value;
223
+ }
247
224
  }
248
225
  setBitrate(bitrate) {
249
226
  this.encoderCtl(EncoderCtl.SetBitrate, normalizeBitrate(bitrate));
250
227
  }
251
228
  getBitrate() {
252
229
  this.#assertLive();
253
- const bitrate = this.#module._oc_encoder_ctl_get_bitrate(this.#ptr);
254
- if (bitrate < 0) {
255
- throw createOpusError(this.#module, bitrate, "getBitrate");
256
- }
257
- return bitrate;
230
+ return checkOpusResult(this.#module, this.#module._oc_encoder_ctl_get_bitrate(this.#ptr), "getBitrate");
258
231
  }
259
232
  getLookahead() {
260
233
  this.#assertLive();
261
- const lookahead = this.#module._oc_encoder_ctl_get_lookahead(this.#ptr);
262
- if (lookahead < 0) {
263
- throw createOpusError(this.#module, lookahead, "getLookahead");
264
- }
265
- return lookahead;
234
+ return checkOpusResult(this.#module, this.#module._oc_encoder_ctl_get_lookahead(this.#ptr), "getLookahead");
266
235
  }
267
236
  getInDtx() {
268
237
  this.#assertLive();
269
- const inDtx = this.#module._oc_encoder_ctl_get_in_dtx(this.#ptr);
270
- if (inDtx < 0) {
271
- throw createOpusError(this.#module, inDtx, "getInDtx");
272
- }
238
+ const inDtx = checkOpusResult(this.#module, this.#module._oc_encoder_ctl_get_in_dtx(this.#ptr), "getInDtx");
273
239
  return inDtx !== 0;
274
240
  }
275
241
  setComplexity(complexity) {
@@ -302,13 +268,17 @@ class WasmOpusEncoder {
302
268
  setVbrConstraint(enabled) {
303
269
  this.encoderCtl(EncoderCtl.SetVbrConstraint, enabled ? 1 : 0);
304
270
  }
271
+ reset() {
272
+ this.#assertLive();
273
+ checkOpusResult(this.#module, this.#module._oc_reset_encoder(this.#ptr), "resetEncoder");
274
+ }
305
275
  free() {
306
276
  if (this.#freed) {
307
277
  return;
308
278
  }
309
279
  this.#packet.free();
310
280
  this.#pcm.free();
311
- this.#module._oc_destroy_encoder(this.#ptr);
281
+ this.#module._opus_encoder_destroy(this.#ptr);
312
282
  this.#freed = true;
313
283
  }
314
284
  [Symbol.dispose]() {
@@ -319,11 +289,6 @@ class WasmOpusEncoder {
319
289
  throw new Error("OpusEncoder has been freed");
320
290
  }
321
291
  }
322
- #check(code, operation) {
323
- if (code < 0) {
324
- throw createOpusError(this.#module, code, operation);
325
- }
326
- }
327
292
  }
328
293
  class WasmOpusDecoder {
329
294
  channels;
@@ -341,49 +306,35 @@ class WasmOpusDecoder {
341
306
  this.channels = options.channels;
342
307
  this.maxFrameSize = options.maxFrameSize;
343
308
  this.sampleRate = options.sampleRate;
344
- const errorPtr = checkedMalloc(module, 4);
345
- try {
346
- const ptr = module._oc_create_decoder(options.sampleRate, options.channels, errorPtr);
347
- const error = module.HEAP32[errorPtr >> 2] ?? 0;
348
- if (!ptr || error !== 0) {
349
- throw createOpusError(module, error, "createDecoder");
350
- }
351
- this.#ptr = ptr;
352
- }
353
- finally {
354
- module._free(errorPtr);
355
- }
309
+ this.#ptr = createCodecHandle(module, "createDecoder", (errorPtr) => module._opus_decoder_create(options.sampleRate, options.channels, errorPtr));
356
310
  }
357
311
  decode(packet, options = {}) {
358
- this.#assertLive();
359
- const frameSize = this.#resolveDecodeFrameSize(packet, options);
360
- const pcmBytes = frameSize * this.channels * 2;
361
- const pcmPtr = this.#pcm.ensure(pcmBytes);
362
- const { packetLength, packetPtr } = this.#copyPacket(packet, options.decodeFec);
363
- const decodedSamples = this.#module._oc_decode(this.#ptr, packetPtr, packetLength, pcmPtr, frameSize, options.decodeFec ? 1 : 0);
364
- if (decodedSamples < 0) {
365
- throw createOpusError(this.#module, decodedSamples, packet === null ? "decodePacketLoss" : "decode");
366
- }
367
- const sampleCount = decodedSamples * this.channels;
368
- return this.#module.HEAP16.slice(pcmPtr >> 1, (pcmPtr >> 1) + sampleCount);
312
+ return this.#decode(packet, options, false);
369
313
  }
370
314
  decodeFloat(packet, options = {}) {
315
+ return this.#decode(packet, options, true);
316
+ }
317
+ #decode(packet, options, float) {
371
318
  this.#assertLive();
372
319
  const frameSize = this.#resolveDecodeFrameSize(packet, options);
373
- const pcmBytes = frameSize * this.channels * 4;
374
- const pcmPtr = this.#pcm.ensure(pcmBytes);
320
+ const pcmPtr = this.#pcm.ensure(frameSize * this.channels * (float ? 4 : 2));
375
321
  const { packetLength, packetPtr } = this.#copyPacket(packet, options.decodeFec);
376
- const decodedSamples = this.#module._oc_decode_float(this.#ptr, packetPtr, packetLength, pcmPtr, frameSize, options.decodeFec ? 1 : 0);
377
- if (decodedSamples < 0) {
378
- throw createOpusError(this.#module, decodedSamples, packet === null ? "decodePacketLossFloat" : "decodeFloat");
379
- }
322
+ const operation = packet === null
323
+ ? (float ? "decodePacketLossFloat" : "decodePacketLoss")
324
+ : (float ? "decodeFloat" : "decode");
325
+ const decodedSamples = checkOpusResult(this.#module, this.#module[float ? "_opus_decode_float" : "_opus_decode"](this.#ptr, packetPtr, packetLength, pcmPtr, frameSize, options.decodeFec ? 1 : 0), operation);
380
326
  const sampleCount = decodedSamples * this.channels;
381
- return this.#module.HEAPF32.slice(pcmPtr >> 2, (pcmPtr >> 2) + sampleCount);
327
+ // Read the current heap after native decoding and return an owned copy.
328
+ return float
329
+ ? this.#module.HEAPF32.slice(pcmPtr >> 2, (pcmPtr >> 2) + sampleCount)
330
+ : this.#module.HEAP16.slice(pcmPtr >> 1, (pcmPtr >> 1) + sampleCount);
382
331
  }
383
332
  decodeFrames(packets, options = {}) {
333
+ this.#assertLive();
384
334
  return packets.map((packet) => this.decode(packet, options));
385
335
  }
386
336
  decodeFloatFrames(packets, options = {}) {
337
+ this.#assertLive();
387
338
  return packets.map((packet) => this.decodeFloat(packet, options));
388
339
  }
389
340
  decodePacketLoss(frameSize = samplesForDuration(this.sampleRate, DEFAULT_FRAME_DURATION_MS)) {
@@ -399,10 +350,11 @@ class WasmOpusDecoder {
399
350
  if (!DECODER_INTEGER_CTL_REQUESTS.has(request)) {
400
351
  throw new RangeError("decoderCtl only supports integer setter requests");
401
352
  }
402
- const code = this.#module._oc_decoder_ctl(this.#ptr, request, value);
403
- if (code < 0) {
404
- throw createOpusError(this.#module, code, "decoderCtl");
405
- }
353
+ checkOpusResult(this.#module, this.#module._oc_decoder_ctl(this.#ptr, request, value), "decoderCtl");
354
+ }
355
+ reset() {
356
+ this.#assertLive();
357
+ checkOpusResult(this.#module, this.#module._oc_reset_decoder(this.#ptr), "resetDecoder");
406
358
  }
407
359
  free() {
408
360
  if (this.#freed) {
@@ -410,7 +362,7 @@ class WasmOpusDecoder {
410
362
  }
411
363
  this.#packet.free();
412
364
  this.#pcm.free();
413
- this.#module._oc_destroy_decoder(this.#ptr);
365
+ this.#module._opus_decoder_destroy(this.#ptr);
414
366
  this.#freed = true;
415
367
  }
416
368
  [Symbol.dispose]() {
@@ -494,24 +446,33 @@ function resolveOpusErrorCodeName(code) {
494
446
  return undefined;
495
447
  }
496
448
  function createOpusError(module, code, operation) {
497
- const message = module.UTF8ToString(module._oc_strerror(code));
449
+ const message = module.UTF8ToString(module._opus_strerror(code));
498
450
  return new OpusError(code, `libopus ${operation} failed (${code}): ${message}`, operation);
499
451
  }
452
+ function checkOpusResult(module, code, operation) {
453
+ if (code < 0) {
454
+ throw createOpusError(module, code, operation);
455
+ }
456
+ return code;
457
+ }
500
458
  function toUint8Array(input) {
501
459
  return input instanceof Uint8Array
502
460
  ? input
503
461
  : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
504
462
  }
463
+ function isApplication(value) {
464
+ return Object.values(Application).some((mode) => mode === value);
465
+ }
505
466
  function normalizeEncoderOptions(options) {
506
467
  const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
507
468
  const channels = options.channels ?? DEFAULT_CHANNELS;
508
469
  validateCodecOptions({ channels, sampleRate });
509
470
  const application = options.application ?? Application.Audio;
510
- if (!Object.values(Application).includes(application)) {
471
+ if (!isApplication(application)) {
511
472
  throw new RangeError("application must be Application.Voip, Application.Audio, or Application.RestrictedLowDelay");
512
473
  }
513
474
  const frameSize = options.frameSize ?? samplesForDuration(sampleRate, DEFAULT_FRAME_DURATION_MS);
514
- validateEncodeFrameSize(frameSize, sampleRate, "frameSize");
475
+ validateEncodeFrameSize(frameSize, sampleRate);
515
476
  if (options.maxBandwidth !== undefined) {
516
477
  validateBandwidth(options.maxBandwidth, "maxBandwidth");
517
478
  }
@@ -576,8 +537,11 @@ function validateBandwidth(bandwidth, name) {
576
537
  throw new RangeError(`${name} must be Bandwidth.Narrowband, Bandwidth.Mediumband, Bandwidth.Wideband, Bandwidth.Superwideband, or Bandwidth.Fullband`);
577
538
  }
578
539
  }
579
- function validateEncodeFrameSize(frameSize, sampleRate, name) {
580
- validateFrameSizeForDurations(frameSize, sampleRate, name, ENCODE_FRAME_DURATIONS_MS);
540
+ function validateEncodeFrameSize(frameSize, sampleRate) {
541
+ const validFrameSizes = ENCODE_FRAME_DURATIONS_MS.map((durationMs) => samplesForDuration(sampleRate, durationMs));
542
+ if (!Number.isInteger(frameSize) || !validFrameSizes.includes(frameSize)) {
543
+ throw new RangeError(`frameSize must be one of ${validFrameSizes.join(", ")} samples at ${sampleRate} Hz`);
544
+ }
581
545
  }
582
546
  function validateDecodeCapacity(frameSize, sampleRate, name) {
583
547
  const maxFrameSize = samplesForDuration(sampleRate, MAX_PACKET_DURATION_MS);
@@ -595,12 +559,6 @@ function validatePlcFrameSize(frameSize, sampleRate, name) {
595
559
  throw new RangeError(`${name} must be a multiple of ${minFrameSize} samples from ${minFrameSize} to ${maxFrameSize} at ${sampleRate} Hz`);
596
560
  }
597
561
  }
598
- function validateFrameSizeForDurations(frameSize, sampleRate, name, durationsMs) {
599
- const validFrameSizes = durationsMs.map((durationMs) => samplesForDuration(sampleRate, durationMs));
600
- if (!Number.isInteger(frameSize) || !validFrameSizes.includes(frameSize)) {
601
- throw new RangeError(`${name} must be one of ${validFrameSizes.join(", ")} samples at ${sampleRate} Hz`);
602
- }
603
- }
604
562
  function validateInteger(value, name) {
605
563
  if (!Number.isInteger(value)) {
606
564
  throw new RangeError(`${name} must be an integer`);
@@ -611,6 +569,20 @@ function validateIntegerRange(value, min, max, name) {
611
569
  throw new RangeError(`${name} must be an integer from ${min} to ${max}`);
612
570
  }
613
571
  }
572
+ function createCodecHandle(module, operation, create) {
573
+ const errorPtr = checkedMalloc(module, 4);
574
+ try {
575
+ const ptr = create(errorPtr);
576
+ const error = module.HEAP32[errorPtr >> 2] ?? 0;
577
+ if (!ptr || error !== 0) {
578
+ throw createOpusError(module, error, operation);
579
+ }
580
+ return ptr;
581
+ }
582
+ finally {
583
+ module._free(errorPtr);
584
+ }
585
+ }
614
586
  function checkedMalloc(module, bytes) {
615
587
  validateIntegerRange(bytes, 1, MAX_I32, "malloc size");
616
588
  const ptr = module._malloc(bytes);
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "libopus-wasm",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
+ "packageManager": "pnpm@11.27.1",
4
5
  "description": "Small, modern WASM bindings for libopus raw packet encode/decode.",
5
6
  "type": "module",
6
7
  "sideEffects": false,
@@ -32,27 +33,35 @@
32
33
  "CHANGELOG.md",
33
34
  "LICENSE",
34
35
  "README.md",
35
- "THIRD_PARTY_NOTICES.md"
36
+ "THIRD_PARTY_NOTICES.md",
37
+ "scripts/release-smoke.mjs"
36
38
  ],
37
- "devDependencies": {
38
- "@discordjs/opus": "0.10.0",
39
- "@types/node": "26.6.2",
40
- "@vitest/coverage-v8": "5.0.1",
41
- "typescript": "^7.0.2",
42
- "vite": "8.3.0",
43
- "vitest": "5.0.1"
44
- },
45
- "engines": {
46
- "node": ">=22"
47
- },
48
39
  "scripts": {
49
40
  "build": "pnpm build:wasm && tsc -p tsconfig.json && node scripts/copy-generated.mjs",
50
41
  "build:wasm": "node scripts/build-libopus-wasm.mjs",
51
42
  "benchmark": "pnpm build && node scripts/benchmark-native.mjs",
52
43
  "clean": "rm -rf dist .cache",
53
44
  "docs:build": "node scripts/build-docs-site.mjs",
45
+ "prepack": "pnpm build",
54
46
  "test": "pnpm build:wasm && vitest run",
55
47
  "test:coverage": "pnpm build:wasm && vitest run --coverage",
56
- "typecheck": "tsc -p tsconfig.json --noEmit"
48
+ "typecheck": "tsc -p tsconfig.json --noEmit",
49
+ "test:browser": "pnpm build && playwright test",
50
+ "size:check": "node scripts/check-size.mjs",
51
+ "test:integrations": "node scripts/check-integrations.mjs",
52
+ "profile:allocations": "node --expose-gc scripts/profile-allocations.mjs"
53
+ },
54
+ "devDependencies": {
55
+ "@discordjs/opus": "0.10.0",
56
+ "@types/node": "26.6.6",
57
+ "@vitest/coverage-v8": "5.0.3",
58
+ "typescript": "^7.0.2",
59
+ "vite": "8.3.5",
60
+ "vitest": "5.0.3",
61
+ "prism-media": "1.3.5",
62
+ "@playwright/test": "1.64.1"
63
+ },
64
+ "engines": {
65
+ "node": ">=22"
57
66
  }
58
- }
67
+ }
@@ -0,0 +1,38 @@
1
+ import assert from "node:assert/strict";
2
+ import { createDecoder, createEncoder, getPacketInfo } from "libopus-wasm";
3
+ import { OpusEncoder } from "libopus-wasm/discordjs";
4
+
5
+ const encoder = await createEncoder();
6
+ const decoder = await createDecoder();
7
+ try {
8
+ const pcm = makePcm(encoder.frameSize, encoder.channels, encoder.sampleRate);
9
+ const packet = encoder.encode(pcm);
10
+ assert.ok(packet.byteLength > 0);
11
+ assert.equal((await getPacketInfo(packet)).samples, encoder.frameSize);
12
+ decoder.reset();
13
+ const decoded = decoder.decode(packet);
14
+ assert.equal(decoded.length, pcm.length);
15
+ assert.ok(decoded.some((sample) => sample !== 0), "decoded audio must not be silent");
16
+ } finally {
17
+ encoder.free();
18
+ decoder.free();
19
+ }
20
+
21
+ const opus = await OpusEncoder.create(48000, 2);
22
+ try {
23
+ const pcm = Buffer.from(makePcm(960, 2, 48000).buffer);
24
+ const packet = opus.encode(pcm);
25
+ assert.ok(packet.byteLength > 0);
26
+ const decoded = opus.decode(packet);
27
+ assert.equal(decoded.length, pcm.length);
28
+ assert.ok(decoded.some((byte) => byte !== 0), "adapter audio must not be silent");
29
+ } finally {
30
+ opus.free();
31
+ }
32
+ console.log("Packed ESM and Discord adapter encode/decode passed.");
33
+
34
+ function makePcm(frameSize, channels, sampleRate) {
35
+ return Int16Array.from({ length: frameSize * channels }, (_, index) =>
36
+ Math.round(Math.sin((Math.floor(index / channels) * 2 * Math.PI * 440) / sampleRate) * 8000),
37
+ );
38
+ }