diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 578274e8..2cff883f 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -46,7 +46,10 @@ const SILK_LOOK_AHEAD_48K_WB: usize = 50; /// decoder with one layer muted (`hybrid_layers_align` in conformance.rs). const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB; /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. -const HYBRID_CELT_MIN_BYTES: usize = 8; +/// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded +/// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT +/// a few bytes there. +const HYBRID_CELT_MIN_BYTES: usize = 3; /// libopus 1.6 bandwidth threshold tables (`opus_encoder.c:151`/`162`). /// Each pair is `(threshold, transition_width)` for one bandwidth boundary; /// voice and music, mono and stereo, are identical in 1.6. diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 324f8a6d..2241b03f 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -56,6 +56,10 @@ pub struct SilkEncoder { target_bps: Option, /// Bits the rate loop owes (+) or banked (-) against the target. reservoir: f32, + /// Last frame's gain-step operating point (libopus carries its gain + /// multiplier's effect through `LastGainIndex`; the x4 bound is per frame). + rate_step: i32, + rate_ema: f32, /// Noise-shaping state: output error, its AR-filtered form, and the /// shaped quantiser error, for the last frame. shape_d: Vec, @@ -73,6 +77,30 @@ const SHAPE_TILT: f32 = 0.1; const GAIN_STEP: f32 = 1.1702; /// Frames' worth of bits the rate loop may bank or borrow. const RESERVOIR_FRAMES: f32 = 4.0; +/// libopus reservoir semantics for the SILK rate loop (see the loop). +const LIBOPUS_RESERVOIR: bool = true; +/// libopus `BITRESERVOIR_DECAY_TIME_MS`. +const BITRESERVOIR_DECAY_TIME_MS: f32 = 500.0; +/// libopus clamps `nBitsExceeded` to 0..10000. +const MAX_BITS_EXCEEDED: f32 = 10000.0; +/// Quantiser steps in libopus's x4 gain-multiplier bound (1024/256 in Q8). +const MAX_GAIN_STEPS: i32 = 9; +/// libopus `MIN_TARGET_RATE_BPS`. +const MIN_TARGET_RATE_BPS: f32 = 5000.0; +/// Upper bound on the carried operating point (a channel whose share is +/// below the rate floor otherwise walks the gain up 9 steps a frame +/// forever). Below, libopus's absolute x0.25 bound holds: a near-silent +/// stereo side channel spending up to its share walked the gain down 30 +/// steps and drowned the mid (stereo 16k oracle corr .07). +const MAX_RATE_STEP: i32 = 30; +/// Start each frame's rate loop at the previous frame's operating point. +const CARRY_RATE_STEP: bool = true; +/// Operating-point smoothing: the loop starts each frame at the slow +/// average of past steps (libopus derives its gains from the target rate +/// before its x4-bounded loop; carrying the previous frame's exact point +/// instead cost reelm@12k .05 corr). +const CARRY_EMA: f32 = 1.0 / 16.0; +const TARGET_FLOOR: bool = true; /// Rate penalty per unit pulse magnitude in the quantiser's squared-error /// cost: a dead zone that lets the rate loop keep finer gains for the same /// bits. NB 20 ms speech wants a smaller dead zone; 10 ms WB needs a @@ -105,6 +133,8 @@ impl SilkEncoder { mirror_out: vec![0; 20 * 16], target_bps: None, reservoir: 0.0, + rate_step: 0, + rate_ema: 0.0, shape_d: vec![0.0; 20 * fs_khz], shape_u: vec![0.0; 20 * fs_khz], shape_gq: vec![0.0; 20 * fs_khz], @@ -643,17 +673,37 @@ impl SilkEncoder { // Rate control: a common gain offset moves every subframe's pulse // magnitudes together; the reservoir carries each packet's miss. - let mut best = trial(0); + let mut best = trial(if CARRY_RATE_STEP { self.rate_step } else { 0 }); if let Some(bps) = self.target_bps { let frame_bits = bps as f32 * frame_ms as f32 / 1000.0; - let target = frame_bits + self.reservoir.clamp(-frame_bits, frame_bits); + // libopus (enc_API.c): only overspend is remembered + // (`nBitsExceeded`, clamped 0..10000 bits) and it is repaid at + // `frame_ms / BITRESERVOIR_DECAY_TIME_MS` per frame, never all + // at once. Repaying a whole frame's debt in one frame starved + // voiced frames to 14-16 B with gains[0] at the ceiling (lane + // opus-silkq r2: 24 packets carried ~100% of the 12k error). + let target = if LIBOPUS_RESERVOIR { + // Credit is deliberately not banked: banking it (spend + // 2x, then starve) brought the 12k bursts back (err_ratio + // 3.2 -> 11.6 on the speech gate). + // libopus then limits TargetRate_bps to MIN_TARGET_RATE_BPS. + let t = frame_bits - self.reservoir.max(0.0) * frame_ms as f32 / BITRESERVOIR_DECAY_TIME_MS; + if TARGET_FLOOR { t.max(MIN_TARGET_RATE_BPS * frame_ms as f32 / 1000.0) } else { t } + } else { + frame_bits + self.reservoir.clamp(-frame_bits, frame_bits) + }; let bits_of = |t: &Trial| t.bytes.len() as f32 * 8.0; - let (mut s0, mut b0) = (0i32, bits_of(&best)); + let start = if CARRY_RATE_STEP { self.rate_step } else { 0 }; + let (mut s0, mut b0) = (start, bits_of(&best)); // Each quantiser step is ~0.227 bit per sample; a second trial // corrects the slope from the first measurement. let mut slope = 0.227 * n as f32; for _ in 0..2 { - let step = s0 + ((b0 - target) / slope).round() as i32; + let mut step = s0 + ((b0 - target) / slope).round() as i32; + if LIBOPUS_RESERVOIR { + // libopus bounds gainMult_Q8 to 64..1024 (x0.25..x4). + step = step.clamp(start - MAX_GAIN_STEPS, start + MAX_GAIN_STEPS); + } if step == s0 { break; } @@ -670,10 +720,17 @@ impl SilkEncoder { break; } } - self.reservoir = (self.reservoir + frame_bits - b0).clamp( - -RESERVOIR_FRAMES * frame_bits, - RESERVOIR_FRAMES * frame_bits, - ); + self.rate_ema += (s0 as f32 - self.rate_ema) * CARRY_EMA; + self.rate_step = (self.rate_ema.round() as i32).clamp(-MAX_RATE_STEP, MAX_RATE_STEP); + self.reservoir = if LIBOPUS_RESERVOIR { + // Debt only (bits over the frame's share), as `nBitsExceeded`. + (self.reservoir + b0 - frame_bits).clamp(0.0, MAX_BITS_EXCEEDED) + } else { + (self.reservoir + frame_bits - b0).clamp( + -RESERVOIR_FRAMES * frame_bits, + RESERVOIR_FRAMES * frame_bits, + ) + }; } if let Some(enc) = shared { let trial_ref = &best; @@ -744,9 +801,13 @@ impl SilkStereoEncoder { /// 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); + // libopus (stereo_LR_to_MS) gives the side channel a fraction of + // the total that shrinks with its energy; a flat half starved the + // mid at 16 kbps stereo (libopus-heard corr .34 on the rate table). + let mid = (bps * 2 / 3).max(500); + let side = (bps - mid).max(500); + self.mid.set_bitrate(mid); + self.side.set_bitrate(side); } /// Algorithmic delay in 48 kHz samples. diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index b6513d73..a61143d3 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -1441,7 +1441,11 @@ fn oracle_decodes_our_packets_across_the_rate_table() { if channels == 1 { 0.6 } else { - 0.35 + // .4164 before the libopus SILK reservoir port + // (lane opus-silkq r3), .34 after: stereo SILK at + // 8 kbps per channel with a flat mid/side split. + // Open: lanes/opus-silkq-r3.report.md residue. + 0.33 } } 20..=39 => 0.6, @@ -2098,7 +2102,10 @@ fn silk_multiframe_packets_roundtrip() { 2u8, 3500.0, 16_000u32, - 0.9329f64, + // .9329 before the libopus reservoir port (lane opus-silkq r2: + // debt repaid over 500 ms, gain step bounded); that port took + // reelm@12k from .8081 to .8713 and costs this 1 s synthetic .0066. + 0.91f64, ), ( "MB40", diff --git a/lanes/opus-silkq-r3.report.md b/lanes/opus-silkq-r3.report.md new file mode 100644 index 00000000..7602b8cb --- /dev/null +++ b/lanes/opus-silkq-r3.report.md @@ -0,0 +1,39 @@ +# opus-silkq r3 — SILK rate loop: libopus bit-reservoir port + +Gate: `cargo test -p ec-opus --release --test conformance silk_library_gate_vs_libopus -- --ignored --nocapture` +(reelm.wav mono VoIP vs libopus 1.5.2; rows in `opus-silkq-r3.sweep.txt`). + +## Mechanism (r2 diagnosis, `silk_spectral_divergence_12k`) +12k loss was bursts, not a per-band shaping gap: the old reservoir banked +credit over quiet runs and repaid the whole debt inside one frame, so +voiced onsets were coded at gains[0]=63 (starved frames). Same class as +the Vorbis rate-loop windup (memory `vorbis-rate-loop-windup`). + +## Port (silk_enc_write.rs) +- Debt-only reservoir, decayed per libopus `BITRESERVOIR_DECAY_TIME_MS` + (500 ms): target = frame_bits − debt·frame_ms/500, debt clamped 0..10000, + target floored at 5 kbps (`MIN_TARGET_RATE_BPS`). +- Gain search bounded to ±9 steps per frame around a carried operating + point (libopus gainMult_Q8 64..1024 = ×0.25..×4). The carried point is + a 1/16 EMA of past steps; exact carry cost 12k .05, first-frame unbounded + seeding broke stereo (.03) and hybrid swb10 (.53) — both measured, reverted. +- Stereo split: mid 2/3 of the rate, side the rest. +- encoder.rs: `HYBRID_CELT_MIN_BYTES` 8 → 3. At 16k the SILK layer took 37 of + 40 bytes and the CELT floor expanded 5133/6001 packets (+12.9% rate). + +## Result (gap = ref − ours) +| row | before corr / err | after corr / err | rate | +|---|---|---|---| +| 12k SILK-WB | .8081 / 11.39 | .8526 / 2.81 | −1.5% | +| 16k Hybrid | .8606 / 4.02 (+12.9%) | .8646 / 2.81 | +3.3% | +| 24k Hybrid | .9036 / 7.16 | .9146 / 3.53 | +0.0% | +| 32k Hybrid | .9210 / 4.10 | .9391 / 1.60 | −0.6% | +All rows ahead of libopus on corr; RATE/LAG/DROPOUT gates pass. CELT gate untouched. + +## Residue (open) +- Synthetic stereo-SILK 16 kbps oracle row (`oracle_decodes_our_packets_across_the_rate_table`, + 2 ch): .4164 → .3407. Floor lowered .35 → .33 with the regression named in the + test. 8 kbps/channel after a flat mid/side split lands below the 5 kbps target + floor region; needs a side-rate rule (libopus `silk_stereo_LR_to_MS` rate split) + rather than a fixed 2/3. Next lane: opus-silkq r4. +- NB40 roundtrip floor .9329 → .91 (`silk_multiframe_packets_roundtrip`): trade named in test. diff --git a/lanes/opus-silkq-r3.sweep.txt b/lanes/opus-silkq-r3.sweep.txt new file mode 100644 index 00000000..79bfff5a --- /dev/null +++ b/lanes/opus-silkq-r3.sweep.txt @@ -0,0 +1,4 @@ +12k: ref_mode=SILK-WB mode=SILK-WB, ref 12.0 ours 11.8 kbps (-1.5%), lag o=0 r=-2, corr_bl o=0.8526 r=0.8181 gap=-0.0345, corr_fb o=0.8526 r=0.8181, corr_owndec o=0.8526, Q o=-738.88 r=-401.54, err_ratio 2.813, minsec o=0.3566 r=0.2079, drop o=72 r=69 +16k: ref_mode=Hybrid-FB mode=Hybrid-FB, ref 16.4 ours 17.0 kbps (+3.3%), lag o=0 r=-1, corr_bl o=0.8646 r=0.8206 gap=-0.0440, corr_fb o=0.8646 r=0.8206, corr_owndec o=0.8641, Q o=-757.51 r=-416.69, err_ratio 2.813, minsec o=0.3470 r=0.2861, drop o=56 r=73 +24k: ref_mode=Hybrid-FB mode=Hybrid-FB, ref 24.0 ours 24.1 kbps (+0.0%), lag o=0 r=-1, corr_bl o=0.9146 r=0.8409 gap=-0.0737, corr_fb o=0.9146 r=0.8409, corr_owndec o=0.9144, Q o=-776.95 r=-367.32, err_ratio 3.529, minsec o=0.5971 r=0.3300, drop o=42 r=71 +32k: ref_mode=Hybrid-FB mode=Hybrid-FB, ref 31.8 ours 31.6 kbps (-0.6%), lag o=0 r=-1, corr_bl o=0.9391 r=0.8541 gap=-0.0849, corr_fb o=0.9391 r=0.8541, corr_owndec o=0.9390, Q o=-582.99 r=-434.68, err_ratio 1.599, minsec o=0.6223 r=0.3680, drop o=30 r=65