use core::time::Duration;
use std::fmt;
use crate::error::{Error, Result};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde",
serde(rename_all = "snake_case", deny_unknown_fields)
)]
pub enum SampleRate {
#[cfg_attr(feature = "serde", serde(rename = "8k"))]
Rate8k,
#[cfg_attr(feature = "serde", serde(rename = "16k"))]
#[default]
Rate16k,
}
impl SampleRate {
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn hz(self) -> u32 {
match self {
Self::Rate8k => 8_000,
Self::Rate16k => 16_000,
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn chunk_samples(self) -> usize {
match self {
Self::Rate8k => 256,
Self::Rate16k => 512,
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn from_hz(rate: u32) -> Result<Self> {
match rate {
8_000 => Ok(Self::Rate8k),
16_000 => Ok(Self::Rate16k),
other => Err(Error::UnsupportedSampleRate { rate: other }),
}
}
}
impl fmt::Display for SampleRate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Rate8k => "8k",
Self::Rate16k => "16k",
})
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
const fn default_start_threshold() -> f32 {
0.5
}
#[cfg_attr(not(tarpaulin), inline(always))]
const fn default_min_run_duration() -> Duration {
Duration::from_millis(250)
}
#[cfg_attr(not(tarpaulin), inline(always))]
const fn default_min_gap_duration() -> Duration {
Duration::from_millis(100)
}
#[cfg_attr(not(tarpaulin), inline(always))]
const fn default_min_gap_at_max_run() -> Duration {
Duration::from_millis(98)
}
#[cfg_attr(not(tarpaulin), inline(always))]
const fn default_pad() -> Duration {
Duration::from_millis(30)
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct RunOptions {
#[cfg_attr(feature = "serde", serde(default))]
sample_rate: SampleRate,
#[cfg_attr(
feature = "serde",
serde(
default = "default_start_threshold",
deserialize_with = "deserialize_threshold"
)
)]
start_threshold: f32,
#[cfg_attr(
feature = "serde",
serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_optional_threshold"
)
)]
end_threshold: Option<f32>,
#[cfg_attr(
feature = "serde",
serde(
default = "default_min_run_duration",
alias = "min_speech_duration",
with = "humantime_serde"
)
)]
min_run_duration: Duration,
#[cfg_attr(
feature = "serde",
serde(
default = "default_min_gap_duration",
alias = "min_silence_duration",
with = "humantime_serde"
)
)]
min_gap_duration: Duration,
#[cfg_attr(
feature = "serde",
serde(
default = "default_min_gap_at_max_run",
alias = "min_silence_at_max_speech",
with = "humantime_serde"
)
)]
min_gap_at_max_run: Duration,
#[cfg_attr(
feature = "serde",
serde(
default,
skip_serializing_if = "Option::is_none",
alias = "max_speech_duration",
with = "humantime_serde::option"
)
)]
max_run_duration: Option<Duration>,
#[cfg_attr(
feature = "serde",
serde(
default = "default_pad",
alias = "speech_pad",
with = "humantime_serde"
)
)]
pad: Duration,
}
pub type SpeechOptions = RunOptions;
impl Default for RunOptions {
#[cfg_attr(not(tarpaulin), inline(always))]
fn default() -> Self {
Self::new()
}
}
impl RunOptions {
pub const MIN_THRESHOLD: f32 = 0.01;
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn new() -> Self {
Self {
sample_rate: SampleRate::Rate16k,
start_threshold: default_start_threshold(),
end_threshold: None,
min_run_duration: default_min_run_duration(),
min_gap_duration: default_min_gap_duration(),
min_gap_at_max_run: default_min_gap_at_max_run(),
max_run_duration: None,
pad: default_pad(),
}
}
#[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 start_threshold(&self) -> f32 {
self.start_threshold
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn end_threshold(&self) -> f32 {
effective_end_threshold(
self.start_threshold,
self
.end_threshold
.unwrap_or_else(|| default_end_threshold(self.start_threshold)),
)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn min_run_duration(&self) -> Duration {
self.min_run_duration
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn min_gap_duration(&self) -> Duration {
self.min_gap_duration
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn min_gap_at_max_run(&self) -> Duration {
self.min_gap_at_max_run
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn max_run_duration(&self) -> Option<Duration> {
self.max_run_duration
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn pad(&self) -> Duration {
self.pad
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn min_run_samples(&self) -> u64 {
ms_to_samples(self.min_run_duration, self.sample_rate)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn min_gap_samples(&self) -> u64 {
ms_to_samples(self.min_gap_duration, self.sample_rate)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn min_gap_at_max_run_samples(&self) -> u64 {
ms_to_samples(self.min_gap_at_max_run, self.sample_rate)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn max_run_samples(&self) -> Option<u64> {
self.max_run_samples_for_frame(self.sample_rate.chunk_samples() as u64)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub(crate) fn max_run_samples_for_frame(&self, frame_hop: u64) -> Option<u64> {
self.max_run_duration.map(|duration| {
ms_to_samples(duration, self.sample_rate)
.saturating_sub(frame_hop)
.saturating_sub(self.pad_samples().saturating_mul(2))
})
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn pad_samples(&self) -> u64 {
ms_to_samples(self.pad, self.sample_rate)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_sample_rate(mut self, sample_rate: SampleRate) -> Self {
self.set_sample_rate(sample_rate);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_start_threshold(mut self, threshold: f32) -> Self {
self.set_start_threshold(threshold);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_end_threshold(mut self, threshold: f32) -> Self {
self.set_end_threshold(threshold);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn clear_end_threshold(mut self) -> Self {
self.end_threshold = None;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_min_run_duration(mut self, duration: Duration) -> Self {
self.set_min_run_duration(duration);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_min_gap_duration(mut self, duration: Duration) -> Self {
self.set_min_gap_duration(duration);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_min_gap_at_max_run(mut self, duration: Duration) -> Self {
self.set_min_gap_at_max_run(duration);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_max_run_duration(mut self, duration: Duration) -> Self {
self.set_max_run_duration(duration);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn clear_max_run_duration(mut self) -> Self {
self.max_run_duration = None;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_pad(mut self, pad: Duration) -> Self {
self.set_pad(pad);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_sample_rate(&mut self, sample_rate: SampleRate) -> &mut Self {
self.sample_rate = sample_rate;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_start_threshold(&mut self, threshold: f32) -> &mut Self {
self.start_threshold = sanitize_threshold(threshold);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_end_threshold(&mut self, threshold: f32) -> &mut Self {
self.end_threshold = Some(sanitize_threshold(threshold));
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_min_run_duration(&mut self, duration: Duration) -> &mut Self {
self.min_run_duration = duration;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_min_gap_duration(&mut self, duration: Duration) -> &mut Self {
self.min_gap_duration = duration;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_min_gap_at_max_run(&mut self, duration: Duration) -> &mut Self {
self.min_gap_at_max_run = duration;
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_max_run_duration(&mut self, duration: Duration) -> &mut Self {
self.max_run_duration = Some(duration);
self
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_pad(&mut self, pad: Duration) -> &mut Self {
self.pad = pad;
self
}
}
impl RunOptions {
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn min_speech_duration(&self) -> Duration {
self.min_run_duration()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn min_silence_duration(&self) -> Duration {
self.min_gap_duration()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn min_silence_at_max_speech(&self) -> Duration {
self.min_gap_at_max_run()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn max_speech_duration(&self) -> Option<Duration> {
self.max_run_duration()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn speech_pad(&self) -> Duration {
self.pad()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn min_speech_samples(&self) -> u64 {
self.min_run_samples()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn min_silence_samples(&self) -> u64 {
self.min_gap_samples()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn min_silence_at_max_speech_samples(&self) -> u64 {
self.min_gap_at_max_run_samples()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn max_speech_samples(&self) -> Option<u64> {
self.max_run_samples()
}
#[cfg(test)]
#[cfg_attr(not(tarpaulin), inline(always))]
pub(crate) fn max_speech_samples_for_frame(&self, frame_hop: u64) -> Option<u64> {
self.max_run_samples_for_frame(frame_hop)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub fn speech_pad_samples(&self) -> u64 {
self.pad_samples()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_min_speech_duration(self, duration: Duration) -> Self {
self.with_min_run_duration(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_min_silence_duration(self, duration: Duration) -> Self {
self.with_min_gap_duration(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_min_silence_at_max_speech(self, duration: Duration) -> Self {
self.with_min_gap_at_max_run(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_max_speech_duration(self, duration: Duration) -> Self {
self.with_max_run_duration(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn clear_max_speech_duration(self) -> Self {
self.clear_max_run_duration()
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn with_speech_pad(self, pad: Duration) -> Self {
self.with_pad(pad)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_min_speech_duration(&mut self, duration: Duration) -> &mut Self {
self.set_min_run_duration(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_min_silence_duration(&mut self, duration: Duration) -> &mut Self {
self.set_min_gap_duration(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_min_silence_at_max_speech(&mut self, duration: Duration) -> &mut Self {
self.set_min_gap_at_max_run(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_max_speech_duration(&mut self, duration: Duration) -> &mut Self {
self.set_max_run_duration(duration)
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn set_speech_pad(&mut self, pad: Duration) -> &mut Self {
self.set_pad(pad)
}
}
impl fmt::Display for RunOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "sample_rate={}", self.sample_rate)?;
write!(f, ",start_threshold={}", self.start_threshold)?;
if let Some(end_threshold) = self.end_threshold {
write!(f, ",end_threshold={end_threshold}")?;
}
write!(
f,
",min_run_duration={}",
humantime::format_duration(self.min_run_duration)
)?;
write!(
f,
",min_gap_duration={}",
humantime::format_duration(self.min_gap_duration)
)?;
write!(
f,
",min_gap_at_max_run={}",
humantime::format_duration(self.min_gap_at_max_run)
)?;
if let Some(max_run_duration) = self.max_run_duration {
write!(
f,
",max_run_duration={}",
humantime::format_duration(max_run_duration)
)?;
}
write!(f, ",pad={}", humantime::format_duration(self.pad))
}
}
#[inline]
pub(crate) const fn ms_to_samples(duration: Duration, sample_rate: SampleRate) -> u64 {
let samples = (duration.as_millis() * (sample_rate.hz() as u128)) / 1_000;
if samples > u64::MAX as u128 {
u64::MAX
} else {
samples as u64
}
}
#[inline]
const fn sanitize_threshold(value: f32) -> f32 {
if value.is_finite() {
value.clamp(RunOptions::MIN_THRESHOLD, 1.0)
} else {
RunOptions::MIN_THRESHOLD
}
}
#[cfg(feature = "serde")]
fn deserialize_threshold<'de, D>(deserializer: D) -> core::result::Result<f32, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(sanitize_threshold(f32::deserialize(deserializer)?))
}
#[cfg(feature = "serde")]
fn deserialize_optional_threshold<'de, D>(
deserializer: D,
) -> core::result::Result<Option<f32>, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Option::<f32>::deserialize(deserializer)?.map(sanitize_threshold))
}
#[inline]
const fn default_end_threshold(start_threshold: f32) -> f32 {
sanitize_threshold((sanitize_threshold(start_threshold) - 0.15).max(RunOptions::MIN_THRESHOLD))
}
#[inline]
const fn effective_end_threshold(start_threshold: f32, end_threshold: f32) -> f32 {
let start_threshold = sanitize_threshold(start_threshold);
let end_threshold = sanitize_threshold(end_threshold);
if end_threshold < start_threshold {
end_threshold
} else {
default_end_threshold(start_threshold)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{RunOptions, SampleRate, SpeechOptions, ms_to_samples};
#[test]
fn sample_rate_chunk_contract_matches_silero_model() {
assert_eq!(SampleRate::Rate16k.chunk_samples(), 512);
assert_eq!(SampleRate::Rate8k.chunk_samples(), 256);
}
#[test]
fn speech_config_defaults_match_expected_streaming_behavior() {
let config = SpeechOptions::default();
assert_eq!(config.sample_rate(), SampleRate::Rate16k);
assert_eq!(config.start_threshold(), 0.5);
assert_eq!(config.end_threshold(), 0.35);
assert_eq!(config.min_speech_duration(), Duration::from_millis(250));
assert_eq!(config.min_silence_duration(), Duration::from_millis(100));
assert_eq!(
config.min_silence_at_max_speech(),
Duration::from_millis(98)
);
assert_eq!(config.max_speech_duration(), None);
assert_eq!(config.speech_pad(), Duration::from_millis(30));
}
#[test]
fn ms_to_samples_uses_stream_rate() {
assert_eq!(
ms_to_samples(Duration::from_millis(100), SampleRate::Rate16k),
1_600
);
assert_eq!(
ms_to_samples(Duration::from_millis(100), SampleRate::Rate8k),
800
);
}
#[test]
fn end_threshold_falls_back_to_default_gap_when_builder_order_would_invert_hysteresis() {
let options = SpeechOptions::default()
.with_start_threshold(0.4)
.with_end_threshold(0.6);
assert!(options.end_threshold() < options.start_threshold());
assert!((options.end_threshold() - 0.25).abs() < f32::EPSILON);
let reordered = SpeechOptions::default()
.with_end_threshold(0.6)
.with_start_threshold(0.4);
assert!(reordered.end_threshold() < reordered.start_threshold());
assert!((options.end_threshold() - reordered.end_threshold()).abs() < f32::EPSILON);
let valid = SpeechOptions::default()
.with_start_threshold(0.6)
.with_end_threshold(0.2);
assert!((valid.end_threshold() - 0.2).abs() < f32::EPSILON);
}
#[test]
fn max_speech_duration_converts_to_samples_with_stream_lookahead_and_padding() {
let options = SpeechOptions::default()
.with_speech_pad(Duration::from_millis(30))
.with_max_speech_duration(Duration::from_millis(1_000));
assert_eq!(
options.max_speech_duration(),
Some(Duration::from_millis(1_000))
);
assert_eq!(options.min_silence_at_max_speech_samples(), 1_568);
assert_eq!(options.max_speech_samples(), Some(14_528));
assert_eq!(options.max_speech_samples_for_frame(512), Some(14_528));
assert_eq!(options.max_speech_samples_for_frame(4_096), Some(10_944));
}
#[test]
fn thresholds_are_clamped_strictly_above_zero() {
for (raw, name) in [
(0.0_f32, "zero"),
(-1.0, "finite negative"),
(f32::NEG_INFINITY, "-inf"),
(f32::NAN, "NaN"),
(RunOptions::MIN_THRESHOLD / 2.0, "below the floor"),
] {
let options = SpeechOptions::default()
.with_start_threshold(raw)
.with_end_threshold(raw);
assert_eq!(
options.start_threshold(),
RunOptions::MIN_THRESHOLD,
"{name}: start threshold"
);
assert!(
options.start_threshold() > 0.0,
"{name}: start threshold must be strictly positive"
);
assert!(
options.end_threshold() > 0.0,
"{name}: end threshold must be strictly positive"
);
}
}
#[test]
fn the_hysteresis_window_is_never_inverted_across_the_permitted_range() {
for step in 0..=1_000u32 {
let raw = step as f32 / 1_000.0;
let derived = SpeechOptions::default().with_start_threshold(raw);
assert!(
derived.end_threshold() > 0.0,
"start {raw}: derived end threshold must be strictly positive"
);
assert!(
derived.end_threshold() <= derived.start_threshold(),
"start {raw}: derived end {} exceeds start {}",
derived.end_threshold(),
derived.start_threshold()
);
for end_step in 0..=20u32 {
let raw_end = end_step as f32 / 20.0;
let explicit = derived.clone().with_end_threshold(raw_end);
assert!(
explicit.end_threshold() > 0.0,
"start {raw} / end {raw_end}: end threshold must be strictly positive"
);
assert!(
explicit.end_threshold() <= explicit.start_threshold(),
"start {raw} / end {raw_end}: end {} exceeds start {}",
explicit.end_threshold(),
explicit.start_threshold()
);
}
}
}
#[test]
fn sample_rate_display_matches_its_serde_word() {
assert_eq!(SampleRate::Rate8k.to_string(), "8k");
assert_eq!(SampleRate::Rate16k.to_string(), "16k");
}
#[test]
fn display_pins_every_field_verbatim() {
let options = RunOptions::default()
.with_sample_rate(SampleRate::Rate8k)
.with_start_threshold(0.7)
.with_end_threshold(0.2)
.with_min_run_duration(Duration::from_millis(300))
.with_min_gap_duration(Duration::from_millis(150))
.with_min_gap_at_max_run(Duration::from_millis(90))
.with_max_run_duration(Duration::from_secs(2))
.with_pad(Duration::from_millis(40));
assert_eq!(
options.to_string(),
"sample_rate=8k,start_threshold=0.7,end_threshold=0.2,min_run_duration=300ms,min_gap_duration=150ms,min_gap_at_max_run=90ms,max_run_duration=2s,pad=40ms"
);
}
#[test]
fn display_pins_the_partial_default_document_verbatim() {
let options = RunOptions::default()
.with_sample_rate(SampleRate::Rate8k)
.with_pad(Duration::from_secs(2));
assert_eq!(
options.to_string(),
"sample_rate=8k,start_threshold=0.5,min_run_duration=250ms,min_gap_duration=100ms,min_gap_at_max_run=98ms,pad=2s"
);
}
#[test]
fn run_options_partial_eq_is_structural() {
assert_eq!(RunOptions::default(), RunOptions::default());
let different_threshold = RunOptions::default().with_start_threshold(0.9);
assert_ne!(RunOptions::default(), different_threshold);
let different_pad = RunOptions::default().with_pad(Duration::from_millis(999));
assert_ne!(RunOptions::default(), different_pad);
}
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use std::time::Duration;
use super::{RunOptions, SampleRate};
#[test]
fn options_round_trip_under_the_neutral_field_names() {
let options = RunOptions::default()
.with_min_run_duration(Duration::from_millis(300))
.with_min_gap_duration(Duration::from_millis(150))
.with_min_gap_at_max_run(Duration::from_millis(90))
.with_max_run_duration(Duration::from_millis(5_000))
.with_pad(Duration::from_millis(40));
let json = serde_json::to_string(&options).expect("serialize");
assert!(json.contains("min_run_duration"), "{json}");
assert!(json.contains("min_gap_duration"), "{json}");
assert!(json.contains("min_gap_at_max_run"), "{json}");
assert!(json.contains("max_run_duration"), "{json}");
assert!(json.contains("\"pad\""), "{json}");
let restored: RunOptions = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.min_run_duration(), Duration::from_millis(300));
assert_eq!(restored.min_gap_duration(), Duration::from_millis(150));
assert_eq!(restored.min_gap_at_max_run(), Duration::from_millis(90));
assert_eq!(
restored.max_run_duration(),
Some(Duration::from_millis(5_000))
);
assert_eq!(restored.pad(), Duration::from_millis(40));
}
#[test]
fn out_of_range_thresholds_are_sanitized_on_deserialize() {
for (literal, raw) in [
("-1.0", -1.0_f32),
("5.0", 5.0),
("1e39", f32::INFINITY),
("-1e39", f32::NEG_INFINITY),
] {
let json = format!(r#"{{"start_threshold": {literal}, "end_threshold": {literal}}}"#);
let restored: RunOptions = serde_json::from_str(&json).expect("deserialize");
let built = RunOptions::default()
.with_start_threshold(raw)
.with_end_threshold(raw);
assert_eq!(
restored.start_threshold(),
built.start_threshold(),
"{literal}: start threshold"
);
assert_eq!(
serde_json::to_string(&restored).expect("re-serialize"),
serde_json::to_string(&built).expect("serialize"),
"{literal}: the stored fields must match the setter path"
);
}
}
#[test]
fn default_options_survive_their_own_round_trip() {
let defaults = RunOptions::default();
let json = serde_json::to_string(&defaults).expect("serialize");
assert!(!json.contains("end_threshold"), "{json}");
assert!(!json.contains("max_run_duration"), "{json}");
let restored: RunOptions = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.max_run_duration(), None);
assert_eq!(restored.start_threshold(), defaults.start_threshold());
assert_eq!(restored.end_threshold(), defaults.end_threshold());
assert_eq!(restored.min_run_duration(), defaults.min_run_duration());
assert_eq!(restored.min_gap_duration(), defaults.min_gap_duration());
assert_eq!(restored.min_gap_at_max_run(), defaults.min_gap_at_max_run());
assert_eq!(restored.pad(), defaults.pad());
}
#[test]
fn legacy_speech_field_names_still_deserialize() {
let legacy = r#"{
"sample_rate": "16k",
"start_threshold": 0.5,
"min_speech_duration": "300ms",
"min_silence_duration": "150ms",
"min_silence_at_max_speech": "90ms",
"max_speech_duration": "5s",
"speech_pad": "40ms"
}"#;
let restored: RunOptions = serde_json::from_str(legacy).expect("deserialize 0.1 profile");
assert_eq!(restored.min_run_duration(), Duration::from_millis(300));
assert_eq!(restored.min_gap_duration(), Duration::from_millis(150));
assert_eq!(restored.min_gap_at_max_run(), Duration::from_millis(90));
assert_eq!(
restored.max_run_duration(),
Some(Duration::from_millis(5_000))
);
assert_eq!(restored.pad(), Duration::from_millis(40));
}
#[test]
fn the_threshold_floor_applies_on_the_serde_path_too() {
for (literal, raw) in [
("0.0", 0.0_f32),
("0.005", 0.005),
("-1.0", -1.0),
("-1e39", f32::NEG_INFINITY),
] {
let json = format!(r#"{{"start_threshold": {literal}, "end_threshold": {literal}}}"#);
let restored: RunOptions = serde_json::from_str(&json).expect("deserialize");
let built = RunOptions::default()
.with_start_threshold(raw)
.with_end_threshold(raw);
assert_eq!(
restored.start_threshold(),
RunOptions::MIN_THRESHOLD,
"{literal}: start threshold is lifted to the floor"
);
assert_eq!(
restored.start_threshold(),
built.start_threshold(),
"{literal}: start threshold path parity"
);
assert_eq!(
serde_json::to_string(&restored).expect("re-serialize"),
serde_json::to_string(&built).expect("serialize"),
"{literal}: the stored fields must match the setter path"
);
}
}
#[test]
fn a_full_json_document_round_trips() {
let options = RunOptions::default()
.with_sample_rate(SampleRate::Rate8k)
.with_start_threshold(0.7)
.with_end_threshold(0.2)
.with_min_run_duration(Duration::from_millis(300))
.with_min_gap_duration(Duration::from_millis(150))
.with_min_gap_at_max_run(Duration::from_millis(90))
.with_max_run_duration(Duration::from_secs(2))
.with_pad(Duration::from_millis(40));
let json = serde_json::to_string(&options).expect("serialize");
assert!(json.contains(r#""sample_rate":"8k""#), "{json}");
assert!(json.contains(r#""max_run_duration":"2s""#), "{json}");
let restored: RunOptions = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.sample_rate(), SampleRate::Rate8k);
assert_eq!(restored.start_threshold(), 0.7);
assert_eq!(restored.end_threshold(), 0.2);
assert_eq!(restored.min_run_duration(), Duration::from_millis(300));
assert_eq!(restored.min_gap_duration(), Duration::from_millis(150));
assert_eq!(restored.min_gap_at_max_run(), Duration::from_millis(90));
assert_eq!(restored.max_run_duration(), Some(Duration::from_secs(2)));
assert_eq!(restored.pad(), Duration::from_millis(40));
}
#[test]
fn a_partial_json_document_fills_the_rest_from_defaults() {
let json = r#"{"sample_rate": "8k", "pad": "2s"}"#;
let restored: RunOptions = serde_json::from_str(json).expect("deserialize");
let defaults = RunOptions::default();
assert_eq!(restored.sample_rate(), SampleRate::Rate8k);
assert_eq!(restored.pad(), Duration::from_secs(2));
assert_eq!(restored.start_threshold(), defaults.start_threshold());
assert_eq!(restored.end_threshold(), defaults.end_threshold());
assert_eq!(restored.min_run_duration(), defaults.min_run_duration());
assert_eq!(restored.min_gap_duration(), defaults.min_gap_duration());
assert_eq!(restored.min_gap_at_max_run(), defaults.min_gap_at_max_run());
assert_eq!(restored.max_run_duration(), defaults.max_run_duration());
}
#[test]
fn an_unknown_field_is_refused_by_name() {
let json = r#"{"pda": "40ms"}"#;
let err = serde_json::from_str::<RunOptions>(json).expect_err("unknown field must be refused");
assert!(
err.to_string().contains("pda"),
"error should name the unknown field: {err}"
);
}
}
#[cfg(all(test, feature = "serde"))]
mod toml_tests {
use std::time::Duration;
use super::{RunOptions, SampleRate};
#[test]
fn a_full_toml_document_round_trips() {
let options = RunOptions::default()
.with_sample_rate(SampleRate::Rate8k)
.with_start_threshold(0.7)
.with_end_threshold(0.2)
.with_min_run_duration(Duration::from_millis(300))
.with_min_gap_duration(Duration::from_millis(150))
.with_min_gap_at_max_run(Duration::from_millis(90))
.with_max_run_duration(Duration::from_secs(2))
.with_pad(Duration::from_millis(40));
let document = toml::to_string(&options).expect("serialize");
assert!(document.contains("8k"), "{document}");
assert!(document.contains("2s"), "{document}");
let restored: RunOptions = toml::from_str(&document).expect("deserialize");
assert_eq!(restored.sample_rate(), SampleRate::Rate8k);
assert_eq!(restored.start_threshold(), 0.7);
assert_eq!(restored.end_threshold(), 0.2);
assert_eq!(restored.min_run_duration(), Duration::from_millis(300));
assert_eq!(restored.min_gap_duration(), Duration::from_millis(150));
assert_eq!(restored.min_gap_at_max_run(), Duration::from_millis(90));
assert_eq!(restored.max_run_duration(), Some(Duration::from_secs(2)));
assert_eq!(restored.pad(), Duration::from_millis(40));
}
#[test]
fn a_partial_toml_document_fills_the_rest_from_defaults() {
let document = "sample_rate = \"8k\"\npad = \"2s\"\n";
let restored: RunOptions = toml::from_str(document).expect("deserialize");
let defaults = RunOptions::default();
assert_eq!(restored.sample_rate(), SampleRate::Rate8k);
assert_eq!(restored.pad(), Duration::from_secs(2));
assert_eq!(restored.start_threshold(), defaults.start_threshold());
assert_eq!(restored.end_threshold(), defaults.end_threshold());
assert_eq!(restored.min_run_duration(), defaults.min_run_duration());
assert_eq!(restored.min_gap_duration(), defaults.min_gap_duration());
assert_eq!(restored.min_gap_at_max_run(), defaults.min_gap_at_max_run());
assert_eq!(restored.max_run_duration(), defaults.max_run_duration());
}
#[test]
fn an_unknown_field_is_refused_by_name_too() {
let err = toml::from_str::<RunOptions>("pda = \"40ms\"\n").expect_err("unknown field");
assert!(
err.to_string().contains("pda"),
"error should name the unknown field: {err}"
);
}
}