forge
Explore
Log in

Don't you dare go Hollow

ec-opus: SILK comfort noise (silk/CNG.c, bit-exact vs libopus 1.6 SILK PLC), Encoder::set_dtx (libopus DTX: TOC-only packets after 200 ms inactivity, 400 ms refresh), LBRR for stereo 10/20 ms and mono 40/60 ms, loss-driven LTP scaling (silk_LTP_scale_ctrl), MultistreamDecoder::conceal/decode_fec, MultistreamEncoder::set_inband_fec/set_packet_loss_perc; CELT noise PLC synthesizes long blocks like libopus; FEC-off output unchanged

Browse files at this commit

237a87ff01dcc3ecb5ac92fe344f1d01ff89af62Ahmet Kaan GümüşParent: 86fb0f3
crates/ec-opus/src/celt.rsmodified+1 -5
@@ -1334,7 +1334,6 @@ struct Plc {
1334 ext: Vec<f32>,1334 ext: Vec<f32>,
1335 start: usize,1335 start: usize,
1336 end: usize,1336 end: usize,
1337- transient: bool,
1338 }1337 }
1339 1338
1340 impl CeltDecoder {1339 impl CeltDecoder {
@@ -1385,7 +1384,6 @@ impl CeltDecoder {
1385 ext: vec![0.0; max_n + OVERLAP],1384 ext: vec![0.0; max_n + OVERLAP],
1386 start: 0,1385 start: 0,
1387 end: NB_BANDS,1386 end: NB_BANDS,
1388- transient: false,
1389 },1387 },
1390 diag: CeltDecDiag {1388 diag: CeltDecDiag {
1391 silence: false,1389 silence: false,
@@ -1522,7 +1520,6 @@ impl CeltDecoder {
1522 false1520 false
1523 };1521 };
1524 let short_blocks = if transient { m } else { 0 };1522 let short_blocks = if transient { m } else { 0 };
1525- self.plc.transient = transient;
1526 1523
1527 let intra = if tell + 3 <= total_bits {1524 let intra = if tell + 3 <= total_bits {
1528 dec.dec_bit_logp(3)1525 dec.dec_bit_logp(3)
@@ -2889,8 +2886,7 @@ impl CeltDecoder {
2889 self.decode_mem2886 self.decode_mem
2890 .copy_within(base + n..base + DECODE_BUFFER, base);2887 .copy_within(base + n..base + DECODE_BUFFER, base);
2891 }2888 }
2892- let short_blocks = if self.plc.transient { m } else { 0 };2889+ self.inverse_mdcts(0, lm, n, cc);
2893- self.inverse_mdcts(short_blocks, lm, n, cc);
2894 }2890 }
2895 2891
2896 fn plc_pitch_search(&self) -> usize {2892 fn plc_pitch_search(&self) -> usize {
crates/ec-opus/src/encoder.rsmodified+123 -6
@@ -87,6 +87,28 @@ pub enum Application {
87 LowDelay,87 LowDelay,
88 }88 }
89 89
90+const DTX_START_Q1: i32 = 10 * 2 * 20;
91+const DTX_END_Q1: i32 = (10 + 20) * 2 * 20;
92+const DTX_ACTIVITY_THRESHOLD: f32 = 0.1;
93+const DTX_PSEUDO_SNR_THRESHOLD: f32 = 316.23;
94+const DTX_SILENCE: f32 = 1.0 / 16_777_216.0;
95+
96+/// The TOC-only packet libopus sends in DTX: code 0 is the TOC alone; code 3
97+/// keeps its frame-count byte with no frames. Self-delimited framing adds a
98+/// zero frame length after it.
99+fn dtx_packet(toc: u8, count: u8, self_delimited: bool) -> ([u8; 3], usize) {
100+ let mut bytes = [0u8; 3];
101+ let len = if toc & 3 == 3 {
102+ bytes[0] = toc;
103+ bytes[1] = count & 0x3F;
104+ if self_delimited { 3 } else { 2 }
105+ } else {
106+ bytes[0] = toc & !3;
107+ if self_delimited { 2 } else { 1 }
108+ };
109+ (bytes, len)
110+}
111+
90 /// One elementary Opus encoder: mono or stereo.112 /// One elementary Opus encoder: mono or stereo.
91 #[derive(Clone, Debug)]113 #[derive(Clone, Debug)]
92 pub struct Encoder {114 pub struct Encoder {
@@ -157,8 +179,13 @@ pub struct Encoder {
157 lbrr_coded: bool,179 lbrr_coded: bool,
158 fec_bandwidth: Option<Bandwidth>,180 fec_bandwidth: Option<Bandwidth>,
159 last_silk: Option<u8>,181 last_silk: Option<u8>,
182+ use_dtx: bool,
183+ nb_no_activity_ms_q1: i32,
184+ peak_signal_energy: f32,
160 }185 }
161 186
187+const STEREO_TAG: u8 = 100;
188+
162 fn toc_bandwidth(toc: u8) -> Bandwidth {189 fn toc_bandwidth(toc: u8) -> Bandwidth {
163 const BW: [Bandwidth; 5] = [190 const BW: [Bandwidth; 5] = [
164 Bandwidth::Narrow,191 Bandwidth::Narrow,
@@ -245,6 +272,9 @@ impl Encoder {
245 lbrr_coded: false,272 lbrr_coded: false,
246 fec_bandwidth: None,273 fec_bandwidth: None,
247 last_silk: None,274 last_silk: None,
275+ use_dtx: false,
276+ nb_no_activity_ms_q1: 0,
277+ peak_signal_energy: 0.0,
248 };278 };
249 // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how279 // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how
250 // the gate rows at `set_libopus_input_alignment` were produced.280 // the gate rows at `set_libopus_input_alignment` were produced.
@@ -397,6 +427,46 @@ impl Encoder {
397 self.packet_loss_perc = perc.min(100);427 self.packet_loss_perc = perc.min(100);
398 }428 }
399 429
430+ /// OPUS_SET_DTX: send TOC-only packets during silence/inactivity (after 200 ms), refreshing every 400 ms.
431+ pub fn set_dtx(&mut self, on: bool) {
432+ self.use_dtx = on;
433+ }
434+
435+ /// libopus `decide_dtx_mode` plus the activity test of `opus_encode_native`
436+ /// for one frame: true when this frame's packet is a DTX one.
437+ fn dtx_frame(&mut self, pcm: &[f32], frame_size: usize) -> bool {
438+ if !self.use_dtx {
439+ return false;
440+ }
441+ let n = frame_size * self.channels;
442+ let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32;
443+ let is_silence = pcm.iter().all(|x| x.abs() <= DTX_SILENCE);
444+ let (valid, prob) = (self.info.valid, self.info.activity_probability);
445+ if !is_silence && valid && prob > DTX_ACTIVITY_THRESHOLD {
446+ self.peak_signal_energy = (0.999 * self.peak_signal_energy).max(energy);
447+ }
448+ let active = if is_silence {
449+ false
450+ } else if valid {
451+ prob >= DTX_ACTIVITY_THRESHOLD
452+ || self.peak_signal_energy < DTX_PSEUDO_SNR_THRESHOLD * energy
453+ } else {
454+ true
455+ };
456+ if active {
457+ self.nb_no_activity_ms_q1 = 0;
458+ return false;
459+ }
460+ self.nb_no_activity_ms_q1 += 2 * 1000 * frame_size as i32 / self.sample_rate as i32;
461+ if self.nb_no_activity_ms_q1 > DTX_START_Q1 {
462+ if self.nb_no_activity_ms_q1 <= DTX_END_Q1 {
463+ return true;
464+ }
465+ self.nb_no_activity_ms_q1 = DTX_START_Q1;
466+ }
467+ false
468+ }
469+
400 /// Current target bitrate.470 /// Current target bitrate.
401 pub fn bitrate(&self) -> u32 {471 pub fn bitrate(&self) -> u32 {
402 self.bitrate472 self.bitrate
@@ -453,6 +523,8 @@ impl Encoder {
453 self.lbrr_coded = false;523 self.lbrr_coded = false;
454 self.fec_bandwidth = None;524 self.fec_bandwidth = None;
455 self.last_silk = None;525 self.last_silk = None;
526+ self.nb_no_activity_ms_q1 = 0;
527+ self.peak_signal_energy = 0.0;
456 }528 }
457 529
458 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])530 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])
@@ -721,7 +793,12 @@ impl Encoder {
721 if let Some(fs_khz) = self.silk_choice(frame_48k) {793 if let Some(fs_khz) = self.silk_choice(frame_48k) {
722 let budget = self.packet_budget(frame_48k, cap);794 let budget = self.packet_budget(frame_48k, cap);
723 if self.channels == 2 {795 if self.channels == 2 {
724- self.last_silk = None;796+ let (lbrr, loss, same) = (
797+ self.lbrr_coded,
798+ self.packet_loss_perc,
799+ self.last_silk == Some(fs_khz as u8 + STEREO_TAG),
800+ );
801+ self.last_silk = Some(fs_khz as u8 + STEREO_TAG);
725 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);802 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
726 if frame_48k > 960 {803 if frame_48k > 960 {
727 return self.encode_stereo_silk_multiframe(fs_khz, frame_48k);804 return self.encode_stereo_silk_multiframe(fs_khz, frame_48k);
@@ -737,6 +814,11 @@ impl Encoder {
737 .silk_stereo_wb814 .silk_stereo_wb
738 .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))),815 .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))),
739 };816 };
817+ if !same {
818+ enc.drop_lbrr();
819+ }
820+ enc.set_lbrr(lbrr, loss);
821+ enc.set_packet_loss(loss);
740 enc.set_bitrate(self.bitrate);822 enc.set_bitrate(self.bitrate);
741 enc.set_max_bytes(budget);823 enc.set_max_bytes(budget);
742 let n =824 let n =
@@ -765,6 +847,7 @@ impl Encoder {
765 enc.drop_lbrr();847 enc.drop_lbrr();
766 }848 }
767 enc.set_lbrr(lbrr, loss);849 enc.set_lbrr(lbrr, loss);
850+ enc.set_packet_loss(loss);
768 // Keep SILK's own reservoir-based rate control tracking the851 // Keep SILK's own reservoir-based rate control tracking the
769 // Encoder's current target on every frame — cheap (an Option<u32>852 // Encoder's current target on every frame — cheap (an Option<u32>
770 // store) and catches set_bitrate calls made between frames.853 // store) and catches set_bitrate calls made between frames.
@@ -928,8 +1011,7 @@ impl Encoder {
928 1011
929 fn fec_for(&self, frame_48k: usize) -> (bool, Option<Bandwidth>) {1012 fn fec_for(&self, frame_48k: usize) -> (bool, Option<Bandwidth>) {
930 if !self.inband_fec1013 if !self.inband_fec
931- || self.channels != 11014+ || !(matches!(frame_48k, 480 | 960) || (self.channels == 1 && frame_48k <= 2880))
932- || !matches!(frame_48k, 480 | 960)
933 || self.mode == Some(Mode::Celt)1015 || self.mode == Some(Mode::Celt)
934 {1016 {
935 return (false, None);1017 return (false, None);
@@ -1140,6 +1222,7 @@ impl Encoder {
1140 Err(e) => Err(e),1222 Err(e) => Err(e),
1141 Ok((toc, payload)) => {1223 Ok((toc, payload)) => {
1142 let n = payload.len();1224 let n = payload.len();
1225+ let count = payload.first().copied().unwrap_or(0);
1143 if out.len() < 1 + n {1226 if out.len() < 1 + n {
1144 Err(Error::corrupt(format!(1227 Err(Error::corrupt(format!(
1145 "opus encode: packet needs {} bytes, buffer holds {}",1228 "opus encode: packet needs {} bytes, buffer holds {}",
@@ -1149,7 +1232,18 @@ impl Encoder {
1149 } else {1232 } else {
1150 out[0] = toc;1233 out[0] = toc;
1151 out[1..1 + n].copy_from_slice(payload);1234 out[1..1 + n].copy_from_slice(payload);
1152- Ok(1 + n)1235+ if self.dtx_frame(pcm, frame_size) {
1236+ self.final_range = 0;
1237+ let (bytes, len) = dtx_packet(toc, count, false);
1238+ if out.len() < len {
1239+ Err(Error::corrupt("opus encode: DTX packet buffer too small"))
1240+ } else {
1241+ out[..len].copy_from_slice(&bytes[..len]);
1242+ Ok(len)
1243+ }
1244+ } else {
1245+ Ok(1 + n)
1246+ }
1153 }1247 }
1154 }1248 }
1155 };1249 };
@@ -1177,6 +1271,7 @@ impl Encoder {
1177 let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(3)) {1271 let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(3)) {
1178 Err(e) => Err(e),1272 Err(e) => Err(e),
1179 Ok((toc, payload)) => {1273 Ok((toc, payload)) => {
1274+ let count = payload.first().copied().unwrap_or(0);
1180 let (head, last) = if toc & 3 == 3 {1275 let (head, last) = if toc & 3 == 3 {
1181 let count = usize::from(payload[0] & 0x3F);1276 let count = usize::from(payload[0] & 0x3F);
1182 let mut pos = 1;1277 let mut pos = 1;
@@ -1210,7 +1305,18 @@ impl Encoder {
1210 out[1..1 + head].copy_from_slice(&payload[..head]);1305 out[1..1 + head].copy_from_slice(&payload[..head]);
1211 out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]);1306 out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]);
1212 out[1 + head + len_bytes..total].copy_from_slice(&payload[head..]);1307 out[1 + head + len_bytes..total].copy_from_slice(&payload[head..]);
1213- Ok(total)1308+ if self.dtx_frame(pcm, frame_size) {
1309+ self.final_range = 0;
1310+ let (bytes, len) = dtx_packet(toc, count, true);
1311+ if out.len() < len {
1312+ Err(Error::corrupt("opus encode: DTX packet buffer too small"))
1313+ } else {
1314+ out[..len].copy_from_slice(&bytes[..len]);
1315+ Ok(len)
1316+ }
1317+ } else {
1318+ Ok(total)
1319+ }
1214 }1320 }
1215 }1321 }
1216 }1322 }
@@ -1270,10 +1376,20 @@ impl Encoder {
1270 if self.lbrr_coded { Bandwidth::Full } else { bandwidth },1376 if self.lbrr_coded { Bandwidth::Full } else { bandwidth },
1271 );1377 );
1272 if self.channels == 2 {1378 if self.channels == 2 {
1273- self.last_silk = None;1379+ let (lbrr, loss, same) = (
1380+ self.lbrr_coded,
1381+ self.packet_loss_perc,
1382+ self.last_silk == Some(16 + STEREO_TAG),
1383+ );
1384+ self.last_silk = Some(16 + STEREO_TAG);
1274 let silk = self1385 let silk = self
1275 .silk_stereo_wb1386 .silk_stereo_wb
1276 .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true)));1387 .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true)));
1388+ if !same {
1389+ silk.drop_lbrr();
1390+ }
1391+ silk.set_lbrr(lbrr, loss);
1392+ silk.set_packet_loss(loss);
1277 silk.set_bitrate(silk_rate);1393 silk.set_bitrate(silk_rate);
1278 silk.set_max_bytes(silk_max);1394 silk.set_max_bytes(silk_max);
1279 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;1395 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
@@ -1290,6 +1406,7 @@ impl Encoder {
1290 silk.drop_lbrr();1406 silk.drop_lbrr();
1291 }1407 }
1292 silk.set_lbrr(lbrr, loss);1408 silk.set_lbrr(lbrr, loss);
1409+ silk.set_packet_loss(loss);
1293 silk.set_bitrate(silk_rate);1410 silk.set_bitrate(silk_rate);
1294 silk.set_max_bytes(silk_max);1411 silk.set_max_bytes(silk_max);
1295 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;1412 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
crates/ec-opus/src/lib.rsmodified+1 -1
@@ -103,7 +103,7 @@ pub struct Decoder {
103 channels: usize,103 channels: usize,
104 downsample: usize,104 downsample: usize,
105 celt: CeltDecoder,105 celt: CeltDecoder,
106- /// Boxed because a `SilkDecoder` is 6496 bytes, 83% of what a `Decoder`106+ /// Boxed because a `SilkDecoder` is 6512 bytes, 83% of what a `Decoder`
107 /// costs a caller taking one BY VALUE from `Decoder::new`. It is the107 /// costs a caller taking one BY VALUE from `Decoder::new`. It is the
108 /// decoder's largest field and its only large one; `celt` is 1448.108 /// decoder's largest field and its only large one; `celt` is 1448.
109 /// `Stack`: crate::stack_budget.109 /// `Stack`: crate::stack_budget.
crates/ec-opus/src/multistream.rsmodified+104 -28
@@ -20,6 +20,7 @@
20 20
21 use ec_core::{Error, Result};21 use ec_core::{Error, Result};
22 22
23+use crate::packet::Packet;
23 use crate::Decoder;24 use crate::Decoder;
24 25
25 /// A decoder for a multichannel Opus stream, mono through 255 channels.26 /// A decoder for a multichannel Opus stream, mono through 255 channels.
@@ -32,6 +33,8 @@ pub struct MultistreamDecoder {
32 sample_rate: u32,33 sample_rate: u32,
33 /// Scratch for one stream's output.34 /// Scratch for one stream's output.
34 buf: Vec<f32>,35 buf: Vec<f32>,
36+ /// Scratch for one stream's first frame as a plain packet.
37+ fec: Vec<u8>,
35 }38 }
36 39
37 impl MultistreamDecoder {40 impl MultistreamDecoder {
@@ -94,6 +97,7 @@ impl MultistreamDecoder {
94 channels: mapping.len(),97 channels: mapping.len(),
95 sample_rate,98 sample_rate,
96 buf: vec![0.0; 2 * 5760],99 buf: vec![0.0; 2 * 5760],
100+ fec: Vec::with_capacity(1276),
97 })101 })
98 }102 }
99 103
@@ -166,45 +170,105 @@ impl MultistreamDecoder {
166 rest = &rest[consumed.min(rest.len())..];170 rest = &rest[consumed.min(rest.len())..];
167 if s == 0 {171 if s == 0 {
168 frame_size = n;172 frame_size = n;
169- if out.len() < n * self.channels {173+ self.check_out(frame_size, out)?;
170- return Err(Error::corrupt(format!(
171- "opus multistream: output buffer holds {} samples, packet needs {}",
172- out.len(),
173- n * self.channels
174- )));
175- }
176 } else if n != frame_size {174 } else if n != frame_size {
177 return Err(Error::corrupt(format!(175 return Err(Error::corrupt(format!(
178 "opus multistream: stream {s} decoded {n} samples, stream 0 gave {frame_size}"176 "opus multistream: stream {s} decoded {n} samples, stream 0 gave {frame_size}"
179 )));177 )));
180 }178 }
181- // Route this stream's channels to the outputs that name them.179+ self.route(s, frame_size, out);
182- for (c, &m) in self.mapping.iter().enumerate() {180+ }
183- if m == 255 {181+ self.silence(frame_size, out);
184- continue;182+ Ok(frame_size)
183+ }
184+
185+ /// Conceals `frame_size` lost samples per channel on every stream
186+ /// (libopus `opus_multistream_decode(NULL)`), returning samples per
187+ /// channel.
188+ pub fn conceal(&mut self, frame_size: usize, out: &mut [f32]) -> Result<usize> {
189+ self.check_out(frame_size, out)?;
190+ for s in 0..self.streams.len() {
191+ self.streams[s].conceal(frame_size, &mut self.buf)?;
192+ self.route(s, frame_size, out);
193+ }
194+ self.silence(frame_size, out);
195+ Ok(frame_size)
196+ }
197+
198+ /// Recovers a lost multistream packet from the in-band FEC of the packet
199+ /// after it (libopus `decode_fec=1`). Each stream's first frame is handed
200+ /// to that stream's FEC path; a stream whose bytes cannot be read, and
201+ /// every stream after it, is concealed. Returns samples per channel.
202+ pub fn decode_fec(
203+ &mut self,
204+ next_packet: &[u8],
205+ frame_size: usize,
206+ out: &mut [f32],
207+ ) -> Result<usize> {
208+ self.check_out(frame_size, out)?;
209+ let nb_streams = self.streams.len();
210+ let mut rest = next_packet;
211+ for s in 0..nb_streams {
212+ let last = s == nb_streams - 1;
213+ match first_frame(rest, !last, &mut self.fec) {
214+ Ok(consumed) => {
215+ rest = &rest[consumed.min(rest.len())..];
216+ self.streams[s].decode_fec(&self.fec, frame_size, &mut self.buf)?;
217+ }
218+ Err(_) => {
219+ rest = &[];
220+ self.streams[s].conceal(frame_size, &mut self.buf)?;
185 }221 }
186- let m = m as usize;222+ }
187- let src = if s < self.coupled {223+ self.route(s, frame_size, out);
188- if m == 2 * s {224+ }
189- Some(0)225+ self.silence(frame_size, out);
190- } else if m == 2 * s + 1 {226+ Ok(frame_size)
191- Some(1)227+ }
192- } else {228+
193- None229+ fn check_out(&self, frame_size: usize, out: &[f32]) -> Result<()> {
194- }230+ if out.len() < frame_size * self.channels {
195- } else if m == s + self.coupled {231+ return Err(Error::corrupt(format!(
232+ "opus multistream: output buffer holds {} samples, packet needs {}",
233+ out.len(),
234+ frame_size * self.channels
235+ )));
236+ }
237+ Ok(())
238+ }
239+
240+ /// Copies stream `s`'s channels from `self.buf` to the output channels
241+ /// the mapping names.
242+ fn route(&self, s: usize, frame_size: usize, out: &mut [f32]) {
243+ let stream_channels = if s < self.coupled { 2 } else { 1 };
244+ for (c, &m) in self.mapping.iter().enumerate() {
245+ if m == 255 {
246+ continue;
247+ }
248+ let m = m as usize;
249+ let src = if s < self.coupled {
250+ if m == 2 * s {
196 Some(0)251 Some(0)
252+ } else if m == 2 * s + 1 {
253+ Some(1)
197 } else {254 } else {
198 None255 None
199- };256+ }
200- if let Some(off) = src {257+ } else if m == s + self.coupled {
201- for i in 0..frame_size {258+ Some(0)
202- out[self.channels * i + c] = self.buf[stream_channels * i + off];259+ } else {
203- }260+ None
261+ };
262+ if let Some(off) = src {
263+ for i in 0..frame_size {
264+ out[self.channels * i + c] = self.buf[stream_channels * i + off];
204 }265 }
205 }266 }
206 }267 }
207- // Channels the mapping leaves unassigned are silent.268+ }
269+
270+ /// Channels the mapping leaves unassigned are silent.
271+ fn silence(&self, frame_size: usize, out: &mut [f32]) {
208 for (c, &m) in self.mapping.iter().enumerate() {272 for (c, &m) in self.mapping.iter().enumerate() {
209 if m == 255 {273 if m == 255 {
210 for i in 0..frame_size {274 for i in 0..frame_size {
@@ -212,10 +276,22 @@ impl MultistreamDecoder {
212 }276 }
213 }277 }
214 }278 }
215- Ok(frame_size)
216 }279 }
217 }280 }
218 281
282+/// Reads the first frame of the stream packet at the head of `data` and
283+/// rebuilds it as a plain code-0 packet in `scratch`, returning the bytes the
284+/// stream packet occupied.
285+fn first_frame(data: &[u8], self_delimited: bool, scratch: &mut Vec<u8>) -> Result<usize> {
286+ let packet = Packet::parse(data, self_delimited)?;
287+ let first: &[u8] = packet.frames.first().copied().unwrap_or(&[]);
288+ let toc = packet.toc;
289+ scratch.clear();
290+ scratch.push((toc.config << 3) | (u8::from(toc.stereo) << 2));
291+ scratch.extend_from_slice(first);
292+ Ok(packet.consumed)
293+}
294+
219 #[cfg(test)]295 #[cfg(test)]
220 mod tests {296 mod tests {
221 use super::*;297 use super::*;
crates/ec-opus/src/multistream_enc.rsmodified+14 -0
@@ -136,6 +136,20 @@ impl MultistreamEncoder {
136 }136 }
137 }137 }
138 138
139+ /// OPUS_SET_INBAND_FEC on every stream.
140+ pub fn set_inband_fec(&mut self, on: bool) {
141+ for enc in self.streams.iter_mut() {
142+ enc.set_inband_fec(on);
143+ }
144+ }
145+
146+ /// OPUS_SET_PACKET_LOSS_PERC on every stream.
147+ pub fn set_packet_loss_perc(&mut self, perc: u8) {
148+ for enc in self.streams.iter_mut() {
149+ enc.set_packet_loss_perc(perc);
150+ }
151+ }
152+
139 /// Drops all inter-frame state in every stream.153 /// Drops all inter-frame state in every stream.
140 pub fn reset(&mut self) {154 pub fn reset(&mut self) {
141 for enc in self.streams.iter_mut() {155 for enc in self.streams.iter_mut() {
crates/ec-opus/src/silk.rsmodified+141 -1
@@ -14,7 +14,8 @@
14 //!14 //!
15 //! LBRR (in-band FEC) frames are decoded through [`SilkFrameMode::Lbrr`], and15 //! LBRR (in-band FEC) frames are decoded through [`SilkFrameMode::Lbrr`], and
16 //! lost frames are concealed by the packet loss concealment of the reference16 //! lost frames are concealed by the packet loss concealment of the reference
17-//! (`silk/PLC.c`), selected with [`SilkFrameMode::Lost`].17+//! (`silk/PLC.c`), selected with [`SilkFrameMode::Lost`], and comfort noise
18+//! (`silk/CNG.c`) is mixed into frames while the signal is noise-like.
18 19
19 // SILK is transliterated fixed-point arithmetic: the loops below index parallel20 // SILK is transliterated fixed-point arithmetic: the loops below index parallel
20 // arrays by position because the reference's index arithmetic is the21 // arrays by position because the reference's index arithmetic is the
@@ -51,7 +52,12 @@ const N_RATE_LEVELS: usize = 10;
51 pub(crate) const PE_MIN_LAG_MS: i32 = 2;52 pub(crate) const PE_MIN_LAG_MS: i32 = 2;
52 pub(crate) const PE_MAX_LAG_MS: i32 = 18;53 pub(crate) const PE_MAX_LAG_MS: i32 = 18;
53 const STEREO_INTERP_LEN_MS: usize = 8;54 const STEREO_INTERP_LEN_MS: usize = 8;
55+const TYPE_NO_VOICE_ACTIVITY: i32 = 0;
54 const TYPE_VOICED: i32 = 2;56 const TYPE_VOICED: i32 = 2;
57+const CNG_BUF_MASK_MAX: i32 = 255;
58+const CNG_GAIN_SMTH_Q16: i32 = 4634;
59+const CNG_NLSF_SMTH_Q16: i32 = 16348;
60+const CNG_GAIN_SMTH_THRESHOLD_Q16: i32 = 46396;
55 const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;61 const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;
56 const BWE_COEF_Q16: i32 = 64881;62 const BWE_COEF_Q16: i32 = 64881;
57 const BWE_AFTER_LOSS_Q16: i32 = 63570;63 const BWE_AFTER_LOSS_Q16: i32 = 63570;
@@ -124,6 +130,11 @@ pub(crate) fn smulbb(a: i32, b: i32) -> i32 {
124 (a as i16 as i32).wrapping_mul(b as i16 as i32)130 (a as i16 as i32).wrapping_mul(b as i16 as i32)
125 }131 }
126 132
133+#[inline]
134+fn smultt(a: i32, b: i32) -> i32 {
135+ (a >> 16) * (b >> 16)
136+}
137+
127 #[inline]138 #[inline]
128 fn smlabb(a: i32, b: i32, c: i32) -> i32 {139 fn smlabb(a: i32, b: i32, c: i32) -> i32 {
129 a.wrapping_add(smulbb(b, c))140 a.wrapping_add(smulbb(b, c))
@@ -358,6 +369,30 @@ struct PlcState {
358 subfr_length: usize,369 subfr_length: usize,
359 }370 }
360 371
372+/// Comfort noise state (`silk_CNG_struct`).
373+#[derive(Clone, Debug)]
374+struct CngState {
375+ exc_buf_q14: [i32; MAX_FRAME_LENGTH],
376+ smth_nlsf_q15: [i16; MAX_LPC_ORDER],
377+ synth_state: [i32; MAX_LPC_ORDER],
378+ smth_gain_q16: i32,
379+ rand_seed: i32,
380+ fs_khz: usize,
381+}
382+
383+impl Default for CngState {
384+ fn default() -> Self {
385+ CngState {
386+ exc_buf_q14: [0; MAX_FRAME_LENGTH],
387+ smth_nlsf_q15: [0; MAX_LPC_ORDER],
388+ synth_state: [0; MAX_LPC_ORDER],
389+ smth_gain_q16: 0,
390+ rand_seed: 0,
391+ fs_khz: 0,
392+ }
393+ }
394+}
395+
361 /// One SILK channel's inter-frame state.396 /// One SILK channel's inter-frame state.
362 #[derive(Clone, Debug)]397 #[derive(Clone, Debug)]
363 struct ChannelState {398 struct ChannelState {
@@ -389,6 +424,7 @@ struct ChannelState {
389 lbrr_flags: [bool; 3],424 lbrr_flags: [bool; 3],
390 resampler: Resampler,425 resampler: Resampler,
391 plc: PlcState,426 plc: PlcState,
427+ cng: Box<CngState>,
392 loss_cnt: i32,428 loss_cnt: i32,
393 }429 }
394 430
@@ -421,6 +457,7 @@ impl ChannelState {
421 lbrr_flags: [false; 3],457 lbrr_flags: [false; 3],
422 resampler: Resampler::default(),458 resampler: Resampler::default(),
423 plc: PlcState::default(),459 plc: PlcState::default(),
460+ cng: Box::default(),
424 loss_cnt: 0,461 loss_cnt: 0,
425 }462 }
426 }463 }
@@ -1686,6 +1723,108 @@ impl ChannelState {
1686 }1723 }
1687 }1724 }
1688 1725
1726+/// `silk_CNG_exc`: draws the comfort noise excitation from the saved history.
1727+fn cng_exc(exc: &mut [i32], exc_buf: &[i32], rand_seed: &mut i32) {
1728+ let mut exc_mask = CNG_BUF_MASK_MAX;
1729+ while exc_mask > exc.len() as i32 {
1730+ exc_mask >>= 1;
1731+ }
1732+ let mut seed = *rand_seed;
1733+ for v in exc.iter_mut() {
1734+ seed = silk_rand(seed);
1735+ let idx = ((seed >> 24) & exc_mask) as usize;
1736+ *v = exc_buf[idx];
1737+ }
1738+ *rand_seed = seed;
1739+}
1740+
1741+impl ChannelState {
1742+ /// `silk_CNG_Reset`.
1743+ fn cng_reset(&mut self) {
1744+ let order = self.lpc_order;
1745+ let step = 32767 / (order as i32 + 1);
1746+ let mut acc = 0i32;
1747+ for i in 0..order {
1748+ acc += step;
1749+ self.cng.smth_nlsf_q15[i] = acc as i16;
1750+ }
1751+ self.cng.smth_gain_q16 = 0;
1752+ self.cng.rand_seed = 3176576;
1753+ }
1754+
1755+ /// `silk_CNG`: mixes comfort noise into `frame`.
1756+ fn cng(&mut self, ctrl: &FrameCtrl, frame: &mut [i16]) {
1757+ if self.fs_khz != self.cng.fs_khz {
1758+ self.cng_reset();
1759+ self.cng.fs_khz = self.fs_khz;
1760+ }
1761+ let order = self.lpc_order;
1762+ let sl = self.subfr_length;
1763+ let nb = self.nb_subfr;
1764+ if self.loss_cnt == 0 && self.prev_signal_type == TYPE_NO_VOICE_ACTIVITY {
1765+ for i in 0..order {
1766+ let d = self.prev_nlsf_q15[i] as i32 - self.cng.smth_nlsf_q15[i] as i32;
1767+ self.cng.smth_nlsf_q15[i] =
1768+ (self.cng.smth_nlsf_q15[i] as i32 + smulwb(d, CNG_NLSF_SMTH_Q16)) as i16;
1769+ }
1770+ let mut max_gain = 0;
1771+ let mut subfr = 0;
1772+ for i in 0..nb {
1773+ if ctrl.gains_q16[i] > max_gain {
1774+ max_gain = ctrl.gains_q16[i];
1775+ subfr = i;
1776+ }
1777+ }
1778+ self.cng.exc_buf_q14.copy_within(0..(nb - 1) * sl, sl);
1779+ self.cng.exc_buf_q14[..sl].copy_from_slice(&self.exc_q14[subfr * sl..(subfr + 1) * sl]);
1780+ for i in 0..nb {
1781+ let g = ctrl.gains_q16[i];
1782+ self.cng.smth_gain_q16 += smulwb(g - self.cng.smth_gain_q16, CNG_GAIN_SMTH_Q16);
1783+ if smulww(self.cng.smth_gain_q16, CNG_GAIN_SMTH_THRESHOLD_Q16) > g {
1784+ self.cng.smth_gain_q16 = g;
1785+ }
1786+ }
1787+ }
1788+ if self.loss_cnt != 0 {
1789+ let length = frame.len();
1790+ let smth = self.cng.smth_gain_q16;
1791+ let mut gain_q16 = smulww(self.plc.rand_scale_q14 as i32, self.plc.prev_gain_q16[1]);
1792+ if gain_q16 >= 1 << 21 || smth > 1 << 23 {
1793+ gain_q16 = smultt(gain_q16, gain_q16);
1794+ gain_q16 = smultt(smth, smth).wrapping_sub(gain_q16 << 5);
1795+ gain_q16 = sqrt_approx(gain_q16) << 16;
1796+ } else {
1797+ gain_q16 = smulww(gain_q16, gain_q16);
1798+ gain_q16 = smulww(smth, smth).wrapping_sub(gain_q16 << 5);
1799+ gain_q16 = sqrt_approx(gain_q16) << 8;
1800+ }
1801+ let gain_q10 = gain_q16 >> 6;
1802+
1803+ let mut sig = [0i32; MAX_FRAME_LENGTH + MAX_LPC_ORDER];
1804+ cng_exc(
1805+ &mut sig[MAX_LPC_ORDER..MAX_LPC_ORDER + length],
1806+ &self.cng.exc_buf_q14,
1807+ &mut self.cng.rand_seed,
1808+ );
1809+ let a_q12 = nlsf2a(&self.cng.smth_nlsf_q15, order);
1810+ sig[..MAX_LPC_ORDER].copy_from_slice(&self.cng.synth_state);
1811+ for i in 0..length {
1812+ let mut pred = (order >> 1) as i32;
1813+ for j in 0..order {
1814+ pred = smlawb(pred, sig[MAX_LPC_ORDER + i - j - 1], a_q12[j] as i32);
1815+ }
1816+ let s = MAX_LPC_ORDER + i;
1817+ sig[s] = sig[s].saturating_add(lshift_sat32(pred, 4));
1818+ let noise = sat16(rshift_round(smulww(sig[s], gain_q10), 8));
1819+ frame[i] = sat16(frame[i] as i32 + noise as i32);
1820+ }
1821+ self.cng.synth_state.copy_from_slice(&sig[length..length + MAX_LPC_ORDER]);
1822+ } else {
1823+ self.cng.synth_state[..order].fill(0);
1824+ }
1825+ }
1826+}
1827+
1689 /// `silk_LPC_analysis_filter`: the whitening filter used to rebuild the LTP1828 /// `silk_LPC_analysis_filter`: the whitening filter used to rebuild the LTP
1690 /// state from previously decoded output.1829 /// state from previously decoded output.
1691 fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b_q12: &[i16], len: usize, d: usize) {1830 fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b_q12: &[i16], len: usize, d: usize) {
@@ -1869,6 +2008,7 @@ fn decode_frame(
1869 let mv_len = ch.ltp_mem_length - fl;2008 let mv_len = ch.ltp_mem_length - fl;
1870 ch.out_buf.copy_within(fl..fl + mv_len, 0);2009 ch.out_buf.copy_within(fl..fl + mv_len, 0);
1871 ch.out_buf[mv_len..mv_len + fl].copy_from_slice(&out[..fl]);2010 ch.out_buf[mv_len..mv_len + fl].copy_from_slice(&out[..fl]);
2011+ ch.cng(&ctrl, &mut out[..fl]);
1872 ch.plc_glue_frames(&mut out[..fl]);2012 ch.plc_glue_frames(&mut out[..fl]);
1873 ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1];2013 ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1];
1874 fl2014 fl
crates/ec-opus/src/silk_enc_write.rsmodified+188 -73
@@ -97,10 +97,15 @@ pub struct SilkEncoder {
97 last_diag: SilkFrameDiag,97 last_diag: SilkFrameDiag,
98 lbrr_enabled: bool,98 lbrr_enabled: bool,
99 lbrr_gain_increases: i32,99 lbrr_gain_increases: i32,
100- pending_lbrr: Option<Box<Trial>>,100+ pending_lbrr: [Option<Box<Trial>>; MAX_PACKET_FRAMES],
101- lbrr_in_packet: Option<Box<Trial>>,101+ lbrr_in_packet: [Option<Box<Trial>>; MAX_PACKET_FRAMES],
102+ lbrr_chain: Option<i32>,
103+ loss_perc: u8,
104+ last_snr_db: f32,
102 }105 }
103 106
107+const MAX_PACKET_FRAMES: usize = 3;
108+
104 /// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth109 /// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth
105 /// expansions of the LPC, harmonic comb depth, voiced spectral tilt, and the110 /// expansions of the LPC, harmonic comb depth, voiced spectral tilt, and the
106 /// linear ratio of one gain-quantiser step (2^(1.365 dB / 6.02)).111 /// linear ratio of one gain-quantiser step (2^(1.365 dB / 6.02)).
@@ -182,8 +187,11 @@ impl SilkEncoder {
182 last_diag: SilkFrameDiag::default(),187 last_diag: SilkFrameDiag::default(),
183 lbrr_enabled: false,188 lbrr_enabled: false,
184 lbrr_gain_increases: 7,189 lbrr_gain_increases: 7,
185- pending_lbrr: None,190+ pending_lbrr: Default::default(),
186- lbrr_in_packet: None,191+ lbrr_in_packet: Default::default(),
192+ lbrr_chain: None,
193+ loss_perc: 0,
194+ last_snr_db: 0.0,
187 }195 }
188 }196 }
189 197
@@ -225,18 +233,28 @@ impl SilkEncoder {
225 7233 7
226 };234 };
227 } else {235 } else {
228- self.pending_lbrr = None;236+ self.pending_lbrr = Default::default();
229 }237 }
230 self.lbrr_enabled = enabled;238 self.lbrr_enabled = enabled;
231 }239 }
232 240
233- /// Drops the LBRR frame waiting for the next packet (that packet will not follow the frame it protects).241+ /// Drops the LBRR frames waiting for the next packet (that packet will not follow the frames they protect).
234 pub fn drop_lbrr(&mut self) {242 pub fn drop_lbrr(&mut self) {
235- self.pending_lbrr = None;243+ self.pending_lbrr = Default::default();
244+ }
245+
246+ /// Expected packet loss in percent; raises LTP scaling (libopus silk_LTP_scale_ctrl).
247+ pub fn set_packet_loss(&mut self, perc: u8) {
248+ self.loss_perc = perc;
236 }249 }
237 250
238 fn reset_state(&mut self) {251 fn reset_state(&mut self) {
252+ let (lbrr, gain_increases, loss_perc) =
253+ (self.lbrr_enabled, self.lbrr_gain_increases, self.loss_perc);
239 *self = Self::with_fs_khz(self.fs_khz);254 *self = Self::with_fs_khz(self.fs_khz);
255+ self.lbrr_enabled = lbrr;
256+ self.lbrr_gain_increases = gain_increases;
257+ self.loss_perc = loss_perc;
240 }258 }
241 259
242 /// Algorithmic delay in 48 kHz samples: the analysis resampler only260 /// Algorithmic delay in 48 kHz samples: the analysis resampler only
@@ -278,17 +296,17 @@ impl SilkEncoder {
278 let mut frames = Vec::with_capacity(frames_per_packet);296 let mut frames = Vec::with_capacity(frames_per_packet);
279 let sub_ms = if frame_ms == 10 { 10 } else { 20 };297 let sub_ms = if frame_ms == 10 { 10 } else { 20 };
280 let mut prev_signal_type = 0;298 let mut prev_signal_type = 0;
299+ self.lbrr_in_packet = Default::default();
281 for i in 0..frames_per_packet {300 for i in 0..frames_per_packet {
282 let from = i * sub_ms * 48;301 let from = i * sub_ms * 48;
283 let to = from + sub_ms * 48;302 let to = from + sub_ms * 48;
284- let conditional = i > 0;
285 let trial = self.encode_inner(303 let trial = self.encode_inner(
286 &pcm48[from..to],304 &pcm48[from..to],
287 sub_ms,305 sub_ms,
288 None,306 None,
289- conditional,307+ i,
308+ frames_per_packet,
290 prev_signal_type,309 prev_signal_type,
291- frames_per_packet == 1,
292 )?;310 )?;
293 prev_signal_type = trial.signal_type;311 prev_signal_type = trial.signal_type;
294 frames.push(trial);312 frames.push(trial);
@@ -298,8 +316,9 @@ impl SilkEncoder {
298 }316 }
299 self.range.reset(1275);317 self.range.reset(1275);
300 let refs: Vec<&Trial> = frames.iter().collect();318 let refs: Vec<&Trial> = frames.iter().collect();
301- let lbrr = self.lbrr_in_packet.take();319+ let lbrr = std::mem::take(&mut self.lbrr_in_packet);
302- write_packet_header(&mut self.range, &refs, lbrr.as_deref());320+ let lbrr_refs: [Option<&Trial>; MAX_PACKET_FRAMES] = lbrr.each_ref().map(|t| t.as_deref());
321+ write_packet_header(&mut self.range, &refs, &lbrr_refs[..frames_per_packet]);
303 prev_signal_type = 0;322 prev_signal_type = 0;
304 for (i, frame) in frames.iter().enumerate() {323 for (i, frame) in frames.iter().enumerate() {
305 write_frame_data(&mut self.range, frame, i > 0, prev_signal_type);324 write_frame_data(&mut self.range, frame, i > 0, prev_signal_type);
@@ -347,7 +366,7 @@ impl SilkEncoder {
347 enc: &mut RangeEncoder,366 enc: &mut RangeEncoder,
348 frame_ms: usize,367 frame_ms: usize,
349 ) -> Result<()> {368 ) -> Result<()> {
350- let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0, true)?;369+ let trial = self.encode_inner(pcm48, frame_ms, Some(enc), 0, 1, 0)?;
351 self.voiced_frames += usize::from(trial.voiced);370 self.voiced_frames += usize::from(trial.voiced);
352 Ok(())371 Ok(())
353 }372 }
@@ -396,9 +415,9 @@ impl SilkEncoder {
396 pcm48: &[f32],415 pcm48: &[f32],
397 frame_ms: usize,416 frame_ms: usize,
398 shared: Option<&mut RangeEncoder>,417 shared: Option<&mut RangeEncoder>,
399- conditional: bool,418+ frame: usize,
419+ frames: usize,
400 prev_signal_type: i32,420 prev_signal_type: i32,
401- single_frame_packet: bool,
402 ) -> Result<Trial> {421 ) -> Result<Trial> {
403 assert!(422 assert!(
404 matches!(frame_ms, 10 | 20),423 matches!(frame_ms, 10 | 20),
@@ -409,12 +428,9 @@ impl SilkEncoder {
409 48 * frame_ms,428 48 * frame_ms,
410 "SilkEncoder input is 48 kHz mono"429 "SilkEncoder input is 48 kHz mono"
411 );430 );
412- let pending = if single_frame_packet {431+ let conditional = frame > 0;
413- self.pending_lbrr.take()432+ let single_frame_packet = frames == 1;
414- } else {433+ let pending = self.pending_lbrr[frame].take();
415- self.pending_lbrr = None;
416- None
417- };
418 let fs = self.fs_khz;434 let fs = self.fs_khz;
419 let order = if fs == 16 { MAX_LPC_ORDER } else { 10 };435 let order = if fs == 16 { MAX_LPC_ORDER } else { 10 };
420 let nb_subfr = frame_ms / 5;436 let nb_subfr = frame_ms / 5;
@@ -516,6 +532,7 @@ impl SilkEncoder {
516 // of the best vector is the LTP gain that picks the scale index.532 // of the best vector is the LTP gain that picks the scale index.
517 let mut targets = [0i32; MAX_NB_SUBFR];533 let mut targets = [0i32; MAX_NB_SUBFR];
518 let mut ltp_gain = 0f32;534 let mut ltp_gain = 0f32;
535+ let mut ltp_res_energy = 0f32;
519 {536 {
520 let mut r_ol: Vec<f32> = (-(n as isize)..0).map(whiten).collect();537 let mut r_ol: Vec<f32> = (-(n as isize)..0).map(whiten).collect();
521 r_ol.extend_from_slice(&res);538 r_ol.extend_from_slice(&res);
@@ -534,6 +551,7 @@ impl SilkEncoder {
534 ((0..sub).map(|i| res[k * sub + i].powi(2)).sum(), 0.0)551 ((0..sub).map(|i| res[k * sub + i].powi(2)).sum(), 0.0)
535 };552 };
536 ltp_gain = ltp_gain.max(gsum);553 ltp_gain = ltp_gain.max(gsum);
554+ ltp_res_energy += e;
537 let rms = (e / sub as f32).sqrt();555 let rms = (e / sub as f32).sqrt();
538 targets[k] = ((rms * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32;556 targets[k] = ((rms * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32;
539 }557 }
@@ -548,7 +566,7 @@ impl SilkEncoder {
548 };566 };
549 // Over-unity LTP gain: scale the previous frame's history down so567 // Over-unity LTP gain: scale the previous frame's history down so
550 // quantisation error does not build up through the pitch loop.568 // quantisation error does not build up through the pitch loop.
551- let ltp_scale_index = if !voiced {569+ let mut ltp_scale_index = if !voiced {
552 0570 0
553 } else if ltp_gain > 1.25 {571 } else if ltp_gain > 1.25 {
554 2572 2
@@ -557,6 +575,20 @@ impl SilkEncoder {
557 } else {575 } else {
558 0576 0
559 };577 };
578+ if !conditional && voiced && self.loss_perc > 0 {
579+ let mut round_loss = self.loss_perc as f32 * frames as f32;
580+ if self.lbrr_enabled {
581+ round_loss = 2.0 + round_loss * round_loss / 100.0;
582+ }
583+ let res_energy: f32 = res.iter().map(|v| v * v).sum();
584+ let pred_gain_db =
585+ (10.0 * (res_energy / ltp_res_energy.max(1e-9)).log10()).max(0.0);
586+ let x_gain = pred_gain_db * round_loss;
587+ let snr = self.last_snr_db;
588+ let loss_index = usize::from(x_gain > 2f32.powf(22.66 - snr))
589+ + usize::from(x_gain > 2f32.powf(30.47 - snr));
590+ ltp_scale_index = ltp_scale_index.max(loss_index);
591+ }
560 let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0;592 let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0;
561 // Inactive or low-energy frames (and sparse voiced excitation) take the593 // Inactive or low-energy frames (and sparse voiced excitation) take the
562 // small quantisation offset; dense unvoiced excitation the large one.594 // small quantisation offset; dense unvoiced excitation the large one.
@@ -717,15 +749,15 @@ impl SilkEncoder {
717 // One full trial at a common gain offset (in quantiser steps): returns749 // One full trial at a common gain offset (in quantiser steps): returns
718 // the coded packet body so the rate loop can read its exact size.750 // the coded packet body so the rate loop can read its exact size.
719 let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] };751 let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] };
720- let mut trial = |step: i32| -> Trial {752+ let mut trial = |step: i32, cond: bool, start_prev: i32| -> Trial {
721 let scale = GAIN_STEP.powi(step);753 let scale = GAIN_STEP.powi(step);
722 let mut t = targets;754 let mut t = targets;
723 for v in t.iter_mut() {755 for v in t.iter_mut() {
724 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;756 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;
725 }757 }
726- let mut prev_gain_index = self.prev_gain_index;758+ let mut prev_gain_index = start_prev;
727 let (gain_idx, gains_q16) =759 let (gain_idx, gains_q16) =
728- quantize_gains(&t, &mut prev_gain_index, conditional, nb_subfr);760+ quantize_gains(&t, &mut prev_gain_index, cond, nb_subfr);
729 let (per_index, run) = candidates761 let (per_index, run) = candidates
730 .iter()762 .iter()
731 .map(|&per| (per, run(per, &gains_q16)))763 .map(|&per| (per, run(per, &gains_q16)))
@@ -756,8 +788,9 @@ impl SilkEncoder {
756 };788 };
757 let enc = &mut self.range;789 let enc = &mut self.range;
758 enc.reset(1275);790 enc.reset(1275);
759- write_packet_header(enc, &[&trial], pending.as_deref());791+ let measured_lbrr = [if single_frame_packet { pending.as_deref() } else { None }];
760- write_frame_data(enc, &trial, conditional, prev_signal_type);792+ write_packet_header(enc, &[&trial], &measured_lbrr);
793+ write_frame_data(enc, &trial, cond, prev_signal_type);
761 enc.done();794 enc.done();
762 debug_assert!(!enc.error());795 debug_assert!(!enc.error());
763 let len = enc.range_bytes();796 let len = enc.range_bytes();
@@ -769,7 +802,7 @@ impl SilkEncoder {
769 // Rate control: a common gain offset moves every subframe's pulse802 // Rate control: a common gain offset moves every subframe's pulse
770 // magnitudes together; the reservoir carries each packet's miss.803 // magnitudes together; the reservoir carries each packet's miss.
771 let mut chosen_step = if CARRY_RATE_STEP { self.rate_step } else { 0 };804 let mut chosen_step = if CARRY_RATE_STEP { self.rate_step } else { 0 };
772- let mut best = trial(chosen_step);805+ let mut best = trial(chosen_step, conditional, self.prev_gain_index);
773 if let Some(bps) = self.target_bps {806 if let Some(bps) = self.target_bps {
774 let mut frame_bits = bps as f32 * frame_ms as f32 / 1000.0;807 let mut frame_bits = bps as f32 * frame_ms as f32 / 1000.0;
775 // A packet cap is a promise to fill it: the CBR packet is padded to808 // A packet cap is a promise to fill it: the CBR packet is padded to
@@ -809,7 +842,7 @@ impl SilkEncoder {
809 if step == s0 {842 if step == s0 {
810 break;843 break;
811 }844 }
812- let t = trial(step);845+ let t = trial(step, conditional, self.prev_gain_index);
813 let b1 = bits_of(&t);846 let b1 = bits_of(&t);
814 if (b1 - target).abs() < (b0 - target).abs() {847 if (b1 - target).abs() < (b0 - target).abs() {
815 if b1 != b0 {848 if b1 != b0 {
@@ -845,7 +878,7 @@ impl SilkEncoder {
845 }878 }
846 floor_step = best_step;879 floor_step = best_step;
847 let before = best.bytes.len();880 let before = best.bytes.len();
848- best = trial(step);881+ best = trial(step, conditional, self.prev_gain_index);
849 best_step = step;882 best_step = step;
850 trials += 1;883 trials += 1;
851 if best.bytes.len() == before {884 if best.bytes.len() == before {
@@ -858,7 +891,7 @@ impl SilkEncoder {
858 while best.bytes.len() > max && mul < 64.0 {891 while best.bytes.len() > max && mul < 64.0 {
859 mul *= if mul < 4.0 { 1.15 } else { 2.0 };892 mul *= if mul < 4.0 { 1.15 } else { 2.0 };
860 lam_mul.set(mul);893 lam_mul.set(mul);
861- best = trial(best_step);894+ best = trial(best_step, conditional, self.prev_gain_index);
862 }895 }
863 lam_mul.set(1.0);896 lam_mul.set(1.0);
864 // The ceil step can overshoot a whole step's worth of bytes;897 // The ceil step can overshoot a whole step's worth of bytes;
@@ -868,7 +901,7 @@ impl SilkEncoder {
868 && best_step - 1 > floor_step901 && best_step - 1 > floor_step
869 && trials < MAX_BUDGET_TRIALS902 && trials < MAX_BUDGET_TRIALS
870 {903 {
871- let finer = trial(best_step - 1);904+ let finer = trial(best_step - 1, conditional, self.prev_gain_index);
872 trials += 1;905 trials += 1;
873 if finer.bytes.len() > max {906 if finer.bytes.len() > max {
874 break;907 break;
@@ -891,18 +924,34 @@ impl SilkEncoder {
891 )924 )
892 };925 };
893 }926 }
894- let new_lbrr = if self.lbrr_enabled && single_frame_packet && best.vad_flag {927+ let (lbrr_cond, lbrr_prev) = match self.lbrr_chain {
895- Some(Box::new(trial(chosen_step + self.lbrr_gain_increases)))928+ Some(prev) if conditional => (true, prev),
929+ _ => (false, self.prev_gain_index),
930+ };
931+ let new_lbrr = if self.lbrr_enabled && best.vad_flag {
932+ Some(Box::new(trial(
933+ chosen_step + self.lbrr_gain_increases,
934+ lbrr_cond,
935+ lbrr_prev,
936+ )))
896 } else {937 } else {
897 None938 None
898 };939 };
899 if let Some(enc) = shared {940 if let Some(enc) = shared {
900 let trial_ref = &best;941 let trial_ref = &best;
901- write_packet_header(enc, &[trial_ref], pending.as_deref());942+ write_packet_header(enc, &[trial_ref], &[pending.as_deref()]);
902 write_frame_data(enc, trial_ref, conditional, prev_signal_type);943 write_frame_data(enc, trial_ref, conditional, prev_signal_type);
903 }944 }
904- self.pending_lbrr = new_lbrr;945+ self.lbrr_chain = new_lbrr.as_ref().map(|t| t.prev_gain_index);
905- self.lbrr_in_packet = pending;946+ self.pending_lbrr[frame] = new_lbrr;
947+ if frame + 1 == frames {
948+ for slot in self.pending_lbrr.iter_mut().skip(frames) {
949+ *slot = None;
950+ }
951+ }
952+ self.lbrr_in_packet[frame] = pending;
953+ let x_energy: f32 = x.iter().map(|v| v * v).sum();
954+ self.last_snr_db = 10.0 * (x_energy / best.run.err.max(1e-9)).max(1e-9).log10();
906 self.prev_gain_index = best.prev_gain_index;955 self.prev_gain_index = best.prev_gain_index;
907 self.shape_d.copy_from_slice(&best.run.d[n..]);956 self.shape_d.copy_from_slice(&best.run.d[n..]);
908 self.shape_u.copy_from_slice(&best.run.u[n..]);957 self.shape_u.copy_from_slice(&best.run.u[n..]);
@@ -1006,6 +1055,24 @@ impl SilkStereoEncoder {
1006 self.max_bytes = max;1055 self.max_bytes = max;
1007 }1056 }
1008 1057
1058+ /// Enables LBRR on the mid and side channels (see SilkEncoder::set_lbrr).
1059+ pub fn set_lbrr(&mut self, enabled: bool, loss_perc: u8) {
1060+ self.mid.set_lbrr(enabled, loss_perc);
1061+ self.side.set_lbrr(enabled, loss_perc);
1062+ }
1063+
1064+ /// Drops the LBRR frames waiting for the next packet on both channels.
1065+ pub fn drop_lbrr(&mut self) {
1066+ self.mid.drop_lbrr();
1067+ self.side.drop_lbrr();
1068+ }
1069+
1070+ /// Expected packet loss in percent; raises LTP scaling on both channels.
1071+ pub fn set_packet_loss(&mut self, perc: u8) {
1072+ self.mid.set_packet_loss(perc);
1073+ self.side.set_packet_loss(perc);
1074+ }
1075+
1009 /// Hands each channel its share of the packet budget, split as the bits1076 /// Hands each channel its share of the packet budget, split as the bits
1010 /// are (`mid_bps : side_bps`), less a two-byte margin for the shared header.1077 /// are (`mid_bps : side_bps`), less a two-byte margin for the shared header.
1011 /// A side channel that is not coded takes no share.1078 /// A side channel that is not coded takes no share.
@@ -1150,26 +1217,27 @@ impl SilkStereoEncoder {
1150 };1217 };
1151 let mid_trial = self1218 let mid_trial = self
1152 .mid1219 .mid
1153- .encode_inner(&mid, frame_ms, None, false, 0, true)?;1220+ .encode_inner(&mid, frame_ms, None, 0, 1, 0)?;
1154 let side_trial = if mid_only {1221 let side_trial = if mid_only {
1155 None1222 None
1156 } else {1223 } else {
1157 self.side_budget_after_mid(mid_trial.bytes.len());1224 self.side_budget_after_mid(mid_trial.bytes.len());
1158 Some(1225 Some(
1159 self.side1226 self.side
1160- .encode_inner(&side, frame_ms, None, false, 0, true)?,1227+ .encode_inner(&side, frame_ms, None, 0, 1, 0)?,
1161 )1228 )
1162 };1229 };
1163- let side_vad = side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false);1230+ let mid_lbrr = self.mid.lbrr_in_packet[0].take();
1164- write_stereo_packet_header(enc, mid_trial.vad_flag, side_vad);1231+ let side_lbrr = self.side.lbrr_in_packet[0].take();
1165- write_stereo_zero_pred(enc);1232+ write_stereo_packet(
1166- if !side_vad {1233+ enc,
1167- enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);1234+ &mid_trial,
1168- }1235+ side_trial.as_ref(),
1169- write_frame_data(enc, &mid_trial, false, 0);1236+ mid_only,
1170- if let Some(trial) = &side_trial {1237+ self.prev_mid_only,
1171- write_frame_data(enc, trial, false, 0);1238+ mid_lbrr.as_deref(),
1172- }1239+ side_lbrr.as_deref(),
1240+ );
1173 self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;1241 self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
1174 match &side_trial {1242 match &side_trial {
1175 Some(trial) => self.side.replay_ms(&trial.bytes, frame_ms)?,1243 Some(trial) => self.side.replay_ms(&trial.bytes, frame_ms)?,
@@ -1231,32 +1299,29 @@ impl SilkStereoEncoder {
1231 };1299 };
1232 let mid_trial = self1300 let mid_trial = self
1233 .mid1301 .mid
1234- .encode_inner(&mid, frame_ms, None, false, 0, true)?;1302+ .encode_inner(&mid, frame_ms, None, 0, 1, 0)?;
1235 let side_trial = if mid_only {1303 let side_trial = if mid_only {
1236 None1304 None
1237 } else {1305 } else {
1238 self.side_budget_after_mid(mid_trial.bytes.len());1306 self.side_budget_after_mid(mid_trial.bytes.len());
1239 Some(1307 Some(
1240 self.side1308 self.side
1241- .encode_inner(&side, frame_ms, None, false, 0, true)?,1309+ .encode_inner(&side, frame_ms, None, 0, 1, 0)?,
1242 )1310 )
1243 };1311 };
1244 1312
1245 self.range.reset(1275);1313 self.range.reset(1275);
1246- write_stereo_packet_header(1314+ let mid_lbrr = self.mid.lbrr_in_packet[0].take();
1315+ let side_lbrr = self.side.lbrr_in_packet[0].take();
1316+ write_stereo_packet(
1247 &mut self.range,1317 &mut self.range,
1248- mid_trial.vad_flag,1318+ &mid_trial,
1249- side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false),1319+ side_trial.as_ref(),
1320+ mid_only,
1321+ self.prev_mid_only,
1322+ mid_lbrr.as_deref(),
1323+ side_lbrr.as_deref(),
1250 );1324 );
1251- write_stereo_zero_pred(&mut self.range);
1252- if !side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false) {
1253- self.range
1254- .enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
1255- }
1256- write_frame_data(&mut self.range, &mid_trial, false, 0);
1257- if let Some(trial) = &side_trial {
1258- write_frame_data(&mut self.range, trial, false, 0);
1259- }
1260 self.range.done();1325 self.range.done();
1261 debug_assert!(!self.range.error());1326 debug_assert!(!self.range.error());
1262 let len = self.range.range_bytes();1327 let len = self.range.range_bytes();
@@ -1317,11 +1382,39 @@ impl SilkStereoEncoder {
1317 }1382 }
1318 }1383 }
1319 1384
1320-fn write_stereo_packet_header(enc: &mut RangeEncoder, mid_vad: bool, side_vad: bool) {1385+fn write_stereo_packet(
1321- enc.enc_bit_logp(mid_vad, 1);1386+ enc: &mut RangeEncoder,
1322- enc.enc_bit_logp(false, 1);1387+ mid: &Trial,
1388+ side: Option<&Trial>,
1389+ mid_only: bool,
1390+ prev_mid_only: bool,
1391+ mid_lbrr: Option<&Trial>,
1392+ side_lbrr: Option<&Trial>,
1393+) {
1394+ let side_lbrr = side_lbrr.filter(|_| mid_lbrr.is_some());
1395+ let side_vad = side.is_some_and(|t| t.vad_flag);
1396+ enc.enc_bit_logp(mid.vad_flag, 1);
1397+ enc.enc_bit_logp(mid_lbrr.is_some(), 1);
1323 enc.enc_bit_logp(side_vad, 1);1398 enc.enc_bit_logp(side_vad, 1);
1324- enc.enc_bit_logp(false, 1);1399+ enc.enc_bit_logp(side_lbrr.is_some(), 1);
1400+ if let Some(m) = mid_lbrr {
1401+ write_stereo_zero_pred(enc);
1402+ if side_lbrr.is_none() {
1403+ enc.enc_icdf(usize::from(prev_mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
1404+ }
1405+ write_frame_data(enc, m, false, 0);
1406+ if let Some(s) = side_lbrr {
1407+ write_frame_data(enc, s, false, 0);
1408+ }
1409+ }
1410+ write_stereo_zero_pred(enc);
1411+ if !side_vad {
1412+ enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
1413+ }
1414+ write_frame_data(enc, mid, false, 0);
1415+ if let Some(s) = side {
1416+ write_frame_data(enc, s, false, 0);
1417+ }
1325 }1418 }
1326 1419
1327 fn write_stereo_zero_pred(enc: &mut RangeEncoder) {1420 fn write_stereo_zero_pred(enc: &mut RangeEncoder) {
@@ -1366,15 +1459,37 @@ struct Trial {
1366 seed_index: i32,1459 seed_index: i32,
1367 }1460 }
1368 1461
1369-fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial], lbrr: Option<&Trial>) {1462+fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial], lbrr: &[Option<&Trial>]) {
1370 for frame in frames {1463 for frame in frames {
1371 enc.enc_bit_logp(frame.vad_flag, 1);1464 enc.enc_bit_logp(frame.vad_flag, 1);
1372 }1465 }
1373- enc.enc_bit_logp(lbrr.is_some(), 1);1466+ let lbrr = &lbrr[..frames.len()];
1374- if let Some(t) = lbrr1467+ let any = lbrr.iter().any(Option::is_some);
1375- && frames.len() == 11468+ enc.enc_bit_logp(any, 1);
1376- {1469+ if !any {
1377- write_frame_data(enc, t, false, 0);1470+ return;
1471+ }
1472+ if frames.len() > 1 {
1473+ let mask = lbrr
1474+ .iter()
1475+ .enumerate()
1476+ .fold(0usize, |m, (i, t)| m | (usize::from(t.is_some()) << i));
1477+ let icdf: &[u8] = if frames.len() == 2 {
1478+ &LBRR_FLAGS_2_ICDF
1479+ } else {
1480+ &LBRR_FLAGS_3_ICDF
1481+ };
1482+ enc.enc_icdf(mask - 1, icdf, 8);
1483+ }
1484+ for (i, slot) in lbrr.iter().enumerate() {
1485+ let Some(t) = slot else { continue };
1486+ let conditional = i > 0 && lbrr[i - 1].is_some();
1487+ let prev_signal_type = if conditional {
1488+ lbrr[i - 1].map_or(0, |p| p.signal_type)
1489+ } else {
1490+ 0
1491+ };
1492+ write_frame_data(enc, t, conditional, prev_signal_type);
1378 }1493 }
1379 }1494 }
1380 1495
crates/ec-opus/src/stack_budget.rsmodified+10 -10
@@ -69,8 +69,8 @@
69 //! that holds one is a `Box`, which69 //! 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,08072+//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,088
73-//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4080 = 8,160` bytes --73+//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4088 = 8,176` bytes --
74 //! **0.39%** of a 2 MiB thread -- and the budget sits 2.01x above the74 //! **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 the75 //! 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 defect76 //! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect
@@ -114,7 +114,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
114 // -- lib.rs -----------------------------------------------------------114 // -- lib.rs -----------------------------------------------------------
115 (115 (
116 "Decoder",116 "Decoder",
117- Some(1576),117+ Some(1568),
118 true,118 true,
119 "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \119 "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \
120 because a 6304-byte SilkDecoder sat inline; that field is now a Box",120 because a 6304-byte SilkDecoder sat inline; that field is now a Box",
@@ -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(4080),125+ Some(4088),
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 \
@@ -138,7 +138,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
138 // -- celt.rs ----------------------------------------------------------138 // -- celt.rs ----------------------------------------------------------
139 (139 (
140 "CeltDecoder",140 "CeltDecoder",
141- Some(1448),141+ Some(1440),
142 true,142 true,
143 "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \143 "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \
144 value into Decoder::celt",144 value into Decoder::celt",
@@ -164,7 +164,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
164 // -- multistream.rs / multistream_enc.rs ------------------------------164 // -- multistream.rs / multistream_enc.rs ------------------------------
165 (165 (
166 "MultistreamDecoder",166 "MultistreamDecoder",
167- Some(96),167+ Some(120),
168 true,168 true,
169 "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \169 "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \
170 public by-value chain: with_rate -> try_with_rate -> Result<..>",170 public by-value chain: with_rate -> try_with_rate -> Result<..>",
@@ -218,10 +218,10 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
218 // -- silk.rs ----------------------------------------------------------218 // -- silk.rs ----------------------------------------------------------
219 (219 (
220 "SilkDecoder",220 "SilkDecoder",
221- Some(6496),221+ Some(6512),
222 true,222 true,
223 "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \223 "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \
224- root, so 6496 bytes is a caller's by-value cost TODAY even though \224+ root, so 6512 bytes is a caller's by-value cost TODAY even though \
225 Decoder::new moves it straight into a Box. At 77% of the budget it \225 Decoder::new moves it straight into a Box. At 77% of the budget it \
226 is the LARGEST budgeted row in the table, and the one that says how \226 is the LARGEST budgeted row in the table, and the one that says how \
227 little headroom the budget would have left if it had stayed inline",227 little headroom the budget would have left if it had stayed inline",
@@ -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(6880),238+ Some(6944),
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(20432),246+ Some(20576),
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 \