Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
785 changes: 689 additions & 96 deletions kodecs-opus/src/safe/celt/bands.rs

Large diffs are not rendered by default.

109 changes: 109 additions & 0 deletions kodecs-opus/src/safe/celt/coder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
//! A range coder running in either direction, for the steps libopus shares between its
//! encoder and decoder behind an `encode` flag.

use super::MAX_FRAME_BYTES;
use crate::safe::range;

/// The range coder of a frame being encoded or decoded.
pub(super) enum Coder<'c, 'a> {
Encode(&'c mut range::Encoder<'a>),
Decode(&'c mut range::Decoder<'a>),
}

impl<'a> Coder<'_, 'a> {
pub(super) fn encoding(&self) -> bool {
matches!(self, Self::Encode(_))
}

/// The encoder, for the encoder's own searches.
///
/// # Panics
///
/// When decoding.
pub(super) fn encoder(&mut self) -> &mut range::Encoder<'a> {
match self {
Self::Encode(enc) => enc,
Self::Decode(_) => panic!("only the encoder searches"),
}
}

pub(super) fn tell_frac(&self) -> u32 {
match self {
Self::Encode(enc) => enc.tell_frac(),
Self::Decode(dec) => dec.tell_frac(),
}
}

/// Encode `bit`, or decode a bit, whose probability of being set is 2 to the power of
/// `-logp`.
pub(super) fn bit_logp(&mut self, bit: bool, logp: u32) -> bool {
match self {
Self::Encode(enc) => {
enc.bit_logp(bit, logp);
bit
}
Self::Decode(dec) => dec.bit_logp(logp),
}
}

/// Encode `value`, or decode a value, uniform below `total`.
pub(super) fn uint(&mut self, value: u32, total: u32) -> u32 {
match self {
Self::Encode(enc) => {
enc.uint(value, total);
value
}
Self::Decode(dec) => dec.uint(total),
}
}

/// Encode `value`, or decode a value, as `count` raw bits.
pub(super) fn bits(&mut self, value: u32, count: u32) -> u32 {
match self {
Self::Encode(enc) => {
enc.bits(value, count);
value
}
Self::Decode(dec) => dec.bits(count),
}
}
}

/// An encoder's state after a trial encode, with the bytes it wrote, which a second trial
/// from the same start overwrites.
pub(super) struct Snapshot {
checkpoint: range::Checkpoint,
/// The range bytes before the trial, which it left alone.
from: usize,
range: [u8; MAX_FRAME_BYTES],
raw: [u8; MAX_FRAME_BYTES],
}

impl Snapshot {
/// Save `enc` after a trial that started with `from` range bytes written.
pub(super) fn take(enc: &range::Encoder<'_>, from: usize) -> Self {
let mut range = [0; MAX_FRAME_BYTES];
let written = &enc.range_written()[from..];
range[..written.len()].copy_from_slice(written);
let mut raw = [0; MAX_FRAME_BYTES];
let written = enc.raw_written();
raw[..written.len()].copy_from_slice(written);
Self {
checkpoint: enc.checkpoint(),
from,
range,
raw,
}
}

/// Rewind `enc` to the end of the saved trial, rewriting its bytes.
pub(super) fn restore(&self, enc: &mut range::Encoder<'_>) {
enc.restore(&self.checkpoint);
let written = &mut enc.range_written_mut()[self.from..];
let len = written.len();
written.copy_from_slice(&self.range[..len]);
let written = enc.raw_written_mut();
let len = written.len();
written.copy_from_slice(&self.raw[..len]);
}
}
115 changes: 115 additions & 0 deletions kodecs-opus/src/safe/celt/comb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
//! The pitch comb filter the encoder's prefilter and the decoder's postfilter share, from
//! libopus's celt/celt.c.
//! Copyright (c) 2007-2008 CSIRO, 2007-2010 Xiph.Org Foundation, and 2008 Gregory Maxwell.

use super::{COMBFILTER_MINPERIOD, OVERLAP};

/// The pitch filter's parameters for one frame.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Filter {
pub period: usize,
pub gain: f32,
pub tapset: usize,
}

/// The comb filter's taps for each tapset.
const COMB_GAINS: [[f32; 3]; 3] = [
[0.306_640_63, 0.217_041_02, 0.129_638_67],
[0.463_867_2, 0.268_066_4, 0.0],
[0.799_804_7, 0.100_097_656, 0.0],
];

/// Filter `n` samples of `buf` from `at` with a three-tap comb at the pitch period,
/// cross-fading from `old` to `new` over the window's overlap (none without a window).
///
/// Without `out` it filters in place, so later taps read already filtered samples, as
/// libopus's in-place call does; with it, the result goes there and `buf` is unchanged.
pub(super) fn comb_filter(
buf: &mut [f32],
at: usize,
mut out: Option<&mut [f32]>,
n: usize,
old: Filter,
new: Filter,
window: Option<&[f32; OVERLAP]>,
) {
let in_place = out.is_none();
let mut write = |buf: &mut [f32], i: usize, value: f32| match out.as_deref_mut() {
Some(out) => out[i] = value,
None => buf[at + i] = value,
};
if old.gain == 0.0 && new.gain == 0.0 {
if !in_place {
for i in 0..n {
let value = buf[at + i];
write(buf, i, value);
}
}
return;
}
// A zero gain comes with a zero period, which needs to be at least 2 to read real data.
let t0 = old.period.max(COMBFILTER_MINPERIOD);
let t1 = new.period.max(COMBFILTER_MINPERIOD);
let g00 = old.gain * COMB_GAINS[old.tapset][0];
let g01 = old.gain * COMB_GAINS[old.tapset][1];
let g02 = old.gain * COMB_GAINS[old.tapset][2];
let g10 = new.gain * COMB_GAINS[new.tapset][0];
let g11 = new.gain * COMB_GAINS[new.tapset][1];
let g12 = new.gain * COMB_GAINS[new.tapset][2];
let x = |buf: &[f32], i: usize, back: usize| buf[at + i - back];
let mut x1 = buf[at + 1 - t1];
let mut x2 = buf[at - t1];
let mut x3 = buf[at - t1 - 1];
let mut x4 = buf[at - t1 - 2];
// An unchanged filter needs no cross-fade.
let overlap = match window {
Some(_) if old.gain == new.gain && t0 == t1 && old.tapset == new.tapset => 0,
Some(_) => OVERLAP,
None => 0,
};
let mut i = 0;
if let Some(window) = window {
while i < overlap {
let x0 = buf[at + i + 2 - t1];
let f = window[i] * window[i];
let value = buf[at + i]
+ (1.0 - f) * g00 * x(buf, i, t0)
+ (1.0 - f) * g01 * (buf[at + i + 1 - t0] + x(buf, i, t0 + 1))
+ (1.0 - f) * g02 * (buf[at + i + 2 - t0] + x(buf, i, t0 + 2))
+ f * g10 * x2
+ f * g11 * (x1 + x3)
+ f * g12 * (x0 + x4);
write(buf, i, value);
x4 = x3;
x3 = x2;
x2 = x1;
x1 = x0;
i += 1;
}
}
if new.gain == 0.0 {
if !in_place {
for i in overlap..n {
let value = buf[at + i];
write(buf, i, value);
}
}
return;
}

// The constant filter, which rereads its history from the current position.
let mut x4 = buf[at + i - t1 - 2];
let mut x3 = buf[at + i - t1 - 1];
let mut x2 = buf[at + i - t1];
let mut x1 = buf[at + i + 1 - t1];
while i < n {
let x0 = buf[at + i + 2 - t1];
let value = buf[at + i] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4);
write(buf, i, value);
x4 = x3;
x3 = x2;
x2 = x1;
x1 = x0;
i += 1;
}
}
30 changes: 28 additions & 2 deletions kodecs-opus/src/safe/celt/cwrs.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Decoding PVQ codewords by their combinatorial index, from libopus's celt/cwrs.c.
//! Coding PVQ codewords by their combinatorial index, from libopus's celt/cwrs.c.
//! Copyright (c) 2007-2008 CSIRO, 2007-2009 Xiph.Org Foundation, and 2007-2009 Timothy B.
//! Terriberry.

Expand Down Expand Up @@ -47,6 +47,31 @@ fn v(n: usize, k: usize) -> u32 {
u(n, k).wrapping_add(u(n, k + 1))
}

/// Encode the codeword `y`, which holds `k` pulses.
pub(super) fn encode_pulses(y: &[i32], k: usize, enc: &mut range::Encoder) {
enc.uint(icwrs(y), v(y.len(), k));
}

/// The index of codeword `y` among those of its dimensions and pulses.
fn icwrs(y: &[i32]) -> u32 {
let n = y.len();
assert!(n >= 2, "a codeword has at least two dimensions");
let mut j = n - 1;
let mut index = u32::from(y[j] < 0);
let mut k = y[j].unsigned_abs() as usize;
loop {
j -= 1;
index += u(n - j, k);
k += y[j].unsigned_abs() as usize;
if y[j] < 0 {
index += u(n - j, k + 1);
}
if j == 0 {
return index;
}
}
}

/// Decode `y.len()` coordinates holding `k` pulses, returning their squared norm.
pub(super) fn decode_pulses(y: &mut [i32], k: usize, dec: &mut range::Decoder) -> f32 {
let n = y.len();
Expand Down Expand Up @@ -152,14 +177,15 @@ mod tests {
}

#[test]
fn every_index_decodes_to_a_distinct_codeword_with_k_pulses() {
fn every_index_round_trips_through_a_distinct_codeword_with_k_pulses() {
for (n, k) in [(2, 3), (3, 2), (4, 4), (5, 7), (8, 2), (6, 6)] {
let mut seen = std::collections::HashSet::new();
for index in 0..v(n, k) {
let mut y = vec![0; n];
let yy = cwrsi(&mut y, k, index);
assert_eq!(y.iter().map(|c| c.unsigned_abs() as usize).sum::<usize>(), k);
assert_eq!(yy, y.iter().map(|&c| (c * c) as f32).sum::<f32>());
assert_eq!(icwrs(&y), index, "N={n} K={k} encodes back");
assert!(seen.insert(y), "N={n} K={k} index {index} repeats");
}
}
Expand Down
Loading