timestretch 0.5.0

Pure Rust audio time stretching library optimized for EDM
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
//! Persistent transient-event scheduling for deterministic stream processing.

use crate::core::fft::COMPLEX_ZERO;
use crate::core::window::{generate_window, WindowType};
use rustfft::{num_complex::Complex, FftPlanner};
use std::sync::Arc;

/// Sub-bass/low-band split (Hz) used for reset-mask routing.
const BAND_SUB_END_HZ: f64 = 100.0;
/// Low/mid split (Hz) used for reset-mask routing.
const BAND_LOW_END_HZ: f64 = 500.0;
/// Mid/high split (Hz) used for reset-mask routing.
const BAND_MID_END_HZ: f64 = 4000.0;
/// Reference configuration the frame-count tunings below were calibrated at:
/// 4096 FFT / 1024 hop / 44.1 kHz. Time-based derivations reproduce the
/// legacy per-frame values exactly at this configuration and scale them to
/// equivalent absolute time elsewhere (e.g. 1024/256 low-latency streaming).
const REFERENCE_FFT_SIZE: f64 = 4096.0;

/// Adaptation time constant for the spectral-flux statistics EMA.
///
/// Chosen so the per-frame alpha `1 - exp(-frame_secs / T)` equals the
/// legacy `FLUX_EMA_ALPHA = 0.2` at the reference hop (1024 / 44.1 kHz,
/// `T = frame_secs / ln(1.25)`).
const FLUX_STAT_TIME_SECS: f64 = 0.104058;
/// Sigma multiplier for adaptive spectral-flux threshold.
const FLUX_THRESHOLD_SIGMA: f64 = 2.5;
/// Required jump versus previous frame flux to classify a transient.
const FLUX_SPIKE_RATIO: f64 = 1.6;
/// Absolute guard to suppress near-silence false triggers.
const FLUX_ABS_MIN: f64 = 1e-4;
/// Extra emphasis on high-band flux.
const FLUX_HIGH_WEIGHT: f64 = 1.25;
/// Extra trigger threshold per overlap window when modulation already holds
/// low bands phase-locked.
const FLUX_MODULATION_THRESHOLD_SCALE_STEP: f64 = 0.08;
/// Extra spike-ratio requirement per overlap window during modulation holds.
const FLUX_MODULATION_SPIKE_RATIO_STEP: f64 = 0.05;
/// Minimum upper-band share required before low-band-suppressed modulation
/// converts a detected event into a mid/high phase reset.
const FLUX_MODULATION_MIN_UPPER_SHARE: f64 = 0.55;
/// Minimum upper-band energy relative to the adaptive threshold before
/// modulation-hold events may reset only the upper bands.
const FLUX_MODULATION_MIN_UPPER_THRESHOLD_SHARE: f64 = 0.35;
/// Required upper-band dominance over held low bands before modulation-hold
/// mode turns a seam-side event into a fresh upper-band reset.
const FLUX_MODULATION_MIN_UPPER_DOMINANCE: f64 = 1.25;
/// Number of flux frames to observe before trigger checks.
///
/// Deliberately a frame count, not time-derived: warmup bootstraps the flux
/// mean/variance statistics, which need a minimum number of observations
/// regardless of hop duration. Keeping it small also bounds how much audio
/// after a stream start or seek rebuild goes without transient resets
/// (~17 ms at 256 hop, ~70 ms at the reference 1024 hop).
const FLUX_WARMUP_FRAMES: usize = 3;
/// Maximum analysis frames scanned per scheduler pass.
const FLUX_MAX_SCAN_FRAMES: usize = 8;
/// Minimum cooldown time after an event to avoid duplicate resets.
///
/// 2 frames at the reference hop (~46 ms); scales to 8 frames at 256 hop so
/// the cooldown still covers a kick's decay at low-latency configurations.
const FLUX_RESET_COOLDOWN_SECS: f64 = 0.0464;
/// Floor for the derived minimum cooldown frame count.
const FLUX_RESET_COOLDOWN_MIN_FRAMES: usize = 2;
/// Base overlap windows used by tests when verifying modulation cooldown scaling.
#[cfg(test)]
const MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS: usize = 2;

#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct TransientSchedulerStats {
    pub(crate) events_detected_total: u64,
    pub(crate) reset_band_counts_total: [u64; 4],
}

/// Stateful spectral-flux transient scheduler.
///
/// The scheduler consumes stereo interleaved analysis snapshots (L/R),
/// computes a stereo-coherent transient score from per-channel magnitudes, and
/// emits a per-band phase-reset
/// mask (`[sub_bass, low, mid, high]`) when a transient event is detected.
pub(crate) struct TransientEventScheduler {
    fft_size: usize,
    hop_size: usize,
    sample_rate: u32,
    max_frames: usize,
    num_bins: usize,
    sub_end_bin: usize,
    low_end_bin: usize,
    mid_end_bin: usize,
    fft_forward: Arc<dyn rustfft::Fft<f32>>,
    fft_scratch: Vec<Complex<f32>>,
    fft_buffer: Vec<Complex<f32>>,
    prev_magnitudes: Vec<f32>,
    window: Vec<f32>,
    left_buffer: Vec<f32>,
    right_buffer: Vec<f32>,
    left_magnitudes: Vec<f32>,
    mean_flux: f64,
    var_flux: f64,
    prev_flux: f64,
    warmup_frames: usize,
    cooldown_frames: usize,
    last_processed_frame_start: Option<usize>,
    stats: TransientSchedulerStats,
    /// Initial warmup frame count ([`FLUX_WARMUP_FRAMES`]).
    warmup_frames_initial: usize,
    /// Derived minimum cooldown frames ([`FLUX_RESET_COOLDOWN_SECS`]).
    min_cooldown_frames: usize,
    /// Derived per-frame statistics EMA alpha ([`FLUX_STAT_TIME_SECS`]).
    flux_ema_alpha: f64,
    /// Modulation-hold per-window threshold step, scaled by
    /// `fft_size / 4096` so the desensitization ceiling stays constant when
    /// the processor's time-based window cap grows at smaller FFT sizes.
    modulation_threshold_scale_step: f64,
    /// Modulation-hold per-window spike-ratio step, scaled like
    /// [`Self::modulation_threshold_scale_step`].
    modulation_spike_ratio_step: f64,
}

impl TransientEventScheduler {
    pub(crate) fn new(
        fft_size: usize,
        hop_size: usize,
        sample_rate: u32,
        max_frames: usize,
    ) -> Self {
        let mut planner = FftPlanner::new();
        let fft_forward = planner.plan_fft_forward(fft_size);
        let num_bins = fft_size / 2 + 1;
        let bin_hz = sample_rate as f64 / fft_size as f64;
        let sub_end_bin =
            ((BAND_SUB_END_HZ / bin_hz).floor() as usize).min(num_bins.saturating_sub(1));
        let low_end_bin =
            ((BAND_LOW_END_HZ / bin_hz).floor() as usize).min(num_bins.saturating_sub(1));
        let mid_end_bin =
            ((BAND_MID_END_HZ / bin_hz).floor() as usize).min(num_bins.saturating_sub(1));

        // Derive temporal tunings (cooldown, statistics adaptation) from
        // absolute time so the scheduler behaves the same across hop sizes.
        // At the reference 4096/1024/44.1kHz configuration these reproduce
        // the legacy constants exactly (min cooldown 2, alpha 0.2). Warmup
        // stays a frame count — it bootstraps statistics, not a time span.
        let frame_secs = hop_size.max(1) as f64 / sample_rate.max(1) as f64;
        let warmup_frames_initial = FLUX_WARMUP_FRAMES;
        let min_cooldown_frames = ((FLUX_RESET_COOLDOWN_SECS / frame_secs).ceil() as usize)
            .max(FLUX_RESET_COOLDOWN_MIN_FRAMES);
        let flux_ema_alpha = 1.0 - (-frame_secs / FLUX_STAT_TIME_SECS).exp();
        let fft_scale = fft_size as f64 / REFERENCE_FFT_SIZE;
        let modulation_threshold_scale_step = FLUX_MODULATION_THRESHOLD_SCALE_STEP * fft_scale;
        let modulation_spike_ratio_step = FLUX_MODULATION_SPIKE_RATIO_STEP * fft_scale;

        Self {
            fft_size,
            hop_size,
            sample_rate,
            max_frames,
            num_bins,
            sub_end_bin,
            low_end_bin,
            mid_end_bin,
            fft_scratch: vec![COMPLEX_ZERO; fft_forward.get_inplace_scratch_len()],
            fft_forward,
            fft_buffer: vec![COMPLEX_ZERO; fft_size],
            prev_magnitudes: vec![0.0; num_bins],
            window: generate_window(WindowType::Hann, fft_size),
            left_buffer: Vec::with_capacity(max_frames),
            right_buffer: Vec::with_capacity(max_frames),
            left_magnitudes: vec![0.0; num_bins],
            mean_flux: 0.0,
            var_flux: 0.0,
            prev_flux: 0.0,
            warmup_frames: warmup_frames_initial,
            cooldown_frames: 0,
            last_processed_frame_start: None,
            stats: TransientSchedulerStats::default(),
            warmup_frames_initial,
            min_cooldown_frames,
            flux_ema_alpha,
            modulation_threshold_scale_step,
            modulation_spike_ratio_step,
        }
    }

    pub(crate) fn reset(&mut self) {
        self.prev_magnitudes.fill(0.0);
        self.mean_flux = 0.0;
        self.var_flux = 0.0;
        self.prev_flux = 0.0;
        self.warmup_frames = self.warmup_frames_initial;
        self.cooldown_frames = 0;
        self.left_buffer.clear();
        self.right_buffer.clear();
        self.last_processed_frame_start = None;
        self.stats = TransientSchedulerStats::default();
    }

    #[inline]
    fn reset_cooldown_frames(&self, modulation_overlap_windows: usize) -> usize {
        if self.hop_size == 0 {
            return self.min_cooldown_frames;
        }

        // Hold the scheduler through the full overlapping-window footprint of
        // a detected event so the same click is not reclassified as a fresh
        // transient on the next few callback snapshots.
        let overlap_frames = self.fft_size.div_ceil(self.hop_size).saturating_sub(1);
        let mut cooldown_frames = self.min_cooldown_frames.max(overlap_frames);

        if modulation_overlap_windows > 0 {
            // Cross-unity/near-unity modulation already keeps low bands phase
            // locked. Extend the accepted-event hold so the same broadband hit
            // does not retrigger a second upper-band-only reset while the
            // modulation seam is still draining through overlapped callbacks.
            cooldown_frames = cooldown_frames
                .saturating_add(overlap_frames.saturating_mul(modulation_overlap_windows));
        }

        cooldown_frames
    }

    #[inline]
    fn rejected_modulation_hold_cooldown_frames(&self, modulation_overlap_windows: usize) -> usize {
        if self.hop_size == 0 {
            return 1;
        }

        // Rejected low-dominant events should still hold through the currently
        // overlapping callback footprint plus almost one more overlap window so
        // the same physical onset is not re-evaluated as a fresh upper-band
        // reset right as the overlap tail drains through adjacent callbacks.
        let overlap_frames = self
            .fft_size
            .div_ceil(self.hop_size)
            .saturating_sub(1)
            .max(1);
        overlap_frames
            .saturating_mul(modulation_overlap_windows.max(1))
            .saturating_add(overlap_frames.saturating_sub(1))
    }

    #[inline]
    fn trigger_requirements(
        &self,
        suppress_low_bands: bool,
        modulation_overlap_windows: usize,
    ) -> (f64, f64) {
        if !suppress_low_bands || modulation_overlap_windows == 0 {
            return (1.0, FLUX_SPIKE_RATIO);
        }

        let overlap_windows = modulation_overlap_windows as f64;
        let threshold_scale = 1.0 + self.modulation_threshold_scale_step * overlap_windows;
        let spike_ratio =
            FLUX_SPIKE_RATIO * (1.0 + self.modulation_spike_ratio_step * overlap_windows);

        (threshold_scale, spike_ratio)
    }

    #[inline]
    fn should_accept_upper_band_reset_during_modulation_hold(
        &self,
        sub_flux: f64,
        low_flux: f64,
        mid_flux: f64,
        high_flux: f64,
        threshold: f64,
    ) -> bool {
        let upper_flux = mid_flux + high_flux;
        let total_flux = sub_flux + low_flux + upper_flux;
        if total_flux <= 0.0 {
            return false;
        }

        let upper_share = upper_flux / total_flux;
        let upper_strength = upper_flux / threshold.max(1e-12);
        let held_low_flux = sub_flux + low_flux;
        let upper_dominance = upper_flux / held_low_flux.max(1e-12);
        upper_share >= FLUX_MODULATION_MIN_UPPER_SHARE
            && upper_strength >= FLUX_MODULATION_MIN_UPPER_THRESHOLD_SHARE
            && upper_dominance >= FLUX_MODULATION_MIN_UPPER_DOMINANCE
    }

    /// Detects a transient event from stereo interleaved input and returns a
    /// per-band reset mask when detected.
    ///
    /// The input may be larger than the configured scheduler capacity; in that
    /// case, only the most-recent `max_frames` region is analyzed.
    pub(crate) fn detect_stereo_reset_mask(
        &mut self,
        interleaved_stereo: &[f32],
        frame_origin: usize,
        suppress_low_bands: bool,
        modulation_overlap_windows: usize,
    ) -> Option<[bool; 4]> {
        if self.hop_size == 0 || interleaved_stereo.len() < self.fft_size.saturating_mul(2) {
            return None;
        }

        let mut frames = interleaved_stereo.len() / 2;
        if frames < self.fft_size.saturating_add(self.hop_size) {
            return None;
        }

        let mut start_sample = 0usize;
        let mut absolute_frame_origin = frame_origin;
        if frames > self.max_frames {
            let drop_frames = frames - self.max_frames;
            start_sample = drop_frames.saturating_mul(2);
            frames = self.max_frames;
            absolute_frame_origin = absolute_frame_origin.saturating_add(drop_frames);
        }
        let stereo = &interleaved_stereo[start_sample..start_sample + frames.saturating_mul(2)];

        if self.left_buffer.capacity() < frames || self.right_buffer.capacity() < frames {
            return None;
        }
        self.left_buffer.clear();
        self.right_buffer.clear();
        for frame in stereo.chunks_exact(2) {
            self.left_buffer.push(frame[0]);
            self.right_buffer.push(frame[1]);
        }

        self.scan_frames(
            frames,
            absolute_frame_origin,
            true,
            suppress_low_bands,
            modulation_overlap_windows,
        )
    }

    /// Detects a transient event from a mono input snapshot and returns a
    /// per-band reset mask when detected.
    ///
    /// Mirrors [`Self::detect_stereo_reset_mask`]; all flux statistics,
    /// cooldowns, and mask routing are shared, only the per-frame magnitude
    /// source differs (single channel instead of an L/R average).
    pub(crate) fn detect_mono_reset_mask(
        &mut self,
        mono: &[f32],
        frame_origin: usize,
        suppress_low_bands: bool,
        modulation_overlap_windows: usize,
    ) -> Option<[bool; 4]> {
        if self.hop_size == 0 || mono.len() < self.fft_size {
            return None;
        }

        let mut frames = mono.len();
        if frames < self.fft_size.saturating_add(self.hop_size) {
            return None;
        }

        let mut start_sample = 0usize;
        let mut absolute_frame_origin = frame_origin;
        if frames > self.max_frames {
            let drop_frames = frames - self.max_frames;
            start_sample = drop_frames;
            frames = self.max_frames;
            absolute_frame_origin = absolute_frame_origin.saturating_add(drop_frames);
        }

        if self.left_buffer.capacity() < frames {
            return None;
        }
        self.left_buffer.clear();
        self.left_buffer
            .extend_from_slice(&mono[start_sample..start_sample + frames]);

        self.scan_frames(
            frames,
            absolute_frame_origin,
            false,
            suppress_low_bands,
            modulation_overlap_windows,
        )
    }

    /// Shared per-frame flux scan over the prepared channel buffers.
    ///
    /// Reads `left_buffer` (and `right_buffer` when `stereo`) and runs the
    /// incremental spectral-flux transient detection, returning the combined
    /// reset mask for the first accepted event, if any.
    fn scan_frames(
        &mut self,
        frames: usize,
        absolute_frame_origin: usize,
        stereo: bool,
        suppress_low_bands: bool,
        modulation_overlap_windows: usize,
    ) -> Option<[bool; 4]> {
        let num_frames = (frames - self.fft_size) / self.hop_size + 1;
        if num_frames < 2 {
            return None;
        }

        // We only need recent analysis frames to schedule phase resets in the
        // deterministic stream path.
        let start_frame = num_frames.saturating_sub(FLUX_MAX_SCAN_FRAMES);
        let mut reset_mask = [false; 4];

        for frame_idx in start_frame..num_frames {
            let start = frame_idx * self.hop_size;
            let absolute_frame_start = absolute_frame_origin.saturating_add(start);
            if let Some(last_start) = self.last_processed_frame_start {
                // Require one full-hop of absolute forward progress before a
                // new scheduler pass can rescan the same transient region.
                // This prevents sub-hop-overlapped callbacks from burning the
                // cooldown on nearly identical FFT windows.
                if absolute_frame_start < last_start.saturating_add(self.hop_size) {
                    continue;
                }
            }

            let left_frame = &self.left_buffer[start..start + self.fft_size];

            for (dst, (&sample, &window)) in self
                .fft_buffer
                .iter_mut()
                .zip(left_frame.iter().zip(self.window.iter()))
            {
                *dst = Complex::new(sample * window, 0.0);
            }
            self.fft_forward
                .process_with_scratch(&mut self.fft_buffer, &mut self.fft_scratch);

            if stereo {
                for bin in 1..self.num_bins {
                    self.left_magnitudes[bin] = self.fft_buffer[bin].norm();
                }

                let right_frame = &self.right_buffer[start..start + self.fft_size];
                for (dst, (&sample, &window)) in self
                    .fft_buffer
                    .iter_mut()
                    .zip(right_frame.iter().zip(self.window.iter()))
                {
                    *dst = Complex::new(sample * window, 0.0);
                }
                self.fft_forward
                    .process_with_scratch(&mut self.fft_buffer, &mut self.fft_scratch);
            }

            let mut sub_flux = 0.0f64;
            let mut low_flux = 0.0f64;
            let mut mid_flux = 0.0f64;
            let mut high_flux = 0.0f64;

            for bin in 1..self.num_bins {
                let mag = if stereo {
                    // Average per-channel magnitudes. This avoids mid-channel
                    // cancellation for anti-phase/wide stereo transients.
                    (self.left_magnitudes[bin] + self.fft_buffer[bin].norm()) * 0.5
                } else {
                    self.fft_buffer[bin].norm()
                };
                let diff = (mag - self.prev_magnitudes[bin]).max(0.0) as f64;
                if bin <= self.sub_end_bin {
                    sub_flux += diff;
                } else if bin <= self.low_end_bin {
                    low_flux += diff;
                } else if bin <= self.mid_end_bin {
                    mid_flux += diff;
                } else {
                    high_flux += diff;
                }
                self.prev_magnitudes[bin] = mag;
            }

            let flux = sub_flux * 0.8 + low_flux + mid_flux + high_flux * FLUX_HIGH_WEIGHT;
            if self.warmup_frames > 0 {
                self.update_flux_stats(flux);
                self.prev_flux = flux;
                self.warmup_frames = self.warmup_frames.saturating_sub(1);
                continue;
            }

            let sigma = self.var_flux.max(0.0).sqrt();
            let (threshold_scale, spike_ratio) =
                self.trigger_requirements(suppress_low_bands, modulation_overlap_windows);
            let threshold = (self.mean_flux + FLUX_THRESHOLD_SIGMA * sigma) * threshold_scale;
            let is_transient = flux > threshold
                && flux > self.prev_flux.max(FLUX_ABS_MIN) * spike_ratio
                && flux > FLUX_ABS_MIN;

            let triggered_event = is_transient && self.cooldown_frames == 0;
            if triggered_event {
                let mut event_mask =
                    self.select_reset_mask(sub_flux, low_flux, mid_flux, high_flux, threshold);
                if suppress_low_bands {
                    if !self.should_accept_upper_band_reset_during_modulation_hold(
                        sub_flux, low_flux, mid_flux, high_flux, threshold,
                    ) {
                        self.cooldown_frames = self
                            .rejected_modulation_hold_cooldown_frames(modulation_overlap_windows);
                        self.update_flux_stats(flux);
                        self.prev_flux = flux;
                        self.last_processed_frame_start = Some(absolute_frame_start);
                        continue;
                    }
                    event_mask[0] = false;
                    event_mask[1] = false;
                }
                for i in 0..4 {
                    reset_mask[i] |= event_mask[i];
                    if event_mask[i] {
                        self.stats.reset_band_counts_total[i] =
                            self.stats.reset_band_counts_total[i].saturating_add(1);
                    }
                }
                self.stats.events_detected_total =
                    self.stats.events_detected_total.saturating_add(1);
                self.cooldown_frames = self.reset_cooldown_frames(modulation_overlap_windows);
            }

            self.update_flux_stats(flux);
            self.prev_flux = flux;
            if !triggered_event {
                self.cooldown_frames = self.cooldown_frames.saturating_sub(1);
            }
            self.last_processed_frame_start = Some(absolute_frame_start);
            if triggered_event {
                // The caller can apply only one reset mask per scheduler pass.
                // Stop after the first accepted event so later onsets remain
                // individually schedulable on the next overlapping callback
                // instead of being merged into one broader reset.
                break;
            }
        }

        if reset_mask.iter().any(|&v| v) {
            Some(reset_mask)
        } else {
            None
        }
    }

    #[inline]
    fn update_flux_stats(&mut self, flux: f64) {
        let delta = flux - self.mean_flux;
        self.mean_flux += self.flux_ema_alpha * delta;
        self.var_flux += self.flux_ema_alpha * (delta * delta - self.var_flux);
    }

    /// Builds a per-band phase-reset mask from detected band fluxes.
    ///
    /// Mask layout: `[sub_bass, low, mid, high]`.
    fn select_reset_mask(
        &self,
        sub_flux: f64,
        low_flux: f64,
        mid_flux: f64,
        high_flux: f64,
        threshold: f64,
    ) -> [bool; 4] {
        let peak = low_flux.max(mid_flux).max(high_flux).max(1e-12);
        let mut mask = [false; 4];

        // Always protect upper content on detected events for crisp attacks.
        // Mid+high resets are deterministic to avoid missing percussive edges
        // when one upper band under-reports due to windowed energy split.
        mask[2] = true;
        mask[3] = true;

        // Kick-assist low-band reset: engage only when the event carries
        // enough actual low-end transient energy, not just an upper-band hit
        // with a modest low shelf.
        let low_energy_spike = sub_flux + low_flux > threshold * 0.75;
        let low_dominant =
            low_flux > peak * 0.30 && low_flux > threshold * 0.12 && low_energy_spike;
        let low_broadband_support =
            low_flux > peak * 0.22 && (mid_flux > peak * 0.25 || high_flux > peak * 0.25);
        let low_balance_guard = low_flux > (mid_flux + high_flux) * 0.18;
        if low_dominant || (low_broadband_support && low_energy_spike && low_balance_guard) {
            mask[1] = true;
        }

        // Keep sub resets conservative to avoid destabilizing sustained bass.
        if sub_flux > low_flux * 0.8 && sub_flux + low_flux > threshold * 1.05 {
            mask[0] = true;
        }

        mask
    }

    #[allow(dead_code)]
    pub(crate) fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    #[inline]
    pub(crate) fn stats(&self) -> TransientSchedulerStats {
        self.stats
    }
}

#[cfg(test)]
mod tests {
    use super::{
        TransientEventScheduler, FLUX_MODULATION_MIN_UPPER_DOMINANCE,
        FLUX_MODULATION_MIN_UPPER_SHARE, FLUX_MODULATION_MIN_UPPER_THRESHOLD_SHARE,
        FLUX_MODULATION_SPIKE_RATIO_STEP, FLUX_MODULATION_THRESHOLD_SCALE_STEP, FLUX_SPIKE_RATIO,
        FLUX_WARMUP_FRAMES, MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS,
    };
    use std::f32::consts::PI;

    #[test]
    fn derived_tunings_match_legacy_constants_at_reference_config() {
        // 4096/1024 @ 44.1 kHz is the configuration the frame-count tunings
        // were calibrated at; the time-based derivation must reproduce the
        // legacy constants exactly there.
        let scheduler = TransientEventScheduler::new(4096, 1024, 44_100, 16384);
        assert_eq!(scheduler.warmup_frames_initial, FLUX_WARMUP_FRAMES);
        assert_eq!(scheduler.min_cooldown_frames, 2);
        assert!(
            (scheduler.flux_ema_alpha - 0.2).abs() < 1e-4,
            "reference EMA alpha drifted: {}",
            scheduler.flux_ema_alpha
        );
        assert_eq!(
            scheduler.modulation_threshold_scale_step,
            FLUX_MODULATION_THRESHOLD_SCALE_STEP
        );
        assert_eq!(
            scheduler.modulation_spike_ratio_step,
            FLUX_MODULATION_SPIKE_RATIO_STEP
        );
    }

    #[test]
    fn derived_tunings_scale_to_absolute_time_at_low_latency_config() {
        // 1024/256 @ 44.1 kHz: 4x the frame rate, so temporal frame counts
        // scale ~4x (same absolute time) and the EMA alpha shrinks to keep
        // the same adaptation time constant. Warmup stays a fixed
        // observation count.
        let scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);
        assert_eq!(scheduler.warmup_frames_initial, FLUX_WARMUP_FRAMES);
        assert_eq!(scheduler.min_cooldown_frames, 8);
        assert!(
            (scheduler.flux_ema_alpha - 0.0543).abs() < 5e-4,
            "low-latency EMA alpha off: {}",
            scheduler.flux_ema_alpha
        );
        // Desensitization steps shrink by fft/4096 so the ceiling stays
        // constant when the processor's window cap grows at small FFT sizes.
        assert_eq!(
            scheduler.modulation_threshold_scale_step,
            FLUX_MODULATION_THRESHOLD_SCALE_STEP * 0.25
        );
        assert_eq!(
            scheduler.modulation_spike_ratio_step,
            FLUX_MODULATION_SPIKE_RATIO_STEP * 0.25
        );
        // Warmup and reset() agree.
        assert_eq!(scheduler.warmup_frames, scheduler.warmup_frames_initial);
    }

    #[test]
    fn scheduler_detects_click_transient() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut stereo = vec![0.0f32; frames * 2];
        for i in 0..frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            // Place the click near the tail so the scheduler's recent-frame
            // scan window observes it.
            let click = if (3400..3420).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + click;
            stereo[i * 2 + 1] = base * 0.9 + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let mask = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        assert!(mask.is_some(), "expected transient reset mask");
        let mask = mask.unwrap();
        assert!(
            mask[2] || mask[3],
            "expected at least mid/high reset for click transient, got {:?}",
            mask
        );
    }

    #[test]
    fn scheduler_detects_antiphase_click_transient() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut stereo = vec![0.0f32; frames * 2];
        for i in 0..frames {
            let t = i as f32 / sr as f32;
            let base_l = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let base_r = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let click = if (3400..3420).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base_l + click;
            stereo[i * 2 + 1] = base_r - click; // anti-phase transient
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let mask = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        assert!(
            mask.is_some(),
            "expected reset mask for anti-phase transient content"
        );
    }

    #[test]
    fn scheduler_reset_clears_state() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let stereo = vec![0.0f32; frames * 2];

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let _ = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        scheduler.reset();
        let mask = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        assert!(
            mask.is_none(),
            "silent input should not produce reset mask after reset"
        );
    }

    #[test]
    fn scheduler_skips_duplicate_frames_for_same_origin() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut stereo = vec![0.0f32; frames * 2];
        for i in 0..frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let click = if (3400..3420).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + click;
            stereo[i * 2 + 1] = base * 0.9 + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let first = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        let second = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        assert!(first.is_some(), "first pass should observe transient");
        assert!(
            second.is_none(),
            "second pass with same origin should not reprocess duplicate frames"
        );
    }

    #[test]
    fn scheduler_detects_mono_click_transient() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut mono = vec![0.0f32; frames];
        for (i, sample) in mono.iter_mut().enumerate() {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let click = if (3400..3420).contains(&i) { 2.0 } else { 0.0 };
            *sample = base + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let mask = scheduler.detect_mono_reset_mask(&mono, 0, false, 0);
        assert!(mask.is_some(), "expected mono transient reset mask");
        let mask = mask.unwrap();
        assert!(
            mask[2] || mask[3],
            "expected at least mid/high reset for mono click transient, got {:?}",
            mask
        );
    }

    #[test]
    fn scheduler_mono_skips_duplicate_frames_for_same_origin() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut mono = vec![0.0f32; frames];
        for (i, sample) in mono.iter_mut().enumerate() {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let click = if (3400..3420).contains(&i) { 2.0 } else { 0.0 };
            *sample = base + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let first = scheduler.detect_mono_reset_mask(&mono, 0, false, 0);
        let second = scheduler.detect_mono_reset_mask(&mono, 0, false, 0);
        assert!(first.is_some(), "first mono pass should observe transient");
        assert!(
            second.is_none(),
            "second mono pass with same origin should not reprocess duplicate frames"
        );
    }

    #[test]
    fn scheduler_mono_ignores_steady_tone() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mono: Vec<f32> = (0..frames)
            .map(|i| (2.0 * PI * 220.0 * i as f32 / sr as f32).sin() * 0.3)
            .collect();

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let mask = scheduler.detect_mono_reset_mask(&mono, 0, false, 0);
        assert!(
            mask.is_none(),
            "steady mono tone should not trigger phase resets, got {:?}",
            mask
        );
    }

    #[test]
    fn scheduler_select_reset_mask_always_sets_mid_and_high() {
        let mut scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);
        scheduler.warmup_frames = 0;
        let mask = scheduler.select_reset_mask(0.0, 0.2, 0.1, 0.3, 1.0);
        assert!(mask[3], "high band should always reset on detected events");
        assert!(mask[2], "mid band should always reset on detected events");
    }

    #[test]
    fn scheduler_select_reset_mask_enables_low_for_broadband_percussion() {
        let mut scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);
        scheduler.warmup_frames = 0;
        let mask = scheduler.select_reset_mask(0.18, 0.32, 0.90, 1.00, 0.60);
        assert!(
            mask[1],
            "low band should reset when broadband hits include meaningful low energy"
        );
        assert!(
            !mask[0],
            "sub band should remain conservative for moderate low-end events"
        );
    }

    #[test]
    fn scheduler_select_reset_mask_skips_low_for_bright_transient_with_weak_low_shelf() {
        let mut scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);
        scheduler.warmup_frames = 0;
        let mask = scheduler.select_reset_mask(0.02, 0.31, 0.75, 0.95, 0.60);
        assert!(
            !mask[1],
            "low band should stay locked when upper-band transients only carry a weak low shelf"
        );
        assert!(mask[2], "mid band should still reset for bright transients");
        assert!(
            mask[3],
            "high band should still reset for bright transients"
        );
    }

    #[test]
    fn scheduler_extends_cooldown_when_modulation_holds_low_bands() {
        let fft = 1024usize;
        let hop = 256usize;
        let overlap_frames = fft.div_ceil(hop).saturating_sub(1);
        let scheduler = TransientEventScheduler::new(fft, hop, 44_100, 4096);

        let base = scheduler.reset_cooldown_frames(0);
        let modulation =
            scheduler.reset_cooldown_frames(MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS);

        assert_eq!(
            base,
            scheduler.min_cooldown_frames.max(overlap_frames),
            "base cooldown should cover the time-derived minimum or one overlap footprint"
        );
        assert_eq!(
            modulation,
            base + overlap_frames * MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS,
            "modulation low-band holds should add one extra overlap window of duplicate-reset protection"
        );
    }

    #[test]
    fn scheduler_cooldown_scales_with_requested_modulation_overlap_windows() {
        let fft = 1024usize;
        let hop = 256usize;
        let overlap_frames = fft.div_ceil(hop).saturating_sub(1);
        let scheduler = TransientEventScheduler::new(fft, hop, 44_100, 4096);

        let base = scheduler.reset_cooldown_frames(0);
        let strong_modulation =
            scheduler.reset_cooldown_frames(MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS + 2);

        assert_eq!(
            strong_modulation,
            base + overlap_frames * (MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS + 2),
            "larger modulation bursts should hold accepted resets through extra overlap windows"
        );
    }

    #[test]
    fn scheduler_rejected_modulation_hold_cooldown_nearly_matches_full_reset_hold() {
        let fft = 1024usize;
        let hop = 256usize;
        let overlap_frames = fft.div_ceil(hop).saturating_sub(1);
        let scheduler = TransientEventScheduler::new(fft, hop, 44_100, 4096);

        let rejected = scheduler.rejected_modulation_hold_cooldown_frames(
            MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS,
        );
        let accepted =
            scheduler.reset_cooldown_frames(MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS);

        assert_eq!(
            rejected,
            overlap_frames * MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS
                + overlap_frames.saturating_sub(1),
            "rejected modulation-hold events should hold through the overlap tail plus one more near-full window"
        );
        assert!(
            rejected < accepted,
            "rejected low-dominant events should still unblock slightly sooner than a real accepted reset"
        );
    }

    #[test]
    fn scheduler_trigger_requirements_stay_neutral_without_modulation_hold() {
        let scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);

        assert_eq!(
            scheduler.trigger_requirements(false, 0),
            (1.0, FLUX_SPIKE_RATIO)
        );
        assert_eq!(
            scheduler.trigger_requirements(true, 0),
            (1.0, FLUX_SPIKE_RATIO)
        );
    }

    #[test]
    fn scheduler_trigger_requirements_tighten_with_modulation_overlap_windows() {
        let scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);

        let (threshold_scale, spike_ratio) =
            scheduler.trigger_requirements(true, MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS);

        assert_eq!(
            threshold_scale,
            1.0
                + scheduler.modulation_threshold_scale_step
                    * MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS as f64,
            "low-band-suppressed modulation should require a proportionally stronger flux threshold"
        );
        assert_eq!(
            spike_ratio,
            FLUX_SPIKE_RATIO
                * (1.0
                    + scheduler.modulation_spike_ratio_step
                        * MODULATION_RESET_COOLDOWN_BASE_OVERLAP_WINDOWS as f64),
            "low-band-suppressed modulation should require a proportionally larger frame-to-frame spike"
        );
    }

    #[test]
    fn scheduler_modulation_hold_rejects_low_dominant_event_without_clear_upper_attack() {
        let scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);
        let threshold = 1.0;
        let upper_flux = 0.34;
        let total_flux = upper_flux / (FLUX_MODULATION_MIN_UPPER_SHARE - 0.01);
        let low_flux = total_flux - upper_flux;

        assert!(
            !scheduler.should_accept_upper_band_reset_during_modulation_hold(
                0.0, low_flux, upper_flux * 0.35, upper_flux * 0.65, threshold
            ),
            "modulation-hold mode should reject events whose energy stays mostly in the held low bands"
        );
    }

    #[test]
    fn scheduler_modulation_hold_accepts_clear_upper_band_attack() {
        let scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);
        let threshold = 1.0;
        let upper_flux = FLUX_MODULATION_MIN_UPPER_THRESHOLD_SHARE + 0.08;
        let low_flux = upper_flux * (1.0 / FLUX_MODULATION_MIN_UPPER_SHARE - 1.0) * 0.6;

        assert!(
            scheduler.should_accept_upper_band_reset_during_modulation_hold(
                0.0, low_flux, upper_flux * 0.45, upper_flux * 0.55, threshold
            ),
            "modulation-hold mode should still allow distinct upper-band attacks to reseed the vocoder"
        );
    }

    #[test]
    fn scheduler_modulation_hold_rejects_borderline_upper_share_when_low_bands_still_compete() {
        let scheduler = TransientEventScheduler::new(1024, 256, 44_100, 4096);
        let threshold = 1.0;
        let held_low_flux = 0.32;
        let upper_flux = held_low_flux * (FLUX_MODULATION_MIN_UPPER_DOMINANCE - 0.02);
        let total_flux = held_low_flux + upper_flux;

        assert!(
            upper_flux / total_flux > FLUX_MODULATION_MIN_UPPER_SHARE,
            "test fixture should still clear the existing upper-share gate"
        );
        assert!(
            upper_flux / threshold > FLUX_MODULATION_MIN_UPPER_THRESHOLD_SHARE,
            "test fixture should still clear the existing upper-strength gate"
        );
        assert!(
            !scheduler.should_accept_upper_band_reset_during_modulation_hold(
                0.0,
                held_low_flux,
                upper_flux * 0.45,
                upper_flux * 0.55,
                threshold,
            ),
            "modulation-hold mode should keep rejecting seam-side events until upper bands clearly dominate the held low bands"
        );
    }

    #[test]
    fn scheduler_stats_accumulate_and_reset() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut stereo = vec![0.0f32; frames * 2];
        for i in 0..frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let click = if (3400..3420).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + click;
            stereo[i * 2 + 1] = base * 0.9 + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let _ = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        let stats = scheduler.stats();
        assert!(
            stats.events_detected_total > 0,
            "expected at least one detected transient event"
        );
        assert!(
            stats.reset_band_counts_total[2] > 0 && stats.reset_band_counts_total[3] > 0,
            "expected upper-band reset counts to accumulate"
        );

        scheduler.reset();
        let reset_stats = scheduler.stats();
        assert_eq!(reset_stats.events_detected_total, 0);
        assert_eq!(reset_stats.reset_band_counts_total, [0, 0, 0, 0]);
    }

    #[test]
    fn scheduler_tail_transient_preserves_full_cooldown_window() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut stereo = vec![0.0f32; frames * 2];
        for i in 0..frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            // Align the click so only the final scanned analysis frame sees it.
            let click = if (3840..3860).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + click;
            stereo[i * 2 + 1] = base * 0.9 + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let mask = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        assert!(mask.is_some(), "expected tail transient reset mask");
        assert_eq!(
            scheduler.cooldown_frames,
            scheduler
                .min_cooldown_frames
                .max(fft.div_ceil(hop).saturating_sub(1)),
            "detected events should keep the full configured cooldown for subsequent analysis frames"
        );
    }

    #[test]
    fn scheduler_sub_hop_overlap_does_not_advance_cursor_or_burn_cooldown() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let callback_frames = 4096usize;
        let half_hop = hop / 2;
        let total_frames = callback_frames + half_hop;
        let mut stereo = vec![0.0f32; total_frames * 2];
        for i in 0..total_frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            // Align the click so only the final scanned analysis frame in the
            // first callback sees it.
            let click = if (3840..3860).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + click;
            stereo[i * 2 + 1] = base * 0.9 + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, callback_frames);
        let first = scheduler.detect_stereo_reset_mask(&stereo[..callback_frames * 2], 0, false, 0);
        assert!(
            first.is_some(),
            "expected initial tail transient reset mask"
        );
        assert_eq!(
            scheduler.last_processed_frame_start,
            Some(3072),
            "tail click should advance the processed-frame cursor to the final schedulable frame"
        );
        let expected_cooldown = scheduler.reset_cooldown_frames(0);
        assert_eq!(
            scheduler.cooldown_frames, expected_cooldown,
            "detected event should arm the full cooldown"
        );

        let shifted_start = half_hop * 2;
        let shifted_end = shifted_start + callback_frames * 2;
        let second = scheduler.detect_stereo_reset_mask(
            &stereo[shifted_start..shifted_end],
            half_hop,
            false,
            0,
        );
        assert!(
            second.is_none(),
            "sub-hop-overlapped callback should not schedule a duplicate transient reset"
        );
        assert_eq!(
            scheduler.last_processed_frame_start,
            Some(3072),
            "sub-hop-overlapped callback should not advance the processed-frame cursor"
        );
        assert_eq!(
            scheduler.cooldown_frames, expected_cooldown,
            "sub-hop-overlapped callback should not consume cooldown on nearly identical windows"
        );
        assert_eq!(
            scheduler.stats().events_detected_total,
            1,
            "sub-hop-overlapped callback should not count as a fresh transient event"
        );
    }

    #[test]
    fn scheduler_tail_transient_does_not_retrigger_across_repeated_half_hop_callbacks() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let callback_frames = 4096usize;
        let half_hop = hop / 2;
        let total_frames = callback_frames + hop * 4;
        let mut stereo = vec![0.0f32; total_frames * 2];
        for i in 0..total_frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            // Keep a single late transient inside the overlapping callback
            // windows long enough to exercise repeated half-hop re-entry.
            let click = if (3840..3860).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + click;
            stereo[i * 2 + 1] = base * 0.9 + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, callback_frames);
        let mut triggered_origins = Vec::new();
        for origin in (0..=8).map(|step| step * half_hop) {
            let start = origin * 2;
            let end = start + callback_frames * 2;
            let mask = scheduler.detect_stereo_reset_mask(&stereo[start..end], origin, false, 0);
            if mask.is_some() {
                triggered_origins.push(origin);
            }
        }

        assert_eq!(
            triggered_origins,
            vec![0],
            "repeated half-hop callbacks should not retrigger one tail transient after the initial pass"
        );
        assert_eq!(
            scheduler.stats().events_detected_total,
            1,
            "one tail transient should count as a single reset event across repeated half-hop callbacks"
        );
    }

    #[test]
    fn scheduler_tail_transient_does_not_retrigger_across_mixed_sub_hop_callbacks() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let callback_frames = 4096usize;
        let quarter_hop = hop / 4;
        let total_frames = callback_frames + hop * 4;
        let mut stereo = vec![0.0f32; total_frames * 2];
        for i in 0..total_frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            // Keep one late transient inside the overlapping callback windows
            // while the callback origin advances by mixed sub-hop strides.
            let click = if (3840..3860).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + click;
            stereo[i * 2 + 1] = base * 0.9 + click;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, callback_frames);
        let expected_last_start = Some(3072usize);
        let expected_cooldown = scheduler.reset_cooldown_frames(0);
        let mut triggered_origins = Vec::new();

        for origin in [
            0usize,
            quarter_hop,
            hop / 2,
            hop - quarter_hop,
            hop,
            hop + quarter_hop,
            hop + hop / 2,
            hop * 2,
        ] {
            let start = origin * 2;
            let end = start + callback_frames * 2;
            let mask = scheduler.detect_stereo_reset_mask(&stereo[start..end], origin, false, 0);
            if mask.is_some() {
                triggered_origins.push(origin);
            }

            if origin > 0 && origin < hop {
                assert!(
                    mask.is_none(),
                    "mixed sub-hop callback at origin {origin} should not reschedule the same tail transient"
                );
                assert_eq!(
                    scheduler.last_processed_frame_start,
                    expected_last_start,
                    "mixed sub-hop callback at origin {origin} should not advance the processed-frame cursor"
                );
                assert_eq!(
                    scheduler.cooldown_frames, expected_cooldown,
                    "mixed sub-hop callback at origin {origin} should not burn the transient cooldown"
                );
            }
        }

        assert_eq!(
            triggered_origins,
            vec![0],
            "mixed sub-hop callbacks should not retrigger one tail transient after the initial pass"
        );
        assert_eq!(
            scheduler.stats().events_detected_total,
            1,
            "one tail transient should count as a single reset event across mixed sub-hop callbacks"
        );
    }

    #[test]
    fn scheduler_mixed_sub_hop_callbacks_schedule_next_distinct_transient_once() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let callback_frames = 4096usize;
        let quarter_hop = hop / 4;
        let total_frames = callback_frames + hop * 10;
        let mut stereo = vec![0.0f32; total_frames * 2];
        for i in 0..total_frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            // The first click is late enough to trigger near the end of the
            // initial callback without being visible in the prior analysis
            // frame. The second first becomes visible in the frame scanned
            // right after the time-based cooldown (8 frames at 256 hop,
            // ~46 ms) expires, so it should fire exactly once on the first
            // post-cooldown mixed callback that clears the full-hop gate.
            let click_a = if (3328..3348).contains(&i) { 2.0 } else { 0.0 };
            let click_b = if (6200..6280).contains(&i) { 4.0 } else { 0.0 };
            let sample = base + click_a + click_b;
            stereo[i * 2] = sample;
            stereo[i * 2 + 1] = sample * 0.9;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, callback_frames);
        let mut triggered_origins = Vec::new();
        // Ten full-hop groups, each visited at four sub-hop offsets.
        for group in 0..10usize {
            for offset in [0, quarter_hop, hop / 2, hop - quarter_hop] {
                let origin = group * hop + offset;
                let start = origin * 2;
                let end = start + callback_frames * 2;
                let mask =
                    scheduler.detect_stereo_reset_mask(&stereo[start..end], origin, false, 0);
                if mask.is_some() {
                    triggered_origins.push(origin);
                }
            }
        }

        assert_eq!(
            triggered_origins.len(),
            2,
            "expected exactly two scheduled events, got {:?}",
            triggered_origins
        );
        assert_eq!(triggered_origins[0], 0, "first click should fire at once");
        assert!(
            (hop * 9..hop * 10).contains(&triggered_origins[1]),
            "second click should fire exactly once in the first post-cooldown \
             full-hop group, got {:?}",
            triggered_origins
        );
        assert_eq!(
            scheduler.stats().events_detected_total,
            2,
            "two distinct transients should produce exactly two reset events across mixed sub-hop callbacks"
        );
    }

    #[test]
    fn scheduler_broad_tail_transient_does_not_retrigger_across_overlapping_callbacks() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let callback_frames = 4096usize;
        let total_frames = callback_frames + hop * 4;
        let mut stereo = vec![0.0f32; total_frames * 2];
        for i in 0..total_frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let burst = if (3600..4000).contains(&i) { 2.0 } else { 0.0 };
            stereo[i * 2] = base + burst;
            stereo[i * 2 + 1] = base * 0.9 + burst;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, callback_frames);
        for origin in [0usize, hop, hop * 2, hop * 3] {
            let start = origin * 2;
            let end = start + callback_frames * 2;
            let _ = scheduler.detect_stereo_reset_mask(&stereo[start..end], origin, false, 0);
        }

        let stats = scheduler.stats();
        assert_eq!(
            stats.events_detected_total, 1,
            "one broad tail transient should not retrigger across overlapping callbacks"
        );
    }

    #[test]
    fn scheduler_pass_emits_only_first_schedulable_event() {
        let sr = 44_100u32;
        let fft = 1024usize;
        let hop = 256usize;
        let frames = 4096usize;
        let mut stereo = vec![0.0f32; frames * 2];
        for i in 0..frames {
            let t = i as f32 / sr as f32;
            let base = (2.0 * PI * 220.0 * t).sin() * 0.2;
            let click_a = if (2816..2836).contains(&i) { 2.0 } else { 0.0 };
            let click_b = if (3840..3860).contains(&i) { 2.0 } else { 0.0 };
            let sample = base + click_a + click_b;
            stereo[i * 2] = sample;
            stereo[i * 2 + 1] = sample * 0.9;
        }

        let mut scheduler = TransientEventScheduler::new(fft, hop, sr, frames);
        let mask = scheduler.detect_stereo_reset_mask(&stereo, 0, false, 0);
        assert!(mask.is_some(), "expected first-event reset mask");

        let stats = scheduler.stats();
        assert_eq!(
            stats.events_detected_total, 1,
            "one scheduler pass should emit only the earliest schedulable transient event"
        );
    }
}