1use super::{Decoder, Encoder};
2use crate::{media::PcmBuf, media::Sample};
3pub enum Bitrate {
4 Mode1_64000,
5 Mode2_56000,
6 Mode3_48000,
7}
8
9const QUANT_DECISION_LEVEL: [i32; 32] = [
11 0, 35, 72, 110, 150, 190, 233, 276, 323, 370, 422, 473, 530, 587, 650, 714, 786, 858, 940,
12 1023, 1121, 1219, 1339, 1458, 1612, 1765, 1980, 2195, 2557, 2919, 0, 0,
13];
14
15const QUANT_INDEX_NEG: [i32; 32] = [
17 0, 63, 62, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11,
18 10, 9, 8, 7, 6, 5, 4, 0,
19];
20
21const QUANT_INDEX_POS: [i32; 32] = [
23 0, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39,
24 38, 37, 36, 35, 34, 33, 32, 0,
25];
26
27const SCALE_FACTOR_ADJUST_LOW: [i32; 8] = [-60, -30, 58, 172, 334, 538, 1198, 3042];
29
30const LOG_SCALE_FACTOR_MAP: [i32; 16] = [0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0];
32
33const INV_LOG_BASE: [i32; 32] = [
35 2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834,
36 2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371, 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008,
37];
38
39const QUANT_MULT_LOW_4BIT: [i32; 16] = [
41 0, -20456, -12896, -8968, -6288, -4240, -2584, -1200, 20456, 12896, 8968, 6288, 4240, 2584,
42 1200, 0,
43];
44
45const QUANT_MULT_HIGH_2BIT: [i32; 4] = [-7408, -1616, 7408, 1616];
47
48const QMF_FILTER_COEFS: [i32; 12] = [3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11];
50
51const HIGH_QUANT_INDEX_NEG: [i32; 3] = [0, 1, 0];
53
54const HIGH_QUANT_INDEX_POS: [i32; 3] = [0, 3, 2];
56
57const SCALE_FACTOR_ADJUST_HIGH: [i32; 3] = [0, -214, 798];
59
60const HIGH_LOG_SCALE_MAP: [i32; 4] = [2, 1, 2, 1];
62
63const QUANT_MULT_56K: [i32; 32] = [
65 -280, -280, -23352, -17560, -14120, -11664, -9752, -8184, -6864, -5712, -4696, -3784, -2960,
66 -2208, -1520, -880, 23352, 17560, 14120, 11664, 9752, 8184, 6864, 5712, 4696, 3784, 2960, 2208,
67 1520, 880, 280, -280,
68];
69
70const QUANT_MULT_64K: [i32; 64] = [
72 -136, -136, -136, -136, -24808, -21904, -19008, -16704, -14984, -13512, -12280, -11192, -10232,
73 -9360, -8576, -7856, -7192, -6576, -6000, -5456, -4944, -4464, -4008, -3576, -3168, -2776,
74 -2400, -2032, -1688, -1360, -1040, -728, 24808, 21904, 19008, 16704, 14984, 13512, 12280,
75 11192, 10232, 9360, 8576, 7856, 7192, 6576, 6000, 5456, 4944, 4464, 4008, 3576, 3168, 2776,
76 2400, 2032, 1688, 1360, 1040, 728, 432, 136, -432, -136,
77];
78
79impl Bitrate {
80 fn bits_per_sample(&self) -> i32 {
81 match self {
82 Bitrate::Mode1_64000 => 8,
83 Bitrate::Mode2_56000 => 7,
84 Bitrate::Mode3_48000 => 6,
85 }
86 }
87}
88
89#[derive(Default)]
92struct G722Band {
93 signal_estimate: i32,
95 pole_filter_output: i32,
97 zero_filter_output: i32,
99 reconstructed_signal: [i32; 3],
101 pole_coefficients: [i32; 3],
103 pole_coefficients_temp: [i32; 3],
105 partial_reconstructed: [i32; 3],
107 difference_signal: [i32; 7],
109 zero_coefficients: [i32; 7],
111 zero_coefficients_temp: [i32; 7],
113 sign_bits: [i32; 7],
115 log_scale_factor: i32,
117 quantizer_step_size: i32,
119}
120
121fn saturate(amp: i32) -> i32 {
122 amp.clamp(i16::MIN as i32, i16::MAX as i32)
123}
124
125fn block4(band: &mut G722Band, d: i32) {
129 band.difference_signal[0] = d;
132 band.reconstructed_signal[0] = saturate(band.signal_estimate + d);
134
135 band.partial_reconstructed[0] = saturate(band.zero_filter_output + d);
138
139 band.sign_bits[0] = band.partial_reconstructed[0] >> 15;
142 band.sign_bits[1] = band.partial_reconstructed[1] >> 15;
143 band.sign_bits[2] = band.partial_reconstructed[2] >> 15;
144
145 let a1_scaled = saturate(band.pole_coefficients[1] << 2);
147
148 let mut a2_update = if band.sign_bits[0] == band.sign_bits[1] {
150 -a1_scaled
151 } else {
152 a1_scaled
153 };
154 a2_update = a2_update.min(32767);
155
156 let mut a2_adj = a2_update >> 7;
158 if band.sign_bits[0] == band.sign_bits[2] {
159 a2_adj += 128;
160 } else {
161 a2_adj -= 128;
162 }
163
164 a2_adj += (band.pole_coefficients[2] * 32512) >> 15;
166
167 band.pole_coefficients_temp[2] = a2_adj.clamp(-12288, 12288);
169
170 band.sign_bits[0] = band.partial_reconstructed[0] >> 15; band.sign_bits[1] = band.partial_reconstructed[1] >> 15; let sign_factor = if band.sign_bits[0] == band.sign_bits[1] {
176 192
177 } else {
178 -192
179 };
180 let leakage = (band.pole_coefficients[1] * 32640) >> 15;
181
182 band.pole_coefficients_temp[1] = saturate(sign_factor + leakage);
184
185 let limit = saturate(15360 - band.pole_coefficients_temp[2]);
187
188 if band.pole_coefficients_temp[1] > limit {
191 band.pole_coefficients_temp[1] = limit;
192 } else if band.pole_coefficients_temp[1] < -limit {
193 band.pole_coefficients_temp[1] = -limit;
194 }
195
196 let step_size = if d == 0 { 0 } else { 128 };
198 band.sign_bits[0] = d >> 15; for i in 1..7 {
202 band.sign_bits[i] = band.difference_signal[i] >> 15; let adj = if band.sign_bits[i] == band.sign_bits[0] {
205 step_size
206 } else {
207 -step_size
208 };
209 let leakage = (band.zero_coefficients[i] * 32640) >> 15;
211 band.zero_coefficients_temp[i] = saturate(adj + leakage);
213 }
214
215 band.difference_signal.copy_within(0..6, 1);
218
219 band.zero_coefficients
221 .copy_from_slice(&band.zero_coefficients_temp);
222
223 band.reconstructed_signal.copy_within(0..2, 1);
225 band.partial_reconstructed.copy_within(0..2, 1);
226 band.pole_coefficients[1] = band.pole_coefficients_temp[1];
227 band.pole_coefficients[2] = band.pole_coefficients_temp[2];
228
229 let r1_adj = saturate(band.reconstructed_signal[1] << 1); let pole1 = (band.pole_coefficients[1] * r1_adj) >> 15;
233
234 let r2_adj = saturate(band.reconstructed_signal[2] << 1); let pole2 = (band.pole_coefficients[2] * r2_adj) >> 15;
236
237 band.pole_filter_output = saturate(pole1 + pole2);
239
240 band.zero_filter_output = 0;
243 for i in 1..7 {
244 let d_adj = saturate(band.difference_signal[i] << 1); band.zero_filter_output += (band.zero_coefficients[i] * d_adj) >> 15;
246 }
247 band.zero_filter_output = saturate(band.zero_filter_output);
248
249 band.signal_estimate = saturate(band.pole_filter_output + band.zero_filter_output);
252}
253
254pub struct G722Encoder {
255 packed: bool,
256 eight_k: bool,
257 bits_per_sample: i32,
258 x: [i32; 24],
259 band: [G722Band; 2],
260 out_buffer: u32,
261 out_bits: i32,
262}
263
264pub struct G722Decoder {
265 packed: bool,
266 eight_k: bool,
267 bits_per_sample: i32,
268 x: [i32; 24],
269 band: [G722Band; 2],
270 in_buffer: u32,
271 in_bits: i32,
272}
273
274impl G722Encoder {
275 pub fn new() -> Self {
276 Self::with_options(Bitrate::Mode1_64000, false, false)
277 }
278
279 pub fn with_options(rate: Bitrate, eight_k: bool, packed: bool) -> Self {
281 let mut encoder = Self {
282 packed,
283 eight_k,
284 bits_per_sample: rate.bits_per_sample(),
285 x: [0; 24],
286 band: [G722Band::default(), G722Band::default()],
287 out_buffer: 0,
288 out_bits: 0,
289 };
290
291 encoder.band[0].log_scale_factor = 32 << 2; encoder.band[1].log_scale_factor = 8 << 2; encoder
296 }
297
298 fn g722_encode(&mut self, amp: &[i16]) -> Vec<u8> {
301 let mut output = Vec::with_capacity(amp.len() / 2 + 1);
303
304 let mut xlow: i32;
306 let mut xhigh: i32 = 0;
307 let mut input_idx = 0;
308
309 while input_idx < amp.len() {
311 if self.eight_k {
313 xlow = amp[input_idx] as i32 >> 1;
315 input_idx += 1;
316 } else {
317 self.x.copy_within(2..24, 0);
320
321 self.x[22] = amp[input_idx] as i32;
323 input_idx += 1;
324 self.x[23] = if input_idx < amp.len() {
325 amp[input_idx] as i32
326 } else {
327 0 };
329 input_idx += 1;
330
331 let mut sumeven = 0;
333 let mut sumodd = 0;
334 for i in 0..12 {
335 sumodd += self.x[2 * i] * QMF_FILTER_COEFS[i];
336 sumeven += self.x[2 * i + 1] * QMF_FILTER_COEFS[11 - i];
337 }
338
339 xlow = (sumeven + sumodd) >> 14;
341 xhigh = (sumeven - sumodd) >> 14;
342 }
343
344 let code = if self.eight_k {
346 self.encode_low_band(xlow, true)
348 } else {
349 let ilow = self.encode_low_band(xlow, false);
351 let ihigh = self.encode_high_band(xhigh);
352 (ihigh << 6 | ilow) >> (8 - self.bits_per_sample)
353 };
354
355 self.output_code(code, &mut output);
357 }
358
359 if self.packed && self.out_bits > 0 {
361 output.push((self.out_buffer & 0xFF) as u8);
362 }
363
364 output
365 }
366
367 fn encode_low_band(&mut self, xlow: i32, is_eight_k: bool) -> i32 {
370 let el = saturate(xlow - self.band[0].signal_estimate);
372
373 let wd = if el >= 0 { el } else { -(el + 1) };
375
376 let mut quantization_idx = 1;
378 while quantization_idx < 30 {
379 let decision_level =
380 (QUANT_DECISION_LEVEL[quantization_idx] * self.band[0].log_scale_factor) >> 12;
381 if wd < decision_level {
382 break;
383 }
384 quantization_idx += 1;
385 }
386
387 let ilow = if el < 0 {
389 QUANT_INDEX_NEG[quantization_idx]
390 } else {
391 QUANT_INDEX_POS[quantization_idx]
392 };
393
394 let ril = ilow >> 2;
396 let wd2 = QUANT_MULT_LOW_4BIT[ril as usize];
397 let dlow = (self.band[0].log_scale_factor * wd2) >> 15;
398
399 let il4 = LOG_SCALE_FACTOR_MAP[ril as usize];
401 let mut nb = (self.band[0].quantizer_step_size * 127) >> 7;
402 nb += SCALE_FACTOR_ADJUST_LOW[il4 as usize];
403 self.band[0].quantizer_step_size = nb.clamp(0, 18432);
404
405 let wd1 = self.band[0].quantizer_step_size >> 6 & 31;
407 let wd2 = 8 - (self.band[0].quantizer_step_size >> 11);
408 let wd3 = if wd2 < 0 {
409 INV_LOG_BASE[wd1 as usize] << -wd2
410 } else {
411 INV_LOG_BASE[wd1 as usize] >> wd2
412 };
413 self.band[0].log_scale_factor = wd3 << 2;
414
415 block4(&mut self.band[0], dlow);
417
418 if is_eight_k {
420 ((0xc0 | ilow) >> 8) - self.bits_per_sample
421 } else {
422 ilow
423 }
424 }
425
426 fn encode_high_band(&mut self, xhigh: i32) -> i32 {
429 let eh = saturate(xhigh - self.band[1].signal_estimate);
431
432 let wd = if eh >= 0 { eh } else { -(eh + 1) };
434 let decision_level = (564 * self.band[1].log_scale_factor) >> 12;
435
436 let mih = if wd >= decision_level { 2 } else { 1 };
438 let ihigh = if eh < 0 {
439 HIGH_QUANT_INDEX_NEG[mih as usize]
440 } else {
441 HIGH_QUANT_INDEX_POS[mih as usize]
442 };
443
444 let wd2 = QUANT_MULT_HIGH_2BIT[ihigh as usize];
446 let dhigh = (self.band[1].log_scale_factor * wd2) >> 15;
447
448 let ih2 = HIGH_LOG_SCALE_MAP[ihigh as usize];
450 let mut nb = (self.band[1].quantizer_step_size * 127) >> 7;
451 nb += SCALE_FACTOR_ADJUST_HIGH[ih2 as usize];
452 self.band[1].quantizer_step_size = nb.clamp(0, 22528);
453
454 let wd1 = self.band[1].quantizer_step_size >> 6 & 31;
456 let wd2 = 10 - (self.band[1].quantizer_step_size >> 11);
457 let wd3 = if wd2 < 0 {
458 INV_LOG_BASE[wd1 as usize] << -wd2
459 } else {
460 INV_LOG_BASE[wd1 as usize] >> wd2
461 };
462 self.band[1].log_scale_factor = wd3 << 2;
463
464 block4(&mut self.band[1], dhigh);
466
467 ihigh
468 }
469
470 fn output_code(&mut self, code: i32, output: &mut Vec<u8>) {
472 if self.packed {
473 self.out_buffer |= (code as u32) << self.out_bits;
475 self.out_bits += self.bits_per_sample;
476
477 if self.out_bits >= 8 {
479 output.push((self.out_buffer & 0xFF) as u8);
480 self.out_bits -= 8;
481 self.out_buffer >>= 8;
482 }
483 } else {
484 output.push(code as u8);
486 }
487 }
488}
489
490impl G722Decoder {
491 pub fn new() -> Self {
492 Self::with_options(Bitrate::Mode1_64000, false, false)
493 }
494
495 pub fn with_options(rate: Bitrate, packed: bool, eight_k: bool) -> Self {
496 Self {
497 packed,
498 eight_k,
499 bits_per_sample: rate.bits_per_sample(),
500 x: Default::default(),
501 band: Default::default(),
502 in_buffer: 0,
503 in_bits: 0,
504 }
505 }
506
507 fn extract_code(&mut self, data: &[u8], idx: &mut usize) -> i32 {
509 if self.packed {
510 if self.in_bits < self.bits_per_sample {
512 self.in_buffer |= (data[*idx] as u32) << self.in_bits;
513 *idx += 1;
514 self.in_bits += 8;
515 }
516 let code = (self.in_buffer & ((1 << self.bits_per_sample) - 1) as u32) as i32;
517 self.in_buffer >>= self.bits_per_sample;
518 self.in_bits -= self.bits_per_sample;
519 code
520 } else {
521 let code = data[*idx] as i32;
523 *idx += 1;
524 code
525 }
526 }
527
528 fn parse_code(&self, code: i32) -> (i32, i32, i32) {
530 match self.bits_per_sample {
532 7 => {
533 let wd1 = code & 0x1f;
535 let ihigh = (code >> 5) & 0x3;
536 let wd2 = QUANT_MULT_56K[wd1 as usize];
537 (wd1 >> 1, ihigh, wd2)
538 }
539 6 => {
540 let wd1 = code & 0xf;
542 let ihigh = (code >> 4) & 0x3;
543 let wd2 = QUANT_MULT_LOW_4BIT[wd1 as usize];
544 (wd1, ihigh, wd2)
545 }
546 _ => {
547 let wd1 = code & 0x3f;
549 let ihigh = (code >> 6) & 0x3;
550 let wd2 = QUANT_MULT_64K[wd1 as usize];
551 (wd1 >> 2, ihigh, wd2)
552 }
553 }
554 }
555
556 fn process_low_band(&mut self, wd1: i32, wd2: i32) -> i32 {
558 let dequant = (self.band[0].log_scale_factor * wd2) >> 15;
560
561 let rlow = self.band[0].signal_estimate + dequant;
563
564 let rlow = rlow.clamp(-16384, 16383);
566
567 let wd2 = QUANT_MULT_LOW_4BIT[wd1 as usize];
569 let dlowt = (self.band[0].log_scale_factor * wd2) >> 15;
570
571 let wd2 = LOG_SCALE_FACTOR_MAP[wd1 as usize];
573 let mut wd1 = (self.band[0].quantizer_step_size * 127) >> 7;
574 wd1 += SCALE_FACTOR_ADJUST_LOW[wd2 as usize];
575 self.band[0].quantizer_step_size = wd1.clamp(0, 18432);
576
577 let wd1 = (self.band[0].quantizer_step_size >> 6) & 31;
579 let wd2 = 8 - (self.band[0].quantizer_step_size >> 11);
580 let wd3 = if wd2 < 0 {
581 INV_LOG_BASE[wd1 as usize] << -wd2
582 } else {
583 INV_LOG_BASE[wd1 as usize] >> wd2
584 };
585 self.band[0].log_scale_factor = wd3 << 2;
586
587 block4(&mut self.band[0], dlowt);
589
590 rlow
591 }
592
593 fn process_high_band(&mut self, ihigh: i32) -> i32 {
595 let wd2 = QUANT_MULT_HIGH_2BIT[ihigh as usize];
597 let dhigh = (self.band[1].log_scale_factor * wd2) >> 15;
598
599 let rhigh = dhigh + self.band[1].signal_estimate;
601
602 let rhigh = rhigh.clamp(-16384, 16383);
604
605 let wd2 = HIGH_LOG_SCALE_MAP[ihigh as usize];
607 let mut wd1 = (self.band[1].quantizer_step_size * 127) >> 7;
608 wd1 += SCALE_FACTOR_ADJUST_HIGH[wd2 as usize];
609 self.band[1].quantizer_step_size = wd1.clamp(0, 22528);
610
611 let wd1 = (self.band[1].quantizer_step_size >> 6) & 31;
613 let wd2 = 10 - (self.band[1].quantizer_step_size >> 11);
614 let wd3 = if wd2 < 0 {
615 INV_LOG_BASE[wd1 as usize] << -wd2
616 } else {
617 INV_LOG_BASE[wd1 as usize] >> wd2
618 };
619 self.band[1].log_scale_factor = wd3 << 2;
620
621 block4(&mut self.band[1], dhigh);
623
624 rhigh
625 }
626
627 fn apply_qmf_synthesis(&mut self, rlow: i32, rhigh: i32) -> [i16; 2] {
629 self.x.copy_within(2..24, 0);
631
632 self.x[22] = rlow + rhigh;
634 self.x[23] = rlow - rhigh;
635
636 let mut xout1 = 0;
638 let mut xout2 = 0;
639
640 for i in 0..12 {
641 xout2 += self.x[2 * i] * QMF_FILTER_COEFS[i];
642 xout1 += self.x[2 * i + 1] * QMF_FILTER_COEFS[11 - i];
643 }
644
645 [saturate(xout1 >> 11) as i16, saturate(xout2 >> 11) as i16]
647 }
648
649 pub fn decode_frame(&mut self, data: &[u8]) -> PcmBuf {
652 let mut output = Vec::with_capacity(data.len() * 2);
653 let mut idx = 0;
654
655 while idx < data.len() {
656 let code = self.extract_code(data, &mut idx);
658
659 let (wd1, ihigh, wd2) = self.parse_code(code);
661
662 let rlow = self.process_low_band(wd1, wd2);
664
665 if self.eight_k {
666 output.push((rlow << 1) as i16);
668 } else {
669 let rhigh = self.process_high_band(ihigh);
671
672 let samples = self.apply_qmf_synthesis(rlow, rhigh);
674 output.extend_from_slice(&samples);
675 }
676 }
677
678 output
679 }
680}
681
682impl Encoder for G722Encoder {
683 fn encode(&mut self, samples: &[Sample]) -> Vec<u8> {
684 self.g722_encode(samples)
685 }
686
687 fn sample_rate(&self) -> u32 {
688 16000 }
690
691 fn channels(&self) -> u16 {
692 1 }
694}
695
696impl Decoder for G722Decoder {
697 fn decode(&mut self, data: &[u8]) -> PcmBuf {
698 self.decode_frame(data)
699 }
700
701 fn sample_rate(&self) -> u32 {
702 16000
703 }
704
705 fn channels(&self) -> u16 {
706 1
707 }
708}