From 9dde4bf63bee33528d100c7fd2ae0121d4056505 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Wed, 11 Nov 2026 17:10:35 +0000 Subject: [PATCH] feat(OpusEncoder): add encodeFloat and decodeFloat Expose opus_encode_float and opus_decode_float so audio can be handled as 32-bit floating point PCM instead of signed 16-bit integers. - encodeFloat() accepts a Buffer or Float32Array of interleaved samples. The samples are copied into an aligned scratch vector first, since Buffers (e.g. pooled ones) aren't guaranteed to be 4-byte aligned, and oversized inputs are rejected before copying. - decodeFloat() decodes into a lazily allocated float buffer, so encoders that never use it don't pay for the extra memory, and returns a Buffer of little-endian float32 samples. - Both methods validate their input and report libopus errors the same way as encode() and decode(). Adds tests, typings and a README example. close #171 --- README.md | 4 +++ src/node-opus.cc | 88 ++++++++++++++++++++++++++++++++++++++++++++++ src/node-opus.h | 8 +++++ tests/test.js | 69 ++++++++++++++++++++++++++++++++++++ typings/index.d.ts | 10 ++++++ 5 files changed, 179 insertions(+) diff --git a/README.md b/README.md index 1a38aa33..84e9b90c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ const encoder = new OpusEncoder(48_000, 2); // Encode and decode. const encoded = encoder.encode(buffer); const decoded = encoder.decode(encoded); + +// Encode and decode 32-bit floating point PCM instead of 16-bit integer PCM. +const encodedFloat = encoder.encodeFloat(floatBuffer); +const decodedFloat = encoder.decodeFloat(encodedFloat); ``` ## Platform support diff --git a/src/node-opus.cc b/src/node-opus.cc index ad52b793..ca2ad2fa 100644 --- a/src/node-opus.cc +++ b/src/node-opus.cc @@ -1,6 +1,7 @@ #include "napi.h" #include "../deps/opus/include/opus.h" #include "node-opus.h" +#include using namespace Napi; @@ -30,7 +31,9 @@ Object NodeOpusEncoder::Init(Napi::Env env, Object exports) { Function func = DefineClass(env, "OpusEncoder", { InstanceMethod("encode", &NodeOpusEncoder::Encode), + InstanceMethod("encodeFloat", &NodeOpusEncoder::EncodeFloat), InstanceMethod("decode", &NodeOpusEncoder::Decode), + InstanceMethod("decodeFloat", &NodeOpusEncoder::DecodeFloat), InstanceMethod("applyEncoderCTL", &NodeOpusEncoder::ApplyEncoderCTL), InstanceMethod("applyDecoderCTL", &NodeOpusEncoder::ApplyDecoderCTL), InstanceMethod("setBitrate", &NodeOpusEncoder::SetBitrate), @@ -126,6 +129,47 @@ Napi::Value NodeOpusEncoder::Encode(const CallbackInfo& args) { return Buffer::Copy(env, reinterpret_cast(this->outOpus), compressedLength); } +Napi::Value NodeOpusEncoder::EncodeFloat(const CallbackInfo& args) { + Napi::Env env = args.Env(); + + if (this->EnsureEncoder() != OPUS_OK) { + Napi::Error::New(env, "Could not create encoder. Check the encoder parameters").ThrowAsJavaScriptException(); + return env.Null(); + } + + if (args.Length() < 1) { + Napi::RangeError::New(env, "Expected 1 argument").ThrowAsJavaScriptException(); + return env.Null(); + } + + if (!args[0].IsTypedArray()) { + Napi::TypeError::New(env, "Provided input needs to be a buffer").ThrowAsJavaScriptException(); + return env.Null(); + } + + Buffer buf = args[0].As>(); + int frameSize = buf.Length() / sizeof(float) / this->channels; + + // Opus never accepts frames longer than this, so don't bother copying them. + if (frameSize > MAX_FRAME_SIZE) { + Napi::TypeError::New(env, getOpusError(OPUS_BAD_ARG)).ThrowAsJavaScriptException(); + return env.Null(); + } + + // The buffer isn't guaranteed to be aligned for floats (e.g. pooled Buffers), so copy the samples out. + std::vector pcm(static_cast(frameSize) * this->channels); + memcpy(pcm.data(), buf.Data(), pcm.size() * sizeof(float)); + + int compressedLength = opus_encode_float(this->encoder, pcm.data(), frameSize, &(this->outOpus[0]), MAX_PACKET_SIZE); + + if (compressedLength < 0) { + Napi::TypeError::New(env, getOpusError(compressedLength)).ThrowAsJavaScriptException(); + return env.Null(); + } + + return Buffer::Copy(env, reinterpret_cast(this->outOpus), compressedLength); +} + Napi::Value NodeOpusEncoder::Decode(const CallbackInfo& args) { Napi::Env env = args.Env(); @@ -167,6 +211,50 @@ Napi::Value NodeOpusEncoder::Decode(const CallbackInfo& args) { return Buffer::Copy(env, reinterpret_cast(this->outPcm), decodedLength); } +Napi::Value NodeOpusEncoder::DecodeFloat(const CallbackInfo& args) { + Napi::Env env = args.Env(); + + if (args.Length() < 1) { + Napi::RangeError::New(env, "Expected 1 argument").ThrowAsJavaScriptException(); + return env.Null(); + } + + if (!args[0].IsTypedArray()) { + Napi::TypeError::New(env, "Provided input needs to be a buffer").ThrowAsJavaScriptException(); + return env.Null(); + } + + Buffer buf = args[0].As>(); + unsigned char* compressedData = buf.Data(); + size_t compressedDataLength = buf.Length(); + + if (this->EnsureDecoder() != OPUS_OK) { + Napi::Error::New(env, "Could not create decoder. Check the decoder parameters").ThrowAsJavaScriptException(); + return env.Null(); + } + + // Opus decodes at most 2 channels. + if (this->outPcmFloat.empty()) this->outPcmFloat.resize(2 * MAX_FRAME_SIZE); + + int decodedSamples = opus_decode_float( + this->decoder, + compressedData, + compressedDataLength, + this->outPcmFloat.data(), + MAX_FRAME_SIZE, + /* decode_fec */ 0 + ); + + if (decodedSamples < 0) { + Napi::TypeError::New(env, getOpusError(decodedSamples)).ThrowAsJavaScriptException(); + return env.Null(); + } + + int decodedLength = decodedSamples * sizeof(float) * this->channels; + + return Buffer::Copy(env, reinterpret_cast(this->outPcmFloat.data()), decodedLength); +} + void NodeOpusEncoder::ApplyEncoderCTL(const CallbackInfo& args) { Napi::Env env = args.Env(); diff --git a/src/node-opus.h b/src/node-opus.h index a984a078..917b5851 100644 --- a/src/node-opus.h +++ b/src/node-opus.h @@ -1,3 +1,5 @@ +#include + using namespace Napi; #define FRAME_SIZE 960 @@ -17,6 +19,8 @@ class NodeOpusEncoder : public ObjectWrap { unsigned char outOpus[MAX_PACKET_SIZE]; // Opus decodes at most 2 channels. opus_int16 outPcm[2 * MAX_FRAME_SIZE]; + // Only allocated once decodeFloat() is used. + std::vector outPcmFloat; protected: int EnsureEncoder(); @@ -31,8 +35,12 @@ class NodeOpusEncoder : public ObjectWrap { ~NodeOpusEncoder(); Napi::Value Encode(const CallbackInfo& args); + + Napi::Value EncodeFloat(const CallbackInfo& args); Napi::Value Decode(const CallbackInfo& args); + + Napi::Value DecodeFloat(const CallbackInfo& args); void ApplyEncoderCTL(const CallbackInfo& args); diff --git a/tests/test.js b/tests/test.js index e75d4ea5..c57e2117 100644 --- a/tests/test.js +++ b/tests/test.js @@ -17,6 +17,36 @@ const { OpusEncoder } = require('../lib/index.js'); assert(reEncoded.length === 45, 're-encoded frame length is not 45'); } +// Float encoding test +{ + const frame = fs.readFileSync(path.join(__dirname, 'frame.opus')); + + const decoded = new OpusEncoder(16_000, 1).decode(frame); + const decodedFloat = new OpusEncoder(16_000, 1).decodeFloat(frame); + + assert(decodedFloat.length === 1280, 'Decoded float frame length is not 1280'); + + // The float output matches the 16-bit output to within a single 16-bit step. + for (let index = 0; index < decoded.length / 2; index++) { + const expected = decoded.readInt16LE(index * 2) / 32_768; + assert(Math.abs(decodedFloat.readFloatLE(index * 4) - expected) <= 1 / 32_768, `Sample ${index} differs`); + } + + const opus = new OpusEncoder(16_000, 1); + const reEncoded = opus.encodeFloat(decodedFloat); + assert(reEncoded.length === 45, 're-encoded float frame length is not 45'); + + // Typed arrays and buffers that aren't aligned to 4 bytes are accepted + const samples = new Float32Array( + decodedFloat.buffer.slice(decodedFloat.byteOffset, decodedFloat.byteOffset + decodedFloat.length), + ); + assert(new OpusEncoder(16_000, 1).encodeFloat(samples).equals(reEncoded), 'Float32Array input differs'); + + const unaligned = Buffer.alloc(decodedFloat.length + 1); + decodedFloat.copy(unaligned, 1); + assert(new OpusEncoder(16_000, 1).encodeFloat(unaligned.subarray(1)).equals(reEncoded), 'Unaligned input differs'); +} + // Default values work { new OpusEncoder(); @@ -37,6 +67,16 @@ const { OpusEncoder } = require('../lib/index.js'); () => new OpusEncoder().decode(new DataView(new ArrayBuffer(0))), /Provided input needs to be a buffer/, ); + assert.throws( + () => new OpusEncoder().encodeFloat(new DataView(new ArrayBuffer(7680))), + /Provided input needs to be a buffer/, + ); + assert.throws( + () => new OpusEncoder().decodeFloat(new DataView(new ArrayBuffer(0))), + /Provided input needs to be a buffer/, + ); + assert.throws(() => new OpusEncoder().encodeFloat(), /Expected 1 argument/); + assert.throws(() => new OpusEncoder().decodeFloat(), /Expected 1 argument/); } // Invalid values throw @@ -45,6 +85,8 @@ const { OpusEncoder } = require('../lib/index.js'); assert.throws(() => opus.encode(Buffer.alloc(960 * 2)), /Could not create encoder/); assert.throws(() => opus.decode(Buffer.alloc(3)), /Could not create decoder/); + assert.throws(() => opus.encodeFloat(Buffer.alloc(960 * 4)), /Could not create encoder/); + assert.throws(() => opus.decodeFloat(Buffer.alloc(3)), /Could not create decoder/); } // Failing to encode throws @@ -55,4 +97,31 @@ const { OpusEncoder } = require('../lib/index.js'); assert(opus.encode(Buffer.alloc(960 * 2 * 2)).length > 0, 'Encoding a valid frame after an error failed'); } +// Failing to encode floats throws +{ + const opus = new OpusEncoder(48_000, 2); + + assert.throws(() => opus.encodeFloat(Buffer.alloc(10)), /One or more invalid\/out of range arguments/); + assert.throws( + () => opus.encodeFloat(Buffer.alloc(6 * 960 * 2 * 4 + 8)), + /One or more invalid\/out of range arguments/, + ); + assert(opus.encodeFloat(Buffer.alloc(960 * 2 * 4)).length > 0, 'Encoding a valid float frame after an error failed'); +} + +// Failing to decode floats throws +{ + const opus = new OpusEncoder(48_000, 2); + + assert.throws(() => opus.decodeFloat(Buffer.from([0xff, 0xff, 0xff])), /The compressed data passed is corrupted/); +} + +// Float round trip at 48kHz stereo +{ + const opus = new OpusEncoder(48_000, 2); + const decoded = opus.decodeFloat(opus.encodeFloat(Buffer.alloc(960 * 2 * 4))); + + assert(decoded.length === 960 * 2 * 4, 'Round-tripped float frame length is not 7680'); +} + console.log('Passed'); diff --git a/typings/index.d.ts b/typings/index.d.ts index eaa6757d..f7347589 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -2,11 +2,21 @@ declare module '@discordjs/opus' { export class OpusEncoder { public constructor(rate?: number, channels?: number); public encode(buf: Buffer): Buffer; + /** + * Encodes the given PCM 32-bit little-endian floating point samples (in the range -1.0 to 1.0) to an Opus buffer + * @param buf PCM float buffer + */ + public encodeFloat(buf: Buffer | Float32Array): Buffer; /** * Decodes the given Opus buffer to PCM signed 16-bit little-endian * @param buf Opus buffer */ public decode(buf: Buffer): Buffer; + /** + * Decodes the given Opus buffer to PCM 32-bit little-endian floating point samples + * @param buf Opus buffer + */ + public decodeFloat(buf: Buffer): Buffer; public applyEncoderCTL(ctl: number, value: number): void; public applyDecoderCTL(ctl: number, value: number): void; public setBitrate(bitrate: number): void;