forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

api.rs902 lines, 33.9 KiBHistoryRawDownload
1//! `silk/enc_API.c`, `silk/init_encoder.c`, `silk/control_codec.c`, `silk/control_SNR.c`,
2//! `silk/control_audio_bandwidth.c`, `silk/check_control_input.c`.
3
4use super::encode::{
5 TRANSITION_FRAMES, encode_do_vad, encode_frame, encode_indices, encode_pulses,
6 hp_variable_cutoff,
7};
8use super::resampler::SilkResampler;
9use super::stereo::{StereoEncState, stereo_encode_mid_only, stereo_encode_pred, stereo_lr_to_ms};
10use super::vad::vad_init;
11use super::*;
12use crate::range::RangeEncoder;
13use crate::silk::tables::{LBRR_FLAGS_2_ICDF, LBRR_FLAGS_3_ICDF, QUANTIZATION_OFFSETS_Q10};
14use crate::silk_fix::{lin2log, rshift_round, sat16, smlawb, smulwb};
15
16macro_rules! fix_const {
17 ($c:expr, $q:expr) => {
18 (($c) * ((1i64 << $q) as f64) + 0.5) as i32
19 };
20}
21
22const BITRESERVOIR_DECAY_TIME_MS: i32 = 500;
23const SPEECH_ACT_THR_SWITCH_Q8: i32 = fix_const!(0.05, 8);
24const SPEECH_ACT_SLOPE_Q24: i32 = fix_const!((1.0 - 0.05) / 5000.0, 24);
25const WARPING_Q16_PER_FS_KHZ: i32 = fix_const!(0.015, 16);
26const LBRR_LOSS_SLOPE_Q16: i32 = fix_const!(0.2, 16);
27
28/// `silk_EncControlStruct`.
29#[derive(Clone, Debug, Default)]
30pub(crate) struct EncControl {
31 pub(crate) n_channels_api: usize,
32 pub(crate) n_channels_internal: usize,
33 pub(crate) api_sample_rate: i32,
34 pub(crate) max_internal_sample_rate: i32,
35 pub(crate) min_internal_sample_rate: i32,
36 pub(crate) desired_internal_sample_rate: i32,
37 pub(crate) payload_size_ms: usize,
38 pub(crate) bit_rate: i32,
39 pub(crate) packet_loss_percentage: i32,
40 pub(crate) complexity: i32,
41 pub(crate) use_in_band_fec: bool,
42 pub(crate) lbrr_coded: bool,
43 pub(crate) use_dtx: bool,
44 pub(crate) use_cbr: bool,
45 pub(crate) max_bits: i32,
46 pub(crate) to_mono: bool,
47 pub(crate) opus_can_switch: bool,
48 pub(crate) reduced_dependency: bool,
49 pub(crate) internal_sample_rate: i32,
50 pub(crate) allow_bandwidth_switch: bool,
51 pub(crate) in_wb_mode_without_variable_lp: bool,
52 pub(crate) stereo_width_q14: i32,
53 pub(crate) switch_ready: bool,
54 pub(crate) signal_type: i32,
55 pub(crate) offset: i32,
56}
57
58/// `silk_encoder` (two channel states and their API resamplers).
59#[derive(Clone, Debug)]
60pub(crate) struct SilkEnc {
61 pub(crate) s_stereo: StereoEncState,
62 pub(crate) n_bits_used_lbrr: i32,
63 pub(crate) n_bits_exceeded: i32,
64 pub(crate) n_channels_api: usize,
65 pub(crate) n_channels_internal: usize,
66 pub(crate) n_prev_channels_internal: usize,
67 pub(crate) time_since_switch_allowed_ms: i32,
68 pub(crate) allow_bandwidth_switch: bool,
69 pub(crate) prev_decode_only_middle: bool,
70 pub(crate) state_fxx: [Box<EncState>; 2],
71 pub(crate) resampler: [Option<Box<SilkResampler>>; 2],
72}
73
74const TARGET_RATE_NB_21: [u8; 107] = [
75 0, 15, 39, 52, 61, 68, 74, 79, 84, 88, 92, 95, 99, 102, 105, 108, 111, 114, 117, 119, 122, 124,
76 126, 129, 131, 133, 135, 137, 139, 142, 143, 145, 147, 149, 151, 153, 155, 157, 158, 160, 162,
77 163, 165, 167, 168, 170, 171, 173, 174, 176, 177, 179, 180, 182, 183, 185, 186, 187, 189, 190,
78 192, 193, 194, 196, 197, 199, 200, 201, 203, 204, 205, 207, 208, 209, 211, 212, 213, 215, 216,
79 217, 219, 220, 221, 223, 224, 225, 227, 228, 230, 231, 232, 234, 235, 236, 238, 239, 241, 242,
80 243, 245, 246, 248, 249, 250, 252, 253, 255,
81];
82
83const TARGET_RATE_MB_21: [u8; 155] = [
84 0, 0, 28, 43, 52, 59, 65, 70, 74, 78, 81, 85, 87, 90, 93, 95, 98, 100, 102, 105, 107, 109, 111,
85 113, 115, 116, 118, 120, 122, 123, 125, 127, 128, 130, 131, 133, 134, 136, 137, 138, 140, 141,
86 143, 144, 145, 147, 148, 149, 151, 152, 153, 154, 156, 157, 158, 159, 160, 162, 163, 164, 165,
87 166, 167, 168, 169, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185,
88 186, 187, 188, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203,
89 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 214, 215, 216, 217, 218, 219, 220,
90 221, 222, 223, 224, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 236, 237,
91 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
92];
93
94const TARGET_RATE_WB_21: [u8; 191] = [
95 0, 0, 0, 8, 29, 41, 49, 56, 62, 66, 70, 74, 77, 80, 83, 86, 88, 91, 93, 95, 97, 99, 101, 103,
96 105, 107, 108, 110, 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 127, 129, 130, 131,
97 132, 134, 135, 136, 137, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
98 153, 154, 156, 157, 158, 159, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,
99 171, 172, 173, 174, 175, 176, 177, 177, 178, 179, 180, 181, 181, 182, 183, 184, 185, 185, 186,
100 187, 188, 189, 189, 190, 191, 192, 192, 193, 194, 195, 195, 196, 197, 198, 198, 199, 200, 200,
101 201, 202, 203, 203, 204, 205, 206, 206, 207, 208, 209, 209, 210, 211, 211, 212, 213, 214, 214,
102 215, 216, 216, 217, 218, 219, 219, 220, 221, 221, 222, 223, 224, 224, 225, 226, 226, 227, 228,
103 229, 229, 230, 231, 232, 232, 233, 234, 234, 235, 236, 237, 237, 238, 239, 240, 240, 241, 242,
104 243, 243, 244, 245, 246, 246, 247, 248, 249, 249, 250, 251, 252, 253, 255,
105];
106
107fn silk_limit(a: i32, limit1: i32, limit2: i32) -> i32 {
108 if limit1 > limit2 {
109 if a > limit1 {
110 limit1
111 } else if a < limit2 {
112 limit2
113 } else {
114 a
115 }
116 } else if a > limit2 {
117 limit2
118 } else if a < limit1 {
119 limit1
120 } else {
121 a
122 }
123}
124
125fn float2short(x: f32) -> i16 {
126 sat16((x as f64).round_ties_even() as i32)
127}
128
129fn resample(r: &mut Option<Box<SilkResampler>>, out: &mut [i16], input: &[i16], in_len: usize) {
130 if let Some(r) = r {
131 r.process(out, &input[..in_len]);
132 }
133}
134
135fn init_state(st: &mut EncState) {
136 *st = EncState::default();
137 st.variable_hp_smth1_q15 = (lin2log(fix_const!(60.0, 16)) - (16 << 7)) << 8;
138 st.variable_hp_smth2_q15 = st.variable_hp_smth1_q15;
139 st.first_frame_after_reset = true;
140 vad_init(&mut st.s_vad);
141}
142
143/// `silk_InitEncoder`.
144pub(crate) fn init_encoder(channels: usize) -> SilkEnc {
145 let mut enc = SilkEnc {
146 s_stereo: StereoEncState::default(),
147 n_bits_used_lbrr: 0,
148 n_bits_exceeded: 0,
149 n_channels_api: 1,
150 n_channels_internal: 1,
151 n_prev_channels_internal: 0,
152 time_since_switch_allowed_ms: 0,
153 allow_bandwidth_switch: false,
154 prev_decode_only_middle: false,
155 state_fxx: [Box::default(), Box::default()],
156 resampler: [None, None],
157 };
158 for n in 0..channels.min(2) {
159 init_state(&mut enc.state_fxx[n]);
160 }
161 enc
162}
163
164fn control_snr(st: &mut EncState, target_rate_bps: i32) {
165 st.target_rate_bps = target_rate_bps;
166 let mut target = target_rate_bps;
167 if st.nb_subfr == 2 {
168 target -= 2000 + st.fs_khz as i32 / 16;
169 }
170 let table: &[u8] = match st.fs_khz {
171 8 => &TARGET_RATE_NB_21,
172 12 => &TARGET_RATE_MB_21,
173 _ => &TARGET_RATE_WB_21,
174 };
175 let bound = table.len() as i32;
176 let id = ((target + 200) / 400 - 10).min(bound - 1);
177 st.snr_db_q7 = if id <= 0 {
178 0
179 } else {
180 table[id as usize] as i32 * 21
181 };
182}
183
184fn check_control_input(c: &EncControl) -> bool {
185 let api_ok = matches!(
186 c.api_sample_rate,
187 8000 | 12000 | 16000 | 24000 | 32000 | 44100 | 48000
188 );
189 let internal_ok = |r: i32| matches!(r, 8000 | 12000 | 16000);
190 api_ok
191 && internal_ok(c.desired_internal_sample_rate)
192 && internal_ok(c.max_internal_sample_rate)
193 && internal_ok(c.min_internal_sample_rate)
194 && c.min_internal_sample_rate <= c.desired_internal_sample_rate
195 && c.max_internal_sample_rate >= c.desired_internal_sample_rate
196 && c.min_internal_sample_rate <= c.max_internal_sample_rate
197 && matches!(c.payload_size_ms, 10 | 20 | 40 | 60)
198 && (0..=100).contains(&c.packet_loss_percentage)
199 && (1..=2).contains(&c.n_channels_api)
200 && (1..=2).contains(&c.n_channels_internal)
201 && c.n_channels_internal <= c.n_channels_api
202 && (0..=10).contains(&c.complexity)
203}
204
205fn control_audio_bandwidth(st: &mut EncState, enc: &mut EncControl) -> i32 {
206 let mut orig_khz = st.fs_khz as i32;
207 if orig_khz == 0 {
208 orig_khz = st.s_lp.saved_fs_khz;
209 }
210 let mut fs_khz = orig_khz;
211 let mut fs_hz = orig_khz * 1000;
212 let pms = enc.payload_size_ms as i32;
213 if fs_hz == 0 {
214 fs_hz = st.desired_internal_fs_hz.min(st.api_fs_hz);
215 fs_khz = fs_hz / 1000;
216 } else if fs_hz > st.api_fs_hz || fs_hz > st.max_internal_fs_hz || fs_hz < st.min_internal_fs_hz
217 {
218 fs_hz = st
219 .api_fs_hz
220 .min(st.max_internal_fs_hz)
221 .max(st.min_internal_fs_hz);
222 fs_khz = fs_hz / 1000;
223 } else {
224 if st.s_lp.transition_frame_no >= TRANSITION_FRAMES {
225 st.s_lp.mode = 0;
226 }
227 if st.allow_bandwidth_switch || enc.opus_can_switch {
228 if orig_khz * 1000 > st.desired_internal_fs_hz {
229 if st.s_lp.mode == 0 {
230 st.s_lp.transition_frame_no = TRANSITION_FRAMES;
231 st.s_lp.in_lp_state = [0; 2];
232 }
233 if enc.opus_can_switch {
234 st.s_lp.mode = 0;
235 fs_khz = if orig_khz == 16 { 12 } else { 8 };
236 } else if st.s_lp.transition_frame_no <= 0 {
237 enc.switch_ready = true;
238 enc.max_bits -= enc.max_bits * 5 / (pms + 5);
239 } else {
240 st.s_lp.mode = -2;
241 }
242 } else if orig_khz * 1000 < st.desired_internal_fs_hz {
243 if enc.opus_can_switch {
244 fs_khz = if orig_khz == 8 { 12 } else { 16 };
245 st.s_lp.transition_frame_no = 0;
246 st.s_lp.in_lp_state = [0; 2];
247 st.s_lp.mode = 1;
248 } else if st.s_lp.mode == 0 {
249 enc.switch_ready = true;
250 enc.max_bits -= enc.max_bits * 5 / (pms + 5);
251 } else {
252 st.s_lp.mode = 1;
253 }
254 } else if st.s_lp.mode < 0 {
255 st.s_lp.mode = 1;
256 }
257 }
258 }
259 fs_khz
260}
261
262fn setup_resamplers(st: &mut EncState, resampler: &mut Option<Box<SilkResampler>>, fs_khz: usize) {
263 if st.fs_khz != fs_khz || st.prev_api_fs_hz != st.api_fs_hz {
264 let api_khz = (st.api_fs_hz / 1000) as usize;
265 let fs_hz = fs_khz as i32 * 1000;
266 if st.fs_khz == 0 {
267 *resampler = Some(Box::new(SilkResampler::new(st.api_fs_hz, fs_hz, true)));
268 } else {
269 let buf_length_ms = (st.nb_subfr * 5) * 2 + LA_SHAPE_MS;
270 let old_samples = buf_length_ms * st.fs_khz;
271 let new_samples = buf_length_ms * fs_khz;
272 let api_samples = buf_length_ms * api_khz;
273 let mut x_fix = vec![0i16; old_samples.max(new_samples)];
274 for k in 0..old_samples {
275 x_fix[k] = float2short(st.x_buf[k]);
276 }
277 let mut temp = SilkResampler::new(st.fs_khz as i32 * 1000, st.api_fs_hz, false);
278 let mut x_api = vec![0i16; api_samples];
279 temp.process(&mut x_api, &x_fix[..old_samples]);
280 let mut r = SilkResampler::new(st.api_fs_hz, fs_hz, true);
281 r.process(&mut x_fix, &x_api);
282 for k in 0..new_samples {
283 st.x_buf[k] = x_fix[k] as f32;
284 }
285 *resampler = Some(Box::new(r));
286 }
287 }
288 st.prev_api_fs_hz = st.api_fs_hz;
289}
290
291fn setup_fs(st: &mut EncState, fs_khz: usize, packet_size_ms: usize) {
292 if packet_size_ms != st.packet_size_ms {
293 if packet_size_ms <= 10 {
294 st.n_frames_per_packet = 1;
295 st.nb_subfr = if packet_size_ms == 10 { 2 } else { 1 };
296 st.frame_length = packet_size_ms * fs_khz;
297 st.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS_2_SF * fs_khz;
298 } else {
299 st.n_frames_per_packet = packet_size_ms / MAX_FRAME_LENGTH_MS;
300 st.nb_subfr = MAX_NB_SUBFR;
301 st.frame_length = 20 * fs_khz;
302 st.pitch_lpc_win_length = FIND_PITCH_LPC_WIN_MS * fs_khz;
303 }
304 st.packet_size_ms = packet_size_ms;
305 st.target_rate_bps = 0;
306 }
307 if st.fs_khz != fs_khz {
308 st.s_shape = ShapeState::default();
309 st.s_nsq = NsqState::default();
310 st.prev_nlsfq_q15 = [0; MAX_LPC_ORDER];
311 st.s_lp.in_lp_state = [0; 2];
312 st.input_buf_ix = 0;
313 st.n_frames_encoded = 0;
314 st.target_rate_bps = 0;
315 st.prev_lag = 100;
316 st.first_frame_after_reset = true;
317 st.s_shape.last_gain_index = 10;
318 st.s_nsq.lag_prev = 100;
319 st.s_nsq.prev_gain_q16 = 65536;
320 st.prev_signal_type = TYPE_NO_VOICE_ACTIVITY;
321 st.fs_khz = fs_khz;
322 st.predict_lpc_order = if fs_khz == 8 || fs_khz == 12 {
323 MIN_LPC_ORDER
324 } else {
325 MAX_LPC_ORDER
326 };
327 st.nlsf_cb_wb = fs_khz == 16;
328 st.subfr_length = SUB_FRAME_LENGTH_MS * fs_khz;
329 st.frame_length = st.subfr_length * st.nb_subfr;
330 st.ltp_mem_length = LTP_MEM_LENGTH_MS * fs_khz;
331 st.la_pitch = LA_PITCH_MS * fs_khz;
332 st.max_pitch_lag = 18 * fs_khz as i32;
333 st.pitch_lpc_win_length = if st.nb_subfr == MAX_NB_SUBFR {
334 FIND_PITCH_LPC_WIN_MS * fs_khz
335 } else {
336 FIND_PITCH_LPC_WIN_MS_2_SF * fs_khz
337 };
338 }
339}
340
341fn setup_complexity(st: &mut EncState, complexity: i32) {
342 let fs = st.fs_khz;
343 let (
344 pe_complexity,
345 threshold,
346 pe_order,
347 shaping_order,
348 la_mult,
349 n_states,
350 interp,
351 survivors,
352 warp,
353 ) = if complexity < 1 {
354 (0, fix_const!(0.8, 16), 6, 12, 3, 1, false, 2, false)
355 } else if complexity < 2 {
356 (1, fix_const!(0.76, 16), 8, 14, 5, 1, false, 3, false)
357 } else if complexity < 3 {
358 (0, fix_const!(0.8, 16), 6, 12, 3, 2, false, 2, false)
359 } else if complexity < 4 {
360 (1, fix_const!(0.76, 16), 8, 14, 5, 2, false, 4, false)
361 } else if complexity < 6 {
362 (1, fix_const!(0.74, 16), 10, 16, 5, 2, true, 6, true)
363 } else if complexity < 8 {
364 (1, fix_const!(0.72, 16), 12, 20, 5, 3, true, 8, true)
365 } else {
366 (
367 2,
368 fix_const!(0.7, 16),
369 16,
370 24,
371 5,
372 MAX_DEL_DEC_STATES,
373 true,
374 16,
375 true,
376 )
377 };
378 st.pitch_estimation_complexity = pe_complexity;
379 st.pitch_estimation_threshold_q16 = threshold;
380 st.pitch_estimation_lpc_order = pe_order.min(st.predict_lpc_order);
381 st.shaping_lpc_order = shaping_order;
382 st.la_shape = la_mult * fs;
383 st.n_states_delayed_decision = n_states;
384 st.use_interpolated_nlsfs = interp;
385 st.nlsf_msvq_survivors = survivors;
386 st.warping_q16 = if warp {
387 fs as i32 * WARPING_Q16_PER_FS_KHZ
388 } else {
389 0
390 };
391 st.shape_win_length = SUB_FRAME_LENGTH_MS * fs + 2 * st.la_shape;
392 st.complexity = complexity;
393}
394
395fn setup_lbrr(st: &mut EncState, lbrr_coded: bool) {
396 let was_enabled = st.lbrr_enabled;
397 st.lbrr_enabled = lbrr_coded;
398 if st.lbrr_enabled {
399 st.lbrr_gain_increases = if !was_enabled {
400 7
401 } else {
402 (7 - smulwb(st.packet_loss_perc, LBRR_LOSS_SLOPE_Q16)).max(3)
403 };
404 }
405}
406
407#[allow(clippy::too_many_arguments)]
408fn control_encoder(
409 st: &mut EncState,
410 resampler: &mut Option<Box<SilkResampler>>,
411 control: &mut EncControl,
412 allow_bw_switch: bool,
413 channel_nb: usize,
414 force_fs_khz: usize,
415) {
416 st.use_dtx = control.use_dtx;
417 st.use_cbr = control.use_cbr;
418 st.api_fs_hz = control.api_sample_rate;
419 st.max_internal_fs_hz = control.max_internal_sample_rate;
420 st.min_internal_fs_hz = control.min_internal_sample_rate;
421 st.desired_internal_fs_hz = control.desired_internal_sample_rate;
422 st.use_in_band_fec = control.use_in_band_fec;
423 st.n_channels_api = control.n_channels_api;
424 st.n_channels_internal = control.n_channels_internal;
425 st.allow_bandwidth_switch = allow_bw_switch;
426 st.channel_nb = channel_nb;
427 if st.controlled_since_last_payload && !st.prefill_flag {
428 if st.api_fs_hz != st.prev_api_fs_hz && st.fs_khz > 0 {
429 let fs = st.fs_khz;
430 setup_resamplers(st, resampler, fs);
431 }
432 return;
433 }
434 let mut fs_khz = control_audio_bandwidth(st, control);
435 if force_fs_khz != 0 {
436 fs_khz = force_fs_khz as i32;
437 }
438 setup_resamplers(st, resampler, fs_khz as usize);
439 setup_fs(st, fs_khz as usize, control.payload_size_ms);
440 setup_complexity(st, control.complexity);
441 st.packet_loss_perc = control.packet_loss_percentage;
442 setup_lbrr(st, control.lbrr_coded);
443 st.controlled_since_last_payload = true;
444}
445
446/// `silk_Encode`. `samples_in` is interleaved int16 at the API rate.
447#[allow(clippy::too_many_arguments)]
448pub(crate) fn silk_encode(
449 enc: &mut SilkEnc,
450 control: &mut EncControl,
451 samples_in: &[i16],
452 n_samples_in: usize,
453 range: &mut RangeEncoder,
454 n_bytes_out: &mut i32,
455 prefill_flag: i32,
456 activity: i32,
457) {
458 if !check_control_input(control) {
459 return;
460 }
461 let prefill = prefill_flag != 0;
462 let n_ch_api = control.n_channels_api;
463 let n_ch_int = control.n_channels_internal;
464 if control.reduced_dependency {
465 for n in 0..n_ch_api {
466 enc.state_fxx[n].first_frame_after_reset = true;
467 }
468 }
469 for n in 0..n_ch_api {
470 enc.state_fxx[n].n_frames_encoded = 0;
471 }
472 control.switch_ready = false;
473 if n_ch_int > enc.n_channels_internal {
474 init_state(&mut enc.state_fxx[1]);
475 enc.resampler[1] = None;
476 if n_ch_api == 2 {
477 enc.resampler[1] = enc.resampler[0].clone();
478 enc.state_fxx[1].in_hp_state = enc.state_fxx[0].in_hp_state;
479 }
480 let s = &mut enc.s_stereo;
481 s.pred_prev_q13 = [0; 2];
482 s.s_side = [0; 2];
483 s.mid_side_amp_q0 = [0, 1, 0, 1];
484 s.width_prev_q14 = 0;
485 s.smth_width_q14 = 1 << 14;
486 }
487 let transition = control.payload_size_ms != enc.state_fxx[0].packet_size_ms
488 || enc.n_channels_internal != n_ch_int;
489 enc.n_channels_api = n_ch_api;
490 enc.n_channels_internal = n_ch_int;
491
492 let api_rate = control.api_sample_rate;
493 let n_blocks = (100 * n_samples_in as i32) / api_rate;
494 let tot_blocks = if n_blocks > 1 { n_blocks >> 1 } else { 1 };
495 let mut curr_block = 0;
496
497 let mut tmp_payload_size_ms = 0;
498 let mut tmp_complexity = 0;
499 if prefill {
500 if n_blocks != 1 {
501 return;
502 }
503 let save_lp = if prefill_flag == 2 {
504 let mut lp = enc.state_fxx[0].s_lp;
505 lp.saved_fs_khz = enc.state_fxx[0].fs_khz as i32;
506 Some(lp)
507 } else {
508 None
509 };
510 for n in 0..n_ch_int {
511 init_state(&mut enc.state_fxx[n]);
512 if let Some(lp) = save_lp {
513 enc.state_fxx[n].s_lp = lp;
514 }
515 enc.resampler[n] = None;
516 }
517 tmp_payload_size_ms = control.payload_size_ms;
518 control.payload_size_ms = 10;
519 tmp_complexity = control.complexity;
520 control.complexity = 0;
521 for n in 0..n_ch_int {
522 enc.state_fxx[n].controlled_since_last_payload = false;
523 enc.state_fxx[n].prefill_flag = true;
524 }
525 } else {
526 if n_blocks * api_rate != 100 * n_samples_in as i32 {
527 return;
528 }
529 if 1000 * n_samples_in as i32 > control.payload_size_ms as i32 * api_rate {
530 return;
531 }
532 }
533
534 for n in 0..n_ch_int {
535 let force_fs = if n == 1 { enc.state_fxx[0].fs_khz } else { 0 };
536 control_encoder(
537 &mut enc.state_fxx[n],
538 &mut enc.resampler[n],
539 control,
540 enc.allow_bandwidth_switch,
541 n,
542 force_fs,
543 );
544 let npp = enc.state_fxx[0].n_frames_per_packet;
545 if enc.state_fxx[n].first_frame_after_reset || transition {
546 for i in 0..npp {
547 enc.state_fxx[n].lbrr_flags[i] = false;
548 }
549 }
550 enc.state_fxx[n].in_dtx = enc.state_fxx[n].use_dtx;
551 }
552
553 let max_fs = enc.state_fxx[0].fs_khz as i32;
554 let mut n_left = n_samples_in as i32;
555 let mut in_pos = 0usize;
556 let n_to_buffer_max = 10 * n_blocks * max_fs;
557 let n_from_max = (n_to_buffer_max * api_rate) / (max_fs * 1000);
558 let mut buf = vec![0i16; n_from_max as usize];
559
560 loop {
561 let mut curr_nbits_lbrr = 0i32;
562 let fs0 = enc.state_fxx[0].fs_khz as i32;
563 let mut n_to_buffer = (enc.state_fxx[0].frame_length as i32
564 - enc.state_fxx[0].input_buf_ix as i32)
565 .min(n_to_buffer_max);
566 let nf = ((n_to_buffer * api_rate) / (fs0 * 1000)) as usize;
567 let ix0 = enc.state_fxx[0].input_buf_ix;
568
569 if n_ch_api == 2 && n_ch_int == 2 {
570 let id = enc.state_fxx[0].n_frames_encoded;
571 for n in 0..nf {
572 buf[n] = samples_in[in_pos + 2 * n];
573 }
574 if enc.n_prev_channels_internal == 1 && id == 0 {
575 enc.resampler[1] = enc.resampler[0].clone();
576 }
577 resample(
578 &mut enc.resampler[0],
579 &mut enc.state_fxx[0].input_buf[ix0 + 2..],
580 &buf,
581 nf,
582 );
583 enc.state_fxx[0].input_buf_ix += n_to_buffer as usize;
584 let fs1 = enc.state_fxx[1].fs_khz as i32;
585 n_to_buffer = (enc.state_fxx[1].frame_length as i32
586 - enc.state_fxx[1].input_buf_ix as i32)
587 .min(10 * n_blocks * fs1);
588 for n in 0..nf {
589 buf[n] = samples_in[in_pos + 2 * n + 1];
590 }
591 let ix1 = enc.state_fxx[1].input_buf_ix;
592 resample(
593 &mut enc.resampler[1],
594 &mut enc.state_fxx[1].input_buf[ix1 + 2..],
595 &buf,
596 nf,
597 );
598 enc.state_fxx[1].input_buf_ix += n_to_buffer as usize;
599 } else if n_ch_api == 2 && n_ch_int == 1 {
600 for n in 0..nf {
601 let sum = samples_in[in_pos + 2 * n] as i32 + samples_in[in_pos + 2 * n + 1] as i32;
602 buf[n] = rshift_round(sum, 1) as i16;
603 }
604 resample(
605 &mut enc.resampler[0],
606 &mut enc.state_fxx[0].input_buf[ix0 + 2..],
607 &buf,
608 nf,
609 );
610 if enc.n_prev_channels_internal == 2
611 && enc.state_fxx[0].n_frames_encoded == 0
612 && enc.state_fxx[1].fs_khz == enc.state_fxx[0].fs_khz
613 {
614 let ix1 = enc.state_fxx[1].input_buf_ix;
615 resample(
616 &mut enc.resampler[1],
617 &mut enc.state_fxx[1].input_buf[ix1 + 2..],
618 &buf,
619 nf,
620 );
621 let fl = enc.state_fxx[0].frame_length;
622 let (s0, s1) = enc.state_fxx.split_at_mut(1);
623 for n in 0..fl {
624 s0[0].input_buf[ix0 + n + 2] = ((s0[0].input_buf[ix0 + n + 2] as i32
625 + s1[0].input_buf[ix1 + n + 2] as i32)
626 >> 1) as i16;
627 }
628 }
629 enc.state_fxx[0].input_buf_ix += n_to_buffer as usize;
630 } else {
631 buf[..nf].copy_from_slice(&samples_in[in_pos..in_pos + nf]);
632 resample(
633 &mut enc.resampler[0],
634 &mut enc.state_fxx[0].input_buf[ix0 + 2..],
635 &buf,
636 nf,
637 );
638 enc.state_fxx[0].input_buf_ix += n_to_buffer as usize;
639 }
640 in_pos += nf * n_ch_api;
641 n_left -= nf as i32;
642 enc.allow_bandwidth_switch = false;
643
644 if enc.state_fxx[0].input_buf_ix < enc.state_fxx[0].frame_length {
645 break;
646 }
647
648 if enc.state_fxx[0].n_frames_encoded == 0 && !prefill {
649 let npp0 = enc.state_fxx[0].n_frames_per_packet;
650 let icdf0 = (256 - (256i32 >> (((npp0 + 1) * n_ch_int) as u32))) as u8;
651 range.enc_icdf(0, &[icdf0, 0], 8);
652 curr_nbits_lbrr = range.tell() as i32;
653 for n in 0..n_ch_int {
654 let npp_n = enc.state_fxx[n].n_frames_per_packet;
655 let mut lbrr_symbol = 0i32;
656 for i in 0..npp_n {
657 lbrr_symbol |= (enc.state_fxx[n].lbrr_flags[i] as i32) << i;
658 }
659 enc.state_fxx[n].lbrr_flag = lbrr_symbol > 0;
660 if lbrr_symbol != 0 && npp_n > 1 {
661 let icdf: &[u8] = if npp_n == 2 {
662 &LBRR_FLAGS_2_ICDF
663 } else {
664 &LBRR_FLAGS_3_ICDF
665 };
666 range.enc_icdf((lbrr_symbol - 1) as usize, icdf, 8);
667 }
668 }
669 for i in 0..npp0 {
670 for n in 0..n_ch_int {
671 if enc.state_fxx[n].lbrr_flags[i] {
672 if n_ch_int == 2 && n == 0 {
673 stereo_encode_pred(range, &enc.s_stereo.pred_ix[i]);
674 if !enc.state_fxx[1].lbrr_flags[i] {
675 stereo_encode_mid_only(range, enc.s_stereo.mid_only_flags[i]);
676 }
677 }
678 let cond = if i > 0 && enc.state_fxx[n].lbrr_flags[i - 1] {
679 CondCoding::Conditionally
680 } else {
681 CondCoding::Independently
682 };
683 encode_indices(&mut enc.state_fxx[n], range, i, true, cond);
684 let st = &enc.state_fxx[n];
685 let idx = st.indices_lbrr[i];
686 encode_pulses(
687 range,
688 idx.signal_type,
689 idx.quant_offset_type,
690 &st.pulses_lbrr[i],
691 st.frame_length,
692 );
693 }
694 }
695 }
696 for n in 0..n_ch_int {
697 enc.state_fxx[n].lbrr_flags = [false; MAX_FRAMES_PER_PACKET];
698 }
699 curr_nbits_lbrr = range.tell() as i32 - curr_nbits_lbrr;
700 }
701
702 hp_variable_cutoff(&mut enc.state_fxx[0]);
703
704 let pms = control.payload_size_ms as i32;
705 let mut n_bits = (control.bit_rate * pms) / 1000;
706 if !prefill {
707 if curr_nbits_lbrr < 10 {
708 enc.n_bits_used_lbrr = 0;
709 } else if enc.n_bits_used_lbrr < 10 {
710 enc.n_bits_used_lbrr = curr_nbits_lbrr;
711 } else {
712 enc.n_bits_used_lbrr = (enc.n_bits_used_lbrr + curr_nbits_lbrr) / 2;
713 }
714 n_bits -= enc.n_bits_used_lbrr;
715 }
716 n_bits /= enc.state_fxx[0].n_frames_per_packet as i32;
717 let mut target_rate = if pms == 10 { n_bits * 100 } else { n_bits * 50 };
718 target_rate -= (enc.n_bits_exceeded * 1000) / BITRESERVOIR_DECAY_TIME_MS;
719 if !prefill && enc.state_fxx[0].n_frames_encoded > 0 {
720 let nfe = enc.state_fxx[0].n_frames_encoded as i32;
721 let bits_balance = range.tell() as i32 - enc.n_bits_used_lbrr - n_bits * nfe;
722 target_rate -= (bits_balance * 1000) / BITRESERVOIR_DECAY_TIME_MS;
723 }
724 target_rate = silk_limit(target_rate, control.bit_rate, 5000);
725
726 let mut ms_rates = [0i32; 2];
727 if n_ch_int == 2 {
728 let nfe = enc.state_fxx[0].n_frames_encoded;
729 let fs0 = enc.state_fxx[0].fs_khz;
730 let fl = enc.state_fxx[0].frame_length;
731 let mut ix = enc.s_stereo.pred_ix[nfe];
732 let mut mo = enc.s_stereo.mid_only_flags[nfe];
733 {
734 let (s0, s1) = enc.state_fxx.split_at_mut(1);
735 let speech_act = s0[0].speech_activity_q8;
736 stereo_lr_to_ms(
737 &mut enc.s_stereo,
738 &mut s0[0].input_buf,
739 &mut s1[0].input_buf,
740 &mut ix,
741 &mut mo,
742 &mut ms_rates,
743 target_rate,
744 speech_act,
745 control.to_mono,
746 fs0,
747 fl,
748 );
749 }
750 enc.s_stereo.pred_ix[nfe] = ix;
751 enc.s_stereo.mid_only_flags[nfe] = mo;
752 if mo == 0 {
753 if enc.prev_decode_only_middle {
754 let st1 = &mut enc.state_fxx[1];
755 st1.s_shape = ShapeState::default();
756 st1.s_nsq = NsqState::default();
757 st1.prev_nlsfq_q15 = [0; MAX_LPC_ORDER];
758 let st1 = &mut enc.state_fxx[1];
759 st1.s_lp.in_lp_state = [0; 2];
760 st1.prev_lag = 100;
761 st1.s_nsq.lag_prev = 100;
762 st1.s_shape.last_gain_index = 10;
763 st1.prev_signal_type = TYPE_NO_VOICE_ACTIVITY;
764 st1.s_nsq.prev_gain_q16 = 65536;
765 st1.first_frame_after_reset = true;
766 }
767 encode_do_vad(&mut enc.state_fxx[1], activity);
768 } else {
769 enc.state_fxx[1].vad_flags[nfe] = false;
770 }
771 if !prefill {
772 stereo_encode_pred(range, &enc.s_stereo.pred_ix[nfe]);
773 if !enc.state_fxx[1].vad_flags[nfe] {
774 stereo_encode_mid_only(range, enc.s_stereo.mid_only_flags[nfe]);
775 }
776 }
777 } else {
778 let mid = enc.s_stereo.s_mid;
779 enc.state_fxx[0].input_buf[0] = mid[0];
780 enc.state_fxx[0].input_buf[1] = mid[1];
781 let fl = enc.state_fxx[0].frame_length;
782 enc.s_stereo.s_mid = [
783 enc.state_fxx[0].input_buf[fl],
784 enc.state_fxx[0].input_buf[fl + 1],
785 ];
786 }
787
788 encode_do_vad(&mut enc.state_fxx[0], activity);
789
790 for n in 0..n_ch_int {
791 let mut max_bits = control.max_bits;
792 if tot_blocks == 2 && curr_block == 0 {
793 max_bits = max_bits * 3 / 5;
794 } else if tot_blocks == 3 {
795 if curr_block == 0 {
796 max_bits = max_bits * 2 / 5;
797 } else if curr_block == 1 {
798 max_bits = max_bits * 3 / 4;
799 }
800 }
801 let mut use_cbr = control.use_cbr && curr_block == tot_blocks - 1;
802 let channel_rate = if n_ch_int == 1 {
803 target_rate
804 } else {
805 if n == 0 && ms_rates[1] > 0 {
806 use_cbr = false;
807 max_bits -= control.max_bits / (tot_blocks * 2);
808 }
809 ms_rates[n]
810 };
811 if channel_rate > 0 {
812 control_snr(&mut enc.state_fxx[n], channel_rate);
813 let nfe0 = enc.state_fxx[0].n_frames_encoded as i32;
814 let cond = if nfe0 - n as i32 <= 0 {
815 CondCoding::Independently
816 } else if n > 0 && enc.prev_decode_only_middle {
817 CondCoding::IndependentlyNoLtpScaling
818 } else {
819 CondCoding::Conditionally
820 };
821 encode_frame(
822 &mut enc.state_fxx[n],
823 n_bytes_out,
824 range,
825 cond,
826 max_bits,
827 use_cbr,
828 );
829 }
830 enc.state_fxx[n].controlled_since_last_payload = false;
831 enc.state_fxx[n].input_buf_ix = 0;
832 enc.state_fxx[n].n_frames_encoded += 1;
833 }
834 let nfe = enc.state_fxx[0].n_frames_encoded;
835 enc.prev_decode_only_middle = enc.s_stereo.mid_only_flags[nfe - 1] != 0;
836
837 if *n_bytes_out > 0
838 && enc.state_fxx[0].n_frames_encoded == enc.state_fxx[0].n_frames_per_packet
839 {
840 let mut flags = 0u32;
841 for n in 0..n_ch_int {
842 let st = &enc.state_fxx[n];
843 for i in 0..st.n_frames_per_packet {
844 flags <<= 1;
845 flags |= st.vad_flags[i] as u32;
846 }
847 flags <<= 1;
848 flags |= st.lbrr_flag as u32;
849 }
850 if !prefill {
851 let nbits = ((enc.state_fxx[0].n_frames_per_packet + 1) * n_ch_int) as u32;
852 range.patch_initial_bits(flags, nbits);
853 }
854 if enc.state_fxx[0].in_dtx && (n_ch_int == 1 || enc.state_fxx[1].in_dtx) {
855 *n_bytes_out = 0;
856 }
857 enc.n_bits_exceeded += *n_bytes_out * 8;
858 enc.n_bits_exceeded -= (control.bit_rate * pms) / 1000;
859 enc.n_bits_exceeded = silk_limit(enc.n_bits_exceeded, 0, 10000);
860 let thr = smlawb(
861 SPEECH_ACT_THR_SWITCH_Q8,
862 SPEECH_ACT_SLOPE_Q24,
863 enc.time_since_switch_allowed_ms,
864 );
865 if enc.state_fxx[0].speech_activity_q8 < thr {
866 enc.allow_bandwidth_switch = true;
867 enc.time_since_switch_allowed_ms = 0;
868 } else {
869 enc.allow_bandwidth_switch = false;
870 enc.time_since_switch_allowed_ms += pms;
871 }
872 }
873 if n_left == 0 {
874 break;
875 }
876 curr_block += 1;
877 }
878
879 enc.n_prev_channels_internal = n_ch_int;
880 control.allow_bandwidth_switch = enc.allow_bandwidth_switch;
881 control.in_wb_mode_without_variable_lp =
882 enc.state_fxx[0].fs_khz == 16 && enc.state_fxx[0].s_lp.mode == 0;
883 control.internal_sample_rate = enc.state_fxx[0].fs_khz as i32 * 1000;
884 control.stereo_width_q14 = if control.to_mono {
885 0
886 } else {
887 enc.s_stereo.smth_width_q14 as i32
888 };
889 if prefill {
890 control.payload_size_ms = tmp_payload_size_ms;
891 control.complexity = tmp_complexity;
892 for n in 0..n_ch_int {
893 enc.state_fxx[n].controlled_since_last_payload = false;
894 enc.state_fxx[n].prefill_flag = false;
895 }
896 }
897 let signal_type = enc.state_fxx[0].indices.signal_type as i32;
898 let quant_offset_type = enc.state_fxx[0].indices.quant_offset_type as usize;
899 control.signal_type = signal_type;
900 control.offset =
901 QUANTIZATION_OFFSETS_Q10[(signal_type >> 1) as usize][quant_offset_type] as i32;
902}