libopus-wasm 0.0.1 → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.2.0 - 2026-06-01
6
+
7
+ - Add named Opus error codes, `codeName` metadata, and `isOpusError()` for structured libopus error handling.
8
+ - Add coverage tooling and broaden validation-path tests.
9
+ - Add dedicated docs pages for packet inspection (`getPacketInfo`) and error handling, list `getPacketInfo` in the API reference, and wire both into the site navigation.
10
+
11
+ ## 0.1.0 - 2026-05-26
12
+
13
+ - Initial npm release of `libopus-wasm`, a small ESM-only WebAssembly wrapper around libopus 1.6.1 for raw Opus packet encode/decode in Node 20+ and browsers.
14
+ - Ship a self-contained single-file WASM module with browser and Node support, no `locateFile` hook, no second `.wasm` request, and no native install-time build.
15
+ - Add Discord/WebRTC-ready defaults: 48 kHz, stereo, 20 ms frames, raw packets, `Application.Audio`, 64 kbps, and complexity 10.
16
+ - Add async `loadLibopus()`, `createEncoder()`, `createDecoder()`, and `getPacketInfo()` top-level APIs with one lazily shared WASM module.
17
+ - Add Int16 PCM encode/decode via `encode()` and `decode()`, including `Int16Array` input and `Uint8Array` little-endian PCM input support.
18
+ - Add Float32 PCM encode/decode via `encodeFloat()` and `decodeFloat()` for Web Audio and DSP pipelines.
19
+ - Add batch helpers `encodeFrames()`, `encodeFloatFrames()`, `decodeFrames()`, and `decodeFloatFrames()`.
20
+ - Add raw packet metadata inspection with validation, returning bandwidth, channel count, frame count, sample count, samples per frame, duration, and sample rate.
21
+ - Add packet-loss concealment APIs `decodePacketLoss()`, `decodePacketLossFloat()`, and `decode(null, { frameSize })`.
22
+ - Add in-band FEC support through encoder `fec` / `packetLossPercent` options and decoder `decodeFec` recovery.
23
+ - Add encoder tuning options and setters for application, bitrate, complexity, DTX, FEC, max bandwidth, packet loss percentage, signal, VBR, and constrained VBR.
24
+ - Add encoder state readers `getBitrate()`, `getLookahead()`, and `getInDtx()`.
25
+ - Add curated integer CTL passthroughs with `EncoderCtl`, `DecoderCtl`, `encoderCtl()`, and `decoderCtl()` while rejecting pointer-style getter CTLs at the JS boundary.
26
+ - Add exported constants and types for `Application`, `Signal`, `Bitrate`, `Bandwidth`, `SampleRate`, `ChannelCount`, encoder/decoder options, packet info, handle types, and `OpusError`.
27
+ - Add strict argument validation for supported sample rates, mono/stereo channels, Opus frame durations, packet sizes, PLC/FEC frame sizes, CTL requests, and freed handles.
28
+ - Add deterministic cleanup through `free()` and `[Symbol.dispose]()` on encoder, decoder, and Discord-compatible handles.
29
+ - Add `libopus-wasm/discordjs`, a Node-only async-ready `@discordjs/opus` adapter with `OpusEncoder.create()`, `ready`, `encode()`, `decode()`, CTL methods, bitrate/FEC/PLP helpers, and `Buffer` output.
30
+ - Add reproducible source builds that download libopus 1.6.1 from Xiph.Org, verify the pinned SHA-256, compile with Emscripten, and emit generated bindings into `dist/generated/`.
31
+ - Add Vitest coverage for version reporting, defaults, encode/decode paths, non-48 kHz frame derivation, CTLs, bitrate sentinels, Float32, packet metadata, PLC/FEC, invalid packets, Discord adapter behavior, and disposal.
32
+ - Add native comparison benchmark tooling against `@discordjs/opus` plus a manual GitHub Actions benchmark workflow.
33
+ - Add CI for Node 22 and Node 24 that installs with pnpm, builds WASM, runs tests, and verifies `pnpm pack --dry-run`.
34
+ - Add generated documentation site content for install, quickstart, encoding, decoding, packet loss, encoder tuning, CTLs, Discord compatibility, browser usage, building, benchmark, and API reference.
package/README.md CHANGED
@@ -1,11 +1,24 @@
1
1
  # libopus-wasm
2
2
 
3
+ ![libopus-wasm banner](docs/assets/readme-banner.jpg)
4
+
3
5
  [![CI](https://github.com/openclaw/libopus-wasm/actions/workflows/ci.yml/badge.svg)](https://github.com/openclaw/libopus-wasm/actions/workflows/ci.yml)
6
+ [![Docs](https://img.shields.io/badge/docs-libopus--wasm.dev-6d4aff)](https://libopus-wasm.dev)
7
+
8
+ Small, modern WebAssembly bindings for [libopus](https://opus-codec.org/) raw
9
+ packet encode/decode. One single-file ES module that runs unchanged in browsers
10
+ and Node — no `locateFile` hook, no second `.wasm` request, no native build step.
4
11
 
5
- Small, modern WASM bindings for libopus raw packet encode/decode.
12
+ The default path is realtime voice: 48 kHz, stereo, 20 ms frames, raw Opus
13
+ packets, no Ogg/WebM container layer.
6
14
 
7
- This package targets the narrow realtime voice use case: 48 kHz PCM and raw
8
- Opus packets, with no Ogg/WebM container layer.
15
+ - **Browser and Node** from one import. Bundles cleanly with Vite, webpack, esbuild.
16
+ - **Int16 and Float32 PCM** — use whatever your pipeline already speaks.
17
+ - **Loss-resilient** — in-band FEC and packet-loss concealment.
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.
20
+
21
+ 📖 **Full documentation: [libopus-wasm.dev](https://libopus-wasm.dev)**
9
22
 
10
23
  ## Install
11
24
 
@@ -13,34 +26,193 @@ Opus packets, with no Ogg/WebM container layer.
13
26
  npm install libopus-wasm
14
27
  ```
15
28
 
16
- ## Usage
29
+ ESM-only; Node 20+ or any current browser. No `@types` install needed.
30
+
31
+ ## Quick start
32
+
33
+ ```ts
34
+ import { createDecoder, createEncoder, getPacketInfo } from "libopus-wasm";
35
+
36
+ const encoder = await createEncoder(); // 48 kHz, stereo, 20 ms, audio
37
+ const decoder = await createDecoder();
38
+
39
+ const pcm = new Int16Array(encoder.frameSize * encoder.channels); // 960 * 2
40
+ const packet = encoder.encode(pcm); // Uint8Array — one raw Opus packet
41
+ const info = await getPacketInfo(packet); // duration, frames, bandwidth
42
+ const frame = decoder.decode(packet); // Int16Array — interleaved PCM
43
+
44
+ encoder.free();
45
+ decoder.free();
46
+ ```
47
+
48
+ Both factories share one lazily-loaded WASM module; the first call pays the load
49
+ cost and the rest are cheap.
50
+
51
+ ## Examples
52
+
53
+ ### Float32 PCM
54
+
55
+ Encode and decode floats directly — ideal for Web Audio:
56
+
57
+ ```ts
58
+ const frame = new Float32Array(encoder.frameSize * encoder.channels); // [-1, 1]
59
+ const packet = encoder.encodeFloat(frame);
60
+ const decoded = decoder.decodeFloat(packet); // Float32Array
61
+ ```
62
+
63
+ ### Batches
64
+
65
+ ```ts
66
+ const packets = encoder.encodeFrames([frameA, frameB, frameC]); // Uint8Array[]
67
+ const frames = decoder.decodeFrames(packets); // Int16Array[]
68
+ ```
69
+
70
+ ### Packet loss: FEC + concealment
17
71
 
18
72
  ```ts
19
- import { Application, createDecoder, createEncoder } from "libopus-wasm";
73
+ // Encoder: enable in-band FEC and declare the expected loss rate.
74
+ const encoder = await createEncoder({ fec: true, packetLossPercent: 15 });
75
+
76
+ // Decoder: a packet is lost. If the next packet is in hand, recover from its
77
+ // FEC data; otherwise synthesize a concealment frame.
78
+ const recovered = decoder.decode(nextPacket, { decodeFec: true, frameSize: 960 });
79
+ const concealed = decoder.decodePacketLoss(960); // == decode(null, { frameSize: 960 })
80
+ ```
20
81
 
82
+ See [Packet loss](https://libopus-wasm.dev/packet-loss.html) for the full receive loop.
83
+
84
+ ### Tuning the encoder
85
+
86
+ ```ts
21
87
  const encoder = await createEncoder({
22
- sampleRate: 48_000,
23
- channels: 2,
24
88
  application: Application.Audio,
89
+ bitrate: 96000, // or "auto" / "max"
90
+ complexity: 10, // 0..10
91
+ signal: Signal.Music,
92
+ vbr: true,
25
93
  });
26
- const decoder = await createDecoder({ sampleRate: 48_000, channels: 2 });
27
-
28
- try {
29
- const frameSize = 960; // 20 ms at 48 kHz
30
- const pcm = new Int16Array(frameSize * 2);
31
- const packet = encoder.encodePcm16(pcm, frameSize);
32
- const decoded = decoder.decodeFrame(packet, frameSize);
33
- console.log(decoded.length);
34
- } finally {
35
- encoder.free();
36
- decoder.free();
37
- }
94
+
95
+ encoder.setBitrate(128000);
96
+ encoder.setMaxBandwidth(Bandwidth.Wideband);
97
+ encoder.getBitrate(); // 128000
98
+ ```
99
+
100
+ ### Deterministic cleanup with `using`
101
+
102
+ ```ts
103
+ {
104
+ using encoder = await createEncoder();
105
+ using decoder = await createDecoder();
106
+ decoder.decode(encoder.encode(new Int16Array(960 * 2)));
107
+ } // both freed automatically at scope exit
38
108
  ```
39
109
 
40
- ## Build
110
+ ## discord.js compatibility
41
111
 
42
- The npm package ships compiled output. Building from source requires
43
- Emscripten (`emcc`) on `PATH`.
112
+ `libopus-wasm/discordjs` matches the [`@discordjs/opus`](https://github.com/discordjs/opus)
113
+ method shape, minus the native toolchain. It is Node-only (uses `Buffer`) and
114
+ loads asynchronously:
115
+
116
+ ```ts
117
+ import { OpusEncoder } from "libopus-wasm/discordjs";
118
+
119
+ const opus = await OpusEncoder.create(48000, 2);
120
+ const packet = opus.encode(pcmBuffer);
121
+ const decoded = opus.decode(packet);
122
+ opus.setBitrate(64000);
123
+ opus.setFEC(true);
124
+ opus.free();
125
+ ```
126
+
127
+ Or construct directly and await `ready` to keep existing call sites:
128
+
129
+ ```ts
130
+ const opus = new OpusEncoder(48000, 2);
131
+ await opus.ready;
132
+ ```
133
+
134
+ More in [discord.js compatibility](https://libopus-wasm.dev/discordjs.html).
135
+
136
+ ## Browser
137
+
138
+ The main entry inlines the WASM, so it bundles with no plugins and needs no
139
+ cross-origin isolation. Web Audio delivers Float32 samples that go straight into
140
+ `encodeFloat` — see [Browser usage](https://libopus-wasm.dev/browser.html) for a
141
+ microphone-capture walkthrough.
142
+
143
+ ## API overview
144
+
145
+ Full reference with every option and constant lives at
146
+ [libopus-wasm.dev/api-reference](https://libopus-wasm.dev/api-reference.html).
147
+
148
+ ### Top-level
149
+
150
+ | Function | Returns | Description |
151
+ | --- | --- | --- |
152
+ | `loadLibopus()` | `Promise<{ version }>` | Loads the module; returns the bundled libopus version. |
153
+ | `createEncoder(options?)` | `Promise<OpusEncoderHandle>` | Create a raw-packet encoder. |
154
+ | `createDecoder(options?)` | `Promise<OpusDecoderHandle>` | Create a raw-packet decoder. |
155
+ | `getPacketInfo(packet, options?)` | `Promise<OpusPacketInfo>` | Validate a raw packet and return duration, frame count, channels, and bandwidth. |
156
+
157
+ ### Encoder
158
+
159
+ | Member | Description |
160
+ | --- | --- |
161
+ | `encode(pcm, options?)` | Encode one Int16 frame (`Int16Array \| Uint8Array`) → `Uint8Array`. |
162
+ | `encodeFloat(pcm, options?)` | Encode one `Float32Array` frame → `Uint8Array`. |
163
+ | `encodeFrames` / `encodeFloatFrames` | Batch variants → `Uint8Array[]`. |
164
+ | `setBitrate` / `getBitrate` | Bitrate (`number \| "auto" \| "max"`). |
165
+ | `setComplexity` `setSignal` `setMaxBandwidth` | Quality and bandwidth controls. |
166
+ | `setVbr` `setVbrConstraint` `setDtx` | Rate-mode controls. |
167
+ | `setFec` `setPacketLossPercent` | Loss-resilience controls. |
168
+ | `getLookahead` `getInDtx` | Encoder state. |
169
+ | `encoderCtl(request, value)` | Curated integer-setter [CTL passthrough](https://libopus-wasm.dev/ctl.html). |
170
+ | `free()` / `[Symbol.dispose]()` | Release WASM memory. |
171
+
172
+ Read-only: `application`, `channels`, `frameSize`, `sampleRate`.
173
+
174
+ ### Decoder
175
+
176
+ | Member | Description |
177
+ | --- | --- |
178
+ | `decode(packet, options?)` | Decode a packet (or `null` for PLC) → `Int16Array`. |
179
+ | `decodeFloat(packet, options?)` | Decode → `Float32Array`. |
180
+ | `decodeFrames` / `decodeFloatFrames` | Batch variants; `null` entries are concealed. |
181
+ | `decodePacketLoss(frameSize?)` | Synthesize one concealment frame. |
182
+ | `decodePacketLossFloat(frameSize?)` | Float32 variant. |
183
+ | `decoderCtl(request, value)` | Integer-setter CTL passthrough. |
184
+ | `free()` / `[Symbol.dispose]()` | Release WASM memory. |
185
+
186
+ Read-only: `channels`, `maxFrameSize`, `sampleRate`.
187
+
188
+ ### Constants
189
+
190
+ `Application` (`Voip`, `Audio`, `RestrictedLowDelay`) ·
191
+ `Signal` (`Auto`, `Voice`, `Music`) ·
192
+ `Bitrate` (`Auto`, `Max`) ·
193
+ `Bandwidth` (`Narrowband`…`Fullband`) ·
194
+ `EncoderCtl` / `DecoderCtl` request codes ·
195
+ `OpusError` (`code`, `codeName`, `operation`) ·
196
+ `OpusErrorCode` · `isOpusError`.
197
+
198
+ ### Supported formats
199
+
200
+ | Constraint | Allowed values |
201
+ | --- | --- |
202
+ | Sample rate | `8000`, `12000`, `16000`, `24000`, `48000` Hz |
203
+ | Channels | `1` (mono), `2` (stereo) |
204
+ | Encode frame duration | `2.5`, `5`, `10`, `20`, `40`, `60` ms |
205
+ | Decode output capacity | up to `120` ms |
206
+ | PLC / FEC frame size | multiples of `2.5` ms, up to `120` ms |
207
+
208
+ Validation errors (wrong frame size, out-of-range option, empty packet,
209
+ non-allow-listed CTL) throw a `RangeError` before reaching WASM; libopus errors
210
+ surface as `OpusError`.
211
+
212
+ ## Build from source
213
+
214
+ The npm package ships compiled output, so using it needs no toolchain. Building
215
+ from source requires Emscripten (`emcc`) on `PATH`:
44
216
 
45
217
  ```bash
46
218
  pnpm install
@@ -49,21 +221,8 @@ pnpm test
49
221
  ```
50
222
 
51
223
  `pnpm build` downloads `libopus 1.6.1` from Xiph.Org, verifies the pinned
52
- SHA-256, builds it with Emscripten, and emits a single-file ES module under
53
- `dist/generated/`.
54
-
55
- ## API
56
-
57
- - `loadLibopus()`: returns the bundled libopus version string.
58
- - `createEncoder(options)`: creates a raw packet encoder.
59
- - `createDecoder(options)`: creates a raw packet decoder.
60
- - `encoder.encodePcm16(pcm, frameSize)`: encodes one PCM frame.
61
- - `decoder.decodeFrame(packet, frameSize)`: decodes one raw Opus packet.
62
- - `encoder.setBitrate`, `encoder.setFec`, `encoder.setPacketLossPercent`: small CTL surface for realtime voice tuning.
63
- - `free()`: releases the underlying libopus encoder/decoder.
64
-
65
- Supported sample rates are `8000`, `12000`, `16000`, `24000`, and `48000`.
66
- Supported channel counts are mono and stereo.
224
+ SHA-256, compiles it with Emscripten, and emits a single-file ES module under
225
+ `dist/generated/`. See [Building from source](https://libopus-wasm.dev/building.html).
67
226
 
68
227
  ## Benchmark
69
228
 
@@ -73,8 +232,7 @@ Native comparison requires `@discordjs/opus` to build on the host:
73
232
  pnpm benchmark
74
233
  ```
75
234
 
76
- Local Apple Silicon result on Node 26, 20k iterations, 48 kHz stereo, 20 ms
77
- frames:
235
+ Apple Silicon, Node 26, 20k iterations, 48 kHz stereo, 20 ms frames:
78
236
 
79
237
  ```text
80
238
  wasm encode: 15,304 ops/sec
@@ -83,5 +241,11 @@ wasm decode: 38,416 ops/sec
83
241
  native decode: 41,280 ops/sec
84
242
  ```
85
243
 
86
- The benchmark is intended as a regression check, not a stable cross-machine
87
- score. CI also exposes a manual `Benchmark` workflow.
244
+ A regression check, not a portable score. CI also exposes a manual `Benchmark`
245
+ workflow. More in [Benchmark](https://libopus-wasm.dev/benchmark.html).
246
+
247
+ ## Documentation & license
248
+
249
+ Full docs: **[libopus-wasm.dev](https://libopus-wasm.dev)**. Released under the
250
+ [MIT license](LICENSE); libopus carries its own BSD license, reproduced in
251
+ [THIRD_PARTY_NOTICES](THIRD_PARTY_NOTICES.md). Not affiliated with Xiph.Org.
@@ -0,0 +1,20 @@
1
+ import { Buffer } from "node:buffer";
2
+ export declare class OpusEncoder {
3
+ #private;
4
+ readonly channels: number;
5
+ readonly rate: number;
6
+ readonly ready: Promise<void>;
7
+ constructor(rate?: number, channels?: number);
8
+ static create(rate?: number, channels?: number): Promise<OpusEncoder>;
9
+ encode(buf: Buffer | Uint8Array): Buffer;
10
+ decode(buf: Buffer | Uint8Array): Buffer;
11
+ applyEncoderCTL(ctl: number, value: number): void;
12
+ applyDecoderCTL(ctl: number, value: number): void;
13
+ setBitrate(bitrate: number): void;
14
+ getBitrate(): number;
15
+ setFEC(enabled: boolean): void;
16
+ setPLP(percentage: number): void;
17
+ free(): void;
18
+ [Symbol.dispose](): void;
19
+ }
20
+ //# sourceMappingURL=discordjs.d.ts.map
@@ -0,0 +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;gBAMlB,IAAI,SAAS,EAAE,QAAQ,SAAI;WA2B1B,MAAM,CAAC,IAAI,SAAS,EAAE,QAAQ,SAAI,GAAG,OAAO,CAAC,WAAW,CAAC;IAMtE,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM;IAMxC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM;IAMxC,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAIjD,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAIjD,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAIjC,UAAU,IAAI,MAAM;IAIpB,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAI9B,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAIhC,IAAI,IAAI,IAAI;IASZ,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI;CA0BzB"}
@@ -0,0 +1,108 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { createDecoder, createEncoder } from "./index.js";
3
+ export class OpusEncoder {
4
+ channels;
5
+ rate;
6
+ ready;
7
+ #decoder;
8
+ #encoder;
9
+ #freed = false;
10
+ #initError;
11
+ constructor(rate = 48_000, channels = 2) {
12
+ this.rate = rate;
13
+ this.channels = channels;
14
+ this.ready = Promise.all([
15
+ createEncoder({
16
+ channels: channels,
17
+ sampleRate: rate,
18
+ }),
19
+ createDecoder({
20
+ channels: channels,
21
+ sampleRate: rate,
22
+ }),
23
+ ]).then(([encoder, decoder]) => {
24
+ if (this.#freed) {
25
+ encoder.free();
26
+ decoder.free();
27
+ return;
28
+ }
29
+ this.#encoder = encoder;
30
+ this.#decoder = decoder;
31
+ }).catch((error) => {
32
+ this.#initError = error;
33
+ throw error;
34
+ });
35
+ this.ready.catch(() => undefined);
36
+ }
37
+ static async create(rate = 48_000, channels = 2) {
38
+ const encoder = new OpusEncoder(rate, channels);
39
+ await encoder.ready;
40
+ return encoder;
41
+ }
42
+ encode(buf) {
43
+ const encoder = this.#requireEncoder();
44
+ const frameSize = inferFrameSize(buf.byteLength, this.channels);
45
+ return Buffer.from(encoder.encode(buf, { frameSize }));
46
+ }
47
+ decode(buf) {
48
+ const decoder = this.#requireDecoder();
49
+ const pcm = decoder.decode(buf);
50
+ return Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength);
51
+ }
52
+ applyEncoderCTL(ctl, value) {
53
+ this.#requireEncoder().encoderCtl(ctl, value);
54
+ }
55
+ applyDecoderCTL(ctl, value) {
56
+ this.#requireDecoder().decoderCtl(ctl, value);
57
+ }
58
+ setBitrate(bitrate) {
59
+ this.#requireEncoder().setBitrate(bitrate);
60
+ }
61
+ getBitrate() {
62
+ return this.#requireEncoder().getBitrate();
63
+ }
64
+ setFEC(enabled) {
65
+ this.#requireEncoder().setFec(enabled);
66
+ }
67
+ setPLP(percentage) {
68
+ this.#requireEncoder().setPacketLossPercent(percentage);
69
+ }
70
+ free() {
71
+ if (this.#freed) {
72
+ return;
73
+ }
74
+ this.#freed = true;
75
+ this.#encoder?.free();
76
+ this.#decoder?.free();
77
+ }
78
+ [Symbol.dispose]() {
79
+ this.free();
80
+ }
81
+ #requireEncoder() {
82
+ this.#throwInitErrorIfAny();
83
+ if (!this.#encoder || this.#freed) {
84
+ throw new Error("OpusEncoder is not ready; await encoder.ready or use OpusEncoder.create()");
85
+ }
86
+ return this.#encoder;
87
+ }
88
+ #requireDecoder() {
89
+ this.#throwInitErrorIfAny();
90
+ if (!this.#decoder || this.#freed) {
91
+ throw new Error("OpusEncoder is not ready; await encoder.ready or use OpusEncoder.create()");
92
+ }
93
+ return this.#decoder;
94
+ }
95
+ #throwInitErrorIfAny() {
96
+ if (!this.#initError) {
97
+ return;
98
+ }
99
+ throw new Error("OpusEncoder failed to initialize", { cause: this.#initError });
100
+ }
101
+ }
102
+ function inferFrameSize(byteLength, channels) {
103
+ const frameSize = byteLength / 2 / channels;
104
+ if (!Number.isInteger(frameSize) || frameSize <= 0) {
105
+ throw new RangeError("PCM buffer length must contain whole signed 16-bit samples for each channel");
106
+ }
107
+ return frameSize;
108
+ }
package/dist/index.d.ts CHANGED
@@ -3,45 +3,151 @@ export declare const Application: {
3
3
  readonly Audio: 2049;
4
4
  readonly RestrictedLowDelay: 2051;
5
5
  };
6
+ export declare const Signal: {
7
+ readonly Auto: -1000;
8
+ readonly Voice: 3001;
9
+ readonly Music: 3002;
10
+ };
11
+ export declare const Bitrate: {
12
+ readonly Auto: -1000;
13
+ readonly Max: -1;
14
+ };
15
+ export declare const Bandwidth: {
16
+ readonly Narrowband: 1101;
17
+ readonly Mediumband: 1102;
18
+ readonly Wideband: 1103;
19
+ readonly Superwideband: 1104;
20
+ readonly Fullband: 1105;
21
+ };
22
+ export declare const EncoderCtl: {
23
+ readonly SetApplication: 4000;
24
+ readonly SetBitrate: 4002;
25
+ readonly SetMaxBandwidth: 4004;
26
+ readonly SetVbr: 4006;
27
+ readonly SetBandwidth: 4008;
28
+ readonly SetComplexity: 4010;
29
+ readonly SetInBandFec: 4012;
30
+ readonly SetPacketLossPercent: 4014;
31
+ readonly SetDtx: 4016;
32
+ readonly SetVbrConstraint: 4020;
33
+ readonly SetForceChannels: 4022;
34
+ readonly SetSignal: 4024;
35
+ readonly SetLsbDepth: 4036;
36
+ readonly SetExpertFrameDuration: 4040;
37
+ readonly SetPredictionDisabled: 4042;
38
+ readonly SetPhaseInversionDisabled: 4046;
39
+ };
40
+ export declare const DecoderCtl: {
41
+ readonly SetGain: 4034;
42
+ readonly SetPhaseInversionDisabled: 4046;
43
+ };
6
44
  export type Application = (typeof Application)[keyof typeof Application];
45
+ export type Signal = (typeof Signal)[keyof typeof Signal];
46
+ export type Bitrate = number | "auto" | "max";
47
+ export type Bandwidth = (typeof Bandwidth)[keyof typeof Bandwidth];
48
+ export type SampleRate = 8000 | 12000 | 16000 | 24000 | 48000;
49
+ export type ChannelCount = 1 | 2;
7
50
  export type CodecOptions = {
8
- channels: 1 | 2;
9
- sampleRate: 8000 | 12000 | 16000 | 24000 | 48000;
51
+ channels?: ChannelCount;
52
+ sampleRate?: SampleRate;
10
53
  };
11
54
  export type EncoderOptions = CodecOptions & {
12
55
  application?: Application;
13
- bitrate?: number;
56
+ bitrate?: Bitrate;
57
+ complexity?: number;
58
+ dtx?: boolean;
14
59
  fec?: boolean;
60
+ frameSize?: number;
61
+ maxBandwidth?: Bandwidth;
15
62
  packetLossPercent?: number;
63
+ signal?: Signal;
64
+ vbr?: boolean;
65
+ vbrConstraint?: boolean;
66
+ };
67
+ export type DecoderOptions = CodecOptions & {
68
+ maxFrameSize?: number;
16
69
  };
17
70
  export type DecodeOptions = {
18
71
  decodeFec?: boolean;
72
+ frameSize?: number;
73
+ maxFrameSize?: number;
19
74
  };
20
75
  export type EncodeOptions = {
76
+ frameSize?: number;
21
77
  maxPacketBytes?: number;
22
78
  };
23
- export type OpusEncoder = {
24
- readonly channels: 1 | 2;
25
- readonly sampleRate: CodecOptions["sampleRate"];
26
- encodePcm16(pcm: Int16Array | Uint8Array, frameSize: number, options?: EncodeOptions): Uint8Array;
79
+ export type PacketInfoOptions = {
80
+ sampleRate?: SampleRate;
81
+ };
82
+ export type OpusPacketInfo = {
83
+ readonly bandwidth: Bandwidth;
84
+ readonly channels: ChannelCount;
85
+ readonly durationMs: number;
86
+ readonly frames: number;
87
+ readonly samples: number;
88
+ readonly samplesPerFrame: number;
89
+ readonly sampleRate: SampleRate;
90
+ };
91
+ export type OpusEncoderHandle = {
92
+ readonly application: Application;
93
+ readonly channels: ChannelCount;
94
+ readonly frameSize: number;
95
+ readonly sampleRate: SampleRate;
96
+ encode(pcm: Int16Array | Uint8Array, options?: EncodeOptions): Uint8Array;
97
+ encodeFloat(pcm: Float32Array, options?: EncodeOptions): Uint8Array;
98
+ encodeFrames(frames: readonly (Int16Array | Uint8Array)[], options?: EncodeOptions): Uint8Array[];
99
+ encodeFloatFrames(frames: readonly Float32Array[], options?: EncodeOptions): Uint8Array[];
100
+ encoderCtl(request: number, value: number): void;
27
101
  free(): void;
28
- setBitrate(bitrate: number): void;
102
+ getBitrate(): number;
103
+ getInDtx(): boolean;
104
+ getLookahead(): number;
105
+ setBitrate(bitrate: Bitrate): void;
106
+ setComplexity(complexity: number): void;
107
+ setDtx(enabled: boolean): void;
29
108
  setFec(enabled: boolean): void;
109
+ setMaxBandwidth(bandwidth: Bandwidth): void;
30
110
  setPacketLossPercent(percentage: number): void;
111
+ setSignal(signal: Signal): void;
112
+ setVbr(enabled: boolean): void;
113
+ setVbrConstraint(enabled: boolean): void;
114
+ [Symbol.dispose](): void;
31
115
  };
32
- export type OpusDecoder = {
33
- readonly channels: 1 | 2;
34
- readonly sampleRate: CodecOptions["sampleRate"];
35
- decodeFrame(packet: Uint8Array, frameSize: number, options?: DecodeOptions): Int16Array;
116
+ export type OpusDecoderHandle = {
117
+ readonly channels: ChannelCount;
118
+ readonly maxFrameSize: number;
119
+ readonly sampleRate: SampleRate;
120
+ decode(packet: Uint8Array | null, options?: DecodeOptions): Int16Array;
121
+ decodeFloat(packet: Uint8Array | null, options?: DecodeOptions): Float32Array;
122
+ decodeFrames(packets: readonly (Uint8Array | null)[], options?: DecodeOptions): Int16Array[];
123
+ decodeFloatFrames(packets: readonly (Uint8Array | null)[], options?: DecodeOptions): Float32Array[];
124
+ decodePacketLoss(frameSize?: number): Int16Array;
125
+ decodePacketLossFloat(frameSize?: number): Float32Array;
126
+ decoderCtl(request: number, value: number): void;
36
127
  free(): void;
128
+ [Symbol.dispose](): void;
37
129
  };
38
130
  export declare function loadLibopus(): Promise<{
39
131
  version: string;
40
132
  }>;
41
- export declare function createEncoder(options: EncoderOptions): Promise<OpusEncoder>;
42
- export declare function createDecoder(options: CodecOptions): Promise<OpusDecoder>;
133
+ export declare function createEncoder(options?: EncoderOptions): Promise<OpusEncoderHandle>;
134
+ export declare function createDecoder(options?: DecoderOptions): Promise<OpusDecoderHandle>;
135
+ export declare function getPacketInfo(packet: Uint8Array, options?: PacketInfoOptions): Promise<OpusPacketInfo>;
43
136
  export declare class OpusError extends Error {
44
137
  readonly code: number;
45
- constructor(code: number, message: string);
138
+ readonly codeName: OpusErrorCodeName | undefined;
139
+ readonly operation: string | undefined;
140
+ constructor(code: number, message: string, operation?: string);
46
141
  }
142
+ export declare const OpusErrorCode: {
143
+ readonly BadArg: -1;
144
+ readonly BufferTooSmall: -2;
145
+ readonly InternalError: -3;
146
+ readonly InvalidPacket: -4;
147
+ readonly Unimplemented: -5;
148
+ readonly InvalidState: -6;
149
+ readonly AllocFail: -7;
150
+ };
151
+ export type OpusErrorCodeName = keyof typeof OpusErrorCode;
152
+ export declare function isOpusError(error: unknown): error is OpusError;
47
153
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,WAAW;;;;CAId,CAAC;AAEX,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC;AAEzE,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC;IAChB,UAAU,EAAE,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;CAClD,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,YAAY,GAAG;IAC1C,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,OAAO,CAA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