ec-opus: in-band FEC (SILK LBRR): Encoder::set_inband_fec/set_packet_loss_perc (libopus decide_fec, loss-aware equiv rate, FEC forces SILK/hybrid; mono SILK/hybrid 10/20 ms), Decoder::decode_fec (LBRR decode, hybrid CELT band concealment, PLC fallback); interop with libopus 1.6 both ways; FEC-off output unchanged
Browse files at this commit90e21f2297d9f5fda6eb547a1ff2703e5a6c3467Parent: a31973f8 changed files +368 -38
- crates/ec-opus/src/celt.rs +6 -0
- crates/ec-opus/src/encoder.rs +137 -5
- crates/ec-opus/src/lib.rs +68 -12
- crates/ec-opus/src/silk.rs +54 -9
- crates/ec-opus/src/silk_enc_write.rs +59 -6
- crates/ec-opus/src/stack_budget.rs +5 -5
- crates/ec-opus/tests/conformance.rs +1 -1
- crates/ec-opus/tests/plc.rs +38 -0
crates/ec-opus/src/celt.rsmodified+6 -0
| @@ -2735,6 +2735,12 @@ fn frame_lm(frame_size: usize) -> Result<usize> { | |||
| 2735 | } | 2735 | } |
| 2736 | 2736 | ||
| 2737 | impl CeltDecoder { | 2737 | impl CeltDecoder { |
| 2738 | + /// Sets the band range the next concealment covers (hybrid FEC: 17..end). | ||
| 2739 | + pub fn set_conceal_bands(&mut self, start: usize, end: usize) { | ||
| 2740 | + self.plc.start = start; | ||
| 2741 | + self.plc.end = end.min(NB_BANDS); | ||
| 2742 | + } | ||
| 2743 | + | ||
| 2738 | /// Packet loss concealment for one lost frame of `frame_size` 48 kHz | 2744 | /// Packet loss concealment for one lost frame of `frame_size` 48 kHz |
| 2739 | /// samples: pitch-periodic LPC extension for the first losses, then | 2745 | /// samples: pitch-periodic LPC extension for the first losses, then |
| 2740 | /// band-shaped noise decaying towards the background level. | 2746 | /// band-shaped noise decaying towards the background level. |
crates/ec-opus/src/encoder.rsmodified+137 -5
| @@ -9,6 +9,9 @@ | |||
| 9 | //! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under | 9 | //! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under |
| 10 | //! CELT from band 17 up, one range-coded stream). | 10 | //! CELT from band 17 up, one range-coded stream). |
| 11 | //! | 11 | //! |
| 12 | +//! In-band FEC (SILK LBRR, [`Encoder::set_inband_fec`]) is mono SILK and | ||
| 13 | +//! hybrid 10/20 ms only. | ||
| 14 | +//! | ||
| 12 | //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and | 15 | //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and |
| 13 | //! the coded bandwidth is capped at the input's own Nyquist, so the images | 16 | //! the coded bandwidth is capped at the input's own Nyquist, so the images |
| 14 | //! the stuffing puts there are never coded and the decoder's decimation | 17 | //! the stuffing puts there are never coded and the decoder's decimation |
| @@ -149,6 +152,11 @@ pub struct Encoder { | |||
| 149 | analysis_on: bool, | 152 | analysis_on: bool, |
| 150 | /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). | 153 | /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). |
| 151 | bw_detect: bool, | 154 | bw_detect: bool, |
| 155 | + inband_fec: bool, | ||
| 156 | + packet_loss_perc: u8, | ||
| 157 | + lbrr_coded: bool, | ||
| 158 | + fec_bandwidth: Option<Bandwidth>, | ||
| 159 | + last_silk: Option<u8>, | ||
| 152 | } | 160 | } |
| 153 | 161 | ||
| 154 | fn toc_bandwidth(toc: u8) -> Bandwidth { | 162 | fn toc_bandwidth(toc: u8) -> Bandwidth { |
| @@ -232,6 +240,11 @@ impl Encoder { | |||
| 232 | info: AnalysisInfo::default(), | 240 | info: AnalysisInfo::default(), |
| 233 | analysis_on: crate::celt_enc::analysis_params().0, | 241 | analysis_on: crate::celt_enc::analysis_params().0, |
| 234 | bw_detect: crate::celt_enc::analysis_params().5, | 242 | bw_detect: crate::celt_enc::analysis_params().5, |
| 243 | + inband_fec: false, | ||
| 244 | + packet_loss_perc: 0, | ||
| 245 | + lbrr_coded: false, | ||
| 246 | + fec_bandwidth: None, | ||
| 247 | + last_silk: None, | ||
| 235 | }; | 248 | }; |
| 236 | // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how | 249 | // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how |
| 237 | // the gate rows at `set_libopus_input_alignment` were produced. | 250 | // the gate rows at `set_libopus_input_alignment` were produced. |
| @@ -374,6 +387,16 @@ impl Encoder { | |||
| 374 | self.bitrate = bps.clamp(500, 510_000); | 387 | self.bitrate = bps.clamp(500, 510_000); |
| 375 | } | 388 | } |
| 376 | 389 | ||
| 390 | + /// OPUS_SET_INBAND_FEC: code LBRR (in-band FEC) when the loss rate and bitrate justify it; prefers SILK/hybrid over CELT under loss. | ||
| 391 | + pub fn set_inband_fec(&mut self, on: bool) { | ||
| 392 | + self.inband_fec = on; | ||
| 393 | + } | ||
| 394 | + | ||
| 395 | + /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped). | ||
| 396 | + pub fn set_packet_loss_perc(&mut self, perc: u8) { | ||
| 397 | + self.packet_loss_perc = perc.min(100); | ||
| 398 | + } | ||
| 399 | + | ||
| 377 | /// Current target bitrate. | 400 | /// Current target bitrate. |
| 378 | pub fn bitrate(&self) -> u32 { | 401 | pub fn bitrate(&self) -> u32 { |
| 379 | self.bitrate | 402 | self.bitrate |
| @@ -427,6 +450,9 @@ impl Encoder { | |||
| 427 | self.final_range = 0; | 450 | self.final_range = 0; |
| 428 | self.analysis.reset(); | 451 | self.analysis.reset(); |
| 429 | self.info = AnalysisInfo::default(); | 452 | self.info = AnalysisInfo::default(); |
| 453 | + self.lbrr_coded = false; | ||
| 454 | + self.fec_bandwidth = None; | ||
| 455 | + self.last_silk = None; | ||
| 430 | } | 456 | } |
| 431 | 457 | ||
| 432 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) | 458 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) |
| @@ -442,7 +468,10 @@ impl Encoder { | |||
| 442 | match self.mode { | 468 | match self.mode { |
| 443 | Some(Mode::Celt) | Some(Mode::Hybrid) => None, | 469 | Some(Mode::Celt) | Some(Mode::Hybrid) => None, |
| 444 | Some(Mode::Silk) => { | 470 | Some(Mode::Silk) => { |
| 445 | - let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); | 471 | + let bw = self |
| 472 | + .fec_bandwidth | ||
| 473 | + .or(self.bandwidth) | ||
| 474 | + .unwrap_or_else(|| self.auto_bandwidth()); | ||
| 446 | Some(silk_fs_khz(bw)) | 475 | Some(silk_fs_khz(bw)) |
| 447 | } | 476 | } |
| 448 | None => { | 477 | None => { |
| @@ -452,7 +481,8 @@ impl Encoder { | |||
| 452 | return None; | 481 | return None; |
| 453 | } | 482 | } |
| 454 | let bw = self | 483 | let bw = self |
| 455 | - .bandwidth | 484 | + .fec_bandwidth |
| 485 | + .or(self.bandwidth) | ||
| 456 | .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); | 486 | .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); |
| 457 | // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms): | 487 | // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms): |
| 458 | // cap at Wide so a high equiv rate does not fall through to | 488 | // cap at Wide so a high equiv rate does not fall through to |
| @@ -500,7 +530,8 @@ impl Encoder { | |||
| 500 | return None; | 530 | return None; |
| 501 | } | 531 | } |
| 502 | let bw = self | 532 | let bw = self |
| 503 | - .bandwidth | 533 | + .fec_bandwidth |
| 534 | + .or(self.bandwidth) | ||
| 504 | .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); | 535 | .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); |
| 505 | match bw { | 536 | match bw { |
| 506 | Bandwidth::SuperWide | Bandwidth::Full => Some(bw), | 537 | Bandwidth::SuperWide | Bandwidth::Full => Some(bw), |
| @@ -671,6 +702,7 @@ impl Encoder { | |||
| 671 | cap: usize, | 702 | cap: usize, |
| 672 | ) -> Result<(u8, &[u8])> { | 703 | ) -> Result<(u8, &[u8])> { |
| 673 | let frame_48k = frame_size * self.upsample; | 704 | let frame_48k = frame_size * self.upsample; |
| 705 | + self.fec_bandwidth = None; | ||
| 674 | if frame_48k > 960 && self.silk_choice(frame_48k).is_none() { | 706 | if frame_48k > 960 && self.silk_choice(frame_48k).is_none() { |
| 675 | return self.encode_multiframe(pcm, frame_size, cap); | 707 | return self.encode_multiframe(pcm, frame_size, cap); |
| 676 | } | 708 | } |
| @@ -683,9 +715,13 @@ impl Encoder { | |||
| 683 | } else { | 715 | } else { |
| 684 | AnalysisInfo::default() | 716 | AnalysisInfo::default() |
| 685 | }; | 717 | }; |
| 718 | + let (fec, fec_bw) = self.fec_for(frame_48k); | ||
| 719 | + self.lbrr_coded = fec; | ||
| 720 | + self.fec_bandwidth = fec_bw; | ||
| 686 | if let Some(fs_khz) = self.silk_choice(frame_48k) { | 721 | if let Some(fs_khz) = self.silk_choice(frame_48k) { |
| 687 | let budget = self.packet_budget(frame_48k, cap); | 722 | let budget = self.packet_budget(frame_48k, cap); |
| 688 | if self.channels == 2 { | 723 | if self.channels == 2 { |
| 724 | + self.last_silk = None; | ||
| 689 | Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); | 725 | Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); |
| 690 | if frame_48k > 960 { | 726 | if frame_48k > 960 { |
| 691 | return self.encode_stereo_silk_multiframe(fs_khz, frame_48k); | 727 | return self.encode_stereo_silk_multiframe(fs_khz, frame_48k); |
| @@ -709,6 +745,11 @@ impl Encoder { | |||
| 709 | return Ok((self.silk_buf[0], &self.silk_buf[1..n])); | 745 | return Ok((self.silk_buf[0], &self.silk_buf[1..n])); |
| 710 | } | 746 | } |
| 711 | Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); | 747 | Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); |
| 748 | + let (lbrr, loss, same) = ( | ||
| 749 | + self.lbrr_coded, | ||
| 750 | + self.packet_loss_perc, | ||
| 751 | + self.last_silk == Some(fs_khz as u8), | ||
| 752 | + ); | ||
| 712 | let enc = match fs_khz { | 753 | let enc = match fs_khz { |
| 713 | 8 => self | 754 | 8 => self |
| 714 | .silk_nb | 755 | .silk_nb |
| @@ -720,6 +761,10 @@ impl Encoder { | |||
| 720 | .silk_wb | 761 | .silk_wb |
| 721 | .get_or_insert_with(|| Box::new(SilkEncoder::new(true))), | 762 | .get_or_insert_with(|| Box::new(SilkEncoder::new(true))), |
| 722 | }; | 763 | }; |
| 764 | + if !same { | ||
| 765 | + enc.drop_lbrr(); | ||
| 766 | + } | ||
| 767 | + enc.set_lbrr(lbrr, loss); | ||
| 723 | // Keep SILK's own reservoir-based rate control tracking the | 768 | // Keep SILK's own reservoir-based rate control tracking the |
| 724 | // Encoder's current target on every frame — cheap (an Option<u32> | 769 | // Encoder's current target on every frame — cheap (an Option<u32> |
| 725 | // store) and catches set_bitrate calls made between frames. | 770 | // store) and catches set_bitrate calls made between frames. |
| @@ -728,6 +773,7 @@ impl Encoder { | |||
| 728 | let n = | 773 | let n = |
| 729 | enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf[..], frame_48k / 48)?; | 774 | enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf[..], frame_48k / 48)?; |
| 730 | self.final_range = enc.final_range(); | 775 | self.final_range = enc.final_range(); |
| 776 | + self.last_silk = Some(fs_khz as u8); | ||
| 731 | return Ok((self.silk_buf[0], &self.silk_buf[1..n])); | 777 | return Ok((self.silk_buf[0], &self.silk_buf[1..n])); |
| 732 | } | 778 | } |
| 733 | if let Some(bandwidth) = self.hybrid_choice(frame_48k) { | 779 | if let Some(bandwidth) = self.hybrid_choice(frame_48k) { |
| @@ -740,6 +786,7 @@ impl Encoder { | |||
| 740 | &self.range.data()[..n], | 786 | &self.range.data()[..n], |
| 741 | )); | 787 | )); |
| 742 | } | 788 | } |
| 789 | + self.last_silk = None; | ||
| 743 | let (toc, frame_48k, end) = self.toc(frame_size)?; | 790 | let (toc, frame_48k, end) = self.toc(frame_size)?; |
| 744 | let n = self.encode_frame(pcm, frame_48k, end, cap)?; | 791 | let n = self.encode_frame(pcm, frame_48k, end, cap)?; |
| 745 | Ok((toc, &self.range.data()[..n])) | 792 | Ok((toc, &self.range.data()[..n])) |
| @@ -824,7 +871,10 @@ impl Encoder { | |||
| 824 | } | 871 | } |
| 825 | }; | 872 | }; |
| 826 | let bandwidth = self.bandwidth.unwrap_or_else(|| { | 873 | let bandwidth = self.bandwidth.unwrap_or_else(|| { |
| 827 | - self.auto_bandwidth_at(self.equiv_rate(frame_48k), self.voice_est()) | 874 | + self.auto_bandwidth_at( |
| 875 | + self.equiv_rate_for(frame_48k, Some(Mode::Celt)), | ||
| 876 | + self.voice_est(), | ||
| 877 | + ) | ||
| 828 | }); | 878 | }); |
| 829 | let bw_idx: u8 = match bandwidth { | 879 | let bw_idx: u8 = match bandwidth { |
| 830 | Bandwidth::Narrow => 0, | 880 | Bandwidth::Narrow => 0, |
| @@ -854,6 +904,10 @@ impl Encoder { | |||
| 854 | /// the complexity multiplier. Loss is 0 and complexity ≥ 5, so the | 904 | /// the complexity multiplier. Loss is 0 and complexity ≥ 5, so the |
| 855 | /// are both no-ops. | 905 | /// are both no-ops. |
| 856 | fn equiv_rate(&self, frame_48k: usize) -> i32 { | 906 | fn equiv_rate(&self, frame_48k: usize) -> i32 { |
| 907 | + self.equiv_rate_for(frame_48k, None) | ||
| 908 | + } | ||
| 909 | + | ||
| 910 | + fn equiv_rate_for(&self, frame_48k: usize, mode: Option<Mode>) -> i32 { | ||
| 857 | let frame_rate = 48000 / frame_48k as i32; | 911 | let frame_rate = 48000 / frame_48k as i32; |
| 858 | let mut equiv = self.bitrate as i32; | 912 | let mut equiv = self.bitrate as i32; |
| 859 | if frame_rate > 50 { | 913 | if frame_rate > 50 { |
| @@ -863,9 +917,70 @@ impl Encoder { | |||
| 863 | equiv -= equiv / 12; | 917 | equiv -= equiv / 12; |
| 864 | } | 918 | } |
| 865 | equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100; | 919 | equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100; |
| 920 | + let loss = self.packet_loss_perc as i32; | ||
| 921 | + match mode { | ||
| 922 | + Some(Mode::Silk) | Some(Mode::Hybrid) => equiv -= equiv * loss / (6 * loss + 10), | ||
| 923 | + Some(Mode::Celt) => {} | ||
| 924 | + None => equiv -= equiv * loss / (12 * loss + 20), | ||
| 925 | + } | ||
| 866 | equiv | 926 | equiv |
| 867 | } | 927 | } |
| 868 | 928 | ||
| 929 | + fn fec_for(&self, frame_48k: usize) -> (bool, Option<Bandwidth>) { | ||
| 930 | + if !self.inband_fec | ||
| 931 | + || self.channels != 1 | ||
| 932 | + || !matches!(frame_48k, 480 | 960) | ||
| 933 | + || self.mode == Some(Mode::Celt) | ||
| 934 | + { | ||
| 935 | + return (false, None); | ||
| 936 | + } | ||
| 937 | + if self.mode.is_none() && !self.auto_silk(self.equiv_rate(frame_48k), self.voice_est()) { | ||
| 938 | + return (false, None); | ||
| 939 | + } | ||
| 940 | + let silk_equiv = self.equiv_rate_for(frame_48k, Some(Mode::Silk)); | ||
| 941 | + let ve = self.voice_est(); | ||
| 942 | + let bw = self | ||
| 943 | + .bandwidth | ||
| 944 | + .unwrap_or_else(|| self.auto_bandwidth_at(silk_equiv, ve)); | ||
| 945 | + let (fec, b) = self.decide_fec(bw, silk_equiv); | ||
| 946 | + (fec, (fec && b != bw).then_some(b)) | ||
| 947 | + } | ||
| 948 | + | ||
| 949 | + fn decide_fec(&self, bw: Bandwidth, rate: i32) -> (bool, Bandwidth) { | ||
| 950 | + const FEC_THRESHOLDS: [i32; 10] = [12000, 1000, 14000, 1000, 16000, 1000, 20000, 1000, 22000, 1000]; | ||
| 951 | + const BANDWIDTHS: [Bandwidth; 5] = [ | ||
| 952 | + Bandwidth::Narrow, | ||
| 953 | + Bandwidth::Medium, | ||
| 954 | + Bandwidth::Wide, | ||
| 955 | + Bandwidth::SuperWide, | ||
| 956 | + Bandwidth::Full, | ||
| 957 | + ]; | ||
| 958 | + let loss = self.packet_loss_perc as i32; | ||
| 959 | + if !self.inband_fec || loss == 0 { | ||
| 960 | + return (false, bw); | ||
| 961 | + } | ||
| 962 | + let mut b = BANDWIDTHS.iter().position(|&x| x == bw).unwrap_or(0); | ||
| 963 | + loop { | ||
| 964 | + let mut thres = FEC_THRESHOLDS[2 * b]; | ||
| 965 | + let hyst = FEC_THRESHOLDS[2 * b + 1]; | ||
| 966 | + if self.lbrr_coded { | ||
| 967 | + thres -= hyst; | ||
| 968 | + } else { | ||
| 969 | + thres += hyst; | ||
| 970 | + } | ||
| 971 | + thres = ((thres as i64 * (125 - loss.min(25)) as i64 * 655) >> 16) as i32; | ||
| 972 | + if rate > thres { | ||
| 973 | + return (true, BANDWIDTHS[b]); | ||
| 974 | + } else if loss <= 5 { | ||
| 975 | + return (false, bw); | ||
| 976 | + } else if b > 0 { | ||
| 977 | + b -= 1; | ||
| 978 | + } else { | ||
| 979 | + return (false, bw); | ||
| 980 | + } | ||
| 981 | + } | ||
| 982 | + } | ||
| 983 | + | ||
| 869 | /// Voice activity estimate: VoIP → 115, Audio and LowDelay → 48 | 984 | /// Voice activity estimate: VoIP → 115, Audio and LowDelay → 48 |
| 870 | /// (`opus_encoder.c` `tonality_analysis` proxy — no analysis is modelled, | 985 | /// (`opus_encoder.c` `tonality_analysis` proxy — no analysis is modelled, |
| 871 | /// so the application alone decides). | 986 | /// so the application alone decides). |
| @@ -883,6 +998,9 @@ impl Encoder { | |||
| 883 | if self.application == Application::LowDelay { | 998 | if self.application == Application::LowDelay { |
| 884 | return false; | 999 | return false; |
| 885 | } | 1000 | } |
| 1001 | + if self.inband_fec && self.packet_loss_perc as i32 > (128 - ve) >> 4 { | ||
| 1002 | + return true; | ||
| 1003 | + } | ||
| 886 | let threshold = MODE_THRESHOLD_MUSIC | 1004 | let threshold = MODE_THRESHOLD_MUSIC |
| 887 | + ((ve * ve * (MODE_THRESHOLD_VOICE - MODE_THRESHOLD_MUSIC)) >> 14); | 1005 | + ((ve * ve * (MODE_THRESHOLD_VOICE - MODE_THRESHOLD_MUSIC)) >> 14); |
| 888 | let threshold = if self.application == Application::Voip { | 1006 | let threshold = if self.application == Application::Voip { |
| @@ -1147,8 +1265,12 @@ impl Encoder { | |||
| 1147 | .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]); | 1265 | .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]); |
| 1148 | 1266 | ||
| 1149 | self.range.reset(cap); | 1267 | self.range.reset(cap); |
| 1150 | - let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth); | 1268 | + let silk_rate = Self::hybrid_silk_rate( |
| 1269 | + self.bitrate, | ||
| 1270 | + if self.lbrr_coded { Bandwidth::Full } else { bandwidth }, | ||
| 1271 | + ); | ||
| 1151 | if self.channels == 2 { | 1272 | if self.channels == 2 { |
| 1273 | + self.last_silk = None; | ||
| 1152 | let silk = self | 1274 | let silk = self |
| 1153 | .silk_stereo_wb | 1275 | .silk_stereo_wb |
| 1154 | .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))); | 1276 | .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))); |
| @@ -1156,12 +1278,22 @@ impl Encoder { | |||
| 1156 | silk.set_max_bytes(silk_max); | 1278 | silk.set_max_bytes(silk_max); |
| 1157 | silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; | 1279 | silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; |
| 1158 | } else { | 1280 | } else { |
| 1281 | + let (lbrr, loss, same) = ( | ||
| 1282 | + self.lbrr_coded, | ||
| 1283 | + self.packet_loss_perc, | ||
| 1284 | + self.last_silk == Some(16), | ||
| 1285 | + ); | ||
| 1159 | let silk = self | 1286 | let silk = self |
| 1160 | .silk_wb | 1287 | .silk_wb |
| 1161 | .get_or_insert_with(|| Box::new(SilkEncoder::new(true))); | 1288 | .get_or_insert_with(|| Box::new(SilkEncoder::new(true))); |
| 1289 | + if !same { | ||
| 1290 | + silk.drop_lbrr(); | ||
| 1291 | + } | ||
| 1292 | + silk.set_lbrr(lbrr, loss); | ||
| 1162 | silk.set_bitrate(silk_rate); | 1293 | silk.set_bitrate(silk_rate); |
| 1163 | silk.set_max_bytes(silk_max); | 1294 | silk.set_max_bytes(silk_max); |
| 1164 | silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; | 1295 | silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; |
| 1296 | + self.last_silk = Some(16); | ||
| 1165 | } | 1297 | } |
| 1166 | let silk_bytes = (self.range.tell() as usize).div_ceil(8); | 1298 | let silk_bytes = (self.range.tell() as usize).div_ceil(8); |
| 1167 | let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); | 1299 | let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); |
crates/ec-opus/src/lib.rsmodified+68 -12
| @@ -25,7 +25,8 @@ | |||
| 25 | //! empty packet to [`Decoder::decode_float`]) extends the last CELT frame: | 25 | //! empty packet to [`Decoder::decode_float`]) extends the last CELT frame: |
| 26 | //! pitch-periodic LPC extension for the first losses, then decaying | 26 | //! pitch-periodic LPC extension for the first losses, then decaying |
| 27 | //! band-shaped noise. After a SILK or hybrid frame it yields silence, as does | 27 | //! band-shaped noise. After a SILK or hybrid frame it yields silence, as does |
| 28 | -//! a one-byte (DTX) frame inside a packet. | 28 | +//! a one-byte (DTX) frame inside a packet. [`Decoder::decode_fec`] recovers |
| 29 | +//! a lost SILK or hybrid frame from the in-band FEC of the next packet. | ||
| 29 | //! | 30 | //! |
| 30 | //! The crate also carries the family's Opus *encoder* — [`Encoder`] for one | 31 | //! The crate also carries the family's Opus *encoder* — [`Encoder`] for one |
| 31 | //! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono | 32 | //! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono |
| @@ -268,6 +269,52 @@ impl Decoder { | |||
| 268 | Ok(frame_size) | 269 | Ok(frame_size) |
| 269 | } | 270 | } |
| 270 | 271 | ||
| 272 | + /// Recovers a lost frame from the in-band FEC (SILK LBRR) carried in the packet | ||
| 273 | + /// that follows it, like libopus `opus_decode(next_packet, frame_size, decode_fec=1)`. | ||
| 274 | + /// Falls back to [`Decoder::conceal`] when `next_packet` carries no LBRR data. | ||
| 275 | + /// Returns samples per channel (`frame_size`). | ||
| 276 | + pub fn decode_fec( | ||
| 277 | + &mut self, | ||
| 278 | + next_packet: &[u8], | ||
| 279 | + frame_size: usize, | ||
| 280 | + out: &mut [f32], | ||
| 281 | + ) -> Result<usize> { | ||
| 282 | + if next_packet.is_empty() || frame_size * self.downsample > 5760 { | ||
| 283 | + return self.conceal(frame_size, out); | ||
| 284 | + } | ||
| 285 | + let needed = frame_size * self.channels; | ||
| 286 | + if out.len() < needed { | ||
| 287 | + return Err(Error::corrupt(format!( | ||
| 288 | + "opus: output buffer holds {} samples, FEC needs {needed}", | ||
| 289 | + out.len() | ||
| 290 | + ))); | ||
| 291 | + } | ||
| 292 | + let parsed = Packet::parse(next_packet, false)?; | ||
| 293 | + let toc = parsed.toc; | ||
| 294 | + let mode = toc.mode(); | ||
| 295 | + let frame_48k = toc.frame_size_48k(); | ||
| 296 | + let packet_frame = frame_48k / self.downsample; | ||
| 297 | + let Some(&first) = parsed.frames.first() else { | ||
| 298 | + return self.conceal(frame_size, out); | ||
| 299 | + }; | ||
| 300 | + if frame_size < packet_frame | ||
| 301 | + || mode == Mode::Celt | ||
| 302 | + || self.prev_mode == Some(Mode::Celt) | ||
| 303 | + || first.len() <= 1 | ||
| 304 | + || !SilkDecoder::has_lbrr(first, (frame_48k / 48).max(10)) | ||
| 305 | + { | ||
| 306 | + return self.conceal(frame_size, out); | ||
| 307 | + } | ||
| 308 | + let lead = frame_size - packet_frame; | ||
| 309 | + if lead > 0 { | ||
| 310 | + self.conceal(lead, &mut out[..lead * self.channels])?; | ||
| 311 | + } | ||
| 312 | + let dst = &mut out[lead * self.channels..needed]; | ||
| 313 | + self.range_final = self.decode_frame(first, dst, toc, frame_48k, true)?; | ||
| 314 | + self.last_packet_size = frame_size; | ||
| 315 | + Ok(frame_size) | ||
| 316 | + } | ||
| 317 | + | ||
| 271 | fn decode_impl( | 318 | fn decode_impl( |
| 272 | &mut self, | 319 | &mut self, |
| 273 | data: &[u8], | 320 | data: &[u8], |
| @@ -289,7 +336,7 @@ impl Decoder { | |||
| 289 | let mut range = 0u32; | 336 | let mut range = 0u32; |
| 290 | for frame in &parsed.frames { | 337 | for frame in &parsed.frames { |
| 291 | let dst = &mut out[done * self.channels..(done + frame_out) * self.channels]; | 338 | let dst = &mut out[done * self.channels..(done + frame_out) * self.channels]; |
| 292 | - range = self.decode_frame(frame, dst, toc, frame_48k)?; | 339 | + range = self.decode_frame(frame, dst, toc, frame_48k, false)?; |
| 293 | done += frame_out; | 340 | done += frame_out; |
| 294 | } | 341 | } |
| 295 | self.range_final = range; | 342 | self.range_final = range; |
| @@ -302,13 +349,15 @@ impl Decoder { | |||
| 302 | /// The three modes share this path: SILK fills the low band, CELT the high | 349 | /// The three modes share this path: SILK fills the low band, CELT the high |
| 303 | /// one, and a hybrid frame is their sum. The order of everything read from | 350 | /// one, and a hybrid frame is their sum. The order of everything read from |
| 304 | /// the range decoder here is normative — SILK, then the redundancy flags, | 351 | /// the range decoder here is normative — SILK, then the redundancy flags, |
| 305 | - /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3). | 352 | + /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3). With `fec` set, the |
| 353 | + /// SILK layer decodes LBRR frames and the CELT layer is concealed instead. | ||
| 306 | fn decode_frame( | 354 | fn decode_frame( |
| 307 | &mut self, | 355 | &mut self, |
| 308 | data: &[u8], | 356 | data: &[u8], |
| 309 | out: &mut [f32], | 357 | out: &mut [f32], |
| 310 | toc: Toc, | 358 | toc: Toc, |
| 311 | frame_48k: usize, | 359 | frame_48k: usize, |
| 360 | + fec: bool, | ||
| 312 | ) -> Result<u32> { | 361 | ) -> Result<u32> { |
| 313 | let mode = toc.mode(); | 362 | let mode = toc.mode(); |
| 314 | let stream_channels = toc.channels(); | 363 | let stream_channels = toc.channels(); |
| @@ -353,6 +402,7 @@ impl Decoder { | |||
| 353 | internal_rate, | 402 | internal_rate, |
| 354 | stream_channels, | 403 | stream_channels, |
| 355 | first, | 404 | first, |
| 405 | + fec, | ||
| 356 | )?; | 406 | )?; |
| 357 | if n == 0 { | 407 | if n == 0 { |
| 358 | break; | 408 | break; |
| @@ -366,7 +416,8 @@ impl Decoder { | |||
| 366 | let mut redundancy = false; | 416 | let mut redundancy = false; |
| 367 | let mut celt_to_silk = false; | 417 | let mut celt_to_silk = false; |
| 368 | let mut redundancy_bytes = 0usize; | 418 | let mut redundancy_bytes = 0usize; |
| 369 | - if mode != Mode::Celt | 419 | + if !fec |
| 420 | + && mode != Mode::Celt | ||
| 370 | && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len | 421 | && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len |
| 371 | { | 422 | { |
| 372 | redundancy = if mode == Mode::Hybrid { | 423 | redundancy = if mode == Mode::Hybrid { |
| @@ -418,14 +469,19 @@ impl Decoder { | |||
| 418 | if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy { | 469 | if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy { |
| 419 | self.celt.reset(); | 470 | self.celt.reset(); |
| 420 | } | 471 | } |
| 421 | - self.celt.decode( | 472 | + if fec { |
| 422 | - &mut dec, | 473 | + self.celt.set_conceal_bands(start_band, end_band); |
| 423 | - out, | 474 | + self.celt.conceal(out, frame_48k.min(960))?; |
| 424 | - frame_48k.min(960), | 475 | + } else { |
| 425 | - start_band, | 476 | + self.celt.decode( |
| 426 | - end_band, | 477 | + &mut dec, |
| 427 | - stream_channels, | 478 | + out, |
| 428 | - )?; | 479 | + frame_48k.min(960), |
| 480 | + start_band, | ||
| 481 | + end_band, | ||
| 482 | + stream_channels, | ||
| 483 | + )?; | ||
| 484 | + } | ||
| 429 | } else { | 485 | } else { |
| 430 | out.fill(0.0); | 486 | out.fill(0.0); |
| 431 | // Fade the CELT layer out when leaving hybrid, as the reference | 487 | // Fade the CELT layer out when leaving hybrid, as the reference |
crates/ec-opus/src/silk.rsmodified+54 -9
| @@ -12,9 +12,10 @@ | |||
| 12 | //! written as fixed-point pseudo-code for the same reason). The tables are the | 12 | //! written as fixed-point pseudo-code for the same reason). The tables are the |
| 13 | //! ones the RFC tabulates in Section 4.2, in the layout the reference uses. | 13 | //! ones the RFC tabulates in Section 4.2, in the layout the reference uses. |
| 14 | //! | 14 | //! |
| 15 | -//! Packet loss concealment is not implemented: this decoder is fed complete | 15 | +//! LBRR (in-band FEC) frames can be decoded through the `lbrr` flag of |
| 16 | -//! packets by the container layer, so a lost or empty frame yields silence | 16 | +//! [`SilkDecoder::decode`], but SILK packet loss concealment is not implemented: |
| 17 | -//! rather than an extrapolation. Everything else in the layer is complete. | 17 | +//! a lost or empty frame yields silence rather than an extrapolation. |
| 18 | +//! Everything else in the layer is complete. | ||
| 18 | 19 | ||
| 19 | // SILK is transliterated fixed-point arithmetic: the loops below index parallel | 20 | // SILK is transliterated fixed-point arithmetic: the loops below index parallel |
| 20 | // arrays by position because the reference's index arithmetic is the | 21 | // arrays by position because the reference's index arithmetic is the |
| @@ -477,6 +478,23 @@ impl SilkDecoder { | |||
| 477 | } | 478 | } |
| 478 | } | 479 | } |
| 479 | 480 | ||
| 481 | + /// Whether the first SILK frame of `payload` carries LBRR (FEC) data for the mid channel. | ||
| 482 | + pub fn has_lbrr(payload: &[u8], payload_ms: usize) -> bool { | ||
| 483 | + if payload.is_empty() { | ||
| 484 | + return false; | ||
| 485 | + } | ||
| 486 | + let frames_per_packet = match payload_ms { | ||
| 487 | + 40 => 2, | ||
| 488 | + 60 => 3, | ||
| 489 | + _ => 1, | ||
| 490 | + }; | ||
| 491 | + let mut dec = RangeDecoder::new(payload); | ||
| 492 | + for _ in 0..frames_per_packet { | ||
| 493 | + dec.dec_bit_logp(1); | ||
| 494 | + } | ||
| 495 | + dec.dec_bit_logp(1) | ||
| 496 | + } | ||
| 497 | + | ||
| 480 | /// Drops all inter-packet state. | 498 | /// Drops all inter-packet state. |
| 481 | pub fn reset(&mut self) { | 499 | pub fn reset(&mut self) { |
| 482 | let api_rate = self.api_rate; | 500 | let api_rate = self.api_rate; |
| @@ -490,6 +508,9 @@ impl SilkDecoder { | |||
| 490 | /// `internal_rate` the SILK sample rate the TOC implies (8000, 12000 or | 508 | /// `internal_rate` the SILK sample rate the TOC implies (8000, 12000 or |
| 491 | /// 16000 Hz), and `channels_internal` how many channels the packet codes. | 509 | /// 16000 Hz), and `channels_internal` how many channels the packet codes. |
| 492 | /// Output is interleaved `i16` at the API rate, `channels_api` channels. | 510 | /// Output is interleaved `i16` at the API rate, `channels_api` channels. |
| 511 | + /// With `lbrr` set, decodes the packet's LBRR (in-band FEC) frames instead | ||
| 512 | + /// of the regular ones. | ||
| 513 | + #[allow(clippy::too_many_arguments)] | ||
| 493 | pub fn decode( | 514 | pub fn decode( |
| 494 | &mut self, | 515 | &mut self, |
| 495 | dec: &mut RangeDecoder, | 516 | dec: &mut RangeDecoder, |
| @@ -498,6 +519,7 @@ impl SilkDecoder { | |||
| 498 | internal_rate: u32, | 519 | internal_rate: u32, |
| 499 | channels_internal: usize, | 520 | channels_internal: usize, |
| 500 | new_packet: bool, | 521 | new_packet: bool, |
| 522 | + lbrr: bool, | ||
| 501 | ) -> Result<usize> { | 523 | ) -> Result<usize> { |
| 502 | let fs_khz = (internal_rate / 1000) as usize; | 524 | let fs_khz = (internal_rate / 1000) as usize; |
| 503 | if new_packet { | 525 | if new_packet { |
| @@ -563,7 +585,8 @@ impl SilkDecoder { | |||
| 563 | } | 585 | } |
| 564 | // Skip the LBRR frames: they are only useful for concealment, but | 586 | // Skip the LBRR frames: they are only useful for concealment, but |
| 565 | // their symbols must still be consumed to stay in sync. | 587 | // their symbols must still be consumed to stay in sync. |
| 566 | - for i in 0..self.channels[0].frames_per_packet { | 588 | + let skip = if lbrr { 0 } else { self.channels[0].frames_per_packet }; |
| 589 | + for i in 0..skip { | ||
| 567 | for n in 0..channels_internal { | 590 | for n in 0..channels_internal { |
| 568 | if self.channels[n].lbrr_flags[i] { | 591 | if self.channels[n].lbrr_flags[i] { |
| 569 | if channels_internal == 2 && n == 0 { | 592 | if channels_internal == 2 && n == 0 { |
| @@ -595,10 +618,19 @@ impl SilkDecoder { | |||
| 595 | 618 | ||
| 596 | // Stereo prediction weights for this frame. | 619 | // Stereo prediction weights for this frame. |
| 597 | if channels_internal == 2 { | 620 | if channels_internal == 2 { |
| 598 | - stereo_decode_pred(dec, &mut ms_pred_q13); | ||
| 599 | let frame = self.channels[0].frames_decoded; | 621 | let frame = self.channels[0].frames_decoded; |
| 600 | - if !self.channels[1].vad_flags[frame] { | 622 | + if !lbrr || self.channels[0].lbrr_flags[frame] { |
| 601 | - decode_only_middle = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8) != 0; | 623 | + stereo_decode_pred(dec, &mut ms_pred_q13); |
| 624 | + let side_coded = if lbrr { | ||
| 625 | + self.channels[1].lbrr_flags[frame] | ||
| 626 | + } else { | ||
| 627 | + self.channels[1].vad_flags[frame] | ||
| 628 | + }; | ||
| 629 | + if !side_coded { | ||
| 630 | + decode_only_middle = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8) != 0; | ||
| 631 | + } | ||
| 632 | + } else { | ||
| 633 | + ms_pred_q13 = self.stereo.pred_prev_q13; | ||
| 602 | } | 634 | } |
| 603 | } | 635 | } |
| 604 | if channels_internal == 2 && !decode_only_middle && self.prev_decode_only_middle { | 636 | if channels_internal == 2 && !decode_only_middle && self.prev_decode_only_middle { |
| @@ -620,12 +652,24 @@ impl SilkDecoder { | |||
| 620 | let frame_index = self.channels[0].frames_decoded as i32 - n as i32; | 652 | let frame_index = self.channels[0].frames_decoded as i32 - n as i32; |
| 621 | let cond = if frame_index <= 0 { | 653 | let cond = if frame_index <= 0 { |
| 622 | CondCoding::Independently | 654 | CondCoding::Independently |
| 655 | + } else if lbrr { | ||
| 656 | + if self.channels[n].lbrr_flags[(frame_index - 1) as usize] { | ||
| 657 | + CondCoding::Conditionally | ||
| 658 | + } else { | ||
| 659 | + CondCoding::Independently | ||
| 660 | + } | ||
| 623 | } else if n > 0 && self.prev_decode_only_middle { | 661 | } else if n > 0 && self.prev_decode_only_middle { |
| 624 | CondCoding::IndependentlyNoLtpScaling | 662 | CondCoding::IndependentlyNoLtpScaling |
| 625 | } else { | 663 | } else { |
| 626 | CondCoding::Conditionally | 664 | CondCoding::Conditionally |
| 627 | }; | 665 | }; |
| 628 | - n_samples_dec = decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond); | 666 | + if !lbrr || self.channels[n].lbrr_flags[self.channels[n].frames_decoded] { |
| 667 | + n_samples_dec = | ||
| 668 | + decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond, lbrr); | ||
| 669 | + } else { | ||
| 670 | + n_samples_dec = self.channels[n].frame_length; | ||
| 671 | + buf[2..2 + n_samples_dec].fill(0); | ||
| 672 | + } | ||
| 629 | } else { | 673 | } else { |
| 630 | buf[2..2 + n_samples_dec].fill(0); | 674 | buf[2..2 + n_samples_dec].fill(0); |
| 631 | } | 675 | } |
| @@ -1431,9 +1475,10 @@ fn decode_frame( | |||
| 1431 | dec: &mut RangeDecoder, | 1475 | dec: &mut RangeDecoder, |
| 1432 | out: &mut [i16], | 1476 | out: &mut [i16], |
| 1433 | cond: CondCoding, | 1477 | cond: CondCoding, |
| 1478 | + lbrr: bool, | ||
| 1434 | ) -> usize { | 1479 | ) -> usize { |
| 1435 | let frame_index = ch.frames_decoded; | 1480 | let frame_index = ch.frames_decoded; |
| 1436 | - decode_indices(ch, dec, frame_index, false, cond); | 1481 | + decode_indices(ch, dec, frame_index, lbrr, cond); |
| 1437 | let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN]; | 1482 | let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN]; |
| 1438 | decode_pulses( | 1483 | decode_pulses( |
| 1439 | dec, | 1484 | dec, |
crates/ec-opus/src/silk_enc_write.rsmodified+59 -6
| @@ -95,6 +95,10 @@ pub struct SilkEncoder { | |||
| 95 | shape_gq: Vec<f32>, | 95 | shape_gq: Vec<f32>, |
| 96 | prev_pitch_lag: i32, | 96 | prev_pitch_lag: i32, |
| 97 | last_diag: SilkFrameDiag, | 97 | last_diag: SilkFrameDiag, |
| 98 | + lbrr_enabled: bool, | ||
| 99 | + lbrr_gain_increases: i32, | ||
| 100 | + pending_lbrr: Option<Box<Trial>>, | ||
| 101 | + lbrr_in_packet: Option<Box<Trial>>, | ||
| 98 | } | 102 | } |
| 99 | 103 | ||
| 100 | /// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth | 104 | /// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth |
| @@ -176,6 +180,10 @@ impl SilkEncoder { | |||
| 176 | shape_u: vec![0.0; 20 * fs_khz], | 180 | shape_u: vec![0.0; 20 * fs_khz], |
| 177 | shape_gq: vec![0.0; 20 * fs_khz], | 181 | shape_gq: vec![0.0; 20 * fs_khz], |
| 178 | last_diag: SilkFrameDiag::default(), | 182 | last_diag: SilkFrameDiag::default(), |
| 183 | + lbrr_enabled: false, | ||
| 184 | + lbrr_gain_increases: 7, | ||
| 185 | + pending_lbrr: None, | ||
| 186 | + lbrr_in_packet: None, | ||
| 179 | } | 187 | } |
| 180 | } | 188 | } |
| 181 | 189 | ||
| @@ -208,6 +216,25 @@ impl SilkEncoder { | |||
| 208 | self.max_bytes = max; | 216 | self.max_bytes = max; |
| 209 | } | 217 | } |
| 210 | 218 | ||
| 219 | + /// libopus `silk_setup_LBRR`: enables LBRR (in-band FEC) for the next frames at `loss_perc` % expected loss. | ||
| 220 | + pub fn set_lbrr(&mut self, enabled: bool, loss_perc: u8) { | ||
| 221 | + if enabled { | ||
| 222 | + self.lbrr_gain_increases = if self.lbrr_enabled { | ||
| 223 | + (7 - ((loss_perc as i32 * 13107) >> 16)).max(3) | ||
| 224 | + } else { | ||
| 225 | + 7 | ||
| 226 | + }; | ||
| 227 | + } else { | ||
| 228 | + self.pending_lbrr = None; | ||
| 229 | + } | ||
| 230 | + self.lbrr_enabled = enabled; | ||
| 231 | + } | ||
| 232 | + | ||
| 233 | + /// Drops the LBRR frame waiting for the next packet (that packet will not follow the frame it protects). | ||
| 234 | + pub fn drop_lbrr(&mut self) { | ||
| 235 | + self.pending_lbrr = None; | ||
| 236 | + } | ||
| 237 | + | ||
| 211 | fn reset_state(&mut self) { | 238 | fn reset_state(&mut self) { |
| 212 | *self = Self::with_fs_khz(self.fs_khz); | 239 | *self = Self::with_fs_khz(self.fs_khz); |
| 213 | } | 240 | } |
| @@ -271,7 +298,8 @@ impl SilkEncoder { | |||
| 271 | } | 298 | } |
| 272 | self.range.reset(1275); | 299 | self.range.reset(1275); |
| 273 | let refs: Vec<&Trial> = frames.iter().collect(); | 300 | let refs: Vec<&Trial> = frames.iter().collect(); |
| 274 | - write_packet_header(&mut self.range, &refs); | 301 | + let lbrr = self.lbrr_in_packet.take(); |
| 302 | + write_packet_header(&mut self.range, &refs, lbrr.as_deref()); | ||
| 275 | prev_signal_type = 0; | 303 | prev_signal_type = 0; |
| 276 | for (i, frame) in frames.iter().enumerate() { | 304 | for (i, frame) in frames.iter().enumerate() { |
| 277 | write_frame_data(&mut self.range, frame, i > 0, prev_signal_type); | 305 | write_frame_data(&mut self.range, frame, i > 0, prev_signal_type); |
| @@ -347,6 +375,7 @@ impl SilkEncoder { | |||
| 347 | fs as u32 * 1000, | 375 | fs as u32 * 1000, |
| 348 | 1, | 376 | 1, |
| 349 | first, | 377 | first, |
| 378 | + false, | ||
| 350 | )?; | 379 | )?; |
| 351 | if n == 0 { | 380 | if n == 0 { |
| 352 | break; | 381 | break; |
| @@ -380,6 +409,12 @@ impl SilkEncoder { | |||
| 380 | 48 * frame_ms, | 409 | 48 * frame_ms, |
| 381 | "SilkEncoder input is 48 kHz mono" | 410 | "SilkEncoder input is 48 kHz mono" |
| 382 | ); | 411 | ); |
| 412 | + let pending = if single_frame_packet { | ||
| 413 | + self.pending_lbrr.take() | ||
| 414 | + } else { | ||
| 415 | + self.pending_lbrr = None; | ||
| 416 | + None | ||
| 417 | + }; | ||
| 383 | let fs = self.fs_khz; | 418 | let fs = self.fs_khz; |
| 384 | let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; | 419 | let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; |
| 385 | let nb_subfr = frame_ms / 5; | 420 | let nb_subfr = frame_ms / 5; |
| @@ -721,7 +756,7 @@ impl SilkEncoder { | |||
| 721 | }; | 756 | }; |
| 722 | let enc = &mut self.range; | 757 | let enc = &mut self.range; |
| 723 | enc.reset(1275); | 758 | enc.reset(1275); |
| 724 | - write_packet_header(enc, &[&trial]); | 759 | + write_packet_header(enc, &[&trial], pending.as_deref()); |
| 725 | write_frame_data(enc, &trial, conditional, prev_signal_type); | 760 | write_frame_data(enc, &trial, conditional, prev_signal_type); |
| 726 | enc.done(); | 761 | enc.done(); |
| 727 | debug_assert!(!enc.error()); | 762 | debug_assert!(!enc.error()); |
| @@ -733,7 +768,8 @@ impl SilkEncoder { | |||
| 733 | 768 | ||
| 734 | // Rate control: a common gain offset moves every subframe's pulse | 769 | // Rate control: a common gain offset moves every subframe's pulse |
| 735 | // magnitudes together; the reservoir carries each packet's miss. | 770 | // magnitudes together; the reservoir carries each packet's miss. |
| 736 | - let mut best = trial(if CARRY_RATE_STEP { self.rate_step } else { 0 }); | 771 | + let mut chosen_step = if CARRY_RATE_STEP { self.rate_step } else { 0 }; |
| 772 | + let mut best = trial(chosen_step); | ||
| 737 | if let Some(bps) = self.target_bps { | 773 | if let Some(bps) = self.target_bps { |
| 738 | let mut frame_bits = bps as f32 * frame_ms as f32 / 1000.0; | 774 | let mut frame_bits = bps as f32 * frame_ms as f32 / 1000.0; |
| 739 | // A packet cap is a promise to fill it: the CBR packet is padded to | 775 | // A packet cap is a promise to fill it: the CBR packet is padded to |
| @@ -842,6 +878,7 @@ impl SilkEncoder { | |||
| 842 | } | 878 | } |
| 843 | b0 = bits_of(&best); | 879 | b0 = bits_of(&best); |
| 844 | } | 880 | } |
| 881 | + chosen_step = best_step; | ||
| 845 | self.rate_ema += (s_ctl as f32 - self.rate_ema) * CARRY_EMA; | 882 | self.rate_ema += (s_ctl as f32 - self.rate_ema) * CARRY_EMA; |
| 846 | self.rate_step = (self.rate_ema.round() as i32).clamp(-MAX_RATE_STEP, MAX_RATE_STEP); | 883 | self.rate_step = (self.rate_ema.round() as i32).clamp(-MAX_RATE_STEP, MAX_RATE_STEP); |
| 847 | self.reservoir = if LIBOPUS_RESERVOIR { | 884 | self.reservoir = if LIBOPUS_RESERVOIR { |
| @@ -854,11 +891,18 @@ impl SilkEncoder { | |||
| 854 | ) | 891 | ) |
| 855 | }; | 892 | }; |
| 856 | } | 893 | } |
| 894 | + let new_lbrr = if self.lbrr_enabled && single_frame_packet && best.vad_flag { | ||
| 895 | + Some(Box::new(trial(chosen_step + self.lbrr_gain_increases))) | ||
| 896 | + } else { | ||
| 897 | + None | ||
| 898 | + }; | ||
| 857 | if let Some(enc) = shared { | 899 | if let Some(enc) = shared { |
| 858 | let trial_ref = &best; | 900 | let trial_ref = &best; |
| 859 | - write_packet_header(enc, &[trial_ref]); | 901 | + write_packet_header(enc, &[trial_ref], pending.as_deref()); |
| 860 | write_frame_data(enc, trial_ref, conditional, prev_signal_type); | 902 | write_frame_data(enc, trial_ref, conditional, prev_signal_type); |
| 861 | } | 903 | } |
| 904 | + self.pending_lbrr = new_lbrr; | ||
| 905 | + self.lbrr_in_packet = pending; | ||
| 862 | self.prev_gain_index = best.prev_gain_index; | 906 | self.prev_gain_index = best.prev_gain_index; |
| 863 | self.shape_d.copy_from_slice(&best.run.d[n..]); | 907 | self.shape_d.copy_from_slice(&best.run.d[n..]); |
| 864 | self.shape_u.copy_from_slice(&best.run.u[n..]); | 908 | self.shape_u.copy_from_slice(&best.run.u[n..]); |
| @@ -1265,6 +1309,7 @@ impl SilkStereoEncoder { | |||
| 1265 | fs as u32 * 1000, | 1309 | fs as u32 * 1000, |
| 1266 | 2, | 1310 | 2, |
| 1267 | true, | 1311 | true, |
| 1312 | + false, | ||
| 1268 | )?; | 1313 | )?; |
| 1269 | debug_assert_eq!(n, frame_ms * fs); | 1314 | debug_assert_eq!(n, frame_ms * fs); |
| 1270 | self.mirror_range = dec.range(); | 1315 | self.mirror_range = dec.range(); |
| @@ -1287,6 +1332,7 @@ fn write_stereo_zero_pred(enc: &mut RangeEncoder) { | |||
| 1287 | enc.enc_icdf(2, &UNIFORM5_ICDF, 8); | 1332 | enc.enc_icdf(2, &UNIFORM5_ICDF, 8); |
| 1288 | } | 1333 | } |
| 1289 | /// One closed-loop quantisation of a frame. | 1334 | /// One closed-loop quantisation of a frame. |
| 1335 | +#[derive(Clone, Debug)] | ||
| 1290 | struct Run { | 1336 | struct Run { |
| 1291 | ltp_index: [usize; MAX_NB_SUBFR], | 1337 | ltp_index: [usize; MAX_NB_SUBFR], |
| 1292 | pulses: Vec<i32>, | 1338 | pulses: Vec<i32>, |
| @@ -1296,6 +1342,7 @@ struct Run { | |||
| 1296 | gq: Vec<f32>, | 1342 | gq: Vec<f32>, |
| 1297 | } | 1343 | } |
| 1298 | 1344 | ||
| 1345 | +#[derive(Clone, Debug)] | ||
| 1299 | struct Trial { | 1346 | struct Trial { |
| 1300 | bytes: Vec<u8>, | 1347 | bytes: Vec<u8>, |
| 1301 | range: u32, | 1348 | range: u32, |
| @@ -1319,11 +1366,16 @@ struct Trial { | |||
| 1319 | seed_index: i32, | 1366 | seed_index: i32, |
| 1320 | } | 1367 | } |
| 1321 | 1368 | ||
| 1322 | -fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial]) { | 1369 | +fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial], lbrr: Option<&Trial>) { |
| 1323 | for frame in frames { | 1370 | for frame in frames { |
| 1324 | enc.enc_bit_logp(frame.vad_flag, 1); | 1371 | enc.enc_bit_logp(frame.vad_flag, 1); |
| 1325 | } | 1372 | } |
| 1326 | - enc.enc_bit_logp(false, 1); | 1373 | + enc.enc_bit_logp(lbrr.is_some(), 1); |
| 1374 | + if let Some(t) = lbrr | ||
| 1375 | + && frames.len() == 1 | ||
| 1376 | + { | ||
| 1377 | + write_frame_data(enc, t, false, 0); | ||
| 1378 | + } | ||
| 1327 | } | 1379 | } |
| 1328 | 1380 | ||
| 1329 | fn write_frame_data( | 1381 | fn write_frame_data( |
| @@ -1575,6 +1627,7 @@ mod tests { | |||
| 1575 | if wb { 16000 } else { 8000 }, | 1627 | if wb { 16000 } else { 8000 }, |
| 1576 | 1, | 1628 | 1, |
| 1577 | true, | 1629 | true, |
| 1630 | + false, | ||
| 1578 | ) | 1631 | ) |
| 1579 | .unwrap(); | 1632 | .unwrap(); |
| 1580 | assert_eq!(n, if wb { 320 } else { 160 }); | 1633 | assert_eq!(n, if wb { 320 } else { 160 }); |
crates/ec-opus/src/stack_budget.rsmodified+5 -5
| @@ -69,8 +69,8 @@ | |||
| 69 | //! that holds one is a `Box`, which | 69 | //! that holds one is a `Box`, which |
| 70 | //! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. | 70 | //! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. |
| 71 | //! | 71 | //! |
| 72 | -//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,072 | 72 | +//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,080 |
| 73 | -//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4072 = 8,144` bytes -- | 73 | +//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4080 = 8,160` bytes -- |
| 74 | //! **0.39%** of a 2 MiB thread -- and the budget sits 2.01x above the | 74 | //! **0.39%** of a 2 MiB thread -- and the budget sits 2.01x above the |
| 75 | //! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the | 75 | //! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the |
| 76 | //! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect | 76 | //! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect |
| @@ -122,7 +122,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |||
| 122 | // -- encoder.rs ------------------------------------------------------- | 122 | // -- encoder.rs ------------------------------------------------------- |
| 123 | ( | 123 | ( |
| 124 | "Encoder", | 124 | "Encoder", |
| 125 | - Some(4072), | 125 | + Some(4080), |
| 126 | true, | 126 | true, |
| 127 | "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \ | 127 | "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \ |
| 128 | inline Option<SilkEncoder>/Option<SilkStereoEncoder> slots (79176 \ | 128 | inline Option<SilkEncoder>/Option<SilkStereoEncoder> slots (79176 \ |
| @@ -235,7 +235,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |||
| 235 | // -- silk_enc_write.rs ------------------------------------------------ | 235 | // -- silk_enc_write.rs ------------------------------------------------ |
| 236 | ( | 236 | ( |
| 237 | "SilkEncoder", | 237 | "SilkEncoder", |
| 238 | - Some(6664), | 238 | + Some(6688), |
| 239 | false, | 239 | false, |
| 240 | "silk_enc_write::SilkEncoder::new -> Self. `pub`, `pub use`d at the \ | 240 | "silk_enc_write::SilkEncoder::new -> Self. `pub`, `pub use`d at the \ |
| 241 | crate root, and returned by value -- but every field that holds one \ | 241 | crate root, and returned by value -- but every field that holds one \ |
| @@ -243,7 +243,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |||
| 243 | ), | 243 | ), |
| 244 | ( | 244 | ( |
| 245 | "SilkStereoEncoder", | 245 | "SilkStereoEncoder", |
| 246 | - Some(19808), | 246 | + Some(19856), |
| 247 | false, | 247 | false, |
| 248 | "silk_enc_write::SilkStereoEncoder::new -> Self. The largest single \ | 248 | "silk_enc_write::SilkStereoEncoder::new -> Self. The largest single \ |
| 249 | type in the crate at 2.42x the budget, and the reason three of the \ | 249 | type in the crate at 2.42x the budget, and the reason three of the \ |
crates/ec-opus/tests/conformance.rsmodified+1 -1
| @@ -4513,7 +4513,7 @@ fn collect_indices(packets: &[Vec<u8>]) -> Vec<(ec_opus::SilkDecIndices, usize)> | |||
| 4513 | continue; | 4513 | continue; |
| 4514 | } | 4514 | } |
| 4515 | let mut dec = ec_opus::RangeDecoder::new(frame_data); | 4515 | let mut dec = ec_opus::RangeDecoder::new(frame_data); |
| 4516 | - let _ = silk.decode(&mut dec, &mut silk_pcm, payload_ms, internal_rate, 1, first); | 4516 | + let _ = silk.decode(&mut dec, &mut silk_pcm, payload_ms, internal_rate, 1, first, false); |
| 4517 | let ix = silk.last_indices(); | 4517 | let ix = silk.last_indices(); |
| 4518 | let bytes = frame_data.len(); | 4518 | let bytes = frame_data.len(); |
| 4519 | results.push((ix, bytes)); | 4519 | results.push((ix, bytes)); |
crates/ec-opus/tests/plc.rsmodified+38 -0
| @@ -77,3 +77,41 @@ fn concealment_tracks_and_recovers() { | |||
| 77 | assert!(c50 > 0.9); | 77 | assert!(c50 > 0.9); |
| 78 | assert!(jump < 2.0 * jump_ref); | 78 | assert!(jump < 2.0 * jump_ref); |
| 79 | } | 79 | } |
| 80 | + | ||
| 81 | +#[test] | ||
| 82 | +fn inband_fec_recovers_a_lost_frame() { | ||
| 83 | + let pcm = voice(40); | ||
| 84 | + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | ||
| 85 | + enc.set_bitrate(48000); | ||
| 86 | + enc.set_bandwidth(Some(ec_opus::Bandwidth::Full)); | ||
| 87 | + enc.set_inband_fec(true); | ||
| 88 | + enc.set_packet_loss_perc(15); | ||
| 89 | + let mut pkt = vec![0u8; 1500]; | ||
| 90 | + let packets: Vec<Vec<u8>> = pcm | ||
| 91 | + .chunks_exact(FRAME) | ||
| 92 | + .map(|f| { | ||
| 93 | + let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); | ||
| 94 | + pkt[..n].to_vec() | ||
| 95 | + }) | ||
| 96 | + .collect(); | ||
| 97 | + let mut clean = Decoder::new(48000, 1).unwrap(); | ||
| 98 | + let mut lossy = Decoder::new(48000, 1).unwrap(); | ||
| 99 | + let mut buf = vec![0f32; 5760]; | ||
| 100 | + let (mut a, mut b) = (Vec::new(), Vec::new()); | ||
| 101 | + for (i, p) in packets.iter().enumerate() { | ||
| 102 | + let k = clean.decode_float(p, &mut buf).unwrap(); | ||
| 103 | + a.extend_from_slice(&buf[..k]); | ||
| 104 | + let k = if i == 20 { | ||
| 105 | + lossy.decode_fec(&packets[21], FRAME, &mut buf).unwrap() | ||
| 106 | + } else { | ||
| 107 | + lossy.decode_float(p, &mut buf).unwrap() | ||
| 108 | + }; | ||
| 109 | + b.extend_from_slice(&buf[..k]); | ||
| 110 | + } | ||
| 111 | + let f = |i: usize| i * FRAME..(i + 1) * FRAME; | ||
| 112 | + let c20 = corr(&a[f(20)], &b[f(20)]); | ||
| 113 | + let c22 = corr(&a[f(22)], &b[f(22)]); | ||
| 114 | + eprintln!("fec c20 {c20:.3} c22 {c22:.3}"); | ||
| 115 | + assert!(c20 > 0.7); | ||
| 116 | + assert!(c22 > 0.95); | ||
| 117 | +} | ||