use rayon::prelude::*;
use super::mdct::{DctIv, SplitMdct, Strided, fold_windowed};
use super::scan::active_stereo;
use super::segments::Segment;
use super::steps::{BandScratch, WHOLE_STEP, band_step};
use super::{AAC_HOP, NOISE16, in_stretch};
use crate::kaiser;
const TASKS: usize = 32;
#[derive(Clone, Copy)]
pub(crate) enum Window {
Kbd,
Sine,
Vorbis,
Wma,
Ac3,
}
const AC3_HOP: usize = 256;
impl Window {
pub(crate) fn hop(self) -> usize {
match self {
Self::Kbd | Self::Sine | Self::Vorbis => AAC_HOP,
Self::Wma => 2 * AAC_HOP,
Self::Ac3 => AC3_HOP,
}
}
pub(crate) fn samples(self) -> Vec<f32> {
self.exact().into_iter().map(|w| w as f32).collect()
}
fn exact(self) -> Vec<f64> {
let length = 2 * self.hop();
match self {
Self::Kbd => kbd_window(length, 4.0),
Self::Ac3 => kbd_window(length, 5.0),
Self::Sine | Self::Wma => (0..length)
.map(|n| (std::f64::consts::PI * (n as f64 + 0.5) / length as f64).sin())
.collect(),
Self::Vorbis => (0..length)
.map(|n| {
let sine = (std::f64::consts::PI * (n as f64 + 0.5) / length as f64).sin();
(std::f64::consts::FRAC_PI_2 * sine * sine).sin()
})
.collect(),
}
}
}
fn frames(samples: usize, hop: usize) -> usize {
(samples + 1 - 2 * hop) / hop
}
#[derive(Clone)]
pub(super) struct Aac {
hop: usize,
mdct: SplitMdct,
values: [[Vec<f32>; 2]; 2],
}
impl Aac {
fn new(window: Window) -> Self {
let hop = window.hop();
Self {
hop,
mdct: SplitMdct::new(&window.samples()),
values: std::array::from_fn(|_| std::array::from_fn(|_| vec![0.0; hop / 2])),
}
}
pub(super) fn curve(segment: &Segment, window: Window) -> Vec<f64> {
let channel =
|samples: &[f64]| Strided::new(&samples.iter().map(|s| *s as f32).collect::<Vec<_>>());
let (left, right) = (channel(&segment.left), channel(&segment.right));
let hop = window.hop();
let frames = frames(segment.left.len(), hop);
let aac = Self::new(window);
(0..hop)
.into_par_iter()
.with_min_len(hop / TASKS)
.map_init(
|| aac.clone(),
|aac, offset| aac.count(&left, &right, frames, offset),
)
.collect()
}
fn count(&mut self, left: &Strided, right: &Strided, frames: usize, offset: usize) -> f64 {
let hop = self.hop;
let t2 = (NOISE16 as f32).powi(2);
(0..frames)
.map(|j| {
let start = offset + j * hop;
let [l, r] = &mut self.values;
let [l_even, l_odd] = l;
self.mdct.process(left, start, l_even, l_odd);
let [r_even, r_odd] = r;
self.mdct.process(right, start, r_even, r_odd);
let [apart, joint] = active_stereo([&l[0], &l[1]], [&r[0], &r[1]], t2);
apart.min(joint)
})
.sum()
}
}
pub(crate) fn aac_bands(rate: u32) -> Option<&'static [usize; 50]> {
matches!(rate, 44_100 | 48_000).then_some(&[
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160,
176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704,
736, 768, 800, 832, 864, 896, 928, 1024,
])
}
pub(super) struct AacStepper {
window: Vec<f64>,
dct: DctIv<f64>,
folded: Vec<f64>,
}
impl AacStepper {
pub(super) fn new(window: Window) -> Self {
Self {
window: window.exact(),
dct: DctIv::new(AAC_HOP),
folded: vec![0.0; AAC_HOP],
}
}
pub(super) fn steps(
&mut self,
segment: &Segment,
offset: usize,
bands: &[usize; 50],
) -> [usize; 3] {
let half = std::f64::consts::FRAC_1_SQRT_2;
let mut counts = [0; 3];
let mut lines = [const { Vec::new() }; 4];
let mut scratch = BandScratch::default();
let offset = in_stretch(offset, segment.start, AAC_HOP);
let frames = frames(segment.left.len(), AAC_HOP);
for frame in 0..frames {
let at = offset + frame * AAC_HOP;
let [l, r, m, s] = &mut lines;
self.mdct(&segment.left[at..at + 2 * AAC_HOP], l);
self.mdct(&segment.right[at..at + 2 * AAC_HOP], r);
m.clear();
m.extend(l.iter().zip(r.iter()).map(|(l, r)| (l + r) * half));
s.clear();
s.extend(l.iter().zip(r.iter()).map(|(l, r)| (l - r) * half));
for band in bands.windows(2) {
let mut count = |pair: [&Vec<f64>; 2]| {
pair.iter().fold([0; 3], |[tested, stepped, whole], lines| {
let step = band_step(&lines[band[0]..band[1]], NOISE16, &mut scratch);
let fourths = step.step().map(|step| 4.0 * step.log2());
[
tested + usize::from(step.tested()),
stepped + usize::from(fourths.is_some()),
whole + usize::from(fourths.is_some_and(|f| (f - f.round()).abs() < WHOLE_STEP)),
]
})
};
let [l, r, m, s] = &lines;
let (apart, joint) = (count([l, r]), count([m, s]));
let more = if joint[2] > apart[2] { joint } else { apart };
for (count, more) in counts.iter_mut().zip(more) {
*count += more;
}
}
}
counts
}
fn mdct(&mut self, input: &[f64], lines: &mut Vec<f64>) {
fold_windowed(input, &self.window, &mut self.folded);
lines.resize(AAC_HOP, 0.0);
self.dct.process(&self.folded, lines);
}
}
fn kbd_window(length: usize, alpha: f64) -> Vec<f64> {
let points = length / 2 + 1;
let beta = std::f64::consts::PI * alpha;
let kaiser: Vec<f64> = (0..points)
.map(|n| {
let r = 2.0 * n as f64 / (points - 1) as f64 - 1.0;
kaiser::window(beta, r)
})
.collect();
let total: f64 = kaiser.iter().sum();
let mut half = Vec::with_capacity(length / 2);
let mut running = 0.0;
for k in &kaiser[..points - 1] {
running += k;
half.push((running / total).sqrt());
}
let mirrored: Vec<f64> = half.iter().rev().copied().collect();
half.extend(mirrored);
half
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_kbd_window_is_ffmpegs_long_window() {
let window = kbd_window(2048, 4.0);
for (i, value) in [
(0, 0.000_292_561_534_837_649_7),
(100, 0.024_457_477_148_620_538),
(511, 0.706_119_339_105_633_4),
(1023, 0.999_999_957_203_872_2),
] {
assert!((window[i] - value).abs() < 1e-12, "{i}: {}", window[i]);
}
for i in 0..1024 {
let power = window[i].powi(2) + window[i + 1024].powi(2);
assert!((power - 1.0).abs() < 1e-12, "{i}: {power}");
}
}
}