forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

opus.rs364 lines, 11.2 KiBHistoryRawDownload
1use super::api::{EncControl, SilkEnc, init_encoder, silk_encode};
2use crate::range::RangeEncoder;
3use crate::silk_fix::{lin2log, log2lin, smlawb};
4
5const VARIABLE_HP_MIN_CUTOFF_HZ: i32 = 60;
6const VARIABLE_HP_SMTH_COEF2_Q16: i32 = (0.015f64 * 65536.0 + 0.5) as i32;
7
8/// What `opus_encode_frame_native` hands `silk_Encode` for one frame.
9#[derive(Clone, Copy, Debug)]
10pub(crate) struct SilkFrame {
11 pub(crate) bitrate: i32,
12 pub(crate) max_data_bytes: usize,
13 pub(crate) redundancy_bytes: i32,
14 pub(crate) reserved_bits: i32,
15 pub(crate) vbr: bool,
16 pub(crate) hybrid: bool,
17 pub(crate) swb: bool,
18 pub(crate) internal_khz: i32,
19 pub(crate) stream_channels: usize,
20 pub(crate) to_mono: bool,
21 pub(crate) fec: bool,
22 pub(crate) lbrr_coded: bool,
23 pub(crate) loss_perc: i32,
24 pub(crate) complexity: i32,
25}
26
27/// libopus's SILK layer: `silk_encoder` and its Opus-level rate rules.
28#[derive(Clone, Debug)]
29pub(crate) struct SilkLayer {
30 enc: Box<SilkEnc>,
31 ctl: EncControl,
32 fs: i32,
33 channels: usize,
34 pcm: Vec<i16>,
35 nonfinal: bool,
36}
37
38pub(crate) fn bitrate_to_bits(bitrate: i32, fs: i32, frame_size: i32) -> i32 {
39 bitrate * 6 / (6 * fs / frame_size)
40}
41
42pub(crate) fn bits_to_bitrate(bits: i32, fs: i32, frame_size: i32) -> i32 {
43 bits * (6 * fs / frame_size) / 6
44}
45
46/// libopus `compute_silk_rate_for_hybrid`.
47pub(crate) fn silk_rate_for_hybrid(
48 rate: i32,
49 swb: bool,
50 frame20ms: bool,
51 vbr: bool,
52 fec: bool,
53 channels: i32,
54) -> i32 {
55 const RATE_TABLE: [[i32; 5]; 7] = [
56 [0, 0, 0, 0, 0],
57 [12000, 10000, 10000, 11000, 11000],
58 [16000, 13500, 13500, 15000, 15000],
59 [20000, 16000, 16000, 18000, 18000],
60 [24000, 18000, 18000, 21000, 21000],
61 [32000, 22000, 22000, 28000, 28000],
62 [64000, 38000, 38000, 50000, 50000],
63 ];
64 let rate = rate / channels;
65 let entry = 1 + usize::from(frame20ms) + 2 * usize::from(fec);
66 let n = RATE_TABLE.len();
67 let mut i = 1;
68 while i < n && RATE_TABLE[i][0] <= rate {
69 i += 1;
70 }
71 let mut silk_rate = if i == n {
72 RATE_TABLE[i - 1][entry] + (rate - RATE_TABLE[i - 1][0]) / 2
73 } else {
74 let (lo, hi) = (RATE_TABLE[i - 1][entry], RATE_TABLE[i][entry]);
75 let (x0, x1) = (RATE_TABLE[i - 1][0], RATE_TABLE[i][0]);
76 (lo * (x1 - rate) + hi * (rate - x0)) / (x1 - x0)
77 };
78 if !vbr {
79 silk_rate += 100;
80 }
81 if swb {
82 silk_rate += 300;
83 }
84 silk_rate *= channels;
85 if channels == 2 && rate >= 12000 {
86 silk_rate -= 1000;
87 }
88 silk_rate
89}
90
91fn float2int16(x: f32) -> i16 {
92 (x * 32768.0).clamp(-32768.0, 32767.0).round_ties_even() as i16
93}
94
95impl SilkLayer {
96 pub(crate) fn new(fs: u32, channels: usize) -> SilkLayer {
97 let ctl = EncControl {
98 n_channels_api: channels,
99 n_channels_internal: channels,
100 api_sample_rate: fs as i32,
101 max_internal_sample_rate: 16000,
102 min_internal_sample_rate: 8000,
103 desired_internal_sample_rate: 16000,
104 payload_size_ms: 20,
105 bit_rate: 25000,
106 complexity: 9,
107 ..EncControl::default()
108 };
109 SilkLayer {
110 enc: Box::new(init_encoder(channels)),
111 ctl,
112 fs: fs as i32,
113 channels,
114 pcm: Vec::new(),
115 nonfinal: false,
116 }
117 }
118
119 /// `silk_InitEncoder` after a CELT stretch (libopus `prefill=1` without the prefill).
120 pub(crate) fn reset(&mut self) {
121 *self.enc = init_encoder(self.channels);
122 }
123
124 pub(crate) fn hp_smth1_q15(&self) -> i32 {
125 self.enc.state_fxx[0].variable_hp_smth1_q15
126 }
127
128 pub(crate) fn allow_bandwidth_switch(&self) -> bool {
129 self.ctl.allow_bandwidth_switch
130 }
131
132 pub(crate) fn in_wb_mode_without_variable_lp(&self) -> bool {
133 self.ctl.in_wb_mode_without_variable_lp
134 }
135
136 pub(crate) fn set_nonfinal(&mut self, on: bool) {
137 self.nonfinal = on;
138 }
139
140 fn configure(&mut self, f: &SilkFrame, frame_size: usize) -> (i32, i32) {
141 let fs = self.fs;
142 let fsz = frame_size as i32;
143 let bits_target = (8 * (f.max_data_bytes as i32 - f.redundancy_bytes))
144 .min(bitrate_to_bits(f.bitrate, fs, fsz))
145 - 8;
146 let total_bitrate = bits_to_bitrate(bits_target, fs, fsz);
147 let ctl = &mut self.ctl;
148 ctl.bit_rate = if f.hybrid {
149 silk_rate_for_hybrid(
150 total_bitrate,
151 f.swb,
152 fs == 50 * fsz,
153 f.vbr,
154 f.lbrr_coded,
155 f.stream_channels as i32,
156 )
157 } else {
158 total_bitrate
159 };
160 let bit_rate = ctl.bit_rate;
161 ctl.payload_size_ms = (1000 * fsz / fs) as usize;
162 ctl.n_channels_api = self.channels;
163 ctl.n_channels_internal = f.stream_channels;
164 ctl.to_mono = f.to_mono;
165 ctl.desired_internal_sample_rate = f.internal_khz.min(16) * 1000;
166 ctl.min_internal_sample_rate = if f.hybrid { 16000 } else { 8000 };
167 ctl.max_internal_sample_rate = 16000;
168 if !f.hybrid {
169 let mut effective_max_rate = bits_to_bitrate(f.max_data_bytes as i32 * 8, fs, fsz);
170 if fs / fsz > 50 {
171 effective_max_rate = effective_max_rate * 2 / 3;
172 }
173 if effective_max_rate < 8000 {
174 ctl.max_internal_sample_rate = 12000;
175 ctl.desired_internal_sample_rate = ctl.desired_internal_sample_rate.min(12000);
176 }
177 if effective_max_rate < 7000 {
178 ctl.max_internal_sample_rate = 8000;
179 ctl.desired_internal_sample_rate = ctl.desired_internal_sample_rate.min(8000);
180 }
181 }
182 ctl.use_cbr = !f.vbr;
183 ctl.use_in_band_fec = f.fec;
184 ctl.lbrr_coded = f.lbrr_coded;
185 ctl.packet_loss_percentage = f.loss_perc;
186 ctl.complexity = f.complexity;
187 ctl.max_bits = (f.max_data_bytes as i32 - 1) * 8 - f.reserved_bits;
188 if ctl.use_cbr {
189 if f.hybrid {
190 let other_bits = (ctl.max_bits - ctl.bit_rate * fsz / fs).max(0);
191 ctl.max_bits = (ctl.max_bits - other_bits * 3 / 4).max(0);
192 ctl.use_cbr = false;
193 }
194 } else if f.hybrid {
195 let max_bitrate = silk_rate_for_hybrid(
196 ctl.max_bits * fs / fsz,
197 f.swb,
198 fs == 50 * fsz,
199 f.vbr,
200 f.lbrr_coded,
201 f.stream_channels as i32,
202 );
203 ctl.max_bits = bitrate_to_bits(max_bitrate, fs, fsz);
204 }
205 (bit_rate, total_bitrate)
206 }
207
208 pub(crate) fn encode(
209 &mut self,
210 pcm: &[f32],
211 frame_size: usize,
212 f: &SilkFrame,
213 activity: i32,
214 range: &mut RangeEncoder,
215 ) -> SilkResult {
216 self.pcm.clear();
217 self.pcm.extend(
218 pcm[..frame_size * self.channels]
219 .iter()
220 .map(|&x| float2int16(x)),
221 );
222 let (bit_rate, total_bitrate) = self.configure(f, frame_size);
223 let mut n_bytes = 0;
224 silk_encode(
225 &mut self.enc,
226 &mut self.ctl,
227 &self.pcm,
228 frame_size,
229 range,
230 &mut n_bytes,
231 0,
232 activity,
233 );
234 self.ctl.opus_can_switch = self.ctl.switch_ready && !self.nonfinal;
235 SilkResult {
236 internal_khz: self.ctl.internal_sample_rate / 1000,
237 total_bit_rate: total_bitrate,
238 bit_rate,
239 offset: self.ctl.offset,
240 signal_type: self.ctl.signal_type,
241 stereo_width_q14: self.ctl.stereo_width_q14,
242 opus_can_switch: self.ctl.opus_can_switch,
243 }
244 }
245
246 pub(crate) fn prefill(
247 &mut self,
248 pcm: &[f32],
249 frame_size: usize,
250 f: &SilkFrame,
251 activity: i32,
252 flag: i32,
253 range: &mut RangeEncoder,
254 ) {
255 self.pcm.clear();
256 self.pcm.extend(pcm.iter().map(|&x| float2int16(x)));
257 self.configure(f, frame_size);
258 let n = self.pcm.len() / self.channels;
259 let mut n_bytes = 0;
260 silk_encode(
261 &mut self.enc,
262 &mut self.ctl,
263 &self.pcm,
264 n,
265 range,
266 &mut n_bytes,
267 flag,
268 activity,
269 );
270 self.ctl.opus_can_switch = false;
271 }
272}
273
274#[derive(Clone, Copy, Debug)]
275pub(crate) struct SilkResult {
276 pub(crate) internal_khz: i32,
277 pub(crate) total_bit_rate: i32,
278 pub(crate) bit_rate: i32,
279 pub(crate) offset: i32,
280 pub(crate) signal_type: i32,
281 pub(crate) stereo_width_q14: i32,
282 pub(crate) opus_can_switch: bool,
283}
284
285/// libopus `opus_encoder.c`'s Opus-level input filter state: `hp_cutoff`
286/// (VoIP, variable cutoff that follows SILK's pitch-driven estimate) or the
287/// 3 Hz `dc_reject`, applied once to what every layer reads.
288#[derive(Clone, Debug)]
289pub(crate) struct InputFilter {
290 mem: [f32; 4],
291 smth2_q15: i32,
292}
293
294pub(crate) fn hp_min_smth1_q15() -> i32 {
295 lin2log(VARIABLE_HP_MIN_CUTOFF_HZ) << 8
296}
297
298impl InputFilter {
299 pub(crate) fn new() -> InputFilter {
300 InputFilter {
301 mem: [0.0; 4],
302 smth2_q15: hp_min_smth1_q15(),
303 }
304 }
305
306 #[allow(clippy::approx_constant)]
307 pub(crate) fn hp_cutoff(
308 &mut self,
309 pcm: &[f32],
310 out: &mut [f32],
311 smth1_q15: i32,
312 channels: usize,
313 fs: i32,
314 ) {
315 self.smth2_q15 = smlawb(
316 self.smth2_q15,
317 smth1_q15 - self.smth2_q15,
318 VARIABLE_HP_SMTH_COEF2_Q16,
319 );
320 let cutoff_hz = log2lin(self.smth2_q15 >> 8);
321 let fc_q19 = ((1.5f64 * 3.14159 / 1000.0 * (1 << 19) as f64 + 0.5) as i32 as i16 as i32
322 * cutoff_hz as i16 as i32)
323 / (fs / 1000);
324 let r_q28 = (1i32 << 28) - ((0.92f64 * 512.0 + 0.5) as i32) * fc_q19;
325 let b = [r_q28, -r_q28 << 1, r_q28];
326 let r_q22 = r_q28 >> 6;
327 let smulww = |a: i32, b: i32| ((a as i64 * b as i64) >> 16) as i32;
328 let a = [
329 smulww(r_q22, smulww(fc_q19, fc_q19) - (2 << 22)),
330 smulww(r_q22, r_q22),
331 ];
332 let s = 1.0 / (1i32 << 28) as f32;
333 let (a0, a1) = (a[0] as f32 * s, a[1] as f32 * s);
334 let (b0, b1, b2) = (b[0] as f32 * s, b[1] as f32 * s, b[2] as f32 * s);
335 let c = channels;
336 for ch in 0..c {
337 let (mut s0, mut s1) = (self.mem[2 * ch], self.mem[2 * ch + 1]);
338 for k in 0..out.len() / c {
339 let x = pcm[k * c + ch];
340 let vout = s0 + b0 * x;
341 s0 = s1 - vout * a0 + b1 * x;
342 s1 = -vout * a1 + b2 * x + 1e-30;
343 out[k * c + ch] = vout;
344 }
345 self.mem[2 * ch] = s0;
346 self.mem[2 * ch + 1] = s1;
347 }
348 }
349
350 pub(crate) fn dc_reject(&mut self, pcm: &[f32], out: &mut [f32], channels: usize, fs: i32) {
351 let coef = 6.3 * 3.0 / fs as f32;
352 let coef2 = 1.0 - coef;
353 let c = channels;
354 for ch in 0..c {
355 let mut m = self.mem[2 * ch];
356 for k in 0..out.len() / c {
357 let x = pcm[k * c + ch];
358 out[k * c + ch] = x - m;
359 m = coef * x + 1e-30 + coef2 * m;
360 }
361 self.mem[2 * ch] = m;
362 }
363 }
364}