use std::sync::Arc;
use rayon::prelude::*;
use realfft::num_complex::Complex;
use realfft::{ComplexToReal, RealFftPlanner, RealToComplex};
use super::in_stretch;
use super::mdct::{DctIv, fold};
use super::resample::Resampler;
use crate::decode::opus::RATE;
pub(crate) const FRAME: usize = 960;
const OVERLAP: usize = 120;
const PRE_EMPHASIS: f64 = 0.850_006_103_5;
const EDGES: [usize; BANDS + 1] = [
0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 272, 320, 384, 480, 624, 800,
];
const BANDS: usize = 21;
const MEANS: [f64; BANDS] = [
6.4375, 6.25, 5.75, 5.3125, 5.0625, 4.8125, 4.5, 4.375, 4.875, 4.6875, 4.5625, 4.4375, 4.875,
4.625, 4.3125, 4.5, 4.375, 4.625, 4.75, 4.4375, 3.75,
];
const SCALE: f64 = 10.546_554_702_195_74;
const ALPHA: f64 = 0.5;
const BETA: f64 = 6554.0 / 32768.0;
const BETA_INTRA: f64 = 4915.0 / 32768.0;
#[derive(Clone, Copy)]
pub(crate) struct Short {
pub(crate) length: usize,
alpha: f64,
beta: f64,
}
pub(crate) const DELAYS: [usize; 2] = [312, 120];
pub(crate) const SHORT: [Short; 3] = [
Short {
length: 480,
alpha: 21248.0 / 32768.0,
beta: 12124.0 / 32768.0,
},
Short {
length: 240,
alpha: 26112.0 / 32768.0,
beta: 22282.0 / 32768.0,
},
Short {
length: 120,
alpha: 29440.0 / 32768.0,
beta: 30147.0 / 32768.0,
},
];
impl Short {
pub(crate) fn uncut_offsets(&self) -> [usize; 2] {
DELAYS.map(|delay| (4 * self.length - delay - (self.length - OVERLAP) / 2) % self.length)
}
}
const BLOCKS: usize = 8;
const BLOCK: usize = FRAME / BLOCKS;
const HYBRID_FROM: usize = 17;
const HYBRID_TESTED: [usize; 2] = [18, 19];
const LOWEST_PREDICTING: f64 = -9.0;
const LATTICE: f64 = 32.0;
const NEAR: f64 = 0.003;
const LOUD: f64 = 600.0;
const MIN_TESTED: usize = 12;
const SHARE: f64 = 0.8;
const PERIOD: f64 = 1.0 / LATTICE;
const DB: f64 = 6.020_599_913_279_624;
const ALIAS: f64 = 1.0 - BETA;
const CELLS: usize = 8;
const AGREE: f64 = 0.002;
const SHIFT_LIMIT: f64 = 18.0 / (2.0 * DB);
const LAGS: std::ops::RangeInclusive<usize> = 15..=1022;
const TAPS: [[f32; 3]; 3] = [
[10048.0 / 32768.0, 7112.0 / 32768.0, 4248.0 / 32768.0],
[15200.0 / 32768.0, 8784.0 / 32768.0, 0.0],
[26208.0 / 32768.0, 3280.0 / 32768.0, 0.0],
];
const GAIN: f32 = 0.093_75;
const GAINS: usize = 8;
const SEARCHED: usize = 4;
const MOST_SEARCHED: usize = 40;
const PITCHED: f32 = 0.5;
const LAG_POINTS: usize = 4096;
const FRACTIONS: usize = 4;
pub(crate) const UNCUT_OFFSET: usize = (2 * FRAME - DELAYS[0] - (FRAME - OVERLAP) / 2) % FRAME;
const UNCUT_WINDOWS: usize = 60;
#[derive(Clone, Copy)]
pub(crate) enum Rate {
Native,
From44100,
}
impl Rate {
pub(crate) fn of(rate: u32) -> Option<Self> {
match rate {
RATE => Some(Self::Native),
44_100 => Some(Self::From44100),
_ => None,
}
}
}
fn bins(band: usize, length: usize) -> std::ops::Range<usize> {
EDGES[band] * length / FRAME..EDGES[band + 1] * length / FRAME
}
fn noise(bits: u32, length: usize) -> [f64; BANDS] {
let sigma = 2f64.powi(1 - bits.min(24) as i32) / 12f64.sqrt();
std::array::from_fn(|band| {
let bins = bins(band, length);
let width = bins.len() as f64;
let gain: f64 = bins
.map(|bin| {
let w = std::f64::consts::PI * (bin as f64 + 0.5) / length as f64;
1.0 - 2.0 * PRE_EMPHASIS * w.cos() + PRE_EMPHASIS * PRE_EMPHASIS
})
.sum();
sigma * (gain / width).sqrt()
})
}
fn pre_emphasized(samples: impl Iterator<Item = f64>) -> Vec<f32> {
let mut before = 0.0;
samples
.map(|sample| {
let out = sample - PRE_EMPHASIS * before;
before = sample;
out as f32
})
.collect()
}
struct Celt {
length: usize,
rise: Vec<f32>,
dct: DctIv,
frame: Vec<f32>,
folded: Vec<f32>,
values: Vec<f32>,
short: DctIv,
block: Vec<f32>,
block_folded: Vec<f32>,
block_values: Vec<f32>,
noise: [f64; BANDS],
}
#[derive(Clone, Copy, PartialEq)]
enum Blocks {
Long,
Short,
}
#[derive(Clone, Copy)]
struct Bands {
energy: [f64; BANDS],
loud: [bool; BANDS],
}
impl Celt {
fn new(bits: u32, length: usize) -> Self {
let rise = (0..OVERLAP)
.map(|i| {
let inner = (0.5 * std::f64::consts::PI * (i as f64 + 0.5) / OVERLAP as f64).sin();
(0.5 * std::f64::consts::PI * inner * inner).sin() as f32
})
.collect();
Self {
length,
rise,
dct: DctIv::new(length),
frame: vec![0.0; 2 * length],
folded: vec![0.0; length],
values: vec![0.0; length],
short: DctIv::new(BLOCK),
block: vec![0.0; 2 * BLOCK],
block_folded: vec![0.0; BLOCK],
block_values: vec![0.0; BLOCK],
noise: noise(bits, length),
}
}
fn read(&mut self, samples: &[f32], blocks: Blocks) -> Bands {
match blocks {
Blocks::Long => self.bands(samples),
Blocks::Short => self.short_bands(samples),
}
}
fn short_bands(&mut self, samples: &[f32]) -> Bands {
let flat = (FRAME - OVERLAP) / 2;
let mut squares = [0.0f64; BANDS];
for block in 0..BLOCKS {
let from = flat + block * BLOCK;
let (rising, falling) = self.block.split_at_mut(BLOCK);
for ((out, x), w) in rising.iter_mut().zip(&samples[from..]).zip(&self.rise) {
*out = x * w;
}
let fall = self.rise.iter().rev();
for ((out, x), w) in falling.iter_mut().zip(&samples[from + BLOCK..]).zip(fall) {
*out = x * w;
}
fold(&self.block, &mut self.block_folded);
self
.short
.process(&self.block_folded, &mut self.block_values);
for (band, squares) in squares.iter_mut().enumerate() {
*squares += self.block_values[EDGES[band] / BLOCKS..EDGES[band + 1] / BLOCKS]
.iter()
.map(|v| f64::from(*v).powi(2))
.sum::<f64>();
}
}
let mut bands = Bands {
energy: [0.0; BANDS],
loud: [false; BANDS],
};
let scale = SCALE + 0.5 * (BLOCKS as f64).log2();
for band in 0..BANDS {
bands.energy[band] = 0.5 * (squares[band] + 1e-300).log2() - MEANS[band] + scale;
bands.loud[band] = squares[band].sqrt() >= LOUD * self.noise[band];
}
bands
}
fn bands(&mut self, samples: &[f32]) -> Bands {
let length = self.length;
let flat = (length - OVERLAP) / 2;
let (rise_from, fall_from) = (flat, 2 * length - flat - OVERLAP);
self.frame[..rise_from].fill(0.0);
self.frame[fall_from + OVERLAP..].fill(0.0);
self.frame[rise_from + OVERLAP..fall_from]
.copy_from_slice(&samples[rise_from + OVERLAP..fall_from]);
for (i, w) in self.rise.iter().enumerate() {
self.frame[rise_from + i] = samples[rise_from + i] * w;
self.frame[fall_from + OVERLAP - 1 - i] = samples[fall_from + OVERLAP - 1 - i] * w;
}
fold(&self.frame, &mut self.folded);
self.dct.process(&self.folded, &mut self.values);
let mut bands = Bands {
energy: [0.0; BANDS],
loud: [false; BANDS],
};
let scale = SCALE + 0.5 * (FRAME as f64 / length as f64).log2();
for band in 0..BANDS {
let squares: f64 = self.values[bins(band, length)]
.iter()
.map(|v| f64::from(*v).powi(2))
.sum();
bands.energy[band] = 0.5 * (squares + 1e-300).log2() - MEANS[band] + scale;
bands.loud[band] = squares.sqrt() >= LOUD * self.noise[band];
}
bands
}
}
const ROUNDS: f64 = 6_755_399_441_055_744.0;
fn nearest(x: f64) -> f64 {
(x + ROUNDS) - ROUNDS
}
fn steps(before: &Bands, bands: &Bands, shift: f64) -> [f64; BANDS] {
steps_with((ALPHA, BETA), before, bands, shift)
}
fn steps_with(
(alpha, beta): (f64, f64),
before: &Bands,
bands: &Bands,
shift: f64,
) -> [f64; BANDS] {
let level = 2.0 * shift;
let mut steps = [0.0; BANDS];
let mut lower = 0.0;
for band in 0..BANDS {
let predicted = alpha * (before.energy[band] - level).max(LOWEST_PREDICTING) + lower;
let step = bands.energy[band] - level - predicted;
lower += (1.0 - beta) * nearest(step);
steps[band] = step;
}
steps
}
fn steps_alone(bands: &Bands, shift: f64) -> [f64; BANDS] {
let level = 2.0 * shift;
let mut steps = [0.0; BANDS];
let mut lower = 0.0;
for band in 0..BANDS {
let step = bands.energy[band] - level - lower;
lower += (1.0 - BETA_INTRA) * nearest(step);
steps[band] = step;
}
steps
}
fn on_point(step: f64) -> bool {
let scaled = step * LATTICE;
(scaled - nearest(scaled)).abs() / LATTICE < NEAR
}
fn on_lattice(before: Option<&Bands>, bands: &Bands, shift: f64) -> (usize, usize) {
let steps = match before {
Some(before) => steps(before, bands, shift),
None => steps_alone(bands, shift),
};
tested_and_on(steps, before, bands)
}
fn tested_and_on(steps: [f64; BANDS], before: Option<&Bands>, bands: &Bands) -> (usize, usize) {
let (mut tested, mut hits) = (0, 0);
for (band, step) in steps.into_iter().enumerate() {
if bands.loud[band] && before.is_none_or(|before| before.loud[band]) {
tested += 1;
hits += usize::from(on_point(step));
}
}
(tested, hits)
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Hybrid {
Untested,
Off,
On([i32; 2]),
}
fn hybrid(before: &Bands, bands: &Bands) -> Hybrid {
let loud = |band: &usize| bands.loud[*band] && before.loud[*band];
if !HYBRID_TESTED.iter().all(loud) {
return Hybrid::Untested;
}
let mut lower = 0.0;
let mut steps = [0.0; BANDS];
for band in HYBRID_FROM..=HYBRID_TESTED[HYBRID_TESTED.len() - 1] {
let predicted = ALPHA * before.energy[band].max(LOWEST_PREDICTING) + lower;
steps[band] = bands.energy[band] - predicted;
lower += (1.0 - BETA) * nearest(steps[band]);
}
let tested = HYBRID_TESTED.map(|band| steps[band]);
let points = tested.map(|step| nearest(step * LATTICE) as i32);
if tested.iter().all(|step| on_point(*step)) {
Hybrid::On(points)
} else {
Hybrid::Off
}
}
fn all_sit(channels: impl IntoIterator<Item = Option<bool>>) -> bool {
let mut any = false;
for sits in channels {
match sits {
Some(true) => any = true,
Some(false) => return false,
None => {}
}
}
any
}
fn judged((tested, hits): (usize, usize)) -> Option<bool> {
(tested >= MIN_TESTED).then_some(hits as f64 >= SHARE * tested as f64)
}
fn gathered(sorted: &[f64], width: f64, period: f64) -> (usize, f64) {
let count = sorted.len();
let at = |i: usize| {
if i < count {
sorted[i]
} else {
sorted[i - count] + period
}
};
let (mut most, mut mean) = (0, 0.0);
let mut end = 0;
for (start, first) in sorted.iter().enumerate() {
while end < start + count && at(end) - first < width {
end += 1;
}
if end - start > most {
most = end - start;
mean = (start..end).map(at).sum::<f64>() / most as f64;
}
}
(most, mean)
}
fn named(before: &Bands, bands: &Bands) -> Option<f64> {
let tested = (0..BANDS).filter(|band| bands.loud[*band] && before.loud[*band]);
let count = tested.clone().count();
if count < MIN_TESTED {
return None;
}
let mut most: Option<(usize, f64)> = None;
for cell in 0..CELLS {
let middle = ((cell as f64 + 0.5) / CELLS as f64 - 0.5) * ALIAS;
let steps = steps(before, bands, middle);
let mut places = [0.0; BANDS];
for (place, band) in places.iter_mut().zip(tested.clone()) {
let scaled = steps[band] * LATTICE;
*place = scaled - nearest(scaled);
}
let places = &mut places[..count];
if places.iter().any(|place| !place.is_finite()) {
return None;
}
let mut eighths = [0; 8];
for place in places.iter() {
eighths[((place + 0.5) * 8.0) as usize % 8] += 1;
}
let most_in_three = (0..8)
.map(|i| eighths[i] + eighths[(i + 1) % 8] + eighths[(i + 2) % 8])
.max()
.unwrap_or(0);
if f64::from(most_in_three) < SHARE * count as f64 {
continue;
}
places.sort_by(f64::total_cmp);
let (members, mean) = gathered(places, 2.0 * NEAR * LATTICE, 1.0);
if members as f64 >= SHARE * count as f64 && most.is_none_or(|(most, _)| members > most) {
most = Some((members, middle + (mean - nearest(mean)) * PERIOD));
}
}
most.map(|(_, shift)| shift)
}
fn place(shifts: &[f64]) -> Option<f64> {
let mut places: Vec<f64> = shifts.iter().map(|s| s.rem_euclid(PERIOD)).collect();
places.sort_by(f64::total_cmp);
let (agreeing, mean) = gathered(&places, 2.0 * AGREE, PERIOD);
(agreeing > 0).then(|| mean.rem_euclid(PERIOD))
}
fn shift_at(place: f64, mut passing: impl FnMut(f64) -> usize) -> f64 {
let first = ((-SHIFT_LIMIT - place) / PERIOD).ceil() as i32;
let last = ((SHIFT_LIMIT - place) / PERIOD).floor() as i32;
let (mut most, mut best) = (0, 0.0);
for step in first..=last {
let shift = place + f64::from(step) * PERIOD;
let count = passing(shift);
if count > most || (count == most && shift.abs() < f64::abs(best)) {
(most, best) = (count, shift);
}
}
best
}
pub(crate) struct Counted {
pub(crate) frames: Vec<usize>,
pub(crate) shifted: usize,
pub(crate) hybrid_tested: usize,
pub(crate) hybrid: usize,
pub(crate) hybrid_points: usize,
}
const WAYS: [(Blocks, Option<Blocks>); 6] = [
(Blocks::Long, Some(Blocks::Long)),
(Blocks::Long, Some(Blocks::Short)),
(Blocks::Short, Some(Blocks::Long)),
(Blocks::Short, Some(Blocks::Short)),
(Blocks::Long, None),
(Blocks::Short, None),
];
fn sits(
(run, frame): (usize, usize),
(now, before): (Blocks, Option<Blocks>),
shifts: &[f64],
bands: &mut impl FnMut(usize, usize, usize, Blocks) -> Bands,
) -> bool {
all_sit(shifts.iter().enumerate().map(|(channel, shift)| {
let read = bands(run, channel, frame, now);
let before = before.map(|blocks| bands(run, channel, frame - 1, blocks));
judged(on_lattice(before.as_ref(), &read, *shift))
}))
}
fn sitting(
runs: &[usize],
ways: &[(Blocks, Option<Blocks>)],
shifts: &[f64],
bands: &mut impl FnMut(usize, usize, usize, Blocks) -> Bands,
) -> Vec<usize> {
runs
.iter()
.enumerate()
.map(|(run, frames)| {
(1..*frames)
.filter(|frame| {
ways
.iter()
.any(|way| sits((run, *frame), *way, shifts, bands))
})
.count()
})
.collect()
}
fn counted(
runs: &[usize],
channels: usize,
mut bands: impl FnMut(usize, usize, usize, Blocks) -> Bands,
) -> Counted {
let unshifted = vec![0.0; channels];
let mut frames = sitting(runs, &WAYS[..1], &unshifted, &mut bands);
if frames.iter().sum::<usize>() > 0 {
frames = sitting(runs, &WAYS, &unshifted, &mut bands);
}
let pairs = || {
runs
.iter()
.enumerate()
.flat_map(|(run, frames)| (1..*frames).map(move |frame| (run, frame)))
};
let mut open: Vec<(usize, usize, bool)> =
pairs().map(|(run, frame)| (run, frame, false)).collect();
let mut shifts = Vec::with_capacity(channels);
for channel in 0..channels {
let read: Vec<(Bands, Bands)> = open
.iter()
.map(|(run, frame, _)| {
(
bands(*run, channel, frame - 1, Blocks::Long),
bands(*run, channel, *frame, Blocks::Long),
)
})
.collect();
let named: Vec<f64> = read
.iter()
.filter_map(|(before, now)| named(before, now))
.collect();
let shift = place(&named).map_or(0.0, |place| {
shift_at(place, |shift| {
read
.iter()
.filter(|(before, now)| judged(on_lattice(Some(before), now, shift)) == Some(true))
.count()
})
});
open = open
.into_iter()
.zip(&read)
.filter_map(|((run, frame, any), (before, now))| {
match judged(on_lattice(Some(before), now, shift)) {
Some(true) => Some((run, frame, true)),
Some(false) => None,
None => Some((run, frame, any)),
}
})
.collect();
shifts.push(shift);
}
let mut shifted = open.iter().filter(|(_, _, any)| *any).count();
if shifted > 0 {
shifted = sitting(runs, &WAYS, &shifts, &mut bands).iter().sum();
}
let (mut hybrid_tested, mut hybrid_frames) = (0, 0);
let mut points = std::collections::HashSet::new();
for (run, frame) in pairs() {
let mut sits = Hybrid::Untested;
for channel in 0..channels {
let before = bands(run, channel, frame - 1, Blocks::Long);
match hybrid(&before, &bands(run, channel, frame, Blocks::Long)) {
Hybrid::On(_) if sits != Hybrid::Untested => {}
on @ Hybrid::On(_) => sits = on,
Hybrid::Off => {
sits = Hybrid::Off;
break;
}
Hybrid::Untested => {}
}
}
hybrid_tested += usize::from(sits != Hybrid::Untested);
if let Hybrid::On(on) = sits {
hybrid_frames += 1;
points.insert(on);
}
}
Counted {
frames,
shifted,
hybrid_tested,
hybrid: hybrid_frames,
hybrid_points: points.len(),
}
}
fn frames_in(length: usize) -> usize {
(length / FRAME).saturating_sub(3)
}
fn short_sits(
short: Short,
frame: usize,
alone: bool,
channels: usize,
bands: &mut impl FnMut(usize, usize) -> Bands,
) -> bool {
all_sit((0..channels).map(|channel| {
let now = bands(channel, frame);
judged(if alone {
on_lattice(None, &now, 0.0)
} else {
let before = bands(channel, frame - 1);
let steps = steps_with((short.alpha, short.beta), &before, &now, 0.0);
tested_and_on(steps, Some(&before), &now)
})
}))
}
fn short_sitting(
short: Short,
frames: usize,
channels: usize,
mut bands: impl FnMut(usize, usize) -> Bands,
) -> [usize; 2] {
let mut counts = [0; 2];
for frame in 1..frames {
let after = short_sits(short, frame, false, channels, &mut bands);
counts[0] += usize::from(after);
counts[1] += usize::from(after || short_sits(short, frame, true, channels, &mut bands));
}
counts
}
struct Stretch {
channels: Vec<Vec<f32>>,
start: u64,
}
impl Stretch {
fn of(channels: &[&[f64]], first: u64, rate: Rate) -> Option<Self> {
let emphasized = |channel: &[f64]| pre_emphasized(channel.iter().copied());
Some(match rate {
Rate::Native => Self {
channels: channels.iter().map(|c| emphasized(c)).collect(),
start: first,
},
Rate::From44100 => {
let (resampled, start) = Resampler::to_48000().brought(channels, first)?;
Self {
channels: resampled.iter().map(|c| emphasized(c)).collect(),
start,
}
}
})
}
}
pub(crate) struct Stretches {
stretches: Vec<Option<Stretch>>,
bits: u32,
}
impl Stretches {
pub(crate) fn of(stretches: &[([&[f64]; 2], u64)], rate: Rate, bits: u32) -> Self {
Self {
stretches: stretches
.iter()
.map(|(channels, first)| Stretch::of(channels, *first, rate))
.collect(),
bits,
}
}
pub(crate) fn counted(&self, offsets: std::ops::Range<usize>) -> Vec<Counted> {
let runs: Vec<usize> = self
.stretches
.iter()
.map(|s| s.as_ref().map_or(0, |s| frames_in(s.channels[0].len())))
.collect();
let most = runs.iter().copied().max().unwrap_or(0);
offsets
.into_par_iter()
.with_min_len(FRAME / 32)
.map_init(
|| {
(
Celt::new(self.bits, FRAME),
vec![None; self.stretches.len() * 4 * most],
)
},
|(celt, kept), offset| {
kept.fill(None);
counted(&runs, 2, |run, channel, frame, blocks| {
let stretch = self.stretches[run]
.as_ref()
.expect("a stretch with frames has samples");
let start = in_stretch(offset, stretch.start, FRAME) + frame * FRAME;
let short = usize::from(blocks == Blocks::Short);
*kept[((run * 2 + channel) * 2 + short) * most + frame].get_or_insert_with(|| {
celt.read(&stretch.channels[channel][start..start + 2 * FRAME], blocks)
})
})
},
)
.collect()
}
pub(crate) fn short_counted(&self, short: Short) -> Vec<[usize; 2]> {
let length = short.length;
(0..length)
.into_par_iter()
.with_min_len((length / 32).max(1))
.map_init(
|| (Celt::new(self.bits, length), Vec::new()),
|(celt, kept), offset| {
let mut counts = [0; 2];
for stretch in self.stretches.iter().flatten() {
let frames = (stretch.channels[0].len() / length).saturating_sub(3);
let first = in_stretch(offset, stretch.start, length);
kept.clear();
kept.resize(2 * frames, None);
let run = short_sitting(short, frames, 2, |channel, frame| {
*kept[channel * frames + frame].get_or_insert_with(|| {
celt.bands(&stretch.channels[channel][first + frame * length..][..2 * length])
})
});
counts[0] += run[0];
counts[1] += run[1];
}
counts
},
)
.collect()
}
}
struct Unfilter {
forward: Arc<dyn RealToComplex<f32>>,
inverse: Arc<dyn ComplexToReal<f32>>,
padded: Vec<f32>,
spectrum: Vec<Complex<f32>>,
alike: Vec<f32>,
comb: Vec<f32>,
taken: Vec<f32>,
}
impl Unfilter {
fn new() -> Self {
let mut planner = RealFftPlanner::new();
Self {
forward: planner.plan_fft_forward(LAG_POINTS),
inverse: planner.plan_fft_inverse(LAG_POINTS),
padded: vec![0.0; LAG_POINTS],
spectrum: vec![Complex::new(0.0, 0.0); LAG_POINTS / 2 + 1],
alike: vec![0.0; LAG_POINTS],
comb: vec![0.0; 3 * FRAME],
taken: vec![0.0; 3 * FRAME],
}
}
fn lags(&mut self, samples: &[f32]) -> Vec<usize> {
self.padded[..samples.len()].copy_from_slice(samples);
self.padded[samples.len()..].fill(0.0);
let planned = "buffers of the planned lengths";
self
.forward
.process(&mut self.padded, &mut self.spectrum)
.expect(planned);
for bin in &mut self.spectrum {
*bin = Complex::new(bin.norm_sqr(), 0.0);
}
self
.inverse
.process(&mut self.spectrum, &mut self.alike)
.expect(planned);
let strongest = LAGS
.max_by(|a, b| self.alike[*a].total_cmp(&self.alike[*b]))
.expect("the lags are a range with members");
if self.alike[strongest] < PITCHED * self.alike[0] || self.alike[0] <= 0.0 {
return Vec::new();
}
let mut lags = Vec::new();
for fraction in 1..=FRACTIONS {
let middle = (strongest + fraction / 2) / fraction;
for lag in middle.saturating_sub(1)..=middle + 1 {
if LAGS.contains(&lag) && !lags.contains(&lag) {
lags.push(lag);
}
}
}
lags
}
fn comb(&mut self, channel: &[f32], at: usize, lag: usize, shape: [f32; 3]) {
let [a, b, c] = shape;
for (i, comb) in self.comb.iter_mut().enumerate() {
let back = at + i - lag;
*comb = a * channel[back]
+ b * (channel[back + 1] + channel[back - 1])
+ c * (channel[back + 2] + channel[back - 2]);
}
}
fn judged(&mut self, celt: &mut Celt, channel: &[f32], at: usize, gain: f32) -> Option<bool> {
let samples = &channel[at..at + 3 * FRAME];
for ((taken, sample), comb) in self.taken.iter_mut().zip(samples).zip(&self.comb) {
*taken = sample - gain * comb;
}
let before = celt.bands(&self.taken[..2 * FRAME]);
let now = celt.bands(&self.taken[FRAME..]);
judged(on_lattice(Some(&before), &now, 0.0))
}
fn sits(&mut self, celt: &mut Celt, channels: &[Vec<f32>], at: usize) -> Option<bool> {
let lags = self.lags(&channels[0][at..at + 3 * FRAME]);
if lags.is_empty() {
return None;
}
for lag in lags {
for shape in TAPS {
for gain in (1..=GAINS).map(|step| GAIN * step as f32) {
let sits = all_sit(channels.iter().map(|channel| {
self.comb(channel, at, lag, shape);
self.judged(celt, channel, at, gain)
}));
if sits {
return Some(true);
}
}
}
}
Some(false)
}
}
pub(crate) struct Uncut {
celt: Celt,
unfilter: Unfilter,
unfiltered: [usize; 2],
short: [(Celt, [[usize; 2]; 2]); 3],
rate: Rate,
windows: Vec<Vec<Vec<[Bands; 2]>>>,
}
impl Uncut {
pub(crate) fn new(rate: Rate, bits: u32) -> Self {
Self {
celt: Celt::new(bits, FRAME),
unfilter: Unfilter::new(),
unfiltered: [0; 2],
short: SHORT.map(|short| (Celt::new(bits, short.length), [[0; 2]; 2])),
rate,
windows: Vec::new(),
}
}
pub(crate) fn take(&mut self, first: u64, window: &[Vec<f32>]) {
if self.windows.len() >= UNCUT_WINDOWS {
return;
}
let doubled: Vec<Vec<f64>> = window
.iter()
.map(|c| c.iter().map(|s| f64::from(*s)).collect())
.collect();
let channels: Vec<&[f64]> = doubled.iter().map(Vec::as_slice).collect();
let Some(stretch) = Stretch::of(&channels, first, self.rate) else {
self.windows.push(Vec::new());
return;
};
let length = stretch.channels[0].len();
for (short, (celt, counts)) in SHORT.iter().zip(&mut self.short) {
let frame = short.length;
for (grid, counts) in short.uncut_offsets().into_iter().zip(counts) {
let offset = in_stretch(grid, stretch.start, frame);
let frames = (length.saturating_sub(offset) / frame).saturating_sub(1);
let mut kept = vec![None; stretch.channels.len() * frames];
let run = short_sitting(*short, frames, stretch.channels.len(), |channel, at| {
*kept[channel * frames + at].get_or_insert_with(|| {
celt.bands(&stretch.channels[channel][offset + at * frame..][..2 * frame])
})
});
counts[0] += run[0];
counts[1] += run[1];
}
}
let offset = in_stretch(UNCUT_OFFSET, stretch.start, FRAME);
let frames = (length.saturating_sub(offset) / FRAME).saturating_sub(1);
let bands: Vec<Vec<[Bands; 2]>> = stretch
.channels
.iter()
.map(|channel| {
(0..frames)
.map(|frame| {
let samples = &channel[offset + frame * FRAME..][..2 * FRAME];
[Blocks::Long, Blocks::Short].map(|blocks| self.celt.read(samples, blocks))
})
.collect()
})
.collect();
let first = (*LAGS.end() + 2).saturating_sub(offset).div_ceil(FRAME) + 1;
let unshifted = vec![0.0; bands.len()];
for pair in 0..SEARCHED {
let frame = first + pair * frames.saturating_sub(first) / SEARCHED;
if frame >= frames || self.unfiltered[0] >= MOST_SEARCHED {
break;
}
let as_read = sits(
(0, frame),
WAYS[0],
&unshifted,
&mut |_, channel, frame, _| bands[channel][frame][0],
);
if as_read {
continue;
}
let at = offset + (frame - 1) * FRAME;
if let Some(sits) = self.unfilter.sits(&mut self.celt, &stretch.channels, at) {
self.unfiltered[0] += 1;
self.unfiltered[1] += usize::from(sits);
}
}
self.windows.push(bands);
}
pub(crate) fn counted(&self) -> Counted {
let runs: Vec<usize> = self
.windows
.iter()
.map(|window| window.first().map_or(0, Vec::len))
.collect();
let channels = self.windows.iter().map(Vec::len).max().unwrap_or(0);
counted(&runs, channels, |run, channel, frame, blocks| {
self.windows[run][channel][frame][usize::from(blocks == Blocks::Short)]
})
}
pub(crate) fn unfiltered(&self) -> [usize; 2] {
self.unfiltered
}
pub(crate) fn short_counted(&self) -> [[[usize; 2]; 2]; 3] {
std::array::from_fn(|i| self.short[i].1)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_step_is_on_the_lattice_when_its_prediction_is_taken_off() {
let quiet = Bands {
energy: [-2.0; BANDS],
loud: [true; BANDS],
};
let mut bands = quiet;
let mut lower = 0.0;
for band in 0..BANDS {
let coarse = (band % 5) as f64 - 2.0;
let fine = if band % 2 == 0 { 0.25 } else { -0.125 };
bands.energy[band] = ALPHA * quiet.energy[band] + lower + coarse + fine;
lower += (1.0 - BETA) * coarse;
}
assert_eq!(on_lattice(Some(&quiet), &bands, 0.0), (BANDS, BANDS));
let mut louder = bands;
for energy in &mut louder.energy {
*energy += 0.21;
}
assert_eq!(on_lattice(Some(&quiet), &louder, 0.0), (BANDS, 0));
let mut faint = bands;
faint.loud[3] = false;
faint.loud[7] = false;
assert_eq!(
on_lattice(Some(&quiet), &faint, 0.0),
(BANDS - 2, BANDS - 2)
);
}
#[test]
fn a_short_frame_predicts_with_its_lengths_shares_and_sits_where_its_delay_puts_it() {
let quiet = Bands {
energy: [-2.0; BANDS],
loud: [true; BANDS],
};
for short in SHORT {
let mut bands = quiet;
let mut lower = 0.0;
for band in 0..BANDS {
let coarse = (band % 5) as f64 - 2.0;
let fine = if band % 2 == 0 { 0.25 } else { -0.125 };
bands.energy[band] = short.alpha * quiet.energy[band] + lower + coarse + fine;
lower += (1.0 - short.beta) * coarse;
}
let own = steps_with((short.alpha, short.beta), &quiet, &bands, 0.0);
assert_eq!(tested_and_on(own, Some(&quiet), &bands), (BANDS, BANDS));
let (_, on) = on_lattice(Some(&quiet), &bands, 0.0);
assert!(on < BANDS / 2, "{}: {on}", short.length);
let run = [quiet, bands, bands];
let counts = short_sitting(short, run.len(), 1, |_, frame| run[frame]);
assert_eq!(counts, [1, 1], "{}", short.length);
}
let offsets = SHORT.map(|short| short.uncut_offsets());
assert_eq!(offsets, [[468, 180], [108, 60], [48, 0]]);
}
fn coded_after(before: &Bands, turn: usize) -> Bands {
let mut bands = *before;
let mut lower = 0.0;
for band in 0..BANDS {
let coarse = ((band + turn) % 5) as f64 - 2.0;
let fine = if (band + turn).is_multiple_of(2) {
0.25
} else {
-0.125
};
bands.energy[band] = ALPHA * before.energy[band] + lower + coarse + fine;
lower += (1.0 - BETA) * coarse;
}
bands
}
fn run_at(level: f64, frames: usize) -> Vec<Bands> {
let mut run = vec![Bands {
energy: [-2.0; BANDS],
loud: [true; BANDS],
}];
for turn in 1..frames {
let next = coded_after(&run[turn - 1], turn);
run.push(next);
}
for bands in &mut run {
for energy in &mut bands.energy {
*energy += level;
}
}
run
}
#[test]
fn frames_at_another_level_name_one_place_and_count_once_it_is_taken_off() {
let level = 2.7 / DB;
let run = run_at(level, 9);
let place_of = |shift: f64| shift.rem_euclid(PERIOD);
for pair in run.windows(2) {
assert_eq!(on_lattice(Some(&pair[0]), &pair[1], 0.0), (BANDS, 0));
assert_eq!(
on_lattice(Some(&pair[0]), &pair[1], level / 2.0),
(BANDS, BANDS)
);
let named = named(&pair[0], &pair[1]).expect("every band gathers");
assert!(
(place_of(named) - place_of(level / 2.0)).abs() < 1e-9,
"{named}"
);
}
let moved = counted(&[run.len()], 1, |_, _, frame, _| run[frame]);
assert_eq!(moved.frames, [0]);
assert_eq!(moved.shifted, run.len() - 1);
let run = run_at(0.0, 9);
let unmoved = counted(&[run.len()], 1, |_, _, frame, _| run[frame]);
assert_eq!(unmoved.frames, [run.len() - 1]);
assert_eq!(unmoved.shifted, run.len() - 1);
}
#[test]
fn each_channel_has_a_level_of_its_own() {
let (left, right) = (run_at(-1.0 / DB, 6), run_at(-2.5 / DB, 6));
let both = counted(&[6], 2, |_, channel, frame, _| {
[&left, &right][channel][frame]
});
assert_eq!((both.frames, both.shifted), (vec![0], 5));
let mut noise = run_at(0.0, 6);
for (frame, bands) in noise.iter_mut().enumerate() {
for (band, energy) in bands.energy.iter_mut().enumerate() {
*energy += ((frame * 7 + band * 13) % 17) as f64 * 0.0531;
}
}
let one = counted(&[6], 2, |_, channel, frame, _| {
[&left, &noise][channel][frame]
});
assert_eq!(one.shifted, 0);
}
#[test]
fn a_shift_one_alias_further_loses_only_the_lowest_band() {
let run = run_at(0.0, 2);
let (tested, hits) = on_lattice(Some(&run[0]), &run[1], ALIAS);
assert_eq!((tested, hits), (BANDS, BANDS - 1));
}
fn coded_alone() -> Bands {
let mut bands = Bands {
energy: [0.0; BANDS],
loud: [true; BANDS],
};
let mut lower = 0.0;
for (band, energy) in bands.energy.iter_mut().enumerate() {
let coarse = (band % 5) as f64 - 2.0;
let fine = if band.is_multiple_of(2) { 0.25 } else { -0.125 };
*energy = lower + coarse + fine;
lower += (1.0 - BETA_INTRA) * coarse;
}
bands
}
#[test]
fn a_frame_coded_without_the_one_before_sits_on_the_lattice_alone() {
let alone = coded_alone();
let before = run_at(0.0, 2)[1];
assert_eq!(on_lattice(None, &alone, 0.0), (BANDS, BANDS));
assert!(on_lattice(Some(&before), &alone, 0.0).1 < BANDS / 2);
let mut louder = alone;
for energy in &mut louder.energy {
*energy += 0.3;
}
assert_eq!(on_lattice(None, &louder, 0.0), (BANDS, 0));
assert_eq!(on_lattice(None, &louder, 0.15), (BANDS, BANDS));
}
#[test]
fn frames_read_another_way_count_only_where_a_frame_sits_as_long_blocks() {
let run = run_at(0.0, 5);
let noise = |frame: usize| {
let mut bands = run[frame];
for (band, energy) in bands.energy.iter_mut().enumerate() {
*energy += ((frame * 7 + band * 13) % 17) as f64 * 0.0531;
}
bands
};
let transient = |_, _, frame: usize, blocks: Blocks| {
if (frame == 2) == (blocks == Blocks::Short) {
run[frame]
} else {
noise(frame)
}
};
assert_eq!(counted(&[5], 1, transient).frames, [4]);
let short = |_, _, frame: usize, blocks: Blocks| match blocks {
Blocks::Short => run[frame],
Blocks::Long => noise(frame),
};
assert_eq!(counted(&[5], 1, short).frames, [0]);
}
#[test]
fn a_hybrid_frame_is_tested_on_the_two_bands_under_15_6_khz() {
let before = Bands {
energy: [-2.0; BANDS],
loud: [true; BANDS],
};
let mut bands = before;
let mut lower = 0.0;
for band in HYBRID_FROM..BANDS {
let coarse = (band % 3) as f64 - 1.0;
bands.energy[band] = ALPHA * before.energy[band] + lower + coarse + 0.25;
lower += (1.0 - BETA) * coarse;
}
assert!(matches!(hybrid(&before, &bands), Hybrid::On(_)));
let mut reached = bands;
reached.energy[HYBRID_FROM] += 0.1;
assert_eq!(hybrid(&before, &reached), hybrid(&before, &bands));
let mut off = bands;
off.energy[19] += 0.01;
assert_eq!(hybrid(&before, &off), Hybrid::Off);
let mut faint = bands;
faint.loud[18] = false;
assert_eq!(hybrid(&before, &faint), Hybrid::Untested);
let run = [before, bands, before, bands, before, bands];
let counted = counted(&[6], 1, |_, _, frame, _| run[frame]);
assert_eq!(
(counted.hybrid_tested, counted.hybrid, counted.hybrid_points),
(5, 3, 1)
);
}
#[test]
fn short_blocks_give_a_band_the_energy_of_its_eight_transforms() {
let samples: Vec<f32> = (0..2 * FRAME)
.map(|i| ((i * i) as f32 * 0.000_37).sin() * 0.5)
.collect();
let mut celt = Celt::new(16, FRAME);
let bands = celt.read(&samples, Blocks::Short);
let flat = (FRAME - OVERLAP) / 2;
let pi = std::f64::consts::PI;
let length = BLOCK as f64;
for band in [0, 7, 12, 20] {
let mut squares = 0.0;
for block in 0..BLOCKS {
for k in EDGES[band] / BLOCKS..EDGES[band + 1] / BLOCKS {
let value: f64 = (0..2 * BLOCK)
.map(|n| {
let window = f64::from(celt.rise[if n < BLOCK { n } else { 2 * BLOCK - 1 - n }]);
let angle = pi / length * (n as f64 + 0.5 + length / 2.0) * (k as f64 + 0.5);
window * f64::from(samples[flat + block * BLOCK + n]) * angle.cos()
})
.sum::<f64>()
* (2.0 / length).sqrt();
squares += value * value;
}
}
let energy = 0.5 * squares.log2() - MEANS[band] + SCALE + 1.5;
assert!(
(bands.energy[band] - energy).abs() < 1e-3,
"{band}: {} {energy}",
bands.energy[band]
);
}
}
#[test]
fn values_gather_around_the_end_of_the_circle() {
let (most, mean) = gathered(&[0.01, 0.4, 0.97, 0.99], 0.05, 1.0);
assert_eq!(most, 3);
assert!((mean - 0.99).abs() < 1e-12, "{mean}");
assert_eq!(gathered(&[], 0.05, 1.0).0, 0);
}
#[test]
fn rounding_by_the_sum_is_rounding_to_even() {
for x in [
-2.5,
-1.5,
-0.5,
-0.3,
0.0,
0.3,
0.5,
1.5,
2.5,
1e6 + 0.5,
-77.49,
] {
assert_eq!(nearest(x), f64::round_ties_even(x), "{x}");
}
}
#[test]
fn the_transform_is_the_direct_sum_under_the_low_overlap_window() {
let samples: Vec<f32> = (0..2 * FRAME)
.map(|i| ((i * i) as f32 * 0.000_37).sin() * 0.5)
.collect();
let mut celt = Celt::new(16, FRAME);
celt.bands(&samples);
let flat = (FRAME - OVERLAP) / 2;
let window = |n: usize| -> f64 {
let rise = |i: usize| f64::from(celt.rise[i]);
match n {
n if n < flat => 0.0,
n if n < flat + OVERLAP => rise(n - flat),
n if n < 2 * FRAME - flat - OVERLAP => 1.0,
n if n < 2 * FRAME - flat => rise(2 * FRAME - flat - 1 - n),
_ => 0.0,
}
};
let pi = std::f64::consts::PI;
let length = FRAME as f64;
for k in [0, 7, 100, 479, 800, 959] {
let direct: f64 = samples
.iter()
.enumerate()
.map(|(n, x)| {
let angle = pi / length * (n as f64 + 0.5 + length / 2.0) * (k as f64 + 0.5);
window(n) * f64::from(*x) * angle.cos()
})
.sum::<f64>()
* (2.0 / length).sqrt();
let got = f64::from(celt.values[k]);
assert!((got - direct).abs() < 1e-4, "{k}: {got} {direct}");
}
}
}