### Prefilter Memory and Input Buffer Setup Source: https://docs.rs/opus-rs/latest/src/opus_rs/celt.rs.html Initializes the `pre` buffer by copying prefilter memory and appending the current input frame. This prepares the data for pitch analysis. ```rust let max_period = COMBFILTER_MAXPERIOD; let min_period = COMBFILTER_MINPERIOD; let buf_stride = frame_size + overlap; let pre_size = max_period + frame_size; for c in 0..channels { pre[c * pre_size..c * pre_size + max_period] .copy_from_slice(&prefilter_mem[c * max_period..(c + 1) * max_period]); pre[c * pre_size + max_period..c * pre_size + pre_size].copy_from_slice( &in_buf[c * buf_stride + overlap..c * buf_stride + overlap + frame_size], ); } ``` -------------------------------- ### Setup Silk Encoder Sample Rate and Frame Size Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/control_codec.rs.html Configures the Silk encoder's sample rate, frame length, and related parameters based on the provided sample rate and packet size in milliseconds. It adjusts internal state variables like LPC order and NLSF callbacks based on the sample rate. ```rust use crate::silk::define::*; use crate::silk::structs::*; use crate::silk::tables_nlsf::*; pub const FIND_PITCH_LPC_WIN_MS: i32 = 20 + (LA_PITCH_MS as i32 * 2); pub const FIND_PITCH_LPC_WIN_MS_2_SF: i32 = 10 + (LA_PITCH_MS as i32 * 2); pub const MAX_DEL_DEC_STATES: i32 = 4; pub const LA_SHAPE_MAX: i32 = LA_SHAPE_MS as i32 * MAX_FS_KHZ as i32; pub const SHAPE_LPC_WIN_MAX: i32 = 15 * MAX_FS_KHZ as i32; pub const WARPING_MULTIPLIER_Q16: i32 = 983; pub fn silk_setup_fs(ps_enc: &mut SilkEncoderState, fs_khz: i32, packet_size_ms: i32) -> i32 { let cmn = &mut ps_enc.s_cmn; if packet_size_ms <= 10 { cmn.n_frames_per_packet = 1; cmn.nb_subfr = if packet_size_ms == 10 { 2 } else { 1 }; cmn.frame_length = packet_size_ms * fs_khz; cmn.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS_2_SF * fs_khz; } else { cmn.n_frames_per_packet = packet_size_ms / MAX_FRAME_LENGTH_MS as i32; cmn.nb_subfr = MAX_NB_SUBFR as i32; cmn.frame_length = 20 * fs_khz; cmn.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS * fs_khz; } cmn.packet_size_ms = packet_size_ms; if cmn.fs_khz != fs_khz { ps_enc.s_nsq = SilkNSQState::default(); cmn.prev_nlsf_q15 = [0; MAX_LPC_ORDER]; cmn.prev_lag = 100; cmn.first_frame_after_reset = 1; ps_enc.s_shape.last_gain_index = 10; ps_enc.s_nsq.lag_prev = 100; ps_enc.s_nsq.prev_gain_q16 = 65536; cmn.prev_signal_type = TYPE_NO_VOICE_ACTIVITY; cmn.fs_khz = fs_khz; if fs_khz == 8 || fs_khz == 12 { cmn.predict_lpc_order = MIN_LPC_ORDER as i32; ps_enc.ps_nlsf_cb = Some(&SILK_NLSF_CB_NB_MB); } else { cmn.predict_lpc_order = MAX_LPC_ORDER as i32; ps_enc.ps_nlsf_cb = Some(&SILK_NLSF_CB_WB); } cmn.subfr_length = SUB_FRAME_LENGTH_MS as i32 * fs_khz; cmn.frame_length = cmn.subfr_length * cmn.nb_subfr; cmn.ltp_mem_length = LTP_MEM_LENGTH_MS as i32 * fs_khz; cmn.la_pitch = LA_PITCH_MS as i32 * fs_khz; if cmn.nb_subfr == MAX_NB_SUBFR as i32 { cmn.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS * fs_khz; } else { cmn.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS_2_SF * fs_khz; } } SILK_NO_ERROR } ``` -------------------------------- ### Decode Audio Data with Start Band Source: https://docs.rs/opus-rs/latest/src/opus_rs/celt.rs.html Decodes compressed audio data, allowing specification of the starting frequency band. Useful for partial decoding or specific frequency range processing. ```rust pub fn decode_with_start_band( &mut self, compressed: &[u8], frame_size: usize, pcm: &mut [f32], start_band: usize, ) -> usize { self.decode_impl(compressed, frame_size, pcm, start_band, self.mode.nb_ebands) } ``` -------------------------------- ### Prepare Lowband Views Source: https://docs.rs/opus-rs/latest/src/opus_rs/bands.rs.html Prepares views for lowband audio data, either from scratch or using a scratch buffer. Handles cases where output is not desired or when scratch memory is allowed. ```rust fn prepare_lowband_views( norm: &mut [f32], lowband_scratch_ptr: *mut f32, allow_lowband_scratch: bool, effective_lowband: i32, norm_pos: usize, n: usize, want_out: bool, ) -> (Option<&mut [f32]>, Option<&mut [f32]>) { let len = norm.len(); let out_range = if want_out && norm_pos + n <= len { Some((norm_pos, norm_pos + n)) } else { None }; let Some(lb_start) = (if effective_lowband >= 0 { Some(effective_lowband as usize) } else { None }) else { let lb_out = out_range.map(|(s, e)| &mut norm[s..e]); return (None, lb_out); }; let lb_end = lb_start + n; if lb_end > len { let lb_out = out_range.map(|(s, e)| &mut norm[s..e]); return (None, lb_out); } if allow_lowband_scratch { unsafe { std::ptr::copy_nonoverlapping(norm.as_ptr().add(lb_start), lowband_scratch_ptr, n) }; let lb = Some(unsafe { std::slice::from_raw_parts_mut(lowband_scratch_ptr, n) }); let lb_out = out_range.map(|(s, e)| &mut norm[s..e]); return (lb, lb_out); } if let Some((out_start, out_end)) = out_range { if lb_end <= out_start { let (left, right) = norm.split_at_mut(out_start); let lb = Some(&mut left[lb_start..lb_end]); let lb_out = Some(&mut right[..(out_end - out_start)]); return (lb, lb_out); } if out_end <= lb_start { let (left, right) = norm.split_at_mut(lb_start); let lb_out = Some(&mut left[out_start..out_end]); let lb = Some(&mut right[..n]); return (lb, lb_out); } return (Some(&mut norm[lb_start..lb_end]), None); } (Some(&mut norm[lb_start..lb_end]), None) } ``` -------------------------------- ### SilkDecoder::frame_length Source: https://docs.rs/opus-rs/latest/opus_rs/silk/dec_api/struct.SilkDecoder.html Gets the current frame length of the SilkDecoder. ```APIDOC ## SilkDecoder::frame_length ### Description Gets the current frame length in samples that the SilkDecoder is configured to process. ### Returns - `i32`: The frame length in samples. ``` -------------------------------- ### silk_setup_fs Source: https://docs.rs/opus-rs/latest/opus_rs/silk/control_codec/fn.silk_setup_fs.html Sets up the Silk encoder state. This function initializes the encoder with the given sample rate (in kHz), packet size (in milliseconds), and returns an error code. ```APIDOC ## Function silk_setup_fs ### Description Initializes the Silk encoder state with the specified sample rate and packet size. ### Signature ```rust pub fn silk_setup_fs( ps_enc: &mut SilkEncoderState, fs_khz: i32, packet_size_ms: i32, ) -> i32 ``` ### Parameters * `ps_enc`: A mutable reference to the `SilkEncoderState` to be configured. * `fs_khz`: The desired sample rate in kilohertz (kHz). * `packet_size_ms`: The desired packet size in milliseconds (ms). ### Returns An integer representing the error code. A return value of 0 typically indicates success, while non-zero values indicate an error. ``` -------------------------------- ### SilkDecoder::sample_rate Source: https://docs.rs/opus-rs/latest/opus_rs/silk/dec_api/struct.SilkDecoder.html Gets the sample rate the SilkDecoder is configured to use. ```APIDOC ## SilkDecoder::sample_rate ### Description Gets the sample rate in Hz that the SilkDecoder is configured to use. ### Returns - `i32`: The sample rate in Hz. ``` -------------------------------- ### silk_setup_fs Source: https://docs.rs/opus-rs/latest/opus_rs/silk/control_codec/index.html Configures the sample rate for the Silk encoder. The sample rate affects the audio bandwidth and encoding parameters. ```APIDOC ## Function silk_setup_fs ### Description Configures the sample rate for the Silk encoder. The sample rate affects the audio bandwidth and encoding parameters. ### Signature `pub fn silk_setup_fs(...)` ### Parameters (Parameters not explicitly detailed in the source) ### Returns (Return value not explicitly detailed in the source) ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/opus-rs/latest/opus_rs/mdct/struct.MdctLookup.html Provides the `type_id` method to get the `TypeId` of the instance. ```rust fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ``` -------------------------------- ### KissFftState Initialization Source: https://docs.rs/opus-rs/latest/src/opus_rs/kiss_fft.rs.html Manages the state for Fast Fourier Transform (FFT) computations, including factors, bit reversal table, and twiddle factors. Supports initialization with a specified FFT size. ```APIDOC ## KissFftState::new ### Description Initializes a new `KissFftState` for a given FFT size (`nfft`). It computes the necessary factors, scale, bit reversal table, and twiddle factors. ### Parameters - **nfft** (usize) - The size of the FFT. ### Returns - `Option` - Returns `Some(KissFftState)` if initialization is successful, otherwise `None` (e.g., if `nfft` cannot be factored). ### Example ```rust let fft_state = KissFftState::new(1024); if let Some(state) = fft_state { // Use the fft state } ``` ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/opus-rs/latest/opus_rs/celt/struct.AnalysisInfo.html Provides a method to get the TypeId of the AnalysisInfo struct. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Prepare Input Buffer for Encoding Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/enc_api.rs.html Initializes and populates an input buffer with stereo mid-values and resampled audio data, preparing it for the main encoding functions. ```rust let mut input_buf = [0i16; MAX_FRAME_LENGTH + 2]; input_buf[0] = ps_enc.stereo.s_mid[0]; input_buf[1] = ps_enc.stereo.s_mid[1]; input_buf[2..2 + n].copy_from_slice(&resampler_out[..n]); ps_enc.stereo.s_mid[0] = input_buf[frame_length]; ps_enc.stereo.s_mid[1] = input_buf[frame_length + 1]; ``` -------------------------------- ### Get SilkDecoder Sample Rate Source: https://docs.rs/opus-rs/latest/opus_rs/silk/dec_api/struct.SilkDecoder.html Retrieves the sample rate at which the SilkDecoder is operating. ```rust pub fn sample_rate(&self) -> i32 ``` -------------------------------- ### Finalize and Get Encoded Data Source: https://docs.rs/opus-rs/latest/opus_rs/range_coder/struct.RangeCoder.html Finalizes the encoding process and returns the resulting byte vector. ```rust pub fn finish(&mut self) -> Vec ``` -------------------------------- ### silk_setup_fs Function Signature Source: https://docs.rs/opus-rs/latest/opus_rs/silk/control_codec/fn.silk_setup_fs.html This snippet shows the function signature for silk_setup_fs. It takes a mutable reference to SilkEncoderState, the sample rate in kHz, and the packet size in milliseconds, returning an i32 status code. ```rust pub fn silk_setup_fs( ps_enc: &mut SilkEncoderState, fs_khz: i32, packet_size_ms: i32, ) -> i32 ``` -------------------------------- ### Quantization Calculation (compute_qn) Source: https://docs.rs/opus-rs/latest/src/opus_rs/bands.rs.html Calculates the quantization value 'qb' based on input parameters like band count, bias, offset, and pulse capacity. Includes logic for stereo and bit resolution. ```rust #[inline(always)] pub fn compute_qn(n: usize, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 { static EXP2_TABLE8: [i16; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048]; let mut n2 = (2 * n as i32) - 1; if stereo && n == 2 { n2 -= 1; } let mut qb = celt_sudiv(b + n2 * offset, n2); qb = qb.min(b - pulse_cap - (4 << BITRES)); qb = qb.min(8 << BITRES); if qb < (1i32 << BITRES >> 1) { 1 } else { // The original code snippet was truncated here. // Assuming it would return qb or a related value. qb } } ``` -------------------------------- ### Get Fast Bit Count Source: https://docs.rs/opus-rs/latest/opus_rs/range_coder/struct.RangeCoder.html Returns an approximation of the total bit count for faster reporting. ```rust pub fn tell_fast(&self) -> i32 ``` -------------------------------- ### Get Fractional Bit Count Source: https://docs.rs/opus-rs/latest/opus_rs/range_coder/struct.RangeCoder.html Returns the current fractional bit count of the encoded data. ```rust pub fn tell_frac(&self) -> i32 ``` -------------------------------- ### SilkDecoder::init Source: https://docs.rs/opus-rs/latest/opus_rs/silk/dec_api/struct.SilkDecoder.html Initializes the SilkDecoder with the specified sample rate and number of channels. ```APIDOC ## SilkDecoder::init ### Description Initializes the SilkDecoder with the specified sample rate and number of channels. ### Parameters #### Path Parameters - `sample_rate_hz` (i32) - The desired sample rate in Hz. - `channels` (i32) - The number of audio channels. ### Returns - `i32`: An integer representing the result of the initialization (e.g., 0 for success, non-zero for error). ``` -------------------------------- ### Get SilkDecoder Frame Length Source: https://docs.rs/opus-rs/latest/opus_rs/silk/dec_api/struct.SilkDecoder.html Retrieves the current frame length in samples that the decoder is configured to process. ```rust pub fn frame_length(&self) -> i32 ``` -------------------------------- ### SilkResampler::init Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/resampler.rs.html Initializes the SilkResampler with input and output sample rates. It sets up internal parameters based on the provided rates and determines the resampling mode. ```APIDOC ## SilkResampler::init ### Description Initializes the SilkResampler with input and output sample rates. It sets up internal parameters based on the provided rates and determines the resampling mode. ### Method `pub fn init(&mut self, fs_hz_in: i32, fs_hz_out: i32) -> i32` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * `fs_hz_in` (i32) - The input sample rate in Hz. * `fs_hz_out` (i32) - The output sample rate in Hz. ### Returns * `i32` - Returns 0 on success, or -1 if the input or output sample rates are invalid. ``` -------------------------------- ### PVQ Search Initialization (Scalar Fallback) Source: https://docs.rs/opus-rs/latest/src/opus_rs/pvq.rs.html Initializes PVQ search by calculating absolute values, sums, and signs for input vectors when AVX2 or NEON are not available. This is a scalar fallback implementation. ```rust let mut abs_x = [0.0f32; 32]; let mut y2f = [0.0f32; 32]; let mut sign_x = [0i32; 32]; #[cfg(target_arch = "aarch64")] let sum = unsafe { pvq_search_scalar_init_neon(x, n, &mut abs_x, &mut sign_x) }; #[cfg(all(not(target_arch = "aarch64"), target_arch = "x86_64"))] let sum = unsafe { if std::arch::is_x86_feature_detected!("avx2") { pvq_search_scalar_init_avx2(x, n, &mut abs_x, &mut sign_x) } else { let mut s = 0.0f32; for i in 0..n { let xi = x[i]; let abs_xi = xi.abs(); abs_x[i] = abs_xi; s += abs_xi; sign_x[i] = (xi < 0.0) as i32; } s } }; #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] let sum = { let mut s = 0.0f32; for i in 0..n { let xi = x[i]; let abs_xi = xi.abs(); abs_x[i] = abs_xi; s += abs_xi; sign_x[i] = (xi < 0.0) as i32; } s }; ``` -------------------------------- ### Get Default CeltMode Source: https://docs.rs/opus-rs/latest/opus_rs/modes/fn.default_mode.html Retrieves the default CeltMode configuration. This is useful for initializing Opus encoders with standard settings. ```rust pub fn default_mode() -> &'static CeltMode ``` -------------------------------- ### KissFftState::new Constructor Source: https://docs.rs/opus-rs/latest/src/opus_rs/kiss_fft.rs.html Creates a new KissFftState for a given FFT size (nfft). It factorizes the size, computes the bit reversal table, and generates twiddle factors. Returns None if the FFT size is not factorizable. ```rust impl KissFftState { pub fn new(nfft: usize) -> Option { let mut factors = [0i16; 2 * MAXFACTORS]; if !kf_factor(nfft, &mut factors) { return None; } let scale = 1.0 / nfft as f32; let twiddles = compute_twiddles(nfft); let mut bitrev = vec![0i16; nfft]; compute_bitrev_table(0, &mut bitrev, 1, 1, &factors); Some(Self { nfft, scale, shift: -1, factors, bitrev, twiddles, }) } // ... other methods ... ``` -------------------------------- ### CeltDecoder::decode_from_range_coder_with_band_range Source: https://docs.rs/opus-rs/latest/opus_rs/celt/struct.CeltDecoder.html A specialized decoding method using a `RangeCoder`, allowing control over both the starting and ending frequency bands for decoding. ```APIDOC ## CeltDecoder::decode_from_range_coder_with_band_range ### Description Decodes a frame of CELT audio data from an existing `RangeCoder`, specifying both the start and end frequency bands. ### Signature `pub fn decode_from_range_coder_with_band_range(&mut self, rc: &mut RangeCoder, total_bits: i32, frame_size: usize, pcm: &mut [f32], start_band: usize, end_band: usize) -> usize` ### Parameters * `rc`: A mutable reference to the `RangeCoder` instance. * `total_bits`: The total number of bits available for decoding this frame. * `frame_size`: The expected number of samples per channel in the decoded frame. * `pcm`: A mutable slice of f32 where the decoded PCM samples will be written. * `start_band`: The frequency band index from which to start decoding. * `end_band`: The frequency band index up to which decoding should occur. ### Returns The number of samples decoded per channel. ``` -------------------------------- ### KissFftState Methods Source: https://docs.rs/opus-rs/latest/opus_rs/kiss_fft/struct.KissFftState.html This section details the public methods available for the KissFftState struct, allowing users to create and manage FFT states. ```APIDOC ## KissFftState Represents the state for a Kiss Fast Fourier Transform (FFT). ### Fields * `bitrev`: `Vec` - A vector of integers used for bit reversal in the FFT algorithm. ### Methods #### `new(nfft: usize) -> Option` Creates a new `KissFftState` with the specified number of FFT points (`nfft`). Returns `None` if the `nfft` is not supported. * **Parameters**: * `nfft` (usize): The number of FFT points. #### `new_sub(base: &KissFftState, nfft: usize) -> Option` Creates a new sub-`KissFftState` based on an existing `KissFftState`. This is useful for creating states with a different number of FFT points derived from a base state. * **Parameters**: * `base` (&KissFftState): The base `KissFftState` to derive from. * `nfft` (usize): The number of FFT points for the new sub-state. #### `nfft(&self) -> usize` Returns the number of FFT points for this `KissFftState`. #### `scale(&self) -> f32` Returns the scaling factor associated with this `KissFftState`. ``` -------------------------------- ### CeltDecoder::decode_with_start_band Source: https://docs.rs/opus-rs/latest/opus_rs/celt/struct.CeltDecoder.html Decodes compressed audio data, specifying the starting band for decoding. Returns the number of samples decoded. ```rust pub fn decode_with_start_band( &mut self, compressed: &[u8], frame_size: usize, pcm: &mut [f32], start_band: usize, ) -> usize ``` -------------------------------- ### Control Silk Encoder Initialization Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/control_codec.rs.html Initializes and controls the Silk encoder by setting the sample rate, packet size, target bitrate, and complexity. It calls `silk_setup_fs` and `silk_setup_complexity` internally. ```rust pub fn silk_control_encoder( ps_enc: &mut SilkEncoderState, fs_khz: i32, packet_size_ms: i32, target_rate_bps: i32, complexity: i32, ) -> i32 { let mut ret = silk_setup_fs(ps_enc, fs_khz, packet_size_ms); ret += silk_setup_complexity(ps_enc, complexity); ps_enc.s_cmn.target_rate_bps = target_rate_bps; ret } ``` -------------------------------- ### Get Total Bit Count Source: https://docs.rs/opus-rs/latest/opus_rs/range_coder/struct.RangeCoder.html Returns the total bit count of the encoded data, matching C's `ec_tell()`. ```rust pub fn tell(&self) -> i32 ``` -------------------------------- ### PVQ Search Scalar Initialization with AVX2 Source: https://docs.rs/opus-rs/latest/src/opus_rs/pvq.rs.html Initializes PVQ search parameters using AVX2 instructions. Computes absolute values, sums them, and determines signs for vector elements. ```rust unsafe fn pvq_search_scalar_init_avx2( x: &[f32], n: usize, abs_x: &mut [f32; 32], sign_x: &mut [i32; 32], ) -> f32 { use std::arch::x86_64::*; let sign_mask = _mm256_set1_ps(-0.0f32); let mut acc = _mm256_setzero_ps(); let mut i = 0; while i + 8 <= n { let v = _mm256_loadu_ps(x.as_ptr().add(i)); let a = _mm256_andnot_ps(sign_mask, v); _mm256_storeu_ps(abs_x.as_mut_ptr().add(i), a); acc = _mm256_add_ps(acc, a); for j in 0..8 { sign_x[i + j] = (x[i + j] < 0.0) as i32; } i += 8; } let lo = _mm256_castps256_ps128(acc); let hi = _mm256_extractf128_ps(acc, 1); let s4 = _mm_add_ps(lo, hi); let s2 = _mm_add_ps(s4, _mm_movehl_ps(s4, s4)); let s1 = _mm_add_ss(s2, _mm_shuffle_ps(s2, s2, 1)); let mut sum = _mm_cvtss_f32(s1); for j in i..n { let abs_xi = x[j].abs(); abs_x[j] = abs_xi; sum += abs_xi; sign_x[j] = (x[j] < 0.0) as i32; } sum } ``` -------------------------------- ### Rust Range Coder Laplace Get Freq1 Source: https://docs.rs/opus-rs/latest/src/opus_rs/range_coder.rs.html Helper function to calculate frequency for Laplace distribution, used internally by encode/decode. ```rust fn laplace_get_freq1(&self, fs0: u32, decay: i32) -> u32 { let ft = 32768 - (2 * 16) - fs0; ((ft as i32 * (16384 - decay)) >> 15) as u32 } ``` -------------------------------- ### Quantize All Bands Function Source: https://docs.rs/opus-rs/latest/src/opus_rs/bands.rs.html Initializes and manages the quantization process for all audio bands. It sets up buffers, calculates band normalization, and orchestrates the per-band quantization based on encoding or decoding context. ```rust #[allow(clippy::too_many_arguments)] pub fn quant_all_bands( encode: bool, m: &CeltMode, start: usize, end: usize, x: &mut [f32], mut y: Option<&mut [f32]>, collapse_masks: &mut [u32], band_e: &[f32], pulses: &[i32], short_blocks: bool, spread: i32, dual_stereo: &mut bool, intensity: usize, tf_res: &[i32], total_bits: i32, balance: &mut i32, rc: &mut RangeCoder, lm: i32, coded_bands: i32, resynth: bool, disable_inv: bool, seed: &mut u32, ) { let mut balance_val = *balance; let b_blocks = if short_blocks { 1 << lm } else { 1 }; let c_channels = if y.is_some() { 2 } else { 1 }; let m_val = 1usize << lm as usize; let norm_offset = m_val * (m.e_bands[start] as usize); let norm_size = m_val * (m.e_bands[m.nb_ebands - 1] as usize) - norm_offset; const MAX_NORM_SIZE: usize = 800; debug_assert!(norm_size <= MAX_NORM_SIZE); let mut norm_buf = [std::mem::MaybeUninit::::uninit(); MAX_NORM_SIZE]; let norm = unsafe { std::slice::from_raw_parts_mut(norm_buf.as_mut_ptr() as *mut f32, norm_size) }; let mut norm2_buf = [std::mem::MaybeUninit::::uninit(); MAX_NORM_SIZE]; let norm2 = unsafe { std::slice::from_raw_parts_mut(norm2_buf.as_mut_ptr() as *mut f32, norm_size) }; let mut lowband_scratch_buf = [std::mem::MaybeUninit::::uninit(); MAX_PVQ_N]; let lowband_scratch_ptr = lowband_scratch_buf.as_mut_ptr() as *mut f32; let mut lowband_offset: usize = 0; let mut update_lowband = true; let mut avoid_split_noise = b_blocks > 1; let e_bands = &m.e_bands; let mut ctx_seed = *seed; } ``` -------------------------------- ### Get Silk Decoder Sample Rate Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/dec_api.rs.html Returns the sample rate of the Silk decoder in Hz. This indicates the audio fidelity being decoded. ```rust pub fn sample_rate(&self) -> i32 { self.channel_state[0].fs_khz * 1000 } ``` -------------------------------- ### CeltDecoder::decode_with_start_band Source: https://docs.rs/opus-rs/latest/opus_rs/celt/struct.CeltDecoder.html Decodes compressed audio data, allowing specification of the starting band for decoding. This can be useful for VBR or specific decoding scenarios. ```APIDOC ## CeltDecoder::decode_with_start_band ### Description Decodes a frame of compressed CELT audio data, specifying the starting frequency band for decoding. ### Signature `pub fn decode_with_start_band(&mut self, compressed: &[u8], frame_size: usize, pcm: &mut [f32], start_band: usize) -> usize` ### Parameters * `compressed`: A slice of bytes containing the compressed audio data. * `frame_size`: The expected number of samples per channel in the decoded frame. * `pcm`: A mutable slice of f32 where the decoded PCM samples will be written. * `start_band`: The frequency band index from which to start decoding. ### Returns The number of samples decoded per channel. ``` -------------------------------- ### Opus Decoder Configuration and Usage Source: https://docs.rs/opus-rs/latest/src/opus_rs/lib.rs.html Illustrates the configuration and usage of the Opus decoder, including setting the sample rate and channels. This is essential for reconstructing audio from encoded data. ```rust use opus_rs::OpusDecoder; fn main() { let mut decoder = OpusDecoder::new(48000, 1).unwrap(); let mut input = vec![0u8; 1024]; // Dummy encoded data let mut output = vec![0i16; 48 * 1]; // Fill input with dummy encoded data (e.g., from encoder) for i in input.iter_mut() { *i = 1; } let res = decoder.decode(&input, &mut output); assert!(res.is_ok()); let decoded_samples = &output[..res.unwrap()]; println!("Decoded samples count: {}", decoded_samples.len()); } ``` -------------------------------- ### Initialize PVQ Search (Generic) Source: https://docs.rs/opus-rs/latest/src/opus_rs/pvq.rs.html Initializes PVQ search by calculating absolute values, signs, and their sum for non-AArch64 architectures. This is the generic fallback implementation. ```rust #[cfg(not(target_arch = "aarch64"))] let sum = { let mut s = 0.0f32; for i in 0..n { abs_x_mu[i].write(x[i].abs()); signs_mu[i].write(if x[i] < 0.0 { -1i32 } else { 1i32 }); s += unsafe { abs_x_mu[i].assume_init() }; } s }; ``` -------------------------------- ### CeltEncoder::encode_with_start_band Source: https://docs.rs/opus-rs/latest/opus_rs/celt/struct.CeltEncoder.html Encodes PCM audio data, allowing specification of the starting band for encoding. This can be useful for certain optimization or control scenarios. ```APIDOC ## CeltEncoder::encode_with_start_band ### Description Encodes a frame of PCM audio data, similar to `encode`, but allows specifying the starting frequency band for the encoding process. ### Signature `pub fn encode_with_start_band(&mut self, pcm: &[f32], frame_size: usize, rc: &mut RangeCoder, start_band: usize)` ### Parameters * `pcm`: A slice of f32 representing the PCM audio samples. * `frame_size`: The number of samples in the frame to encode. * `rc`: A mutable reference to a `RangeCoder` to store the encoded output. * `start_band`: The frequency band index from which to start encoding. ``` -------------------------------- ### Decode from Range Coder with Band Range Source: https://docs.rs/opus-rs/latest/src/opus_rs/celt.rs.html Decodes audio data from a RangeCoder, specifying both the start and end frequency bands. This provides fine-grained control over the decoding range. ```rust pub fn decode_from_range_coder_with_band_range( &mut self, rc: &mut RangeCoder, total_bits: i32, frame_size: usize, pcm: &mut [f32], start_band: usize, end_band: usize, ) -> usize { self.decode_impl_from_rc(rc, total_bits, frame_size, pcm, start_band, end_band) } ``` -------------------------------- ### Initialize SilkResampler Source: https://docs.rs/opus-rs/latest/opus_rs/silk/resampler/struct.SilkResampler.html Initializes a SilkResampler instance with input and output sample rates. ```rust pub fn init(&mut self, fs_hz_in: i32, fs_hz_out: i32) -> i32 ``` -------------------------------- ### PVQ U Row Lookup Table Source: https://docs.rs/opus-rs/latest/src/opus_rs/pvq.rs.html Defines the base indices for rows in the `CELT_PVQ_U_DATA` table. Used to quickly find the starting point for a given row in the lookup. ```rust const CELT_PVQ_U_ROW: [u32; 15] = [ 0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257, ]; ``` -------------------------------- ### PVQ Search with Extended Quantization (qext) Source: https://docs.rs/opus-rs/latest/src/opus_rs/pvq.rs.html Performs a PVQ search to find quantized vectors (y, up_y, refine) from input data (x). It normalizes the input, uses the op_pvq_refine function for initial and refined quantization, and handles edge cases like zero input sum. ```rust pub fn pvq_search_qext( x: &[f32], y: &mut [i32], up_y: &mut [i32], refine: &mut [i32], k: i32, extra_bits: i32, n: usize, ) -> f32 { debug_assert!(n <= 32); debug_assert!(extra_bits >= 2); let mut sum = 0.0f32; for i in 0..n { sum += x[i].abs(); } if sum < 1e-15 { y[0] = k; up_y[0] = ((1 << extra_bits) - 1) * k; for i in 1..n { y[i] = 0; up_y[i] = 0; refine[i] = 0; } refine[0] = 0; return (up_y[0] as f32) * (up_y[0] as f32); } #[allow(non_snake_case)] let mut Xn: [f32; 32] = [0.0; 32]; let rcp_sum = 1.0 / sum; for i in 0..n { Xn[i] = x[i].abs() * rcp_sum; } let failed1 = op_pvq_refine(&Xn, y, None, k, 1, k + 1, n); let up = (1 << extra_bits) - 1; let up_k = up * k; let margin = up; let failed2 = op_pvq_refine(&Xn, up_y, Some(y), up_k, up, margin, n); if failed1 || failed2 { y[0] = k; up_y[0] = up_k; for i in 1..n { y[i] = 0; up_y[i] = 0; } } for i in 0..n { refine[i] = up_y[i] - up * y[i]; } let mut yy = 0.0f32; for i in 0..n { yy += (up_y[i] as f32) * (up_y[i] as f32); } for i in 0..n { if x[i] < 0.0 { y[i] = -y[i]; up_y[i] = -up_y[i]; refine[i] = -refine[i]; } } yy } ``` -------------------------------- ### Initialize Silk Decoder and Check Sample Rate Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/dec_api.rs.html Initializes a SilkDecoder with a specified sample rate and channels, then asserts the success of the initialization and the configured sample rate. ```rust let mut dec = SilkDecoder::new(); let ret = dec.init(16000, 1); assert_eq!(ret, 0); assert_eq!(dec.sample_rate(), 16000); ``` -------------------------------- ### Get Silk Decoder Frame Length Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/dec_api.rs.html Returns the current frame length of the Silk decoder. This is typically used to determine the expected number of samples per frame. ```rust pub fn frame_length(&self) -> i32 { self.channel_state[0].frame_length } ``` -------------------------------- ### Opus RS: Initial Bit Allocation and Thresholding Source: https://docs.rs/opus-rs/latest/src/opus_rs/rate.rs.html Handles the initial distribution of bits to frequency bands, checking against thresholds and making decisions based on coded band count and bit budget. Includes logic for encoding and decoding bit decisions. ```rust let mut band_bits = bits[j] + percoeff * band_width + rem; if band_bits >= max(thresh[j], alloc_floor + (1 << BITRES)) { if encode { let depth_threshold = if coded_bands > 17 { if (j as i32) < prev { 7 } else { 9 } } else { 0 }; if coded_bands <= start + 2 || (band_bits > ((depth_threshold * band_width) << lm << BITRES) >> 4 && (j as i32) <= signal_bandwidth) { rc.encode_bit_logp(true, 1); break; } rc.encode_bit_logp(false, 1); } else { let bit = rc.decode_bit_logp(1); if bit { break; } } psum += 1 << BITRES; band_bits -= 1 << BITRES; } psum -= bits[j] + intensity_rsv; if intensity_rsv > 0 { intensity_rsv = LOG2_FRAC_TABLE[j - start] as i32; } psum += intensity_rsv; if band_bits >= alloc_floor { psum += alloc_floor; bits[j] = alloc_floor; } else { bits[j] = 0; } coded_bands -= 1; ``` -------------------------------- ### Silk Resampler Down2 3 (Partial Batch Processing) Source: https://docs.rs/opus-rs/latest/src/opus_rs/silk/resampler.rs.html Handles batch processing for 2x downsampling, utilizing `silk_resampler_private_ar2` for filtering. This snippet shows the setup for batch processing. ```rust pub fn silk_resampler_down2_3(s: &mut [i32], out: &mut [i16], input: &[i16], in_len: i32) { let mut n_samples_in: i32; let mut counter: i32; let mut res_q6: i32; let mut buf = [0i32; (RESAMPLER_MAX_BATCH_SIZE_IN as usize) + ORDER_FIR]; let mut in_idx = 0; let mut out_idx = 0; let mut remaining_len = in_len; buf[0..ORDER_FIR].copy_from_slice(&s[0..ORDER_FIR]); while remaining_len > 0 { n_samples_in = remaining_len.min(RESAMPLER_MAX_BATCH_SIZE_IN); silk_resampler_private_ar2( ``` -------------------------------- ### silk_setup_complexity Source: https://docs.rs/opus-rs/latest/opus_rs/silk/control_codec/index.html Sets the complexity level for the Silk encoder. Higher complexity generally leads to better compression at the cost of increased processing time. ```APIDOC ## Function silk_setup_complexity ### Description Sets the complexity level for the Silk encoder. Higher complexity generally leads to better compression at the cost of increased processing time. ### Signature `pub fn silk_setup_complexity(...)` ### Parameters (Parameters not explicitly detailed in the source) ### Returns (Return value not explicitly detailed in the source) ``` -------------------------------- ### Encode and Decode Raw Bits with RangeCoder Source: https://docs.rs/opus-rs/latest/src/opus_rs/range_coder.rs.html Shows how to encode individual bits with specified lengths using `enc_bits` and then decode them using `dec_bits`. The `finish` method is used to get the encoded data. ```rust let mut enc = RangeCoder::new_encoder(1024); enc.enc_bits(1, 1); enc.enc_bits(5, 3); enc.enc_bits(7, 3); enc.enc_bits(0, 2); let data = enc.finish(); let mut dec = RangeCoder::new_decoder(&data); let b1 = dec.dec_bits(1); let b2 = dec.dec_bits(3); let b3 = dec.dec_bits(3); let b4 = dec.dec_bits(2); assert_eq!(b1, 1); assert_eq!(b2, 5); assert_eq!(b3, 7); assert_eq!(b4, 0); ``` -------------------------------- ### Initialize PVQ Search with NEON Intrinsics Source: https://docs.rs/opus-rs/latest/src/opus_rs/pvq.rs.html Initializes PVQ search by calculating absolute values, signs, and their sum using NEON intrinsics for AArch64. This is an optimized path for ARM processors. ```rust #[cfg(target_arch = "aarch64")] let sum = unsafe { pvq_fast_select_init_neon(x, n, &mut abs_x_mu, &mut signs_mu) }; ``` -------------------------------- ### Opus-RS CELT Encoder Core Logic Source: https://docs.rs/opus-rs/latest/src/opus_rs/celt.rs.html Implements the core encoding logic for CELT, handling frame preparation, pre-emphasis, and input buffer setup. This function is called by public encode methods. ```rust pub fn encode_with_budget( &mut self, pcm: &[f32], frame_size: usize, rc: &mut RangeCoder, start_band: usize, total_bits: i32, ) { self.encode_impl(pcm, frame_size, rc, start_band, Some(total_bits)) } fn encode_impl( &mut self, pcm: &[f32], frame_size: usize, rc: &mut RangeCoder, start_band: usize, explicit_total_bits: Option, ) { let mode = self.mode; let channels = self.channels; let nb_ebands = mode.nb_ebands; let overlap = mode.overlap; let mut lm = 0; while (mode.short_mdct_size << lm) != frame_size { lm += 1; if lm > mode.max_lm { break; } } if (mode.short_mdct_size << lm) != frame_size { lm = 0; } let syn_mem_size = 2048 + overlap; for c in 0..channels { let channel_offset = c * syn_mem_size; self.syn_mem.copy_within( channel_offset + frame_size..channel_offset + syn_mem_size, channel_offset, ); let mut m = self.preemph_mem[c]; let coef = mode.preemph[0]; for i in 0..frame_size { let x = pcm[c * frame_size + i] * 32768.0; let val = x - m; self.syn_mem[channel_offset + syn_mem_size - frame_size + i] = val; m = x * coef; } self.preemph_mem[c] = m; } let buf_stride = frame_size + overlap; let in_buf = &mut self.w_in_buf[..buf_stride * channels]; for c in 0..channels { let channel_offset = c * syn_mem_size; let in_buf_offset = c * buf_stride; let src_start = syn_mem_size - frame_size - overlap; in_buf[in_buf_offset..in_buf_offset + buf_stride].copy_from_slice( &self.syn_mem[channel_offset + src_start..channel_offset + syn_mem_size], ); } let mut tf_estimate = 0.0f32; let mut tf_chan = 0; let mut weak_transient = false; let is_transient = if self.complexity >= 1 { transient_analysis( in_buf, buf_stride, channels, &mut tf_estimate, &mut tf_chan, false, &mut weak_transient, 0.0, 0.0, &mut self.w_transient_tmp, &mut self.w_transient_tmp2, ) } else { false }; let toneishness = if self.analysis.valid { self.analysis.tonality } else { 0.0 }; let _tone_freq = 0.0f32; let pf_enabled = start_band == 0 && self.complexity >= 5 && toneishness < 0.99 && channels == 1; let (pf_on, gain1, pitch_index) = if pf_enabled { run_prefilter( in_buf, &mut self.prefilter_mem, self.prefilter_period, self.prefilter_gain, self.prefilter_tapset, self.tapset_decision, mode.window, channels, frame_size, overlap, &mut self.w_prefilter_pre, &mut self.w_prefilter_pitch_buf, &mut self.w_prefilter_before, &mut self.w_prefilter_after, &self.analysis, self.loss_rate, ) } else { (false, 0.0f32, COMBFILTER_MINPERIOD) }; let syn_mem_size = 2048 + overlap; for c in 0..channels { let channel_offset = c * syn_mem_size; let in_buf_offset = c * buf_stride; self.syn_mem[channel_offset + syn_mem_size - overlap..channel_offset + syn_mem_size] ```