diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index bb40b3f3..553724b1 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -1,14 +1,13 @@ -//! The Opus packet encoder: CELT and mono SILK, 8 to 48 kHz in. +//! The Opus packet encoder: CELT, SILK and hybrid, 8 to 48 kHz in. //! //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3) //! or the self-delimited variant of Appendix B that the multistream framing //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s -//! default) picks CELT (TOC configs 16..31, every rate and frame size) or -//! SILK (TOC configs 0/1/4/5/8/9, mono NB/MB/WB 10 or 20 ms only — -//! stereo SILK and SILK at other frame sizes fall back to CELT, documented -//! at the fallback site) or Hybrid (TOC configs 13/15, mono SWB/FB 20 ms: -//! SILK at 16 kHz under CELT from band 17 up, one range-coded stream; -//! stereo and other frame sizes fall back to CELT). +//! default) picks CELT (TOC configs 16..31, every rate and frame size), SILK +//! (TOC configs 0/1/4/5/8/9, mono or stereo NB/MB/WB 10 or 20 ms; mono also +//! 40/60 ms through [`SilkEncoder`]), or Hybrid (TOC configs 13/15, mono +//! SWB/FB 20 ms: SILK at 16 kHz under CELT from band 17 up, one range-coded +//! stream; stereo and other frame sizes fall back to CELT). //! //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and //! the coded bandwidth is capped at the input's own Nyquist, so the images @@ -25,7 +24,7 @@ use ec_core::{Error, Result}; use crate::celt_enc::CeltEncoder; use crate::packet::{Bandwidth, Mode}; use crate::range::RangeEncoder; -use crate::silk_enc_write::SilkEncoder; +use crate::silk_enc_write::{SilkEncoder, SilkStereoEncoder}; /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). const MAX_FRAME_BYTES: usize = 1275; @@ -82,6 +81,9 @@ pub struct Encoder { silk_nb: Option, silk_mb: Option, silk_wb: Option, + silk_stereo_nb: Option, + silk_stereo_mb: Option, + silk_stereo_wb: Option, /// Scratch space for the SILK payload, sized once so the steady-state /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. silk_buf: [u8; MAX_FRAME_BYTES + 1], @@ -132,6 +134,9 @@ impl Encoder { silk_nb: None, silk_mb: None, silk_wb: None, + silk_stereo_nb: None, + silk_stereo_mb: None, + silk_stereo_wb: None, silk_buf: [0u8; MAX_FRAME_BYTES + 1], silk_delay: Vec::new(), silk_stuff: Vec::new(), @@ -141,7 +146,7 @@ impl Encoder { /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and /// `hybrid_choice` make from the application and bitrate; pass `None` to /// restore the automatic pick. Requests this encoder cannot honour - /// (stereo SILK/Hybrid, SILK longer than 20 ms, or 10 ms Hybrid) fall back to CELT. + /// (SILK longer than 20 ms through this wrapper or 10 ms Hybrid) fall back to CELT. pub fn set_mode(&mut self, mode: Option) { self.mode = mode; } @@ -219,6 +224,9 @@ impl Encoder { self.silk_nb = None; self.silk_mb = None; self.silk_wb = None; + self.silk_stereo_nb = None; + self.silk_stereo_mb = None; + self.silk_stereo_wb = None; self.silk_delay.clear(); self.final_range = 0; } @@ -252,11 +260,10 @@ impl Encoder { } /// `wants_silk` narrowed to what this encoder can actually code as SILK: - /// mono, 10 or 20 ms (480 or 960 samples at 48 kHz) frames only. Stereo - /// SILK and longer SILK packets are future work; both fall back to CELT. + /// mono or stereo, 10 or 20 ms (480 or 960 samples at 48 kHz) frames. fn silk_choice(&self, frame_48k: usize) -> Option { let fs_khz = self.wants_silk()?; - if self.channels != 1 || !matches!(frame_48k, 480 | 960) { + if !matches!(frame_48k, 480 | 960) { return None; } Some(fs_khz) @@ -339,6 +346,21 @@ impl Encoder { } } + fn zero_stuff_stereo(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec) { + if upsample == 1 { + out.clear(); + out.extend_from_slice(&pcm[..2 * frame_size]); + return; + } + out.resize(2 * frame_size * upsample, 0.0); + out.fill(0.0); + for i in 0..frame_size { + let dst = 2 * i * upsample; + out[dst] = pcm[2 * i] * upsample as f32; + out[dst + 1] = pcm[2 * i + 1] * upsample as f32; + } + } + /// Picks SILK or CELT for one frame and encodes it, returning the TOC /// byte and the payload bytes (excluding TOC), borrowed from scratch /// space owned by `self` — no allocation on the steady-state path. @@ -352,6 +374,25 @@ impl Encoder { ) -> Result<(u8, &[u8])> { let frame_48k = frame_size * self.upsample; if let Some(fs_khz) = self.silk_choice(frame_48k) { + if self.channels == 2 { + Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); + let enc = match fs_khz { + 8 => self + .silk_stereo_nb + .get_or_insert_with(|| SilkStereoEncoder::new(false)), + 12 => self + .silk_stereo_mb + .get_or_insert_with(SilkStereoEncoder::new_mediumband), + _ => self + .silk_stereo_wb + .get_or_insert_with(|| SilkStereoEncoder::new(true)), + }; + enc.set_bitrate(self.bitrate); + let n = + enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?; + self.final_range = enc.final_range(); + return Ok((self.silk_buf[0], &self.silk_buf[1..n])); + } Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); let enc = match fs_khz { 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)), diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 91faa230..0f407f0d 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -81,7 +81,7 @@ pub use multistream_enc::MultistreamEncoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; pub use range::{RangeDecoder, RangeEncoder}; pub use silk::SilkDecoder; -pub use silk_enc_write::SilkEncoder; +pub use silk_enc_write::{SilkEncoder, SilkStereoEncoder}; use ec_core::{Error, Result}; diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 4b820008..2136c0a0 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -1,5 +1,5 @@ //! SILK payload writer (subtask D2a): turns the analysis in [`crate::silk_enc`] -//! into a decodable mono SILK packet, NB (8 kHz), MB (12 kHz) or WB (16 kHz). +//! into decodable SILK packets, NB (8 kHz), MB (12 kHz) or WB (16 kHz). //! //! Symbol order is exactly `silk::decode()`'s, and every decision is made //! against the decoder's own tables and reconstruction functions. The @@ -12,7 +12,7 @@ //! output error is fed back through short-term (bandwidth-expanded LPC), //! harmonic and tilt shaping filters so the noise hides under the signal's //! own spectrum, and a gain-offset rate loop sizes each packet against -//! [`SilkEncoder::set_bitrate`]. Stereo is not written yet. +//! [`SilkEncoder::set_bitrate`]. // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic. #![allow(clippy::needless_range_loop)] @@ -38,7 +38,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0; /// with 16 such pulses in one block. const MAX_PULSE: i32 = 1023; -/// A mono, 10 or 20 ms, NB/MB/WB SILK encoder. +/// A mono, 10/20/40/60 ms, NB/MB/WB SILK encoder. #[derive(Clone, Debug)] pub struct SilkEncoder { fs_khz: usize, @@ -127,6 +127,10 @@ impl SilkEncoder { self.target_bps = Some(bps); } + fn reset_state(&mut self) { + *self = Self::with_fs_khz(self.fs_khz); + } + /// Algorithmic delay in 48 kHz samples: the analysis resampler only /// (the decoder adds its own resampler delay on the way back up). pub fn delay_samples(&self) -> usize { @@ -180,6 +184,9 @@ impl SilkEncoder { prev_signal_type = trial.signal_type; frames.push(trial); } + if frames.iter().any(|frame| frame.voiced) { + self.voiced_frames += 1; + } self.range.reset(1275); let refs: Vec<&Trial> = frames.iter().collect(); write_packet_header(&mut self.range, &refs); @@ -225,8 +232,9 @@ impl SilkEncoder { /// must [`SilkEncoder::replay`] the finished payload so this encoder's /// decoder mirror advances. pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> { - self.encode_inner(pcm48, 20, Some(enc), false, 0) - .map(|_| ()) + let trial = self.encode_inner(pcm48, 20, Some(enc), false, 0)?; + self.voiced_frames += usize::from(trial.voiced); + Ok(()) } /// Decodes `payload` (TOC stripped) through the mirror decoder so the next @@ -662,7 +670,6 @@ impl SilkEncoder { write_frame_data(enc, trial_ref, conditional, prev_signal_type); } self.prev_gain_index = best.prev_gain_index; - self.voiced_frames += usize::from(voiced); self.shape_d.copy_from_slice(&best.run.d[n..]); self.shape_u.copy_from_slice(&best.run.u[n..]); self.shape_gq.copy_from_slice(&best.run.gq[n..]); @@ -670,6 +677,187 @@ impl SilkEncoder { } } +/// A stereo, 10 or 20 ms, NB/MB/WB SILK encoder. +#[derive(Clone, Debug)] +pub struct SilkStereoEncoder { + fs_khz: usize, + mid: SilkEncoder, + side: SilkEncoder, + range: RangeEncoder, + mirror: SilkDecoder, + final_range: u32, + mirror_range: u32, + mirror_out: Vec, + target_bps: Option, + prev_mid_only: bool, + voiced_frames: usize, +} + +impl SilkStereoEncoder { + /// Narrowband or wideband stereo encoder. + pub fn new(wideband: bool) -> SilkStereoEncoder { + Self::with_fs_khz(if wideband { 16 } else { 8 }) + } + + /// Mediumband stereo encoder. + pub fn new_mediumband() -> SilkStereoEncoder { + Self::with_fs_khz(12) + } + + fn with_fs_khz(fs_khz: usize) -> SilkStereoEncoder { + SilkStereoEncoder { + fs_khz, + mid: SilkEncoder::with_fs_khz(fs_khz), + side: SilkEncoder::with_fs_khz(fs_khz), + range: RangeEncoder::new(), + mirror: SilkDecoder::new(fs_khz as u32 * 1000, 2), + final_range: 0, + mirror_range: 0, + mirror_out: vec![0; 2 * 20 * fs_khz], + target_bps: None, + prev_mid_only: false, + voiced_frames: 0, + } + } + + /// The range coder state after the last packet. + pub fn final_range(&self) -> u32 { + self.final_range + } + + /// Packets so far coded with a long-term predictor in either channel. + pub fn voiced_frames(&self) -> usize { + self.voiced_frames + } + + /// Target bit rate in bits per second for the whole stereo packet. + pub fn set_bitrate(&mut self, bps: u32) { + self.target_bps = Some(bps); + let per_channel = (bps / 2).max(500); + self.mid.set_bitrate(per_channel); + self.side.set_bitrate(per_channel); + } + + /// Algorithmic delay in 48 kHz samples. + pub fn delay_samples(&self) -> usize { + self.mid.delay_samples() + } + + /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz. + pub fn encode_frame_ms( + &mut self, + pcm48: &[f32], + out: &mut [u8], + frame_ms: usize, + ) -> Result { + assert!( + matches!(frame_ms, 10 | 20), + "SilkStereoEncoder codes 10 or 20 ms stereo frames" + ); + assert_eq!( + pcm48.len(), + 2 * 48 * frame_ms, + "SilkStereoEncoder input is 48 kHz stereo" + ); + if self.prev_mid_only { + self.side.reset_state(); + if let Some(bps) = self.target_bps { + self.side.set_bitrate((bps / 2).max(500)); + } + } + let samples = 48 * frame_ms; + let mut mid = Vec::with_capacity(samples); + let mut side = Vec::with_capacity(samples); + let mut side_energy = 0.0f32; + for lr in pcm48.chunks_exact(2) { + let m = 0.5 * (lr[0] + lr[1]); + let s = 0.5 * (lr[0] - lr[1]); + mid.push(m); + side.push(s); + side_energy += s * s; + } + let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?; + let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?; + let mid_only = side_energy < 1.0e-10; + + self.range.reset(1275); + write_stereo_packet_header(&mut self.range, &mid_trial, &side_trial, mid_only); + write_stereo_zero_pred(&mut self.range); + if !side_trial.vad_flag { + self.range + .enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8); + } + write_frame_data(&mut self.range, &mid_trial, false, 0); + if !mid_only { + write_frame_data(&mut self.range, &side_trial, false, 0); + } + self.range.done(); + debug_assert!(!self.range.error()); + let len = self.range.range_bytes(); + self.final_range = self.range.range(); + let duration = if frame_ms == 10 { 0u8 } else { 1 }; + let base = match self.fs_khz { + 8 => 0u8, + 12 => 4, + _ => 8, + }; + if out.len() < 1 + len { + return Err(ec_core::Error::corrupt(format!( + "silk stereo encode: packet needs {} bytes, buffer holds {}", + 1 + len, + out.len() + ))); + } + out[0] = ((base + duration) << 3) | 0x04; + out[1..1 + len].copy_from_slice(&self.range.data()[..len]); + self.replay_ms(&out[1..1 + len], frame_ms)?; + self.mid.replay_ms(&mid_trial.bytes, frame_ms)?; + if mid_only { + self.side.reset_state(); + } else { + self.side.replay_ms(&side_trial.bytes, frame_ms)?; + } + self.prev_mid_only = mid_only; + self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced); + debug_assert_eq!(self.mirror_range, self.final_range); + Ok(1 + len) + } + + fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { + let fs = self.fs_khz; + let mut dec = RangeDecoder::new(payload); + let total = 2 * frame_ms * fs; + if self.mirror_out.len() < total { + self.mirror_out.resize(total, 0); + } + let n = self.mirror.decode( + &mut dec, + &mut self.mirror_out[..total], + frame_ms, + fs as u32 * 1000, + 2, + true, + )?; + debug_assert_eq!(n, frame_ms * fs); + self.mirror_range = dec.range(); + Ok(()) + } +} + +fn write_stereo_packet_header(enc: &mut RangeEncoder, mid: &Trial, side: &Trial, mid_only: bool) { + enc.enc_bit_logp(mid.vad_flag, 1); + enc.enc_bit_logp(false, 1); + enc.enc_bit_logp(if mid_only { false } else { side.vad_flag }, 1); + enc.enc_bit_logp(false, 1); +} + +fn write_stereo_zero_pred(enc: &mut RangeEncoder) { + enc.enc_icdf(12, &STEREO_PRED_JOINT_ICDF, 8); + enc.enc_icdf(1, &UNIFORM3_ICDF, 8); + enc.enc_icdf(2, &UNIFORM5_ICDF, 8); + enc.enc_icdf(1, &UNIFORM3_ICDF, 8); + enc.enc_icdf(2, &UNIFORM5_ICDF, 8); +} /// One closed-loop quantisation of a frame. struct Run { ltp_index: [usize; MAX_NB_SUBFR], diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 55e22b95..365adcb6 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -1037,7 +1037,14 @@ fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec PathBuf { - std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id())) + let root = std::env::var_os("EC_OPUS_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(|| { + let home = std::env::var_os("HOME").expect("HOME set for encoder scratch"); + PathBuf::from(home).join(".cache/silk2") + }); + fs::create_dir_all(&root).unwrap(); + root.join(format!("ec-opus-enc-{}-{name}", std::process::id())) } /// The full product rate table, mono and stereo, decoded by libopus: the @@ -1799,6 +1806,123 @@ fn silk_multiframe_packets_roundtrip() { } } +fn stereo_speech_pair() -> Vec { + let left = speech_like(); + let mut out = Vec::with_capacity(left.len() * 2); + for (i, &l) in left.iter().enumerate() { + let t = i as f64 / 48000.0; + let r = 0.78 * l + 0.12 * (std::f64::consts::TAU * 310.0 * t).sin() as f32; + out.push(l); + out.push(r); + } + out +} + +fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch: usize) -> f64 { + let b: Vec = decoded.chunks_exact(channels).map(|f| f[ch]).collect(); + aligned_corr(reference, &b, 2000).0 +} + +#[test] +fn silk_stereo_speech_roundtrip() { + let pcm = stereo_speech_pair(); + let total = pcm.len() / 2; + for (tag, bandwidth, per_channel_bps, cutoff, config) in [ + ("NB20", Bandwidth::Narrow, 16_000u32, 3500.0, 1u8), + ("MB20", Bandwidth::Medium, 20_000, 5500.0, 5), + ("WB20", Bandwidth::Wide, 24_000, 7000.0, 9), + ] { + let frame = if tag.ends_with("10") { 480 } else { 960 }; + let frame_ms = frame / 48; + let mut mono_floor = [0.0f64; 2]; + for ch in 0..2 { + let mono: Vec = pcm.chunks_exact(2).map(|f| f[ch]).collect(); + let silk = match bandwidth { + Bandwidth::Narrow => SilkEncoder::new(false), + Bandwidth::Medium => SilkEncoder::new_mediumband(), + _ => SilkEncoder::new(true), + }; + let reference = lowpass(&mono, cutoff); + let (decoded, _, _) = silk_roundtrip_ms(silk, &mono, frame_ms, Some(per_channel_bps)); + mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0; + } + + let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap(); + enc.set_mode(Some(ec_opus::Mode::Silk)); + enc.set_bandwidth(Some(bandwidth)); + enc.set_bitrate(per_channel_bps * 2); + let mut dec = Decoder::new(48000, 2).unwrap(); + let mut out = vec![0u8; 1500]; + let mut buf = vec![0.0f32; 5760 * 2]; + let mut decoded = Vec::new(); + let mut packets = Vec::new(); + let mut padded = pcm.clone(); + padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0); + for block in padded.chunks(frame * 2) { + let len = enc.encode_float(block, frame, &mut out).expect("encode"); + let toc = ec_opus::Toc::new(out[0]); + assert_eq!(toc.config, config, "{tag}: wrong TOC config"); + assert!(toc.stereo, "{tag}: SILK TOC is not stereo"); + let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); + assert_eq!(n, frame, "{tag}: decoded frame size"); + assert_eq!(dec.final_range(), enc.final_range(), "{tag}: range state"); + decoded.extend_from_slice(&buf[..n * 2]); + packets.push(out[..len].to_vec()); + } + let bytes: usize = packets.iter().map(Vec::len).sum(); + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64); + for ch in 0..2 { + let source: Vec = pcm.chunks_exact(2).map(|f| f[ch]).collect(); + let reference = lowpass(&source, cutoff); + let corr = aligned_channel_corr(&reference, &decoded, 2, ch); + eprintln!( + "silk stereo {tag} ch{ch}: corr {corr:.4}, mono {:.4}, {kbps:.2} kbps", + mono_floor[ch] + ); + assert!( + corr + 0.01 >= mono_floor[ch], + "{tag} ch{ch}: stereo corr {corr:.4} trails mono {:.4}", + mono_floor[ch] + ); + } + if Command::new("ffmpeg").arg("-version").output().is_ok() { + let path = temp_path(&format!("silk-stereo-{tag}.opus")); + write_ogg_opus( + &path, + &packets, + opus_head(2, enc.look_ahead(frame) as u16, None), + 2, + total, + enc.look_ahead(frame) as i64, + ); + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); + if Command::new("gst-launch-1.0") + .arg("--version") + .output() + .is_ok() + { + let location = format!("location={}", path.display()); + let out = Command::new("gst-launch-1.0") + .args([ + "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", + "fakesink", + ]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: gst decode: {stderr}"); + } + let _ = fs::remove_file(&path); + } + } +} #[test] fn silk_compares_to_celt_on_speech_at_speech_rates() { let pcm = speech_like();