Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
88 changes: 88 additions & 0 deletions src/node-opus.cc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "napi.h"
#include "../deps/opus/include/opus.h"
#include "node-opus.h"
#include <cstring>

using namespace Napi;

Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -126,6 +129,47 @@ Napi::Value NodeOpusEncoder::Encode(const CallbackInfo& args) {
return Buffer<char>::Copy(env, reinterpret_cast<char*>(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<char> buf = args[0].As<Buffer<char>>();
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<float> pcm(static_cast<size_t>(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<char>::Copy(env, reinterpret_cast<char*>(this->outOpus), compressedLength);
}

Napi::Value NodeOpusEncoder::Decode(const CallbackInfo& args) {
Napi::Env env = args.Env();

Expand Down Expand Up @@ -167,6 +211,50 @@ Napi::Value NodeOpusEncoder::Decode(const CallbackInfo& args) {
return Buffer<char>::Copy(env, reinterpret_cast<char*>(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<unsigned char> buf = args[0].As<Buffer<unsigned char>>();
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<char>::Copy(env, reinterpret_cast<char*>(this->outPcmFloat.data()), decodedLength);
}

void NodeOpusEncoder::ApplyEncoderCTL(const CallbackInfo& args) {
Napi::Env env = args.Env();

Expand Down
8 changes: 8 additions & 0 deletions src/node-opus.h
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include <vector>

using namespace Napi;

#define FRAME_SIZE 960
Expand All @@ -17,6 +19,8 @@ class NodeOpusEncoder : public ObjectWrap<NodeOpusEncoder> {
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<float> outPcmFloat;

protected:
int EnsureEncoder();
Expand All @@ -31,8 +35,12 @@ class NodeOpusEncoder : public ObjectWrap<NodeOpusEncoder> {
~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);

Expand Down
69 changes: 69 additions & 0 deletions tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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');
10 changes: 10 additions & 0 deletions typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down