use alloc::vec::Vec;
use core::ops::Range;
use core::time::Duration;
use crate::analyze::{Analysis, Domain};
use crate::errors::ConfigError;
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Threshold {
Auto,
Abs(f32),
BelowRef(f32),
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct SegmentConfig {
pub(crate) threshold: Threshold,
pub(crate) min_silence: Duration,
pub(crate) min_sound: Duration,
pub(crate) pre: Duration,
pub(crate) tail: Duration,
}
impl Default for SegmentConfig {
fn default() -> Self {
Self {
threshold: Threshold::Auto,
min_silence: Duration::from_millis(250),
min_sound: Duration::from_millis(100),
pre: Duration::from_millis(100),
tail: Duration::from_millis(200),
}
}
}
impl SegmentConfig {
pub fn threshold(mut self, threshold: Threshold) -> Result<Self, ConfigError> {
let valid = match threshold {
Threshold::Auto => true,
Threshold::Abs(v) => v.is_finite(),
Threshold::BelowRef(v) => v.is_finite() && v >= 0.0,
};
if !valid {
return Err(ConfigError::InvalidThreshold);
}
self.threshold = threshold;
Ok(self)
}
#[must_use]
pub fn min_silence(mut self, d: Duration) -> Self {
self.min_silence = d;
self
}
#[must_use]
pub fn min_sound(mut self, d: Duration) -> Self {
self.min_sound = d;
self
}
#[must_use]
pub fn padding(mut self, pre: Duration, tail: Duration) -> Self {
self.pre = pre;
self.tail = tail;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Span {
pub start: u64,
pub end: u64,
pub kind: Kind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Kind {
Silence,
Sound,
}
const MIN_RANGE_DB: f64 = 20.0;
#[derive(Clone, Copy, Debug)]
pub(crate) struct Levels {
pub(crate) floor: f32,
pub(crate) reference: f32,
pub(crate) on: f32,
pub(crate) off: f32,
}
impl Levels {
pub(crate) fn new(analysis: &Analysis, threshold: Threshold) -> Self {
let mut values: Vec<f32> = analysis
.values()
.iter()
.zip(analysis.zero())
.filter(|(_, zero)| !**zero)
.map(|(v, _)| *v)
.collect();
if values.is_empty() {
return Self {
floor: 0.0,
reference: 0.0,
on: f32::INFINITY,
off: f32::INFINITY,
};
}
values.sort_unstable_by(f32::total_cmp);
let percentile = |p: usize| values[(p * (values.len() - 1) + 50) / 100];
let floor = percentile(10);
let reference = percentile(99);
let (on, off) = match (analysis.domain(), threshold) {
(Domain::Decibels, Threshold::Auto) => {
let on = (floor + 4.0).max((floor + 6.0).min(reference - 20.0));
(on, on - 3.0)
}
(Domain::Scores, Threshold::Auto) => (0.5, 0.35),
(_, Threshold::Abs(v)) => (v, v),
(_, Threshold::BelowRef(v)) => (reference - v, reference - v),
};
Self {
floor,
reference,
on,
off,
}
}
pub(crate) fn normalize(&self, domain: Domain, value: f64) -> f64 {
match domain {
Domain::Scores => value.clamp(0.0, 1.0),
Domain::Decibels => {
let range = f64::from(self.reference - self.floor).max(MIN_RANGE_DB);
((value - f64::from(self.floor)) / range).clamp(0.0, 1.0)
}
}
}
pub(crate) fn below_off(&self, analysis: &Analysis) -> Vec<bool> {
analysis
.values()
.iter()
.zip(analysis.zero())
.map(|(v, z)| *z || *v < self.off)
.collect()
}
}
pub(crate) fn silence_runs(
analysis: &Analysis,
levels: &Levels,
config: &SegmentConfig,
) -> Vec<Range<usize>> {
let mut sound = Vec::with_capacity(analysis.frames());
let mut state = false;
for (v, zero) in analysis.values().iter().zip(analysis.zero()) {
state = !*zero
&& if state {
*v >= levels.off
} else {
*v >= levels.on
};
sound.push(state);
}
fill_short_runs(&mut sound, true, analysis.frames_in(config.min_sound));
fill_short_runs(&mut sound, false, analysis.frames_in(config.min_silence));
runs(&sound)
.filter(|(loud, _)| !loud)
.map(|(_, r)| r)
.collect()
}
fn fill_short_runs(flags: &mut [bool], kind: bool, min: usize) {
let short: Vec<Range<usize>> = runs(flags)
.filter(|(k, r)| *k == kind && r.len() < min)
.map(|(_, r)| r)
.collect();
for r in short {
flags[r].fill(!kind);
}
}
pub(crate) fn runs(flags: &[bool]) -> impl Iterator<Item = (bool, Range<usize>)> + '_ {
let mut start = 0;
core::iter::from_fn(move || {
let kind = *flags.get(start)?;
let len = flags[start..].iter().take_while(|f| **f == kind).count();
let run = start..start + len;
start += len;
Some((kind, run))
})
}
pub(crate) fn split_point(next_start: usize, prev_end: usize, silence: &Range<usize>) -> usize {
next_start
.midpoint(prev_end)
.clamp(silence.start, silence.end)
}
impl Analysis {
#[must_use]
pub fn segments(&self, config: &SegmentConfig) -> Vec<Span> {
let sounds = self.padded_sounds(config);
let mut spans = Vec::with_capacity(2 * sounds.len() + 1);
let mut at = 0;
for r in sounds {
if r.start > at {
spans.push(self.span(at, r.start, Kind::Silence));
}
spans.push(self.span(r.start, r.end, Kind::Sound));
at = r.end;
}
if at < self.frames() {
spans.push(self.span(at, self.frames(), Kind::Silence));
}
spans
}
#[must_use]
pub fn trim(&self, config: &SegmentConfig) -> Option<Range<u64>> {
let sounds = self.padded_sounds(config);
let first = sounds.first()?;
let last = sounds.last()?;
Some(self.position(first.start)..self.position(last.end))
}
fn span(&self, start: usize, end: usize, kind: Kind) -> Span {
Span {
start: self.position(start),
end: self.position(end),
kind,
}
}
fn padded_sounds(&self, config: &SegmentConfig) -> Vec<Range<usize>> {
let levels = Levels::new(self, config.threshold);
let silences = silence_runs(self, &levels, config);
let (pre, tail) = (self.frames_in(config.pre), self.frames_in(config.tail));
let n = self.frames();
let mut sounds: Vec<Range<usize>> = Vec::new();
let mut at = 0;
let mut gap = 0..0;
for silence in silences.iter().chain(core::iter::once(&(n..n))) {
if silence.start > at {
let mut start = at.saturating_sub(pre);
let end = (silence.start + tail).min(n);
if let Some(prev) = sounds.last_mut() {
if start < prev.end {
let mid = split_point(start, prev.end, &gap);
prev.end = mid;
start = mid;
}
}
sounds.push(start..end);
}
at = silence.end;
gap = silence.clone();
}
sounds
}
}