choon 0.2.0

Check that lossless audio is actually lossless
Documentation
//! the AAC analysis: a long block's 2048-point MDCT at a hop of 1024 under either of the
//! format's two windows, for the count of a grid's offsets and for the quantizer's steps. the
//! count runs too under the windows, and at the lengths, of Vorbis's and WMA's long blocks and
//! of an AC-3 block

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;

/// the tasks a job's offsets are split into at most, so that one file's scan can fill the pool
const TASKS: usize = 32;

/// the window of a block a grid is counted under: an AAC long block's two, and those of the
/// other codecs counted with the same transform
#[derive(Clone, Copy)]
pub(crate) enum Window {
  /// Kaiser-Bessel derived, with an alpha of 4
  Kbd,
  Sine,
  /// the window of a Vorbis long block, whose transform has the same length and hop
  Vorbis,
  /// the sine window of a WMA long block, which is twice as long at twice the hop
  Wma,
  /// the Kaiser-Bessel-derived window of an AC-3 block, with an alpha of 5: 512 samples at a
  /// hop of 256
  Ac3,
}

/// the samples an AC-3 block advances by
const AC3_HOP: usize = 256;

impl Window {
  /// the samples a long block advances by
  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,
    }
  }

  /// the window over the samples of a long block, two hops of them
  pub(crate) fn samples(self) -> Vec<f32> {
    self.exact().into_iter().map(|w| w as f32).collect()
  }

  /// the same in double precision
  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(),
      // sin(pi/2 sin^2(pi (n + 1/2) / N))
      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(),
    }
  }
}

/// the long frames every offset of the grid holds in a segment of `samples` samples
fn frames(samples: usize, hop: usize) -> usize {
  (samples + 1 - 2 * hop) / hop
}

/// the analysis of a long block, AAC's, Vorbis's or WMA's, or of an AC-3 block: its window and
/// an orthonormal MDCT, transformed in single precision
#[derive(Clone)]
pub(super) struct Aac {
  /// the samples a block advances by, and the lines its transform gives
  hop: usize,
  mdct: SplitMdct,
  /// the transform of left and right, each as the halves [`SplitMdct`] gives
  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])),
    }
  }

  /// the active count summed over the long frames of `segment`, for each offset of the grid
  /// from its first sample. every offset counts the same frames. runs of offsets are tasks on
  /// rayon's thread pool, each with an analysis of its own.
  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);
    // the window and the transform's tables are made once and copied for each task
    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()
  }

  /// the active count summed over the `frames` long frames of `left` and `right` on the grid
  /// at `offset`, the frames every offset holds
  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()
  }
}

/// the edges of a long block's scalefactor bands in lines at `rate`, for the rates the steps
/// are read at
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,
  ])
}

/// the AAC analysis the steps are read with: a long block's window and an orthonormal MDCT in
/// double precision, whose rounding stays far under the samples'
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],
    }
  }

  /// the bands of `segment`'s long frames on the grid at `offset` from the file's first
  /// sample: how many were tested, sit on one step, and on a whole one. each band is taken as
  /// left and right or as mid and side, whichever has more whole steps.
  ///
  /// in this transform's scale a step is a whole power of the fourth root of two as it is
  /// coded, and a mid or side value is the coded one times the square root of two, two such
  /// powers.
  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) {
        // tested, stepped and whole, over the two channels of a pair
        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
  }

  /// the orthonormal MDCT of `input`, 2048 samples, windowed, into `lines`
  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);
  }
}

/// the Kaiser-Bessel-derived window of `length` samples with `alpha`: the square root of the
/// running sum of a Kaiser window of `length / 2 + 1` points with beta pi alpha over its total,
/// mirrored
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);
    // values of the reference implementation's window
    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}");
    }
  }
}