use super::resample::Resampler;
use super::{SEGMENT, SEGMENTS};
use crate::totals::CLIPPED;
const SEGMENT_AT: [f64; SEGMENTS] = [0.2, 0.4, 0.6, 0.8];
const CLIPPED_SHARE: f64 = 0.05;
const QUIET_POWER: f64 = 1e-4;
const QUIETER: f64 = 0.1;
const LOW_POWER: f64 = 1e-2;
pub(super) struct Segment {
pub(super) start: u64,
pub(super) left: Vec<f64>,
pub(super) right: Vec<f64>,
clipped: usize,
power: f64,
}
impl Segment {
fn starting(start: u64) -> Self {
Self {
start,
left: Vec::with_capacity(SEGMENT),
right: Vec::with_capacity(SEGMENT),
clipped: 0,
power: 0.0,
}
}
fn push(&mut self, left: f64, right: f64) {
self.clipped += usize::from(left.abs() >= CLIPPED || right.abs() >= CLIPPED);
self.power += left * left + right * right;
self.left.push(left);
self.right.push(right);
}
fn is_clipped(&self) -> bool {
self.clipped as f64 > CLIPPED_SHARE * SEGMENT as f64
}
fn overlaps(&self, other: &Self) -> bool {
self.start < other.start + SEGMENT as u64 && other.start < self.start + SEGMENT as u64
}
fn next(&self) -> u64 {
self.start + self.left.len() as u64
}
fn full(&self) -> bool {
self.left.len() == SEGMENT
}
pub(super) fn brought(&self, resampler: &Resampler) -> Option<Self> {
let (channels, start) = resampler.brought(&[&self.left, &self.right], self.start)?;
let [mut left, mut right] = <[Vec<f64>; 2]>::try_from(channels).ok()?;
left.truncate(SEGMENT);
right.truncate(SEGMENT);
Some(Self {
start,
left,
right,
clipped: 0,
power: 0.0,
})
}
fn wanted(&self, first: u64, available: usize) -> Option<(usize, usize)> {
let next = self.next();
let from = usize::try_from(next.checked_sub(first)?).ok()?;
let count = (SEGMENT - self.left.len()).min(available.checked_sub(from)?);
(count > 0).then_some((from, count))
}
}
#[derive(Default)]
struct Spares {
filling: Option<Segment>,
kept: Vec<Segment>,
}
impl Spares {
const KEPT: usize = 2 * SEGMENTS;
fn take(&mut self, first: u64, left: &[f32], right: &[f32]) {
let filling = self.filling.take().filter(|s| s.next() == first);
let mut filling = filling.unwrap_or_else(|| Segment::starting(first));
for (l, r) in left.iter().zip(right) {
filling.push(f64::from(*l), f64::from(*r));
if filling.full() {
let next = Segment::starting(filling.next());
self.keep(std::mem::replace(&mut filling, next));
}
}
self.filling = Some(filling);
}
fn keep(&mut self, stretch: Segment) {
let quiet = stretch.power < QUIET_POWER * 2.0 * SEGMENT as f64;
if stretch.is_clipped() || quiet {
return;
}
self.kept.push(stretch);
self
.kept
.sort_by(|a, b| b.power.total_cmp(&a.power).then(a.start.cmp(&b.start)));
self.kept.truncate(Self::KEPT);
}
}
pub(crate) struct Segments(pub(super) Vec<Segment>, Spares);
impl Segments {
pub(crate) fn of(frames: u64) -> Option<Self> {
let length = SEGMENT as u64;
if frames < length {
return None;
}
let segments = SEGMENT_AT
.iter()
.map(|at| Segment::starting(((frames as f64 * at) as u64).min(frames - length)))
.collect();
Some(Self(segments, Spares::default()))
}
pub(crate) fn settle(&mut self) -> usize {
let mut replaced = 0;
for index in 0..self.0.len() {
if !self.0[index].full() {
continue;
}
let free = self.1.kept.iter().position(|spare| {
self
.0
.iter()
.enumerate()
.all(|(other, segment)| other == index || !spare.overlaps(segment))
});
let gives_way = |spare: &Segment| {
let segment = &self.0[index];
let low = segment.power < LOW_POWER * 2.0 * SEGMENT as f64;
segment.is_clipped() || (low && segment.power < QUIETER * spare.power)
};
if let Some(at) = free.filter(|at| gives_way(&self.1.kept[*at])) {
self.0[index] = self.1.kept.remove(at);
replaced += 1;
}
}
self.0.sort_by_key(|segment| segment.start);
replaced
}
pub(crate) fn clipped(&self) -> usize {
self.0.iter().filter(|s| s.full() && s.is_clipped()).count()
}
pub(crate) fn take(&mut self, first: u64, window: &[Vec<f32>]) {
let [left, right] = match window {
[mono] => [mono, mono],
[left, right, ..] => [left, right],
[] => return,
};
for segment in &mut self.0 {
if let Some((from, count)) = segment.wanted(first, left.len()) {
let range = from..from + count;
for (l, r) in left[range.clone()].iter().zip(&right[range]) {
segment.push(f64::from(*l), f64::from(*r));
}
}
}
self.1.take(first, left, right);
}
pub(crate) fn take_interleaved(&mut self, first: u64, samples: &[i32], channels: usize) {
let frames = samples.len() / channels;
let scale = 1.0 / 2_147_483_648.0;
for segment in &mut self.0 {
if let Some((from, count)) = segment.wanted(first, frames) {
for frame in samples.chunks_exact(channels).skip(from).take(count) {
let right = frame.get(1).unwrap_or(&frame[0]);
segment.push(f64::from(frame[0]) * scale, f64::from(*right) * scale);
}
}
}
}
pub(crate) fn missing(&self) -> Vec<usize> {
(0..self.0.len()).filter(|i| !self.0[*i].full()).collect()
}
pub(crate) fn needs(&self, index: usize) -> Option<u64> {
let segment = &self.0[index];
(!segment.full()).then(|| segment.next())
}
pub(crate) fn untouched(&self, index: usize) -> bool {
self.0[index].left.is_empty()
}
pub(crate) fn complete(&self) -> bool {
self.0.iter().all(Segment::full)
}
}