use rayon::prelude::*;
use super::aac::{Aac, AacStepper, Window, aac_bands};
use super::lattice;
use super::mp3::{GranuleSteps, Mp3, mp3_bands};
use super::resample::Resampler;
use super::segments::{Segment, Segments};
use super::{
AacSteps, CodecScan, MP3_HOP, Mp3Neighbours, Mp3Steps, OPUS_UNCUT_OFFSET, OpusHybrid, OpusScan,
OpusShifted, OpusShort, OpusUnfiltered, OtherRate, SEGMENTS, Scan, in_stretch,
};
const MAD_TO_SD: f64 = 1.4826;
const NEAR: usize = 16;
pub(crate) struct Opus {
pub(crate) rate: lattice::Rate,
pub(crate) bits: u32,
pub(crate) uncut: lattice::Counted,
pub(crate) uncut_short: [[[usize; 2]; 2]; 3],
pub(crate) unfiltered: [usize; 2],
}
pub(crate) fn jobs(opus: bool, other_rate: bool, wma: bool) -> usize {
(5 + usize::from(wma) + usize::from(opus) + 3 * usize::from(opus && other_rate)) * SEGMENTS
+ lattice::SHORT.len() * usize::from(opus)
}
pub(crate) fn scan(
segments: &Segments,
rate: u32,
opus: Option<Opus>,
other_rate: bool,
wma: bool,
go_on: impl Fn() -> bool + Sync,
ended: impl Fn() + Sync,
) -> Option<Scan> {
assert!(segments.complete(), "every segment is full before a scan");
let stretches = opus.as_ref().map(|opus| {
let stretches: Vec<_> = segments
.0
.iter()
.map(|segment| ([&segment.left[..], &segment.right[..]], segment.start))
.collect();
lattice::Stretches::of(&stretches, opus.rate, opus.bits)
});
let to_other = match rate {
48_000 => Some((44_100, Resampler::to_44100())),
44_100 => Some((48_000, Resampler::to_48000())),
_ => None,
};
let other = to_other.filter(|_| other_rate).map(|(rate, resampler)| {
let segments: Vec<Option<Segment>> = segments
.0
.par_iter()
.map(|segment| segment.brought(resampler))
.collect();
(rate, segments)
});
let part = lattice::FRAME / SEGMENTS;
let counts = |segment, rate| {
[
Job::Aac(Window::Kbd, segment, rate),
Job::Aac(Window::Sine, segment, rate),
Job::Mp3(segment, rate),
]
};
let jobs: Vec<Job> = segments
.0
.iter()
.flat_map(|segment| counts(segment, Rate::Own))
.chain(segments.0.iter().flat_map(|segment| {
[
Some(Window::Vorbis),
Some(Window::Ac3),
wma.then_some(Window::Wma),
]
.into_iter()
.flatten()
.map(move |window| Job::Aac(window, segment, Rate::Own))
}))
.chain(
other
.iter()
.flat_map(|(_, segments)| segments.iter().flatten())
.flat_map(|segment| counts(segment, Rate::Other)),
)
.chain(
stretches
.iter()
.flat_map(|stretches| (0..SEGMENTS).map(move |i| Job::Opus(stretches, i * part))),
)
.chain(
stretches
.iter()
.flat_map(|stretches| lattice::SHORT.map(|short| Job::OpusShort(stretches, short))),
)
.collect();
let curves: Vec<Curve> = jobs
.into_par_iter()
.map(|job| {
go_on().then(|| {
let curve = match job {
Job::Aac(window, segment, rate) => Curve::Aac(
window,
rate,
in_file(&levelled(&Aac::curve(segment, window)), segment.start),
),
Job::Mp3(segment, rate) => {
let (hybrid, subbands) = Mp3::new().curves(segment);
Curve::Mp3(
rate,
in_file(&levelled(&hybrid), segment.start),
in_file(&levelled(&subbands), segment.start),
)
}
Job::Opus(stretches, from) => Curve::Opus(stretches.counted(from..from + part)),
Job::OpusShort(stretches, short) => Curve::OpusShort(stretches.short_counted(short)),
};
ended();
curve
})
})
.collect::<Option<_>>()?;
let (mut aac, mut sine, mut mp3) = <[[Vec<Vec<f64>>; 2]; 3]>::default().into();
let (mut vorbis, mut wma_curves, mut mp2) = (Vec::new(), Vec::new(), Vec::new());
let mut ac3 = Vec::new();
let mut frames = Vec::new();
let mut short = Vec::new();
for curve in curves {
match curve {
Curve::Aac(Window::Kbd, rate, curve) => aac[rate as usize].push(curve),
Curve::Aac(Window::Sine, rate, curve) => sine[rate as usize].push(curve),
Curve::Aac(Window::Vorbis, _, curve) => vorbis.push(curve),
Curve::Aac(Window::Wma, _, curve) => wma_curves.push(curve),
Curve::Aac(Window::Ac3, _, curve) => ac3.push(curve),
Curve::Mp3(rate, curve, subbands) => {
mp3[rate as usize].push(curve);
if matches!(rate, Rate::Own) {
mp2.push(subbands);
}
}
Curve::Opus(counted) => frames.extend(counted),
Curve::OpusShort(counted) => short.push(counted),
}
}
let [aac, other_aac] = aac;
let [sine, other_sine] = sine;
let [mp3, other_mp3] = mp3;
let other_rate = other
.filter(|_| other_mp3.len() == SEGMENTS)
.map(|(rate, _)| OtherRate {
rate,
aac: codec_scan(&other_aac),
aac_sine: codec_scan(&other_sine),
mp3: codec_scan(&other_mp3),
});
let (aac, sine, mp3) = (codec_scan(&aac), codec_scan(&sine), codec_scan(&mp3));
let (mp3_bands, aac_bands) = (mp3_bands(rate), aac_bands(rate));
let stepped: Vec<SegmentSteps> = segments
.0
.par_iter()
.map(|segment| {
go_on().then(|| {
let mp3_steps = || {
mp3_bands.map(|bands| {
let offset = in_stretch(mp3.offset, segment.start, MP3_HOP);
Mp3::new().steps(segment, offset, bands)
})
};
let aac_steps = |window, count: &CodecScan| {
aac_bands.map(|bands| AacStepper::new(window).steps(segment, count.offset, bands))
};
let (mp3_steps, (kbd, sine)) = rayon::join(mp3_steps, || {
rayon::join(
|| aac_steps(Window::Kbd, &aac),
|| aac_steps(Window::Sine, &sine),
)
});
SegmentSteps {
mp3: mp3_steps,
aac: kbd.zip(sine).map(<[_; 2]>::from),
}
})
})
.collect::<Option<_>>()?;
let mp3_steps = mp3_bands.map(|_| {
let mut steps = Mp3Steps {
tested: 0,
stepped: 0,
whole: 0,
segment_whole: [0; SEGMENTS],
neighbours: None,
};
let mut neighbours = Mp3Neighbours::default();
for (segment, in_segment) in stepped.iter().zip(&mut steps.segment_whole) {
for granule in segment.mp3.iter().flatten() {
steps.tested += granule.tested;
steps.stepped += granule.stepped;
steps.whole += granule.whole;
*in_segment += granule.whole;
neighbours.add(&granule.neighbours);
}
}
steps.neighbours = Some(neighbours);
steps
});
let aac_steps = |window: usize| {
aac_bands.map(|_| {
let mut steps = AacSteps {
tested: 0,
stepped: 0,
whole: 0,
segment_whole: [0; SEGMENTS],
};
for (segment, in_segment) in stepped.iter().zip(&mut steps.segment_whole) {
for [tested, stepped, whole] in segment.aac.iter().map(|windows| windows[window]) {
steps.tested += tested;
steps.stepped += stepped;
steps.whole += whole;
*in_segment += whole;
}
}
steps
})
};
let (aac_steps, aac_sine_steps) = (aac_steps(0), aac_steps(1));
Some(Scan {
other_rate,
aac,
aac_sine: Some(sine),
vorbis: Some(codec_scan(&vorbis)),
wma: (!wma_curves.is_empty()).then(|| codec_scan(&wma_curves)),
ac3: Some(codec_scan(&ac3)),
mp2: Some(codec_scan(&mp2)),
mp3,
mp3_steps,
aac_steps,
aac_sine_steps,
opus: opus.map(|opus| opus_scan(&frames, &short, &opus)),
})
}
struct SegmentSteps {
mp3: Option<Vec<GranuleSteps>>,
aac: Option<[[usize; 3]; 2]>,
}
#[derive(Clone, Copy)]
enum Rate {
Own,
Other,
}
#[derive(Clone, Copy)]
enum Job<'a> {
Aac(Window, &'a Segment, Rate),
Mp3(&'a Segment, Rate),
Opus(&'a lattice::Stretches, usize),
OpusShort(&'a lattice::Stretches, lattice::Short),
}
enum Curve {
Aac(Window, Rate, Vec<f64>),
Mp3(Rate, Vec<f64>, Vec<f64>),
Opus(Vec<lattice::Counted>),
OpusShort(Vec<[usize; 2]>),
}
fn most(none: usize, counts: impl Iterator<Item = (usize, usize)>) -> (usize, usize) {
counts.fold((none, 0), |(at, most), (o, count)| {
if count > most { (o, count) } else { (at, most) }
})
}
fn opus_scan(counted: &[lattice::Counted], short: &[Vec<[usize; 2]>], opus: &Opus) -> OpusScan {
let uncut = &opus.uncut;
let [searched, unfiltered] = opus.unfiltered;
let with_alone = |[after, either]: [usize; 2]| if after > 0 { either } else { 0 };
let short = lattice::SHORT
.iter()
.zip(short)
.zip(opus.uncut_short)
.map(|((length, counted), uncut)| {
let grids = length.uncut_offsets();
let (offset, frames) = most(
grids[0],
counted.iter().copied().map(with_alone).enumerate(),
);
let (uncut_offset, uncut_frames) =
most(grids[0], grids.into_iter().zip(uncut.map(with_alone)));
OpusShort {
length: length.length,
offset,
frames,
uncut_offset,
uncut_frames,
}
})
.collect();
let (offset, frames) = most(
OPUS_UNCUT_OFFSET,
counted.iter().map(|c| c.frames.iter().sum()).enumerate(),
);
let (shifted_offset, shifted_frames) = most(
OPUS_UNCUT_OFFSET,
counted.iter().map(|c| c.shifted).enumerate(),
);
let (hybrid_offset, hybrid_frames) = most(
OPUS_UNCUT_OFFSET,
counted.iter().map(|c| c.hybrid).enumerate(),
);
OpusScan {
offset,
frames,
segment_frames: std::array::from_fn(|i| counted[offset].frames[i]),
uncut_frames: uncut.frames.iter().sum(),
shifted: Some(OpusShifted {
offset: shifted_offset,
frames: shifted_frames,
uncut_frames: uncut.shifted,
}),
hybrid: Some(OpusHybrid {
offset: hybrid_offset,
frames: hybrid_frames,
tested: counted[hybrid_offset].hybrid_tested,
steps: counted[hybrid_offset].hybrid_points,
uncut_frames: uncut.hybrid,
uncut_tested: uncut.hybrid_tested,
uncut_steps: uncut.hybrid_points,
}),
short,
unfiltered: Some(OpusUnfiltered {
searched,
frames: unfiltered,
}),
}
}
fn levelled(curve: &[f64]) -> Vec<f64> {
let mut near = Vec::with_capacity(2 * NEAR + 1);
(0..curve.len())
.map(|o| {
near.clear();
near.extend_from_slice(&curve[o.saturating_sub(NEAR)..(o + NEAR + 1).min(curve.len())]);
curve[o] - median(&mut near)
})
.collect()
}
fn in_file(curve: &[f64], start: u64) -> Vec<f64> {
let hop = curve.len();
(0..hop).map(|o| curve[in_stretch(o, start, hop)]).collect()
}
fn codec_scan(curves: &[Vec<f64>]) -> CodecScan {
let hop = curves[0].len();
let summed: Vec<f64> = (0..hop)
.map(|o| curves.iter().map(|c| c[o]).sum())
.collect();
let (z, offset) = robust_z(&summed);
let own: [(f64, usize); SEGMENTS] = std::array::from_fn(|i| robust_z(&curves[i]));
CodecScan {
offset,
z,
segments_agreeing: own.iter().filter(|(_, at)| *at == offset).count(),
segment_z: own.map(|(z, _)| z),
segment_offset: own.map(|(_, at)| at),
}
}
fn robust_z(curve: &[f64]) -> (f64, usize) {
let mut sorted = curve.to_vec();
let middle = median(&mut sorted);
for value in &mut sorted {
*value = (*value - middle).abs();
}
let mad = MAD_TO_SD * median(&mut sorted);
let (lowest, at) = curve
.iter()
.enumerate()
.fold((f64::INFINITY, 0), |(low, at), (i, c)| {
if *c < low { (*c, i) } else { (low, at) }
});
let z = if mad > 0.0 {
(middle - lowest) / mad
} else {
0.0
};
(z, at)
}
fn median(values: &mut [f64]) -> f64 {
values.sort_by(f64::total_cmp);
let half = values.len() / 2;
if values.len().is_multiple_of(2) {
(values[half - 1] + values[half]) / 2.0
} else {
values[half]
}
}
const EXPONENT_BITS: u32 = 0x7f80_0000;
const ONE: u32 = 0x3f80_0000;
const LANES: usize = 16;
const GROUPS: usize = 32;
struct Pairs {
t2: f32,
exponents: [i32; LANES],
products: [f32; LANES],
held: usize,
logged: usize,
logs: f64,
}
impl Pairs {
fn new(t2: f32) -> Self {
Self {
t2,
exponents: [0; LANES],
products: [1.0; LANES],
held: 0,
logged: 0,
logs: 0.0,
}
}
#[inline(always)]
fn take(&mut self, a: &[f32; LANES], b: &[f32; LANES]) {
let t2 = self.t2;
let floored = |v: f32| if v * v > t2 { v * v } else { t2 };
for j in 0..LANES {
let bits = (floored(a[j]) * floored(b[j])).to_bits();
self.exponents[j] += (bits >> 23) as i32;
self.products[j] *= f32::from_bits((bits & !EXPONENT_BITS) | ONE);
}
self.held += 1;
if self.held == GROUPS {
self.log();
}
}
fn log(&mut self) {
self.logs += self
.products
.iter()
.map(|p| f64::from(*p))
.product::<f64>()
.log2();
self.products = [1.0; LANES];
self.logged += self.held;
self.held = 0;
}
fn active(mut self) -> f64 {
if self.held > 0 {
self.log();
}
let pairs = (self.logged * LANES) as f64;
let exponents: i32 = self.exponents.iter().sum();
let floor = f64::from(self.t2 * self.t2).log2();
(f64::from(exponents) - 127.0 * pairs + self.logs - pairs * floor) * std::f64::consts::LOG10_2
}
}
pub(super) fn active(a: &[f32], b: &[f32], t2: f32) -> f64 {
let ((a, a_rest), (b, b_rest)) = (a.as_chunks(), b.as_chunks());
debug_assert!(a_rest.is_empty() && b_rest.is_empty() && a.len() == b.len());
let mut pairs = Pairs::new(t2);
for (a, b) in a.iter().zip(b) {
pairs.take(a, b);
}
pairs.active()
}
pub(super) fn active_stereo(left: [&[f32]; 2], right: [&[f32]; 2], t2: f32) -> [f64; 2] {
let (mut apart, mut joint) = (Pairs::new(t2), Pairs::new(2.0 * t2));
for (left, right) in left.into_iter().zip(right) {
let ((left, left_rest), (right, right_rest)) = (left.as_chunks(), right.as_chunks());
debug_assert!(left_rest.is_empty() && right_rest.is_empty() && left.len() == right.len());
for (l, r) in left.iter().zip(right) {
let sum: [f32; LANES] = std::array::from_fn(|j| l[j] + r[j]);
let difference: [f32; LANES] = std::array::from_fn(|j| l[j] - r[j]);
apart.take(l, r);
joint.take(&sum, &difference);
}
}
[apart.active(), joint.active()]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn z_is_the_lowest_entry_below_the_median_in_robust_deviations() {
let curve = [10.0, 11.0, 9.0, 10.0, 12.0, 8.0, 2.0, 10.0, 11.0, 9.0];
let (z, at) = robust_z(&curve);
assert_eq!(at, 6);
assert!((z - 8.0 / MAD_TO_SD).abs() < 1e-12, "{z}");
assert_eq!(robust_z(&[3.0; 8]), (0.0, 0), "a flat curve has no z");
}
#[test]
fn a_low_stretch_of_offsets_is_no_dip_and_one_low_offset_on_a_slope_is() {
let noise = |o: usize| ((o * 37) % 11) as f64;
let shelf: Vec<f64> = (0..1024)
.map(|o| noise(o) - if o < 128 { 60.0 } else { 0.0 })
.collect();
assert!(
robust_z(&shelf).0 > 10.0,
"the counts as they are read as a dip"
);
assert!(robust_z(&levelled(&shelf)).0 < 4.0);
let slope: Vec<f64> = (0..1024)
.map(|o| o as f64 * 3.0 + noise(o) - if o == 700 { 80.0 } else { 0.0 })
.collect();
assert!(robust_z(&slope).0 < 2.0, "the slope hides the dip");
let (z, at) = robust_z(&levelled(&slope));
assert_eq!(at, 700);
assert!(z > 8.0, "{z}");
}
#[test]
fn segment_curves_are_turned_into_the_files_offsets_before_they_agree() {
let hop = 8;
let dip = |at: usize| -> Vec<f64> {
(0..hop)
.map(|o| if o == at { 1.0 } else { 10.0 + o as f64 * 0.1 })
.collect()
};
let curves = [
in_file(&dip(3), 3),
in_file(&dip(5), 9),
in_file(&dip(7), 23),
in_file(&dip(4), 5),
];
let scan = codec_scan(&curves);
assert_eq!(scan.offset, 6);
assert_eq!(scan.segments_agreeing, 3);
}
#[test]
fn the_counts_are_the_sum_of_the_logs() {
let t2 = 1e-9f32;
let direct = |lines: &[f32]| -> f64 {
lines
.iter()
.map(|v| (f64::from(*v).powi(2) / f64::from(t2)).max(1.0).log10())
.sum()
};
for n in [32usize, 1024, 2048] {
let lines = |seed: f32| -> Vec<f32> {
(0..n)
.map(|i| ((i * i) as f32 * seed).sin() * 10f32.powi((i % 9) as i32 - 6))
.collect()
};
let (left, right) = (lines(0.37), lines(0.53));
let half = std::f32::consts::FRAC_1_SQRT_2;
let mid: Vec<f32> = left
.iter()
.zip(&right)
.map(|(l, r)| (l + r) * half)
.collect();
let side: Vec<f32> = left
.iter()
.zip(&right)
.map(|(l, r)| (l - r) * half)
.collect();
let near = |counted: f64, direct: f64| (counted - direct).abs() < 1e-5 * direct.max(1.0);
let apart = direct(&left) + direct(&right);
let counted = active(&left, &right, t2);
assert!(near(counted, apart), "{n}: {counted} {apart}");
let (l, r) = (left.split_at(n / 2), right.split_at(n / 2));
let [counted, joint] = active_stereo([l.0, l.1], [r.0, r.1], t2);
assert!(near(counted, apart), "{n}: {counted} {apart}");
let both = direct(&mid) + direct(&side);
assert!(near(joint, both), "{n}: {joint} {both}");
}
let under = active(&[1e-6; 64], &[0.0; 64], t2);
assert!(
under.abs() < 1e-6,
"values under the level count nothing: {under}"
);
}
}