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 {
13341334 ext: Vec<f32>,
13351335 start: usize,
13361336 end: usize,
1337- transient: bool,
13381337 }
13391338
13401339 impl CeltDecoder {
@@ -1385,7 +1384,6 @@ impl CeltDecoder {
13851384 ext: vec![0.0; max_n + OVERLAP],
13861385 start: 0,
13871386 end: NB_BANDS,
1388- transient: false,
13891387 },
13901388 diag: CeltDecDiag {
13911389 silence: false,
@@ -1522,7 +1520,6 @@ impl CeltDecoder {
15221520 false
15231521 };
15241522 let short_blocks = if transient { m } else { 0 };
1525- self.plc.transient = transient;
15261523
15271524 let intra = if tell + 3 <= total_bits {
15281525 dec.dec_bit_logp(3)
@@ -2889,8 +2886,7 @@ impl CeltDecoder {
28892886 self.decode_mem
28902887 .copy_within(base + n..base + DECODE_BUFFER, base);
28912888 }
2892- let short_blocks = if self.plc.transient { m } else { 0 };
2893- self.inverse_mdcts(short_blocks, lm, n, cc);
2889+ self.inverse_mdcts(0, lm, n, cc);
28942890 }
28952891
28962892 fn plc_pitch_search(&self) -> usize {
crates/ec-opus/src/encoder.rsmodified+123 -6
@@ -87,6 +87,28 @@ pub enum Application {
8787 LowDelay,
8888 }
8989
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+
90112 /// One elementary Opus encoder: mono or stereo.
91113 #[derive(Clone, Debug)]
92114 pub struct Encoder {
@@ -157,8 +179,13 @@ pub struct Encoder {
157179 lbrr_coded: bool,
158180 fec_bandwidth: Option<Bandwidth>,
159181 last_silk: Option<u8>,
182+ use_dtx: bool,
183+ nb_no_activity_ms_q1: i32,
184+ peak_signal_energy: f32,
160185 }
161186
187+const STEREO_TAG: u8 = 100;
188+
162189 fn toc_bandwidth(toc: u8) -> Bandwidth {
163190 const BW: [Bandwidth; 5] = [
164191 Bandwidth::Narrow,
@@ -245,6 +272,9 @@ impl Encoder {
245272 lbrr_coded: false,
246273 fec_bandwidth: None,
247274 last_silk: None,
275+ use_dtx: false,
276+ nb_no_activity_ms_q1: 0,
277+ peak_signal_energy: 0.0,
248278 };
249279 // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how
250280 // the gate rows at `set_libopus_input_alignment` were produced.
@@ -397,6 +427,46 @@ impl Encoder {
397427 self.packet_loss_perc = perc.min(100);
398428 }
399429
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+
400470 /// Current target bitrate.
401471 pub fn bitrate(&self) -> u32 {
402472 self.bitrate
@@ -453,6 +523,8 @@ impl Encoder {
453523 self.lbrr_coded = false;
454524 self.fec_bandwidth = None;
455525 self.last_silk = None;
526+ self.nb_no_activity_ms_q1 = 0;
527+ self.peak_signal_energy = 0.0;
456528 }
457529
458530 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])
@@ -721,7 +793,12 @@ impl Encoder {
721793 if let Some(fs_khz) = self.silk_choice(frame_48k) {
722794 let budget = self.packet_budget(frame_48k, cap);
723795 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);
725802 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
726803 if frame_48k > 960 {
727804 return self.encode_stereo_silk_multiframe(fs_khz, frame_48k);
@@ -737,6 +814,11 @@ impl Encoder {
737814 .silk_stereo_wb
738815 .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))),
739816 };
817+ if !same {
818+ enc.drop_lbrr();
819+ }
820+ enc.set_lbrr(lbrr, loss);
821+ enc.set_packet_loss(loss);
740822 enc.set_bitrate(self.bitrate);
741823 enc.set_max_bytes(budget);
742824 let n =
@@ -765,6 +847,7 @@ impl Encoder {
765847 enc.drop_lbrr();
766848 }
767849 enc.set_lbrr(lbrr, loss);
850+ enc.set_packet_loss(loss);
768851 // Keep SILK's own reservoir-based rate control tracking the
769852 // Encoder's current target on every frame — cheap (an Option<u32>
770853 // store) and catches set_bitrate calls made between frames.
@@ -928,8 +1011,7 @@ impl Encoder {
9281011
9291012 fn fec_for(&self, frame_48k: usize) -> (bool, Option<Bandwidth>) {
9301013 if !self.inband_fec
931- || self.channels != 1
932- || !matches!(frame_48k, 480 | 960)
1014+ || !(matches!(frame_48k, 480 | 960) || (self.channels == 1 && frame_48k <= 2880))
9331015 || self.mode == Some(Mode::Celt)
9341016 {
9351017 return (false, None);
@@ -1140,6 +1222,7 @@ impl Encoder {
11401222 Err(e) => Err(e),
11411223 Ok((toc, payload)) => {
11421224 let n = payload.len();
1225+ let count = payload.first().copied().unwrap_or(0);
11431226 if out.len() < 1 + n {
11441227 Err(Error::corrupt(format!(
11451228 "opus encode: packet needs {} bytes, buffer holds {}",
@@ -1149,7 +1232,18 @@ impl Encoder {
11491232 } else {
11501233 out[0] = toc;
11511234 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+ }
11531247 }
11541248 }
11551249 };
@@ -1177,6 +1271,7 @@ impl Encoder {
11771271 let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(3)) {
11781272 Err(e) => Err(e),
11791273 Ok((toc, payload)) => {
1274+ let count = payload.first().copied().unwrap_or(0);
11801275 let (head, last) = if toc & 3 == 3 {
11811276 let count = usize::from(payload[0] & 0x3F);
11821277 let mut pos = 1;
@@ -1210,7 +1305,18 @@ impl Encoder {
12101305 out[1..1 + head].copy_from_slice(&payload[..head]);
12111306 out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]);
12121307 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+ }
12141320 }
12151321 }
12161322 }
@@ -1270,10 +1376,20 @@ impl Encoder {
12701376 if self.lbrr_coded { Bandwidth::Full } else { bandwidth },
12711377 );
12721378 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);
12741385 let silk = self
12751386 .silk_stereo_wb
12761387 .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);
12771393 silk.set_bitrate(silk_rate);
12781394 silk.set_max_bytes(silk_max);
12791395 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
@@ -1290,6 +1406,7 @@ impl Encoder {
12901406 silk.drop_lbrr();
12911407 }
12921408 silk.set_lbrr(lbrr, loss);
1409+ silk.set_packet_loss(loss);
12931410 silk.set_bitrate(silk_rate);
12941411 silk.set_max_bytes(silk_max);
12951412 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 {
103103 channels: usize,
104104 downsample: usize,
105105 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`
107107 /// costs a caller taking one BY VALUE from `Decoder::new`. It is the
108108 /// decoder's largest field and its only large one; `celt` is 1448.
109109 /// `Stack`: crate::stack_budget.
crates/ec-opus/src/multistream.rsmodified+104 -28
@@ -20,6 +20,7 @@
2020
2121 use ec_core::{Error, Result};
2222
23+use crate::packet::Packet;
2324 use crate::Decoder;
2425
2526 /// A decoder for a multichannel Opus stream, mono through 255 channels.
@@ -32,6 +33,8 @@ pub struct MultistreamDecoder {
3233 sample_rate: u32,
3334 /// Scratch for one stream's output.
3435 buf: Vec<f32>,
36+ /// Scratch for one stream's first frame as a plain packet.
37+ fec: Vec<u8>,
3538 }
3639
3740 impl MultistreamDecoder {
@@ -94,6 +97,7 @@ impl MultistreamDecoder {
9497 channels: mapping.len(),
9598 sample_rate,
9699 buf: vec![0.0; 2 * 5760],
100+ fec: Vec::with_capacity(1276),
97101 })
98102 }
99103
@@ -166,45 +170,105 @@ impl MultistreamDecoder {
166170 rest = &rest[consumed.min(rest.len())..];
167171 if s == 0 {
168172 frame_size = n;
169- if out.len() < n * self.channels {
170- return Err(Error::corrupt(format!(
171- "opus multistream: output buffer holds {} samples, packet needs {}",
172- out.len(),
173- n * self.channels
174- )));
175- }
173+ self.check_out(frame_size, out)?;
176174 } else if n != frame_size {
177175 return Err(Error::corrupt(format!(
178176 "opus multistream: stream {s} decoded {n} samples, stream 0 gave {frame_size}"
179177 )));
180178 }
181- // Route this stream's channels to the outputs that name them.
182- for (c, &m) in self.mapping.iter().enumerate() {
183- if m == 255 {
184- continue;
179+ self.route(s, frame_size, out);
180+ }
181+ self.silence(frame_size, out);
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)?;
185221 }
186- let m = m as usize;
187- let src = if s < self.coupled {
188- if m == 2 * s {
189- Some(0)
190- } else if m == 2 * s + 1 {
191- Some(1)
192- } else {
193- None
194- }
195- } else if m == s + self.coupled {
222+ }
223+ self.route(s, frame_size, out);
224+ }
225+ self.silence(frame_size, out);
226+ Ok(frame_size)
227+ }
228+
229+ fn check_out(&self, frame_size: usize, out: &[f32]) -> Result<()> {
230+ if out.len() < frame_size * self.channels {
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 {
196251 Some(0)
252+ } else if m == 2 * s + 1 {
253+ Some(1)
197254 } else {
198255 None
199- };
200- if let Some(off) = src {
201- for i in 0..frame_size {
202- out[self.channels * i + c] = self.buf[stream_channels * i + off];
203- }
256+ }
257+ } else if m == s + self.coupled {
258+ Some(0)
259+ } else {
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];
204265 }
205266 }
206267 }
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]) {
208272 for (c, &m) in self.mapping.iter().enumerate() {
209273 if m == 255 {
210274 for i in 0..frame_size {
@@ -212,10 +276,22 @@ impl MultistreamDecoder {
212276 }
213277 }
214278 }
215- Ok(frame_size)
216279 }
217280 }
218281
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+
219295 #[cfg(test)]
220296 mod tests {
221297 use super::*;
crates/ec-opus/src/multistream_enc.rsmodified+14 -0
@@ -136,6 +136,20 @@ impl MultistreamEncoder {
136136 }
137137 }
138138
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+
139153 /// Drops all inter-frame state in every stream.
140154 pub fn reset(&mut self) {
141155 for enc in self.streams.iter_mut() {
crates/ec-opus/src/silk.rsmodified+141 -1
@@ -14,7 +14,8 @@
1414 //!
1515 //! LBRR (in-band FEC) frames are decoded through [`SilkFrameMode::Lbrr`], and
1616 //! 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.
1819
1920 // SILK is transliterated fixed-point arithmetic: the loops below index parallel
2021 // arrays by position because the reference's index arithmetic is the
@@ -51,7 +52,12 @@ const N_RATE_LEVELS: usize = 10;
5152 pub(crate) const PE_MIN_LAG_MS: i32 = 2;
5253 pub(crate) const PE_MAX_LAG_MS: i32 = 18;
5354 const STEREO_INTERP_LEN_MS: usize = 8;
55+const TYPE_NO_VOICE_ACTIVITY: i32 = 0;
5456 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;
5561 const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;
5662 const BWE_COEF_Q16: i32 = 64881;
5763 const BWE_AFTER_LOSS_Q16: i32 = 63570;
@@ -124,6 +130,11 @@ pub(crate) fn smulbb(a: i32, b: i32) -> i32 {
124130 (a as i16 as i32).wrapping_mul(b as i16 as i32)
125131 }
126132
133+#[inline]
134+fn smultt(a: i32, b: i32) -> i32 {
135+ (a >> 16) * (b >> 16)
136+}
137+
127138 #[inline]
128139 fn smlabb(a: i32, b: i32, c: i32) -> i32 {
129140 a.wrapping_add(smulbb(b, c))
@@ -358,6 +369,30 @@ struct PlcState {
358369 subfr_length: usize,
359370 }
360371
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+
361396 /// One SILK channel's inter-frame state.
362397 #[derive(Clone, Debug)]
363398 struct ChannelState {
@@ -389,6 +424,7 @@ struct ChannelState {
389424 lbrr_flags: [bool; 3],
390425 resampler: Resampler,
391426 plc: PlcState,
427+ cng: Box<CngState>,
392428 loss_cnt: i32,
393429 }
394430
@@ -421,6 +457,7 @@ impl ChannelState {
421457 lbrr_flags: [false; 3],
422458 resampler: Resampler::default(),
423459 plc: PlcState::default(),
460+ cng: Box::default(),
424461 loss_cnt: 0,
425462 }
426463 }
@@ -1686,6 +1723,108 @@ impl ChannelState {
16861723 }
16871724 }
16881725
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+
16891828 /// `silk_LPC_analysis_filter`: the whitening filter used to rebuild the LTP
16901829 /// state from previously decoded output.
16911830 fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b_q12: &[i16], len: usize, d: usize) {
@@ -1869,6 +2008,7 @@ fn decode_frame(
18692008 let mv_len = ch.ltp_mem_length - fl;
18702009 ch.out_buf.copy_within(fl..fl + mv_len, 0);
18712010 ch.out_buf[mv_len..mv_len + fl].copy_from_slice(&out[..fl]);
2011+ ch.cng(&ctrl, &mut out[..fl]);
18722012 ch.plc_glue_frames(&mut out[..fl]);
18732013 ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1];
18742014 fl
crates/ec-opus/src/silk_enc_write.rsmodified+188 -73
@@ -97,10 +97,15 @@ pub struct SilkEncoder {
9797 last_diag: SilkFrameDiag,
9898 lbrr_enabled: bool,
9999 lbrr_gain_increases: i32,
100- pending_lbrr: Option<Box<Trial>>,
101- lbrr_in_packet: Option<Box<Trial>>,
100+ pending_lbrr: [Option<Box<Trial>>; MAX_PACKET_FRAMES],
101+ lbrr_in_packet: [Option<Box<Trial>>; MAX_PACKET_FRAMES],
102+ lbrr_chain: Option<i32>,
103+ loss_perc: u8,
104+ last_snr_db: f32,
102105 }
103106
107+const MAX_PACKET_FRAMES: usize = 3;
108+
104109 /// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth
105110 /// expansions of the LPC, harmonic comb depth, voiced spectral tilt, and the
106111 /// linear ratio of one gain-quantiser step (2^(1.365 dB / 6.02)).
@@ -182,8 +187,11 @@ impl SilkEncoder {
182187 last_diag: SilkFrameDiag::default(),
183188 lbrr_enabled: false,
184189 lbrr_gain_increases: 7,
185- pending_lbrr: None,
186- lbrr_in_packet: None,
190+ pending_lbrr: Default::default(),
191+ lbrr_in_packet: Default::default(),
192+ lbrr_chain: None,
193+ loss_perc: 0,
194+ last_snr_db: 0.0,
187195 }
188196 }
189197
@@ -225,18 +233,28 @@ impl SilkEncoder {
225233 7
226234 };
227235 } else {
228- self.pending_lbrr = None;
236+ self.pending_lbrr = Default::default();
229237 }
230238 self.lbrr_enabled = enabled;
231239 }
232240
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).
234242 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;
236249 }
237250
238251 fn reset_state(&mut self) {
252+ let (lbrr, gain_increases, loss_perc) =
253+ (self.lbrr_enabled, self.lbrr_gain_increases, self.loss_perc);
239254 *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;
240258 }
241259
242260 /// Algorithmic delay in 48 kHz samples: the analysis resampler only
@@ -278,17 +296,17 @@ impl SilkEncoder {
278296 let mut frames = Vec::with_capacity(frames_per_packet);
279297 let sub_ms = if frame_ms == 10 { 10 } else { 20 };
280298 let mut prev_signal_type = 0;
299+ self.lbrr_in_packet = Default::default();
281300 for i in 0..frames_per_packet {
282301 let from = i * sub_ms * 48;
283302 let to = from + sub_ms * 48;
284- let conditional = i > 0;
285303 let trial = self.encode_inner(
286304 &pcm48[from..to],
287305 sub_ms,
288306 None,
289- conditional,
307+ i,
308+ frames_per_packet,
290309 prev_signal_type,
291- frames_per_packet == 1,
292310 )?;
293311 prev_signal_type = trial.signal_type;
294312 frames.push(trial);
@@ -298,8 +316,9 @@ impl SilkEncoder {
298316 }
299317 self.range.reset(1275);
300318 let refs: Vec<&Trial> = frames.iter().collect();
301- let lbrr = self.lbrr_in_packet.take();
302- write_packet_header(&mut self.range, &refs, lbrr.as_deref());
319+ let lbrr = std::mem::take(&mut self.lbrr_in_packet);
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]);
303322 prev_signal_type = 0;
304323 for (i, frame) in frames.iter().enumerate() {
305324 write_frame_data(&mut self.range, frame, i > 0, prev_signal_type);
@@ -347,7 +366,7 @@ impl SilkEncoder {
347366 enc: &mut RangeEncoder,
348367 frame_ms: usize,
349368 ) -> 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)?;
351370 self.voiced_frames += usize::from(trial.voiced);
352371 Ok(())
353372 }
@@ -396,9 +415,9 @@ impl SilkEncoder {
396415 pcm48: &[f32],
397416 frame_ms: usize,
398417 shared: Option<&mut RangeEncoder>,
399- conditional: bool,
418+ frame: usize,
419+ frames: usize,
400420 prev_signal_type: i32,
401- single_frame_packet: bool,
402421 ) -> Result<Trial> {
403422 assert!(
404423 matches!(frame_ms, 10 | 20),
@@ -409,12 +428,9 @@ impl SilkEncoder {
409428 48 * frame_ms,
410429 "SilkEncoder input is 48 kHz mono"
411430 );
412- let pending = if single_frame_packet {
413- self.pending_lbrr.take()
414- } else {
415- self.pending_lbrr = None;
416- None
417- };
431+ let conditional = frame > 0;
432+ let single_frame_packet = frames == 1;
433+ let pending = self.pending_lbrr[frame].take();
418434 let fs = self.fs_khz;
419435 let order = if fs == 16 { MAX_LPC_ORDER } else { 10 };
420436 let nb_subfr = frame_ms / 5;
@@ -516,6 +532,7 @@ impl SilkEncoder {
516532 // of the best vector is the LTP gain that picks the scale index.
517533 let mut targets = [0i32; MAX_NB_SUBFR];
518534 let mut ltp_gain = 0f32;
535+ let mut ltp_res_energy = 0f32;
519536 {
520537 let mut r_ol: Vec<f32> = (-(n as isize)..0).map(whiten).collect();
521538 r_ol.extend_from_slice(&res);
@@ -534,6 +551,7 @@ impl SilkEncoder {
534551 ((0..sub).map(|i| res[k * sub + i].powi(2)).sum(), 0.0)
535552 };
536553 ltp_gain = ltp_gain.max(gsum);
554+ ltp_res_energy += e;
537555 let rms = (e / sub as f32).sqrt();
538556 targets[k] = ((rms * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32;
539557 }
@@ -548,7 +566,7 @@ impl SilkEncoder {
548566 };
549567 // Over-unity LTP gain: scale the previous frame's history down so
550568 // 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 {
552570 0
553571 } else if ltp_gain > 1.25 {
554572 2
@@ -557,6 +575,20 @@ impl SilkEncoder {
557575 } else {
558576 0
559577 };
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+ }
560592 let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0;
561593 // Inactive or low-energy frames (and sparse voiced excitation) take the
562594 // small quantisation offset; dense unvoiced excitation the large one.
@@ -717,15 +749,15 @@ impl SilkEncoder {
717749 // One full trial at a common gain offset (in quantiser steps): returns
718750 // the coded packet body so the rate loop can read its exact size.
719751 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 {
721753 let scale = GAIN_STEP.powi(step);
722754 let mut t = targets;
723755 for v in t.iter_mut() {
724756 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;
725757 }
726- let mut prev_gain_index = self.prev_gain_index;
758+ let mut prev_gain_index = start_prev;
727759 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);
729761 let (per_index, run) = candidates
730762 .iter()
731763 .map(|&per| (per, run(per, &gains_q16)))
@@ -756,8 +788,9 @@ impl SilkEncoder {
756788 };
757789 let enc = &mut self.range;
758790 enc.reset(1275);
759- write_packet_header(enc, &[&trial], pending.as_deref());
760- write_frame_data(enc, &trial, conditional, prev_signal_type);
791+ let measured_lbrr = [if single_frame_packet { pending.as_deref() } else { None }];
792+ write_packet_header(enc, &[&trial], &measured_lbrr);
793+ write_frame_data(enc, &trial, cond, prev_signal_type);
761794 enc.done();
762795 debug_assert!(!enc.error());
763796 let len = enc.range_bytes();
@@ -769,7 +802,7 @@ impl SilkEncoder {
769802 // Rate control: a common gain offset moves every subframe's pulse
770803 // magnitudes together; the reservoir carries each packet's miss.
771804 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);
773806 if let Some(bps) = self.target_bps {
774807 let mut frame_bits = bps as f32 * frame_ms as f32 / 1000.0;
775808 // A packet cap is a promise to fill it: the CBR packet is padded to
@@ -809,7 +842,7 @@ impl SilkEncoder {
809842 if step == s0 {
810843 break;
811844 }
812- let t = trial(step);
845+ let t = trial(step, conditional, self.prev_gain_index);
813846 let b1 = bits_of(&t);
814847 if (b1 - target).abs() < (b0 - target).abs() {
815848 if b1 != b0 {
@@ -845,7 +878,7 @@ impl SilkEncoder {
845878 }
846879 floor_step = best_step;
847880 let before = best.bytes.len();
848- best = trial(step);
881+ best = trial(step, conditional, self.prev_gain_index);
849882 best_step = step;
850883 trials += 1;
851884 if best.bytes.len() == before {
@@ -858,7 +891,7 @@ impl SilkEncoder {
858891 while best.bytes.len() > max && mul < 64.0 {
859892 mul *= if mul < 4.0 { 1.15 } else { 2.0 };
860893 lam_mul.set(mul);
861- best = trial(best_step);
894+ best = trial(best_step, conditional, self.prev_gain_index);
862895 }
863896 lam_mul.set(1.0);
864897 // The ceil step can overshoot a whole step's worth of bytes;
@@ -868,7 +901,7 @@ impl SilkEncoder {
868901 && best_step - 1 > floor_step
869902 && trials < MAX_BUDGET_TRIALS
870903 {
871- let finer = trial(best_step - 1);
904+ let finer = trial(best_step - 1, conditional, self.prev_gain_index);
872905 trials += 1;
873906 if finer.bytes.len() > max {
874907 break;
@@ -891,18 +924,34 @@ impl SilkEncoder {
891924 )
892925 };
893926 }
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)))
927+ let (lbrr_cond, lbrr_prev) = match self.lbrr_chain {
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+ )))
896937 } else {
897938 None
898939 };
899940 if let Some(enc) = shared {
900941 let trial_ref = &best;
901- write_packet_header(enc, &[trial_ref], pending.as_deref());
942+ write_packet_header(enc, &[trial_ref], &[pending.as_deref()]);
902943 write_frame_data(enc, trial_ref, conditional, prev_signal_type);
903944 }
904- self.pending_lbrr = new_lbrr;
905- self.lbrr_in_packet = pending;
945+ self.lbrr_chain = new_lbrr.as_ref().map(|t| t.prev_gain_index);
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();
906955 self.prev_gain_index = best.prev_gain_index;
907956 self.shape_d.copy_from_slice(&best.run.d[n..]);
908957 self.shape_u.copy_from_slice(&best.run.u[n..]);
@@ -1006,6 +1055,24 @@ impl SilkStereoEncoder {
10061055 self.max_bytes = max;
10071056 }
10081057
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+
10091076 /// Hands each channel its share of the packet budget, split as the bits
10101077 /// are (`mid_bps : side_bps`), less a two-byte margin for the shared header.
10111078 /// A side channel that is not coded takes no share.
@@ -1150,26 +1217,27 @@ impl SilkStereoEncoder {
11501217 };
11511218 let mid_trial = self
11521219 .mid
1153- .encode_inner(&mid, frame_ms, None, false, 0, true)?;
1220+ .encode_inner(&mid, frame_ms, None, 0, 1, 0)?;
11541221 let side_trial = if mid_only {
11551222 None
11561223 } else {
11571224 self.side_budget_after_mid(mid_trial.bytes.len());
11581225 Some(
11591226 self.side
1160- .encode_inner(&side, frame_ms, None, false, 0, true)?,
1227+ .encode_inner(&side, frame_ms, None, 0, 1, 0)?,
11611228 )
11621229 };
1163- let side_vad = side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false);
1164- write_stereo_packet_header(enc, mid_trial.vad_flag, side_vad);
1165- write_stereo_zero_pred(enc);
1166- if !side_vad {
1167- enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
1168- }
1169- write_frame_data(enc, &mid_trial, false, 0);
1170- if let Some(trial) = &side_trial {
1171- write_frame_data(enc, trial, false, 0);
1172- }
1230+ let mid_lbrr = self.mid.lbrr_in_packet[0].take();
1231+ let side_lbrr = self.side.lbrr_in_packet[0].take();
1232+ write_stereo_packet(
1233+ enc,
1234+ &mid_trial,
1235+ side_trial.as_ref(),
1236+ mid_only,
1237+ self.prev_mid_only,
1238+ mid_lbrr.as_deref(),
1239+ side_lbrr.as_deref(),
1240+ );
11731241 self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
11741242 match &side_trial {
11751243 Some(trial) => self.side.replay_ms(&trial.bytes, frame_ms)?,
@@ -1231,32 +1299,29 @@ impl SilkStereoEncoder {
12311299 };
12321300 let mid_trial = self
12331301 .mid
1234- .encode_inner(&mid, frame_ms, None, false, 0, true)?;
1302+ .encode_inner(&mid, frame_ms, None, 0, 1, 0)?;
12351303 let side_trial = if mid_only {
12361304 None
12371305 } else {
12381306 self.side_budget_after_mid(mid_trial.bytes.len());
12391307 Some(
12401308 self.side
1241- .encode_inner(&side, frame_ms, None, false, 0, true)?,
1309+ .encode_inner(&side, frame_ms, None, 0, 1, 0)?,
12421310 )
12431311 };
12441312
12451313 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(
12471317 &mut self.range,
1248- mid_trial.vad_flag,
1249- side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false),
1318+ &mid_trial,
1319+ side_trial.as_ref(),
1320+ mid_only,
1321+ self.prev_mid_only,
1322+ mid_lbrr.as_deref(),
1323+ side_lbrr.as_deref(),
12501324 );
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- }
12601325 self.range.done();
12611326 debug_assert!(!self.range.error());
12621327 let len = self.range.range_bytes();
@@ -1317,11 +1382,39 @@ impl SilkStereoEncoder {
13171382 }
13181383 }
13191384
1320-fn write_stereo_packet_header(enc: &mut RangeEncoder, mid_vad: bool, side_vad: bool) {
1321- enc.enc_bit_logp(mid_vad, 1);
1322- enc.enc_bit_logp(false, 1);
1385+fn write_stereo_packet(
1386+ enc: &mut RangeEncoder,
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);
13231398 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+ }
13251418 }
13261419
13271420 fn write_stereo_zero_pred(enc: &mut RangeEncoder) {
@@ -1366,15 +1459,37 @@ struct Trial {
13661459 seed_index: i32,
13671460 }
13681461
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>]) {
13701463 for frame in frames {
13711464 enc.enc_bit_logp(frame.vad_flag, 1);
13721465 }
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);
1466+ let lbrr = &lbrr[..frames.len()];
1467+ let any = lbrr.iter().any(Option::is_some);
1468+ enc.enc_bit_logp(any, 1);
1469+ if !any {
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);
13781493 }
13791494 }
13801495
crates/ec-opus/src/stack_budget.rsmodified+10 -10
@@ -69,8 +69,8 @@
6969 //! that holds one is a `Box`, which
7070 //! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source.
7171 //!
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 4080 = 8,160` bytes --
72+//! **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 4088 = 8,176` bytes --
7474 //! **0.39%** of a 2 MiB thread -- and the budget sits 2.01x above the
7575 //! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the
7676 //! 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)] = &[
114114 // -- lib.rs -----------------------------------------------------------
115115 (
116116 "Decoder",
117- Some(1576),
117+ Some(1568),
118118 true,
119119 "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \
120120 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)] = &[
122122 // -- encoder.rs -------------------------------------------------------
123123 (
124124 "Encoder",
125- Some(4080),
125+ Some(4088),
126126 true,
127127 "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \
128128 inline Option<SilkEncoder>/Option<SilkStereoEncoder> slots (79176 \
@@ -138,7 +138,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
138138 // -- celt.rs ----------------------------------------------------------
139139 (
140140 "CeltDecoder",
141- Some(1448),
141+ Some(1440),
142142 true,
143143 "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \
144144 value into Decoder::celt",
@@ -164,7 +164,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
164164 // -- multistream.rs / multistream_enc.rs ------------------------------
165165 (
166166 "MultistreamDecoder",
167- Some(96),
167+ Some(120),
168168 true,
169169 "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \
170170 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)] = &[
218218 // -- silk.rs ----------------------------------------------------------
219219 (
220220 "SilkDecoder",
221- Some(6496),
221+ Some(6512),
222222 true,
223223 "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 \
225225 Decoder::new moves it straight into a Box. At 77% of the budget it \
226226 is the LARGEST budgeted row in the table, and the one that says how \
227227 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)] = &[
235235 // -- silk_enc_write.rs ------------------------------------------------
236236 (
237237 "SilkEncoder",
238- Some(6880),
238+ Some(6944),
239239 false,
240240 "silk_enc_write::SilkEncoder::new -> Self. `pub`, `pub use`d at the \
241241 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)] = &[
243243 ),
244244 (
245245 "SilkStereoEncoder",
246- Some(20432),
246+ Some(20576),
247247 false,
248248 "silk_enc_write::SilkStereoEncoder::new -> Self. The largest single \
249249 type in the crate at 2.42x the budget, and the reason three of the \