This commit is contained in:
skdhg committed 2023-08-06 20:49:41 +05:45
1 parent bcc733eca3
commit 6af1855646
15 files changed
+1221 -122

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[submodule "libopus"]
path = libopus
url = https://github.com/xiph/opus
+2 -2
View File
@@ -7,8 +7,6 @@ version = "0.0.0"
crate-type = ["cdylib"]
[dependencies]
audiopus = { version = "0.2.0", features = ["decoder", "encoder"] }
byteorder = "1.4.3"
dasp = { version = "0.11.0" }
# Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
napi = { version = "2.12.2", default-features = false, features = ["napi4"] }
@@ -17,6 +15,8 @@ symphonia = { version = "0.5.3", features = ["all"] }
[build-dependencies]
napi-build = "2.0.1"
cmake = "0.1"
bindgen = "0.59.1"
[profile.release]
lto = true
@@ -28,7 +28,7 @@
</head>
<body>
<div class="container">
<canvas id="chart1691322049684" width="16" height="9"></canvas>
<canvas id="chart1691334240726" width="16" height="9"></canvas>
</div>
<script>
const format = (num) => {
@@ -51,18 +51,18 @@
chunked.map((chunk) => chunk.join('')).join(' ') + fractionStr
)
}
const ctx1691322049684 = document
.getElementById('chart1691322049684')
const ctx1691334240726 = document
.getElementById('chart1691334240726')
.getContext('2d')
const chart1691322049684 = new Chart(ctx1691322049684, {
const chart1691334240726 = new Chart(ctx1691334240726, {
type: 'bar',
data: {
labels: ["mediaplex","@discordjs/opus","opusscript","opusscript (no wasm)"],
datasets: [
{
data: [10098,11674,6040,2579],
backgroundColor: ["hsl(103.8, 85%, 55%)","hsl(120, 85%, 55%)","hsl(62.087999999999994, 85%, 55%)","hsl(26.508000000000006, 85%, 55%)"],
borderColor: ["hsl(103.8, 85%, 55%)","hsl(120, 85%, 55%)","hsl(62.087999999999994, 85%, 55%)","hsl(26.508000000000006, 85%, 55%)"],
data: [10721,11758,5943,2560],
backgroundColor: ["hsl(109.41600000000001, 85%, 55%)","hsl(120, 85%, 55%)","hsl(60.647999999999996, 85%, 55%)","hsl(26.123999999999995, 85%, 55%)"],
borderColor: ["hsl(109.41600000000001, 85%, 55%)","hsl(120, 85%, 55%)","hsl(60.647999999999996, 85%, 55%)","hsl(26.123999999999995, 85%, 55%)"],
borderWidth: 2,
},
],
@@ -28,7 +28,7 @@
</head>
<body>
<div class="container">
<canvas id="chart1691322027037" width="16" height="9"></canvas>
<canvas id="chart1691334217982" width="16" height="9"></canvas>
</div>
<script>
const format = (num) => {
@@ -51,18 +51,18 @@
chunked.map((chunk) => chunk.join('')).join(' ') + fractionStr
)
}
const ctx1691322027037 = document
.getElementById('chart1691322027037')
const ctx1691334217982 = document
.getElementById('chart1691334217982')
.getContext('2d')
const chart1691322027037 = new Chart(ctx1691322027037, {
const chart1691334217982 = new Chart(ctx1691334217982, {
type: 'bar',
data: {
labels: ["mediaplex","@discordjs/opus","opusscript","opusscript (no wasm)"],
datasets: [
{
data: [3112,3119,4111,261],
backgroundColor: ["hsl(90.84, 85%, 55%)","hsl(91.04400000000001, 85%, 55%)","hsl(120, 85%, 55%)","hsl(7.619999999999994, 85%, 55%)"],
borderColor: ["hsl(90.84, 85%, 55%)","hsl(91.04400000000001, 85%, 55%)","hsl(120, 85%, 55%)","hsl(7.619999999999994, 85%, 55%)"],
data: [3589,3203,4190,259],
backgroundColor: ["hsl(102.79199999999999, 85%, 55%)","hsl(91.728, 85%, 55%)","hsl(120, 85%, 55%)","hsl(7.416000000000008, 85%, 55%)"],
borderColor: ["hsl(102.79199999999999, 85%, 55%)","hsl(91.728, 85%, 55%)","hsl(120, 85%, 55%)","hsl(7.416000000000008, 85%, 55%)"],
borderWidth: 2,
},
],
+119
View File
@@ -1,5 +1,124 @@
// based on https://github.com/Lakelezz/audiopus_sys
extern crate napi_build;
use std::path::PathBuf;
use std::{env, fmt::Display, path::Path};
use bindgen;
const fn rustc_linking_word(is_static_link: bool) -> &'static str {
if is_static_link {
"static"
} else {
"dylib"
}
}
fn generate_binding() {
const ALLOW_UNCONVENTIONALS: &'static str = "#![allow(non_upper_case_globals)]\n\
#![allow(non_camel_case_types)]\n\
#![allow(non_snake_case)]\n";
let bindings = bindgen::Builder::default()
.header("src/opus/libopus.h")
.raw_line(ALLOW_UNCONVENTIONALS)
.generate()
.expect("Unable to generate binding");
let binding_target_path = PathBuf::new().join("src").join("opus").join("lib.rs");
bindings
.write_to_file(binding_target_path)
.expect("Could not write binding to the file at `src/opus/lib.rs`");
println!("cargo:info=Successfully generated binding.");
}
fn build_opus(is_static: bool) {
let opus_path = Path::new("libopus");
println!(
"cargo:info=Opus source path used: {:?}.",
opus_path
.canonicalize()
.expect("Could not canonicalise to absolute path")
);
println!("cargo:info=Building Opus via CMake.");
let opus_build_dir = cmake::build(opus_path);
link_opus(is_static, opus_build_dir.display())
}
fn link_opus(is_static: bool, opus_build_dir: impl Display) {
let is_static_text = rustc_linking_word(is_static);
println!(
"cargo:info=Linking Opus as {} lib: {}",
is_static_text, opus_build_dir
);
println!("cargo:rustc-link-lib={}=opus", is_static_text);
println!("cargo:rustc-link-search=native={}/lib", opus_build_dir);
}
#[cfg(any(unix, target_env = "gnu"))]
fn find_via_pkg_config(is_static: bool) -> bool {
pkg_config::Config::new()
.statik(is_static)
.probe("opus")
.is_ok()
}
fn default_library_linking() -> bool {
#[cfg(any(windows, target_os = "macos", target_env = "musl"))]
{
true
}
#[cfg(any(target_os = "freebsd", all(unix, target_env = "gnu")))]
{
false
}
}
fn is_static_build() -> bool {
if cfg!(feature = "static") && cfg!(feature = "dynamic") {
default_library_linking()
} else if cfg!(feature = "static")
|| env::var("LIBOPUS_STATIC").is_ok()
|| env::var("OPUS_STATIC").is_ok()
{
println!("cargo:info=Static feature or environment variable found.");
true
} else if cfg!(feature = "dynamic") {
println!("cargo:info=Dynamic feature enabled.");
false
} else {
println!("cargo:info=No feature or environment variable found, linking by default.");
default_library_linking()
}
}
fn main() {
generate_binding();
let is_static = is_static_build();
#[cfg(any(unix, target_env = "gnu"))]
{
if std::env::var("LIBOPUS_NO_PKG").is_ok() || std::env::var("OPUS_NO_PKG").is_ok() {
println!("cargo:info=Bypassed `pkg-config`.");
} else if find_via_pkg_config(is_static) {
println!("cargo:info=Found `Opus` via `pkg_config`.");
return;
} else {
println!("cargo:info=`pkg_config` could not find `Opus`.");
}
}
build_opus(is_static);
napi_build::setup();
}
+92
View File
@@ -3,6 +3,97 @@
/* auto-generated by NAPI-RS */
export function getOpusVersion(): string
export interface ProbeResult {
/** The number of channels */
channels: number
/** The sample rate */
sampleRate: number
/** The number of frames per block */
framesPerBlock: number
/** The codec type */
codec: CodecType
/** The number of frames */
nFrames: number
/** The approximate duration of this media in seconds */
duration: number
/** The metadata object */
metadata: Array<MetadataField>
}
export const enum CodecType {
UNKNOWN = 0,
PCM_S32LE = 256,
PCM_S32LE_PLANAR = 257,
PCM_S32BE = 258,
PCM_S32BE_PLANAR = 259,
PCM_S24LE = 260,
PCM_S24LE_PLANAR = 261,
PCM_S24BE = 262,
PCM_S24BE_PLANAR = 263,
PCM_S16LE = 264,
PCM_S16LE_PLANAR = 265,
PCM_S16BE = 266,
PCM_S16BE_PLANAR = 267,
PCM_S8 = 268,
PCM_S8_PLANAR = 269,
PCM_U32LE = 270,
PCM_U32LE_PLANAR = 271,
PCM_U32BE = 272,
PCM_U32BE_PLANAR = 273,
PCM_U24LE = 274,
PCM_U24LE_PLANAR = 275,
PCM_U24BE = 276,
PCM_U24BE_PLANAR = 277,
PCM_U16LE = 278,
PCM_U16LE_PLANAR = 279,
PCM_U16BE = 280,
PCM_U16BE_PLANAR = 281,
PCM_U8 = 282,
PCM_U8_PLANAR = 283,
PCM_F32LE = 284,
PCM_F32LE_PLANAR = 285,
PCM_F32BE = 286,
PCM_F32BE_PLANAR = 287,
PCM_F64LE = 288,
PCM_F64LE_PLANAR = 289,
PCM_F64BE = 290,
PCM_F64BE_PLANAR = 291,
PCM_ALAW = 292,
PCM_MULAW = 293,
ADPCM_G722 = 512,
ADPCM_G726 = 513,
ADPCM_G726LE = 514,
ADPCM_MS = 515,
ADPCM_IMA_WAV = 516,
ADPCM_IMA_QT = 517,
VORBIS = 4096,
MP1 = 4097,
MP2 = 4098,
MP3 = 4099,
AAC = 4100,
OPUS = 4101,
SPEEX = 4102,
MUSEPACK = 4103,
ATRAC1 = 4104,
ATRAC3 = 4105,
ATRAC3PLUS = 4106,
ATRAC9 = 4107,
EAC3 = 4108,
AC4 = 4109,
DCA = 4110,
WMA = 4111,
FLAC = 8192,
WAVPACK = 8193,
MONKEYS_AUDIO = 8194,
ALAC = 8195,
TTA = 8196
}
export interface MetadataField {
name: string
value: string
}
export function probe(data: Buffer): ProbeResult
export type JsOpusEncoder = OpusEncoder
export class OpusEncoder {
constructor(sampleRate: number, channels: number)
encode(data: Buffer): Buffer
@@ -11,5 +102,6 @@ export class OpusEncoder {
getBitrate(): number
applyEncoderCtl(request: number, value: number): void
applyDecoderCtl(request: number, value: number): void
get version(): string
destroy(): void
}
+4 -1
View File
@@ -252,6 +252,9 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}
const { OpusEncoder } = nativeBinding
const { getOpusVersion, OpusEncoder, CodecType, probe } = nativeBinding
module.exports.getOpusVersion = getOpusVersion
module.exports.OpusEncoder = OpusEncoder
module.exports.CodecType = CodecType
module.exports.probe = probe
Submodule
+1
Submodule libopus added at 9fc8fc4cf4.
+1
View File
@@ -25,6 +25,7 @@
"devDependencies": {
"@discordjs/opus": "^0.9.0",
"@napi-rs/cli": "^2.16.1",
"@types/node": "^20.4.8",
"ava": "^5.1.1",
"benny": "^3.7.1",
"opusscript": "^0.1.0"
+1 -1
View File
@@ -1,5 +1,5 @@
#![deny(clippy::all)]
#![allow(non_camel_case_types, non_snake_case)]
#![allow(non_camel_case_types, non_snake_case, unused)]
#[macro_use]
extern crate napi_derive;
+755
View File
@@ -0,0 +1,755 @@
/* automatically generated by rust-bindgen 0.59.2 */
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
pub const OPUS_OK: u32 = 0;
pub const OPUS_BAD_ARG: i32 = -1;
pub const OPUS_BUFFER_TOO_SMALL: i32 = -2;
pub const OPUS_INTERNAL_ERROR: i32 = -3;
pub const OPUS_INVALID_PACKET: i32 = -4;
pub const OPUS_UNIMPLEMENTED: i32 = -5;
pub const OPUS_INVALID_STATE: i32 = -6;
pub const OPUS_ALLOC_FAIL: i32 = -7;
pub const OPUS_SET_APPLICATION_REQUEST: u32 = 4000;
pub const OPUS_GET_APPLICATION_REQUEST: u32 = 4001;
pub const OPUS_SET_BITRATE_REQUEST: u32 = 4002;
pub const OPUS_GET_BITRATE_REQUEST: u32 = 4003;
pub const OPUS_SET_MAX_BANDWIDTH_REQUEST: u32 = 4004;
pub const OPUS_GET_MAX_BANDWIDTH_REQUEST: u32 = 4005;
pub const OPUS_SET_VBR_REQUEST: u32 = 4006;
pub const OPUS_GET_VBR_REQUEST: u32 = 4007;
pub const OPUS_SET_BANDWIDTH_REQUEST: u32 = 4008;
pub const OPUS_GET_BANDWIDTH_REQUEST: u32 = 4009;
pub const OPUS_SET_COMPLEXITY_REQUEST: u32 = 4010;
pub const OPUS_GET_COMPLEXITY_REQUEST: u32 = 4011;
pub const OPUS_SET_INBAND_FEC_REQUEST: u32 = 4012;
pub const OPUS_GET_INBAND_FEC_REQUEST: u32 = 4013;
pub const OPUS_SET_PACKET_LOSS_PERC_REQUEST: u32 = 4014;
pub const OPUS_GET_PACKET_LOSS_PERC_REQUEST: u32 = 4015;
pub const OPUS_SET_DTX_REQUEST: u32 = 4016;
pub const OPUS_GET_DTX_REQUEST: u32 = 4017;
pub const OPUS_SET_VBR_CONSTRAINT_REQUEST: u32 = 4020;
pub const OPUS_GET_VBR_CONSTRAINT_REQUEST: u32 = 4021;
pub const OPUS_SET_FORCE_CHANNELS_REQUEST: u32 = 4022;
pub const OPUS_GET_FORCE_CHANNELS_REQUEST: u32 = 4023;
pub const OPUS_SET_SIGNAL_REQUEST: u32 = 4024;
pub const OPUS_GET_SIGNAL_REQUEST: u32 = 4025;
pub const OPUS_GET_LOOKAHEAD_REQUEST: u32 = 4027;
pub const OPUS_GET_SAMPLE_RATE_REQUEST: u32 = 4029;
pub const OPUS_GET_FINAL_RANGE_REQUEST: u32 = 4031;
pub const OPUS_GET_PITCH_REQUEST: u32 = 4033;
pub const OPUS_SET_GAIN_REQUEST: u32 = 4034;
pub const OPUS_GET_GAIN_REQUEST: u32 = 4045;
pub const OPUS_SET_LSB_DEPTH_REQUEST: u32 = 4036;
pub const OPUS_GET_LSB_DEPTH_REQUEST: u32 = 4037;
pub const OPUS_GET_LAST_PACKET_DURATION_REQUEST: u32 = 4039;
pub const OPUS_SET_EXPERT_FRAME_DURATION_REQUEST: u32 = 4040;
pub const OPUS_GET_EXPERT_FRAME_DURATION_REQUEST: u32 = 4041;
pub const OPUS_SET_PREDICTION_DISABLED_REQUEST: u32 = 4042;
pub const OPUS_GET_PREDICTION_DISABLED_REQUEST: u32 = 4043;
pub const OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST: u32 = 4046;
pub const OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST: u32 = 4047;
pub const OPUS_GET_IN_DTX_REQUEST: u32 = 4049;
pub const OPUS_AUTO: i32 = -1000;
pub const OPUS_BITRATE_MAX: i32 = -1;
pub const OPUS_APPLICATION_VOIP: u32 = 2048;
pub const OPUS_APPLICATION_AUDIO: u32 = 2049;
pub const OPUS_APPLICATION_RESTRICTED_LOWDELAY: u32 = 2051;
pub const OPUS_SIGNAL_VOICE: u32 = 3001;
pub const OPUS_SIGNAL_MUSIC: u32 = 3002;
pub const OPUS_BANDWIDTH_NARROWBAND: u32 = 1101;
pub const OPUS_BANDWIDTH_MEDIUMBAND: u32 = 1102;
pub const OPUS_BANDWIDTH_WIDEBAND: u32 = 1103;
pub const OPUS_BANDWIDTH_SUPERWIDEBAND: u32 = 1104;
pub const OPUS_BANDWIDTH_FULLBAND: u32 = 1105;
pub const OPUS_FRAMESIZE_ARG: u32 = 5000;
pub const OPUS_FRAMESIZE_2_5_MS: u32 = 5001;
pub const OPUS_FRAMESIZE_5_MS: u32 = 5002;
pub const OPUS_FRAMESIZE_10_MS: u32 = 5003;
pub const OPUS_FRAMESIZE_20_MS: u32 = 5004;
pub const OPUS_FRAMESIZE_40_MS: u32 = 5005;
pub const OPUS_FRAMESIZE_60_MS: u32 = 5006;
pub const OPUS_FRAMESIZE_80_MS: u32 = 5007;
pub const OPUS_FRAMESIZE_100_MS: u32 = 5008;
pub const OPUS_FRAMESIZE_120_MS: u32 = 5009;
pub const OPUS_RESET_STATE: u32 = 4028;
pub type opus_int32 = ::std::os::raw::c_int;
pub type opus_uint32 = ::std::os::raw::c_uint;
pub type opus_int16 = ::std::os::raw::c_short;
pub type opus_uint16 = ::std::os::raw::c_ushort;
extern "C" {
#[doc = " Converts an opus error code into a human readable string."]
#[doc = ""]
#[doc = " @param[in] error <tt>int</tt>: Error number"]
#[doc = " @returns Error string"]
pub fn opus_strerror(error: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char;
}
extern "C" {
#[doc = " Gets the libopus version string."]
#[doc = ""]
#[doc = " Applications may look for the substring \"-fixed\" in the version string to"]
#[doc = " determine whether they have a fixed-point or floating-point build at"]
#[doc = " runtime."]
#[doc = ""]
#[doc = " @returns Version string"]
pub fn opus_get_version_string() -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct OpusEncoder {
_unused: [u8; 0],
}
extern "C" {
#[doc = " Gets the size of an <code>OpusEncoder</code> structure."]
#[doc = " @param[in] channels <tt>int</tt>: Number of channels."]
#[doc = " This must be 1 or 2."]
#[doc = " @returns The size in bytes."]
pub fn opus_encoder_get_size(channels: ::std::os::raw::c_int) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Allocates and initializes an encoder state."]
#[doc = " There are three coding modes:"]
#[doc = ""]
#[doc = " @ref OPUS_APPLICATION_VOIP gives best quality at a given bitrate for voice"]
#[doc = " signals. It enhances the input signal by high-pass filtering and"]
#[doc = " emphasizing formants and harmonics. Optionally it includes in-band"]
#[doc = " forward error correction to protect against packet loss. Use this"]
#[doc = " mode for typical VoIP applications. Because of the enhancement,"]
#[doc = " even at high bitrates the output may sound different from the input."]
#[doc = ""]
#[doc = " @ref OPUS_APPLICATION_AUDIO gives best quality at a given bitrate for most"]
#[doc = " non-voice signals like music. Use this mode for music and mixed"]
#[doc = " (music/voice) content, broadcast, and applications requiring less"]
#[doc = " than 15 ms of coding delay."]
#[doc = ""]
#[doc = " @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY configures low-delay mode that"]
#[doc = " disables the speech-optimized mode in exchange for slightly reduced delay."]
#[doc = " This mode can only be set on an newly initialized or freshly reset encoder"]
#[doc = " because it changes the codec delay."]
#[doc = ""]
#[doc = " This is useful when the caller knows that the speech-optimized modes will not be needed (use with caution)."]
#[doc = " @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)"]
#[doc = " This must be one of 8000, 12000, 16000,"]
#[doc = " 24000, or 48000."]
#[doc = " @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal"]
#[doc = " @param [in] application <tt>int</tt>: Coding mode (one of @ref OPUS_APPLICATION_VOIP, @ref OPUS_APPLICATION_AUDIO, or @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY)"]
#[doc = " @param [out] error <tt>int*</tt>: @ref opus_errorcodes"]
#[doc = " @note Regardless of the sampling rate and number channels selected, the Opus encoder"]
#[doc = " can switch to a lower audio bandwidth or number of channels if the bitrate"]
#[doc = " selected is too low. This also means that it is safe to always use 48 kHz stereo input"]
#[doc = " and let the encoder optimize the encoding."]
pub fn opus_encoder_create(
Fs: opus_int32,
channels: ::std::os::raw::c_int,
application: ::std::os::raw::c_int,
error: *mut ::std::os::raw::c_int,
) -> *mut OpusEncoder;
}
extern "C" {
#[doc = " Initializes a previously allocated encoder state"]
#[doc = " The memory pointed to by st must be at least the size returned by opus_encoder_get_size()."]
#[doc = " This is intended for applications which use their own allocator instead of malloc."]
#[doc = " @see opus_encoder_create(),opus_encoder_get_size()"]
#[doc = " To reset a previously initialized state, use the #OPUS_RESET_STATE CTL."]
#[doc = " @param [in] st <tt>OpusEncoder*</tt>: Encoder state"]
#[doc = " @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)"]
#[doc = " This must be one of 8000, 12000, 16000,"]
#[doc = " 24000, or 48000."]
#[doc = " @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal"]
#[doc = " @param [in] application <tt>int</tt>: Coding mode (one of OPUS_APPLICATION_VOIP, OPUS_APPLICATION_AUDIO, or OPUS_APPLICATION_RESTRICTED_LOWDELAY)"]
#[doc = " @retval #OPUS_OK Success or @ref opus_errorcodes"]
pub fn opus_encoder_init(
st: *mut OpusEncoder,
Fs: opus_int32,
channels: ::std::os::raw::c_int,
application: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Encodes an Opus frame."]
#[doc = " @param [in] st <tt>OpusEncoder*</tt>: Encoder state"]
#[doc = " @param [in] pcm <tt>opus_int16*</tt>: Input signal (interleaved if 2 channels). length is frame_size*channels*sizeof(opus_int16)"]
#[doc = " @param [in] frame_size <tt>int</tt>: Number of samples per channel in the"]
#[doc = " input signal."]
#[doc = " This must be an Opus frame size for"]
#[doc = " the encoder's sampling rate."]
#[doc = " For example, at 48 kHz the permitted"]
#[doc = " values are 120, 240, 480, 960, 1920,"]
#[doc = " and 2880."]
#[doc = " Passing in a duration of less than"]
#[doc = " 10 ms (480 samples at 48 kHz) will"]
#[doc = " prevent the encoder from using the LPC"]
#[doc = " or hybrid modes."]
#[doc = " @param [out] data <tt>unsigned char*</tt>: Output payload."]
#[doc = " This must contain storage for at"]
#[doc = " least \\a max_data_bytes."]
#[doc = " @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated"]
#[doc = " memory for the output"]
#[doc = " payload. This may be"]
#[doc = " used to impose an upper limit on"]
#[doc = " the instant bitrate, but should"]
#[doc = " not be used as the only bitrate"]
#[doc = " control. Use #OPUS_SET_BITRATE to"]
#[doc = " control the bitrate."]
#[doc = " @returns The length of the encoded packet (in bytes) on success or a"]
#[doc = " negative error code (see @ref opus_errorcodes) on failure."]
pub fn opus_encode(
st: *mut OpusEncoder,
pcm: *const opus_int16,
frame_size: ::std::os::raw::c_int,
data: *mut ::std::os::raw::c_uchar,
max_data_bytes: opus_int32,
) -> opus_int32;
}
extern "C" {
#[doc = " Encodes an Opus frame from floating point input."]
#[doc = " @param [in] st <tt>OpusEncoder*</tt>: Encoder state"]
#[doc = " @param [in] pcm <tt>float*</tt>: Input in float format (interleaved if 2 channels), with a normal range of +/-1.0."]
#[doc = " Samples with a range beyond +/-1.0 are supported but will"]
#[doc = " be clipped by decoders using the integer API and should"]
#[doc = " only be used if it is known that the far end supports"]
#[doc = " extended dynamic range."]
#[doc = " length is frame_size*channels*sizeof(float)"]
#[doc = " @param [in] frame_size <tt>int</tt>: Number of samples per channel in the"]
#[doc = " input signal."]
#[doc = " This must be an Opus frame size for"]
#[doc = " the encoder's sampling rate."]
#[doc = " For example, at 48 kHz the permitted"]
#[doc = " values are 120, 240, 480, 960, 1920,"]
#[doc = " and 2880."]
#[doc = " Passing in a duration of less than"]
#[doc = " 10 ms (480 samples at 48 kHz) will"]
#[doc = " prevent the encoder from using the LPC"]
#[doc = " or hybrid modes."]
#[doc = " @param [out] data <tt>unsigned char*</tt>: Output payload."]
#[doc = " This must contain storage for at"]
#[doc = " least \\a max_data_bytes."]
#[doc = " @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated"]
#[doc = " memory for the output"]
#[doc = " payload. This may be"]
#[doc = " used to impose an upper limit on"]
#[doc = " the instant bitrate, but should"]
#[doc = " not be used as the only bitrate"]
#[doc = " control. Use #OPUS_SET_BITRATE to"]
#[doc = " control the bitrate."]
#[doc = " @returns The length of the encoded packet (in bytes) on success or a"]
#[doc = " negative error code (see @ref opus_errorcodes) on failure."]
pub fn opus_encode_float(
st: *mut OpusEncoder,
pcm: *const f32,
frame_size: ::std::os::raw::c_int,
data: *mut ::std::os::raw::c_uchar,
max_data_bytes: opus_int32,
) -> opus_int32;
}
extern "C" {
#[doc = " Frees an <code>OpusEncoder</code> allocated by opus_encoder_create()."]
#[doc = " @param[in] st <tt>OpusEncoder*</tt>: State to be freed."]
pub fn opus_encoder_destroy(st: *mut OpusEncoder);
}
extern "C" {
#[doc = " Perform a CTL function on an Opus encoder."]
#[doc = ""]
#[doc = " Generally the request and subsequent arguments are generated"]
#[doc = " by a convenience macro."]
#[doc = " @param st <tt>OpusEncoder*</tt>: Encoder state."]
#[doc = " @param request This and all remaining parameters should be replaced by one"]
#[doc = " of the convenience macros in @ref opus_genericctls or"]
#[doc = " @ref opus_encoderctls."]
#[doc = " @see opus_genericctls"]
#[doc = " @see opus_encoderctls"]
pub fn opus_encoder_ctl(
st: *mut OpusEncoder,
request: ::std::os::raw::c_int,
...
) -> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct OpusDecoder {
_unused: [u8; 0],
}
extern "C" {
#[doc = " Gets the size of an <code>OpusDecoder</code> structure."]
#[doc = " @param [in] channels <tt>int</tt>: Number of channels."]
#[doc = " This must be 1 or 2."]
#[doc = " @returns The size in bytes."]
pub fn opus_decoder_get_size(channels: ::std::os::raw::c_int) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Allocates and initializes a decoder state."]
#[doc = " @param [in] Fs <tt>opus_int32</tt>: Sample rate to decode at (Hz)."]
#[doc = " This must be one of 8000, 12000, 16000,"]
#[doc = " 24000, or 48000."]
#[doc = " @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode"]
#[doc = " @param [out] error <tt>int*</tt>: #OPUS_OK Success or @ref opus_errorcodes"]
#[doc = ""]
#[doc = " Internally Opus stores data at 48000 Hz, so that should be the default"]
#[doc = " value for Fs. However, the decoder can efficiently decode to buffers"]
#[doc = " at 8, 12, 16, and 24 kHz so if for some reason the caller cannot use"]
#[doc = " data at the full sample rate, or knows the compressed data doesn't"]
#[doc = " use the full frequency range, it can request decoding at a reduced"]
#[doc = " rate. Likewise, the decoder is capable of filling in either mono or"]
#[doc = " interleaved stereo pcm buffers, at the caller's request."]
pub fn opus_decoder_create(
Fs: opus_int32,
channels: ::std::os::raw::c_int,
error: *mut ::std::os::raw::c_int,
) -> *mut OpusDecoder;
}
extern "C" {
#[doc = " Initializes a previously allocated decoder state."]
#[doc = " The state must be at least the size returned by opus_decoder_get_size()."]
#[doc = " This is intended for applications which use their own allocator instead of malloc. @see opus_decoder_create,opus_decoder_get_size"]
#[doc = " To reset a previously initialized state, use the #OPUS_RESET_STATE CTL."]
#[doc = " @param [in] st <tt>OpusDecoder*</tt>: Decoder state."]
#[doc = " @param [in] Fs <tt>opus_int32</tt>: Sampling rate to decode to (Hz)."]
#[doc = " This must be one of 8000, 12000, 16000,"]
#[doc = " 24000, or 48000."]
#[doc = " @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode"]
#[doc = " @retval #OPUS_OK Success or @ref opus_errorcodes"]
pub fn opus_decoder_init(
st: *mut OpusDecoder,
Fs: opus_int32,
channels: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Decode an Opus packet."]
#[doc = " @param [in] st <tt>OpusDecoder*</tt>: Decoder state"]
#[doc = " @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss"]
#[doc = " @param [in] len <tt>opus_int32</tt>: Number of bytes in payload*"]
#[doc = " @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length"]
#[doc = " is frame_size*channels*sizeof(opus_int16)"]
#[doc = " @param [in] frame_size Number of samples per channel of available space in \\a pcm."]
#[doc = " If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will"]
#[doc = " not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),"]
#[doc = " then frame_size needs to be exactly the duration of audio that is missing, otherwise the"]
#[doc = " decoder will not be in the optimal state to decode the next incoming packet. For the PLC and"]
#[doc = " FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms."]
#[doc = " @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be"]
#[doc = " decoded. If no such data is available, the frame is decoded as if it were lost."]
#[doc = " @returns Number of decoded samples or @ref opus_errorcodes"]
pub fn opus_decode(
st: *mut OpusDecoder,
data: *const ::std::os::raw::c_uchar,
len: opus_int32,
pcm: *mut opus_int16,
frame_size: ::std::os::raw::c_int,
decode_fec: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Decode an Opus packet with floating point output."]
#[doc = " @param [in] st <tt>OpusDecoder*</tt>: Decoder state"]
#[doc = " @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss"]
#[doc = " @param [in] len <tt>opus_int32</tt>: Number of bytes in payload"]
#[doc = " @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length"]
#[doc = " is frame_size*channels*sizeof(float)"]
#[doc = " @param [in] frame_size Number of samples per channel of available space in \\a pcm."]
#[doc = " If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will"]
#[doc = " not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),"]
#[doc = " then frame_size needs to be exactly the duration of audio that is missing, otherwise the"]
#[doc = " decoder will not be in the optimal state to decode the next incoming packet. For the PLC and"]
#[doc = " FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms."]
#[doc = " @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be"]
#[doc = " decoded. If no such data is available the frame is decoded as if it were lost."]
#[doc = " @returns Number of decoded samples or @ref opus_errorcodes"]
pub fn opus_decode_float(
st: *mut OpusDecoder,
data: *const ::std::os::raw::c_uchar,
len: opus_int32,
pcm: *mut f32,
frame_size: ::std::os::raw::c_int,
decode_fec: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Perform a CTL function on an Opus decoder."]
#[doc = ""]
#[doc = " Generally the request and subsequent arguments are generated"]
#[doc = " by a convenience macro."]
#[doc = " @param st <tt>OpusDecoder*</tt>: Decoder state."]
#[doc = " @param request This and all remaining parameters should be replaced by one"]
#[doc = " of the convenience macros in @ref opus_genericctls or"]
#[doc = " @ref opus_decoderctls."]
#[doc = " @see opus_genericctls"]
#[doc = " @see opus_decoderctls"]
pub fn opus_decoder_ctl(
st: *mut OpusDecoder,
request: ::std::os::raw::c_int,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Frees an <code>OpusDecoder</code> allocated by opus_decoder_create()."]
#[doc = " @param[in] st <tt>OpusDecoder*</tt>: State to be freed."]
pub fn opus_decoder_destroy(st: *mut OpusDecoder);
}
extern "C" {
#[doc = " Parse an opus packet into one or more frames."]
#[doc = " Opus_decode will perform this operation internally so most applications do"]
#[doc = " not need to use this function."]
#[doc = " This function does not copy the frames, the returned pointers are pointers into"]
#[doc = " the input packet."]
#[doc = " @param [in] data <tt>char*</tt>: Opus packet to be parsed"]
#[doc = " @param [in] len <tt>opus_int32</tt>: size of data"]
#[doc = " @param [out] out_toc <tt>char*</tt>: TOC pointer"]
#[doc = " @param [out] frames <tt>char*[48]</tt> encapsulated frames"]
#[doc = " @param [out] size <tt>opus_int16[48]</tt> sizes of the encapsulated frames"]
#[doc = " @param [out] payload_offset <tt>int*</tt>: returns the position of the payload within the packet (in bytes)"]
#[doc = " @returns number of frames"]
pub fn opus_packet_parse(
data: *const ::std::os::raw::c_uchar,
len: opus_int32,
out_toc: *mut ::std::os::raw::c_uchar,
frames: *mut *const ::std::os::raw::c_uchar,
size: *mut opus_int16,
payload_offset: *mut ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Gets the bandwidth of an Opus packet."]
#[doc = " @param [in] data <tt>char*</tt>: Opus packet"]
#[doc = " @retval OPUS_BANDWIDTH_NARROWBAND Narrowband (4kHz bandpass)"]
#[doc = " @retval OPUS_BANDWIDTH_MEDIUMBAND Mediumband (6kHz bandpass)"]
#[doc = " @retval OPUS_BANDWIDTH_WIDEBAND Wideband (8kHz bandpass)"]
#[doc = " @retval OPUS_BANDWIDTH_SUPERWIDEBAND Superwideband (12kHz bandpass)"]
#[doc = " @retval OPUS_BANDWIDTH_FULLBAND Fullband (20kHz bandpass)"]
#[doc = " @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type"]
pub fn opus_packet_get_bandwidth(data: *const ::std::os::raw::c_uchar) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Gets the number of samples per frame from an Opus packet."]
#[doc = " @param [in] data <tt>char*</tt>: Opus packet."]
#[doc = " This must contain at least one byte of"]
#[doc = " data."]
#[doc = " @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz."]
#[doc = " This must be a multiple of 400, or"]
#[doc = " inaccurate results will be returned."]
#[doc = " @returns Number of samples per frame."]
pub fn opus_packet_get_samples_per_frame(
data: *const ::std::os::raw::c_uchar,
Fs: opus_int32,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Gets the number of channels from an Opus packet."]
#[doc = " @param [in] data <tt>char*</tt>: Opus packet"]
#[doc = " @returns Number of channels"]
#[doc = " @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type"]
pub fn opus_packet_get_nb_channels(data: *const ::std::os::raw::c_uchar)
-> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Gets the number of frames in an Opus packet."]
#[doc = " @param [in] packet <tt>char*</tt>: Opus packet"]
#[doc = " @param [in] len <tt>opus_int32</tt>: Length of packet"]
#[doc = " @returns Number of frames"]
#[doc = " @retval OPUS_BAD_ARG Insufficient data was passed to the function"]
#[doc = " @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type"]
pub fn opus_packet_get_nb_frames(
packet: *const ::std::os::raw::c_uchar,
len: opus_int32,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Gets the number of samples of an Opus packet."]
#[doc = " @param [in] packet <tt>char*</tt>: Opus packet"]
#[doc = " @param [in] len <tt>opus_int32</tt>: Length of packet"]
#[doc = " @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz."]
#[doc = " This must be a multiple of 400, or"]
#[doc = " inaccurate results will be returned."]
#[doc = " @returns Number of samples"]
#[doc = " @retval OPUS_BAD_ARG Insufficient data was passed to the function"]
#[doc = " @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type"]
pub fn opus_packet_get_nb_samples(
packet: *const ::std::os::raw::c_uchar,
len: opus_int32,
Fs: opus_int32,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Gets the number of samples of an Opus packet."]
#[doc = " @param [in] dec <tt>OpusDecoder*</tt>: Decoder state"]
#[doc = " @param [in] packet <tt>char*</tt>: Opus packet"]
#[doc = " @param [in] len <tt>opus_int32</tt>: Length of packet"]
#[doc = " @returns Number of samples"]
#[doc = " @retval OPUS_BAD_ARG Insufficient data was passed to the function"]
#[doc = " @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type"]
pub fn opus_decoder_get_nb_samples(
dec: *const OpusDecoder,
packet: *const ::std::os::raw::c_uchar,
len: opus_int32,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Applies soft-clipping to bring a float signal within the [-1,1] range. If"]
#[doc = " the signal is already in that range, nothing is done. If there are values"]
#[doc = " outside of [-1,1], then the signal is clipped as smoothly as possible to"]
#[doc = " both fit in the range and avoid creating excessive distortion in the"]
#[doc = " process."]
#[doc = " @param [in,out] pcm <tt>float*</tt>: Input PCM and modified PCM"]
#[doc = " @param [in] frame_size <tt>int</tt> Number of samples per channel to process"]
#[doc = " @param [in] channels <tt>int</tt>: Number of channels"]
#[doc = " @param [in,out] softclip_mem <tt>float*</tt>: State memory for the soft clipping process (one float per channel, initialized to zero)"]
pub fn opus_pcm_soft_clip(
pcm: *mut f32,
frame_size: ::std::os::raw::c_int,
channels: ::std::os::raw::c_int,
softclip_mem: *mut f32,
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct OpusRepacketizer {
_unused: [u8; 0],
}
extern "C" {
#[doc = " Gets the size of an <code>OpusRepacketizer</code> structure."]
#[doc = " @returns The size in bytes."]
pub fn opus_repacketizer_get_size() -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " (Re)initializes a previously allocated repacketizer state."]
#[doc = " The state must be at least the size returned by opus_repacketizer_get_size()."]
#[doc = " This can be used for applications which use their own allocator instead of"]
#[doc = " malloc()."]
#[doc = " It must also be called to reset the queue of packets waiting to be"]
#[doc = " repacketized, which is necessary if the maximum packet duration of 120 ms"]
#[doc = " is reached or if you wish to submit packets with a different Opus"]
#[doc = " configuration (coding mode, audio bandwidth, frame size, or channel count)."]
#[doc = " Failure to do so will prevent a new packet from being added with"]
#[doc = " opus_repacketizer_cat()."]
#[doc = " @see opus_repacketizer_create"]
#[doc = " @see opus_repacketizer_get_size"]
#[doc = " @see opus_repacketizer_cat"]
#[doc = " @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to"]
#[doc = " (re)initialize."]
#[doc = " @returns A pointer to the same repacketizer state that was passed in."]
pub fn opus_repacketizer_init(rp: *mut OpusRepacketizer) -> *mut OpusRepacketizer;
}
extern "C" {
#[doc = " Allocates memory and initializes the new repacketizer with"]
#[doc = " opus_repacketizer_init()."]
pub fn opus_repacketizer_create() -> *mut OpusRepacketizer;
}
extern "C" {
#[doc = " Frees an <code>OpusRepacketizer</code> allocated by"]
#[doc = " opus_repacketizer_create()."]
#[doc = " @param[in] rp <tt>OpusRepacketizer*</tt>: State to be freed."]
pub fn opus_repacketizer_destroy(rp: *mut OpusRepacketizer);
}
extern "C" {
#[doc = " Add a packet to the current repacketizer state."]
#[doc = " This packet must match the configuration of any packets already submitted"]
#[doc = " for repacketization since the last call to opus_repacketizer_init()."]
#[doc = " This means that it must have the same coding mode, audio bandwidth, frame"]
#[doc = " size, and channel count."]
#[doc = " This can be checked in advance by examining the top 6 bits of the first"]
#[doc = " byte of the packet, and ensuring they match the top 6 bits of the first"]
#[doc = " byte of any previously submitted packet."]
#[doc = " The total duration of audio in the repacketizer state also must not exceed"]
#[doc = " 120 ms, the maximum duration of a single packet, after adding this packet."]
#[doc = ""]
#[doc = " The contents of the current repacketizer state can be extracted into new"]
#[doc = " packets using opus_repacketizer_out() or opus_repacketizer_out_range()."]
#[doc = ""]
#[doc = " In order to add a packet with a different configuration or to add more"]
#[doc = " audio beyond 120 ms, you must clear the repacketizer state by calling"]
#[doc = " opus_repacketizer_init()."]
#[doc = " If a packet is too large to add to the current repacketizer state, no part"]
#[doc = " of it is added, even if it contains multiple frames, some of which might"]
#[doc = " fit."]
#[doc = " If you wish to be able to add parts of such packets, you should first use"]
#[doc = " another repacketizer to split the packet into pieces and add them"]
#[doc = " individually."]
#[doc = " @see opus_repacketizer_out_range"]
#[doc = " @see opus_repacketizer_out"]
#[doc = " @see opus_repacketizer_init"]
#[doc = " @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to which to"]
#[doc = " add the packet."]
#[doc = " @param[in] data <tt>const unsigned char*</tt>: The packet data."]
#[doc = " The application must ensure"]
#[doc = " this pointer remains valid"]
#[doc = " until the next call to"]
#[doc = " opus_repacketizer_init() or"]
#[doc = " opus_repacketizer_destroy()."]
#[doc = " @param len <tt>opus_int32</tt>: The number of bytes in the packet data."]
#[doc = " @returns An error code indicating whether or not the operation succeeded."]
#[doc = " @retval #OPUS_OK The packet's contents have been added to the repacketizer"]
#[doc = " state."]
#[doc = " @retval #OPUS_INVALID_PACKET The packet did not have a valid TOC sequence,"]
#[doc = " the packet's TOC sequence was not compatible"]
#[doc = " with previously submitted packets (because"]
#[doc = " the coding mode, audio bandwidth, frame size,"]
#[doc = " or channel count did not match), or adding"]
#[doc = " this packet would increase the total amount of"]
#[doc = " audio stored in the repacketizer state to more"]
#[doc = " than 120 ms."]
pub fn opus_repacketizer_cat(
rp: *mut OpusRepacketizer,
data: *const ::std::os::raw::c_uchar,
len: opus_int32,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Construct a new packet from data previously submitted to the repacketizer"]
#[doc = " state via opus_repacketizer_cat()."]
#[doc = " @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to"]
#[doc = " construct the new packet."]
#[doc = " @param begin <tt>int</tt>: The index of the first frame in the current"]
#[doc = " repacketizer state to include in the output."]
#[doc = " @param end <tt>int</tt>: One past the index of the last frame in the"]
#[doc = " current repacketizer state to include in the"]
#[doc = " output."]
#[doc = " @param[out] data <tt>const unsigned char*</tt>: The buffer in which to"]
#[doc = " store the output packet."]
#[doc = " @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in"]
#[doc = " the output buffer. In order to guarantee"]
#[doc = " success, this should be at least"]
#[doc = " <code>1276</code> for a single frame,"]
#[doc = " or for multiple frames,"]
#[doc = " <code>1277*(end-begin)</code>."]
#[doc = " However, <code>1*(end-begin)</code> plus"]
#[doc = " the size of all packet data submitted to"]
#[doc = " the repacketizer since the last call to"]
#[doc = " opus_repacketizer_init() or"]
#[doc = " opus_repacketizer_create() is also"]
#[doc = " sufficient, and possibly much smaller."]
#[doc = " @returns The total size of the output packet on success, or an error code"]
#[doc = " on failure."]
#[doc = " @retval #OPUS_BAD_ARG <code>[begin,end)</code> was an invalid range of"]
#[doc = " frames (begin < 0, begin >= end, or end >"]
#[doc = " opus_repacketizer_get_nb_frames())."]
#[doc = " @retval #OPUS_BUFFER_TOO_SMALL \\a maxlen was insufficient to contain the"]
#[doc = " complete output packet."]
pub fn opus_repacketizer_out_range(
rp: *mut OpusRepacketizer,
begin: ::std::os::raw::c_int,
end: ::std::os::raw::c_int,
data: *mut ::std::os::raw::c_uchar,
maxlen: opus_int32,
) -> opus_int32;
}
extern "C" {
#[doc = " Return the total number of frames contained in packet data submitted to"]
#[doc = " the repacketizer state so far via opus_repacketizer_cat() since the last"]
#[doc = " call to opus_repacketizer_init() or opus_repacketizer_create()."]
#[doc = " This defines the valid range of packets that can be extracted with"]
#[doc = " opus_repacketizer_out_range() or opus_repacketizer_out()."]
#[doc = " @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state containing the"]
#[doc = " frames."]
#[doc = " @returns The total number of frames contained in the packet data submitted"]
#[doc = " to the repacketizer state."]
pub fn opus_repacketizer_get_nb_frames(rp: *mut OpusRepacketizer) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Construct a new packet from data previously submitted to the repacketizer"]
#[doc = " state via opus_repacketizer_cat()."]
#[doc = " This is a convenience routine that returns all the data submitted so far"]
#[doc = " in a single packet."]
#[doc = " It is equivalent to calling"]
#[doc = " @code"]
#[doc = " opus_repacketizer_out_range(rp, 0, opus_repacketizer_get_nb_frames(rp),"]
#[doc = " data, maxlen)"]
#[doc = " @endcode"]
#[doc = " @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to"]
#[doc = " construct the new packet."]
#[doc = " @param[out] data <tt>const unsigned char*</tt>: The buffer in which to"]
#[doc = " store the output packet."]
#[doc = " @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in"]
#[doc = " the output buffer. In order to guarantee"]
#[doc = " success, this should be at least"]
#[doc = " <code>1277*opus_repacketizer_get_nb_frames(rp)</code>."]
#[doc = " However,"]
#[doc = " <code>1*opus_repacketizer_get_nb_frames(rp)</code>"]
#[doc = " plus the size of all packet data"]
#[doc = " submitted to the repacketizer since the"]
#[doc = " last call to opus_repacketizer_init() or"]
#[doc = " opus_repacketizer_create() is also"]
#[doc = " sufficient, and possibly much smaller."]
#[doc = " @returns The total size of the output packet on success, or an error code"]
#[doc = " on failure."]
#[doc = " @retval #OPUS_BUFFER_TOO_SMALL \\a maxlen was insufficient to contain the"]
#[doc = " complete output packet."]
pub fn opus_repacketizer_out(
rp: *mut OpusRepacketizer,
data: *mut ::std::os::raw::c_uchar,
maxlen: opus_int32,
) -> opus_int32;
}
extern "C" {
#[doc = " Pads a given Opus packet to a larger size (possibly changing the TOC sequence)."]
#[doc = " @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the"]
#[doc = " packet to pad."]
#[doc = " @param len <tt>opus_int32</tt>: The size of the packet."]
#[doc = " This must be at least 1."]
#[doc = " @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding."]
#[doc = " This must be at least as large as len."]
#[doc = " @returns an error code"]
#[doc = " @retval #OPUS_OK \\a on success."]
#[doc = " @retval #OPUS_BAD_ARG \\a len was less than 1 or new_len was less than len."]
#[doc = " @retval #OPUS_INVALID_PACKET \\a data did not contain a valid Opus packet."]
pub fn opus_packet_pad(
data: *mut ::std::os::raw::c_uchar,
len: opus_int32,
new_len: opus_int32,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Remove all padding from a given Opus packet and rewrite the TOC sequence to"]
#[doc = " minimize space usage."]
#[doc = " @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the"]
#[doc = " packet to strip."]
#[doc = " @param len <tt>opus_int32</tt>: The size of the packet."]
#[doc = " This must be at least 1."]
#[doc = " @returns The new size of the output packet on success, or an error code"]
#[doc = " on failure."]
#[doc = " @retval #OPUS_BAD_ARG \\a len was less than 1."]
#[doc = " @retval #OPUS_INVALID_PACKET \\a data did not contain a valid Opus packet."]
pub fn opus_packet_unpad(data: *mut ::std::os::raw::c_uchar, len: opus_int32) -> opus_int32;
}
extern "C" {
#[doc = " Pads a given Opus multi-stream packet to a larger size (possibly changing the TOC sequence)."]
#[doc = " @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the"]
#[doc = " packet to pad."]
#[doc = " @param len <tt>opus_int32</tt>: The size of the packet."]
#[doc = " This must be at least 1."]
#[doc = " @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding."]
#[doc = " This must be at least 1."]
#[doc = " @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet."]
#[doc = " This must be at least as large as len."]
#[doc = " @returns an error code"]
#[doc = " @retval #OPUS_OK \\a on success."]
#[doc = " @retval #OPUS_BAD_ARG \\a len was less than 1."]
#[doc = " @retval #OPUS_INVALID_PACKET \\a data did not contain a valid Opus packet."]
pub fn opus_multistream_packet_pad(
data: *mut ::std::os::raw::c_uchar,
len: opus_int32,
new_len: opus_int32,
nb_streams: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[doc = " Remove all padding from a given Opus multi-stream packet and rewrite the TOC sequence to"]
#[doc = " minimize space usage."]
#[doc = " @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the"]
#[doc = " packet to strip."]
#[doc = " @param len <tt>opus_int32</tt>: The size of the packet."]
#[doc = " This must be at least 1."]
#[doc = " @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet."]
#[doc = " This must be at least 1."]
#[doc = " @returns The new size of the output packet on success, or an error code"]
#[doc = " on failure."]
#[doc = " @retval #OPUS_BAD_ARG \\a len was less than 1 or new_len was less than len."]
#[doc = " @retval #OPUS_INVALID_PACKET \\a data did not contain a valid Opus packet."]
pub fn opus_multistream_packet_unpad(
data: *mut ::std::os::raw::c_uchar,
len: opus_int32,
nb_streams: ::std::os::raw::c_int,
) -> opus_int32;
}
+1
View File
@@ -0,0 +1 @@
#include "../../libopus/include/opus.h"
+219 -104
View File
@@ -1,114 +1,167 @@
use audiopus::coder::{Decoder, Encoder};
use audiopus::{Application, Bitrate, Channels, SampleRate};
use napi::bindgen_prelude::*;
use napi::Error;
use napi::Result;
use self::lib::*;
mod lib;
const FRAME_SIZE: usize = 960;
const MAX_FRAME_SIZE: usize = 6 * FRAME_SIZE;
const MAX_PACKET_SIZE: usize = 3 * 1276;
fn get_decode_error(decoded_samples: i32) -> &'static str {
match decoded_samples {
OPUS_BAD_ARG => "One or more invalid/out of range arguments",
OPUS_BUFFER_TOO_SMALL => "The mode struct passed is invalid",
OPUS_INTERNAL_ERROR => "An internal error was detected",
OPUS_INVALID_PACKET => "The compressed data passed is corrupted",
OPUS_UNIMPLEMENTED => "Invalid/unsupported request number",
OPUS_INVALID_STATE => "An encoder or decoder structure is invalid or already freed.",
OPUS_ALLOC_FAIL => "Memory allocation has failed",
_ => "Unknown OPUS error",
}
}
#[napi]
pub struct OpusEncoder {
encoder: Option<Encoder>,
decoder: Option<Decoder>,
pub fn get_opus_version() -> String {
let ver = unsafe { opus_get_version_string() };
let c_str = unsafe { std::ffi::CStr::from_ptr(ver).to_str() };
return c_str.unwrap_or("unknown").to_string();
}
#[napi(js_name = "OpusEncoder")]
pub struct JsOpusEncoder {
encoder: *mut OpusEncoder,
decoder: *mut OpusDecoder,
sample_rate: i32,
channels: i32,
}
#[napi]
impl OpusEncoder {
#[napi(js_name = "OpusEncoder")]
impl JsOpusEncoder {
#[napi(constructor)]
pub fn new(sample_rate: i32, channels: i32) -> Result<Self> {
if channels != 1 && channels != 2 {
return Err(Error::new(Status::InvalidArg, "Invalid channels"));
}
Ok(OpusEncoder {
encoder: None,
decoder: None,
Ok(JsOpusEncoder {
encoder: std::ptr::null_mut(),
decoder: std::ptr::null_mut(),
sample_rate,
channels,
})
}
fn ensure_encoder(&mut self) {
if self.encoder.is_none() {
let rate = self.resolve_sample_rate().unwrap();
let channels = self.resolve_channels().unwrap();
self.encoder = Some(Encoder::new(rate, channels, Application::Audio).unwrap());
fn ensure_encoder(&mut self) -> i32 {
if self.encoder.is_null() {
let mut opus_code = 0;
let pointer = unsafe {
opus_encoder_create(
self.sample_rate,
self.channels,
OPUS_APPLICATION_AUDIO as i32,
&mut opus_code,
)
};
if opus_code == OPUS_OK as i32 || !pointer.is_null() {
self.encoder = pointer;
}
return opus_code;
}
OPUS_OK as i32
}
fn ensure_decoder(&mut self) {
if self.decoder.is_none() {
let rate = self.resolve_sample_rate().unwrap();
let channels = self.resolve_channels().unwrap();
self.decoder = Some(Decoder::new(rate, channels).unwrap());
}
}
fn ensure_decoder(&mut self) -> i32 {
if self.decoder.is_null() {
let mut opus_code = 0;
fn resolve_sample_rate(&self) -> std::result::Result<SampleRate, Error> {
match self.sample_rate {
8000 => Ok(SampleRate::Hz8000),
12000 => Ok(SampleRate::Hz12000),
16000 => Ok(SampleRate::Hz16000),
24000 => Ok(SampleRate::Hz24000),
48000 => Ok(SampleRate::Hz48000),
_ => return Err(Error::new(Status::InvalidArg, "Invalid sample rate")),
}
}
let pointer = unsafe { opus_decoder_create(self.sample_rate, self.channels, &mut opus_code) };
fn resolve_channels(&self) -> std::result::Result<Channels, Error> {
match self.channels {
1 => Ok(Channels::Mono),
2 => Ok(Channels::Stereo),
_ => return Err(Error::new(Status::InvalidArg, "Invalid channels")),
if opus_code == OPUS_OK as i32 || !pointer.is_null() {
self.decoder = pointer;
}
return opus_code;
}
OPUS_OK as i32
}
#[napi(catch_unwind)]
pub fn encode(&mut self, data: Buffer) -> Result<Buffer> {
self.ensure_encoder();
let status = self.ensure_encoder();
let encoder = self.encoder.as_mut().unwrap();
let data_ref: &[u8] = &data;
let mut out_buffer = vec![0u8; MAX_FRAME_SIZE];
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to create encoder: {}", get_decode_error(status)),
));
}
let data_i16 = unsafe {
let ptr = data_ref.as_ptr() as *const i16;
let len = data_ref.len() / 2;
let mut out_buffer = vec![0u8; MAX_PACKET_SIZE];
let pcm = unsafe {
let ptr = data.as_ptr() as *const i16;
let len = data.len() / 2;
std::slice::from_raw_parts(ptr, len)
};
let len = encoder
.encode(data_i16, &mut out_buffer)
.map_err(|e| Error::new(Status::GenericFailure, format!("Failed to encode: {}", e)))?;
let frame_size = data.len() as i32 / 2 / self.channels as i32;
Ok(out_buffer[..len].to_vec().into())
let compressed_len = unsafe {
opus_encode(
self.encoder,
pcm.as_ptr(),
frame_size,
out_buffer.as_mut_ptr(),
MAX_PACKET_SIZE as i32,
)
};
out_buffer.truncate(compressed_len as usize);
Ok(out_buffer.into())
}
#[napi(catch_unwind)]
pub fn decode(&mut self, data: Buffer) -> Result<Buffer> {
self.ensure_decoder();
let status = self.ensure_decoder();
let decoder = self.decoder.as_mut().unwrap();
let data_ref: &[u8] = &data;
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to create decoder: {}", get_decode_error(status)),
));
}
let mut out = vec![0i16; MAX_FRAME_SIZE * self.channels as usize];
let len = decoder
.decode(Some(data_ref), &mut out, false)
.map_err(|e| Error::new(Status::GenericFailure, format!("Failed to decode: {}", e)))?;
let decoded_samples = unsafe {
opus_decode(
self.decoder,
data.as_ptr(),
data.len() as i32,
out.as_mut_ptr(),
MAX_FRAME_SIZE as i32,
0,
)
};
if len == 0 {
return Err(Error::new(Status::GenericFailure, "Failed to decode"));
if decoded_samples < 0 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to decode: {}", get_decode_error(decoded_samples)),
));
}
let decoded_length = len * 2 * self.channels as usize;
let decoded_length = decoded_samples * 2 * self.channels;
let out = unsafe {
let ptr = out.as_ptr() as *const u8;
std::slice::from_raw_parts(ptr, decoded_length)
std::slice::from_raw_parts(ptr, decoded_length as usize)
};
Ok(out.to_vec().into())
@@ -116,73 +169,135 @@ impl OpusEncoder {
#[napi(catch_unwind)]
pub fn set_bitrate(&mut self, bitrate: i32) -> Result<()> {
self.ensure_encoder();
let status = self.ensure_encoder();
let encoder = self.encoder.as_mut().unwrap();
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to create encoder: {}", get_decode_error(status)),
));
}
encoder
.set_bitrate(Bitrate::BitsPerSecond(bitrate))
.map_err(|e| {
Error::new(
Status::GenericFailure,
format!("Failed to set bitrate: {}", e),
)
})?;
let status =
unsafe { opus_encoder_ctl(self.encoder, OPUS_SET_BITRATE_REQUEST as i32, bitrate) };
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to apply encoder ctl: {}", get_decode_error(status)),
));
}
Ok(())
}
#[napi(catch_unwind)]
pub fn get_bitrate(&mut self) -> Result<i32> {
self.ensure_encoder();
let status = self.ensure_encoder();
let encoder = self.encoder.as_mut().unwrap();
let bitrate = encoder.bitrate().map_err(|e| {
Error::new(
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to get bitrate: {}", e),
)
})?;
match bitrate {
Bitrate::BitsPerSecond(bitrate) => Ok(bitrate),
_ => Err(Error::new(
Status::GenericFailure,
"Failed to get bitrate: Invalid bitrate",
)),
format!("Failed to create encoder: {}", get_decode_error(status)),
));
}
let mut value = 0;
let status =
unsafe { opus_encoder_ctl(self.encoder, OPUS_GET_BITRATE_REQUEST as i32, &mut value) };
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to apply encoder ctl: {}", get_decode_error(status)),
));
}
Ok(value)
}
#[napi(catch_unwind)]
pub fn apply_encoder_ctl(&mut self, request: i32, value: i32) -> Result<()> {
self.ensure_encoder();
let status = self.ensure_encoder();
let encoder = self.encoder.as_mut().unwrap();
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to create encoder: {}", get_decode_error(status)),
));
}
encoder
.set_encoder_ctl_request(request, value)
.map_err(|e| {
Error::new(
Status::GenericFailure,
format!("Failed to apply encoder ctl: {}", e),
)
})?;
let status = unsafe { opus_encoder_ctl(self.encoder, request, value) };
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to apply encoder ctl: {}", get_decode_error(status)),
));
}
Ok(())
}
#[napi]
pub fn apply_decoder_ctl(&mut self, _request: i32, _value: i32) -> Result<()> {
// Currently, this function is not implemented due to being private in the library.
// It will be implemented if it becomes available in the future. This currently exists
// for compatibility reasons.
pub fn apply_decoder_ctl(&mut self, request: i32, value: i32) -> Result<()> {
let status = self.ensure_decoder();
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to create decoder: {}", get_decode_error(status)),
));
}
let status = unsafe { opus_decoder_ctl(self.decoder, request, value) };
if status != OPUS_OK as i32 {
return Err(Error::new(
Status::GenericFailure,
format!("Failed to apply decoder ctl: {}", get_decode_error(status)),
));
}
Ok(())
}
#[napi(getter)]
pub fn get_version() -> String {
get_opus_version()
}
#[napi]
pub fn destroy(&mut self) {
self.encoder = None;
self.decoder = None;
pub fn destroy(&mut self) -> Result<()> {
if !self.encoder.is_null() {
unsafe {
opus_encoder_destroy(self.encoder);
}
}
if !self.decoder.is_null() {
unsafe {
opus_decoder_destroy(self.decoder);
}
}
Ok(())
}
}
impl Drop for JsOpusEncoder {
fn drop(&mut self) {
if !self.encoder.is_null() {
unsafe {
opus_encoder_destroy(self.encoder);
}
}
if !self.decoder.is_null() {
unsafe {
opus_decoder_destroy(self.decoder);
}
}
}
}
+1
View File
@@ -14,6 +14,7 @@ pub struct JsProbeResult {
/// The number of frames per block
pub frames_per_block: u32,
/// The codec type
#[napi(ts_type="CodecType")]
pub codec: JsCodecType,
/// The number of frames
pub n_frames: u32,
+8
View File
@@ -151,6 +151,13 @@ __metadata:
languageName: node
linkType: hard
"@types/node@npm:^20.4.8":
version: 20.4.8
resolution: "@types/node@npm:20.4.8"
checksum: 86a3963c0c7af3410553d1dfa4b018a20b3cb3ab4d8e8ffe27408b6338c5de0374b0bf379bc705da2205b466daa751ccfe062f453ba9bde34fdb0e5163ca6a68
languageName: node
linkType: hard
"abbrev@npm:1, abbrev@npm:^1.0.0":
version: 1.1.1
resolution: "abbrev@npm:1.1.1"
@@ -1500,6 +1507,7 @@ __metadata:
dependencies:
"@discordjs/opus": ^0.9.0
"@napi-rs/cli": ^2.16.1
"@types/node": ^20.4.8
ava: ^5.1.1
benny: ^3.7.1
opusscript: ^0.1.0