forge
Explore
Log in

Don't you dare go Hollow

Encode multiframe silk

Browse files at this commit

d8fab2069fb0c288d69ab2b2e48b7c5f9e98370fAhmet Kaan GümüşParent: d5b5f3d
  • feat
    • encode multiframe silk
Show full message
feat(ec-opus): encode multiframe silk
crates/ec-opus/src/silk_enc_write.rsmodified+221 -114
@@ -12,8 +12,7 @@
1212 //! output error is fed back through short-term (bandwidth-expanded LPC),
1313 //! harmonic and tilt shaping filters so the noise hides under the signal's
1414 //! own spectrum, and a gain-offset rate loop sizes each packet against
15-//! [`SilkEncoder::set_bitrate`]. 40/60 ms packets and stereo are not
16-//! written yet.
15+//! [`SilkEncoder::set_bitrate`]. Stereo is not written yet.
1716
1817 // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic.
1918 #![allow(clippy::needless_range_loop)]
@@ -27,7 +26,7 @@ use crate::silk::{
2726 nlsf2a, silk_rand,
2827 };
2928 use crate::silk_enc::{
30- Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf,
29+ NlsfQuant, Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf,
3130 };
3231
3332 const SHELL_LEN: usize = 16;
@@ -140,27 +139,66 @@ impl SilkEncoder {
140139 self.encode_frame_ms(pcm48, out, 20)
141140 }
142141
143- /// Encodes 10 or 20 ms of mono 48 kHz samples as one code-0 packet in
144- /// `out`, returning its length.
142+ /// Encodes 10, 20, 40 or 60 ms of mono 48 kHz samples as one code-0
143+ /// packet in `out`, returning its length.
145144 pub fn encode_frame_ms(
146145 &mut self,
147146 pcm48: &[f32],
148147 out: &mut [u8],
149148 frame_ms: usize,
150149 ) -> Result<usize> {
151- let Trial { bytes, range, .. } = self.encode_inner(pcm48, frame_ms, None)?;
152- let len = bytes.len();
153- self.final_range = range;
154- let duration = match frame_ms {
155- 10 => 0u8,
156- 20 => 1,
150+ let frames_per_packet = match frame_ms {
151+ 10 | 20 => 1usize,
152+ 40 => 2,
153+ 60 => 3,
157154 _ => {
158155 return Err(ec_core::Error::unsupported(
159156 format!("silk encode frame of {frame_ms} ms"),
160- "SILK encoder writes 10 or 20 ms packets",
157+ "SILK encoder writes 10, 20, 40 or 60 ms packets",
161158 ));
162159 }
163160 };
161+ assert_eq!(
162+ pcm48.len(),
163+ 48 * frame_ms,
164+ "SilkEncoder input is 48 kHz mono"
165+ );
166+ let mut frames = Vec::with_capacity(frames_per_packet);
167+ let sub_ms = if frame_ms == 10 { 10 } else { 20 };
168+ let mut prev_signal_type = 0;
169+ for i in 0..frames_per_packet {
170+ let from = i * sub_ms * 48;
171+ let to = from + sub_ms * 48;
172+ let conditional = i > 0;
173+ let trial = self.encode_inner(
174+ &pcm48[from..to],
175+ sub_ms,
176+ None,
177+ conditional,
178+ prev_signal_type,
179+ )?;
180+ prev_signal_type = trial.signal_type;
181+ frames.push(trial);
182+ }
183+ self.range.reset(1275);
184+ let refs: Vec<&Trial> = frames.iter().collect();
185+ write_packet_header(&mut self.range, &refs);
186+ prev_signal_type = 0;
187+ for (i, frame) in frames.iter().enumerate() {
188+ write_frame_data(&mut self.range, frame, i > 0, prev_signal_type);
189+ prev_signal_type = frame.signal_type;
190+ }
191+ self.range.done();
192+ debug_assert!(!self.range.error());
193+ let len = self.range.range_bytes();
194+ self.final_range = self.range.range();
195+ let duration = match frame_ms {
196+ 10 => 0u8,
197+ 20 => 1,
198+ 40 => 2,
199+ 60 => 3,
200+ _ => unreachable!(),
201+ };
164202 let base = match self.fs_khz {
165203 8 => 0u8,
166204 12 => 4,
@@ -175,7 +213,7 @@ impl SilkEncoder {
175213 )));
176214 }
177215 out[0] = toc;
178- out[1..1 + len].copy_from_slice(&bytes);
216+ out[1..1 + len].copy_from_slice(&self.range.data()[..len]);
179217 self.replay_ms(&out[1..1 + len], frame_ms)?;
180218 debug_assert_eq!(self.mirror_range, self.final_range);
181219 Ok(1 + len)
@@ -187,7 +225,8 @@ impl SilkEncoder {
187225 /// must [`SilkEncoder::replay`] the finished payload so this encoder's
188226 /// decoder mirror advances.
189227 pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> {
190- self.encode_inner(pcm48, 20, Some(enc)).map(|_| ())
228+ self.encode_inner(pcm48, 20, Some(enc), false, 0)
229+ .map(|_| ())
191230 }
192231
193232 /// Decodes `payload` (TOC stripped) through the mirror decoder so the next
@@ -201,14 +240,27 @@ impl SilkEncoder {
201240 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
202241 let fs = self.fs_khz;
203242 let mut dec = RangeDecoder::new(payload);
204- self.mirror.decode(
205- &mut dec,
206- &mut self.mirror_out,
207- frame_ms,
208- fs as u32 * 1000,
209- 1,
210- true,
211- )?;
243+ let total = frame_ms * fs;
244+ if self.mirror_out.len() < total {
245+ self.mirror_out.resize(total, 0);
246+ }
247+ let mut done = 0usize;
248+ let mut first = true;
249+ while done < total {
250+ let n = self.mirror.decode(
251+ &mut dec,
252+ &mut self.mirror_out[done..],
253+ frame_ms,
254+ fs as u32 * 1000,
255+ 1,
256+ first,
257+ )?;
258+ if n == 0 {
259+ break;
260+ }
261+ done += n;
262+ first = false;
263+ }
212264 self.mirror_range = dec.range();
213265 Ok(())
214266 }
@@ -222,6 +274,8 @@ impl SilkEncoder {
222274 pcm48: &[f32],
223275 frame_ms: usize,
224276 shared: Option<&mut RangeEncoder>,
277+ conditional: bool,
278+ prev_signal_type: i32,
225279 ) -> Result<Trial> {
226280 assert!(
227281 matches!(frame_ms, 10 | 20),
@@ -516,85 +570,7 @@ impl SilkEncoder {
516570 }
517571 };
518572
519- // Bitstream writer, in decode()'s order; shared by the sizing trials
520- // and the hybrid path's shared coder.
521- let write = |enc: &mut RangeEncoder, gain_idx: &[i8], per_index: usize, run: &Run| {
522- enc.enc_bit_logp(vad_flag, 1); // VAD flag
523- enc.enc_bit_logp(false, 1); // LBRR flag
524- // Frame type.
525- if vad_flag {
526- enc.enc_icdf(
527- ((signal_type << 1) | quant_offset_type as i32) as usize - 2,
528- &TYPE_OFFSET_VAD_ICDF,
529- 8,
530- );
531- } else {
532- enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8);
533- }
534- // Gains: one frame per packet, so always independently coded.
535- enc.enc_icdf(
536- (gain_idx[0] as usize) >> 3,
537- &GAIN_ICDF[signal_type as usize],
538- 8,
539- );
540- enc.enc_icdf((gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8);
541- for k in 1..nb_subfr {
542- enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8);
543- }
544- // NLSFs.
545- let cb = nlsf_cb(wb);
546- let stage1_icdf = &cb.cb1_icdf[(signal_type as usize >> 1) * cb.n_vectors..];
547- enc.enc_icdf(nq.indices[0] as usize, stage1_icdf, 8);
548- let (ec_ix, _) = crate::silk::nlsf_unpack(cb, nq.indices[0] as usize);
549- for i in 0..order {
550- let q = nq.indices[i + 1] as i32;
551- let icdf = &cb.ec_icdf[ec_ix[i] as usize..];
552- if q <= -4 {
553- enc.enc_icdf(0, icdf, 8);
554- enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8);
555- } else if q >= 4 {
556- enc.enc_icdf(8, icdf, 8);
557- enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8);
558- } else {
559- enc.enc_icdf((q + 4) as usize, icdf, 8);
560- }
561- }
562- if nb_subfr == MAX_NB_SUBFR {
563- enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8);
564- }
565- // Pitch + LTP. (One frame per packet: the decoder only takes the
566- // lag-delta code path for the 2nd+ frame of a packet, so the
567- // absolute lag is always coded here.)
568- if voiced {
569- let half = fs as i32 >> 1;
570- enc.enc_icdf((lag_index / half) as usize, &PITCH_LAG_ICDF, 8);
571- let low_icdf: &[u8] = match fs {
572- 16 => &UNIFORM8_ICDF,
573- 12 => &UNIFORM6_ICDF,
574- _ => &UNIFORM4_ICDF,
575- };
576- enc.enc_icdf((lag_index % half) as usize, low_icdf, 8);
577- let contour_icdf: &[u8] = match (fs, nb_subfr) {
578- (8, 4) => &PITCH_CONTOUR_NB_ICDF,
579- (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
580- (_, 4) => &PITCH_CONTOUR_ICDF,
581- _ => &PITCH_CONTOUR_10_MS_ICDF,
582- };
583- enc.enc_icdf(contour_index as usize, contour_icdf, 8);
584- enc.enc_icdf(per_index, &LTP_PER_INDEX_ICDF, 8);
585- let gain_icdf: &[u8] = match per_index {
586- 0 => &LTP_GAIN_ICDF_0,
587- 1 => &LTP_GAIN_ICDF_1,
588- _ => &LTP_GAIN_ICDF_2,
589- };
590- for k in 0..nb_subfr {
591- enc.enc_icdf(run.ltp_index[k], gain_icdf, 8);
592- }
593- enc.enc_icdf(ltp_scale_index, &LTPSCALE_ICDF, 8);
594- }
595- enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8);
596- encode_pulses(enc, &run.pulses, signal_type, quant_offset_type as i32);
597- };
573+ let fs = self.fs_khz;
598574 // One full trial at a common gain offset (in quantiser steps): returns
599575 // the coded packet body so the rate loop can read its exact size.
600576 let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] };
@@ -605,28 +581,45 @@ impl SilkEncoder {
605581 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;
606582 }
607583 let mut prev_gain_index = self.prev_gain_index;
608- let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, nb_subfr);
584+ let (gain_idx, gains_q16) =
585+ quantize_gains(&t, &mut prev_gain_index, conditional, nb_subfr);
609586 let (per_index, run) = candidates
610587 .iter()
611588 .map(|&per| (per, run(per, &gains_q16)))
612589 .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap())
613590 .unwrap();
614591
615- // --- Bitstream, in decode()'s order. ---
592+ let mut trial = Trial {
593+ bytes: Vec::new(),
594+ range: 0,
595+ prev_gain_index,
596+ gain_idx,
597+ per_index,
598+ run,
599+ vad_flag,
600+ signal_type,
601+ quant_offset_type,
602+ wb,
603+ order,
604+ nb_subfr,
605+ fs,
606+ lag_index,
607+ contour_index,
608+ voiced,
609+ ltp_scale_index,
610+ nq: nq.clone(),
611+ seed_index,
612+ };
616613 let enc = &mut self.range;
617614 enc.reset(1275);
618- write(enc, &gain_idx, per_index, &run);
615+ write_packet_header(enc, &[&trial]);
616+ write_frame_data(enc, &trial, conditional, prev_signal_type);
619617 enc.done();
620618 debug_assert!(!enc.error());
621619 let len = enc.range_bytes();
622- Trial {
623- bytes: enc.data()[..len].to_vec(),
624- range: enc.range(),
625- prev_gain_index,
626- gain_idx,
627- per_index,
628- run,
629- }
620+ trial.bytes = enc.data()[..len].to_vec();
621+ trial.range = enc.range();
622+ trial
630623 };
631624
632625 // Rate control: a common gain offset moves every subframe's pulse
@@ -664,7 +657,9 @@ impl SilkEncoder {
664657 );
665658 }
666659 if let Some(enc) = shared {
667- write(enc, &best.gain_idx, best.per_index, &best.run);
660+ let trial_ref = &best;
661+ write_packet_header(enc, &[trial_ref]);
662+ write_frame_data(enc, trial_ref, conditional, prev_signal_type);
668663 }
669664 self.prev_gain_index = best.prev_gain_index;
670665 self.voiced_frames += usize::from(voiced);
@@ -685,7 +680,6 @@ struct Run {
685680 gq: Vec<f32>,
686681 }
687682
688-/// One coded candidate of a frame at a given gain offset.
689683 struct Trial {
690684 bytes: Vec<u8>,
691685 range: u32,
@@ -693,6 +687,119 @@ struct Trial {
693687 gain_idx: [i8; MAX_NB_SUBFR],
694688 per_index: usize,
695689 run: Run,
690+ vad_flag: bool,
691+ signal_type: i32,
692+ quant_offset_type: usize,
693+ wb: bool,
694+ order: usize,
695+ nb_subfr: usize,
696+ fs: usize,
697+ lag_index: i32,
698+ contour_index: i32,
699+ voiced: bool,
700+ ltp_scale_index: usize,
701+ nq: NlsfQuant,
702+ seed_index: i32,
703+}
704+
705+fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial]) {
706+ for frame in frames {
707+ enc.enc_bit_logp(frame.vad_flag, 1);
708+ }
709+ enc.enc_bit_logp(false, 1);
710+}
711+
712+fn write_frame_data(
713+ enc: &mut RangeEncoder,
714+ frame: &Trial,
715+ conditional: bool,
716+ prev_signal_type: i32,
717+) {
718+ if frame.vad_flag {
719+ enc.enc_icdf(
720+ ((frame.signal_type << 1) | frame.quant_offset_type as i32) as usize - 2,
721+ &TYPE_OFFSET_VAD_ICDF,
722+ 8,
723+ );
724+ } else {
725+ enc.enc_icdf(frame.quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8);
726+ }
727+ if conditional {
728+ enc.enc_icdf(frame.gain_idx[0] as usize, &DELTA_GAIN_ICDF, 8);
729+ } else {
730+ enc.enc_icdf(
731+ (frame.gain_idx[0] as usize) >> 3,
732+ &GAIN_ICDF[frame.signal_type as usize],
733+ 8,
734+ );
735+ enc.enc_icdf((frame.gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8);
736+ }
737+ for k in 1..frame.nb_subfr {
738+ enc.enc_icdf(frame.gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8);
739+ }
740+ let cb = nlsf_cb(frame.wb);
741+ let stage1_icdf = &cb.cb1_icdf[(frame.signal_type as usize >> 1) * cb.n_vectors..];
742+ enc.enc_icdf(frame.nq.indices[0] as usize, stage1_icdf, 8);
743+ let (ec_ix, _) = crate::silk::nlsf_unpack(cb, frame.nq.indices[0] as usize);
744+ for i in 0..frame.order {
745+ let q = frame.nq.indices[i + 1] as i32;
746+ let icdf = &cb.ec_icdf[ec_ix[i] as usize..];
747+ if q <= -4 {
748+ enc.enc_icdf(0, icdf, 8);
749+ enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8);
750+ } else if q >= 4 {
751+ enc.enc_icdf(8, icdf, 8);
752+ enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8);
753+ } else {
754+ enc.enc_icdf((q + 4) as usize, icdf, 8);
755+ }
756+ }
757+ if frame.nb_subfr == MAX_NB_SUBFR {
758+ enc.enc_icdf(
759+ frame.nq.interp_index as usize,
760+ &NLSF_INTERPOLATION_FACTOR_ICDF,
761+ 8,
762+ );
763+ }
764+ if frame.voiced {
765+ if conditional && prev_signal_type == 2 {
766+ enc.enc_icdf(0, &PITCH_DELTA_ICDF, 8);
767+ }
768+ let half = frame.fs as i32 >> 1;
769+ enc.enc_icdf((frame.lag_index / half) as usize, &PITCH_LAG_ICDF, 8);
770+ let low_icdf: &[u8] = match frame.fs {
771+ 16 => &UNIFORM8_ICDF,
772+ 12 => &UNIFORM6_ICDF,
773+ _ => &UNIFORM4_ICDF,
774+ };
775+ enc.enc_icdf((frame.lag_index % half) as usize, low_icdf, 8);
776+ let contour_icdf: &[u8] = match (frame.fs, frame.nb_subfr) {
777+ (8, 4) => &PITCH_CONTOUR_NB_ICDF,
778+ (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
779+ (_, 4) => &PITCH_CONTOUR_ICDF,
780+ _ => &PITCH_CONTOUR_10_MS_ICDF,
781+ };
782+ enc.enc_icdf(frame.contour_index as usize, contour_icdf, 8);
783+ enc.enc_icdf(frame.per_index, &LTP_PER_INDEX_ICDF, 8);
784+ let gain_icdf: &[u8] = match frame.per_index {
785+ 0 => &LTP_GAIN_ICDF_0,
786+ 1 => &LTP_GAIN_ICDF_1,
787+ _ => &LTP_GAIN_ICDF_2,
788+ };
789+ for k in 0..frame.nb_subfr {
790+ enc.enc_icdf(frame.run.ltp_index[k], gain_icdf, 8);
791+ }
792+ if !conditional {
793+ enc.enc_icdf(frame.ltp_scale_index, &LTPSCALE_ICDF, 8);
794+ }
795+ }
796+ enc.enc_icdf(frame.seed_index as usize, &UNIFORM4_ICDF, 8);
797+ encode_pulses(
798+ enc,
799+ &frame.run.pulses,
800+ frame.signal_type,
801+ frame.quant_offset_type as i32,
802+ );
696803 }
697804
698805 /// Bits an ICDF symbol costs, for choosing among equivalent codings.
crates/ec-opus/tests/conformance.rsmodified+65 -5
@@ -972,9 +972,9 @@ fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8]
972972 ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping)
973973 }
974974
975-/// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the
976-/// stream to exactly `total_samples` — RFC 7845 end-trimming plus the
977-/// pre-skip accounting.
975+/// Muxes packets into an Ogg-Opus file whose final granule trims the stream
976+/// to exactly `total_samples` — RFC 7845 end-trimming plus the pre-skip
977+/// accounting.
978978 fn write_ogg_opus(
979979 path: &Path,
980980 packets: &[Vec<u8>],
@@ -996,16 +996,17 @@ fn write_ogg_opus(
996996 let mut pts = 0i64;
997997 for (idx, p) in packets.iter().enumerate() {
998998 let last = idx == packets.len() - 1;
999+ let packet_dur = ec_opus::Packet::parse(p, false).unwrap().samples_48k() as i64;
9991000 let dur = if last {
10001001 total_samples as i64 + pre_skip - pts
10011002 } else {
1002- 960
1003+ packet_dur
10031004 };
10041005 let pkt = CorePacket::new(0, tb, p.clone())
10051006 .with_pts(pts)
10061007 .with_duration(dur);
10071008 mux.write_packet(&pkt).unwrap();
1008- pts += 960;
1009+ pts += packet_dur;
10091010 }
10101011 mux.finish().unwrap();
10111012 }
@@ -1739,6 +1740,65 @@ fn silk_mediumband_and_10ms_roundtrip() {
17391740 }
17401741 }
17411742
1743+#[test]
1744+fn silk_multiframe_packets_roundtrip() {
1745+ let full = speech_like();
1746+ let pcm = &full[..46_080];
1747+ for (tag, enc, frame_ms, config, cutoff, bps) in [
1748+ (
1749+ "NB40",
1750+ SilkEncoder::new(false),
1751+ 40usize,
1752+ 2u8,
1753+ 3500.0,
1754+ 16_000u32,
1755+ ),
1756+ ("MB40", SilkEncoder::new_mediumband(), 40, 6, 5500.0, 20_000),
1757+ ("WB40", SilkEncoder::new(true), 40, 10, 7000.0, 24_000),
1758+ ("WB60", SilkEncoder::new(true), 60, 11, 7000.0, 24_000),
1759+ ] {
1760+ let (decoded, packets, voiced) = silk_roundtrip_ms(enc, pcm, frame_ms, Some(bps));
1761+ let toc = ec_opus::Toc::new(packets[0][0]);
1762+ assert_eq!(toc.config, config, "{tag}: wrong TOC config");
1763+ assert_eq!(toc.code, 0, "{tag}: multiframe SILK uses one Opus frame");
1764+ let reference = lowpass(pcm, cutoff);
1765+ let (corr, lag) = aligned_corr(&reference, &decoded, 2500);
1766+ let bytes: usize = packets.iter().map(Vec::len).sum();
1767+ let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64);
1768+ eprintln!(
1769+ "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps",
1770+ packets.len()
1771+ );
1772+ assert!(corr >= 0.70, "{tag}: corr {corr:.4}");
1773+ assert!(voiced > 0, "{tag}: no frame coded with LTP");
1774+ if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) {
1775+ let (c, _) = aligned_corr(&oracle, &decoded, 2500);
1776+ assert!(
1777+ c >= 0.99,
1778+ "{tag}: internal decode vs external decode corr {c:.4}"
1779+ );
1780+ }
1781+ if Command::new("gst-launch-1.0")
1782+ .arg("--version")
1783+ .output()
1784+ .is_ok()
1785+ {
1786+ let path = temp_path(&format!("silk-{tag}-gst.opus"));
1787+ write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120);
1788+ let location = format!("location={}", path.display());
1789+ let out = Command::new("gst-launch-1.0")
1790+ .args([
1791+ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink",
1792+ ])
1793+ .output()
1794+ .unwrap();
1795+ let stderr = String::from_utf8_lossy(&out.stderr);
1796+ assert!(out.status.success(), "{tag}: gst decode: {stderr}");
1797+ let _ = fs::remove_file(&path);
1798+ }
1799+ }
1800+}
1801+
17421802 #[test]
17431803 fn silk_compares_to_celt_on_speech_at_speech_rates() {
17441804 let pcm = speech_like();