libopus-wasm 0.0.1 → 0.1.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,28 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 - 2026-05-26
6
+
7
+ - 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.
8
+ - 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.
9
+ - Add Discord/WebRTC-ready defaults: 48 kHz, stereo, 20 ms frames, raw packets, `Application.Audio`, 64 kbps, and complexity 10.
10
+ - Add async `loadLibopus()`, `createEncoder()`, `createDecoder()`, and `getPacketInfo()` top-level APIs with one lazily shared WASM module.
11
+ - Add Int16 PCM encode/decode via `encode()` and `decode()`, including `Int16Array` input and `Uint8Array` little-endian PCM input support.
12
+ - Add Float32 PCM encode/decode via `encodeFloat()` and `decodeFloat()` for Web Audio and DSP pipelines.
13
+ - Add batch helpers `encodeFrames()`, `encodeFloatFrames()`, `decodeFrames()`, and `decodeFloatFrames()`.
14
+ - Add raw packet metadata inspection with validation, returning bandwidth, channel count, frame count, sample count, samples per frame, duration, and sample rate.
15
+ - Add packet-loss concealment APIs `decodePacketLoss()`, `decodePacketLossFloat()`, and `decode(null, { frameSize })`.
16
+ - Add in-band FEC support through encoder `fec` / `packetLossPercent` options and decoder `decodeFec` recovery.
17
+ - Add encoder tuning options and setters for application, bitrate, complexity, DTX, FEC, max bandwidth, packet loss percentage, signal, VBR, and constrained VBR.
18
+ - Add encoder state readers `getBitrate()`, `getLookahead()`, and `getInDtx()`.
19
+ - Add curated integer CTL passthroughs with `EncoderCtl`, `DecoderCtl`, `encoderCtl()`, and `decoderCtl()` while rejecting pointer-style getter CTLs at the JS boundary.
20
+ - Add exported constants and types for `Application`, `Signal`, `Bitrate`, `Bandwidth`, `SampleRate`, `ChannelCount`, encoder/decoder options, packet info, handle types, and `OpusError`.
21
+ - 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.
22
+ - Add deterministic cleanup through `free()` and `[Symbol.dispose]()` on encoder, decoder, and Discord-compatible handles.
23
+ - 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.
24
+ - 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/`.
25
+ - 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.
26
+ - Add native comparison benchmark tooling against `@discordjs/opus` plus a manual GitHub Actions benchmark workflow.
27
+ - Add CI for Node 22 and Node 24 that installs with pnpm, builds WASM, runs tests, and verifies `pnpm pack --dry-run`.
28
+ - 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,22 @@
1
1
  # libopus-wasm
2
2
 
3
3
  [![CI](https://github.com/openclaw/libopus-wasm/actions/workflows/ci.yml/badge.svg)](https://github.com/openclaw/libopus-wasm/actions/workflows/ci.yml)
4
+ [![Docs](https://img.shields.io/badge/docs-libopus--wasm.dev-6d4aff)](https://libopus-wasm.dev)
4
5
 
5
- Small, modern WASM bindings for libopus raw packet encode/decode.
6
+ Small, modern WebAssembly bindings for [libopus](https://opus-codec.org/) raw
7
+ packet encode/decode. One single-file ES module that runs unchanged in browsers
8
+ and Node — no `locateFile` hook, no second `.wasm` request, no native build step.
6
9
 
7
- This package targets the narrow realtime voice use case: 48 kHz PCM and raw
8
- Opus packets, with no Ogg/WebM container layer.
10
+ The default path is realtime voice: 48 kHz, stereo, 20 ms frames, raw Opus
11
+ packets, no Ogg/WebM container layer.
12
+
13
+ - **Browser and Node** from one import. Bundles cleanly with Vite, webpack, esbuild.
14
+ - **Int16 and Float32 PCM** — use whatever your pipeline already speaks.
15
+ - **Loss-resilient** — in-band FEC and packet-loss concealment.
16
+ - **Tunable** — bitrate, VBR/CBR, complexity, signal, bandwidth, DTX, plus a curated CTL passthrough.
17
+ - **Drop-in `@discordjs/opus` adapter** — same method shape, no node-gyp.
18
+
19
+ 📖 **Full documentation: [libopus-wasm.dev](https://libopus-wasm.dev)**
9
20
 
10
21
  ## Install
11
22
 
@@ -13,34 +24,192 @@ Opus packets, with no Ogg/WebM container layer.
13
24
  npm install libopus-wasm
14
25
  ```
15
26
 
16
- ## Usage
27
+ ESM-only; Node 20+ or any current browser. No `@types` install needed.
28
+
29
+ ## Quick start
30
+
31
+ ```ts
32
+ import { createDecoder, createEncoder, getPacketInfo } from "libopus-wasm";
33
+
34
+ const encoder = await createEncoder(); // 48 kHz, stereo, 20 ms, audio
35
+ const decoder = await createDecoder();
36
+
37
+ const pcm = new Int16Array(encoder.frameSize * encoder.channels); // 960 * 2
38
+ const packet = encoder.encode(pcm); // Uint8Array — one raw Opus packet
39
+ const info = await getPacketInfo(packet); // duration, frames, bandwidth
40
+ const frame = decoder.decode(packet); // Int16Array — interleaved PCM
41
+
42
+ encoder.free();
43
+ decoder.free();
44
+ ```
45
+
46
+ Both factories share one lazily-loaded WASM module; the first call pays the load
47
+ cost and the rest are cheap.
48
+
49
+ ## Examples
50
+
51
+ ### Float32 PCM
52
+
53
+ Encode and decode floats directly — ideal for Web Audio:
54
+
55
+ ```ts
56
+ const frame = new Float32Array(encoder.frameSize * encoder.channels); // [-1, 1]
57
+ const packet = encoder.encodeFloat(frame);
58
+ const decoded = decoder.decodeFloat(packet); // Float32Array
59
+ ```
60
+
61
+ ### Batches
62
+
63
+ ```ts
64
+ const packets = encoder.encodeFrames([frameA, frameB, frameC]); // Uint8Array[]
65
+ const frames = decoder.decodeFrames(packets); // Int16Array[]
66
+ ```
67
+
68
+ ### Packet loss: FEC + concealment
17
69
 
18
70
  ```ts
19
- import { Application, createDecoder, createEncoder } from "libopus-wasm";
71
+ // Encoder: enable in-band FEC and declare the expected loss rate.
72
+ const encoder = await createEncoder({ fec: true, packetLossPercent: 15 });
73
+
74
+ // Decoder: a packet is lost. If the next packet is in hand, recover from its
75
+ // FEC data; otherwise synthesize a concealment frame.
76
+ const recovered = decoder.decode(nextPacket, { decodeFec: true, frameSize: 960 });
77
+ const concealed = decoder.decodePacketLoss(960); // == decode(null, { frameSize: 960 })
78
+ ```
79
+
80
+ See [Packet loss](https://libopus-wasm.dev/packet-loss.html) for the full receive loop.
20
81
 
82
+ ### Tuning the encoder
83
+
84
+ ```ts
21
85
  const encoder = await createEncoder({
22
- sampleRate: 48_000,
23
- channels: 2,
24
86
  application: Application.Audio,
87
+ bitrate: 96000, // or "auto" / "max"
88
+ complexity: 10, // 0..10
89
+ signal: Signal.Music,
90
+ vbr: true,
25
91
  });
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
- }
92
+
93
+ encoder.setBitrate(128000);
94
+ encoder.setMaxBandwidth(Bandwidth.Wideband);
95
+ encoder.getBitrate(); // 128000
96
+ ```
97
+
98
+ ### Deterministic cleanup with `using`
99
+
100
+ ```ts
101
+ {
102
+ using encoder = await createEncoder();
103
+ using decoder = await createDecoder();
104
+ decoder.decode(encoder.encode(new Int16Array(960 * 2)));
105
+ } // both freed automatically at scope exit
38
106
  ```
39
107
 
40
- ## Build
108
+ ## discord.js compatibility
41
109
 
42
- The npm package ships compiled output. Building from source requires
43
- Emscripten (`emcc`) on `PATH`.
110
+ `libopus-wasm/discordjs` matches the [`@discordjs/opus`](https://github.com/discordjs/opus)
111
+ method shape, minus the native toolchain. It is Node-only (uses `Buffer`) and
112
+ loads asynchronously:
113
+
114
+ ```ts
115
+ import { OpusEncoder } from "libopus-wasm/discordjs";
116
+
117
+ const opus = await OpusEncoder.create(48000, 2);
118
+ const packet = opus.encode(pcmBuffer);
119
+ const decoded = opus.decode(packet);
120
+ opus.setBitrate(64000);
121
+ opus.setFEC(true);
122
+ opus.free();
123
+ ```
124
+
125
+ Or construct directly and await `ready` to keep existing call sites:
126
+
127
+ ```ts
128
+ const opus = new OpusEncoder(48000, 2);
129
+ await opus.ready;
130
+ ```
131
+
132
+ More in [discord.js compatibility](https://libopus-wasm.dev/discordjs.html).
133
+
134
+ ## Browser
135
+
136
+ The main entry inlines the WASM, so it bundles with no plugins and needs no
137
+ cross-origin isolation. Web Audio delivers Float32 samples that go straight into
138
+ `encodeFloat` — see [Browser usage](https://libopus-wasm.dev/browser.html) for a
139
+ microphone-capture walkthrough.
140
+
141
+ ## API overview
142
+
143
+ Full reference with every option and constant lives at
144
+ [libopus-wasm.dev/api-reference](https://libopus-wasm.dev/api-reference.html).
145
+
146
+ ### Top-level
147
+
148
+ | Function | Returns | Description |
149
+ | --- | --- | --- |
150
+ | `loadLibopus()` | `Promise<{ version }>` | Loads the module; returns the bundled libopus version. |
151
+ | `createEncoder(options?)` | `Promise<OpusEncoderHandle>` | Create a raw-packet encoder. |
152
+ | `createDecoder(options?)` | `Promise<OpusDecoderHandle>` | Create a raw-packet decoder. |
153
+ | `getPacketInfo(packet, options?)` | `Promise<OpusPacketInfo>` | Validate a raw packet and return duration, frame count, channels, and bandwidth. |
154
+
155
+ ### Encoder
156
+
157
+ | Member | Description |
158
+ | --- | --- |
159
+ | `encode(pcm, options?)` | Encode one Int16 frame (`Int16Array \| Uint8Array`) → `Uint8Array`. |
160
+ | `encodeFloat(pcm, options?)` | Encode one `Float32Array` frame → `Uint8Array`. |
161
+ | `encodeFrames` / `encodeFloatFrames` | Batch variants → `Uint8Array[]`. |
162
+ | `setBitrate` / `getBitrate` | Bitrate (`number \| "auto" \| "max"`). |
163
+ | `setComplexity` `setSignal` `setMaxBandwidth` | Quality and bandwidth controls. |
164
+ | `setVbr` `setVbrConstraint` `setDtx` | Rate-mode controls. |
165
+ | `setFec` `setPacketLossPercent` | Loss-resilience controls. |
166
+ | `getLookahead` `getInDtx` | Encoder state. |
167
+ | `encoderCtl(request, value)` | Curated integer-setter [CTL passthrough](https://libopus-wasm.dev/ctl.html). |
168
+ | `free()` / `[Symbol.dispose]()` | Release WASM memory. |
169
+
170
+ Read-only: `application`, `channels`, `frameSize`, `sampleRate`.
171
+
172
+ ### Decoder
173
+
174
+ | Member | Description |
175
+ | --- | --- |
176
+ | `decode(packet, options?)` | Decode a packet (or `null` for PLC) → `Int16Array`. |
177
+ | `decodeFloat(packet, options?)` | Decode → `Float32Array`. |
178
+ | `decodeFrames` / `decodeFloatFrames` | Batch variants; `null` entries are concealed. |
179
+ | `decodePacketLoss(frameSize?)` | Synthesize one concealment frame. |
180
+ | `decodePacketLossFloat(frameSize?)` | Float32 variant. |
181
+ | `decoderCtl(request, value)` | Integer-setter CTL passthrough. |
182
+ | `free()` / `[Symbol.dispose]()` | Release WASM memory. |
183
+
184
+ Read-only: `channels`, `maxFrameSize`, `sampleRate`.
185
+
186
+ ### Constants
187
+
188
+ `Application` (`Voip`, `Audio`, `RestrictedLowDelay`) ·
189
+ `Signal` (`Auto`, `Voice`, `Music`) ·
190
+ `Bitrate` (`Auto`, `Max`) ·
191
+ `Bandwidth` (`Narrowband`…`Fullband`) ·
192
+ `EncoderCtl` / `DecoderCtl` request codes ·
193
+ `OpusError` (`code`, `operation`).
194
+
195
+ ### Supported formats
196
+
197
+ | Constraint | Allowed values |
198
+ | --- | --- |
199
+ | Sample rate | `8000`, `12000`, `16000`, `24000`, `48000` Hz |
200
+ | Channels | `1` (mono), `2` (stereo) |
201
+ | Encode frame duration | `2.5`, `5`, `10`, `20`, `40`, `60` ms |
202
+ | Decode output capacity | up to `120` ms |
203
+ | PLC / FEC frame size | multiples of `2.5` ms, up to `120` ms |
204
+
205
+ Validation errors (wrong frame size, out-of-range option, empty packet,
206
+ non-allow-listed CTL) throw a `RangeError` before reaching WASM; libopus errors
207
+ surface as `OpusError`.
208
+
209
+ ## Build from source
210
+
211
+ The npm package ships compiled output, so using it needs no toolchain. Building
212
+ from source requires Emscripten (`emcc`) on `PATH`:
44
213
 
45
214
  ```bash
46
215
  pnpm install
@@ -49,21 +218,8 @@ pnpm test
49
218
  ```
50
219
 
51
220
  `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.
221
+ SHA-256, compiles it with Emscripten, and emits a single-file ES module under
222
+ `dist/generated/`. See [Building from source](https://libopus-wasm.dev/building.html).
67
223
 
68
224
  ## Benchmark
69
225
 
@@ -73,8 +229,7 @@ Native comparison requires `@discordjs/opus` to build on the host:
73
229
  pnpm benchmark
74
230
  ```
75
231
 
76
- Local Apple Silicon result on Node 26, 20k iterations, 48 kHz stereo, 20 ms
77
- frames:
232
+ Apple Silicon, Node 26, 20k iterations, 48 kHz stereo, 20 ms frames:
78
233
 
79
234
  ```text
80
235
  wasm encode: 15,304 ops/sec
@@ -83,5 +238,11 @@ wasm decode: 38,416 ops/sec
83
238
  native decode: 41,280 ops/sec
84
239
  ```
85
240
 
86
- The benchmark is intended as a regression check, not a stable cross-machine
87
- score. CI also exposes a manual `Benchmark` workflow.
241
+ A regression check, not a portable score. CI also exposes a manual `Benchmark`
242
+ workflow. More in [Benchmark](https://libopus-wasm.dev/benchmark.html).
243
+
244
+ ## Documentation & license
245
+
246
+ Full docs: **[libopus-wasm.dev](https://libopus-wasm.dev)**. Released under the
247
+ [MIT license](LICENSE); libopus carries its own BSD license, reproduced in
248
+ [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,139 @@ 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 operation: string | undefined;
139
+ constructor(code: number, message: string, operation?: string);
46
140
  }
47
141
  //# 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,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,QAAQ,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,YAAY,CAAC,YAAY,CAAC,CAAC;IAChD,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,UAAU,CAAC;IAClG,IAAI,IAAI,IAAI,CAAC;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