zuoer 0.3.2

Domain-neutral run segmenter: the Silero-derived hysteresis state machine that turns any frame-probability sequence into contiguous runs with mean/peak aggregates — one instance per class for sound-event detection. Over it sits a backend-agnostic voice-activity-detection (VAD) shell: the VadBackend seam and the Speech* names. The model, inference runtime, and audio I/O live in the backend crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
use core::time::Duration;
use std::fmt;

use crate::error::{Error, Result};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Sample rates this crate supports directly (8 kHz and 16 kHz).
#[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 {
  /// 8 kHz sample rate, which uses smaller chunks and less context.
  #[cfg_attr(feature = "serde", serde(rename = "8k"))]
  Rate8k,
  /// 16 kHz sample rate, which uses larger chunks and more context for better accuracy.
  #[cfg_attr(feature = "serde", serde(rename = "16k"))]
  #[default]
  Rate16k,
}

impl SampleRate {
  /// Returns the sample rate in Hz.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn hz(self) -> u32 {
    match self {
      Self::Rate8k => 8_000,
      Self::Rate16k => 16_000,
    }
  }

  /// Returns the number of samples in the legacy default model chunk for
  /// this sample rate (`256` at 8 kHz, `512` at 16 kHz).
  ///
  /// This is the default frame hop a [`RunSegmenter`](crate::RunSegmenter)
  /// advances by when no backend overrides it — the Silero geometry. A
  /// backend that declares a different hop drives the segmenter through
  /// [`VadBackend::frame_hop`](crate::VadBackend::frame_hop) instead, so
  /// this value is only the fallback, not a fixed contract.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn chunk_samples(self) -> usize {
    match self {
      Self::Rate8k => 256,
      Self::Rate16k => 512,
    }
  }

  /// Create a `SampleRate` from a raw Hz value, returning an error if the rate is not supported.
  #[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 }),
    }
  }
}

/// The same word this sample rate's `serde` face uses (`"8k"` / `"16k"`).
///
/// This spelling is persisted by downstream derivation fingerprints —
/// change it only with a breaking bump.
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)
}

/// Configuration for turning a frame-probability sequence into
/// [`Run`](crate::Run)s.
///
/// Domain-neutral: the same thresholds and durations drive speech
/// segmentation, sound-event detection, or any other "probability
/// sequence to contiguous runs" problem. The speech-flavoured accessor
/// names (`min_speech_duration`, `speech_pad`, ...) are kept as forwarding
/// accessors, so a VAD caller written against [`SpeechOptions`] compiles
/// unchanged; see the correspondence table in the [crate docs](crate).
///
/// # Serde
///
/// With the `serde` feature the fields serialize under their **neutral**
/// names (`min_run_duration`, `min_gap_duration`, `min_gap_at_max_run`,
/// `max_run_duration`, `pad`). Each also accepts its 0.1 speech-flavoured
/// name as a deserialization alias, so configuration profiles persisted by
/// 0.1 still load.
///
/// Deserialization is held to the same contract as the setters:
/// `start_threshold` and `end_threshold` are clamped into
/// [`[MIN_THRESHOLD, 1]`](RunOptions::MIN_THRESHOLD) on the way in
/// exactly as [`Self::set_start_threshold`] / [`Self::set_end_threshold`]
/// clamp them, so a hand-edited profile cannot install a threshold no
/// setter would have stored. Every field the serializer omits is optional
/// on the way back in, so a serialized `RunOptions` always round-trips.
///
/// Unknown keys are refused (`deny_unknown_fields`) rather than silently
/// ignored, by name — a misspelled key in a hand-edited profile (e.g. a
/// `pad` typo'd as `pda`) is a configuration error, not a value this type
/// should resolve to a default.
#[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,
}

/// The speech-flavoured name for [`RunOptions`].
///
/// A plain alias: identical type, identical constructors, identical
/// defaults. Speech-named accessors (`min_speech_duration`, `speech_pad`,
/// ...) forward to their neutral counterparts.
pub type SpeechOptions = RunOptions;

impl Default for RunOptions {
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn default() -> Self {
    Self::new()
  }
}

impl RunOptions {
  /// The lowest threshold these options will store.
  ///
  /// [`start_threshold`](Self::start_threshold) and an explicitly set
  /// [`end_threshold`](Self::end_threshold) are clamped into
  /// `[MIN_THRESHOLD, 1.0]` — on the setter path and, with the `serde`
  /// feature, on the deserialize path alike — and the derived end
  /// threshold bottoms out at the same value. Two properties follow, and
  /// the rest of the crate depends on both:
  ///
  /// - **Every effective threshold is strictly positive.** A frame that
  ///   [`RunSegmenter::push_probability`](crate::RunSegmenter::push_probability)
  ///   canonicalizes to `0.0` therefore satisfies no threshold, which is
  ///   what makes that canonicalization behaviour-preserving rather than
  ///   an exception to reason about.
  /// - **The hysteresis window is never inverted**:
  ///   `end_threshold() <= start_threshold()` for every start threshold
  ///   these options can hold. An inverted window is not cosmetic: a
  ///   frame in the resulting `[start, end)` band satisfies the start
  ///   comparison — which clears the tentative gap and restarts it on the
  ///   same frame — without satisfying the end comparison that sustains
  ///   the run, so the gap age never grows and the run never closes.
  ///
  /// `0.01` rather than an arbitrarily small positive value: it is
  /// already the floor of the derived end threshold (`start - 0.15`,
  /// floored), so the two agree by construction instead of by
  /// coincidence — which is what makes the non-inversion property
  /// provable. It is also the point below which a threshold stops
  /// discriminating: nothing under one percent rejects a frame a
  /// detector would realistically emit.
  pub const MIN_THRESHOLD: f32 = 0.01;

  /// Create a new `RunOptions` with default values.
  #[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(),
      // Matches the upstream silero-vad Python default (0.098 s).
      min_gap_at_max_run: default_min_gap_at_max_run(),
      max_run_duration: None,
      pad: default_pad(),
    }
  }

  /// Returns the sample rate the timeline is measured in.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn sample_rate(&self) -> SampleRate {
    self.sample_rate
  }

  /// Returns the start threshold, which is the minimum probability
  /// required to open a run.
  ///
  /// Always in [`[MIN_THRESHOLD, 1]`](Self::MIN_THRESHOLD) — in
  /// particular, always strictly positive.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn start_threshold(&self) -> f32 {
    self.start_threshold
  }

  /// Returns the effective end threshold.
  ///
  /// If a user-supplied end threshold would break the hysteresis
  /// window, this falls back to the same derived threshold used by the
  /// default configuration so behavior stays stable regardless of
  /// builder call order.
  ///
  /// Always in [`[MIN_THRESHOLD, 1]`](Self::MIN_THRESHOLD) and never
  /// above [`start_threshold`](Self::start_threshold), for every
  /// threshold pair these options can hold.
  #[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)),
    )
  }

  /// Returns the minimum duration of an emitted run.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn min_run_duration(&self) -> Duration {
    self.min_run_duration
  }

  /// Returns the minimum duration of a below-threshold gap required to close a run.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn min_gap_duration(&self) -> Duration {
    self.min_gap_duration
  }

  /// Returns the minimum gap duration used as a preferred split point when the maximum run duration is reached.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn min_gap_at_max_run(&self) -> Duration {
    self.min_gap_at_max_run
  }

  /// Returns the maximum duration of a run before the segmenter force-splits it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn max_run_duration(&self) -> Option<Duration> {
    self.max_run_duration
  }

  /// Returns the amount of padding added to each side of an emitted run.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn pad(&self) -> Duration {
    self.pad
  }

  /// Returns the minimum duration of an emitted run, in samples.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn min_run_samples(&self) -> u64 {
    ms_to_samples(self.min_run_duration, self.sample_rate)
  }

  /// Returns the minimum gap required to close a run, in samples.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn min_gap_samples(&self) -> u64 {
    ms_to_samples(self.min_gap_duration, self.sample_rate)
  }

  /// Returns the minimum gap usable as a preferred split point when the maximum run duration is reached, in samples.
  #[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)
  }

  /// Returns the maximum run duration before force-splitting, in
  /// samples, for the sample rate's legacy default model-chunk hop.
  ///
  /// This assumes the bundled ONNX backend's hop (`chunk_samples` per
  /// probability). A backend that declares a different frame hop force-
  /// splits on that active hop instead: the
  /// [`RunSegmenter`](crate::RunSegmenter) driving
  /// [`detect_speech_with`](crate::detect_speech_with) applies the
  /// backend's [`frame_hop`](crate::VadBackend::frame_hop) automatically,
  /// so those runs honor the backend's hop rather than this method's
  /// chunk assumption.
  #[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)
  }

  /// Returns the maximum run length in samples before force-splitting for
  /// a given frame hop.
  ///
  /// Matches the upstream silero-vad derivation at the active frame hop:
  /// - `- frame_hop` because the split check runs on the next frame after
  ///   the limit is exceeded — the timeline advances by the consuming
  ///   segmenter's hop (the sample rate's model chunk for the ONNX
  ///   backend, but e.g. 4096 for another), not by `chunk_samples`
  /// - `- 2 * pad_samples` because emitted runs pad both the end of the
  ///   current run and the start of the next one
  #[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))
    })
  }

  /// Returns the amount of padding added to each side of an emitted run, in samples.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn pad_samples(&self) -> u64 {
    ms_to_samples(self.pad, self.sample_rate)
  }

  /// Set the sample rate the timeline is measured in.
  #[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
  }

  /// Set the start threshold, the minimum probability required to open a
  /// run. Defaults to `0.5`.
  ///
  /// The value is clamped into
  /// [`[MIN_THRESHOLD, 1]`](Self::MIN_THRESHOLD); a non-finite one
  /// becomes `MIN_THRESHOLD`. A start threshold is therefore always
  /// strictly positive — `0.0` ("every frame opens a run") is not a
  /// configuration these options can express.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_start_threshold(mut self, threshold: f32) -> Self {
    self.set_start_threshold(threshold);
    self
  }

  /// Set the preferred end threshold.
  ///
  /// The stored value is clamped into
  /// [`[MIN_THRESHOLD, 1]`](Self::MIN_THRESHOLD), so it is always
  /// strictly positive. When the threshold is later read via
  /// [`Self::end_threshold`], it is also checked against the current
  /// start threshold. Invalid combinations fall back to the default
  /// derived hysteresis rule even if builder methods are called in a
  /// different order.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_end_threshold(mut self, threshold: f32) -> Self {
    self.set_end_threshold(threshold);
    self
  }

  /// Clear the end threshold, causing it to be automatically derived from the start threshold with a fixed offset.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn clear_end_threshold(mut self) -> Self {
    self.end_threshold = None;
    self
  }

  /// Set the minimum duration of an emitted run.
  #[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
  }

  /// Set the minimum duration of a below-threshold gap required to close a run.
  #[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
  }

  /// Set the minimum gap that can be used as a preferred split point when the maximum run duration is reached.
  #[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
  }

  /// Set the maximum duration of a run before the segmenter force-splits it.
  #[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
  }

  /// Clear the maximum run duration, disabling force-splitting by run length.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn clear_max_run_duration(mut self) -> Self {
    self.max_run_duration = None;
    self
  }

  /// Set the amount of padding added to each side of an emitted run.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_pad(mut self, pad: Duration) -> Self {
    self.set_pad(pad);
    self
  }

  /// Set the sample rate the timeline is measured in.
  #[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
  }

  /// Set the start threshold, the minimum probability required to open a
  /// run. Defaults to `0.5`.
  ///
  /// The value is clamped into
  /// [`[MIN_THRESHOLD, 1]`](Self::MIN_THRESHOLD); a non-finite one
  /// becomes `MIN_THRESHOLD`. A start threshold is therefore always
  /// strictly positive — `0.0` ("every frame opens a run") is not a
  /// configuration these options can express.
  #[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
  }

  /// Set the preferred end threshold.
  ///
  /// The stored value is clamped into
  /// [`[MIN_THRESHOLD, 1]`](Self::MIN_THRESHOLD), so it is always
  /// strictly positive. When the threshold is later read via
  /// [`Self::end_threshold`], it is also checked against the current
  /// start threshold. Invalid combinations fall back to the default
  /// derived hysteresis rule even if builder methods are called in a
  /// different order.
  #[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
  }

  /// Set the minimum duration of an emitted run as a `Duration`.
  /// Sub-second precision is supported according to the precision of `Duration`.
  #[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
  }

  /// Set the minimum duration of a below-threshold gap required to close a run, as a `Duration`.
  /// Sub-second precision is supported according to the precision of `Duration`.
  #[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
  }

  /// Set the minimum gap, as a `Duration`, that can be used as a preferred split point
  /// when the maximum run duration is reached. Sub-second precision is supported according
  /// to the precision of `Duration`.
  #[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
  }

  /// Set the maximum duration of a run, as a `Duration`, before the segmenter
  /// force-splits it. Sub-second precision is supported according to the precision of `Duration`.
  #[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
  }

  /// Set the amount of padding added to each side of an emitted run.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_pad(&mut self, pad: Duration) -> &mut Self {
    self.pad = pad;
    self
  }
}

/// Speech-flavoured shell over the neutral accessors.
///
/// Every method here forwards verbatim to its [`RunOptions`] counterpart —
/// there is no separate state and no behavioural difference. They exist so
/// VAD callers written against 0.1's `SpeechOptions` keep compiling; see
/// the correspondence table in the [crate docs](crate).
impl RunOptions {
  /// Returns the minimum duration of detected speech segments.
  ///
  /// Speech-flavoured name for [`min_run_duration`](Self::min_run_duration).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn min_speech_duration(&self) -> Duration {
    self.min_run_duration()
  }

  /// Returns the minimum duration of silence required to close a detected speech segment.
  ///
  /// Speech-flavoured name for [`min_gap_duration`](Self::min_gap_duration).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn min_silence_duration(&self) -> Duration {
    self.min_gap_duration()
  }

  /// Returns the minimum silence duration used as a preferred split point when the maximum speech duration is reached.
  ///
  /// Speech-flavoured name for [`min_gap_at_max_run`](Self::min_gap_at_max_run).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn min_silence_at_max_speech(&self) -> Duration {
    self.min_gap_at_max_run()
  }

  /// Returns the maximum duration of a speech segment before the segmenter force-splits it.
  ///
  /// Speech-flavoured name for [`max_run_duration`](Self::max_run_duration).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn max_speech_duration(&self) -> Option<Duration> {
    self.max_run_duration()
  }

  /// Returns the amount of padding to add around detected speech segments.
  ///
  /// Speech-flavoured name for [`pad`](Self::pad).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn speech_pad(&self) -> Duration {
    self.pad()
  }

  /// Returns the minimum duration of detected speech segments, in samples.
  ///
  /// Speech-flavoured name for [`min_run_samples`](Self::min_run_samples).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn min_speech_samples(&self) -> u64 {
    self.min_run_samples()
  }

  /// Returns the minimum duration of silence required to close a detected speech segment, in samples.
  ///
  /// Speech-flavoured name for [`min_gap_samples`](Self::min_gap_samples).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn min_silence_samples(&self) -> u64 {
    self.min_gap_samples()
  }

  /// Returns the minimum silence duration used as a preferred split point when max speech duration is reached, in samples.
  ///
  /// Speech-flavoured name for [`min_gap_at_max_run_samples`](Self::min_gap_at_max_run_samples).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn min_silence_at_max_speech_samples(&self) -> u64 {
    self.min_gap_at_max_run_samples()
  }

  /// Returns the maximum speech duration before force-splitting, in samples.
  ///
  /// Speech-flavoured name for [`max_run_samples`](Self::max_run_samples).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn max_speech_samples(&self) -> Option<u64> {
    self.max_run_samples()
  }

  /// Speech-flavoured name for [`max_run_samples_for_frame`](Self::max_run_samples_for_frame).
  ///
  /// Crate-internal, so the only caller is the pinned options test; gated
  /// on `test` rather than carrying a blanket `dead_code` allow.
  #[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)
  }

  /// Returns the amount of padding to add around detected speech segments, in samples.
  ///
  /// Speech-flavoured name for [`pad_samples`](Self::pad_samples).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn speech_pad_samples(&self) -> u64 {
    self.pad_samples()
  }

  /// Set the minimum duration of detected speech segments.
  ///
  /// Speech-flavoured name for [`with_min_run_duration`](Self::with_min_run_duration).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_min_speech_duration(self, duration: Duration) -> Self {
    self.with_min_run_duration(duration)
  }

  /// Set the minimum duration of silence required to close a detected speech segment.
  ///
  /// Speech-flavoured name for [`with_min_gap_duration`](Self::with_min_gap_duration).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_min_silence_duration(self, duration: Duration) -> Self {
    self.with_min_gap_duration(duration)
  }

  /// Set the minimum silence duration that can be used as a preferred split point when maximum speech duration is reached.
  ///
  /// Speech-flavoured name for [`with_min_gap_at_max_run`](Self::with_min_gap_at_max_run).
  #[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)
  }

  /// Set the maximum duration of a speech segment before the segmenter force-splits it.
  ///
  /// Speech-flavoured name for [`with_max_run_duration`](Self::with_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)
  }

  /// Clear the maximum speech duration, disabling force-splitting by segment length.
  ///
  /// Speech-flavoured name for [`clear_max_run_duration`](Self::clear_max_run_duration).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn clear_max_speech_duration(self) -> Self {
    self.clear_max_run_duration()
  }

  /// Set the amount of padding to add around detected speech segments.
  ///
  /// Speech-flavoured name for [`with_pad`](Self::with_pad).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_speech_pad(self, pad: Duration) -> Self {
    self.with_pad(pad)
  }

  /// Set the minimum duration of detected speech segments.
  ///
  /// Speech-flavoured name for [`set_min_run_duration`](Self::set_min_run_duration).
  #[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)
  }

  /// Set the minimum duration of silence required to close a detected speech segment.
  ///
  /// Speech-flavoured name for [`set_min_gap_duration`](Self::set_min_gap_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)
  }

  /// Set the minimum silence duration that can be used as a preferred split point
  /// when maximum speech duration is reached.
  ///
  /// Speech-flavoured name for [`set_min_gap_at_max_run`](Self::set_min_gap_at_max_run).
  #[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)
  }

  /// Set the maximum duration of a speech segment before the segmenter force-splits it.
  ///
  /// Speech-flavoured name for [`set_max_run_duration`](Self::set_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)
  }

  /// Set the amount of padding to add around detected speech segments.
  ///
  /// Speech-flavoured name for [`set_pad`](Self::set_pad).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_speech_pad(&mut self, pad: Duration) -> &mut Self {
    self.set_pad(pad)
  }
}

/// A canonical, one-line rendering of every field: `key=value` pairs in
/// declaration order, joined by `,`. `Duration` fields are spelled the
/// way `humantime` renders them (`pad=2s`), and `sample_rate` delegates
/// to [`SampleRate`]'s own `Display` (`sample_rate=8k`). `end_threshold`
/// and `max_run_duration` are only `Some` sometimes; when `None` the key
/// is omitted entirely rather than printed as a placeholder — the same
/// omission the `serde` face's `skip_serializing_if` applies to both
/// fields.
///
/// This spelling is persisted by downstream derivation fingerprints —
/// change it only with a breaking bump.
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
  }
}

/// Clamp a threshold into the permitted `[MIN_THRESHOLD, 1.0]` range.
///
/// A non-finite threshold has no ordering against frame probabilities at
/// all, so it becomes the floor — the least permissive interpretation of
/// "unusable input" that is still a threshold. See
/// [`RunOptions::MIN_THRESHOLD`] for why the floor is strictly positive.
#[inline]
const fn sanitize_threshold(value: f32) -> f32 {
  if value.is_finite() {
    value.clamp(RunOptions::MIN_THRESHOLD, 1.0)
  } else {
    RunOptions::MIN_THRESHOLD
  }
}

/// Sanitize a threshold arriving through `Deserialize`.
///
/// The derived `Deserialize` writes fields directly and never calls
/// [`RunOptions::set_start_threshold`], so without this a persisted
/// profile could install a zero, negative, or non-finite threshold that
/// no setter would have stored. Deserialization is an input boundary
/// like any other; it applies the same [`sanitize_threshold`] the
/// setters do, so both paths store the same value for the same input.
#[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)?))
}

/// The [`Option`] form of [`deserialize_threshold`], for the
/// [`RunOptions::set_end_threshold`] field.
///
/// A `deserialize_with` on an `Option` field suppresses serde's implicit
/// "a missing `Option` field is `None`" rule, so the field carries an
/// explicit `#[serde(default)]` alongside this.
#[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))
}

/// The end threshold derived from a start threshold when none was set.
///
/// A fixed `0.15` of hysteresis below the start threshold, floored at
/// [`RunOptions::MIN_THRESHOLD`]. Because the start threshold shares that
/// floor, the result is never above it: for `start >= 0.16` the
/// subtraction wins and is strictly below `start`, and for a smaller
/// `start` the floor wins and equals `MIN_THRESHOLD <= start`.
#[inline]
const fn default_end_threshold(start_threshold: f32) -> f32 {
  sanitize_threshold((sanitize_threshold(start_threshold) - 0.15).max(RunOptions::MIN_THRESHOLD))
}

/// Resolve the end threshold actually used, rejecting a configured value
/// that would invert the hysteresis window in favour of the derived one.
///
/// Both branches return a value at most `start_threshold` and at least
/// [`RunOptions::MIN_THRESHOLD`], so the window is never inverted and the
/// end threshold is never zero, whatever the caller supplied and in
/// whatever builder order.
#[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() {
    // The legacy default frame hop. Context geometry (32/64) is
    // Session-specific and lives with the Silero backend, not here.
    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));
    // The public getter assumes the sample rate's native model chunk
    // (512 at 16 kHz) as the one-frame lookahead.
    assert_eq!(options.max_speech_samples_for_frame(512), Some(14_528));
    // A backend that declares a larger frame subtracts THAT frame for the
    // lookahead, not the 512-sample chunk: 16_000 − 4_096 − 2·480 = 10_944.
    assert_eq!(options.max_speech_samples_for_frame(4_096), Some(10_944));
  }

  /// Every threshold `RunOptions` stores is strictly positive. This is
  /// what makes `push_probability`'s canonicalization behaviour-
  /// preserving: a frame canonicalized to `0.0` is below every permitted
  /// threshold, so it can neither open nor sustain a run.
  ///
  /// Mutation (clamp into `[0.0, 1.0]` as before): `0.0`, `-1.0`,
  /// `-inf` and `NaN` all store `0.0`. Red.
  #[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"
      );
    }
  }

  /// The hysteresis window is never inverted: for EVERY start threshold
  /// the setters permit, with the end threshold derived or explicitly
  /// set anywhere in the range, `end_threshold() <= start_threshold()`
  /// and both are strictly positive.
  ///
  /// A start threshold below the derived end threshold's `0.01` floor is
  /// what inverts it, and an inverted window is not cosmetic: a frame in
  /// the `[start, end)` band satisfies the start comparison — which
  /// clears the tentative gap and restarts it on the same frame —
  /// without satisfying the end comparison that sustains the run, so the
  /// gap age never grows and the run never closes.
  ///
  /// Mutation (drop the floor, or set it below `default_end_threshold`'s
  /// own `0.01`): every start threshold under `0.01` derives an end
  /// threshold above it. Red.
  #[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()
        );
      }
    }
  }

  /// `SampleRate::to_string()` is the same word its `serde` face uses.
  /// This is the spelling `RunOptions`'s own `Display` embeds for its
  /// `sample_rate` key, and downstream derivation fingerprints persist
  /// it verbatim.
  ///
  /// Mutation: spell a variant differently (`"8000hz"`, `"Rate8k"`, a
  /// swapped pairing, ...) -> red.
  #[test]
  fn sample_rate_display_matches_its_serde_word() {
    assert_eq!(SampleRate::Rate8k.to_string(), "8k");
    assert_eq!(SampleRate::Rate16k.to_string(), "16k");
  }

  /// Every field, explicitly set — the same values as the full JSON/TOML
  /// round-trip fixtures — pins the exact `Display` string: `key=value`
  /// in declaration order, joined by `,`, durations spelled the way
  /// `humantime` renders them, `sample_rate` delegating to
  /// [`SampleRate`]'s own `Display`.
  ///
  /// Mutation: reorder two fields, change the separator, or format a
  /// duration by hand instead of via `humantime` -> red.
  #[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"
    );
  }

  /// A partial/default document — only `sample_rate` and `pad` set away
  /// from `RunOptions::default()`, the same two fields the partial
  /// JSON/TOML fixtures use — omits `end_threshold` and
  /// `max_run_duration` entirely rather than printing a placeholder for
  /// their `None` state, matching the `serde` face's own
  /// `skip_serializing_if` omission for both fields.
  ///
  /// Mutation: print `None` as `end_threshold=` or `max_run_duration=`,
  /// or drop the omission so both keys always appear -> red.
  #[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"
    );
  }

  /// `RunOptions` derives `PartialEq` structurally: two defaults compare
  /// equal, and changing a single knob of any field type it holds
  /// (`f32` via `start_threshold`, `Duration` via `pad`) makes the two
  /// values compare unequal. This is what lets a downstream type that
  /// embeds `RunOptions` derive `PartialEq` itself instead of
  /// hand-writing equality for a type it does not own.
  ///
  /// Mutation: drop `PartialEq` from the derive list -> does not
  /// compile. Hand-write an `impl PartialEq` that skips a field -> the
  /// corresponding "differs after one knob changes" assertion goes
  /// green when it should stay red. A structural derive cannot make
  /// that mistake.
  #[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));
  }

  /// Deserialization must agree with the setters. `set_start_threshold` /
  /// `set_end_threshold` sanitize into `[0, 1]`, so a persisted profile
  /// carrying an out-of-range or non-finite threshold must not produce an
  /// options value the setter path could not have produced.
  ///
  /// The re-serialized form is compared, not just the accessors:
  /// `end_threshold()` sanitizes on read, so a raw stored value hides
  /// behind the accessor and only surfaces on the next round-trip.
  ///
  /// Mutation: drop the `deserialize_with` sanitizers -> `-1.0` lands in
  /// `start_threshold` verbatim, and `end_threshold` re-serializes as
  /// `-1.0` (or as `null`, for a non-finite value JSON cannot carry).
  /// Red.
  #[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"
      );
    }
  }

  /// Every field the serializer omits has to be optional on the way back
  /// in. `end_threshold` and `max_run_duration` are both
  /// `skip_serializing_if = "Option::is_none"` and both carry a
  /// `deserialize_with` (the threshold sanitizer and
  /// `humantime_serde::option`), which suppresses serde's implicit
  /// "a missing `Option` field is `None`" rule — so without an explicit
  /// `default` the DEFAULT options value does not survive its own
  /// round-trip.
  ///
  /// Mutation: drop either `default` -> `missing field` on deserialize.
  /// Red.
  #[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() {
    // A 0.1-era profile: every duration under its speech-flavoured name.
    // Mutation: drop the `alias` attributes -> `unknown field` -> red.
    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));
  }

  /// The strictly-positive floor is a property of the stored value, not
  /// of the setter, so it has to hold on the deserialize path too — path
  /// parity is what the sanitizers exist for.
  ///
  /// Mutation (floor only in the setters): a persisted `0.0` installs a
  /// zero start threshold the setters cannot produce. Red.
  #[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"
      );
    }
  }

  /// A full profile — every field given explicitly, including
  /// `sample_rate`, `start_threshold` and `end_threshold`, which the
  /// default/partial round-trip tests never disturb — round-trips
  /// exactly through JSON. `max_run_duration` carries the literal
  /// humantime form the crate's docs advertise (`"2s"`).
  #[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));
  }

  /// A partial profile — two of eight fields given, the rest left to
  /// `#[serde(default)]` — round-trips through JSON: the given fields
  /// take their document value and the rest match
  /// `RunOptions::default()`, not zero or `None` by coincidence. The
  /// given `pad` is the crate docs' own humantime example, `"2s"`.
  #[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());
  }

  /// An unknown key is refused, by name, rather than silently ignored.
  /// This is the gap the sound-events household's own options census
  /// named against this crate (`this crate does not forward
  /// zuoer/serde`, `no document face at all`): a typo'd key in a
  /// hand-edited profile is a configuration error, not a value this
  /// type should resolve to a default.
  ///
  /// Mutation: drop the container's `deny_unknown_fields` -> the typo'd
  /// key is silently dropped instead of refused, and `expect_err` panics.
  /// Red.
  #[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};

  /// The same full profile as the JSON round trip
  /// ([`super::serde_tests::a_full_json_document_round_trips`]), this
  /// time through TOML: the `serde` feature's document face is meant to
  /// serve any consumer format built on `serde`, not JSON alone.
  #[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));
  }

  /// A partial TOML document — two of eight keys given, hand-written the
  /// way a deployment's config file would be — fills the rest from
  /// `RunOptions::default()`, the same contract the JSON partial test
  /// holds it to.
  #[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());
  }

  /// `deny_unknown_fields` refuses by name under TOML too. The guarantee
  /// is `serde`-level, not JSON-specific, but JSON and TOML report an
  /// unknown field through different `Deserializer` impls, so this checks
  /// the actual behaviour rather than assuming it carries over.
  #[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}"
    );
  }
}