### Create New G722Encoder Instance Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Encoder.html Instantiates a new G722Encoder with default settings. No specific setup is required beyond calling this function. ```rust pub fn new() -> Self ``` -------------------------------- ### Create New G729Encoder Instance Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g729/struct.G729Encoder.html Instantiates a new G.729 encoder. No setup or imports are required beyond having the struct available. ```rust pub fn new() -> Self> ``` -------------------------------- ### Get Audio Channels Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/pcma.rs.html Returns the number of audio channels supported by the codec. This implementation supports 1 channel. ```rust fn channels(&self) -> u16 { 1 } ``` -------------------------------- ### Get fmtp for Codec Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Returns the fmtp (format parameters) string for codecs that support them, such as Opus and TelephoneEvent. Returns `None` for codecs without specific parameters. ```rust pub fn fmtp(&self) -> Option<&str> { match self { CodecType::PCMU => None, CodecType::PCMA => None, CodecType::G722 => None, CodecType::G729 => None, #[cfg(feature = "opus")] CodecType::Opus => Some("minptime=10;useinbandfec=1"), CodecType::TelephoneEvent => Some("0-16"), } } ``` -------------------------------- ### G729Encoder - Get Channels Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g729/struct.G729Encoder.html Retrieves the number of audio channels expected for input samples. ```APIDOC ## GET /audio_codec/g729/channels ### Description Get the number of channels expected for input. ### Method GET ### Endpoint /audio_codec/g729/channels ### Response #### Success Response (200) - **channels** (u16) - The number of expected audio channels. #### Response Example ```json { "channels": 1 } ``` ``` -------------------------------- ### Decoder Trait Implementation for PcmaDecoder Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcma/struct.PcmaDecoder.html Provides methods for decoding audio data, getting sample rate, and getting channel count. ```APIDOC ## impl Decoder for PcmaDecoder ### decode #### Description Decode encoded audio data into PCM samples. #### Method `fn decode(&mut self, samples: &[u8]) -> PcmBuf` ### sample_rate #### Description Get the sample rate of the decoded audio. #### Method `fn sample_rate(&self) -> u32` ### channels #### Description Get the number of channels. #### Method `fn channels(&self) -> u16` ``` -------------------------------- ### Get Default PcmaDecoder Instance Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcma/struct.PcmaDecoder.html Provides a default instance of PcmaDecoder. This is useful when a default value is needed. ```rust fn default() -> PcmaDecoder ``` -------------------------------- ### Get Audio Sample Rate Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/pcma.rs.html Returns the sample rate of the audio codec. This implementation is fixed at 8000 Hz. ```rust fn sample_rate(&self) -> u32 { 8000 } ``` -------------------------------- ### G729Encoder - Get Sample Rate Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g729/struct.G729Encoder.html Retrieves the expected sample rate for input audio samples. ```APIDOC ## GET /audio_codec/g729/sample_rate ### Description Get the sample rate expected for input samples. ### Method GET ### Endpoint /audio_codec/g729/sample_rate ### Response #### Success Response (200) - **sample_rate** (u32) - The expected sample rate in Hz. #### Response Example ```json { "sample_rate": 8000 } ``` ``` -------------------------------- ### Get Samplerate for Codec Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Returns the sample rate (in Hz) at which the codec operates. Note that G722 has a higher sample rate than some other codecs. ```rust pub fn samplerate(&self) -> u32 { match self { CodecType::PCMU => 8000, CodecType::PCMA => 8000, CodecType::G722 => 16000, CodecType::G729 => 8000, #[cfg(feature = "opus")] CodecType::Opus => 48000, CodecType::TelephoneEvent => 8000, } } ``` -------------------------------- ### Get Decoded Audio Sample Rate Source: https://docs.rs/audio-codec/0.3.30/audio_codec/trait.Decoder.html The sample_rate method returns the sample rate of the audio that the decoder will produce. This is crucial for correctly interpreting the decoded PCM samples. ```rust fn sample_rate(&self) -> u32; ``` -------------------------------- ### Get MIME Type for Codec Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Returns the MIME type string associated with each `CodecType`. This is useful for network protocols and file formats. ```rust impl CodecType { pub fn mime_type(&self) -> &str { match self { CodecType::PCMU => "audio/PCMU", CodecType::PCMA => "audio/PCMA", CodecType::G722 => "audio/G722", CodecType::G729 => "audio/G729", #[cfg(feature = "opus")] CodecType::Opus => "audio/opus", CodecType::TelephoneEvent => "audio/telephone-event", } } } ``` -------------------------------- ### Get G722Encoder Sample Rate Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Encoder.html Retrieves the expected sample rate for input PCM samples for the G722Encoder. This indicates the expected frequency of the audio data. ```rust fn sample_rate(&self) -> u32 ``` -------------------------------- ### Get Number of Audio Channels Source: https://docs.rs/audio-codec/0.3.30/audio_codec/trait.Decoder.html The channels method returns the number of audio channels present in the decoded output. This is important for applications that need to handle mono, stereo, or multi-channel audio. ```rust fn channels(&self) -> u16; ``` -------------------------------- ### Get Channels for Codec Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Returns the number of audio channels supported by the `CodecType`. Opus supports stereo (2 channels), while others typically support mono (1 channel). ```rust pub fn channels(&self) -> u16 { match self { #[cfg(feature = "opus")] CodecType::Opus => 2, _ => 1, } } ``` -------------------------------- ### Initialize G722Decoder with Custom Options Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Decoder.html Creates a new instance of G722Decoder with specified options for bitrate, packing, and sample rate. ```rust pub fn with_options(rate: Bitrate, packed: bool, eight_k: bool) -> Self ``` -------------------------------- ### Initialize G722Encoder with default options Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Creates a new G.722 encoder using the default bitrate (1.64000) and no special options. ```rust pub fn new() -> Self { Self::with_options(Bitrate::Mode1_64000, false, false) } ``` -------------------------------- ### Initialize G722Encoder with custom options Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Creates a G.722 encoder with specified bitrate, sample rate (8kHz or 16kHz), and packing mode. ```rust pub fn with_options(rate: Bitrate, eight_k: bool, packed: bool) -> Self { let mut encoder = Self { packed, eight_k, bits_per_sample: rate.bits_per_sample(), x: [0; 24], band: [G722Band::default(), G722Band::default()], out_buffer: 0, out_bits: 0, }; // Initialize band states with correct starting values encoder.band[0].log_scale_factor = 32 << 2; // Initial det value for lower band encoder.band[1].log_scale_factor = 8 << 2; // Initial det value for upper band encoder } ``` -------------------------------- ### G729Decoder Initialization Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g729/struct.G729Decoder.html Provides information on how to create a new instance of the G729Decoder. ```APIDOC ## POST /api/g729decoder/new ### Description Create a new G.729 decoder instance. ### Method POST ### Endpoint /api/g729decoder/new ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - **G729Decoder** (object) - A new instance of the G729Decoder. #### Response Example ```json { "decoder_instance_id": "unique_decoder_id" } ``` ``` -------------------------------- ### PcmaDecoder::new() Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcma/struct.PcmaDecoder.html Creates a new instance of the PcmaDecoder. ```APIDOC ## PcmaDecoder::new() ### Description Creates a new PcmaDecoder instance. ### Method `pub fn new() -> Self` ``` -------------------------------- ### Create G722Encoder with Options Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Encoder.html Creates a G722Encoder instance with specified bitrate, and options for 8kHz sample rate and packing. Ensure the provided Bitrate is compatible. ```rust pub fn with_options(rate: Bitrate, eight_k: bool, packed: bool) -> Self ``` -------------------------------- ### Get Default PcmuDecoder Value Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcmu/struct.PcmuDecoder.html Returns the default value for PcmuDecoder, useful for initialization when no specific configuration is needed. ```rust fn default() -> PcmuDecoder ``` -------------------------------- ### Initialize Resampler with Custom Rates Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/resampler.rs.html Creates a new `Resampler` instance. Configures filter parameters based on input and output rates. Ensure `output_rate` is not zero to avoid division by zero. ```rust pub fn new(input_rate: usize, output_rate: usize) -> Self { let ratio = output_rate as f64 / input_rate as f64; let num_phases = 128; let taps_per_phase = 16; // Increased to 16 for SIMD alignment (4x f32) let filter_len = num_phases * taps_per_phase; let mut raw_coeffs = vec![0.0f32; filter_len]; let cutoff = if ratio < 1.0 { ratio as f32 * 0.45 } else { 0.45f32 }; let center = (taps_per_phase as f32 - 1.0) / 2.0; for p in 0..num_phases { let mut sum = 0.0; let mut phase_coeffs = vec![0.0f32; taps_per_phase]; for t in 0..taps_per_phase { let x = t as f32 - center - (p as f32 / num_phases as f32); let val = if x.abs() < 1e-6 { 2.0 * cutoff } else { let x_pi = x * PI; (x_pi * 2.0 * cutoff).sin() / x_pi }; let window = 0.54 - 0.46 * (2.0 * PI * (t as f32 * num_phases as f32 + p as f32) / (filter_len as f32 - 1.0)) .cos(); phase_coeffs[t] = val * window; sum += phase_coeffs[t]; } for t in 0..taps_per_phase { raw_coeffs[p * taps_per_phase + t] = phase_coeffs[t] / sum; } } Self { input_rate, output_rate, ratio, coeffs: raw_coeffs, num_phases, taps_per_phase, history: vec![0.0; taps_per_phase], current_pos: 0.0, } } ``` -------------------------------- ### Define PcmaDecoder Struct Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcma/struct.PcmaDecoder.html Defines the structure for the A-law (PCMA) decoder. No specific setup is required to use this struct. ```rust pub struct PcmaDecoder {} ``` -------------------------------- ### Initialize Resampler Source: https://docs.rs/audio-codec/0.3.30/audio_codec/resampler/struct.Resampler.html Creates a new Resampler instance. Specify the input and output sample rates. ```rust pub fn new(input_rate: usize, output_rate: usize) -> Self ``` -------------------------------- ### G729Encoder - Create New Instance Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g729/struct.G729Encoder.html Instantiates a new G.729 audio encoder. ```APIDOC ## POST /audio_codec/g729/new ### Description Creates a new G.729 encoder instance. ### Method POST ### Endpoint /audio_codec/g729/new ### Request Body None ### Response #### Success Response (200) - **G729Encoder** (object) - A new instance of the G729Encoder. #### Response Example ```json { "encoder_instance": "" } ``` ``` -------------------------------- ### Get Clock Rate for Codec Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Returns the clock rate (in Hz) for each `CodecType`. This is the number of samples per second the codec operates on. ```rust pub fn clock_rate(&self) -> u32 { match self { CodecType::PCMU => 8000, CodecType::PCMA => 8000, CodecType::G722 => 8000, CodecType::G729 => 8000, #[cfg(feature = "opus")] CodecType::Opus => 48000, CodecType::TelephoneEvent => 8000, } } ``` -------------------------------- ### PcmaEncoder::new() Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcma/struct.PcmaEncoder.html Constructor for creating a new instance of PcmaEncoder. ```APIDOC ## PcmaEncoder::new() ### Description Creates a new PcmaEncoder instance. ### Method `pub fn new() -> Self` ``` -------------------------------- ### OpusDecoder Initialization Source: https://docs.rs/audio-codec/0.3.30/audio_codec/opus/struct.OpusDecoder.html Provides methods for creating new instances of the OpusDecoder. ```APIDOC ## OpusDecoder::new ### Description Create a new Opus decoder instance with specified sample rate and channels. ### Method `pub fn new(sample_rate: u32, channels: u16) -> Self` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust let decoder = OpusDecoder::new(48000, 2); ``` ### Response #### Success Response (200) - **Self** (OpusDecoder) - A new OpusDecoder instance. #### Response Example ```rust // OpusDecoder instance ``` ## OpusDecoder::new_default ### Description Create a default Opus decoder with a sample rate of 48kHz and stereo channels. ### Method `pub fn new_default() -> Self` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust let decoder = OpusDecoder::new_default(); ``` ### Response #### Success Response (200) - **Self** (OpusDecoder) - A new default OpusDecoder instance. #### Response Example ```rust // OpusDecoder instance ``` ``` -------------------------------- ### G.722 Decoder Constructor (With Options) Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Creates a new G.722 decoder instance with specified options for bitrate, packing, and 8kHz mode. ```rust pub fn with_options(rate: Bitrate, packed: bool, eight_k: bool) -> Self { Self { packed, eight_k, bits_per_sample: rate.bits_per_sample(), x: Default::default(), band: Default::default(), in_buffer: 0, in_bits: 0, } } ``` -------------------------------- ### Create Opus Encoder Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/opus.rs.html Initializes a new Opus encoder with specified sample rate and channel count. Panics if the encoder creation fails. ```rust pub fn new(sample_rate: u32, channel_count: u16) -> Self { let mut error = 0i32; let ptr = opus_encoder_create( sample_rate, channel_count, &mut error, ); if error != OPUS_OK as i32 { panic!( "Failed to create Opus encoder: {}", opus_error_message(error) ); } let encoder = NonNull::new(ptr).unwrap_or_else(|| { panic!("Failed to create Opus encoder: null pointer returned"); }); Self { encoder, sample_rate, channels: if channel_count == 1 { 1 } else { 2 }, } } ``` -------------------------------- ### Get Payload Type for Codec Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Returns the dynamic payload type number assigned to each `CodecType`. These are typically used in RTP packet headers. ```rust pub fn payload_type(&self) -> u8 { match self { CodecType::PCMU => 0, CodecType::PCMA => 8, CodecType::G722 => 9, CodecType::G729 => 18, #[cfg(feature = "opus")] CodecType::Opus => 111, CodecType::TelephoneEvent => 101, } } ``` -------------------------------- ### Get Type ID of a Generic Type T Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Encoder.html Obtains the `TypeId` of a given type `T`. This is part of the `Any` trait implementation and is useful for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Get G722Encoder Channel Count Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Encoder.html Retrieves the number of audio channels the G722Encoder expects for input samples. This is typically 1 for mono or 2 for stereo. ```rust fn channels(&self) -> u16 ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/audio-codec/0.3.30/audio_codec/enum.CodecType.html An experimental nightly-only API for cloning a value into uninitialized memory. Use with caution as it is unsafe. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Sample to Bytes Conversion Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Utilities for converting slices of `Sample` to `Vec`, considering the target system's endianness. ```APIDOC ## `samples_to_bytes(samples: &[Sample]) -> Vec` Converts a slice of `Sample` (audio samples) into a byte vector. ### Behavior based on endianness: - **Little-endian**: Directly reinterprets the memory of the `Sample` slice as bytes. - **Big-endian**: Converts each `Sample` to its little-endian byte representation and collects them. ``` -------------------------------- ### Declare PcmuDecoder Struct Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcmu/struct.PcmuDecoder.html Defines the PcmuDecoder struct, used for decoding μ-law (PCMU) audio format. No specific setup is required beyond this declaration. ```rust pub struct PcmuDecoder {} ``` -------------------------------- ### G722Encoder Constructors Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Encoder.html Provides information on how to create new instances of the G722Encoder. ```APIDOC ## G722Encoder Constructors ### `new()` Creates a new `G722Encoder` with default options. ### `with_options(rate: Bitrate, eight_k: bool, packed: bool)` Creates an encoder with specified bitrate and options. - **rate** (Bitrate): The desired bitrate for encoding. - **eight_k** (bool): If true, uses an 8kHz sampling rate. - **packed** (bool): If true, the output will be packed. ``` -------------------------------- ### G.722 Decoder - Initialization Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Constructs a new G.722 decoder instance with default or specified options. ```APIDOC ## G.722 Decoder - Initialization ### Description Initializes a new G.722 decoder. It can be created with default settings or customized using `with_options`. ### Method `new()` or `with_options(rate: Bitrate, packed: bool, eight_k: bool)` ### Endpoint N/A ### Parameters - **rate** (Bitrate) - The desired bitrate for the decoder (e.g., `Bitrate::Mode1_64000`). - **packed** (bool) - Flag indicating if the input bitstream is packed. - **eight_k** (bool) - Flag indicating if the decoder should operate in an 8kHz mode. ### Request Example ```rust let decoder = G722Decoder::new(); let decoder_custom = G722Decoder::with_options(Bitrate::Mode1_56000, true, false); ``` ### Response - **Self** (G722Decoder) - An instance of the G.722 decoder. ### Response Example N/A ``` -------------------------------- ### Get RTP Map for Codec Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Returns the RTP map string for each `CodecType`. This is used in RTP (Real-time Transport Protocol) sessions to define codec parameters. ```rust pub fn rtpmap(&self) -> &str { match self { CodecType::PCMU => "PCMU/8000", CodecType::PCMA => "PCMA/8000", CodecType::G722 => "G722/8000", CodecType::G729 => "G729/8000", #[cfg(feature = "opus")] CodecType::Opus => "opus/48000/2", CodecType::TelephoneEvent => "telephone-event/8000", } } ``` -------------------------------- ### CodecType::fmtp Implementation Source: https://docs.rs/audio-codec/0.3.30/audio_codec/enum.CodecType.html Returns an optional format parameter string for each CodecType variant. This is used for advanced configuration in RTP. ```rust pub fn fmtp(&self) -> Option<&str> ``` -------------------------------- ### G.722 Decode Frame Logic Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Handles the decoding of G.722 encoded data, differentiating between 8kHz and 16kHz sample rates. Requires setup of the encoder/decoder instance. ```rust let mut output = Vec::with_capacity(data.len() * 2); let mut idx = 0; if self.eight_k { while idx < data.len() { let code = self.extract_code(data, &mut idx); let (wd1, _, wd2) = self.parse_code(code); let rlow = self.process_low_band(wd1, wd2); output.push((rlow << 1) as i16); } } else { while idx < data.len() { let code = self.extract_code(data, &mut idx); let (wd1, ihigh, wd2) = self.parse_code(code); let rlow = self.process_low_band(wd1, wd2); let rhigh = self.process_high_band(ihigh); let pcm = self.apply_qmf_synthesis(rlow, rhigh); output.extend_from_slice(&pcm); } } output ``` -------------------------------- ### Decoder Trait Definition Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Defines the `Decoder` trait for audio decoding. Implementors must provide methods for decoding data, getting the sample rate, and the number of channels. ```rust pub trait Decoder: Send + Sync { /// Decode encoded audio data into PCM samples fn decode(&mut self, data: &[u8]) -> PcmBuf; /// Get the sample rate of the decoded audio fn sample_rate(&self) -> u32; /// Get the number of channels fn channels(&self) -> u16; } ``` -------------------------------- ### G722Decoder Methods Source: https://docs.rs/audio-codec/0.3.30/audio_codec/g722/struct.G722Decoder.html Provides methods for creating and using the G722Decoder, including decoding audio frames. ```APIDOC ## Implementations ### impl G722Decoder #### pub fn new() -> Self Creates a new G722Decoder with default settings. #### pub fn with_options(rate: Bitrate, packed: bool, eight_k: bool) -> Self Creates a new G722Decoder with specified options. - **rate** (Bitrate): The desired audio sample rate. - **packed** (bool): Whether the input data is packed. - **eight_k** (bool): Whether to use the 8kHz variant. #### pub fn decode_frame(&mut self, data: &[u8]) -> PcmBuf Decodes a G.722 frame and returns PCM samples. This is the main decoding function that processes G.722 encoded data. - **data** (&[u8]): A slice of bytes containing the G.722 encoded frame. - Returns: A `PcmBuf` containing the decoded PCM samples. ``` -------------------------------- ### Opus Encoder Creation Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/opus.rs.html Initializes a new Opus encoder instance with specified sample rate, channels, and application type. Panics on creation failure. ```rust pub fn new(sample_rate: u32, channels: u16) -> Self { let channel_count: c_int = if channels == 1 { 1 } else { 2 }; let mut error: c_int = 0; let ptr = unsafe { opus_encoder_create( sample_rate as c_int, channel_count, OPUS_APPLICATION_VOIP, &mut error as *mut c_int, ) }; if error != OPUS_OK { unsafe { if !ptr.is_null() { opus_encoder_destroy(ptr); } } panic!( "Failed to create Opus encoder: " ``` -------------------------------- ### Codec Creation Functions Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Functions to create decoder and encoder instances for different audio codecs. ```APIDOC ## Create Decoder ### Description Creates a decoder instance for the specified audio codec type. ### Function Signature `pub fn create_decoder(codec: CodecType) -> Box` ### Parameters - **codec** (CodecType) - Required - The type of codec to create a decoder for. ### Returns - `Box` - An instance of the decoder. ## Create Encoder ### Description Creates an encoder instance for the specified audio codec type. ### Function Signature `pub fn create_encoder(codec: CodecType) -> Box` ### Parameters - **codec** (CodecType) - Required - The type of codec to create an encoder for. ### Returns - `Box` - An instance of the encoder. ``` -------------------------------- ### Decoder Trait Source: https://docs.rs/audio-codec/0.3.30/audio_codec/trait.Decoder.html The Decoder trait defines the interface for decoding audio data. It requires implementations to provide methods for decoding, retrieving the sample rate, and getting the number of channels. ```APIDOC ## Trait Decoder ### Description Defines the interface for decoding audio data. ### Methods #### `fn decode(&mut self, data: &[u8]) -> PcmBuf` Decode encoded audio data into PCM samples. #### `fn sample_rate(&self) -> u32` Get the sample rate of the decoded audio. #### `fn channels(&self) -> u16` Get the number of channels. ``` -------------------------------- ### QMF Filter and Sample Encoding Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Applies a Quadrature Mirror Filter (QMF) to input samples, calculates low and high band encoded values, and outputs the final code. This is used for processing audio frames. ```rust self.x[22] = rem[0] as i32; self.x[23] = 0; let mut sumodd = self.x[0] * QMF_FILTER_COEFS[0]; sumodd += self.x[2] * QMF_FILTER_COEFS[1]; sumodd += self.x[4] * QMF_FILTER_COEFS[2]; sumodd += self.x[6] * QMF_FILTER_COEFS[3]; sumodd += self.x[8] * QMF_FILTER_COEFS[4]; sumodd += self.x[10] * QMF_FILTER_COEFS[5]; sumodd += self.x[12] * QMF_FILTER_COEFS[6]; sumodd += self.x[14] * QMF_FILTER_COEFS[7]; sumodd += self.x[16] * QMF_FILTER_COEFS[8]; sumodd += self.x[18] * QMF_FILTER_COEFS[9]; sumodd += self.x[20] * QMF_FILTER_COEFS[10]; sumodd += self.x[22] * QMF_FILTER_COEFS[11]; let mut sumeven = self.x[1] * QMF_FILTER_COEFS[11]; sumeven += self.x[3] * QMF_FILTER_COEFS[10]; sumeven += self.x[5] * QMF_FILTER_COEFS[9]; sumeven += self.x[7] * QMF_FILTER_COEFS[8]; sumeven += self.x[9] * QMF_FILTER_COEFS[7]; sumeven += self.x[11] * QMF_FILTER_COEFS[6]; sumeven += self.x[13] * QMF_FILTER_COEFS[5]; sumeven += self.x[15] * QMF_FILTER_COEFS[4]; sumeven += self.x[17] * QMF_FILTER_COEFS[3]; sumeven += self.x[19] * QMF_FILTER_COEFS[2]; sumeven += self.x[21] * QMF_FILTER_COEFS[1]; sumeven += self.x[23] * QMF_FILTER_COEFS[0]; let xlow = (sumeven + sumodd) >> 14; let xhigh = (sumeven - sumodd) >> 14; let ilow = self.encode_low_band(xlow, false); let ihigh = self.encode_high_band(xhigh); let code = (ihigh << 6 | ilow) >> (8 - self.bits_per_sample); self.output_code(code, &mut output); ``` -------------------------------- ### Encoder Trait Definition Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Defines the `Encoder` trait for audio encoding. Implementors must provide methods for encoding PCM samples, getting the input sample rate, and the number of channels. ```rust pub trait Encoder: Send + Sync { /// Encode PCM samples into codec-specific format fn encode(&mut self, samples: &[Sample]) -> Vec; /// Get the sample rate expected for input samples fn sample_rate(&self) -> u32; /// Get the number of channels expected for input fn channels(&self) -> u16; } ``` -------------------------------- ### Create New OpusDecoder Instance Source: https://docs.rs/audio-codec/0.3.30/audio_codec/opus/struct.OpusDecoder.html Creates a new Opus decoder instance with a specified sample rate and number of channels. Ensure the sample rate and channel count are compatible with the Opus format. ```rust pub fn new(sample_rate: u32, channels: u16) -> Self ``` -------------------------------- ### Opus Decoder Creation Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/opus.rs.html Initializes a new Opus decoder instance. Panics if decoder creation fails, ensuring a valid decoder is always available. ```rust pub fn new(sample_rate: u32, channels: u16) -> Self { let channel_count: c_int = if channels == 1 { 1 } else { 2 }; let mut error: c_int = 0; let ptr = unsafe { opus_decoder_create( sample_rate as c_int, channel_count, &mut error as *mut c_int, ) }; if error != OPUS_OK { unsafe { if !ptr.is_null() { opus_decoder_destroy(ptr); } } panic!( "Failed to create Opus decoder: {}", opus_error_message(error) ); } let decoder = NonNull::new(ptr).unwrap_or_else(|| { panic!("Failed to create Opus decoder: null pointer returned"); }); Self { decoder, sample_rate, channels: if channel_count == 1 { 1 } else { 2 }, } } ``` -------------------------------- ### Bytes to Samples Conversion Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Utilities for converting `&[u8]` byte slices to `PcmBuf` (which is a `Vec`), considering the target system's endianness. ```APIDOC ## `bytes_to_samples(u8_data: &[u8]) -> PcmBuf` Converts a byte slice into a `PcmBuf` (vector of audio samples). ### Behavior based on endianness: - **Little-endian**: Directly reinterprets the byte slice as a slice of `Sample` and converts it to a vector. - **Big-endian**: Interprets every two bytes as a little-endian `i16` sample and collects them into a `PcmBuf`. ``` -------------------------------- ### Resampler Structure and Constructor Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/resampler.rs.html Details the Resampler struct, which is a Polyphase FIR Resampler suitable for VoIP, and its associated constructor `new`. ```APIDOC ## struct Resampler ### Description A Polyphase FIR Resampler suitable for VoIP. ### Fields - **input_rate** (usize) - The input audio sample rate. - **output_rate** (usize) - The output audio sample rate. - **ratio** (f64) - The ratio between output and input rates. - **coeffs** (Vec) - The filter coefficients. - **num_phases** (usize) - The number of filter phases. - **taps_per_phase** (usize) - The number of taps per filter phase. - **history** (Vec) - Stores past input samples for filtering. - **current_pos** (f64) - Current position within the resampling process. ### Method `Resampler::new(input_rate: usize, output_rate: usize) -> Self` ### Description Creates a new `Resampler` instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Self** (Resampler) - A new Resampler instance. #### Response Example None ``` -------------------------------- ### Create Default Opus Encoder Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/opus.rs.html Creates a default Opus encoder configured for 48kHz sample rate and stereo channels. If the 'opus_mono' feature is enabled, it defaults to mono. ```rust pub fn new_default() -> Self { #[cfg(feature = "opus_mono")] { return Self::new(48000, 1); } Self::new(48000, 2) } ``` -------------------------------- ### Create Default OpusDecoder Source: https://docs.rs/audio-codec/0.3.30/audio_codec/opus/struct.OpusDecoder.html Creates a default Opus decoder instance configured for 48kHz sample rate and stereo channels. This is a convenient way to initialize the decoder for common use cases. ```rust pub fn new_default() -> Self ``` -------------------------------- ### G.722 Bitrate Bits Per Sample Method Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Method to determine the number of bits per sample for a given G.722 bitrate. Use this to understand the sample resolution for each mode. ```rust impl Bitrate { fn bits_per_sample(&self) -> i32 { match self { Bitrate::Mode1_64000 => 8, Bitrate::Mode2_56000 => 7, Bitrate::Mode3_48000 => 6, } } } ``` -------------------------------- ### Resample audio from 16kHz to 8kHz Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/resampler.rs.html Tests the resampling functionality from a 16kHz input sample rate to an 8kHz output sample rate. Asserts that the output length is within an expected range and that the resampled values are close to the original. ```rust #[test] fn test_resample_16k_to_8k() { let mut resampler = Resampler::new(16000, 8000); let input = vec![1000i16; 160]; let output = resampler.resample(&input); assert!(output.len() >= 75 && output.len() <= 85); for &s in &output[20..output.len() - 20] { assert!((s - 1000).abs() < 100, "Value {} is too far from 1000", s); } } ``` -------------------------------- ### Resample audio from 8kHz to 16kHz Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/resampler.rs.html Tests the resampling functionality from an 8kHz input sample rate to a 16kHz output sample rate. Asserts that the output length is within an expected range and that the resampled values are close to the original. ```rust #[test] fn test_resample_8k_to_16k() { let mut resampler = Resampler::new(8000, 16000); let input = vec![1000i16; 80]; let output = resampler.resample(&input); assert!(output.len() >= 150 && output.len() <= 170); for &s in &output[20..output.len() - 20] { assert!((s - 1000).abs() < 100, "Value {} is too far from 1000", s); } } ``` -------------------------------- ### Audio Configuration API Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/pcma.rs.html Provides methods to retrieve the sample rate and number of channels for the audio codec. ```APIDOC ## GET /config ### Description Retrieves the configuration details of the audio codec, including sample rate and channels. ### Method GET ### Endpoint /config ### Response #### Success Response (200) - **sample_rate** (u32) - The sample rate of the audio codec (e.g., 8000 Hz). - **channels** (u16) - The number of audio channels supported (e.g., 1 for mono). #### Response Example ```json { "sample_rate": 8000, "channels": 1 } ``` ``` -------------------------------- ### Audio Codec Crate Overview Source: https://docs.rs/audio-codec/0.3.30/audio_codec/index.html This section provides an overview of the audio-codec crate, including its re-exports, modules, enums, traits, and functions. ```APIDOC ## Crate audio_codec ### Re-exports - `pub use resampler::Resampler;` - `pub use resampler::resample;` ### Modules - `g722` - `g729` - `opus` - `pcma` - `pcmu` - `resampler` - `telephone_event` ### Enums - `CodecType` ### Traits - `Decoder` - `Encoder` ### Functions - `bytes_to_samples` - `create_decoder` - `create_encoder` - `samples_to_bytes` ### Type Aliases - `PcmBuf` - `Sample` ``` -------------------------------- ### G.722 Decoder Constructor (Default) Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Creates a new G.722 decoder instance with default options (64 kbit/s, non-packed, non-8kHz). ```rust pub fn new() -> Self { Self::with_options(Bitrate::Mode1_64000, false, false) } ``` -------------------------------- ### Encode 16-bit PCM samples into G.722 format (16kHz mode) Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Encodes audio samples in 16kHz mode, processing pairs of samples. This involves applying QMF filters, encoding both low and high bands, and combining them into a single code. ```rust else { // Process all input samples in 16kHz mode // Use chunks_exact(2) for better performance and to avoid bound checks let chunks = amp.chunks_exact(2); let rem = chunks.remainder(); for chunk in chunks { // Shuffle buffer down to make room for new samples self.x.copy_within(2..24, 0); // Add new samples to buffer self.x[22] = chunk[0] as i32; self.x[23] = chunk[1] as i32; // Apply QMF filter to split input into bands // Unrolled loop for 12 coefficients let mut sumodd = self.x[0] * QMF_FILTER_COEFS[0]; sumodd += self.x[2] * QMF_FILTER_COEFS[1]; sumodd += self.x[4] * QMF_FILTER_COEFS[2]; sumodd += self.x[6] * QMF_FILTER_COEFS[3]; sumodd += self.x[8] * QMF_FILTER_COEFS[4]; sumodd += self.x[10] * QMF_FILTER_COEFS[5]; sumodd += self.x[12] * QMF_FILTER_COEFS[6]; sumodd += self.x[14] * QMF_FILTER_COEFS[7]; sumodd += self.x[16] * QMF_FILTER_COEFS[8]; sumodd += self.x[18] * QMF_FILTER_COEFS[9]; sumodd += self.x[20] * QMF_FILTER_COEFS[10]; sumodd += self.x[22] * QMF_FILTER_COEFS[11]; let mut sumeven = self.x[1] * QMF_FILTER_COEFS[11]; sumeven += self.x[3] * QMF_FILTER_COEFS[10]; sumeven += self.x[5] * QMF_FILTER_COEFS[9]; sumeven += self.x[7] * QMF_FILTER_COEFS[8]; sumeven += self.x[9] * QMF_FILTER_COEFS[7]; sumeven += self.x[11] * QMF_FILTER_COEFS[6]; sumeven += self.x[13] * QMF_FILTER_COEFS[5]; sumeven += self.x[15] * QMF_FILTER_COEFS[4]; sumeven += self.x[17] * QMF_FILTER_COEFS[3]; sumeven += self.x[19] * QMF_FILTER_COEFS[2]; sumeven += self.x[21] * QMF_FILTER_COEFS[1]; sumeven += self.x[23] * QMF_FILTER_COEFS[0]; // Scale filter outputs to get low and high bands let xlow = (sumeven + sumodd) >> 14; let xhigh = (sumeven - sumodd) >> 14; // 16kHz mode - encode both bands let ilow = self.encode_low_band(xlow, false); let ihigh = self.encode_high_band(xhigh); let code = (ihigh << 6 | ilow) >> (8 - self.bits_per_sample); // Output the encoded code self.output_code(code, &mut output); } if !rem.is_empty() { self.x.copy_within(2..24, 0); } } ``` -------------------------------- ### resample Function Source: https://docs.rs/audio-codec/0.3.30/audio_codec/resampler/fn.resample.html The `resample` function takes input audio samples, their sample rate, and the desired output sample rate to perform resampling. ```APIDOC ## resample ### Description Resamples audio data from an input sample rate to an output sample rate. ### Method Rust Function ### Endpoint audio_codec::resampler::resample ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual, actual types may vary) pub fn resample( input: &[Sample], input_sample_rate: u32, output_sample_rate: u32, ) -> PcmBuf ``` ### Response #### Success Response (PcmBuf) - **PcmBuf** (type) - The resampled audio data buffer. #### Response Example ```rust // Conceptual representation of the returned PcmBuf // let resampled_audio: PcmBuf = resample(&input_samples, 44100, 48000); ``` ``` -------------------------------- ### PcmuDecoder Methods Source: https://docs.rs/audio-codec/0.3.30/audio_codec/pcmu/struct.PcmuDecoder.html Details on the methods available for the PcmuDecoder struct, including instantiation and decoding. ```APIDOC ## Implementations ### impl PcmuDecoder #### pub fn new() -> Self Creates a new PcmuDecoder instance. ``` -------------------------------- ### Encode 16-bit PCM samples into G.722 format (8kHz mode) Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/g722.rs.html Encodes audio samples in 8kHz mode, directly using input values and scaling for the low band. Only the low band is processed in this mode. ```rust if self.eight_k { while input_idx < amp.len() { // 8kHz mode - Just use input directly with scaling let xlow = amp[input_idx] as i32 >> 1; input_idx += 1; // 8kHz mode - only low band matters let code = self.encode_low_band(xlow, true); self.output_code(code, &mut output); } } ``` -------------------------------- ### A-law Encoding Algorithm Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/pcma.rs.html Implements the A-law (PCMA) encoding algorithm. Handles sign, magnitude scaling, and quantization. Special cases for small negative values and i16::MIN are addressed. ```rust const fn linear2alaw_algo(pcm_val: i16) -> u8 { // Special case handling for small negative values [-8, -1] if pcm_val < 0 && pcm_val >= -8 { return 0xD5; } // Determine sign mask and prepare the positive sample value let (mask, abs_val) = if pcm_val >= 0 { (0xD5, pcm_val) // sign bit = 1 } else { // Handle the edge case of -32768 (i16::MIN), which would overflow when negated if pcm_val == i16::MIN { (0x55, i16::MAX) // Use the maximum positive value } else { (0x55, -pcm_val - 8) // sign bit = 0 } }; // Convert the scaled magnitude to segment number let seg = search(abs_val, &SEG_END, 8); // If out of range, return maximum value if seg >= 8 { return (0x7F ^ mask) as u8; } // Calculate the base value from segment let aval = (seg as i16) << SEG_SHIFT; // Combine the segment value with the quantization bits let shift = if seg < 2 { 4 } else { seg as i16 + 3 }; let result = aval | ((abs_val >> shift) & QUANT_MASK); // Apply the mask to set the sign bit (result ^ mask) as u8 } ``` -------------------------------- ### Optimized Dot Product for ARM Neon Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/resampler.rs.html Implements a dot product using ARM Neon intrinsics for `aarch64`. This function is unsafe and requires the `aarch64` target architecture. ```rust unsafe { use std::arch::aarch64::*; let mut sumv = vdupq_n_f32(0.0); for i in (0..16).step_by(4) { let av = vld1q_f32(a.as_ptr().add(i)); let bv = vld1q_f32(b.as_ptr().add(i)); sumv = vfmaq_f32(sumv, av, bv); } vaddvq_f32(sumv) } ``` -------------------------------- ### Default Opus Decoder Creation Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/opus.rs.html Creates a default Opus decoder configured for 48kHz sample rate and stereo channels. Includes a feature flag for mono support. ```rust pub fn new_default() -> Self { #[cfg(feature = "opus_mono")] { return Self::new(48000, 1); } Self::new(48000, 2) } ``` -------------------------------- ### Convert samples to bytes (little-endian) Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/lib.rs.html Converts a slice of Sample to a Vec using unsafe operations for little-endian systems. Assumes Sample has a layout compatible with u8. ```rust #[cfg(target_endian = "little")] pub fn samples_to_bytes(samples: &[Sample]) -> Vec { unsafe { std::slice::from_raw_parts( samples.as_ptr() as *const u8, samples.len() * std::mem::size_of::(), ) .to_vec() } } ``` -------------------------------- ### Generic resampling function Source: https://docs.rs/audio-codec/0.3.30/src/audio_codec/resampler.rs.html Provides a convenient function to resample audio data between two sample rates. If the input and output sample rates are the same, it returns the input data directly. ```rust pub fn resample(input: &[Sample], input_sample_rate: u32, output_sample_rate: u32) -> PcmBuf { if input_sample_rate == output_sample_rate { return input.to_vec(); } let mut r = Resampler::new(input_sample_rate as usize, output_sample_rate as usize); r.resample(input) } ```