### Create a new DecoderBuilder Source: https://docs.rs/mousiki/0.2.1/mousiki/silk/decoder/struct.DecoderBuilder.html Instantiates a new DecoderBuilder. This is the starting point for configuring a decoder. ```rust pub const fn new() -> Self ``` -------------------------------- ### Get Samples in Subframe Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/packet/enum.Bandwidth.html Calculates the number of samples in a subframe based on the bandwidth. For example, 40 samples for NB, 60 for MB, and 80 for WB. ```rust pub const fn samples_in_subframe(&self) -> u8 ``` -------------------------------- ### Fixed Quantization and Dequantization (Case 1) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/vq.rs.html Initial example demonstrating fixed quantization and dequantization with `SPREAD_NONE`. It sets up buffers, input data, and expected outputs, then asserts the correctness of the process. ```rust let mut buffer = [0u8; 256]; let mut x = [0, 9459, -9458, 9459, 0, 0, 0, 0, 0, 0]; let expected = [0, 9459, -9458, 9459, 0, 0, 0, 0, 0, 0]; let mask; { let n = x.len(); let mut enc = EcEnc::new(&mut buffer); mask = alg_quant_fixed(&mut x, n, 3, SPREAD_NONE, 5, &mut enc, Q31_ONE, true, 0); enc.enc_done(); } let mut xu = [0i16; 10]; let n = xu.len(); let mut dec = EcDec::new(&mut buffer); let umask = alg_unquant_fixed(&mut xu, n, 3, SPREAD_NONE, 5, &mut dec, Q31_ONE); assert_eq!(mask, 3); assert_eq!(umask, 3); assert_i16_slice("alg_case2_q", &x, &expected); assert_i16_slice("alg_case2_u", &xu, &expected); ``` -------------------------------- ### Initialize and Configure Opus Encoder Source: https://docs.rs/mousiki/0.2.1/src/mousiki/opus_encoder.rs.html Demonstrates how to create an Opus encoder with a specific sample rate, channels, and frame size, and then set its bitrate. This is the initial setup for audio encoding. ```rust let mut encoder = opus_encoder_create(48_000, 2, 2049).expect("encoder init"); opus_encoder_ctl(&mut encoder, OpusEncoderCtlRequest::SetBitrate(64_000)) .expect("set bitrate"); ``` -------------------------------- ### Control CELT Encoder State Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/celt_encoder.rs.html Demonstrates how to update CELT encoder state using `opus_custom_encoder_ctl`. This example shows setting complexity, start band, and end band. ```rust let owned = opus_custom_mode_create(48_000, 960).expect("mode"); let mode = owned.mode(); let mut alloc = CeltEncoderAlloc::new(&mode, 2); let mut encoder = alloc .init_custom_encoder(&mode, 2, 2, 1234) .expect("encoder"); opus_custom_encoder_ctl(&mut encoder, EncoderCtlRequest::SetComplexity(7)).unwrap(); assert_eq!(encoder.complexity, 7); opus_custom_encoder_ctl(&mut encoder, EncoderCtlRequest::SetStartBand(1)).unwrap(); assert_eq!(encoder.start_band, 1); opus_custom_encoder_ctl( &mut encoder, EncoderCtlRequest::SetEndBand(mode.num_ebands as i32), ) .unwrap(); ``` -------------------------------- ### MiniKissFft Initialization and Configuration Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/mini_kfft.rs.html Demonstrates the creation of a `MiniKissFft` instance, specifying the FFT size and whether it's for an inverse transform. It handles twiddle factor generation, either using precomputed values for specific sizes or calculating them dynamically, and factorizes the FFT size for the core algorithm. ```rust pub fn new(nfft: usize, inverse_fft: bool) -> Self { assert!(nfft > 0, "FFT size must be greater than zero"); let twiddles = if nfft == FFT_TWIDDLES_48000_960.len() { if inverse_fft { FFT_TWIDDLES_48000_960 .iter() .map(|c| KissFftCpx::new(c.r, -c.i)) .collect() } else { FFT_TWIDDLES_48000_960.to_vec() } } else { (0..nfft) .map(|i| { let mut phase = -2.0 * PI64 * i as f64 / nfft as f64; if inverse_fft { phase = -phase; } KissFftCpx::new(cos(phase) as f32, sin(phase) as f32) }) .collect() }; let factors = if nfft == 480 { C_FACTORS_480.to_vec() } else { kf_factor(nfft) }; assert!( factors.len() <= 2 * MAXFACTORS, "factor buffer overflow: {} entries", factors.len() ); #[cfg(test)] twiddle_trace::maybe_dump(nfft, &twiddles); Self { nfft, inverse: inverse_fft, factors, twiddles, } } ``` -------------------------------- ### Initialize and Test CELT Decoder Control Requests Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/celt_decoder.rs.html Initializes a CELT decoder and tests various control requests to verify their functionality and error handling. This includes setting and getting complexity, start and end bands, channels, error status, lookahead, pitch, signalling, phase inversion, and the decoder's mode. ```rust #[test] fn decoder_ctl_handles_configuration_requests() { let e_bands = [0, 2, 5]; let alloc_vectors = [0u8; 4]; let log_n = [0i16; 2]; let window = [0.0f32; 4]; let mdct = MdctLookup::new(8, 0); let cache = PulseCacheData::new(vec![0; 6], vec![0; 6], vec![0; 6]); let mode = OpusCustomMode::new_test( 48_000, 4, &e_bands, &alloc_vectors, &log_n, &window, mdct, cache, ); let mut alloc = CeltDecoderAlloc::new(&mode, 2); let mut decoder = alloc .init_decoder(&mode, 2, 2) .expect("decoder initialisation should succeed"); let err = opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetComplexity(11)) .unwrap_err(); assert_eq!(err, CeltDecoderCtlError::InvalidArgument); opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetComplexity(7)).unwrap(); let mut complexity = 0; opus_custom_decoder_ctl( &mut decoder, DecoderCtlRequest::GetComplexity(&mut complexity), ) .unwrap(); assert_eq!(complexity, 7); let max = mode.num_ebands as i32; opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetStartBand(1)).unwrap(); assert_eq!(decoder.start_band, 1); let err = opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetStartBand(max)) .unwrap_err(); assert_eq!(err, CeltDecoderCtlError::InvalidArgument); opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetEndBand(max)).unwrap(); assert_eq!(decoder.end_band, max); let err = opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetEndBand(0)).unwrap_err(); assert_eq!(err, CeltDecoderCtlError::InvalidArgument); let err = opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetChannels(3)).unwrap_err(); assert_eq!(err, CeltDecoderCtlError::InvalidArgument); opus_custom_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetChannels(1)).unwrap(); assert_eq!(decoder.stream_channels, 1); opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetChannels(2)).unwrap(); assert_eq!(decoder.stream_channels, 2); decoder.error = -57; let mut reported_error = 0; opus_custom_decoder_ctl( &mut decoder, DecoderCtlRequest::GetAndClearError(&mut reported_error), ) .unwrap(); assert_eq!(reported_error, -57); assert_eq!(decoder.error, 0); decoder.overlap = 6; decoder.downsample = 2; let mut lookahead = 0; opus_custom_decoder_ctl( &mut decoder, DecoderCtlRequest::GetLookahead(&mut lookahead), ) .unwrap(); assert_eq!(lookahead, 3); decoder.postfilter_period = 321; let mut pitch = 0; opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::GetPitch(&mut pitch)).unwrap(); assert_eq!(pitch, 321); opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::SetSignalling(5)).unwrap(); assert_eq!(decoder.signalling, 5); decoder.rng = 0xDEADBEEF; let mut rng = 0; opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::GetFinalRange(&mut rng)).unwrap(); assert_eq!(rng, 0xDEADBEEF); opus_custom_decoder_ctl( &mut decoder, DecoderCtlRequest::SetPhaseInversionDisabled(true), ) .unwrap(); assert!(decoder.disable_inv); let mut disabled = false; opus_custom_decoder_ctl( &mut decoder, DecoderCtlRequest::GetPhaseInversionDisabled(&mut disabled), ) .unwrap(); assert!(disabled); let mut mode_slot = None; opus_custom_decoder_ctl(&mut decoder, DecoderCtlRequest::GetMode(&mut mode_slot)).unwrap(); let mode_ref = mode_slot.expect("mode reference"); assert!(ptr::eq(mode_ref, &mode)); } ``` -------------------------------- ### Initialize Encoder and Control Parameters Source: https://docs.rs/mousiki/0.2.1/src/mousiki/silk/process_gains_flp.rs.html Sets up the encoder's common parameters and initializes the EncoderControlFlp with specific gain and quality settings. ```rust encoder.common.indices.signal_type = FrameSignalType::Voiced; encoder.common.n_states_delayed_decision = 1; encoder.common.speech_activity_q8 = 128; encoder.common.input_tilt_q15 = 5000; let mut control = EncoderControlFlp::default(); control.gains[0] = 2.0; control.gains[1] = 3.0; control.lt_pred_cod_gain = 0.5; control.res_nrg[0] = 0.0; control.res_nrg[1] = 0.0; control.input_quality = 0.4; control.coding_quality = 0.2; ``` -------------------------------- ### Start Timer Interval (No Feature) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/silk/debug.rs.html A no-operation function for starting timer intervals when the 'silk_tic_toc' feature is not enabled. ```rust pub fn tic(_tag: &str) {} ``` -------------------------------- ### Initialize Bandwidth Caps (Fixed-Point) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/celt.rs.html Calculates and fills the `cap` slice with per-band dynamic allocation caps. This function mirrors the behavior of `init_caps()` from `celt/celt.c`. ```rust pub(crate) fn init_caps(mode: &OpusCustomMode<'_>, cap: &mut [i32], lm: usize, channels: usize) { let nb_ebands = mode.num_ebands; assert_eq!(cap.len(), nb_ebands, "cap slice must cover every band"); assert!(channels > 0, "channel count must be positive"); assert!( mode.e_bands.len() > nb_ebands, "mode does not expose the terminating band edge" ); let stride = 2 * lm + (channels - 1); let base_offset = nb_ebands * stride; let caps_table = &mode.cache.caps; assert!( base_offset + nb_ebands <= caps_table.len(), "pulse cache caps table is too small" ); for (band_index, cap_value) in cap.iter_mut().enumerate() { let band_width = i32::from(mode.e_bands[band_index + 1] - mode.e_bands[band_index]); let n = band_width << lm; let cached_cap = i32::from(caps_table[base_offset + band_index]) + 64; let scaled = cached_cap * (channels as i32) * n; *cap_value = scaled >> 2; } } ``` -------------------------------- ### Start Timer Interval (Tic Toc Feature) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/silk/debug.rs.html Records the start time and depth for a given tag when the 'silk_tic_toc' feature is enabled. ```rust pub fn tic(tag: &str) { let start = now(); let mut state = TIMER_STATE.lock(); let id = state.get_or_insert(tag); state.depth[id] = state.depth_ctr; state.start[id] = start; state.depth_ctr += 1; } ``` -------------------------------- ### Calculate Laplace Start Frequency Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/laplace.rs.html Calculates the starting frequency for Laplace distribution encoding based on decay. This is used to determine the initial parameters for the encoding process. ```Rust fn laplace_start_freq(decay: u32) -> u32 { let ft = TOTAL_FREQ - LAPLACE_MINP * (2 * LAPLACE_NMIN + 1); let numerator = u64::from(ft) * u64::from(16384 - decay); let denominator = u64::from(16384 + decay); (numerator / denominator) as u32 + LAPLACE_MINP } ``` -------------------------------- ### SSE4.1 Entry Point for Delayed-Decision Noise-Shaping Quantizer Source: https://docs.rs/mousiki/0.2.1/src/mousiki/silk/nsq_del_dec_sse4_1.rs.html This function serves as the SSE4.1 entry point for the delayed-decision noise-shaping quantizer. It mirrors the C implementation's entry point but currently delegates to the scalar implementation until SIMD dispatch is enabled. ```rust use crate::silk::decode_indices::SideInfoIndices; use crate::silk::encoder::state::{EncoderStateCommon, NoiseShapingQuantizerState}; use crate::silk::nsq_del_dec::silk_nsq_del_dec; /// Mirrors `silk_NSQ_del_dec_sse4_1` while deferring to the scalar /// implementation until SIMD dispatch is enabled. #[allow(clippy::too_many_arguments)] #[inline] pub fn silk_nsq_del_dec_sse4_1( encoder: &EncoderStateCommon, nsq: &mut NoiseShapingQuantizerState, indices: &mut SideInfoIndices, x16: &[i16], pulses: &mut [i8], pred_coef_q12: &[i16], ltp_coef_q14: &[i16], ar_q13: &[i16], harm_shape_gain_q14: &[i32], tilt_q14: &[i32], lf_shp_q14: &[i32], gains_q16: &[i32], pitch_l: &[i32], lambda_q10: i32, ltp_scale_q14: i32, ) { silk_nsq_del_dec( encoder, nsq, indices, x16, pulses, pred_coef_q12, ltp_coef_q14, ar_q13, harm_shape_gain_q14, tilt_q14, lf_shp_q14, gains_q16, pitch_l, lambda_q10, ltp_scale_q14, ) } ``` -------------------------------- ### Get Encoder Size Source: https://docs.rs/mousiki/0.2.1/mousiki/silk/get_encoder_size/fn.get_encoder_size.html Call this function to get the number of bytes required to hold the current Encoder state. The result is written into the provided mutable usize reference. ```rust pub fn get_encoder_size(size_bytes: &mut usize) -> Result<(), SilkError> ``` -------------------------------- ### Select PVQ Candidate (Fixed-Point) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/vq.rs.html Compares a candidate PVQ candidate against the current best using fixed-point arithmetic, updating if the candidate offers a better ratio. Essential for performance-critical audio paths. ```rust fn select_pvq_candidate_fixed( best_id: &mut usize, best_den: &mut FixedOpusVal16, best_num: &mut OpusInt32, candidate_id: usize, candidate_den: FixedOpusVal16, candidate_num: FixedOpusVal16, ) { let left = mult16_16(*best_den, candidate_num); let right = i32::from(candidate_den).wrapping_mul(*best_num); if left > right { *best_id = candidate_id; *best_den = candidate_den; *best_num = i32::from(candidate_num); } } ``` -------------------------------- ### CELT Encoder Usage Example Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/celt_encoder.rs.html Example of using the opus_encode function with a CELT encoder. Ensure the encoder is properly initialized and the input PCM data is available. The function returns the encoded packet. ```rust let _ = crate::opus_encoder::opus_encode(&mut encoder, &input_pcm, 960, &mut packet) .expect("opus_encode"); ``` -------------------------------- ### Mini KissFft Tracing Configuration Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/mini_kfft.rs.html Sets up configuration for tracing FFT operations, allowing for detailed debugging of specific frames, stages, or calls. This is useful for analyzing FFT performance and correctness. ```rust pub(crate) struct TraceConfig { frame: Option, stage: Option, want_bits: bool, start: usize, count: usize, detail: bool, } static TRACE_CONFIG: OnceLock> = OnceLock::new(); static FRAME_INDEX: AtomicUsize = AtomicUsize::new(usize::MAX); static CALL_INDEX: AtomicUsize = AtomicUsize::new(usize::MAX); static CHANNEL_INDEX: AtomicUsize = AtomicUsize::new(usize::MAX); static BLOCK_INDEX: AtomicUsize = AtomicUsize::new(usize::MAX); static TAG_INDEX: AtomicUsize = AtomicUsize::new(0); pub(crate) fn set_mdct_context( frame: usize, call: usize, channel: usize, block: usize, tag: usize, ) { FRAME_INDEX.store(frame, Ordering::Relaxed); CALL_INDEX.store(call, Ordering::Relaxed); CHANNEL_INDEX.store(channel, Ordering::Relaxed); BLOCK_INDEX.store(block, Ordering::Relaxed); } ``` -------------------------------- ### Select Silk VAD Get SA Q8 Implementation Source: https://docs.rs/mousiki/0.2.1/src/mousiki/silk/x86_silk_map.rs.html Selects the appropriate Silk VAD 'get SA Q8' implementation function based on the provided architecture. Uses the `dispatch_index` helper function. ```rust pub fn select_vad_get_sa_q8_impl(arch: i32) -> SilkVadGetSaQ8Impl { SILK_VAD_GETSA_Q8_IMPL[dispatch_index(arch)] } ``` -------------------------------- ### Fixed Quantization and Dequantization (Case 5) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/vq.rs.html Illustrates fixed quantization and dequantization with `SPREAD_LIGHT`. Verifies the results of quantization and dequantization against predefined expected values. ```rust let mut buffer = [0u8; 256]; let mut x = [ 5000, -4000, 3000, -2000, 1000, -500, 250, -125, 6000, -5000, 4000, -3000, 2000, -1000, 500, -250, ]; let expected = [ 9376, 1011, 108, -501, -51, -57, 507, 28, 10390, -8309, -901, -611, 449, -5, 538, -483, ]; let mask; { let n = x.len(); let mut enc = EcEnc::new(&mut buffer); mask = alg_quant_fixed(&mut x, n, 3, SPREAD_LIGHT, 2, &mut enc, Q31_ONE, true, 0); enc.enc_done(); } let mut xu = [0i16; 16]; let n = xu.len(); let mut dec = EcDec::new(&mut buffer); let umask = alg_unquant_fixed(&mut xu, n, 3, SPREAD_LIGHT, 2, &mut dec, Q31_ONE); assert_eq!(mask, 3); assert_eq!(umask, 3); assert_i16_slice("alg_case5_q", &x, &expected); assert_i16_slice("alg_case5_u", &xu, &expected); ``` -------------------------------- ### Initialize Silk VAD Get SA Q8 Dispatch Table Source: https://docs.rs/mousiki/0.2.1/src/mousiki/silk/x86_silk_map.rs.html Initializes the dispatch table for Silk VAD 'get SA Q8' implementations, currently mapping all entries to the SSE4.1 optimized version. ```rust pub const SILK_VAD_GETSA_Q8_IMPL: [SilkVadGetSaQ8Impl; ARCH_IMPL_COUNT] = [silk_vad_get_sa_q8_sse4_1; ARCH_IMPL_COUNT]; ``` -------------------------------- ### Stereo Band Quantization Initialization Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/bands.rs.html Initializes stereo band quantization, handling cases where one channel has minimal energy by copying the other. Includes computation of stereo split parameters. ```rust if left < MIN_STEREO_ENERGY || right < MIN_STEREO_ENERGY { if left > right { y[..n].copy_from_slice(&x[..n]); } else { x[..n].copy_from_slice(&y[..n]); } } compute_theta( ctx, &mut split, x, y, n, &mut b, b_blocks, b_blocks, lm, true, &mut fill_local, coder, ); ``` -------------------------------- ### type_id Source: https://docs.rs/mousiki/0.2.1/mousiki/silk/check_control_input/struct.EncControl.html Gets the TypeId of the EncControl instance. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Parameters - `&self`: An immutable reference to the EncControl instance. ### Returns - `TypeId`: The type identifier of the instance. ``` -------------------------------- ### Mono Decoder Setup and Spectral Decoding Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/celt_decoder.rs.html Initializes mono decoders (TF, native, bridge), prepares a frame, and decodes spectral data for comparison. This snippet is used for testing decoder consistency. ```rust let first_packet = parse_hex_packet(mono_prime_packets[0]); let mut decoder_tf = opus_custom_decoder_create(&mode, 1).expect("tf decoder creation should succeed"); let mut decoder_native = opus_custom_decoder_create(&mode, 1) .expect("native decoder creation should succeed"); let mut decoder_bridge = opus_custom_decoder_create(&mode, 1) .expect("bridge decoder creation should succeed"); let _tf_frame = prepare_frame(&mut decoder_tf, &first_packet, POSTFILTER_FRAME_SIZE, None) .expect("frame preparation should succeed"); crate::test_trace::trace_println!( "frame0 tf_res_first4={:?}", &decoder_tf.decode_tf_res[..4.min(decoder_tf.decode_tf_res.len())] ); let (band0_n, band0_q, band0_index, band0_total, band0_pulses, band0_mask) = debug_first_band_pulses(&mut decoder_native, &first_packet); crate::test_trace::trace_println!( "band0 pulses n={} q={} index={} total={} mask=0x{:02x} pulses={:?}", band0_n, band0_q, band0_index, band0_total, band0_mask, band0_pulses ); let (native_spectrum, native_masks) = decode_packet_band_spectrum(&mut decoder_native, &first_packet, true); let (bridge_spectrum, bridge_masks) = decode_packet_band_spectrum(&mut decoder_bridge, &first_packet, false); let first_diff = native_spectrum .iter() .zip(bridge_spectrum.iter()) .position(|(lhs, rhs)| lhs != rhs); crate::test_trace::trace_println!( "bandcmp frame0 native=0x{:08x} bridge=0x{:08x} masks_native=0x{:08x} masks_bridge=0x{:08x} first_diff={:?}", fnv1a_pcm_le(&native_spectrum), fnv1a_pcm_le(&bridge_spectrum), fnv1a_bytes(&native_masks), fnv1a_bytes(&bridge_masks), first_diff ); crate::test_trace::trace_println!( "bandcmp frame0 masks_native_full={:?}", native_masks ); let lm_dbg = (POSTFILTER_FRAME_SIZE / mode.short_mdct_size).ilog2() as usize; for band_hash in 0..mode.num_ebands { let band_start = (mode.e_bands[band_hash] as usize) << lm_dbg; let band_end = (mode.e_bands[band_hash + 1] as usize) << lm_dbg; let native_hash = fnv1a_pcm_le(&native_spectrum[band_start..band_end]); crate::test_trace::trace_println!( "bandcmp frame0 native_band_hash[{}]=0x{:08x}", band_hash, native_hash ); } if let Some(idx) = first_diff { let lm_dbg = (POSTFILTER_FRAME_SIZE / mode.short_mdct_size).ilog2() as usize; let mut band_idx = 0usize; while band_idx + 1 < mode.num_ebands && ((mode.e_bands[band_idx + 1] as usize) << lm_dbg) <= idx { band_idx += 1; } let band_start = (mode.e_bands[band_idx] as usize) << lm_dbg; crate::test_trace::trace_println!( "bandcmp frame0 coeff[{idx}] band={} band_off={} native={} bridge={}", band_idx, idx - band_start, native_spectrum[idx], bridge_spectrum[idx] ); } ``` -------------------------------- ### mapping_matrix_get_size Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/mapping_matrix/index.html Gets the size of the mapping matrix. ```APIDOC ## mapping_matrix_get_size ### Description Gets the size of the mapping matrix. ### Function Signature `fn mapping_matrix_get_size(matrix: &MappingMatrix) -> usize` ### Parameters * `matrix` (&MappingMatrix) - A reference to the MappingMatrix whose size is to be determined. ### Returns * `usize` - The size of the mapping matrix in bytes. ``` -------------------------------- ### Configure CELT Encoder Settings Source: https://docs.rs/mousiki/0.2.1/src/mousiki/opus_encoder.rs.html Sets the start band and VBR for the CELT encoder. Error handling is included for configuration failures. ```rust opus_custom_encoder_ctl( encoder.celt.encoder(), CeltEncoderCtlRequest::SetStartBand(17), ) .map_err(|_| OpusEncodeError::InternalError)?; opus_custom_encoder_ctl( encoder.celt.encoder(), CeltEncoderCtlRequest::SetVbr(encoder.use_vbr), ) .map_err(|_| OpusEncodeError::InternalError)? ``` -------------------------------- ### OpusRepacketizer::opus_repacketizer_get_size Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/repacketizer/struct.OpusRepacketizer.html Gets the required size for an OpusRepacketizer. ```APIDOC ## OpusRepacketizer::opus_repacketizer_get_size ### Description Returns the size in bytes required to store an OpusRepacketizer. ### Returns - `usize`: The size of the OpusRepacketizer in bytes. ``` -------------------------------- ### Quantization and Unquantization with Aggressive Spread Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/vq.rs.html Illustrates quantizing and unquantizing audio samples using `alg_quant_fixed` and `alg_unquant_fixed` with an aggressive spread setting. This is suitable for scenarios where higher compression is desired, potentially at the cost of some fidelity. ```rust { let n = x.len(); let mut enc = EcEnc::new(&mut buffer); mask = alg_quant_fixed( &mut x, n, 3, SPREAD_AGGRESSIVE, 2, &mut enc, 1_073_741_824, true, 0, ); enc.enc_done(); } let mut xu = [0i16; 16]; let n = xu.len(); let mut dec = EcDec::new(&mut buffer); let umask = alg_unquant_fixed(&mut xu, n, 3, SPREAD_AGGRESSIVE, 2, &mut dec, 1_073_741_824); assert_eq!(mask, 1); assert_eq!(umask, 1); assert_i16_slice("alg_case6_q", &x, &expected); assert_i16_slice("alg_case6_u", &xu, &expected); ``` -------------------------------- ### Begin Frame for Tracing Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/rate.rs.html Initiates tracing for a new frame if tracing is enabled and configured. Increments the global frame index. ```rust pub(crate) fn begin_frame() -> Option { if config().is_some() { let frame = FRAME_INDEX.fetch_add(1, Ordering::Relaxed); CURRENT_FRAME.store(frame as isize, Ordering::Relaxed); Some(frame) } else { CURRENT_FRAME.store(-1, Ordering::Relaxed); None } } ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/dred/struct.OpusDred.html Gets the TypeId of the OpusDred instance. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### OpusEncoder::complexity Source: https://docs.rs/mousiki/0.2.1/src/mousiki/codec.rs.html Gets the current encoding complexity level. ```APIDOC ## OpusEncoder::complexity ### Description Gets the current encoding complexity level. ### Method `complexity` ### Signature `pub fn complexity(&mut self) -> Result` ### Returns - `Result`: On success, returns the current complexity level. On failure, returns an `OpusEncoderCtlError`. ### Errors - `OpusEncoderCtlError`: Indicates an error during the control operation. ``` -------------------------------- ### Create Default BinConfig for FFT Tracing in Rust Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/kiss_fft.rs.html Provides a default BinConfig instance with a predefined set of bins (1 and 61) to be traced. This is used when no specific bin configuration is provided. ```Rust fn default_bins() -> BinConfig { let mut bins = Vec::new(); bins.push(1); bins.push(61); BinConfig { bins, all_bins: false, } } ``` -------------------------------- ### Naive FFT Implementation Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/mini_kfft.rs.html A straightforward, unoptimized implementation of the Fast Fourier Transform for complex numbers. Useful as a reference for testing more optimized FFT algorithms. ```rust fn naive_fft(input: &[KissFftCpx]) -> Vec { let n = input.len(); let mut out = Vec::with_capacity(n); for k in 0..n { let mut sum = KissFftCpx::default(); for (n_index, sample) in input.iter().enumerate() { let angle = -2.0 * PI * (k * n_index) as f32 / n as f32; let tw = KissFftCpx::new(cosf(angle), sinf(angle)); sum = c_add(sum, c_mul(*sample, tw)); } out.push(sum); } out } ``` -------------------------------- ### OpusEncoder::bitrate Source: https://docs.rs/mousiki/0.2.1/src/mousiki/codec.rs.html Gets the current target bitrate of the Opus encoder. ```APIDOC ## OpusEncoder::bitrate ### Description Gets the current target bitrate of the Opus encoder. ### Method `bitrate` ### Signature `pub fn bitrate(&mut self) -> Result` ### Returns - `Result`: On success, returns the current `Bitrate`. On failure, returns an `OpusEncoderCtlError`. ### Errors - `OpusEncoderCtlError`: Indicates an error during the control operation. ``` -------------------------------- ### Get Decoder Complexity Source: https://docs.rs/mousiki/0.2.1/mousiki/struct.Decoder.html Retrieves the current complexity setting of the decoder. ```rust pub fn complexity(&mut self) -> Result ``` -------------------------------- ### Initialize and Use Silk Resampler Source: https://docs.rs/mousiki/0.2.1/src/mousiki/silk/control_codec.rs.html Initializes a Silk resampler and processes audio data. Ensure the resampler is correctly initialized with source and target sample rates before use. The output buffer size must match the expected number of samples. ```rust let mut temp_resampler = ResamplerState::default(); temp_resampler .silk_resampler_init(current_fs_khz * 1000, api_fs_hz, false) .map_err(map_resampler_error)?; let api_buf_samples = buf_length_ms * (api_fs_hz / 1000) as usize; let mut api_buffer = vec![0i16; api_buf_samples]; let produced = silk_resampler( &mut temp_resampler, &mut api_buffer, &encoder.x_buf[..old_buf_samples], ); debug_assert_eq!(produced, api_buf_samples); ``` ```rust let new_buf_samples = buf_length_ms * fs_khz as usize; encoder .resampler_state .silk_resampler_init(api_fs_hz, fs_khz * 1000, true) .map_err(map_resampler_error)?; if new_buf_samples > encoder.x_buf.len() { return Err(SilkError::EncInternalError); } let produced = silk_resampler( &mut encoder.resampler_state, &mut encoder.x_buf[..new_buf_samples], &api_buffer, ); debug_assert_eq!(produced, new_buf_samples); ``` -------------------------------- ### MiniKissFftr Initialization Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/mini_kfft.rs.html Initializes a MiniKissFftr for real FFT processing. Requires an even FFT length and optionally configures inverse FFT. Precomputes twiddle factors. ```rust pub fn new(nfft: usize, inverse_fft: bool) -> Self { assert!(nfft.is_multiple_of(2), "Real FFT requires an even length"); let ncfft = nfft / 2; let substate = MiniKissFft::new(ncfft, inverse_fft); let pack_buffer = vec![KissFftCpx::default(); ncfft]; let tmpbuf = vec![KissFftCpx::default(); ncfft]; let super_twiddles = (0..ncfft / 2) .map(|i| { let mut phase = -PI64 * ((i + 1) as f64 / ncfft as f64 + 0.5); if inverse_fft { phase = -phase; } KissFftCpx::new(cos(phase) as f32, sin(phase) as f32) }) .collect(); Self { substate, pack_buffer, tmpbuf, super_twiddles, } } ``` -------------------------------- ### OpusRepacketizer::opus_repacketizer_get_nb_frames Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/repacketizer/struct.OpusRepacketizer.html Gets the number of frames currently stored in the repacketizer. ```APIDOC ## OpusRepacketizer::opus_repacketizer_get_nb_frames ### Description Retrieves the total number of Opus frames that have been added to the repacketizer and are ready to be output. ### Parameters - `&self`: An immutable reference to the OpusRepacketizer instance. ### Returns - `usize`: The number of frames currently stored. ``` -------------------------------- ### Get Channel Layout Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/opus_multistream/struct.OpusMultistreamDecoder.html Retrieves the channel layout associated with the OpusMultistreamDecoder. ```rust pub fn layout(&self) -> &ChannelLayout ``` -------------------------------- ### Fixed Quantization and Dequantization (Case 2) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/vq.rs.html Example of fixed quantization and dequantization with `SPREAD_NONE`. Verifies the quantized and dequantized values against expected results. ```rust let mut buffer = [0u8; 256]; let mut x = [8000, -4000, 2000, -1000]; let expected = [11585, -11584, 0, 0]; let mask; { let n = x.len(); let mut enc = EcEnc::new(&mut buffer); mask = alg_quant_fixed(&mut x, n, 2, SPREAD_NORMAL, 1, &mut enc, Q31_ONE, true, 0); enc.enc_done(); } let mut xu = [0i16; 4]; let n = xu.len(); let mut dec = EcDec::new(&mut buffer); let umask = alg_unquant_fixed(&mut xu, n, 2, SPREAD_NORMAL, 1, &mut dec, Q31_ONE); assert_eq!(mask, 1); assert_eq!(umask, 1); assert_i16_slice("alg_case3_q", &x, &expected); assert_i16_slice("alg_case3_u", &xu, &expected); ``` -------------------------------- ### Begin CELT Frame Tracing Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/celt_encoder.rs.html Initiates tracing for a new frame if CELT tracing is enabled. Returns the frame index if tracing is active. ```rust pub(crate) fn begin_frame() -> Option { if config().is_some() { let idx = FRAME_INDEX.fetch_add(1, Ordering::Relaxed); CURRENT_FRAME.store(idx as isize, Ordering::Relaxed); Some(idx) } else { CURRENT_FRAME.store(-1, Ordering::Relaxed); None } } ``` -------------------------------- ### opus_encoder_ctl Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/opus_encoder/index.html Controls the Opus encoder by setting or getting various parameters. ```APIDOC ## opus_encoder_ctl ### Description Controls the Opus encoder by setting or getting various parameters. ### Function Signature `opus_encoder_ctl(encoder: *mut OpusEncoder, request: OpusEncoderCtlRequest, value: *mut c_void) -> OpusEncoderCtlError` ### Parameters #### Path Parameters - `encoder` (*mut OpusEncoder) - Required - A mutable pointer to the OpusEncoder instance. - `request` (OpusEncoderCtlRequest) - Required - The control request to perform (e.g., GET_BITRATE, SET_BITRATE). - `value` (*mut c_void) - Required - A pointer to the value associated with the request (can be input or output depending on the request). ### Return Value - `OpusEncoderCtlError` - An error code indicating the success or failure of the operation. ``` -------------------------------- ### PVQ Search Initialization (Fixed-Point) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/vq.rs.html Initializes buffers and variables for the fixed-point PVQ search. It normalizes input coefficients and sets initial pulse counts and reconstructed values. ```rust let mut y = vec![0i16; n]; let mut signx = vec![0i32; n]; for j in 0..n { let value = x[j]; signx[j] = i32::from(value < 0); x[j] = if value < 0 { value.wrapping_neg() } else { value }; pulses[j] = 0; y[j] = 0; } let mut xy: i32 = 0; let mut yy: i16 = 0; let mut pulses_left = k; ``` -------------------------------- ### Get Prediction Disabled Source: https://docs.rs/mousiki/0.2.1/src/mousiki/codec.rs.html Retrieves the current status of prediction for the Opus encoder. ```rust pub fn prediction_disabled(&mut self) -> Result { let mut value = false; opus_encoder_ctl( &mut self.inner, OpusEncoderCtlRequest::GetPredictionDisabled(&mut value), )?; Ok(value) } ``` -------------------------------- ### OpusEncoder::signal Source: https://docs.rs/mousiki/0.2.1/src/mousiki/codec.rs.html Gets the current signal type setting of the Opus encoder. ```APIDOC ## OpusEncoder::signal ### Description Gets the current signal type setting of the Opus encoder. ### Method `signal` ### Signature `pub fn signal(&mut self) -> Result` ### Returns - `Result`: On success, returns the current `Signal` type. On failure, returns an `OpusEncoderCtlError`. ### Errors - `OpusEncoderCtlError`: Indicates an error during the control operation. - `OpusEncoderCtlError::InternalError`: If the signal type cannot be determined from the internal Opus state. ``` -------------------------------- ### Dynamic Allocation Analysis Initialization Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/celt_encoder.rs.html Initializes arrays for dynamic allocation analysis, including offsets, importance, and spread weights. Sets up follower and noise floor calculations. ```rust fn dynalloc_analysis( band_log_e: &[CeltGlog], band_log_e2: &[CeltGlog], old_band_e: &[CeltGlog], nb_ebands: usize, start: usize, end: usize, channels: usize, offsets: &mut [i32], lsb_depth: i32, log_n: &[i16], is_transient: bool, vbr: bool, constrained_vbr: bool, e_bands: &[i16], lm: i32, effective_bytes: i32, tot_boost: &mut i32, lfe: bool, surround_dynalloc: &mut [CeltGlog], analysis: &AnalysisInfo, importance: &mut [i32], spread_weight: &mut [i32], tone_freq: OpusVal16, toneishness: OpusVal32, ) -> CeltGlog { debug_assert!(channels <= MAX_CHANNELS); debug_assert!(band_log_e.len() >= channels * nb_ebands); debug_assert!(band_log_e2.len() >= channels * nb_ebands); debug_assert!(old_band_e.len() >= channels * nb_ebands); debug_assert!(offsets.len() >= nb_ebands); debug_assert!(importance.len() >= nb_ebands); debug_assert!(spread_weight.len() >= nb_ebands); debug_assert!(log_n.len() >= end); debug_assert!(e_bands.len() > end); debug_assert!(surround_dynalloc.len() >= end); offsets.iter_mut().for_each(|value| *value = 0); importance.iter_mut().for_each(|value| *value = 0); spread_weight.iter_mut().for_each(|value| *value = 0); let mut follower = vec![0.0f32; channels * nb_ebands]; let mut noise_floor = vec![0.0f32; nb_ebands]; let mut band_log_e3 = vec![0.0f32; nb_ebands]; let mut max_depth = -31.9f32; #[cfg(test)] let mut max_band = 0usize; #[cfg(test)] let mut max_channel = 0usize; #[cfg(test)] let mut max_band_log_e = 0.0f32; #[cfg(test)] let mut max_noise_floor = 0.0f32; #[cfg(test)] let mut max_depth_val = max_depth; let depth_shift = (9 - lsb_depth) as f32; for i in 0..end { let log_n_val = f32::from(log_n[i]); let mean = E_MEANS .get(i) .copied() .unwrap_or_else(|| *E_MEANS.last().expect("non-empty e_means")); let index = (i + 5) as f32; noise_floor[i] = 0.0625 * log_n_val + 0.5 + depth_shift - mean + 0.0062 * index * index; } for c in 0..channels { let base = c * nb_ebands; for i in 0..end { let depth = band_log_e[base + i] - noise_floor[i]; if depth > max_depth { max_depth = depth; #[cfg(test)] { max_band = i; ``` -------------------------------- ### Get Decoder Gain Source: https://docs.rs/mousiki/0.2.1/mousiki/struct.Decoder.html Retrieves the current output gain setting of the decoder. ```rust pub fn gain(&mut self) -> Result ``` -------------------------------- ### Apply Decode Gain (Fixed Point) Source: https://docs.rs/mousiki/0.2.1/src/mousiki/opus_decoder.rs.html Applies decode gain to PCM data in a fixed-point build. This example demonstrates the gain scaling without soft clipping. ```rust let mut decoder = opus_decoder_create(48_000, 1).expect("decoder should initialise"); decoder.decode_gain = 128; // +0.5 dB. let mut pcm: [OpusRes; 1] = [0.5]; decoder.apply_decode_gain_and_soft_clip(&mut pcm, 1, false); let gain = celt_exp2(super::DECODE_GAIN_SCALE * 128.0); assert!((pcm[0] - 0.5 * gain).abs() < 1e-6); ``` -------------------------------- ### Get Decoder Channels Source: https://docs.rs/mousiki/0.2.1/mousiki/struct.Decoder.html Returns the number of channels configured for this decoder instance. ```rust pub const fn channels(&self) -> Channels ``` -------------------------------- ### Fixed-Point Mode Setup Source: https://docs.rs/mousiki/0.2.1/src/mousiki/celt/quant_bands.rs.html Sets up a custom Opus mode for fixed-point calculations. Used in tests to ensure consistent behavior. ```rust #[cfg(feature = "fixed_point")] fn fixed_mode<'a>( e_bands: &'a [i16], log_n: &'a [i16], alloc_vectors: &'a [u8], window: &'a [f32], ) -> OpusCustomMode<'a> { let mdct = MdctLookup::new(4, 0); OpusCustomMode::new_test( 48_000, 0, e_bands, alloc_vectors, log_n, window, mdct, PulseCacheData::default(), ) } ``` -------------------------------- ### Get Audio Bandwidth Value Source: https://docs.rs/mousiki/0.2.1/mousiki/c_style_api/packet/enum.Bandwidth.html Retrieves the audio bandwidth as a u16 value. ```rust pub const fn audio_band_width(&self) -> u16 ```