Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Refactor opus for strict Clippy checks

Dylan M. Taylor78d77b72d3cf
diff --git a/crates/opus/src/celt.rs b/crates/opus/src/celt.rs
index f1021b8cd..4719c3eab 100644
--- a/crates/opus/src/celt.rs
+++ b/crates/opus/src/celt.rs
@@ -8,11 +8,11 @@ pub(crate) mod tables;
use std::sync::OnceLock;
-use bands::{anti_collapse, denormalise_bands, quant_all_bands, renormalise_vector};
-use energy::{unquant_coarse_energy, unquant_energy_finalise, unquant_fine_energy};
+use bands::{AntiCollapseInput, DenormaliseBandsInput, QuantAllBandsInput, anti_collapse, denormalise_bands, quant_all_bands, renormalise_vector};
+use energy::{EnergyFinalise, unquant_coarse_energy, unquant_energy_finalise, unquant_fine_energy};
use mdct::ImdctScratch;
-use rate::{Mode, compute_allocation};
-use tables::*;
+use rate::{AllocationInput, Mode, compute_allocation};
+use tables::{COMB_GAINS, EBANDS, MAX_LM, NB_EBANDS, OVERLAP, PREEMPH, SHORT_MDCT, SPREAD_ICDF, TAPSET_ICDF, TF_SELECT_TABLE, TRIM_ICDF};
use crate::range::{BITRES, RangeDecoder};
@@ -21,11 +21,58 @@ const COMBFILTER_MINPERIOD: i32 = 15;
const PLC_PITCH_LAG_MAX: usize = 720;
const PLC_PITCH_LAG_MIN: usize = 100;
+struct SynthesisFrame<'a> {
+ bands: &'a [f32],
+ samples: usize,
+ start_band: usize,
+ end_band: usize,
+ coded_channels: usize,
+ transient: bool,
+ lm: usize,
+ silence: bool,
+}
+
pub(crate) fn mode() -> &'static Mode {
static MODE: OnceLock<Mode> = OnceLock::new();
MODE.get_or_init(Mode::new)
}
+fn packet_silence(dec: &mut RangeDecoder, total_bits: i32) -> (bool, i32) {
+ let mut tell = dec.tell();
+ let silence = if tell >= total_bits {
+ true
+ } else if tell == 1 {
+ dec.bit_logp(15)
+ } else {
+ false
+ };
+ if silence {
+ // Pretend we've read all the remaining bits.
+ dec.skip_to_end(total_bits);
+ tell = total_bits;
+ }
+ (silence, tell)
+}
+
+fn read_postfilter(dec: &mut RangeDecoder, start: usize, mut tell: i32, total_bits: i32) -> (f32, i32, usize, i32) {
+ let mut gain = 0.0;
+ let mut pitch = 0;
+ let mut tapset = 0;
+ if start == 0 && tell + 16 <= total_bits {
+ if dec.bit_logp(1) {
+ let octave = dec.uint(6);
+ pitch = ((16 << octave) + dec.bits(4 + octave)) as i32 - 1;
+ let qg = dec.bits(3);
+ if dec.tell() + 2 <= total_bits {
+ tapset = dec.icdf(&TAPSET_ICDF, 2);
+ }
+ gain = 0.09375 * (qg + 1) as f32;
+ }
+ tell = dec.tell();
+ }
+ (gain, pitch, tapset, tell)
+}
+
/// CELT decoder state for one (mono or stereo) stream.
pub struct CeltDecoder {
m: &'static Mode,
@@ -176,34 +223,8 @@ impl CeltDecoder {
}
}
let total_bits_raw = len as i32 * 8;
- let mut tell = dec.tell();
- let silence = if tell >= total_bits_raw {
- true
- } else if tell == 1 {
- dec.bit_logp(15)
- } else {
- false
- };
- if silence {
- // Pretend we've read all the remaining bits.
- dec.skip_to_end(total_bits_raw);
- tell = total_bits_raw;
- }
- let mut postfilter_gain = 0.0f32;
- let mut postfilter_pitch = 0i32;
- let mut postfilter_tapset = 0usize;
- if start == 0 && tell + 16 <= total_bits_raw {
- if dec.bit_logp(1) {
- let octave = dec.uint(6);
- postfilter_pitch = ((16 << octave) + dec.bits(4 + octave)) as i32 - 1;
- let qg = dec.bits(3);
- if dec.tell() + 2 <= total_bits_raw {
- postfilter_tapset = dec.icdf(&TAPSET_ICDF, 2);
- }
- postfilter_gain = 0.09375 * (qg + 1) as f32;
- }
- tell = dec.tell();
- }
+ let (silence, tell) = packet_silence(dec, total_bits_raw);
+ let (postfilter_gain, postfilter_pitch, postfilter_tapset, mut tell) = read_postfilter(dec, start, tell, total_bits_raw);
let is_transient = if lm > 0 && tell + 3 <= total_bits_raw {
let t = dec.bit_logp(3);
tell = dec.tell();
@@ -250,7 +271,18 @@ impl CeltDecoder {
let mut bits = ((len as i32 * 8) << BITRES) - dec.tell_frac() as i32 - 1;
let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm as i32 + 2) << BITRES) { 1 << BITRES } else { 0 };
bits -= anti_collapse_rsv;
- let alloc = compute_allocation(m, start, end, &offsets, &cap, alloc_trim, bits, c, lm, dec);
+ let alloc = compute_allocation(AllocationInput {
+ mode: m,
+ start,
+ end,
+ offsets: &offsets,
+ cap: &cap,
+ trim: alloc_trim,
+ total: bits,
+ channels: c,
+ lm,
+ decoder: dec,
+ });
unquant_fine_energy(start, end, &mut self.old_band_e, &alloc.fine_quant, dec, c);
// Shift the decode memory by one frame.
@@ -268,27 +300,27 @@ impl CeltDecoder {
let (xa, xb) = x.split_at_mut(n);
let yb = if c == 2 { Some(xb) } else { None };
let mut seed = self.rng;
- quant_all_bands(
- m,
+ quant_all_bands(QuantAllBandsInput {
+ mode: m,
start,
end,
- xa,
- yb,
- &mut collapse_masks,
- &alloc.pulses,
+ x_buf: xa,
+ y_buf: yb,
+ collapse_masks: &mut collapse_masks,
+ pulses: &alloc.pulses,
short_blocks,
spread,
- alloc.dual_stereo,
- alloc.intensity,
- &tf_res,
- ((len as i32) * (8 << BITRES)) - anti_collapse_rsv,
- alloc.balance,
- dec,
+ dual_stereo: alloc.dual_stereo,
+ intensity: alloc.intensity,
+ tf_res: &tf_res,
+ total_bits: ((len as i32) * (8 << BITRES)) - anti_collapse_rsv,
+ balance: alloc.balance,
+ decoder: dec,
lm,
- alloc.coded_bands,
- &mut seed,
- self.disable_inv,
- );
+ coded_bands: alloc.coded_bands,
+ seed: &mut seed,
+ disable_inv: self.disable_inv,
+ });
self.rng = seed;
}
let mut anti_collapse_on = false;
@@ -296,16 +328,38 @@ impl CeltDecoder {
anti_collapse_on = dec.bits(1) != 0;
}
let bits_left = len as i32 * 8 - dec.tell();
- unquant_energy_finalise(start, end, &mut self.old_band_e, &alloc.fine_quant, &alloc.fine_priority, bits_left, dec, c);
+ unquant_energy_finalise(EnergyFinalise {
+ start,
+ end,
+ old_e: &mut self.old_band_e,
+ fine_quant: &alloc.fine_quant,
+ fine_priority: &alloc.fine_priority,
+ bits_left,
+ decoder: dec,
+ channels: c,
+ });
if anti_collapse_on {
- anti_collapse(&mut x, &collapse_masks, lm, c, n, start, end, &self.old_band_e, &self.old_log_e, &self.old_log_e2, &alloc.pulses, self.rng);
+ anti_collapse(AntiCollapseInput {
+ x_buf: &mut x,
+ collapse_masks: &collapse_masks,
+ lm,
+ channels: c,
+ size: n,
+ start,
+ end,
+ log_e: &self.old_band_e,
+ prev1: &self.old_log_e,
+ prev2: &self.old_log_e2,
+ pulses: &alloc.pulses,
+ seed: self.rng,
+ });
}
if silence {
for v in self.old_band_e[..c * NB_EBANDS].iter_mut() {
*v = -28.0;
}
}
- self.synthesis(&x, n, start, eff_end, c, is_transient, lm, silence);
+ self.synthesis(SynthesisFrame { bands: &x, samples: n, start_band: start, end_band: eff_end, coded_channels: c, transient: is_transient, lm, silence });
self.x = x;
// Post-filter.
@@ -316,28 +370,32 @@ impl CeltDecoder {
let off = DECODE_BUFFER_SIZE - n;
comb_filter(
mem,
- off,
- self.postfilter_period_old,
- self.postfilter_period,
- SHORT_MDCT,
- self.postfilter_gain_old,
- self.postfilter_gain,
- self.postfilter_tapset_old,
- self.postfilter_tapset,
- &m.window,
+ CombFilterParams {
+ offset: off,
+ old_period: self.postfilter_period_old,
+ new_period: self.postfilter_period,
+ samples: SHORT_MDCT,
+ old_gain: self.postfilter_gain_old,
+ new_gain: self.postfilter_gain,
+ old_tapset: self.postfilter_tapset_old,
+ new_tapset: self.postfilter_tapset,
+ window: &m.window,
+ },
);
if lm != 0 {
comb_filter(
mem,
- off + SHORT_MDCT,
- self.postfilter_period,
- postfilter_pitch,
- n - SHORT_MDCT,
- self.postfilter_gain,
- postfilter_gain,
- self.postfilter_tapset,
- postfilter_tapset,
- &m.window,
+ CombFilterParams {
+ offset: off + SHORT_MDCT,
+ old_period: self.postfilter_period,
+ new_period: postfilter_pitch,
+ samples: n - SHORT_MDCT,
+ old_gain: self.postfilter_gain,
+ new_gain: postfilter_gain,
+ old_tapset: self.postfilter_tapset,
+ new_tapset: postfilter_tapset,
+ window: &m.window,
+ },
);
}
}
@@ -380,8 +438,8 @@ impl CeltDecoder {
}
/// Denormalisation + IMDCT into the decode memory (`celt_synthesis`).
- #[allow(clippy::too_many_arguments)]
- fn synthesis(&mut self, x: &[f32], n: usize, start: usize, eff_end: usize, c: usize, is_transient: bool, lm: usize, silence: bool) {
+ fn synthesis(&mut self, frame: SynthesisFrame<'_>) {
+ let SynthesisFrame { bands: x, samples: n, start_band: start, end_band: eff_end, coded_channels: c, transient: is_transient, lm, silence } = frame;
let cc = self.channels;
let m = self.m;
let mm = 1usize << lm;
@@ -393,7 +451,16 @@ impl CeltDecoder {
let (f0, f1) = freq.split_at_mut(n);
let out_off = DECODE_BUFFER_SIZE - n;
if cc == 2 && c == 1 {
- denormalise_bands(x, f0, &self.old_band_e, start, eff_end, mm, self.downsample, silence);
+ denormalise_bands(DenormaliseBandsInput {
+ x,
+ freq: f0,
+ band_log_e: &self.old_band_e,
+ start,
+ end: eff_end,
+ mm,
+ downsample: self.downsample,
+ silence,
+ });
f1.copy_from_slice(f0);
for (ch, f) in [(0usize, &*f1), (1usize, &*f0)] {
let mem = &mut self.decode_mem[ch * ml..(ch + 1) * ml];
@@ -402,8 +469,26 @@ impl CeltDecoder {
}
}
} else if cc == 1 && c == 2 {
- denormalise_bands(x, f0, &self.old_band_e, start, eff_end, mm, self.downsample, silence);
- denormalise_bands(&x[n..], f1, &self.old_band_e[NB_EBANDS..], start, eff_end, mm, self.downsample, silence);
+ denormalise_bands(DenormaliseBandsInput {
+ x,
+ freq: f0,
+ band_log_e: &self.old_band_e,
+ start,
+ end: eff_end,
+ mm,
+ downsample: self.downsample,
+ silence,
+ });
+ denormalise_bands(DenormaliseBandsInput {
+ x: &x[n..],
+ freq: f1,
+ band_log_e: &self.old_band_e[NB_EBANDS..],
+ start,
+ end: eff_end,
+ mm,
+ downsample: self.downsample,
+ silence,
+ });
for i in 0..n {
f0[i] = 0.5 * (f0[i] + f1[i]);
}
@@ -413,7 +498,16 @@ impl CeltDecoder {
}
} else {
for ch in 0..cc {
- denormalise_bands(&x[ch * n..], f0, &self.old_band_e[ch * NB_EBANDS..], start, eff_end, mm, self.downsample, silence);
+ denormalise_bands(DenormaliseBandsInput {
+ x: &x[ch * n..],
+ freq: f0,
+ band_log_e: &self.old_band_e[ch * NB_EBANDS..],
+ start,
+ end: eff_end,
+ mm,
+ downsample: self.downsample,
+ silence,
+ });
let mem = &mut self.decode_mem[ch * ml..(ch + 1) * ml];
for b in 0..bcount {
m.mdct[shift].backward(&f0[b..], bcount, &mut mem[out_off + nb * b..], &m.window, OVERLAP, &mut self.imdct);
@@ -490,7 +584,16 @@ impl CeltDecoder {
}
let saved_sc = self.stream_channels;
self.stream_channels = cc;
- self.synthesis(&x, n, self.start, eff_end, cc, false, lm, false);
+ self.synthesis(SynthesisFrame {
+ bands: &x,
+ samples: n,
+ start_band: self.start,
+ end_band: eff_end,
+ coded_channels: cc,
+ transient: false,
+ lm,
+ silence: false,
+ });
self.stream_channels = saved_sc;
self.x = x;
} else {
@@ -565,7 +668,7 @@ fn tf_decode(start: usize, end: usize, is_transient: bool, tf_res: &mut [i32; NB
let mut budget = dec.storage() as i32 * 8;
let mut tell = dec.tell();
let mut logp: u32 = if is_transient { 2 } else { 4 };
- let tf_select_rsv = lm > 0 && tell + logp as i32 + 1 <= budget;
+ let tf_select_rsv = lm > 0 && tell + (logp as i32) < budget;
budget -= tf_select_rsv as i32;
let mut tf_changed = 0;
let mut curr = 0;
@@ -589,8 +692,30 @@ fn tf_decode(start: usize, end: usize, is_transient: bool, tf_res: &mut [i32; NB
}
/// Pitch post-filter (in place on `buf[off .. off + n]`, reading history before `off`).
-#[allow(clippy::too_many_arguments)]
-fn comb_filter(buf: &mut [f32], off: usize, t0: i32, t1: i32, n: usize, g0: f32, g1: f32, tapset0: usize, tapset1: usize, window: &[f32; OVERLAP]) {
+struct CombFilterParams<'a> {
+ offset: usize,
+ old_period: i32,
+ new_period: i32,
+ samples: usize,
+ old_gain: f32,
+ new_gain: f32,
+ old_tapset: usize,
+ new_tapset: usize,
+ window: &'a [f32; OVERLAP],
+}
+
+fn comb_filter(buf: &mut [f32], params: CombFilterParams<'_>) {
+ let CombFilterParams {
+ offset: off,
+ old_period: t0,
+ new_period: t1,
+ samples: n,
+ old_gain: g0,
+ new_gain: g1,
+ old_tapset: tapset0,
+ new_tapset: tapset1,
+ window,
+ } = params;
if g0 == 0.0 && g1 == 0.0 {
return;
}
diff --git a/crates/opus/src/celt/bands.rs b/crates/opus/src/celt/bands.rs
index fbc1ab8fa..0295e5f14 100644
--- a/crates/opus/src/celt/bands.rs
+++ b/crates/opus/src/celt/bands.rs
@@ -2,7 +2,7 @@
//! (RFC 6716 §4.3.4 – §4.3.6).
use super::rate::{Mode, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, get_pulses};
-use super::tables::*;
+use super::tables::{E_MEANS, EBANDS, NB_EBANDS, ORDERY, SHORT_MDCT};
use crate::range::{BITRES, RangeDecoder, ilog};
pub const SPREAD_NONE: usize = 0;
@@ -71,7 +71,7 @@ fn exp_rotation1(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) {
x[i + stride] = c * x2 + s * x1;
x[i] = c * x1 + ms * x2;
}
- if len >= 2 * stride + 1 {
+ if len > 2 * stride {
for i in (0..=len - 2 * stride - 1).rev() {
let x1 = x[i];
let x2 = x[i + stride];
@@ -269,8 +269,48 @@ struct Split {
qalloc: i32,
}
+#[derive(Clone, Copy)]
+struct ThetaBand {
+ bb: usize,
+ b0: usize,
+ lm: i32,
+ stereo: bool,
+}
+
+struct QuantPartitionInput<'a> {
+ samples: usize,
+ bits: i32,
+ blocks: usize,
+ lowband: Option<&'a [f32]>,
+ lm: i32,
+ gain: f32,
+ fill: u32,
+}
+
+struct QuantBandInput<'a> {
+ samples: usize,
+ bits: i32,
+ blocks: usize,
+ lowband: Option<&'a mut [f32]>,
+ lm: i32,
+ lowband_out: Option<&'a mut [f32]>,
+ gain: f32,
+ fill: u32,
+}
+
+struct QuantBandStereoInput<'a> {
+ samples: usize,
+ bits: i32,
+ blocks: usize,
+ lowband: Option<&'a mut [f32]>,
+ lm: i32,
+ lowband_out: Option<&'a mut [f32]>,
+ fill: u32,
+}
+
impl BandCtx<'_, '_, '_> {
- fn compute_theta(&mut self, n: i32, b: &mut i32, bb: usize, b0: usize, lm: i32, stereo: bool, fill: &mut u32) -> Split {
+ fn compute_theta(&mut self, n: i32, b: &mut i32, band: ThetaBand, fill: &mut u32) -> Split {
+ let ThetaBand { bb, b0, lm, stereo } = band;
let i = self.i;
let pulse_cap = self.m.log_n[i] + lm * (1 << BITRES);
let offset = (pulse_cap >> 1) - if stereo && n == 2 { QTHETA_OFFSET_TWOPHASE } else { QTHETA_OFFSET };
@@ -301,13 +341,13 @@ impl BandCtx<'_, '_, '_> {
if fm < (half * (half + 1)) >> 1 {
let it = (isqrt32(8 * fm + 1) - 1) >> 1;
fs = it + 1;
- fl = it * (it + 1) >> 1;
+ fl = (it * (it + 1)) >> 1;
itheta = it as i32;
} else {
let q = qn as u32;
let it = (2 * (q + 1) - isqrt32(8 * (ft - fm - 1) + 1)) >> 1;
fs = q + 1 - it;
- fl = ft - ((q + 1 - it) * (q + 2 - it) >> 1);
+ fl = ft - (((q + 1 - it) * (q + 2 - it)) >> 1);
itheta = it as i32;
}
self.dec.update(fl, fl + fs, ft);
@@ -362,8 +402,8 @@ impl BandCtx<'_, '_, '_> {
1
}
- #[allow(clippy::too_many_arguments)]
- fn quant_partition(&mut self, x: &mut [f32], n: usize, mut b: i32, mut bb: usize, lowband: Option<&[f32]>, mut lm: i32, gain: f32, mut fill: u32) -> u32 {
+ fn quant_partition(&mut self, x: &mut [f32], input: QuantPartitionInput<'_>) -> u32 {
+ let QuantPartitionInput { samples: n, bits: mut b, blocks: mut bb, lowband, mut lm, gain, mut fill } = input;
let b0 = bb;
let i = self.i;
let cache = self.m.cache(lm, i);
@@ -376,7 +416,7 @@ impl BandCtx<'_, '_, '_> {
fill = (fill & 1) | (fill << 1);
}
bb = (bb + 1) >> 1;
- let sp = self.compute_theta(n as i32, &mut b, bb, b0, lm, false, &mut fill);
+ let sp = self.compute_theta(n as i32, &mut b, ThetaBand { bb, b0, lm, stereo: false }, &mut fill);
let mid = sp.imid as f32 / 32768.0;
let side = sp.iside as f32 / 32768.0;
let mut delta = sp.delta;
@@ -394,19 +434,25 @@ impl BandCtx<'_, '_, '_> {
let mut rebalance = self.remaining_bits;
let mut cm;
if mbits >= sbits {
- cm = self.quant_partition(xa, n, mbits, bb, lowband, lm, gain * mid, fill);
+ cm = self.quant_partition(xa, QuantPartitionInput { samples: n, bits: mbits, blocks: bb, lowband, lm, gain: gain * mid, fill });
rebalance = mbits - (rebalance - self.remaining_bits);
if rebalance > 3 << BITRES && sp.itheta != 0 {
sbits += rebalance - (3 << BITRES);
}
- cm |= self.quant_partition(ya, n, sbits, bb, next_lowband2, lm, gain * side, fill >> bb) << (b0 >> 1);
+ cm |= self.quant_partition(
+ ya,
+ QuantPartitionInput { samples: n, bits: sbits, blocks: bb, lowband: next_lowband2, lm, gain: gain * side, fill: fill >> bb },
+ ) << (b0 >> 1);
} else {
- cm = self.quant_partition(ya, n, sbits, bb, next_lowband2, lm, gain * side, fill >> bb) << (b0 >> 1);
+ cm = self.quant_partition(
+ ya,
+ QuantPartitionInput { samples: n, bits: sbits, blocks: bb, lowband: next_lowband2, lm, gain: gain * side, fill: fill >> bb },
+ ) << (b0 >> 1);
rebalance = sbits - (rebalance - self.remaining_bits);
if rebalance > 3 << BITRES && sp.itheta != 16384 {
mbits += rebalance - (3 << BITRES);
}
- cm |= self.quant_partition(xa, n, mbits, bb, lowband, lm, gain * mid, fill);
+ cm |= self.quant_partition(xa, QuantPartitionInput { samples: n, bits: mbits, blocks: bb, lowband, lm, gain: gain * mid, fill });
}
return cm;
}
@@ -465,19 +511,8 @@ impl BandCtx<'_, '_, '_> {
}
}
- #[allow(clippy::too_many_arguments)]
- pub fn quant_band(
- &mut self,
- x: &mut [f32],
- n: usize,
- b: i32,
- mut bb: usize,
- mut lowband: Option<&mut [f32]>,
- lm: i32,
- lowband_out: Option<&mut [f32]>,
- gain: f32,
- mut fill: u32,
- ) -> u32 {
+ fn quant_band(&mut self, x: &mut [f32], input: QuantBandInput<'_>) -> u32 {
+ let QuantBandInput { samples: n, bits: b, blocks: mut bb, mut lowband, lm, lowband_out, gain, mut fill } = input;
let n0 = n;
let mut n_b = n;
let b0_orig = bb;
@@ -519,7 +554,7 @@ impl BandCtx<'_, '_, '_> {
{
deinterleave_hadamard(lb, n_b >> recombine, b0 << recombine, long_blocks, &mut tmp);
}
- let mut cm = self.quant_partition(x, n, b, bb, lowband.as_deref(), lm, gain, fill);
+ let mut cm = self.quant_partition(x, QuantPartitionInput { samples: n, bits: b, blocks: bb, lowband: lowband.as_deref(), lm, gain, fill });
if b0 > 1 {
interleave_hadamard(x, n_b >> recombine, b0 << recombine, long_blocks, &mut tmp);
}
@@ -547,24 +582,13 @@ impl BandCtx<'_, '_, '_> {
cm & ((1u32 << bb) - 1)
}
- #[allow(clippy::too_many_arguments)]
- pub fn quant_band_stereo(
- &mut self,
- x: &mut [f32],
- y: &mut [f32],
- n: usize,
- mut b: i32,
- bb: usize,
- lowband: Option<&mut [f32]>,
- lm: i32,
- lowband_out: Option<&mut [f32]>,
- mut fill: u32,
- ) -> u32 {
+ fn quant_band_stereo(&mut self, x: &mut [f32], y: &mut [f32], input: QuantBandStereoInput<'_>) -> u32 {
+ let QuantBandStereoInput { samples: n, bits: mut b, blocks: bb, lowband, lm, lowband_out, mut fill } = input;
let orig_fill = fill;
if n == 1 {
return self.quant_band_n1(x, Some(y), lowband_out);
}
- let sp = self.compute_theta(n as i32, &mut b, bb, bb, lm, true, &mut fill);
+ let sp = self.compute_theta(n as i32, &mut b, ThetaBand { bb, b0: bb, lm, stereo: true }, &mut fill);
let mid = sp.imid as f32 / 32768.0;
let side = sp.iside as f32 / 32768.0;
let mut cm;
@@ -583,11 +607,11 @@ impl BandCtx<'_, '_, '_> {
}
let sign = (1 - 2 * sign) as f32;
if c {
- cm = self.quant_band(y, n, mbits, bb, lowband, lm, lowband_out, 1.0, orig_fill);
+ cm = self.quant_band(y, QuantBandInput { samples: n, bits: mbits, blocks: bb, lowband, lm, lowband_out, gain: 1.0, fill: orig_fill });
x[0] = -sign * y[1];
x[1] = sign * y[0];
} else {
- cm = self.quant_band(x, n, mbits, bb, lowband, lm, lowband_out, 1.0, orig_fill);
+ cm = self.quant_band(x, QuantBandInput { samples: n, bits: mbits, blocks: bb, lowband, lm, lowband_out, gain: 1.0, fill: orig_fill });
y[0] = -sign * x[1];
y[1] = sign * x[0];
}
@@ -607,19 +631,21 @@ impl BandCtx<'_, '_, '_> {
self.remaining_bits -= sp.qalloc;
let mut rebalance = self.remaining_bits;
if mbits >= sbits {
- cm = self.quant_band(x, n, mbits, bb, lowband, lm, lowband_out, 1.0, fill);
+ cm = self.quant_band(x, QuantBandInput { samples: n, bits: mbits, blocks: bb, lowband, lm, lowband_out, gain: 1.0, fill });
rebalance = mbits - (rebalance - self.remaining_bits);
if rebalance > 3 << BITRES && sp.itheta != 0 {
sbits += rebalance - (3 << BITRES);
}
- cm |= self.quant_band(y, n, sbits, bb, None, lm, None, side, fill >> bb);
+ cm |= self
+ .quant_band(y, QuantBandInput { samples: n, bits: sbits, blocks: bb, lowband: None, lm, lowband_out: None, gain: side, fill: fill >> bb });
} else {
- cm = self.quant_band(y, n, sbits, bb, None, lm, None, side, fill >> bb);
+ cm = self
+ .quant_band(y, QuantBandInput { samples: n, bits: sbits, blocks: bb, lowband: None, lm, lowband_out: None, gain: side, fill: fill >> bb });
rebalance = sbits - (rebalance - self.remaining_bits);
if rebalance > 3 << BITRES && sp.itheta != 16384 {
mbits += rebalance - (3 << BITRES);
}
- cm |= self.quant_band(x, n, mbits, bb, lowband, lm, lowband_out, 1.0, fill);
+ cm |= self.quant_band(x, QuantBandInput { samples: n, bits: mbits, blocks: bb, lowband, lm, lowband_out, gain: 1.0, fill });
}
}
if n != 2 {
@@ -660,28 +686,50 @@ fn stereo_merge(x: &mut [f32], y: &mut [f32], mid: f32) {
}
/// Decodes all band shapes (`quant_all_bands`, decoder side).
-#[allow(clippy::too_many_arguments)]
-pub fn quant_all_bands(
- m: &Mode,
- start: usize,
- end: usize,
- x_buf: &mut [f32],
- y_buf: Option<&mut [f32]>,
- collapse_masks: &mut [u32],
- pulses: &[i32; NB_EBANDS],
- short_blocks: bool,
- spread: usize,
- mut dual_stereo: bool,
- intensity: usize,
- tf_res: &[i32; NB_EBANDS],
- total_bits: i32,
- mut balance: i32,
- dec: &mut RangeDecoder,
- lm: usize,
- coded_bands: usize,
- seed: &mut u32,
- disable_inv: bool,
-) {
+pub struct QuantAllBandsInput<'a, 'd> {
+ pub mode: &'a Mode,
+ pub start: usize,
+ pub end: usize,
+ pub x_buf: &'a mut [f32],
+ pub y_buf: Option<&'a mut [f32]>,
+ pub collapse_masks: &'a mut [u32],
+ pub pulses: &'a [i32; NB_EBANDS],
+ pub short_blocks: bool,
+ pub spread: usize,
+ pub dual_stereo: bool,
+ pub intensity: usize,
+ pub tf_res: &'a [i32; NB_EBANDS],
+ pub total_bits: i32,
+ pub balance: i32,
+ pub decoder: &'a mut RangeDecoder<'d>,
+ pub lm: usize,
+ pub coded_bands: usize,
+ pub seed: &'a mut u32,
+ pub disable_inv: bool,
+}
+
+pub fn quant_all_bands(input: QuantAllBandsInput<'_, '_>) {
+ let QuantAllBandsInput {
+ mode: m,
+ start,
+ end,
+ x_buf,
+ y_buf,
+ collapse_masks,
+ pulses,
+ short_blocks,
+ spread,
+ mut dual_stereo,
+ intensity,
+ tf_res,
+ total_bits,
+ mut balance,
+ decoder: dec,
+ lm,
+ coded_bands,
+ seed,
+ disable_inv,
+ } = input;
let mm = 1usize << lm;
let bb = if short_blocks { mm } else { 1 };
let norm_offset = mm * EBANDS[start] as usize;
@@ -790,13 +838,15 @@ pub fn quant_all_bands(
&mut scratch[..n]
});
let lo = if last { None } else { Some(&mut norm[out_off..out_off + n]) };
- x_cm = ctx.quant_band(x, n, b / 2, bb, lb, lm as i32, lo, 1.0, x_cm);
+ x_cm =
+ ctx.quant_band(x, QuantBandInput { samples: n, bits: b / 2, blocks: bb, lowband: lb, lm: lm as i32, lowband_out: lo, gain: 1.0, fill: x_cm });
let lb2 = effective_lowband.map(|e| {
scratch2[..n].copy_from_slice(&norm2[e..e + n]);
&mut scratch2[..n]
});
let lo2 = if last { None } else { Some(&mut norm2[out_off..out_off + n]) };
- y_cm = ctx.quant_band(y, n, b / 2, bb, lb2, lm as i32, lo2, 1.0, y_cm);
+ y_cm =
+ ctx.quant_band(y, QuantBandInput { samples: n, bits: b / 2, blocks: bb, lowband: lb2, lm: lm as i32, lowband_out: lo2, gain: 1.0, fill: y_cm });
} else {
let lb = effective_lowband.map(|e| {
scratch[..n].copy_from_slice(&norm[e..e + n]);
@@ -805,9 +855,16 @@ pub fn quant_all_bands(
let lo = if last { None } else { Some(&mut norm[out_off..out_off + n]) };
if let Some(yb) = y_buf.as_deref_mut() {
let y = &mut yb[xo..xo + n];
- x_cm = ctx.quant_band_stereo(x, y, n, b, bb, lb, lm as i32, lo, x_cm | y_cm);
+ x_cm = ctx.quant_band_stereo(
+ x,
+ y,
+ QuantBandStereoInput { samples: n, bits: b, blocks: bb, lowband: lb, lm: lm as i32, lowband_out: lo, fill: x_cm | y_cm },
+ );
} else {
- x_cm = ctx.quant_band(x, n, b, bb, lb, lm as i32, lo, 1.0, x_cm | y_cm);
+ x_cm = ctx.quant_band(
+ x,
+ QuantBandInput { samples: n, bits: b, blocks: bb, lowband: lb, lm: lm as i32, lowband_out: lo, gain: 1.0, fill: x_cm | y_cm },
+ );
}
y_cm = x_cm;
}
@@ -821,21 +878,23 @@ pub fn quant_all_bands(
}
/// Anti-collapse noise injection (RFC 6716 §4.3.5).
-#[allow(clippy::too_many_arguments)]
-pub fn anti_collapse(
- x_buf: &mut [f32],
- collapse_masks: &[u32],
- lm: usize,
- c: usize,
- size: usize,
- start: usize,
- end: usize,
- log_e: &[f32],
- prev1: &[f32],
- prev2: &[f32],
- pulses: &[i32; NB_EBANDS],
- mut seed: u32,
-) {
+pub struct AntiCollapseInput<'a> {
+ pub x_buf: &'a mut [f32],
+ pub collapse_masks: &'a [u32],
+ pub lm: usize,
+ pub channels: usize,
+ pub size: usize,
+ pub start: usize,
+ pub end: usize,
+ pub log_e: &'a [f32],
+ pub prev1: &'a [f32],
+ pub prev2: &'a [f32],
+ pub pulses: &'a [i32; NB_EBANDS],
+ pub seed: u32,
+}
+
+pub fn anti_collapse(input: AntiCollapseInput<'_>) {
+ let AntiCollapseInput { x_buf, collapse_masks, lm, channels: c, size, start, end, log_e, prev1, prev2, pulses, mut seed } = input;
for i in start..end {
let n0 = (EBANDS[i + 1] - EBANDS[i]) as usize;
let depth = ((1 + pulses[i]) as u32 / n0 as u32) >> lm;
@@ -875,8 +934,19 @@ pub fn anti_collapse(
}
/// Multiplies the normalised shapes by the band energies (`denormalise_bands`).
-#[allow(clippy::too_many_arguments)]
-pub fn denormalise_bands(x: &[f32], freq: &mut [f32], band_log_e: &[f32], mut start: usize, mut end: usize, mm: usize, downsample: usize, silence: bool) {
+pub struct DenormaliseBandsInput<'a> {
+ pub x: &'a [f32],
+ pub freq: &'a mut [f32],
+ pub band_log_e: &'a [f32],
+ pub start: usize,
+ pub end: usize,
+ pub mm: usize,
+ pub downsample: usize,
+ pub silence: bool,
+}
+
+pub fn denormalise_bands(input: DenormaliseBandsInput<'_>) {
+ let DenormaliseBandsInput { x, freq, band_log_e, mut start, mut end, mm, downsample, silence } = input;
let n = mm * SHORT_MDCT;
let mut bound = mm * EBANDS[end] as usize;
if downsample != 1 {
diff --git a/crates/opus/src/celt/energy.rs b/crates/opus/src/celt/energy.rs
index 9260a5bff..16431033f 100644
--- a/crates/opus/src/celt/energy.rs
+++ b/crates/opus/src/celt/energy.rs
@@ -2,7 +2,7 @@
//! (RFC 6716 §4.3.2).
use super::rate::MAX_FINE_BITS;
-use super::tables::*;
+use super::tables::{BETA_COEF, BETA_INTRA, E_PROB_MODEL, NB_EBANDS, PRED_COEF, SMALL_ENERGY_ICDF};
use crate::range::RangeDecoder;
const LAPLACE_MINP: u32 = 1;
@@ -44,7 +44,6 @@ pub fn laplace_decode(dec: &mut RangeDecoder, mut fs: u32, decay: u32) -> i32 {
}
/// `unquant_coarse_energy`.
-#[allow(clippy::too_many_arguments)]
pub fn unquant_coarse_energy(start: usize, end: usize, old_e: &mut [f32], intra: bool, dec: &mut RangeDecoder, c: usize, lm: usize) {
let prob = &E_PROB_MODEL[lm][intra as usize];
let (coef, beta) = if intra { (0.0, BETA_INTRA) } else { (PRED_COEF[lm], BETA_COEF[lm]) };
@@ -88,17 +87,19 @@ pub fn unquant_fine_energy(start: usize, end: usize, old_e: &mut [f32], fine_qua
}
}
-#[allow(clippy::too_many_arguments)]
-pub fn unquant_energy_finalise(
- start: usize,
- end: usize,
- old_e: &mut [f32],
- fine_quant: &[i32; NB_EBANDS],
- fine_priority: &[i32; NB_EBANDS],
- mut bits_left: i32,
- dec: &mut RangeDecoder,
- c: usize,
-) {
+pub struct EnergyFinalise<'a, 'd> {
+ pub start: usize,
+ pub end: usize,
+ pub old_e: &'a mut [f32],
+ pub fine_quant: &'a [i32; NB_EBANDS],
+ pub fine_priority: &'a [i32; NB_EBANDS],
+ pub bits_left: i32,
+ pub decoder: &'a mut RangeDecoder<'d>,
+ pub channels: usize,
+}
+
+pub fn unquant_energy_finalise(input: EnergyFinalise<'_, '_>) {
+ let EnergyFinalise { start, end, old_e, fine_quant, fine_priority, mut bits_left, decoder: dec, channels: c } = input;
for prio in 0..2 {
let mut i = start;
while i < end && bits_left >= c as i32 {
diff --git a/crates/opus/src/celt/rate.rs b/crates/opus/src/celt/rate.rs
index bd398d617..2986b2415 100644
--- a/crates/opus/src/celt/rate.rs
+++ b/crates/opus/src/celt/rate.rs
@@ -1,6 +1,6 @@
//! Pulse cache and bit allocation (RFC 6716 §4.3.3, §4.3.4.1).
-use super::tables::*;
+use super::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS, OVERLAP};
use crate::range::{BITRES, RangeDecoder};
const MAX_PSEUDO: i32 = 40;
@@ -142,7 +142,7 @@ impl Mode {
let mut cap = [0i32; NB_EBANDS];
for (i, cp) in cap.iter_mut().enumerate() {
let n = (EBANDS[i + 1] - EBANDS[i]) << lm;
- *cp = (self.caps[NB_EBANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n >> 2;
+ *cp = ((self.caps[NB_EBANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n) >> 2;
}
cap
}
@@ -217,7 +217,7 @@ fn compute_caps(m: &Mode) -> Vec<u8> {
for j in 0..nb {
let mut n0 = EBANDS[j + 1] - EBANDS[j];
let max_bits = if n0 << i == 1 {
- c * (1 + MAX_FINE_BITS) << BITRES
+ (c * (1 + MAX_FINE_BITS)) << BITRES
} else {
let mut lm0 = 0;
if n0 > 2 {
@@ -257,7 +257,7 @@ fn compute_caps(m: &Mode) -> Vec<u8> {
let num = mb + ndof * offset;
let den = (ndof - 1) << BITRES;
let qb = ((num + (den >> 1)) / den).min(MAX_FINE_BITS);
- mb += c * qb << BITRES;
+ mb += (c * qb) << BITRES;
mb
};
let w = c * ((EBANDS[j + 1] - EBANDS[j]) << i);
@@ -281,19 +281,21 @@ pub struct Allocation {
}
/// `clt_compute_allocation` (decoder side).
-#[allow(clippy::too_many_arguments)]
-pub fn compute_allocation(
- m: &Mode,
- start: usize,
- end: usize,
- offsets: &[i32; NB_EBANDS],
- cap: &[i32; NB_EBANDS],
- alloc_trim: i32,
- total: i32,
- c: usize,
- lm: usize,
- dec: &mut RangeDecoder,
-) -> Allocation {
+pub struct AllocationInput<'a, 'd> {
+ pub mode: &'a Mode,
+ pub start: usize,
+ pub end: usize,
+ pub offsets: &'a [i32; NB_EBANDS],
+ pub cap: &'a [i32; NB_EBANDS],
+ pub trim: i32,
+ pub total: i32,
+ pub channels: usize,
+ pub lm: usize,
+ pub decoder: &'a mut RangeDecoder<'d>,
+}
+
+pub fn compute_allocation(input: AllocationInput<'_, '_>) -> Allocation {
+ let AllocationInput { mode: m, start, end, offsets, cap, trim: alloc_trim, total, channels: c, lm, decoder: dec } = input;
let ci = c as i32;
let lmi = lm as i32;
let mut total = total.max(0);
@@ -318,8 +320,8 @@ pub fn compute_allocation(
let mut trim_offset = [0i32; NB_EBANDS];
for j in start..end {
let w = EBANDS[j + 1] - EBANDS[j];
- thresh[j] = (ci << BITRES).max((3 * w << lmi << BITRES) >> 4);
- trim_offset[j] = ci * w * (alloc_trim - 5 - lmi) * (end as i32 - j as i32 - 1) * (1 << (lmi + BITRES as i32)) >> 6;
+ thresh[j] = (ci << BITRES).max(((3 * w) << lmi << BITRES) >> 4);
+ trim_offset[j] = (ci * w * (alloc_trim - 5 - lmi) * (end as i32 - j as i32 - 1) * (1 << (lmi + BITRES as i32))) >> 6;
if w << lmi == 1 {
trim_offset[j] -= ci << BITRES;
}
@@ -333,7 +335,7 @@ pub fn compute_allocation(
let mid = (lo + hi) >> 1;
for j in (start..end).rev() {
let n = EBANDS[j + 1] - EBANDS[j];
- let mut bitsj = ci * n * (ALLOC[mid as usize][j] as i32) << lmi >> 2;
+ let mut bitsj = (ci * n * (ALLOC[mid as usize][j] as i32)) << lmi >> 2;
if bitsj > 0 {
bitsj = (bitsj + trim_offset[j]).max(0);
}
@@ -358,8 +360,8 @@ pub fn compute_allocation(
lo -= 1;
for j in start..end {
let n = EBANDS[j + 1] - EBANDS[j];
- let mut bits1j = ci * n * (ALLOC[lo as usize][j] as i32) << lmi >> 2;
- let mut bits2j = if hi >= nb_alloc { cap[j] } else { ci * n * (ALLOC[hi as usize][j] as i32) << lmi >> 2 };
+ let mut bits1j = (ci * n * (ALLOC[lo as usize][j] as i32)) << lmi >> 2;
+ let mut bits2j = if hi >= nb_alloc { cap[j] } else { (ci * n * (ALLOC[hi as usize][j] as i32)) << lmi >> 2 };
if bits1j > 0 {
bits1j = (bits1j + trim_offset[j]).max(0);
}
@@ -377,27 +379,61 @@ pub fn compute_allocation(
bits1[j] = bits1j;
bits2[j] = bits2j;
}
- interp_bits2pulses(m, start, end, skip_start, &bits1, &bits2, &thresh, cap, total, skip_rsv, intensity_rsv, dual_stereo_rsv, c, lm, dec)
+ interp_bits2pulses(InterpPulsesInput {
+ mode: m,
+ start,
+ end,
+ skip_start,
+ bits1: &bits1,
+ bits2: &bits2,
+ threshold: &thresh,
+ cap,
+ total,
+ skip_reservation: skip_rsv,
+ intensity_reservation: intensity_rsv,
+ stereo_reservation: dual_stereo_rsv,
+ channels: c,
+ lm,
+ decoder: dec,
+ })
}
-#[allow(clippy::too_many_arguments)]
-fn interp_bits2pulses(
- m: &Mode,
+struct InterpPulsesInput<'a, 'd> {
+ mode: &'a Mode,
start: usize,
end: usize,
skip_start: usize,
- bits1: &[i32; NB_EBANDS],
- bits2: &[i32; NB_EBANDS],
- thresh: &[i32; NB_EBANDS],
- cap: &[i32; NB_EBANDS],
- mut total: i32,
- skip_rsv: i32,
- mut intensity_rsv: i32,
- mut dual_stereo_rsv: i32,
- c: usize,
+ bits1: &'a [i32; NB_EBANDS],
+ bits2: &'a [i32; NB_EBANDS],
+ threshold: &'a [i32; NB_EBANDS],
+ cap: &'a [i32; NB_EBANDS],
+ total: i32,
+ skip_reservation: i32,
+ intensity_reservation: i32,
+ stereo_reservation: i32,
+ channels: usize,
lm: usize,
- dec: &mut RangeDecoder,
-) -> Allocation {
+ decoder: &'a mut RangeDecoder<'d>,
+}
+
+fn interp_bits2pulses(input: InterpPulsesInput<'_, '_>) -> Allocation {
+ let InterpPulsesInput {
+ mode: m,
+ start,
+ end,
+ skip_start,
+ bits1,
+ bits2,
+ threshold: thresh,
+ cap,
+ mut total,
+ skip_reservation: skip_rsv,
+ intensity_reservation: mut intensity_rsv,
+ stereo_reservation: mut dual_stereo_rsv,
+ channels: c,
+ lm,
+ decoder: dec,
+ } = input;
let ci = c as i32;
let alloc_floor = ci << BITRES;
let stereo = (c > 1) as i32;
@@ -409,7 +445,7 @@ fn interp_bits2pulses(
let mut psum = 0;
let mut done = false;
for j in (start..end).rev() {
- let tmp = bits1[j] + (mid * bits2[j] >> ALLOC_STEPS);
+ let tmp = bits1[j] + ((mid * bits2[j]) >> ALLOC_STEPS);
if tmp >= thresh[j] || done {
done = true;
psum += tmp.min(cap[j]);
@@ -427,7 +463,7 @@ fn interp_bits2pulses(
let mut psum = 0;
let mut done = false;
for j in (start..end).rev() {
- let mut tmp = bits1[j] + (lo * bits2[j] >> ALLOC_STEPS);
+ let mut tmp = bits1[j] + ((lo * bits2[j]) >> ALLOC_STEPS);
if tmp < thresh[j] && !done {
tmp = if tmp >= alloc_floor { alloc_floor } else { 0 };
} else {
@@ -507,9 +543,9 @@ fn interp_bits2pulses(
if n == 2 {
offset += (den << BITRES) >> 2;
}
- if bits[j] + offset < den * 2 << BITRES {
+ if bits[j] + offset < (den * 2) << BITRES {
offset += nclogn >> 2;
- } else if bits[j] + offset < den * 3 << BITRES {
+ } else if bits[j] + offset < (den * 3) << BITRES {
offset += nclogn >> 3;
}
let mut eb = (bits[j] + offset + (den << (BITRES - 1))).max(0);
@@ -520,7 +556,7 @@ fn interp_bits2pulses(
eb = eb.min(MAX_FINE_BITS);
ebits[j] = eb;
fine_priority[j] = (eb * (den << BITRES) >= bits[j] + offset) as i32;
- bits[j] -= ci * eb << BITRES;
+ bits[j] -= (ci * eb) << BITRES;
} else {
excess = (bit - (ci << BITRES)).max(0);
bits[j] = bit - excess;
@@ -530,7 +566,7 @@ fn interp_bits2pulses(
if excess > 0 {
let extra_fine = (excess >> (stereo + BITRES as i32)).min(MAX_FINE_BITS - ebits[j]);
ebits[j] += extra_fine;
- let extra_bits = extra_fine * ci << BITRES;
+ let extra_bits = (extra_fine * ci) << BITRES;
fine_priority[j] = (extra_bits >= excess - balance) as i32;
excess -= extra_bits;
}
diff --git a/crates/opus/src/decoder.rs b/crates/opus/src/decoder.rs
index 573d5366f..7c4dc9998 100644
--- a/crates/opus/src/decoder.rs
+++ b/crates/opus/src/decoder.rs
@@ -29,6 +29,34 @@ pub struct StreamDecoder {
gain_q8: i16,
}
+struct SilkFrame {
+ mode: Mode,
+ bandwidth: Option<Bandwidth>,
+ has_packet: bool,
+ fec: bool,
+ frame_size: usize,
+ audio_size: usize,
+ rate: usize,
+ channels: usize,
+}
+
+struct Redundancy {
+ present: bool,
+ celt_to_silk: bool,
+ bytes: usize,
+ packet_len: usize,
+}
+
+fn apply_output_gain(pcm: &mut [f32], samples: usize, channels: usize, gain_q8: i16) {
+ if gain_q8 == 0 {
+ return;
+ }
+ let gain = (6.488_141e-4f32 * gain_q8 as f32).exp2();
+ for sample in pcm.iter_mut().take(samples * channels) {
+ *sample *= gain;
+ }
+}
+
impl StreamDecoder {
/// Creates a decoder producing `channels` (1 or 2) at `rate` (8/12/16/24/48 kHz).
pub fn new(rate: u32, channels: usize) -> Result<StreamDecoder> {
@@ -168,6 +196,87 @@ impl StreamDecoder {
Ok(nb)
}
+ fn decode_silk_frame(&mut self, frame: SilkFrame, dec: &mut Option<&mut RangeDecoder>) -> Result<Vec<f32>> {
+ let SilkFrame { mode, bandwidth, has_packet, fec, frame_size, audio_size, rate, channels } = frame;
+ let mut pcm = Vec::new();
+ if mode == Mode::CeltOnly {
+ return Ok(pcm);
+ }
+ pcm.resize(frame_size.max(rate / 100) * channels, 0.0);
+ if self.prev_mode == Some(Mode::CeltOnly) {
+ self.silk.reset();
+ }
+ let internal_rate = if mode == Mode::SilkOnly {
+ match bandwidth {
+ Some(Bandwidth::Narrowband) => 8000,
+ Some(Bandwidth::Mediumband) => 12000,
+ _ => 16000,
+ }
+ } else {
+ 16000
+ };
+ if has_packet {
+ self.silk.set_stream(self.stream_channels, internal_rate);
+ }
+ let lost = if !has_packet {
+ LostFlag::Lost
+ } else if fec {
+ LostFlag::Lbrr
+ } else {
+ LostFlag::Normal
+ };
+ let payload_ms = (1000 * audio_size / rate).max(10);
+ let mut decoded = 0;
+ while decoded < frame_size {
+ let first = decoded == 0;
+ let count = match self.silk.decode(dec.as_deref_mut(), lost, first, payload_ms, &mut pcm[decoded * channels..]) {
+ Ok(count) => count,
+ Err(_error) if lost != LostFlag::Normal => {
+ let remaining = frame_size - decoded;
+ pcm[decoded * channels..(decoded + remaining) * channels].fill(0.0);
+ remaining
+ }
+ Err(error) => return Err(error),
+ };
+ if count == 0 {
+ break;
+ }
+ decoded += count;
+ }
+ Ok(pcm)
+ }
+
+ fn read_redundancy(&self, mode: Mode, fec: bool, packet_len: usize, dec: &mut Option<&mut RangeDecoder>) -> Redundancy {
+ let mut state = Redundancy { present: false, celt_to_silk: false, bytes: 0, packet_len };
+ let Some(decoder) = dec.as_deref_mut() else { return state };
+ let hybrid = self.mode == Some(Mode::Hybrid);
+ if fec || mode == Mode::CeltOnly || decoder.tell() + 17 + 20 * i32::from(hybrid) > 8 * state.packet_len as i32 {
+ return state;
+ }
+ state.present = if mode == Mode::Hybrid { decoder.bit_logp(12) } else { true };
+ if !state.present {
+ return state;
+ }
+ state.celt_to_silk = decoder.bit_logp(1);
+ state.bytes = if mode == Mode::Hybrid { decoder.uint(256) as usize + 2 } else { state.packet_len - ((decoder.tell() as usize + 7) >> 3) };
+ if state.bytes > state.packet_len || (state.packet_len - state.bytes) * 8 < decoder.tell() as usize {
+ state.packet_len = 0;
+ state.bytes = 0;
+ state.present = false;
+ } else {
+ state.packet_len -= state.bytes;
+ }
+ decoder.shrink_storage(state.bytes);
+ state
+ }
+
+ fn is_mode_transition(&self, has_packet: bool, mode: Mode) -> bool {
+ has_packet
+ && self.prev_mode.is_some()
+ && ((mode == Mode::CeltOnly && self.prev_mode != Some(Mode::CeltOnly) && !self.prev_redundancy)
+ || (mode != Mode::CeltOnly && self.prev_mode == Some(Mode::CeltOnly)))
+ }
+
/// `opus_decode_frame`: decodes one frame (or conceals when `data` is `None`/≤1 byte).
fn decode_frame(&mut self, data: Option<&[u8]>, pcm: &mut [f32], frame_size: usize, fec: bool) -> Result<usize> {
let ch = self.channels;
@@ -226,14 +335,7 @@ impl StreamDecoder {
}
None => None,
};
- let mut transition = false;
- if data.is_some()
- && self.prev_mode.is_some()
- && ((mode == Mode::CeltOnly && self.prev_mode != Some(Mode::CeltOnly) && !self.prev_redundancy)
- || (mode != Mode::CeltOnly && self.prev_mode == Some(Mode::CeltOnly)))
- {
- transition = true;
- }
+ let mut transition = self.is_mode_transition(data.is_some(), mode);
let mut pcm_transition = Vec::new();
if transition && mode == Mode::CeltOnly {
pcm_transition.resize(f5 * ch, 0.0);
@@ -246,78 +348,13 @@ impl StreamDecoder {
frame_size = audiosize;
// SILK.
- let mut pcm_silk: Vec<f32> = Vec::new();
- if mode != Mode::CeltOnly {
- pcm_silk.resize(frame_size.max(f10) * ch, 0.0);
- if self.prev_mode == Some(Mode::CeltOnly) {
- self.silk.reset();
- }
- let payload_ms = (1000 * audiosize / fs).max(10);
- let internal_rate = if mode == Mode::SilkOnly {
- match bandwidth {
- Some(Bandwidth::Narrowband) => 8000,
- Some(Bandwidth::Mediumband) => 12000,
- _ => 16000,
- }
- } else {
- 16000
- };
- if data.is_some() {
- self.silk.set_stream(self.stream_channels, internal_rate);
- }
- let lost = if data.is_none() {
- LostFlag::Lost
- } else if fec {
- LostFlag::Lbrr
- } else {
- LostFlag::Normal
- };
- let mut decoded = 0;
- while decoded < frame_size {
- let first = decoded == 0;
- let n = match self.silk.decode(dec.as_deref_mut(), lost, first, payload_ms, &mut pcm_silk[decoded * ch..]) {
- Ok(n) => n,
- Err(e) => {
- if lost != LostFlag::Normal {
- let n = frame_size - decoded;
- pcm_silk[decoded * ch..(decoded + n) * ch].fill(0.0);
- n
- } else {
- return Err(e);
- }
- }
- };
- if n == 0 {
- break;
- }
- decoded += n;
- }
- }
+ let pcm_silk = self.decode_silk_frame(
+ SilkFrame { mode, bandwidth, has_packet: data.is_some(), fec, frame_size, audio_size: audiosize, rate: fs, channels: ch },
+ &mut dec,
+ )?;
+ let Redundancy { present: redundancy, celt_to_silk, bytes: redundancy_bytes, packet_len: len } = self.read_redundancy(mode, fec, data_len, &mut dec);
let mut start_band = 0;
- let mut redundancy = false;
- let mut celt_to_silk = false;
- let mut redundancy_bytes = 0usize;
- let mut len = data_len;
- if !fec
- && mode != Mode::CeltOnly
- && let Some(d) = dec.as_deref_mut()
- && d.tell() + 17 + 20 * (self.mode == Some(Mode::Hybrid)) as i32 <= 8 * len as i32
- {
- redundancy = if mode == Mode::Hybrid { d.bit_logp(12) } else { true };
- if redundancy {
- celt_to_silk = d.bit_logp(1);
- redundancy_bytes = if mode == Mode::Hybrid { d.uint(256) as usize + 2 } else { len - ((d.tell() as usize + 7) >> 3) };
- if redundancy_bytes > len || (len - redundancy_bytes) * 8 < d.tell() as usize {
- len = 0;
- redundancy_bytes = 0;
- redundancy = false;
- } else {
- len -= redundancy_bytes;
- }
- d.shrink_storage(redundancy_bytes);
- }
- }
if mode != Mode::CeltOnly {
start_band = 17;
}
@@ -389,12 +426,7 @@ impl StreamDecoder {
smooth_fade(&pcm_transition, &cur, pcm, f2_5, ch, window, self.rate);
}
}
- if self.gain_q8 != 0 {
- let g = (6.488_141e-4f32 * self.gain_q8 as f32).exp2();
- for v in pcm[..frame_size * ch].iter_mut() {
- *v *= g;
- }
- }
+ apply_output_gain(pcm, frame_size, ch, self.gain_q8);
self.range_final = match dec.as_deref() {
Some(d) if data_len > 1 => d.rng() ^ redundant_rng,
_ => 0,
diff --git a/crates/opus/src/lib.rs b/crates/opus/src/lib.rs
index ce28e4819..d7842eb41 100644
--- a/crates/opus/src/lib.rs
+++ b/crates/opus/src/lib.rs
@@ -3,9 +3,6 @@
//! Layer L0: no dependencies beyond `std`; no `unsafe`; builds for `wasm32-unknown-unknown`.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
-// The fixed-point parts mirror the normative integer arithmetic; keep C-like shift expressions.
-#![allow(clippy::precedence, clippy::int_plus_one)]
-
pub(crate) mod celt;
mod decoder;
mod header;
diff --git a/crates/opus/src/silk.rs b/crates/opus/src/silk.rs
index b6c307350..14970f20d 100644
--- a/crates/opus/src/silk.rs
+++ b/crates/opus/src/silk.rs
@@ -9,9 +9,14 @@ mod resampler;
#[allow(dead_code)]
pub(crate) mod tables;
-use lpc::*;
+use lpc::{MAX_LPC_ORDER, bwexpander, div32_varq, inverse32_varq, nlsf_decode, nlsf2a, rshift_round, sat16, smlawb, smulwb, smulww};
use resampler::Resampler;
-use tables::*;
+use tables::{
+ CB_NB_10, CB_NB_20, CB_WB_10, CB_WB_20, DELTA_GAIN, EXC_LSB, EXC_SIGN, GAIN_MSB, LBRR_FLAGS, LTP_FILTER, LTP_PERIODICITY, LTP_SCALE, LTP_TAPS_0,
+ LTP_TAPS_1, LTP_TAPS_2, MID_ONLY, NLSF_EXT, NLSF_INTERP, NLSF_SEL_NBMB, NLSF_SEL_WB, NLSF_STAGE1, NLSF_STAGE2, PITCH_CONTOUR, PITCH_DELTA, PITCH_HIGH,
+ PITCH_LOW, PULSE_COUNT, RATE_LEVEL, SHELL_2, SHELL_4, SHELL_8, SHELL_16, STEREO_PRED_JOINT, STEREO_WEIGHTS_Q13, TYPE_ACTIVE, TYPE_INACTIVE, UNIFORM3,
+ UNIFORM4, UNIFORM5, UNIFORM8,
+};
use crate::range::RangeDecoder;
use crate::{Error, Result};
@@ -687,12 +692,11 @@ impl SilkDecoder {
self.internal_rate = internal_rate;
}
- /// Decodes one SILK frame (10 or 20 ms) into interleaved `out` at the API rate.
- pub fn decode(&mut self, mut dec: Option<&mut RangeDecoder>, lost: LostFlag, new_packet: bool, payload_ms: usize, out: &mut [f32]) -> Result<usize> {
+ fn prepare_frame(&mut self, new_packet: bool, payload_ms: usize) -> Result<bool> {
let nci = self.channels_internal;
if new_packet {
- for c in self.ch.iter_mut() {
- c.n_frames_decoded = 0;
+ for channel in &mut self.ch {
+ channel.n_frames_decoded = 0;
}
}
if nci > self.channels_internal_prev && self.channels_internal_prev != 0 {
@@ -700,18 +704,18 @@ impl SilkDecoder {
}
let stereo_to_mono = nci == 1 && self.channels_internal_prev == 2 && self.internal_rate == 1000 * self.ch[0].fs_khz as u32;
if self.ch[0].n_frames_decoded == 0 {
- for c in self.ch.iter_mut().take(nci) {
- let (nfpp, nb) = match payload_ms {
- 10 => (1, 2),
- 20 => (1, 4),
- 40 => (2, 4),
- 60 => (3, 4),
- _ => return Err(Error::InvalidPacket("bad SILK frame size")),
- };
- c.n_frames_per_packet = nfpp;
- c.nb_subfr = nb;
- let fs_khz = ((self.internal_rate >> 10) + 1) as usize;
- c.set_fs(fs_khz, self.api_rate);
+ let (frames, subframes) = match payload_ms {
+ 10 => (1, 2),
+ 20 => (1, 4),
+ 40 => (2, 4),
+ 60 => (3, 4),
+ _ => return Err(Error::InvalidPacket("bad SILK frame size")),
+ };
+ let fs_khz = ((self.internal_rate >> 10) + 1) as usize;
+ for channel in self.ch.iter_mut().take(nci) {
+ channel.n_frames_per_packet = frames;
+ channel.nb_subfr = subframes;
+ channel.set_fs(fs_khz, self.api_rate);
}
}
if self.api_channels == 2 && nci == 2 && self.channels_internal_prev == 1 {
@@ -720,49 +724,66 @@ impl SilkDecoder {
self.ch[1].resampler = self.ch[0].resampler.clone();
}
self.channels_internal_prev = nci;
+ Ok(stereo_to_mono)
+ }
- if lost != LostFlag::Lost && self.ch[0].n_frames_decoded == 0 {
- let d = dec.as_deref_mut().ok_or(Error::InvalidPacket("missing SILK data"))?;
- for c in self.ch.iter_mut().take(nci) {
- for i in 0..c.n_frames_per_packet {
- c.vad_flags[i] = d.bit_logp(1);
- }
- c.lbrr_flag = d.bit_logp(1);
+ fn decode_packet_header(&mut self, dec: &mut Option<&mut RangeDecoder>, lost: LostFlag) -> Result<()> {
+ let nci = self.channels_internal;
+ if lost == LostFlag::Lost || self.ch[0].n_frames_decoded != 0 {
+ return Ok(());
+ }
+ let decoder = dec.as_deref_mut().ok_or(Error::InvalidPacket("missing SILK data"))?;
+ for channel in self.ch.iter_mut().take(nci) {
+ for index in 0..channel.n_frames_per_packet {
+ channel.vad_flags[index] = decoder.bit_logp(1);
}
- for c in self.ch.iter_mut().take(nci) {
- c.lbrr_flags = [false; 3];
- if c.lbrr_flag {
- if c.n_frames_per_packet == 1 {
- c.lbrr_flags[0] = true;
- } else {
- let sym = d.icdf(LBRR_FLAGS[c.n_frames_per_packet - 2], 8) + 1;
- for i in 0..c.n_frames_per_packet {
- c.lbrr_flags[i] = (sym >> i) & 1 != 0;
- }
+ channel.lbrr_flag = decoder.bit_logp(1);
+ }
+ for channel in self.ch.iter_mut().take(nci) {
+ channel.lbrr_flags = [false; 3];
+ if channel.lbrr_flag {
+ if channel.n_frames_per_packet == 1 {
+ channel.lbrr_flags[0] = true;
+ } else {
+ let sym = decoder.icdf(LBRR_FLAGS[channel.n_frames_per_packet - 2], 8) + 1;
+ for index in 0..channel.n_frames_per_packet {
+ channel.lbrr_flags[index] = (sym >> index) & 1 != 0;
}
}
}
- if lost == LostFlag::Normal {
- // Skip LBRR data.
- for i in 0..self.ch[0].n_frames_per_packet {
- for n in 0..nci {
- if self.ch[n].lbrr_flags[i] {
- if nci == 2 && n == 0 {
- stereo_decode_pred(d);
- if !self.ch[1].lbrr_flags[i] {
- d.icdf(&MID_ONLY, 8);
- }
- }
- let cond = if i > 0 && self.ch[n].lbrr_flags[i - 1] { Cond::Conditionally } else { Cond::Independently };
- let c = &mut self.ch[n];
- c.decode_indices(d, i, true, cond);
- let mut pulses = [0i32; MAX_FRAME + 16];
- decode_pulses(d, &mut pulses, c.indices.signal_type, c.indices.quant_offset_type, c.frame_length);
- }
+ }
+ if lost == LostFlag::Normal {
+ self.skip_lbrr_data(decoder, nci);
+ }
+ Ok(())
+ }
+
+ fn skip_lbrr_data(&mut self, decoder: &mut RangeDecoder, nci: usize) {
+ for frame in 0..self.ch[0].n_frames_per_packet {
+ for channel in 0..nci {
+ if !self.ch[channel].lbrr_flags[frame] {
+ continue;
+ }
+ if nci == 2 && channel == 0 {
+ stereo_decode_pred(decoder);
+ if !self.ch[1].lbrr_flags[frame] {
+ decoder.icdf(&MID_ONLY, 8);
}
}
+ let condition = if frame > 0 && self.ch[channel].lbrr_flags[frame - 1] { Cond::Conditionally } else { Cond::Independently };
+ let state = &mut self.ch[channel];
+ state.decode_indices(decoder, frame, true, condition);
+ let mut pulses = [0i32; MAX_FRAME + 16];
+ decode_pulses(decoder, &mut pulses, state.indices.signal_type, state.indices.quant_offset_type, state.frame_length);
}
}
+ }
+
+ /// Decodes one SILK frame (10 or 20 ms) into interleaved `out` at the API rate.
+ pub fn decode(&mut self, mut dec: Option<&mut RangeDecoder>, lost: LostFlag, new_packet: bool, payload_ms: usize, out: &mut [f32]) -> Result<usize> {
+ let nci = self.channels_internal;
+ let stereo_to_mono = self.prepare_frame(new_packet, payload_ms)?;
+ self.decode_packet_header(&mut dec, lost)?;
// Stereo prediction.
if nci == 2 {
let fi = self.ch[0].n_frames_decoded;
diff --git a/crates/opus/src/silk/lpc.rs b/crates/opus/src/silk/lpc.rs
index 29a1e811b..5be9c6c85 100644
--- a/crates/opus/src/silk/lpc.rs
+++ b/crates/opus/src/silk/lpc.rs
@@ -1,7 +1,10 @@
//! Fixed-point NLSF decoding, NLSF→LPC conversion and filter stabilisation
//! (RFC 6716 §4.2.7.5, with the RFC 8251 §6/§7 overflow fixes).
-use super::tables::*;
+use super::tables::{
+ COS_Q12, LSF_ORDER_NBMB, LSF_ORDER_WB, NLSF_CB_NBMB, NLSF_CB_WB, NLSF_MIN_SPACING_NBMB, NLSF_MIN_SPACING_WB, NLSF_PRED_NBMB, NLSF_PRED_WB, NLSF_PSEL_NBMB,
+ NLSF_PSEL_WB,
+};
pub const MAX_LPC_ORDER: usize = 16;