Crate libopusenc

Crate libopusenc 

Source
Expand description

§Library

This library is a safe Rust wrapper around libopusenc, which provides a convenient high-level API for encoding audio data into the Opus format using the reference codec implementation.

§Overview

Opus is a totally open, royalty-free, highly versatile audio codec. Opus is unmatched for interactive speech and music transmission over the Internet, but is also intended for storage and streaming applications. It is standardized by the Internet Engineering Task Force (IETF) as RFC 6716 which incorporated technology from Skype’s SILK codec and Xiph.Org’s CELT codec.

§Technology

Opus can handle a wide range of audio applications, including Voice over IP, videoconferencing, in-game chat, and even remote live music performances. It can scale from low bitrate narrowband speech to very high quality stereo music. Supported features are:

  • Bitrates from 6 kb/s to 510 kb/s
  • Sampling rates from 8 kHz (narrowband) to 48 kHz (fullband)
  • Frame sizes from 2.5 ms to 60 ms
  • Support for both constant bitrate (CBR) and variable bitrate (VBR)
  • Audio bandwidth from narrowband to fullband
  • Support for speech and music
  • Support for mono and stereo
  • Support for up to 255 channels (multistream frames)
  • Dynamically adjustable bitrate, audio bandwidth, and frame size
  • Good loss robustness and packet loss concealment (PLC)
  • Floating point and fixed-point implementation

You can read the full specification, including the reference implementation, in RFC 6716.

§Usage

To use this library, you will need to add it as a dependency in your Cargo.toml file:

[dependencies]
libopusenc = "0.2"

Once you have added the dependency, you can start using the library in your Rust code. Here’s a simple example of how to create an Opus encoder, set some parameters, and encode audio data:

use libopusenc::{OpusEncoder, OpusEncError, OpusEncComments, OpusEncBandwidth};
use libopusenc::{OpusEncApplication, OpusEncBitrate, OpusEncSampleRate, OpusEncChannelMapping};
use std::io::Write; // Import the Write trait to write to a file

fn main() -> Result<(), OpusEncError> {
   // Specify a buffer containing the input audio data
   let input_data: Vec<i16> = vec![0; 96000]; // Example input buffer (1s of stereo audio at 48 kHz)

   // Create a new comments structure to hold metadata for the Opus file
   // This is optional, but allows you to add metadata like title, artist, etc. to the Opus file
   let mut comments = OpusEncComments::create()?;
   comments.add("TITLE", "My Opus Track")? // Add a title to the comments
           .add("ARTIST", "My Artist")?  // Add an artist name
           .add("ALBUM", "My Album")?; // Add an album name

   // Create a new Opus encoder for stereo input audio with a sample rate of 48 kHz
   let mut encoder = OpusEncoder::create_file("target/out.opus", &mut comments, OpusEncSampleRate::Hz48000, 2, OpusEncChannelMapping::MonoStereo)?;

   // Set the encoding parameters
   encoder.set_vbr(true)?  // Enable variable bitrate (VBR) encoding
          .set_complexity(10)? // Set the complexity level (0-10, higher means more CPU usage)
          .set_bandwidth(OpusEncBandwidth::SuperWideband12kHz)?  // Set the output bandwidth to 12 kHz
          .set_application(OpusEncApplication::Audio)?  // Set the application type to audio
          .set_bitrate(OpusEncBitrate::Explicit(24000))?; // Set the target bitrate to 24 kb/s

   // Encode the audio data in the input buffer into single-channel output
   if let Err(err) = encoder.write(&input_data, 1) {
      println!("Failed to encode audio: {}", err);
      return Err(err); // Return the error if encoding failed
   }
   println!("Successfully wrote Opus data to the output file");
   Ok(())
}

The same data can be encoded using callbacks instead of writing directly to a file. This allows you to handle the encoded data in a custom way, such as sending it over a network or storing it into memory. Here’s an example of how to encode using callbacks:

use libopusenc::{OpusEncoder, OpusEncError, OpusEncComments, OpusEncBandwidth};
use libopusenc::{OpusEncApplication, OpusEncBitrate, OpusEncSampleRate, OpusEncChannelMapping};
use std::io::Write; // Import the Write trait to write to a file

fn write_callback(file: &mut std::fs::File, data: &[u8]) -> bool {
   file.write_all(data).expect("Failed to write data to file from within callback");
   true
}
fn close_callback(_file: &mut std::fs::File) -> bool { true }

fn main() -> Result<(), OpusEncError> {
   // Specify a buffer containing the input audio data
   let input_data: Vec<i16> = vec![0; 96000]; // Example input buffer (1s of stereo audio at 48 kHz)

   // Create a new output file to write the encoded Opus data
   let mut output_file = std::fs::File::create("target/out_cb.opus").expect("Failed to create output file");

   // Create a new comments structure to hold metadata for the Opus file
   // This is optional, but allows you to add metadata like title, artist, etc. to the Opus file
   let mut comments = OpusEncComments::create()?;
   comments.add("TITLE", "My Opus Track")? // Add a title to the comments
           .add("ARTIST", "My Artist")?  // Add an artist name
           .add("ALBUM", "My Album")?; // Add an album name

   // Create a new callback-based Opus encoder for stereo input audio with a sample rate of 48 kHz
   let mut encoder = OpusEncoder::create_callbacks(write_callback,
                                                   close_callback,
                                                   Some(&mut output_file),
                                                   &mut comments,
                                                   OpusEncSampleRate::Hz48000,
                                                   2,
                                                   OpusEncChannelMapping::MonoStereo)?;

   // Set the encoding parameters
   encoder.set_vbr(true)?  // Enable variable bitrate (VBR) encoding
          .set_complexity(10)? // Set the complexity level (0-10, higher means more CPU usage)
          .set_bandwidth(OpusEncBandwidth::SuperWideband12kHz)?  // Set the output bandwidth to 12 kHz
          .set_application(OpusEncApplication::Audio)?  // Set the application type to audio
          .set_bitrate(OpusEncBitrate::Explicit(24000))?; // Set the target bitrate to 24 kb/s

   // Encode the audio data in the input buffer into single-channel output
   if let Err(err) = encoder.write(&input_data, 1) {
      println!("Failed to encode audio: {}", err);
      return Err(err); // Return the error if encoding failed
   }
   println!("Successfully wrote Opus data to the output file");
   Ok(())
}

Structs§

OpusEnc
Encapsulates the real-time internal state of an OggOpus encoder.
OpusEncComments
Encapsulates all metadata associated with an OggOpus stream.
OpusEncoder
Provides methods for creating and managing an Opus encoder.

Enums§

OpusEncApplication
Enumerates target Opus encoding applications.
OpusEncBandwidth
Enumerates available Opus encoding bandwidths.
OpusEncBitrate
Enumerates Opus encoding bitrate options.
OpusEncChannelMapping
Enumerates Opus encoding channel mapping modes.
OpusEncError
Enumerates potential Opus encoding errors.
OpusEncForcedChannels
Enumerates available forced number of encoding channels.
OpusEncFrameSize
Enumerates available Opus encoding frame sizes.
OpusEncInbandFec
Enumerates all Opus Forward Error Correction (FEC) settings.
OpusEncPictureType
Enumerates available embedded metadata picture types.
OpusEncPrediction
Enumerates Opus prediction settings.
OpusEncRequest
Enumerates available Opus encoding requests.
OpusEncSampleRate
Enumerates available Opus encoding sample rates.
OpusEncSignalBias
Enumerates Opus signal bias settings.

Functions§

get_abi_version
Returns the ABI version used by this library.
get_version_string
Returns a String representing the library version being used.

Type Aliases§

OpeCloseFunc
Callback function definition for closing an output file or structure.
OpeWriteFunc
Callback function definition for writing encoded data to an output file or structure.