use std::collections::VecDeque;
use crate::options::{RunOptions, SampleRate};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Run {
start_sample: u64,
end_sample: u64,
sample_rate: SampleRate,
mean_probability: f32,
peak_probability: f32,
}
impl Run {
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn new(start_sample: u64, end_sample: u64, sample_rate: SampleRate) -> Self {
Self {
start_sample,
end_sample,
sample_rate,
mean_probability: 0.0,
peak_probability: 0.0,
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_mean_probability(mut self, mean_probability: f32) -> Self {
self.mean_probability = mean_probability;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_peak_probability(mut self, peak_probability: f32) -> Self {
self.peak_probability = peak_probability;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn start_sample(&self) -> u64 {
self.start_sample
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn end_sample(&self) -> u64 {
self.end_sample
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn sample_rate(&self) -> SampleRate {
self.sample_rate
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn sample_count(&self) -> u64 {
self.end_sample.saturating_sub(self.start_sample)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn start_seconds(&self) -> f64 {
self.start_sample as f64 / self.sample_rate.hz() as f64
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn end_seconds(&self) -> f64 {
self.end_sample as f64 / self.sample_rate.hz() as f64
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn mean_probability(&self) -> f32 {
self.mean_probability
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn peak_probability(&self) -> f32 {
self.peak_probability
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Aggregate {
sum: f64,
count: u64,
peak: f32,
}
impl Aggregate {
const EMPTY: Self = Self {
sum: 0.0,
count: 0,
peak: f32::NEG_INFINITY,
};
#[cfg_attr(not(tarpaulin), inline(always))]
fn observe(&mut self, probability: f32) {
self.sum += probability as f64;
self.count += 1;
if probability > self.peak {
self.peak = probability;
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
fn absorb(&mut self, other: &Self) {
self.sum += other.sum;
self.count += other.count;
if other.peak > self.peak {
self.peak = other.peak;
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
fn mean(&self) -> f32 {
if self.count == 0 {
0.0
} else {
(self.sum / self.count as f64) as f32
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
fn peak(&self) -> f32 {
if self.count == 0 { 0.0 } else { self.peak }
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
const fn normalize_probability(probability: f32) -> f32 {
if probability.is_nan() {
0.0
} else {
probability.clamp(0.0, 1.0)
}
}
#[derive(Debug, Clone, Copy)]
struct SplitPoint {
end: u64,
aggregate: Aggregate,
}
#[derive(Debug, Clone, Copy)]
struct PendingRun {
start: u64,
aggregate: Aggregate,
}
#[derive(Debug, Clone)]
pub struct RunSegmenter {
options: RunOptions,
frame_hop: u64,
current_sample: u64,
active_start: Option<u64>,
active_raw_start: Option<u64>,
tentative_end: Option<u64>,
aggregate: Aggregate,
tentative_aggregate: Aggregate,
max_split: Option<SplitPoint>,
next_run: Option<PendingRun>,
pub(crate) pending_segments: VecDeque<Run>,
}
impl RunSegmenter {
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn new(options: RunOptions) -> Self {
let frame_hop = options.sample_rate().chunk_samples() as u64;
Self {
options,
frame_hop,
current_sample: 0,
active_start: None,
active_raw_start: None,
tentative_end: None,
aggregate: Aggregate::EMPTY,
tentative_aggregate: Aggregate::EMPTY,
max_split: None,
next_run: None,
pending_segments: VecDeque::new(),
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn options(&self) -> &RunOptions {
&self.options
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn set_sample_rate(&mut self, sample_rate: SampleRate) {
if self.sample_rate() != sample_rate {
self.options.set_sample_rate(sample_rate);
self.frame_hop = sample_rate.chunk_samples() as u64;
self.reset();
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn sample_rate(&self) -> SampleRate {
self.options.sample_rate()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn frame_hop(&self) -> usize {
self.frame_hop as usize
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn set_frame_hop(&mut self, frame_hop: usize) {
assert!(frame_hop != 0, "frame_hop must be non-zero");
self.frame_hop = frame_hop as u64;
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn is_active(&self) -> bool {
self.active_start.is_some()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn reset(&mut self) {
self.current_sample = 0;
self.clear_run_memory();
self.pending_segments.clear();
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn pending_segment_count(&self) -> usize {
self.pending_segments.len()
}
pub fn push_probability(&mut self, probability: f32) -> Option<Run> {
let probability = normalize_probability(probability);
let frame_hop = self.frame_hop;
let frame_start = self.current_sample;
self.current_sample = self.current_sample.saturating_add(frame_hop);
if probability >= self.options.start_threshold() {
if let Some(tentative_end) = self.tentative_end.take() {
let gap_samples = frame_start.saturating_sub(tentative_end);
if gap_samples > self.options.min_gap_at_max_run_samples() {
self.max_split = Some(SplitPoint {
end: tentative_end,
aggregate: self.aggregate,
});
self.next_run = Some(PendingRun {
start: frame_start,
aggregate: Aggregate::EMPTY,
});
}
self.aggregate.absorb(&self.tentative_aggregate);
self.tentative_aggregate = Aggregate::EMPTY;
}
if self.active_start.is_none() {
self.active_start = Some(frame_start.saturating_sub(self.options.pad_samples()));
self.active_raw_start = Some(frame_start);
self.aggregate = Aggregate::EMPTY;
self.aggregate.observe(probability);
return None;
}
}
let start = self.active_start?;
let raw_start = self.active_raw_start?;
if let Some(max_run_samples) = self.options.max_run_samples_for_frame(self.frame_hop)
&& frame_start.saturating_sub(raw_start) > max_run_samples
{
return self.split_at_max_duration(frame_start, probability);
}
if probability >= self.options.end_threshold() {
self.observe(probability);
return None;
}
let gap_start = *self.tentative_end.get_or_insert(frame_start);
self.observe(probability);
let gap_samples = frame_start.saturating_sub(gap_start);
if gap_samples > self.options.min_gap_at_max_run_samples() {
self.max_split = Some(SplitPoint {
end: gap_start,
aggregate: self.aggregate,
});
}
if gap_samples < self.options.min_gap_samples() {
return None;
}
let aggregate = self.aggregate;
self.clear_run_memory();
self.build_run(start, raw_start, gap_start, &aggregate)
}
pub fn push_probabilities(&mut self, probabilities: &[f32]) {
for &probability in probabilities {
if let Some(run) = self.push_probability(probability) {
self.pending_segments.push_back(run);
}
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn pop_pending(&mut self) -> Option<Run> {
self.pending_segments.pop_front()
}
fn take_trailing(&self) -> Option<Run> {
let start = self.active_start?;
let raw_start = self.active_raw_start?;
let end = self.current_sample;
if end.saturating_sub(raw_start) < self.options.min_run_samples() {
None
} else {
let mut aggregate = self.aggregate;
aggregate.absorb(&self.tentative_aggregate);
Some(Self::finished_run(
start,
end,
self.sample_rate(),
&aggregate,
))
}
}
pub fn finish(&mut self) -> Option<Run> {
if let Some(trailing) = self.take_trailing() {
self.pending_segments.push_back(trailing);
}
self.clear_run_memory();
self.pending_segments.pop_front()
}
fn split_at_max_duration(&mut self, frame_start: u64, probability: f32) -> Option<Run> {
let start = self.active_start?;
let raw_start = self.active_raw_start?;
let (raw_end, aggregate) = match self.max_split {
Some(split) => (split.end, split.aggregate),
None => {
let mut aggregate = self.aggregate;
aggregate.absorb(&self.tentative_aggregate);
(frame_start, aggregate)
}
};
let run = self.build_run(start, raw_start, raw_end, &aggregate);
let next_raw_start = if let Some(next) = self.next_run.filter(|next| next.start >= raw_end) {
self.active_start = Some(next.start.saturating_sub(self.options.pad_samples()));
self.aggregate = next.aggregate;
Some(next.start)
} else if self.max_split.is_none() && probability >= self.options.start_threshold() {
self.active_start = Some(frame_start.saturating_sub(self.options.pad_samples()));
self.aggregate = Aggregate::EMPTY;
Some(frame_start)
} else {
self.active_start = None;
self.aggregate = Aggregate::EMPTY;
None
};
self.active_raw_start = next_raw_start;
self.clear_split_tracking();
if next_raw_start.is_some() {
self.observe(probability);
}
run
}
#[cfg_attr(not(tarpaulin), inline(always))]
fn observe(&mut self, probability: f32) {
if self.tentative_end.is_some() {
self.tentative_aggregate.observe(probability);
} else {
self.aggregate.observe(probability);
}
if let Some(next) = self.next_run.as_mut() {
next.aggregate.observe(probability);
}
}
fn build_run(
&self,
start: u64,
raw_start: u64,
raw_end: u64,
aggregate: &Aggregate,
) -> Option<Run> {
let end_sample = raw_end
.saturating_add(self.options.pad_samples())
.min(self.current_sample);
if raw_end.saturating_sub(raw_start) < self.options.min_run_samples() {
None
} else {
Some(Self::finished_run(
start,
end_sample,
self.sample_rate(),
aggregate,
))
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
fn finished_run(
start_sample: u64,
end_sample: u64,
sample_rate: SampleRate,
aggregate: &Aggregate,
) -> Run {
Run::new(start_sample, end_sample, sample_rate)
.with_mean_probability(aggregate.mean())
.with_peak_probability(aggregate.peak())
}
fn clear_run_memory(&mut self) {
self.active_start = None;
self.active_raw_start = None;
self.aggregate = Aggregate::EMPTY;
self.clear_split_tracking();
}
fn clear_split_tracking(&mut self) {
self.tentative_end = None;
self.tentative_aggregate = Aggregate::EMPTY;
self.max_split = None;
self.next_run = None;
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use crate::{RunOptions, SampleRate};
use super::{Run, RunSegmenter};
const HOP: u64 = 512;
fn collect(segmenter: &mut RunSegmenter, probabilities: &[f32]) -> Vec<Run> {
let mut runs = Vec::new();
for probability in probabilities {
if let Some(run) = segmenter.push_probability(*probability) {
runs.push(run);
}
}
if let Some(run) = segmenter.finish() {
runs.push(run);
}
runs
}
#[track_caller]
fn assert_close(actual: f32, expected: f32, what: &str) {
assert!(
(actual - expected).abs() < 1e-6,
"{what}: expected {expected}, got {actual}"
);
}
#[test]
fn single_frame_run_reports_that_frame_as_mean_and_peak() {
let options = RunOptions::default()
.with_min_run_duration(Duration::ZERO)
.with_pad(Duration::ZERO)
.with_min_gap_duration(Duration::ZERO);
let mut segmenter = RunSegmenter::new(options);
let runs = collect(&mut segmenter, &[0.8, 0.0]);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].start_sample(), 0);
assert_eq!(runs[0].end_sample(), HOP, "one frame wide");
assert_close(runs[0].mean_probability(), 0.8, "mean");
assert_close(runs[0].peak_probability(), 0.8, "peak");
}
#[test]
fn bridged_gap_frames_stay_in_the_mean() {
let options = RunOptions::default()
.with_min_run_duration(Duration::ZERO)
.with_pad(Duration::ZERO);
let mut segmenter = RunSegmenter::new(options);
let mut probabilities = vec![0.6, 1.0];
probabilities.extend([0.0; 4]);
probabilities.extend([0.6, 0.6]);
probabilities.extend([0.0; 5]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].start_sample(), 0);
assert_eq!(
runs[0].end_sample(),
8 * HOP,
"the run spans the eight frames the aggregate covers"
);
assert_close(runs[0].mean_probability(), 0.35, "mean");
assert_close(runs[0].peak_probability(), 1.0, "peak");
}
#[test]
fn padding_is_outside_the_aggregated_span() {
let options = RunOptions::default()
.with_min_run_duration(Duration::ZERO)
.with_min_gap_duration(Duration::ZERO)
.with_pad(Duration::from_millis(32));
let mut segmenter = RunSegmenter::new(options);
let runs = collect(&mut segmenter, &[0.0, 1.0, 1.0, 0.0]);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].start_sample(), 0, "raw start 512 padded back to 0");
assert_eq!(runs[0].end_sample(), 4 * HOP, "raw end 1536 padded to 2048");
assert_eq!(runs[0].sample_count(), 4 * HOP);
assert_close(runs[0].mean_probability(), 1.0, "mean");
assert_close(runs[0].peak_probability(), 1.0, "peak");
}
#[test]
fn trailing_run_aggregates_its_unclosed_gap() {
let options = RunOptions::default()
.with_min_run_duration(Duration::ZERO)
.with_pad(Duration::ZERO);
let mut segmenter = RunSegmenter::new(options);
let runs = collect(&mut segmenter, &[1.0, 1.0, 0.0]);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].end_sample(), 3 * HOP);
assert_close(runs[0].mean_probability(), 2.0 / 3.0, "mean");
assert_close(runs[0].peak_probability(), 1.0, "peak");
}
#[test]
fn force_split_at_the_current_frame_restarts_the_aggregate() {
let options = RunOptions::default()
.with_min_run_duration(Duration::ZERO)
.with_pad(Duration::ZERO)
.with_max_run_duration(Duration::from_millis(160));
let mut segmenter = RunSegmenter::new(options);
let mut probabilities = vec![0.6; 5];
probabilities.extend([1.0; 3]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 2);
assert_eq!(runs[0].end_sample(), 5 * HOP);
assert_close(runs[0].mean_probability(), 0.6, "split run mean");
assert_close(runs[0].peak_probability(), 0.6, "split run peak");
assert_eq!(runs[1].start_sample(), 5 * HOP);
assert_close(runs[1].mean_probability(), 1.0, "continuation mean");
assert_close(runs[1].peak_probability(), 1.0, "continuation peak");
}
#[test]
fn force_split_at_a_recorded_gap_carries_the_pre_gap_aggregate() {
let options = RunOptions::default()
.with_min_run_duration(Duration::ZERO)
.with_pad(Duration::ZERO)
.with_min_gap_duration(Duration::from_millis(300))
.with_min_gap_at_max_run(Duration::from_millis(64))
.with_max_run_duration(Duration::from_millis(256));
let mut segmenter = RunSegmenter::new(options);
let mut probabilities = vec![0.9; 4];
probabilities.extend([0.0; 4]);
probabilities.extend([0.8; 4]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 2);
assert_eq!(runs[0].start_sample(), 0);
assert_eq!(runs[0].end_sample(), 4 * HOP);
assert_close(runs[0].mean_probability(), 0.9, "pre-gap run mean");
assert_close(runs[0].peak_probability(), 0.9, "pre-gap run peak");
assert_eq!(runs[1].start_sample(), 8 * HOP);
assert_eq!(runs[1].end_sample(), 12 * HOP);
assert_close(runs[1].mean_probability(), 0.8, "continuation mean");
assert_close(runs[1].peak_probability(), 0.8, "continuation peak");
}
#[test]
fn run_constructor_zeroes_the_aggregates() {
let run = Run::new(0, 1_000, SampleRate::Rate16k);
assert_close(run.mean_probability(), 0.0, "mean");
assert_close(run.peak_probability(), 0.0, "peak");
let annotated = run.with_mean_probability(0.5).with_peak_probability(0.9);
assert_close(annotated.mean_probability(), 0.5, "mean");
assert_close(annotated.peak_probability(), 0.9, "peak");
assert_eq!(annotated.start_sample(), run.start_sample());
assert_eq!(annotated.end_sample(), run.end_sample());
}
const LOW_INVALID: [(f32, &str); 3] = [
(f32::NAN, "NaN"),
(f32::NEG_INFINITY, "-inf"),
(-1.0, "finite -1.0"),
];
const HIGH_INVALID: [(f32, &str); 2] = [(f32::INFINITY, "+inf"), (2.0, "finite 2.0")];
#[track_caller]
fn assert_in_range(run: &Run, what: &str) {
let mean = run.mean_probability();
let peak = run.peak_probability();
assert!(
mean.is_finite() && (0.0..=1.0).contains(&mean),
"{what}: mean {mean} is not a finite probability in [0, 1]"
);
assert!(
peak.is_finite() && (0.0..=1.0).contains(&peak),
"{what}: peak {peak} is not a finite probability in [0, 1]"
);
}
#[track_caller]
fn assert_all_in_range(runs: &[Run], what: &str) {
for (index, run) in runs.iter().enumerate() {
assert_in_range(run, &format!("{what} run {index}"));
}
}
fn open_options() -> RunOptions {
RunOptions::default()
.with_min_run_duration(Duration::ZERO)
.with_pad(Duration::ZERO)
}
#[test]
fn normal_close_clamps_above_range_probabilities() {
for (invalid, name) in HIGH_INVALID {
let mut segmenter = RunSegmenter::new(open_options());
let mut probabilities = vec![0.6, invalid, 0.6];
probabilities.extend([0.0; 5]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 1, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].start_sample(), 0, "{name}");
assert_eq!(runs[0].end_sample(), 3 * HOP, "{name}");
assert_close(
runs[0].mean_probability(),
2.2 / 3.0,
&format!("{name} mean"),
);
assert_close(runs[0].peak_probability(), 1.0, &format!("{name} peak"));
}
}
#[test]
fn normal_close_maps_below_range_probabilities_to_silence() {
for (invalid, name) in LOW_INVALID {
let mut segmenter = RunSegmenter::new(open_options());
let mut probabilities = vec![0.6, invalid, 0.6];
probabilities.extend([0.0; 5]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 1, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].start_sample(), 0, "{name}");
assert_eq!(runs[0].end_sample(), 3 * HOP, "{name}");
assert_close(runs[0].mean_probability(), 0.4, &format!("{name} mean"));
assert_close(runs[0].peak_probability(), 0.6, &format!("{name} peak"));
}
}
#[test]
fn bridged_gap_maps_below_range_probabilities_to_silence() {
for (invalid, name) in LOW_INVALID {
let mut segmenter = RunSegmenter::new(open_options());
let mut probabilities = vec![0.6, 0.6, 0.0, invalid, 0.0, 0.6, 0.6];
probabilities.extend([0.0; 5]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 1, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].start_sample(), 0, "{name}");
assert_eq!(runs[0].end_sample(), 7 * HOP, "{name}");
assert_close(
runs[0].mean_probability(),
2.4 / 7.0,
&format!("{name} mean"),
);
assert_close(runs[0].peak_probability(), 0.6, &format!("{name} peak"));
}
}
#[test]
fn bridged_gap_clamps_the_bridging_frame() {
for (invalid, name) in HIGH_INVALID {
let mut segmenter = RunSegmenter::new(open_options());
let mut probabilities = vec![0.6, 0.6, 0.0, invalid, 0.0, 0.0, 0.6, 0.6];
probabilities.extend([0.0; 5]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 1, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].start_sample(), 0, "{name}");
assert_eq!(runs[0].end_sample(), 8 * HOP, "{name}");
assert_close(runs[0].mean_probability(), 0.425, &format!("{name} mean"));
assert_close(runs[0].peak_probability(), 1.0, &format!("{name} peak"));
}
}
#[test]
fn force_split_clamps_above_range_probabilities() {
for (invalid, name) in HIGH_INVALID {
let options = open_options().with_max_run_duration(Duration::from_millis(160));
let mut segmenter = RunSegmenter::new(options);
let mut probabilities = vec![0.6, invalid, 0.6, 0.6, 0.6];
probabilities.extend([0.8; 3]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 2, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].end_sample(), 5 * HOP, "{name}");
assert_close(
runs[0].mean_probability(),
0.68,
&format!("{name} split mean"),
);
assert_close(
runs[0].peak_probability(),
1.0,
&format!("{name} split peak"),
);
assert_eq!(runs[1].start_sample(), 5 * HOP, "{name}");
assert_close(
runs[1].mean_probability(),
0.8,
&format!("{name} continuation mean"),
);
}
}
#[test]
fn force_split_maps_below_range_probabilities_to_silence() {
for (invalid, name) in LOW_INVALID {
let options = open_options().with_max_run_duration(Duration::from_millis(160));
let mut segmenter = RunSegmenter::new(options);
let mut probabilities = vec![0.6, invalid, 0.6, 0.6, 0.6];
probabilities.extend([0.8; 3]);
let runs = collect(&mut segmenter, &probabilities);
assert_eq!(runs.len(), 2, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].end_sample(), 5 * HOP, "{name}");
assert_close(
runs[0].mean_probability(),
0.48,
&format!("{name} split mean"),
);
assert_close(
runs[0].peak_probability(),
0.6,
&format!("{name} split peak"),
);
assert_eq!(runs[1].start_sample(), 5 * HOP, "{name}");
assert_close(
runs[1].mean_probability(),
0.8,
&format!("{name} continuation mean"),
);
}
}
#[test]
fn finish_maps_below_range_probabilities_to_silence() {
for (invalid, name) in LOW_INVALID {
let mut segmenter = RunSegmenter::new(open_options());
let runs = collect(&mut segmenter, &[0.6, 0.6, invalid]);
assert_eq!(runs.len(), 1, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].end_sample(), 3 * HOP, "{name}");
assert_close(runs[0].mean_probability(), 0.4, &format!("{name} mean"));
assert_close(runs[0].peak_probability(), 0.6, &format!("{name} peak"));
}
}
#[test]
fn finish_clamps_above_range_probabilities() {
for (invalid, name) in HIGH_INVALID {
let mut segmenter = RunSegmenter::new(open_options());
let runs = collect(&mut segmenter, &[0.6, invalid, 0.6]);
assert_eq!(runs.len(), 1, "{name}");
assert_all_in_range(&runs, name);
assert_eq!(runs[0].end_sample(), 3 * HOP, "{name}");
assert_close(
runs[0].mean_probability(),
2.2 / 3.0,
&format!("{name} mean"),
);
assert_close(runs[0].peak_probability(), 1.0, &format!("{name} peak"));
}
}
fn boundaries(options: RunOptions, probabilities: &[f32]) -> Vec<(u64, u64)> {
let mut segmenter = RunSegmenter::new(options);
collect(&mut segmenter, probabilities)
.iter()
.map(|run| (run.start_sample(), run.end_sample()))
.collect()
}
#[test]
fn nan_frames_do_not_move_segment_boundaries() {
let mut with_nan = vec![0.6, 0.6, f32::NAN, 0.6, 0.6];
with_nan.extend([0.0, f32::NAN, 0.0, 0.0, 0.0]);
with_nan.extend([0.6, 0.6]);
with_nan.extend([0.0; 5]);
let with_zero: Vec<f32> = with_nan
.iter()
.map(|p| if p.is_nan() { 0.0 } else { *p })
.collect();
let nan_boundaries = boundaries(open_options(), &with_nan);
assert_eq!(
nan_boundaries,
boundaries(open_options(), &with_zero),
"a NaN frame must segment exactly like the 0.0 frame it stands for"
);
assert_eq!(
nan_boundaries,
vec![(0, 5 * HOP), (10 * HOP, 12 * HOP)],
"and both must match the pinned boundaries"
);
let split_options = open_options().with_max_run_duration(Duration::from_millis(160));
let mut with_nan = vec![0.6; 5];
with_nan.push(f32::NAN);
with_nan.extend([0.6; 3]);
let with_zero: Vec<f32> = with_nan
.iter()
.map(|p| if p.is_nan() { 0.0 } else { *p })
.collect();
let nan_boundaries = boundaries(split_options.clone(), &with_nan);
assert_eq!(
nan_boundaries,
boundaries(split_options, &with_zero),
"a NaN at the split decision frame must segment exactly like 0.0"
);
assert_eq!(
nan_boundaries,
vec![(0, 5 * HOP), (6 * HOP, 9 * HOP)],
"and both must match the pinned boundaries"
);
}
#[test]
fn repeated_malformed_frames_cannot_hold_a_run_open() {
for (invalid, name) in LOW_INVALID {
let mut segmenter = RunSegmenter::new(open_options().with_start_threshold(0.0));
let mut probabilities = vec![0.6, 0.6];
probabilities.extend([invalid; 64]);
let mut closed = None;
for (index, probability) in probabilities.iter().enumerate() {
if let Some(run) = segmenter.push_probability(*probability) {
closed = Some((index, run));
break;
}
}
let (index, run) = closed.unwrap_or_else(|| {
panic!("{name}: the run must close while the malformed frames are still arriving")
});
assert_eq!(
index, 6,
"{name}: closes on the frame the gap outgrows min_gap_duration"
);
assert_eq!(run.start_sample(), 0, "{name}");
assert_eq!(
run.end_sample(),
2 * HOP,
"{name}: the run ends at the first malformed frame"
);
assert_in_range(&run, name);
assert!(!segmenter.is_active(), "{name}: no run is left open");
for probability in &probabilities[index + 1..] {
assert!(
segmenter.push_probability(*probability).is_none(),
"{name}: a malformed frame must not open a run"
);
}
assert!(segmenter.finish().is_none(), "{name}: nothing trails");
}
}
#[test]
fn canonicalization_is_behaviour_preserving_at_the_lowest_thresholds() {
for (invalid, name) in LOW_INVALID {
let options = || {
open_options()
.with_start_threshold(0.0)
.with_end_threshold(0.0)
};
let mut with_zero = vec![0.6, 0.6, 0.0, 0.6, 0.6];
with_zero.extend([0.0; 5]);
with_zero.extend([0.6, 0.6]);
with_zero.extend([0.0; 5]);
let mut with_invalid = with_zero.clone();
with_invalid[2] = invalid;
with_invalid[6] = invalid;
let invalid_boundaries = boundaries(options(), &with_invalid);
assert_eq!(
invalid_boundaries,
boundaries(options(), &with_zero),
"{name}: must segment exactly like the 0.0 frames it stands for"
);
assert_eq!(
invalid_boundaries,
vec![(0, 5 * HOP), (10 * HOP, 12 * HOP)],
"{name}: and both must match the pinned boundaries"
);
let mut segmenter = RunSegmenter::new(options());
let runs = collect(&mut segmenter, &with_invalid);
assert_all_in_range(&runs, name);
assert_close(
runs[0].mean_probability(),
0.48,
&format!("{name} first mean"),
);
assert_close(
runs[0].peak_probability(),
0.6,
&format!("{name} first peak"),
);
assert_close(
runs[1].mean_probability(),
0.6,
&format!("{name} second mean"),
);
}
}
#[test]
fn canonicalization_moves_no_force_split_boundary_at_the_lowest_thresholds() {
for (invalid, name) in LOW_INVALID {
let options = || {
open_options()
.with_start_threshold(0.0)
.with_max_run_duration(Duration::from_millis(160))
};
let mut with_zero = vec![0.6; 5];
with_zero.push(0.0);
with_zero.extend([0.6; 3]);
let mut with_invalid = with_zero.clone();
with_invalid[5] = invalid;
let invalid_boundaries = boundaries(options(), &with_invalid);
assert_eq!(
invalid_boundaries,
boundaries(options(), &with_zero),
"{name}: the split decision must read the canonical value as 0.0"
);
assert_eq!(
invalid_boundaries,
vec![(0, 5 * HOP), (6 * HOP, 9 * HOP)],
"{name}: and both must match the pinned boundaries"
);
let mut segmenter = RunSegmenter::new(options());
let runs = collect(&mut segmenter, &with_invalid);
assert_all_in_range(&runs, name);
assert_close(
runs[1].mean_probability(),
0.6,
&format!("{name} continuation mean"),
);
}
}
}