//! `silk/enc_API.c`, `silk/init_encoder.c`, `silk/control_codec.c`, `silk/control_SNR.c`, //! `silk/control_audio_bandwidth.c`, `silk/check_control_input.c`. use super::encode::{ TRANSITION_FRAMES, encode_do_vad, encode_frame, encode_indices, encode_pulses, hp_variable_cutoff, }; use super::resampler::SilkResampler; use super::stereo::{StereoEncState, stereo_encode_mid_only, stereo_encode_pred, stereo_lr_to_ms}; use super::vad::vad_init; use super::*; use crate::range::RangeEncoder; use crate::silk_tables::{LBRR_FLAGS_2_ICDF, LBRR_FLAGS_3_ICDF, QUANTIZATION_OFFSETS_Q10}; use crate::silk_fix::{lin2log, rshift_round, sat16, smlawb, smulwb}; macro_rules! fix_const { ($c:expr, $q:expr) => { (($c) * ((1i64 << $q) as f64) + 0.5) as i32 }; } const BITRESERVOIR_DECAY_TIME_MS: i32 = 500; const SPEECH_ACT_THR_SWITCH_Q8: i32 = fix_const!(0.05, 8); const SPEECH_ACT_SLOPE_Q24: i32 = fix_const!((1.0 - 0.05) / 5000.0, 24); const WARPING_Q16_PER_FS_KHZ: i32 = fix_const!(0.015, 16); const LBRR_LOSS_SLOPE_Q16: i32 = fix_const!(0.2, 16); /// `silk_EncControlStruct`. #[derive(Clone, Debug, Default)] pub(crate) struct EncControl { pub(crate) n_channels_api: usize, pub(crate) n_channels_internal: usize, pub(crate) api_sample_rate: i32, pub(crate) max_internal_sample_rate: i32, pub(crate) min_internal_sample_rate: i32, pub(crate) desired_internal_sample_rate: i32, pub(crate) payload_size_ms: usize, pub(crate) bit_rate: i32, pub(crate) packet_loss_percentage: i32, pub(crate) complexity: i32, pub(crate) use_in_band_fec: bool, pub(crate) lbrr_coded: bool, pub(crate) use_dtx: bool, pub(crate) use_cbr: bool, pub(crate) max_bits: i32, pub(crate) to_mono: bool, pub(crate) opus_can_switch: bool, pub(crate) reduced_dependency: bool, pub(crate) internal_sample_rate: i32, pub(crate) allow_bandwidth_switch: bool, pub(crate) in_wb_mode_without_variable_lp: bool, pub(crate) stereo_width_q14: i32, pub(crate) switch_ready: bool, pub(crate) signal_type: i32, pub(crate) offset: i32, } /// `silk_encoder` (two channel states and their API resamplers). #[derive(Clone, Debug)] pub(crate) struct SilkEnc { pub(crate) s_stereo: StereoEncState, pub(crate) n_bits_used_lbrr: i32, pub(crate) n_bits_exceeded: i32, pub(crate) n_channels_api: usize, pub(crate) n_channels_internal: usize, pub(crate) n_prev_channels_internal: usize, pub(crate) time_since_switch_allowed_ms: i32, pub(crate) allow_bandwidth_switch: bool, pub(crate) prev_decode_only_middle: bool, pub(crate) state_fxx: [Box; 2], pub(crate) resampler: [Option>; 2], } const TARGET_RATE_NB_21: [u8; 107] = [ 0, 15, 39, 52, 61, 68, 74, 79, 84, 88, 92, 95, 99, 102, 105, 108, 111, 114, 117, 119, 122, 124, 126, 129, 131, 133, 135, 137, 139, 142, 143, 145, 147, 149, 151, 153, 155, 157, 158, 160, 162, 163, 165, 167, 168, 170, 171, 173, 174, 176, 177, 179, 180, 182, 183, 185, 186, 187, 189, 190, 192, 193, 194, 196, 197, 199, 200, 201, 203, 204, 205, 207, 208, 209, 211, 212, 213, 215, 216, 217, 219, 220, 221, 223, 224, 225, 227, 228, 230, 231, 232, 234, 235, 236, 238, 239, 241, 242, 243, 245, 246, 248, 249, 250, 252, 253, 255, ]; const TARGET_RATE_MB_21: [u8; 155] = [ 0, 0, 28, 43, 52, 59, 65, 70, 74, 78, 81, 85, 87, 90, 93, 95, 98, 100, 102, 105, 107, 109, 111, 113, 115, 116, 118, 120, 122, 123, 125, 127, 128, 130, 131, 133, 134, 136, 137, 138, 140, 141, 143, 144, 145, 147, 148, 149, 151, 152, 153, 154, 156, 157, 158, 159, 160, 162, 163, 164, 165, 166, 167, 168, 169, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, ]; const TARGET_RATE_WB_21: [u8; 191] = [ 0, 0, 0, 8, 29, 41, 49, 56, 62, 66, 70, 74, 77, 80, 83, 86, 88, 91, 93, 95, 97, 99, 101, 103, 105, 107, 108, 110, 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 171, 172, 173, 174, 175, 176, 177, 177, 178, 179, 180, 181, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 189, 190, 191, 192, 192, 193, 194, 195, 195, 196, 197, 198, 198, 199, 200, 200, 201, 202, 203, 203, 204, 205, 206, 206, 207, 208, 209, 209, 210, 211, 211, 212, 213, 214, 214, 215, 216, 216, 217, 218, 219, 219, 220, 221, 221, 222, 223, 224, 224, 225, 226, 226, 227, 228, 229, 229, 230, 231, 232, 232, 233, 234, 234, 235, 236, 237, 237, 238, 239, 240, 240, 241, 242, 243, 243, 244, 245, 246, 246, 247, 248, 249, 249, 250, 251, 252, 253, 255, ]; fn silk_limit(a: i32, limit1: i32, limit2: i32) -> i32 { if limit1 > limit2 { if a > limit1 { limit1 } else if a < limit2 { limit2 } else { a } } else if a > limit2 { limit2 } else if a < limit1 { limit1 } else { a } } fn float2short(x: f32) -> i16 { sat16((x as f64).round_ties_even() as i32) } fn resample(r: &mut Option>, out: &mut [i16], input: &[i16], in_len: usize) { if let Some(r) = r { r.process(out, &input[..in_len]); } } fn init_state(st: &mut EncState) { *st = EncState::default(); st.variable_hp_smth1_q15 = (lin2log(fix_const!(60.0, 16)) - (16 << 7)) << 8; st.variable_hp_smth2_q15 = st.variable_hp_smth1_q15; st.first_frame_after_reset = true; vad_init(&mut st.s_vad); } /// `silk_InitEncoder`. pub(crate) fn init_encoder(channels: usize) -> SilkEnc { let mut enc = SilkEnc { s_stereo: StereoEncState::default(), n_bits_used_lbrr: 0, n_bits_exceeded: 0, n_channels_api: 1, n_channels_internal: 1, n_prev_channels_internal: 0, time_since_switch_allowed_ms: 0, allow_bandwidth_switch: false, prev_decode_only_middle: false, state_fxx: [Box::default(), Box::default()], resampler: [None, None], }; for n in 0..channels.min(2) { init_state(&mut enc.state_fxx[n]); } enc } fn control_snr(st: &mut EncState, target_rate_bps: i32) { st.target_rate_bps = target_rate_bps; let mut target = target_rate_bps; if st.nb_subfr == 2 { target -= 2000 + st.fs_khz as i32 / 16; } let table: &[u8] = match st.fs_khz { 8 => &TARGET_RATE_NB_21, 12 => &TARGET_RATE_MB_21, _ => &TARGET_RATE_WB_21, }; let bound = table.len() as i32; let id = ((target + 200) / 400 - 10).min(bound - 1); st.snr_db_q7 = if id <= 0 { 0 } else { table[id as usize] as i32 * 21 }; } fn check_control_input(c: &EncControl) -> bool { let api_ok = matches!( c.api_sample_rate, 8000 | 12000 | 16000 | 24000 | 32000 | 44100 | 48000 ); let internal_ok = |r: i32| matches!(r, 8000 | 12000 | 16000); api_ok && internal_ok(c.desired_internal_sample_rate) && internal_ok(c.max_internal_sample_rate) && internal_ok(c.min_internal_sample_rate) && c.min_internal_sample_rate <= c.desired_internal_sample_rate && c.max_internal_sample_rate >= c.desired_internal_sample_rate && c.min_internal_sample_rate <= c.max_internal_sample_rate && matches!(c.payload_size_ms, 10 | 20 | 40 | 60) && (0..=100).contains(&c.packet_loss_percentage) && (1..=2).contains(&c.n_channels_api) && (1..=2).contains(&c.n_channels_internal) && c.n_channels_internal <= c.n_channels_api && (0..=10).contains(&c.complexity) } fn control_audio_bandwidth(st: &mut EncState, enc: &mut EncControl) -> i32 { let mut orig_khz = st.fs_khz as i32; if orig_khz == 0 { orig_khz = st.s_lp.saved_fs_khz; } let mut fs_khz = orig_khz; let mut fs_hz = orig_khz * 1000; let pms = enc.payload_size_ms as i32; if fs_hz == 0 { fs_hz = st.desired_internal_fs_hz.min(st.api_fs_hz); fs_khz = fs_hz / 1000; } else if fs_hz > st.api_fs_hz || fs_hz > st.max_internal_fs_hz || fs_hz < st.min_internal_fs_hz { fs_hz = st .api_fs_hz .min(st.max_internal_fs_hz) .max(st.min_internal_fs_hz); fs_khz = fs_hz / 1000; } else { if st.s_lp.transition_frame_no >= TRANSITION_FRAMES { st.s_lp.mode = 0; } if st.allow_bandwidth_switch || enc.opus_can_switch { if orig_khz * 1000 > st.desired_internal_fs_hz { if st.s_lp.mode == 0 { st.s_lp.transition_frame_no = TRANSITION_FRAMES; st.s_lp.in_lp_state = [0; 2]; } if enc.opus_can_switch { st.s_lp.mode = 0; fs_khz = if orig_khz == 16 { 12 } else { 8 }; } else if st.s_lp.transition_frame_no <= 0 { enc.switch_ready = true; enc.max_bits -= enc.max_bits * 5 / (pms + 5); } else { st.s_lp.mode = -2; } } else if orig_khz * 1000 < st.desired_internal_fs_hz { if enc.opus_can_switch { fs_khz = if orig_khz == 8 { 12 } else { 16 }; st.s_lp.transition_frame_no = 0; st.s_lp.in_lp_state = [0; 2]; st.s_lp.mode = 1; } else if st.s_lp.mode == 0 { enc.switch_ready = true; enc.max_bits -= enc.max_bits * 5 / (pms + 5); } else { st.s_lp.mode = 1; } } else if st.s_lp.mode < 0 { st.s_lp.mode = 1; } } } fs_khz } fn setup_resamplers(st: &mut EncState, resampler: &mut Option>, fs_khz: usize) { if st.fs_khz != fs_khz || st.prev_api_fs_hz != st.api_fs_hz { let api_khz = (st.api_fs_hz / 1000) as usize; let fs_hz = fs_khz as i32 * 1000; if st.fs_khz == 0 { *resampler = Some(Box::new(SilkResampler::new(st.api_fs_hz, fs_hz, true))); } else { let buf_length_ms = (st.nb_subfr * 5) * 2 + LA_SHAPE_MS; let old_samples = buf_length_ms * st.fs_khz; let new_samples = buf_length_ms * fs_khz; let api_samples = buf_length_ms * api_khz; let mut x_fix = vec![0i16; old_samples.max(new_samples)]; for k in 0..old_samples { x_fix[k] = float2short(st.x_buf[k]); } let mut temp = SilkResampler::new(st.fs_khz as i32 * 1000, st.api_fs_hz, false); let mut x_api = vec![0i16; api_samples]; temp.process(&mut x_api, &x_fix[..old_samples]); let mut r = SilkResampler::new(st.api_fs_hz, fs_hz, true); r.process(&mut x_fix, &x_api); for k in 0..new_samples { st.x_buf[k] = x_fix[k] as f32; } *resampler = Some(Box::new(r)); } } st.prev_api_fs_hz = st.api_fs_hz; } fn setup_fs(st: &mut EncState, fs_khz: usize, packet_size_ms: usize) { if packet_size_ms != st.packet_size_ms { if packet_size_ms <= 10 { st.n_frames_per_packet = 1; st.nb_subfr = if packet_size_ms == 10 { 2 } else { 1 }; st.frame_length = packet_size_ms * fs_khz; st.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS_2_SF * fs_khz; } else { st.n_frames_per_packet = packet_size_ms / MAX_FRAME_LENGTH_MS; st.nb_subfr = MAX_NB_SUBFR; st.frame_length = 20 * fs_khz; st.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS * fs_khz; } st.packet_size_ms = packet_size_ms; st.target_rate_bps = 0; } if st.fs_khz != fs_khz { st.s_shape = ShapeState::default(); st.s_nsq = NsqState::default(); st.prev_nlsfq_q15 = [0; MAX_LPC_ORDER]; st.s_lp.in_lp_state = [0; 2]; st.input_buf_ix = 0; st.n_frames_encoded = 0; st.target_rate_bps = 0; st.prev_lag = 100; st.first_frame_after_reset = true; st.s_shape.last_gain_index = 10; st.s_nsq.lag_prev = 100; st.s_nsq.prev_gain_q16 = 65536; st.prev_signal_type = TYPE_NO_VOICE_ACTIVITY; st.fs_khz = fs_khz; st.predict_lpc_order = if fs_khz == 8 || fs_khz == 12 { MIN_LPC_ORDER } else { MAX_LPC_ORDER }; st.nlsf_cb_wb = fs_khz == 16; st.subfr_length = SUB_FRAME_LENGTH_MS * fs_khz; st.frame_length = st.subfr_length * st.nb_subfr; st.ltp_mem_length = LTP_MEM_LENGTH_MS * fs_khz; st.la_pitch = LA_PITCH_MS * fs_khz; st.max_pitch_lag = 18 * fs_khz as i32; st.pitch_lpc_win_length = if st.nb_subfr == MAX_NB_SUBFR { FIND_PITCH_LPC_WIN_MS * fs_khz } else { FIND_PITCH_LPC_WIN_MS_2_SF * fs_khz }; } } fn setup_complexity(st: &mut EncState, complexity: i32) { let fs = st.fs_khz; let ( pe_complexity, threshold, pe_order, shaping_order, la_mult, n_states, interp, survivors, warp, ) = if complexity < 1 { (0, fix_const!(0.8, 16), 6, 12, 3, 1, false, 2, false) } else if complexity < 2 { (1, fix_const!(0.76, 16), 8, 14, 5, 1, false, 3, false) } else if complexity < 3 { (0, fix_const!(0.8, 16), 6, 12, 3, 2, false, 2, false) } else if complexity < 4 { (1, fix_const!(0.76, 16), 8, 14, 5, 2, false, 4, false) } else if complexity < 6 { (1, fix_const!(0.74, 16), 10, 16, 5, 2, true, 6, true) } else if complexity < 8 { (1, fix_const!(0.72, 16), 12, 20, 5, 3, true, 8, true) } else { ( 2, fix_const!(0.7, 16), 16, 24, 5, MAX_DEL_DEC_STATES, true, 16, true, ) }; st.pitch_estimation_complexity = pe_complexity; st.pitch_estimation_threshold_q16 = threshold; st.pitch_estimation_lpc_order = pe_order.min(st.predict_lpc_order); st.shaping_lpc_order = shaping_order; st.la_shape = la_mult * fs; st.n_states_delayed_decision = n_states; st.use_interpolated_nlsfs = interp; st.nlsf_msvq_survivors = survivors; st.warping_q16 = if warp { fs as i32 * WARPING_Q16_PER_FS_KHZ } else { 0 }; st.shape_win_length = SUB_FRAME_LENGTH_MS * fs + 2 * st.la_shape; st.complexity = complexity; } fn setup_lbrr(st: &mut EncState, lbrr_coded: bool) { let was_enabled = st.lbrr_enabled; st.lbrr_enabled = lbrr_coded; if st.lbrr_enabled { st.lbrr_gain_increases = if !was_enabled { 7 } else { (7 - smulwb(st.packet_loss_perc, LBRR_LOSS_SLOPE_Q16)).max(3) }; } } #[allow(clippy::too_many_arguments)] fn control_encoder( st: &mut EncState, resampler: &mut Option>, control: &mut EncControl, allow_bw_switch: bool, channel_nb: usize, force_fs_khz: usize, ) { st.use_dtx = control.use_dtx; st.use_cbr = control.use_cbr; st.api_fs_hz = control.api_sample_rate; st.max_internal_fs_hz = control.max_internal_sample_rate; st.min_internal_fs_hz = control.min_internal_sample_rate; st.desired_internal_fs_hz = control.desired_internal_sample_rate; st.use_in_band_fec = control.use_in_band_fec; st.n_channels_api = control.n_channels_api; st.n_channels_internal = control.n_channels_internal; st.allow_bandwidth_switch = allow_bw_switch; st.channel_nb = channel_nb; if st.controlled_since_last_payload && !st.prefill_flag { if st.api_fs_hz != st.prev_api_fs_hz && st.fs_khz > 0 { let fs = st.fs_khz; setup_resamplers(st, resampler, fs); } return; } let mut fs_khz = control_audio_bandwidth(st, control); if force_fs_khz != 0 { fs_khz = force_fs_khz as i32; } setup_resamplers(st, resampler, fs_khz as usize); setup_fs(st, fs_khz as usize, control.payload_size_ms); setup_complexity(st, control.complexity); st.packet_loss_perc = control.packet_loss_percentage; setup_lbrr(st, control.lbrr_coded); st.controlled_since_last_payload = true; } /// `silk_Encode`. `samples_in` is interleaved int16 at the API rate. #[allow(clippy::too_many_arguments)] pub(crate) fn silk_encode( enc: &mut SilkEnc, control: &mut EncControl, samples_in: &[i16], n_samples_in: usize, range: &mut RangeEncoder, n_bytes_out: &mut i32, prefill_flag: i32, activity: i32, ) { if !check_control_input(control) { return; } let prefill = prefill_flag != 0; let n_ch_api = control.n_channels_api; let n_ch_int = control.n_channels_internal; if control.reduced_dependency { for n in 0..n_ch_api { enc.state_fxx[n].first_frame_after_reset = true; } } for n in 0..n_ch_api { enc.state_fxx[n].n_frames_encoded = 0; } control.switch_ready = false; if n_ch_int > enc.n_channels_internal { init_state(&mut enc.state_fxx[1]); enc.resampler[1] = None; if n_ch_api == 2 { enc.resampler[1] = enc.resampler[0].clone(); enc.state_fxx[1].in_hp_state = enc.state_fxx[0].in_hp_state; } let s = &mut enc.s_stereo; s.pred_prev_q13 = [0; 2]; s.s_side = [0; 2]; s.mid_side_amp_q0 = [0, 1, 0, 1]; s.width_prev_q14 = 0; s.smth_width_q14 = 1 << 14; } let transition = control.payload_size_ms != enc.state_fxx[0].packet_size_ms || enc.n_channels_internal != n_ch_int; enc.n_channels_api = n_ch_api; enc.n_channels_internal = n_ch_int; let api_rate = control.api_sample_rate; let n_blocks = (100 * n_samples_in as i32) / api_rate; let tot_blocks = if n_blocks > 1 { n_blocks >> 1 } else { 1 }; let mut curr_block = 0; let mut tmp_payload_size_ms = 0; let mut tmp_complexity = 0; if prefill { if n_blocks != 1 { return; } let save_lp = if prefill_flag == 2 { let mut lp = enc.state_fxx[0].s_lp; lp.saved_fs_khz = enc.state_fxx[0].fs_khz as i32; Some(lp) } else { None }; for n in 0..n_ch_int { init_state(&mut enc.state_fxx[n]); if let Some(lp) = save_lp { enc.state_fxx[n].s_lp = lp; } enc.resampler[n] = None; } tmp_payload_size_ms = control.payload_size_ms; control.payload_size_ms = 10; tmp_complexity = control.complexity; control.complexity = 0; for n in 0..n_ch_int { enc.state_fxx[n].controlled_since_last_payload = false; enc.state_fxx[n].prefill_flag = true; } } else { if n_blocks * api_rate != 100 * n_samples_in as i32 { return; } if 1000 * n_samples_in as i32 > control.payload_size_ms as i32 * api_rate { return; } } for n in 0..n_ch_int { let force_fs = if n == 1 { enc.state_fxx[0].fs_khz } else { 0 }; control_encoder( &mut enc.state_fxx[n], &mut enc.resampler[n], control, enc.allow_bandwidth_switch, n, force_fs, ); let npp = enc.state_fxx[0].n_frames_per_packet; if enc.state_fxx[n].first_frame_after_reset || transition { for i in 0..npp { enc.state_fxx[n].lbrr_flags[i] = false; } } enc.state_fxx[n].in_dtx = enc.state_fxx[n].use_dtx; } let max_fs = enc.state_fxx[0].fs_khz as i32; let mut n_left = n_samples_in as i32; let mut in_pos = 0usize; let n_to_buffer_max = 10 * n_blocks * max_fs; let n_from_max = (n_to_buffer_max * api_rate) / (max_fs * 1000); let mut buf = vec![0i16; n_from_max as usize]; loop { let mut curr_nbits_lbrr = 0i32; let fs0 = enc.state_fxx[0].fs_khz as i32; let mut n_to_buffer = (enc.state_fxx[0].frame_length as i32 - enc.state_fxx[0].input_buf_ix as i32) .min(n_to_buffer_max); let nf = ((n_to_buffer * api_rate) / (fs0 * 1000)) as usize; let ix0 = enc.state_fxx[0].input_buf_ix; if n_ch_api == 2 && n_ch_int == 2 { let id = enc.state_fxx[0].n_frames_encoded; for n in 0..nf { buf[n] = samples_in[in_pos + 2 * n]; } if enc.n_prev_channels_internal == 1 && id == 0 { enc.resampler[1] = enc.resampler[0].clone(); } resample( &mut enc.resampler[0], &mut enc.state_fxx[0].input_buf[ix0 + 2..], &buf, nf, ); enc.state_fxx[0].input_buf_ix += n_to_buffer as usize; let fs1 = enc.state_fxx[1].fs_khz as i32; n_to_buffer = (enc.state_fxx[1].frame_length as i32 - enc.state_fxx[1].input_buf_ix as i32) .min(10 * n_blocks * fs1); for n in 0..nf { buf[n] = samples_in[in_pos + 2 * n + 1]; } let ix1 = enc.state_fxx[1].input_buf_ix; resample( &mut enc.resampler[1], &mut enc.state_fxx[1].input_buf[ix1 + 2..], &buf, nf, ); enc.state_fxx[1].input_buf_ix += n_to_buffer as usize; } else if n_ch_api == 2 && n_ch_int == 1 { for n in 0..nf { let sum = samples_in[in_pos + 2 * n] as i32 + samples_in[in_pos + 2 * n + 1] as i32; buf[n] = rshift_round(sum, 1) as i16; } resample( &mut enc.resampler[0], &mut enc.state_fxx[0].input_buf[ix0 + 2..], &buf, nf, ); if enc.n_prev_channels_internal == 2 && enc.state_fxx[0].n_frames_encoded == 0 && enc.state_fxx[1].fs_khz == enc.state_fxx[0].fs_khz { let ix1 = enc.state_fxx[1].input_buf_ix; resample( &mut enc.resampler[1], &mut enc.state_fxx[1].input_buf[ix1 + 2..], &buf, nf, ); let fl = enc.state_fxx[0].frame_length; let (s0, s1) = enc.state_fxx.split_at_mut(1); for n in 0..fl { s0[0].input_buf[ix0 + n + 2] = ((s0[0].input_buf[ix0 + n + 2] as i32 + s1[0].input_buf[ix1 + n + 2] as i32) >> 1) as i16; } } enc.state_fxx[0].input_buf_ix += n_to_buffer as usize; } else { buf[..nf].copy_from_slice(&samples_in[in_pos..in_pos + nf]); resample( &mut enc.resampler[0], &mut enc.state_fxx[0].input_buf[ix0 + 2..], &buf, nf, ); enc.state_fxx[0].input_buf_ix += n_to_buffer as usize; } in_pos += nf * n_ch_api; n_left -= nf as i32; enc.allow_bandwidth_switch = false; if enc.state_fxx[0].input_buf_ix < enc.state_fxx[0].frame_length { break; } if enc.state_fxx[0].n_frames_encoded == 0 && !prefill { let npp0 = enc.state_fxx[0].n_frames_per_packet; let icdf0 = (256 - (256i32 >> (((npp0 + 1) * n_ch_int) as u32))) as u8; range.enc_icdf(0, &[icdf0, 0], 8); curr_nbits_lbrr = range.tell() as i32; for n in 0..n_ch_int { let npp_n = enc.state_fxx[n].n_frames_per_packet; let mut lbrr_symbol = 0i32; for i in 0..npp_n { lbrr_symbol |= (enc.state_fxx[n].lbrr_flags[i] as i32) << i; } enc.state_fxx[n].lbrr_flag = lbrr_symbol > 0; if lbrr_symbol != 0 && npp_n > 1 { let icdf: &[u8] = if npp_n == 2 { &LBRR_FLAGS_2_ICDF } else { &LBRR_FLAGS_3_ICDF }; range.enc_icdf((lbrr_symbol - 1) as usize, icdf, 8); } } for i in 0..npp0 { for n in 0..n_ch_int { if enc.state_fxx[n].lbrr_flags[i] { if n_ch_int == 2 && n == 0 { stereo_encode_pred(range, &enc.s_stereo.pred_ix[i]); if !enc.state_fxx[1].lbrr_flags[i] { stereo_encode_mid_only(range, enc.s_stereo.mid_only_flags[i]); } } let cond = if i > 0 && enc.state_fxx[n].lbrr_flags[i - 1] { CondCoding::Conditionally } else { CondCoding::Independently }; encode_indices(&mut enc.state_fxx[n], range, i, true, cond); let st = &enc.state_fxx[n]; let idx = st.indices_lbrr[i]; encode_pulses( range, idx.signal_type, idx.quant_offset_type, &st.pulses_lbrr[i], st.frame_length, ); } } } for n in 0..n_ch_int { enc.state_fxx[n].lbrr_flags = [false; MAX_FRAMES_PER_PACKET]; } curr_nbits_lbrr = range.tell() as i32 - curr_nbits_lbrr; } hp_variable_cutoff(&mut enc.state_fxx[0]); let pms = control.payload_size_ms as i32; let mut n_bits = (control.bit_rate * pms) / 1000; if !prefill { if curr_nbits_lbrr < 10 { enc.n_bits_used_lbrr = 0; } else if enc.n_bits_used_lbrr < 10 { enc.n_bits_used_lbrr = curr_nbits_lbrr; } else { enc.n_bits_used_lbrr = (enc.n_bits_used_lbrr + curr_nbits_lbrr) / 2; } n_bits -= enc.n_bits_used_lbrr; } n_bits /= enc.state_fxx[0].n_frames_per_packet as i32; let mut target_rate = if pms == 10 { n_bits * 100 } else { n_bits * 50 }; target_rate -= (enc.n_bits_exceeded * 1000) / BITRESERVOIR_DECAY_TIME_MS; if !prefill && enc.state_fxx[0].n_frames_encoded > 0 { let nfe = enc.state_fxx[0].n_frames_encoded as i32; let bits_balance = range.tell() as i32 - enc.n_bits_used_lbrr - n_bits * nfe; target_rate -= (bits_balance * 1000) / BITRESERVOIR_DECAY_TIME_MS; } target_rate = silk_limit(target_rate, control.bit_rate, 5000); let mut ms_rates = [0i32; 2]; if n_ch_int == 2 { let nfe = enc.state_fxx[0].n_frames_encoded; let fs0 = enc.state_fxx[0].fs_khz; let fl = enc.state_fxx[0].frame_length; let mut ix = enc.s_stereo.pred_ix[nfe]; let mut mo = enc.s_stereo.mid_only_flags[nfe]; { let (s0, s1) = enc.state_fxx.split_at_mut(1); let speech_act = s0[0].speech_activity_q8; stereo_lr_to_ms( &mut enc.s_stereo, &mut s0[0].input_buf, &mut s1[0].input_buf, &mut ix, &mut mo, &mut ms_rates, target_rate, speech_act, control.to_mono, fs0, fl, ); } enc.s_stereo.pred_ix[nfe] = ix; enc.s_stereo.mid_only_flags[nfe] = mo; if mo == 0 { if enc.prev_decode_only_middle { let st1 = &mut enc.state_fxx[1]; st1.s_shape = ShapeState::default(); st1.s_nsq = NsqState::default(); st1.prev_nlsfq_q15 = [0; MAX_LPC_ORDER]; let st1 = &mut enc.state_fxx[1]; st1.s_lp.in_lp_state = [0; 2]; st1.prev_lag = 100; st1.s_nsq.lag_prev = 100; st1.s_shape.last_gain_index = 10; st1.prev_signal_type = TYPE_NO_VOICE_ACTIVITY; st1.s_nsq.prev_gain_q16 = 65536; st1.first_frame_after_reset = true; } encode_do_vad(&mut enc.state_fxx[1], activity); } else { enc.state_fxx[1].vad_flags[nfe] = false; } if !prefill { stereo_encode_pred(range, &enc.s_stereo.pred_ix[nfe]); if !enc.state_fxx[1].vad_flags[nfe] { stereo_encode_mid_only(range, enc.s_stereo.mid_only_flags[nfe]); } } } else { let mid = enc.s_stereo.s_mid; enc.state_fxx[0].input_buf[0] = mid[0]; enc.state_fxx[0].input_buf[1] = mid[1]; let fl = enc.state_fxx[0].frame_length; enc.s_stereo.s_mid = [ enc.state_fxx[0].input_buf[fl], enc.state_fxx[0].input_buf[fl + 1], ]; } encode_do_vad(&mut enc.state_fxx[0], activity); for n in 0..n_ch_int { let mut max_bits = control.max_bits; if tot_blocks == 2 && curr_block == 0 { max_bits = max_bits * 3 / 5; } else if tot_blocks == 3 { if curr_block == 0 { max_bits = max_bits * 2 / 5; } else if curr_block == 1 { max_bits = max_bits * 3 / 4; } } let mut use_cbr = control.use_cbr && curr_block == tot_blocks - 1; let channel_rate = if n_ch_int == 1 { target_rate } else { if n == 0 && ms_rates[1] > 0 { use_cbr = false; max_bits -= control.max_bits / (tot_blocks * 2); } ms_rates[n] }; if channel_rate > 0 { control_snr(&mut enc.state_fxx[n], channel_rate); let nfe0 = enc.state_fxx[0].n_frames_encoded as i32; let cond = if nfe0 - n as i32 <= 0 { CondCoding::Independently } else if n > 0 && enc.prev_decode_only_middle { CondCoding::IndependentlyNoLtpScaling } else { CondCoding::Conditionally }; encode_frame( &mut enc.state_fxx[n], n_bytes_out, range, cond, max_bits, use_cbr, ); } enc.state_fxx[n].controlled_since_last_payload = false; enc.state_fxx[n].input_buf_ix = 0; enc.state_fxx[n].n_frames_encoded += 1; } let nfe = enc.state_fxx[0].n_frames_encoded; enc.prev_decode_only_middle = enc.s_stereo.mid_only_flags[nfe - 1] != 0; if *n_bytes_out > 0 && enc.state_fxx[0].n_frames_encoded == enc.state_fxx[0].n_frames_per_packet { let mut flags = 0u32; for n in 0..n_ch_int { let st = &enc.state_fxx[n]; for i in 0..st.n_frames_per_packet { flags <<= 1; flags |= st.vad_flags[i] as u32; } flags <<= 1; flags |= st.lbrr_flag as u32; } if !prefill { let nbits = ((enc.state_fxx[0].n_frames_per_packet + 1) * n_ch_int) as u32; range.patch_initial_bits(flags, nbits); } if enc.state_fxx[0].in_dtx && (n_ch_int == 1 || enc.state_fxx[1].in_dtx) { *n_bytes_out = 0; } enc.n_bits_exceeded += *n_bytes_out * 8; enc.n_bits_exceeded -= (control.bit_rate * pms) / 1000; enc.n_bits_exceeded = silk_limit(enc.n_bits_exceeded, 0, 10000); let thr = smlawb( SPEECH_ACT_THR_SWITCH_Q8, SPEECH_ACT_SLOPE_Q24, enc.time_since_switch_allowed_ms, ); if enc.state_fxx[0].speech_activity_q8 < thr { enc.allow_bandwidth_switch = true; enc.time_since_switch_allowed_ms = 0; } else { enc.allow_bandwidth_switch = false; enc.time_since_switch_allowed_ms += pms; } } if n_left == 0 { break; } curr_block += 1; } enc.n_prev_channels_internal = n_ch_int; control.allow_bandwidth_switch = enc.allow_bandwidth_switch; control.in_wb_mode_without_variable_lp = enc.state_fxx[0].fs_khz == 16 && enc.state_fxx[0].s_lp.mode == 0; control.internal_sample_rate = enc.state_fxx[0].fs_khz as i32 * 1000; control.stereo_width_q14 = if control.to_mono { 0 } else { enc.s_stereo.smth_width_q14 as i32 }; if prefill { control.payload_size_ms = tmp_payload_size_ms; control.complexity = tmp_complexity; for n in 0..n_ch_int { enc.state_fxx[n].controlled_since_last_payload = false; enc.state_fxx[n].prefill_flag = false; } } let signal_type = enc.state_fxx[0].indices.signal_type as i32; let quant_offset_type = enc.state_fxx[0].indices.quant_offset_type as usize; control.signal_type = signal_type; control.offset = QUANTIZATION_OFFSETS_Q10[(signal_type >> 1) as usize][quant_offset_type] as i32; }