### Vector Correlation Calculation Setup Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/sigproc_fix.rs.html Initializes parameters for vector correlation calculation, including setting up indices and handling positive shifts. ```rust pub fn silk_corr_vector_fix( x: &[i16], t: &[i16], l: usize, order: usize, xt: &mut [i32], rshifts: i32, ) { let mut ptr1_idx = order - 1; if rshifts > 0 { for xt_val in xt[..order].iter_mut() { ``` -------------------------------- ### CeltEncoder::encode_with_start_band Method Source: https://docs.rs/opus-rs/0.1.17/opus_rs/celt/struct.CeltEncoder.html Encodes a frame of PCM audio data, specifying a starting band for encoding. Requires mutable access to self and a RangeCoder. ```rust pub fn encode_with_start_band( &mut self, pcm: &[f32], frame_size: usize, rc: &mut RangeCoder, start_band: usize, ) ``` -------------------------------- ### Setup Silk Encoder Sample Rate Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/control_codec.rs.html Configures the Silk encoder's state based on the provided sample rate and packet size. It adjusts frame lengths, pitch window lengths, and other internal parameters. ```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 } ``` -------------------------------- ### Setup Silk Encoder State Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/control_codec/fn.silk_setup_fs.html Initializes the Silk encoder state with specified sample rate and packet size. This function is used to configure the encoder before processing audio data. ```rust pub fn silk_setup_fs( ps_enc: &mut SilkEncoderState, fs_khz: i32, packet_size_ms: i32, ) -> i32 ``` -------------------------------- ### Function silk_setup_fs Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/control_codec/fn.silk_setup_fs.html Sets up the Silk encoder state with the specified sample rate and packet size. ```APIDOC ## Function silk_setup_fs ### Description Sets up the Silk encoder state with the specified sample rate and packet size. ### Method N/A (Rust function) ### Endpoint N/A (Rust function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Rust Signature ```rust pub fn silk_setup_fs( ps_enc: &mut SilkEncoderState, fs_khz: i32, packet_size_ms: i32, ) -> i32 ``` ### Parameters (Rust) - **ps_enc** (*&mut SilkEncoderState*) - A mutable reference to the Silk encoder state. - **fs_khz** (*i32*) - The sample rate in kHz. - **packet_size_ms** (*i32*) - The packet size in milliseconds. ### Return Value (Rust) - (*i32*) - An integer representing the result of the setup operation. (Specific meaning depends on implementation, typically 0 for success). ``` -------------------------------- ### Get Default CeltMode Source: https://docs.rs/opus-rs/0.1.17/opus_rs/modes/fn.default_mode.html Returns the default CeltMode configuration. No setup or imports are required. ```rust pub fn default_mode() -> &'static CeltMode ``` -------------------------------- ### Opus Decoder - Decode with Start Band Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/celt.rs.html Decodes a compressed audio frame into PCM data, allowing specification of the starting frequency band for decoding. ```APIDOC ## POST /decode_with_start_band ### Description Decodes a compressed audio frame into PCM data, specifying the starting frequency band. ### Method POST ### Endpoint /decode_with_start_band ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **compressed** (bytes) - Required - The compressed audio data. - **frame_size** (usize) - Required - The size of the audio frame to decode. - **pcm** (f32 array) - Required - A mutable slice to store the decoded PCM data. - **start_band** (usize) - Required - The starting frequency band for decoding. ### Request Example ```json { "compressed": "base64_encoded_audio_data", "frame_size": 1024, "pcm": [], "start_band": 1 } ``` ### Response #### Success Response (200) - **usize** - The number of samples decoded. #### Response Example ```json { "decoded_samples": 1024 } ``` ``` -------------------------------- ### Decode Audio Frame with Start Band Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/celt.rs.html Decodes a compressed audio frame, allowing specification of the starting frequency band. Useful for multi-channel or advanced decoding scenarios. ```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) } ``` -------------------------------- ### kiss_fft Module Overview Source: https://docs.rs/opus-rs/0.1.17/opus_rs/kiss_fft/index.html Overview of the kiss_fft module, its structs, constants, and functions. ```APIDOC ## Module kiss_fft This module provides Fast Fourier Transform (FFT) functionalities, likely a port or wrapper around the kiss_fft library. ### Structs - **KissCpx**: Represents a complex number, likely used in FFT calculations. - **KissFftState**: Holds the state for FFT computations. ### Constants - **MAXFACTORS**: A constant related to the maximum factors allowed in FFT computations. ### Functions - **opus_fft**: Performs a forward Fast Fourier Transform. - **opus_fft_impl**: An implementation detail for the FFT function. - **opus_ifft**: Performs an inverse Fast Fourier Transform. ``` -------------------------------- ### CloneToUninit Implementation (Nightly) Source: https://docs.rs/opus-rs/0.1.17/opus_rs/celt/struct.AnalysisInfo.html Nightly-only experimental API for copying data to uninitialized memory. Use with caution. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Determine Fold Start for Spectral Folding Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/bands.rs.html Determines the starting index for spectral folding based on the effective lowband absolute position. It finds the first band whose position is less than or equal to el_abs. ```rust let mut fold_start = lowband_offset; while fold_start > 0 { fold_start -= 1; if m_val * (e_bands[fold_start] as usize) <= el_abs { break; } } ``` -------------------------------- ### NEON Optimized PVQ Initialization Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/pvq.rs.html This function initializes PVQ search using NEON intrinsics for ARM architectures. It computes absolute values and sums of input vectors in parallel. ```rust #[cfg(target_arch = "aarch64")] #[inline(always)] #[allow(unsafe_op_in_unsafe_fn)] unsafe fn pvq_fast_select_init_neon( x: &[f32], n: usize, abs_x: &mut [MaybeUninit; MAX_PVQ_N], signs: &mut [MaybeUninit; MAX_PVQ_N], ) -> f32 { use std::arch::aarch64::* ; let mut sum_vec = vdupq_n_f32(0.0); let mut i = 0; while i + 16 <= n { let vx0 = vld1q_f32(x.as_ptr().add(i)); let vx1 = vld1q_f32(x.as_ptr().add(i + 4)); let vx2 = vld1q_f32(x.as_ptr().add(i + 8)); let vx3 = vld1q_f32(x.as_ptr().add(i + 12)); let vabs0 = vabsq_f32(vx0); let vabs1 = vabsq_f32(vx1); let vabs2 = vabsq_f32(vx2); let vabs3 = vabsq_f32(vx3); vst1q_f32(abs_x.as_mut_ptr().add(i) as *mut f32, vabs0); vst1q_f32(abs_x.as_mut_ptr().add(i + 4) as *mut f32, vabs1); vst1q_f32(abs_x.as_mut_ptr().add(i + 8) as *mut f32, vabs2); vst1q_f32(abs_x.as_mut_ptr().add(i + 12) as *mut f32, vabs3); sum_vec = vaddq_f32(sum_vec, vabs0); sum_vec = vaddq_f32(sum_vec, vabs1); sum_vec = vaddq_f32(sum_vec, vabs2); sum_vec = vaddq_f32(sum_vec, vabs3); for j in 0..16 { signs[i + j].write(if x[i + j] < 0.0 { -1i32 } else { 1i32 }); } i += 16; } while i + 8 <= n { let vx0 = vld1q_f32(x.as_ptr().add(i)); let vx1 = vld1q_f32(x.as_ptr().add(i + 4)); let vabs0 = vabsq_f32(vx0); let vabs1 = vabsq_f32(vx1); vst1q_f32(abs_x.as_mut_ptr().add(i) as *mut f32, vabs0); vst1q_f32(abs_x.as_mut_ptr().add(i + 4) as *mut f32, vabs1); sum_vec = vaddq_f32(sum_vec, vabs0); sum_vec = vaddq_f32(sum_vec, vabs1); for j in 0..8 { signs[i + j].write(if x[i + j] < 0.0 { -1i32 } else { 1i32 }); } i += 8; } while i + 4 <= n { let vx = vld1q_f32(x.as_ptr().add(i)); let vabs = vabsq_f32(vx); vst1q_f32(abs_x.as_mut_ptr().add(i) as *mut f32, vabs); sum_vec = vaddq_f32(sum_vec, vabs); for j in 0..4 { signs[i + j].write(if x[i + j] < 0.0 { -1i32 } else { 1i32 }); } i += 4; } let mut sum = vaddvq_f32(sum_vec); for j in i..n { let abs_xi = x[j].abs(); abs_x[j].write(abs_xi); sum += abs_xi; ``` -------------------------------- ### Get FFT Size Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/kiss_fft.rs.html Returns the FFT size (`nfft`) for the current state. ```rust #[inline] pub fn nfft(&self) -> usize { self.nfft } ``` -------------------------------- ### Get Fractional Bit Count Source: https://docs.rs/opus-rs/0.1.17/opus_rs/range_coder/struct.RangeCoder.html Returns the current bit count as a fractional value. ```rust pub fn tell_frac(&self) -> i32 ``` -------------------------------- ### Initialize Output Buffer and Masks Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/celt.rs.html Initializes the output audio buffer and collapse masks. The output buffer is filled with zeros, and masks are prepared for signal processing. ```rust self.w_x[..frame_size * channels].fill(0.0); let x_pad_end = (frame_size * channels + STRIDE_ACCESS_PAD).min(self.w_x.len()); let x = &mut self.w_x[..x_pad_end]; self.w_collapse_masks[..nb_ebands * channels].fill(0); let collapse_masks = &mut self.w_collapse_masks[..nb_ebands * channels]; ``` -------------------------------- ### Create New KissFftState Source: https://docs.rs/opus-rs/0.1.17/opus_rs/kiss_fft/struct.KissFftState.html Initializes a new KissFftState with a specified number of FFT points (nfft). Returns None if the nfft is invalid. ```rust pub fn new(nfft: usize) -> Option ``` -------------------------------- ### Get SilkDecoder Sample Rate Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/dec_api/struct.SilkDecoder.html Retrieves the configured sample rate in Hz for the SilkDecoder. ```rust pub fn sample_rate(&self) -> i32 ``` -------------------------------- ### Get SilkDecoder Frame Length Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/dec_api/struct.SilkDecoder.html Retrieves the current frame length in samples for the SilkDecoder. ```rust pub fn frame_length(&self) -> i32 ``` -------------------------------- ### Implement PartialEq for Bandwidth Source: https://docs.rs/opus-rs/0.1.17/opus_rs/enum.Bandwidth.html Allows comparison of Bandwidth values for equality using the `==` and `!=` operators. The default implementation is usually sufficient. ```rust fn eq(&self, other: &Bandwidth) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Prepare Lowband Views for Quantization Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/bands.rs.html Prepares the views for lowband data (left and right channels) for quantization. It handles lowband scratch and effective lowband calculations. ```rust let (lb_x, lb_out_x) = prepare_lowband_views( norm, lowband_scratch_ptr, allow_lowband_scratch, effective_lowband, norm_pos, n, !last, ); let (lb_y, lb_out_y) = prepare_lowband_views( norm2, lowband_scratch_ptr, allow_lowband_scratch, effective_lowband, norm_pos, n, !last, ); ``` -------------------------------- ### Function get_pulses Source: https://docs.rs/opus-rs/0.1.17/opus_rs/rate/fn.get_pulses.html This function is part of the opus_rs::rate module and is used to get pulses. ```APIDOC ## Function get_pulses ### Description Retrieves pulses based on the provided integer input. ### Method N/A (This is a function signature, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ```rust pub fn get_pulses(i: i32) -> i32 ``` ``` -------------------------------- ### Initialize Stereo and Bit Allocation Buffers Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/celt.rs.html Initializes buffers for stereo processing, pulse coding, fine priority, and bit allocation across frequency bands. This prepares for the main allocation and quantization steps. ```rust let mut intensity = 0; let mut dual_stereo_val = if channels == 2 { 1 } else { 0 }; let mut balance = 0; self.w_pulses[..nb_ebands].fill(0); let pulses = &mut self.w_pulses[..nb_ebands]; let ebands_stereo = if channels > 1 { nb_ebands * channels } else { nb_ebands }; self.w_fine_priority[..ebands_stereo].fill(0); let fine_priority = &mut self.w_fine_priority[..ebands_stereo]; self.w_ebits[..ebands_stereo].fill(0); let ebits = &mut self.w_ebits[..ebands_stereo]; ``` -------------------------------- ### Get NFFT from KissFftState Source: https://docs.rs/opus-rs/0.1.17/opus_rs/kiss_fft/struct.KissFftState.html Returns the number of FFT points (nfft) configured for this KissFftState. ```rust pub fn nfft(&self) -> usize ``` -------------------------------- ### Get Pulses Function Signature Source: https://docs.rs/opus-rs/0.1.17/opus_rs/rate/fn.get_pulses.html This is the function signature for get_pulses. It takes an i32 and returns an i32. ```rust pub fn get_pulses(i: i32) -> i32 ``` -------------------------------- ### Implement Default for SilkNSQState Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/structs/struct.SilkNSQState.html Provides the `default` method for SilkNSQState, enabling the creation of a SilkNSQState instance with default values. ```rust impl Default for SilkNSQState Source #### fn default() -> Self Returns the “default value” for a type. Read more Source ``` -------------------------------- ### fn type_id(&self) -> TypeId Source: https://docs.rs/opus-rs/0.1.17/opus_rs/bands/struct.SplitCtx.html Gets the TypeId of the current object. This is part of the Any trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### SilkResampler Initialization Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/resampler.rs.html Initializes the SilkResampler with input and output sample rates. ```APIDOC ## POST /silkresampler/init ### Description Initializes the SilkResampler with the specified input and output sample rates. ### Method POST ### Endpoint /silkresampler/init ### Parameters #### Query Parameters - **fs_hz_in** (integer) - Required - Input sample rate in Hz. - **fs_hz_out** (integer) - Required - Output sample rate in Hz. ### Request Body This endpoint does not require a request body. ### Response #### Success Response (200) - **status** (integer) - 0 on success, -1 on error. #### Response Example ```json { "status": 0 } ``` ``` -------------------------------- ### SilkDecoder Initialization and Configuration Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/dec_api.rs.html Provides methods for creating, initializing, and configuring the SilkDecoder for audio processing. ```APIDOC ## SilkDecoder::new() ### Description Creates and initializes a new `SilkDecoder` instance with default settings. ### Method `new` ### Endpoint N/A (Struct method) ### Parameters None ### Request Example ```rust let mut decoder = SilkDecoder::new(); ``` ### Response #### Success Response (Instance) - **SilkDecoder** (struct) - An initialized SilkDecoder instance. #### Response Example ```rust // Returns a SilkDecoder instance ``` ## SilkDecoder::init() ### Description Initializes the Silk decoder with a specified sample rate and number of channels. ### Method `init` ### Endpoint N/A (Struct method) ### Parameters - **sample_rate_hz** (i32) - Required - The target audio sample rate in Hz. - **channels** (i32) - Required - The number of audio channels (1 for mono, 2 for stereo). ### Request Example ```rust let mut decoder = SilkDecoder::new(); let result = decoder.init(16000, 1); // Initialize for 16kHz mono ``` ### Response #### Success Response (0) - **0** (i32) - Indicates successful initialization. #### Error Response (-1 or other negative value) - **i32** - An error code indicating failure during initialization. #### Response Example ```rust // Returns 0 on success, or a negative error code on failure. ``` ``` -------------------------------- ### Get Scaling Factor Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/kiss_fft.rs.html Returns the scaling factor applied to the FFT output, which is typically 1.0 / nfft. ```rust #[inline] pub fn scale(&self) -> f32 { self.scale } } ``` -------------------------------- ### Initialize PVQ Search Fast Select (Non-NEON) Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/pvq.rs.html Initializes absolute values and signs for PVQ search when NEON is not available. Calculates the sum of absolute values. ```rust 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 ``` -------------------------------- ### Get Current Frame Length Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/dec_api.rs.html Retrieves the current frame length of the decoder, which is determined by the audio configuration. ```rust pub fn frame_length(&self) -> i32 { self.channel_state[0].frame_length } ``` -------------------------------- ### CeltEncoder::encode_with_start_band Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/celt.rs.html Encodes an audio frame with a specified starting band, allowing for more granular control over the encoding process. ```APIDOC ## CeltEncoder::encode_with_start_band ### Description Encodes a PCM audio frame using the Celt encoder, starting the encoding process from a specific frequency band. ### Method `encode_with_start_band` ### Parameters - **pcm** (`&[f32]`) - Slice of PCM audio samples to encode. - **frame_size** (`usize`) - The number of samples in the frame. - **rc** (`&mut RangeCoder`) - A mutable reference to the RangeCoder for entropy coding. - **start_band** (`usize`) - The frequency band from which to start encoding. ### Request Body This method does not take a request body in the traditional sense; it operates on the provided PCM data. ``` -------------------------------- ### Initialize NLSF Conversion Polynomials Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/nlsf.rs.html Initializes the polynomial coefficients 'p' and 'q' for the a-to-NLSF conversion process. ```rust fn silk_a2nlsf_init(a_q16: &[i32], p: &mut [i32], q: &mut [i32], dd: usize) { p[dd] = 1 << 16; q[dd] = 1 << 16; for k in 0..dd { p[k] = -a_q16[dd - k - 1] - a_q16[dd + k]; q[k] = -a_q16[dd - k - 1] + a_q16[dd + k]; } for k in (1..=dd).rev() { p[k - 1] -= p[k]; q[k - 1] += q[k]; } silk_a2nlsf_trans_poly(p, dd); silk_a2nlsf_trans_poly(q, dd); } ``` -------------------------------- ### Implement Default for NSQDelDecStruct Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/nsq_del_dec/struct.NSQDelDecStruct.html Allows creating a new NSQDelDecStruct with default initial values. This is convenient for setting up the structure before its first use. ```rust impl Default for NSQDelDecStruct ``` -------------------------------- ### Get Scale Factor from KissFftState Source: https://docs.rs/opus-rs/0.1.17/opus_rs/kiss_fft/struct.KissFftState.html Retrieves the scaling factor associated with this KissFftState. This is often used in FFT computations. ```rust pub fn scale(&self) -> f32 ``` -------------------------------- ### Initialize SilkResampler Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/resampler.rs.html Initializes the SilkResampler with input and output sample rates. It sets up internal parameters, determines the resampling mode, and calculates the inverse ratio for resampling. ```rust pub fn init(&mut self, fs_hz_in: i32, fs_hz_out: i32) -> i32 { *self = Self::default(); let in_id = rate_id(fs_hz_in); let out_id = rate_id(fs_hz_out); if in_id > 2 || out_id > 5 { return -1; } self.input_delay = DELAY_MATRIX_DEC[in_id][out_id] as i32; self.fs_in_khz = fs_hz_in / 1000; self.fs_out_khz = fs_hz_out / 1000; self.batch_size = self.fs_in_khz * RESAMPLER_MAX_BATCH_SIZE_MS; if fs_hz_out == fs_hz_in { self.mode = ResamplerMode::Copy; } else if fs_hz_out == fs_hz_in * 2 { self.mode = ResamplerMode::Up2HQ; } else { self.mode = ResamplerMode::IirFir; } let up2x = if self.mode == ResamplerMode::IirFir { 1 } else { 0 }; self.inv_ratio_q16 = ((((fs_hz_in as i64) << (14 + up2x)) / fs_hz_out as i64) << 2) as i32; while silk_smulww(self.inv_ratio_q16, fs_hz_out) < (fs_hz_in << up2x) { self.inv_ratio_q16 += 1; } 0 } ``` -------------------------------- ### Get Gains ID Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/enc_api.rs.html Retrieves the gain index based on the provided indices and number of subframes. Used in gain quantization. ```rust silk_gains_id(&ps_enc.s_cmn.indices.gains_indices, ps_enc.s_cmn.nb_subfr); ``` -------------------------------- ### CeltEncoder Initialization Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/celt.rs.html Provides details on how to initialize a new CeltEncoder instance with a given mode and channel configuration. ```APIDOC ## CeltEncoder::new ### Description Initializes a new `CeltEncoder` instance. ### Method `new` ### Parameters - **mode** (`&'static CeltMode`) - Reference to the Celt mode configuration. - **channels** (`usize`) - The number of audio channels. ### Returns A new `CeltEncoder` instance with initialized internal buffers and state. ``` -------------------------------- ### Laplace Get Frequency 1 Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/range_coder.rs.html Helper function for Laplace encoding/decoding to calculate the frequency of the next symbol based on decay. ```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 } ``` -------------------------------- ### Get Decoder Sample Rate Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/dec_api.rs.html Returns the current sample rate of the decoder in Hz, derived from the internal kHz setting. ```rust pub fn sample_rate(&self) -> i32 { self.channel_state[0].fs_khz * 1000 } ``` -------------------------------- ### OpusDecoder::new Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/lib.rs.html Initializes a new OpusDecoder instance with the specified sampling rate and number of channels. ```APIDOC ## OpusDecoder::new ### Description Initializes a new OpusDecoder instance. It validates the sampling rate and channel count, then sets up the internal CELT and SILK decoders. ### Method `pub fn new(sampling_rate: i32, channels: usize) -> Result` ### Parameters * **sampling_rate** (i32) - The desired sampling rate for the audio output. Must be one of 8000, 12000, 16000, 24000, or 48000 Hz. * **channels** (usize) - The number of audio channels. Must be 1 (mono) or 2 (stereo). ### Response #### Success Response (Ok) Returns an `Ok` variant containing a new `OpusDecoder` instance if initialization is successful. #### Error Response (Err) Returns an `Err` variant with a static string describing the error if the sampling rate or channel count is invalid. ### Request Example ```rust let decoder = OpusDecoder::new(48000, 2); ``` ### Response Example ```rust // On success: // Ok(OpusDecoder { ... }) // On failure: // Err("Invalid sampling rate") // Err("Invalid number of channels") ``` ``` -------------------------------- ### Get Total Bit Count Source: https://docs.rs/opus-rs/0.1.17/opus_rs/range_coder/struct.RangeCoder.html Returns the total number of bits encoded or decoded, matching C's `ec_tell()`. ```rust pub fn tell(&self) -> i32 ``` -------------------------------- ### SilkResampler Initialization and Processing Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/resampler/struct.SilkResampler.html Methods for initializing and processing audio data with the SilkResampler. ```APIDOC ## impl SilkResampler ### pub fn init(&mut self, fs_hz_in: i32, fs_hz_out: i32) -> i32 #### Description Initializes the SilkResampler with the input and output sample rates. #### Parameters - **fs_hz_in** (i32) - Required - The input sample rate in Hz. - **fs_hz_out** (i32) - Required - The output sample rate in Hz. #### Returns - (i32) - An integer indicating the success or failure of the initialization. A non-zero value typically indicates an error. ### pub fn process(&mut self, out: &mut [i16], input: &[i16], in_len: i32) -> i32 #### Description Processes a chunk of audio data, resampling it from the input rate to the output rate. #### Parameters - **out** (&mut [i16]) - Required - A mutable slice to store the resampled output audio data. - **input** (&[i16]) - Required - A slice containing the input audio data to be resampled. - **in_len** (i32) - Required - The number of samples in the input slice. #### Returns - (i32) - The number of samples written to the `out` buffer. A negative value typically indicates an error. ``` -------------------------------- ### Quantization Partition Logic Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/bands.rs.html Handles the partitioning and quantization of audio data based on bit allocation and band splitting. It includes logic for both mid and side channels, with optional lowband processing. ```rust let mut sbits = b_mut - mbits; let mut mbits = mbits; let mut rebalance = ctx.remaining_bits; let mut cm; if mbits >= sbits { if let Some(lb) = lowband { let (lb_mid, lb_side) = lb.split_at_mut(mid); cm = quant_partition( ctx, x_mid, mid, mbits, b_blocks, Some(lb_mid), lm, gain * (sctx.imid as f32 / 32768.0), fill_mut, ); rebalance = mbits - (rebalance - ctx.remaining_bits); if rebalance > (3 << 3) && sctx.itheta != 0 { sbits += rebalance - (3 << 3); } cm |= quant_partition( ctx, x_side, mid, sbits, b_blocks, Some(lb_side), lm, gain * (sctx.iside as f32 / 32768.0), fill_mut >> b_blocks, ) << (b0 >> 1); } else { cm = quant_partition( ctx, x_mid, mid, mbits, b_blocks, None, lm, gain * (sctx.imid as f32 / 32768.0), fill_mut, ); rebalance = mbits - (rebalance - ctx.remaining_bits); if rebalance > (3 << 3) && sctx.itheta != 0 { sbits += rebalance - (3 << 3); } cm |= quant_partition( ctx, x_side, mid, sbits, b_blocks, None, lm, gain * (sctx.iside as f32 / 32768.0), fill_mut >> b_blocks, ) << (b0 >> 1); } } else if let Some(lb) = lowband { let (lb_mid, lb_side) = lb.split_at_mut(mid); cm = quant_partition( ctx, x_side, mid, sbits, b_blocks, Some(lb_side), lm, gain * (sctx.iside as f32 / 32768.0), fill_mut >> b_blocks, ) << (b0 >> 1); rebalance = sbits - (rebalance - ctx.remaining_bits); if rebalance > (3 << 3) && sctx.itheta != 16384 { mbits += rebalance - (3 << 3); } cm |= quant_partition( ctx, x_mid, mid, mbits, b_blocks, Some(lb_mid), lm, gain * (sctx.imid as f32 / 32768.0), fill_mut, ); } else { cm = quant_partition( ctx, x_side, mid, sbits, b_blocks, None, lm, gain * (sctx.iside as f32 / 32768.0), fill_mut >> b_blocks, ) << (b0 >> 1); rebalance = sbits - (rebalance - ctx.remaining_bits); if rebalance > (3 << 3) && sctx.itheta != 16384 { mbits += rebalance - (3 << 3); } cm |= quant_partition( ctx, x_mid, mid, mbits, b_blocks, None, lm, gain * (sctx.imid as f32 / 32768.0), fill_mut, ); } cm ``` -------------------------------- ### Get Fast Bit Count Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/range_coder.rs.html Provides a fast approximation of the bit count by returning the total number of bits accumulated so far. ```rust pub fn tell_fast(&self) -> i32 { self.nbits_total } ``` -------------------------------- ### Implement CloneToUninit for Clone types (Nightly) Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/structs/struct.SideInfoIndices.html An experimental nightly-only API that performs copy-assignment from self to a raw pointer destination. Requires the type to implement Clone. ```rust impl CloneToUninit for T where T: Clone ``` -------------------------------- ### Prepare Input Buffer for Silk Encoding Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/enc_api.rs.html Prepares the input buffer for Silk encoding by copying stereo mid-values and resampler output. ```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]); ``` -------------------------------- ### Define MAX_LOOK_AHEAD Constant Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/define/constant.MAX_LOOK_AHEAD.html This constant represents the maximum look-ahead in samples for SILK mode. It is a fixed value and does not require any special setup. ```rust pub const MAX_LOOK_AHEAD: usize = _; // 112usize ``` -------------------------------- ### Declare BETA_COEF Constant Source: https://docs.rs/opus-rs/0.1.17/opus_rs/quant_bands/constant.BETA_COEF.html This constant is an array of f32 values used in quantization bands. No specific usage examples are provided in the source. ```rust pub const BETA_COEF: [f32; 4]; ``` -------------------------------- ### Test FFT Roundtrip with 120 points Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/kiss_fft.rs.html Verifies the accuracy of FFT and IFFT by transforming a sine wave and checking if the output matches the original input within a tolerance. Requires the KissFftState for initialization. ```rust #[test] fn test_fft_roundtrip_120() { let nfft = 120; let st = KissFftState::new(nfft).unwrap(); let mut fin = vec![KissCpx::default(); nfft]; let mut fout = vec![KissCpx::default(); nfft]; let mut finv = vec![KissCpx::default(); nfft]; for i in 0..nfft { fin[i] = KissCpx::new((2.0 * PI * 3.0 * i as f32 / nfft as f32).sin(), 0.0); } opus_fft(&st, &fin, &mut fout); opus_ifft(&st, &fout, &mut finv); for i in 0..nfft { assert!( cpx_almost_equal(&finv[i], &fin[i], 1e-4), "Roundtrip failed at index {}: got ({}, {}), expected ({}, {})", i, finv[i].r, finv[i].i, fin[i].r, fin[i].i ); } } ``` -------------------------------- ### Implement Default for SideInfoIndices Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/structs/struct.SideInfoIndices.html Allows creating a SideInfoIndices instance with default values. This is often used for initialization or when a sensible starting state is needed. ```rust impl Default for SideInfoIndices Source ``` -------------------------------- ### Prepare Lowband Views Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/bands.rs.html Prepares views for lowband audio data. This function is a precursor to further processing of low-frequency components. ```rust fn prepare_lowband_views( norm: &mut [f32], ``` -------------------------------- ### Get Minimum of Two Integers Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/macros/fn.silk_min_int.html Use this function to find the smaller of two i32 integers. It is part of the opus_rs::silk::macros module. ```rust pub fn silk_min_int(a: i32, b: i32) -> i32 ``` -------------------------------- ### Compute Quantization Noise (compute_qn) Source: https://docs.rs/opus-rs/0.1.17/opus_rs/bands/fn.compute_qn.html Use this function to compute quantization noise. It takes several parameters related to audio band processing and stereo configuration. ```rust pub fn compute_qn( n: usize, b: i32, offset: i32, pulse_cap: i32, stereo: bool, ) -> i32 ``` -------------------------------- ### PVQ Fast Select Logic (Non-NEON) Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/pvq.rs.html Implements the core PVQ fast select logic for non-NEON architectures. It calculates initial values for y, yy, and xy, and adjusts them based on k and sum. ```rust let rcp = (k as f32 + 0.8) / sum; let abs_x_ptr = abs_x.as_ptr(); let y_ptr = y.as_mut_ptr(); unsafe { for i in 0..n { let yi = (*abs_x_ptr.add(i) * rcp) as i32; *y_ptr.add(i) = yi; let yf = yi as f32; yy += yf * yf; xy += yf * *abs_x_ptr.add(i); k -= yi; } } if k > n as i32 + 3 { let tmp = k as f32; unsafe { yy += tmp * tmp + tmp * *y_ptr as f32; *y_ptr += k; } k = 0; } ``` -------------------------------- ### Update Balance Value with Tell Fraction Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/bands.rs.html Updates the balance value by subtracting the tell fraction, which represents a portion of the data. Used when not at the start of a sequence. ```rust let tell = tell_frac_inline!(rc); if i != start { balance_val -= tell; } ``` -------------------------------- ### Create New FFT State Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/kiss_fft.rs.html Constructor for `KissFftState`. It takes the FFT size `nfft`, factorizes it, computes the bit-reversal table, and generates twiddle factors. Returns `None` if the `nfft` 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, }) } ``` -------------------------------- ### Opus Decoder - Decode from Range Coder with Band Range Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/celt.rs.html Decodes audio data from a RangeCoder, specifying both the start and end frequency bands for decoding. ```APIDOC ## POST /decode_from_range_coder_with_band_range ### Description Decodes audio data from a RangeCoder, specifying both the start and end frequency bands. ### Method POST ### Endpoint /decode_from_range_coder_with_band_range ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **rc** (RangeCoder) - Required - The RangeCoder object containing the compressed data. - **total_bits** (i32) - Required - The total number of bits in the compressed data. - **frame_size** (usize) - Required - The size of the audio frame to decode. - **pcm** (f32 array) - Required - A mutable slice to store the decoded PCM data. - **start_band** (usize) - Required - The starting frequency band for decoding. - **end_band** (usize) - Required - The ending frequency band for decoding. ### Request Example ```json { "rc": "range_coder_object_representation", "total_bits": 8192, "frame_size": 1024, "pcm": [], "start_band": 0, "end_band": 60 } ``` ### Response #### Success Response (200) - **usize** - The number of samples decoded. #### Response Example ```json { "decoded_samples": 1024 } ``` ``` -------------------------------- ### Define SILK_TRANSITION_LP_B_Q28 Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/tables.rs.html Defines the SILK_TRANSITION_LP_B_Q28 constant array, likely for low-pass filter transition coefficients in Silk audio processing, with Q28 precision. ```rust pub const SILK_TRANSITION_LP_B_Q28: [[i32; TRANSITION_NB]; TRANSITION_INT_NUM] = [ [250767114, 501534038, 250767114], [209867381, 419732057, 209867381], [170987846, 341967853, 170987846], [131531482, 263046905, 131531482], [89306658, 178584282, 89306658], ]; ``` -------------------------------- ### CeltDecoder::decode_with_start_band Source: https://docs.rs/opus-rs/0.1.17/opus_rs/celt/struct.CeltDecoder.html Decodes a compressed audio frame, starting decoding from a specific frequency band. Useful for controlling the frequency resolution of the decoded audio. ```rust pub fn decode_with_start_band( &mut self, compressed: &[u8], frame_size: usize, pcm: &mut [f32], start_band: usize, ) -> usize ``` -------------------------------- ### Define SILK_TRANSITION_LP_A_Q28 Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/silk/tables.rs.html Defines the SILK_TRANSITION_LP_A_Q28 constant array, likely for low-pass filter transition coefficients in Silk audio processing, with Q28 precision. ```rust pub const SILK_TRANSITION_LP_A_Q28: [[i32; TRANSITION_NA]; TRANSITION_INT_NUM] = [ [506393414, 239854379], [411067935, 169683996], [306733530, 116694253], [185807084, 77959395], [35497197, 57401098], ]; ``` -------------------------------- ### silk_vad_init Function Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/vad/fn.silk_vad_init.html Initializes the SILK VAD (Voice Activity Detection) state. ```APIDOC ## silk_vad_init ### Description Initializes the SILK VAD state. ### Method Rust Function ### Endpoint opus_rs::silk::vad ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **s_vad** (SilkVADState) - Required - A mutable reference to the SilkVADState to be initialized. ### Request Example ```rust let mut vad_state = SilkVADState::new(); // Assuming SilkVADState has a ::new() constructor silk_vad_init(&mut vad_state); ``` ### Response #### Success Response (0) - **Return Value** (i32) - Returns 0 on success. #### Response Example ```rust 0 ``` #### Error Response - **Return Value** (i32) - Returns a negative value on error. Specific error codes are not detailed here. ``` -------------------------------- ### Get Trigonometric Values for MDCT Source: https://docs.rs/opus-rs/0.1.17/src/opus_rs/mdct.rs.html Retrieves a slice of pre-calculated trigonometric values (cosines) and the corresponding FFT size for a given shift. Used internally by the MDCT. ```rust fn get_trig(&self, shift: usize) -> (&[f32], usize) { let mut offset = 0; let mut curr_n = self.n; for _ in 0..shift { offset += curr_n / 2; curr_n >>= 1; } (&self.trig[offset..offset + curr_n / 2], curr_n / 4) } ``` -------------------------------- ### silk_sqrt_approx Function Signature Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/macros/fn.silk_sqrt_approx.html This is the function signature for silk_sqrt_approx, which approximates the square root of an i32 integer. No specific setup or imports are required to use this function signature. ```rust pub fn silk_sqrt_approx(x: i32) -> i32 ``` -------------------------------- ### Initialize SilkResampler Source: https://docs.rs/opus-rs/0.1.17/opus_rs/silk/resampler/struct.SilkResampler.html Initializes the SilkResampler with input and output sample rates. Returns an i32 status code. ```rust pub fn init(&mut self, fs_hz_in: i32, fs_hz_out: i32) -> i32 ```