timestretch 0.7.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
use std::f32::consts::PI;
use timestretch::{stretch, EdmPreset, StreamProcessor, StretchParams, WindowType};

fn sine_wave(freq: f32, sample_rate: u32, num_samples: usize) -> Vec<f32> {
    (0..num_samples)
        .map(|i| (2.0 * PI * freq * i as f32 / sample_rate as f32).sin())
        .collect()
}

fn rms(signal: &[f32]) -> f32 {
    if signal.is_empty() {
        return 0.0;
    }
    (signal.iter().map(|x| x * x).sum::<f32>() / signal.len() as f32).sqrt()
}

fn spectral_energy_at_freq(signal: &[f32], sample_rate: u32, target_freq: f32) -> f32 {
    let n = signal.len();
    if n == 0 {
        return 0.0;
    }
    let two_pi = 2.0 * PI;
    let mut real = 0.0f64;
    let mut imag = 0.0f64;
    for (i, &s) in signal.iter().enumerate() {
        let angle = two_pi * target_freq * i as f32 / sample_rate as f32;
        real += s as f64 * angle.cos() as f64;
        imag += s as f64 * angle.sin() as f64;
    }
    ((real * real + imag * imag) / n as f64).sqrt() as f32
}

/// Run a streaming stretch and return the full output.
fn stream_stretch(input: &[f32], params: StretchParams, chunk_size: usize) -> Vec<f32> {
    let mut processor = StreamProcessor::new(params);
    let mut output = Vec::new();
    for chunk in input.chunks(chunk_size) {
        if let Ok(out) = processor.process(chunk) {
            output.extend_from_slice(&out);
        }
    }
    if let Ok(remaining) = processor.flush() {
        output.extend_from_slice(&remaining);
    }
    output
}

// ===================== BASIC STREAMING TESTS =====================

#[test]
fn test_streaming_basic_mono() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let output = stream_stretch(&input, params, 4096);
    assert!(!output.is_empty(), "Streaming should produce output");

    let max = output.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    assert!(max > 0.01, "Streaming output should not be silent");
}

#[test]
fn test_streaming_stereo() {
    let sample_rate = 44100;
    let num_frames = sample_rate as usize;
    let mut input = Vec::with_capacity(num_frames * 2);
    for i in 0..num_frames {
        let t = i as f32 / sample_rate as f32;
        input.push((2.0 * PI * 440.0 * t).sin());
        input.push((2.0 * PI * 880.0 * t).sin());
    }

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(2);

    let output = stream_stretch(&input, params, 4096);
    assert!(!output.is_empty());
    assert_eq!(output.len() % 2, 0, "Stereo output must have even length");
}

#[test]
fn test_streaming_ratio_change() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 4);

    let params = StretchParams::new(1.0)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let mut processor = StreamProcessor::new(params);
    let chunk_size = 4096;
    let mut output = Vec::new();

    for (chunk_idx, chunk) in input.chunks(chunk_size).enumerate() {
        if chunk_idx == input.len() / chunk_size / 2 {
            processor
                .set_stretch_ratio(1.5)
                .expect("valid stretch ratio");
        }
        if let Ok(out) = processor.process(chunk) {
            output.extend_from_slice(&out);
        }
    }
    if let Ok(remaining) = processor.flush() {
        output.extend_from_slice(&remaining);
    }

    assert!(!output.is_empty());
}

#[test]
fn test_streaming_flush() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let mut processor = StreamProcessor::new(params);
    let mut output_before_flush = Vec::new();
    for chunk in input.chunks(2048) {
        if let Ok(out) = processor.process(chunk) {
            output_before_flush.extend_from_slice(&out);
        }
    }
    let flushed = processor.flush().unwrap();

    let total = output_before_flush.len() + flushed.len();
    assert!(total > 0, "Total output should be non-empty after flush");
}

#[test]
fn test_streaming_reset() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let output1 = stream_stretch(&input, params.clone(), 4096);

    // Second run after implicit reset (new processor)
    let output2 = stream_stretch(&input, params, 4096);

    let rms1 = rms(&output1);
    let rms2 = rms(&output2);
    assert!(
        (rms1 - rms2).abs() < rms1 * 0.2,
        "Reset should produce consistent output: rms1={}, rms2={}",
        rms1,
        rms2
    );
}

// ===================== STREAMING VS BATCH COMPARISON =====================

#[test]
fn test_streaming_vs_batch_length() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    for &ratio in &[0.75, 1.0, 1.25, 1.5, 2.0] {
        let params = StretchParams::new(ratio)
            .with_sample_rate(sample_rate)
            .with_channels(1);

        let batch_output = stretch(&input, &params).unwrap();
        let stream_output = stream_stretch(&input, params, 4096);

        let batch_ratio = batch_output.len() as f64 / input.len() as f64;
        let stream_ratio = stream_output.len() as f64 / input.len() as f64;

        assert!(
            (batch_ratio - stream_ratio).abs() < 0.5,
            "Ratio {}: batch_ratio={:.3}, stream_ratio={:.3}",
            ratio,
            batch_ratio,
            stream_ratio
        );
    }
}

#[test]
fn test_streaming_vs_batch_rms() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let batch_output = stretch(&input, &params).unwrap();
    let stream_output = stream_stretch(&input, params, 4096);

    let batch_rms = rms(&batch_output);
    let stream_rms = rms(&stream_output);

    assert!(
        (batch_rms - stream_rms).abs() < batch_rms * 0.4,
        "Streaming RMS={} should be close to batch RMS={}",
        stream_rms,
        batch_rms
    );
}

#[test]
fn test_streaming_vs_batch_frequency() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let batch_output = stretch(&input, &params).unwrap();
    let stream_output = stream_stretch(&input, params, 4096);

    let batch_energy = spectral_energy_at_freq(&batch_output, sample_rate, 440.0);
    let stream_energy = spectral_energy_at_freq(&stream_output, sample_rate, 440.0);

    assert!(
        batch_energy > 0.1 && stream_energy > 0.1,
        "440 Hz should be preserved: batch={}, stream={}",
        batch_energy,
        stream_energy
    );
}

// ===================== CHUNK SIZE TESTS =====================

#[test]
fn test_streaming_chunk_size_consistency() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let chunk_sizes = [512, 4096, 16384];
    let mut rms_values = Vec::new();

    for &chunk_size in &chunk_sizes {
        let params = StretchParams::new(1.5)
            .with_sample_rate(sample_rate)
            .with_channels(1);
        let output = stream_stretch(&input, params, chunk_size);
        rms_values.push(rms(&output));
    }

    // All chunk sizes should give similar results
    let avg_rms = rms_values.iter().sum::<f32>() / rms_values.len() as f32;
    for (i, &r) in rms_values.iter().enumerate() {
        assert!(
            (r - avg_rms).abs() < avg_rms * 0.3,
            "Chunk size {} gave RMS {} (avg={})",
            chunk_sizes[i],
            r,
            avg_rms
        );
    }
}

#[test]
fn test_streaming_small_chunks() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let output = stream_stretch(&input, params, 256);
    assert!(
        !output.is_empty(),
        "Small chunks should still produce output"
    );
}

// ===================== STEREO STREAMING TESTS =====================

#[test]
fn test_streaming_stereo_vs_batch() {
    let sample_rate = 44100;
    let num_frames = sample_rate as usize;
    let mut input = Vec::with_capacity(num_frames * 2);
    for i in 0..num_frames {
        let t = i as f32 / sample_rate as f32;
        input.push((2.0 * PI * 440.0 * t).sin());
        input.push((2.0 * PI * 880.0 * t).sin());
    }

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(2);

    let batch_output = stretch(&input, &params).unwrap();
    let stream_output = stream_stretch(&input, params, 4096);

    assert_eq!(batch_output.len() % 2, 0);
    assert_eq!(stream_output.len() % 2, 0);

    let batch_rms = rms(&batch_output);
    let stream_rms = rms(&stream_output);

    assert!(
        (batch_rms - stream_rms).abs() < batch_rms * 0.4,
        "Stereo streaming RMS={} should be close to batch RMS={}",
        stream_rms,
        batch_rms
    );
}

// ===================== EDM PRESET STREAMING =====================

#[test]
fn test_streaming_with_edm_preset() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(1.02)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::DjBeatmatch);

    let output = stream_stretch(&input, params, 4096);
    assert!(!output.is_empty());

    let max = output.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    assert!(max > 0.01, "DJ beatmatch streaming should not be silent");
}

// ===================== EDGE CASE TESTS =====================

#[test]
fn test_streaming_compression() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    for &ratio in &[0.5, 0.75] {
        let params = StretchParams::new(ratio)
            .with_sample_rate(sample_rate)
            .with_channels(1);

        let output = stream_stretch(&input, params, 4096);
        assert!(
            !output.is_empty(),
            "Compression ratio {} should produce output",
            ratio
        );

        let actual_ratio = output.len() as f64 / input.len() as f64;
        assert!(
            (actual_ratio - ratio).abs() < 0.5,
            "Compression ratio {}: expected ~{}, got {}",
            ratio,
            ratio,
            actual_ratio
        );
    }
}

#[test]
fn test_streaming_empty_flush() {
    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(1);

    let mut processor = StreamProcessor::new(params);

    // Flush without any input
    let flushed = processor.flush().unwrap();
    assert!(
        flushed.is_empty(),
        "Flush without input should give empty output"
    );

    // Double flush
    let flushed2 = processor.flush().unwrap();
    assert!(flushed2.is_empty(), "Double flush should give empty output");
}

#[test]
fn test_streaming_single_sample_chunks() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, 4410); // 0.1 second

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let output = stream_stretch(&input, params, 1);
    // May produce output or not depending on implementation, but should not crash
    let _ = output;
}

#[test]
fn test_streaming_large_fft_size() {
    let sample_rate = 44100;
    let input = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_fft_size(8192);

    let output = stream_stretch(&input, params, 4096);
    assert!(
        !output.is_empty(),
        "Large FFT streaming should produce output"
    );
}

// ===================== LATENCY REPORTING =====================

#[test]
fn test_streaming_latency_reporting() {
    let sample_rate = 44100;
    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1);

    let processor = StreamProcessor::new(params);
    let latency = processor.latency_samples();

    // Latency should be reasonable (less than 5 seconds worth)
    assert!(
        latency < sample_rate as usize * 5,
        "Latency {} samples seems too high",
        latency
    );
}

#[test]
fn test_streaming_from_tempo_dj_workflow() {
    // Simulate a DJ matching a 126 BPM track to 128 BPM
    let sample_rate = 44100u32;
    let signal = sine_wave(440.0, sample_rate, sample_rate as usize * 2);
    let chunk_size = 4096;

    let mut processor = StreamProcessor::from_tempo(126.0, 128.0, sample_rate, 1);

    // Verify initial state
    let expected_ratio = 126.0 / 128.0;
    assert!(
        (processor.current_stretch_ratio() - expected_ratio).abs() < 1e-6,
        "Initial ratio should be {}, got {}",
        expected_ratio,
        processor.current_stretch_ratio()
    );
    assert_eq!(processor.source_bpm(), Some(126.0));
    assert_eq!(processor.params().preset, Some(EdmPreset::DjBeatmatch));

    // Process audio
    let mut total_output = Vec::new();
    for chunk in signal.chunks(chunk_size) {
        total_output.extend_from_slice(&processor.process(chunk).unwrap());
    }
    total_output.extend_from_slice(&processor.flush().unwrap());

    assert!(!total_output.is_empty(), "from_tempo should produce output");

    // Output ratio should be close to 126/128 ≈ 0.984
    // Phase vocoder output length has some variance, so allow generous tolerance
    let output_ratio = total_output.len() as f64 / signal.len() as f64;
    assert!(
        (output_ratio - expected_ratio).abs() < 0.3,
        "126→128 BPM: output ratio {} too far from expected {}",
        output_ratio,
        expected_ratio
    );
}

#[test]
fn test_streaming_from_tempo_stereo() {
    let sample_rate = 44100u32;
    let num_frames = sample_rate as usize;
    let mut signal = vec![0.0f32; num_frames * 2];
    for i in 0..num_frames {
        let t = i as f32 / sample_rate as f32;
        signal[i * 2] = (2.0 * std::f32::consts::PI * 440.0 * t).sin();
        signal[i * 2 + 1] = (2.0 * std::f32::consts::PI * 880.0 * t).sin();
    }

    let mut processor = StreamProcessor::from_tempo(120.0, 125.0, sample_rate, 2);

    let mut total_output = Vec::new();
    for chunk in signal.chunks(8192) {
        total_output.extend_from_slice(&processor.process(chunk).unwrap());
    }
    total_output.extend_from_slice(&processor.flush().unwrap());

    assert!(!total_output.is_empty());
    assert_eq!(total_output.len() % 2, 0, "Stereo output must be even");
}

#[test]
fn test_streaming_set_tempo_mid_stream() {
    // Start at 126→128 BPM, then change target to 130 BPM mid-stream
    let sample_rate = 44100u32;
    let signal = sine_wave(440.0, sample_rate, sample_rate as usize * 4);
    let chunk_size = 4096;

    let mut processor = StreamProcessor::from_tempo(126.0, 128.0, sample_rate, 1);
    let mut total_output = Vec::new();

    let chunks: Vec<&[f32]> = signal.chunks(chunk_size).collect();
    let mid = chunks.len() / 2;

    // Process first half at 128 BPM target
    for chunk in &chunks[..mid] {
        total_output.extend_from_slice(&processor.process(chunk).unwrap());
    }

    // Change target to 130 BPM
    assert!(processor.set_tempo(130.0));

    // Process second half
    for chunk in &chunks[mid..] {
        total_output.extend_from_slice(&processor.process(chunk).unwrap());
    }
    total_output.extend_from_slice(&processor.flush().unwrap());

    assert!(
        !total_output.is_empty(),
        "Should produce output across tempo change"
    );

    // Final ratio should approach 126/130
    let target_ratio = 126.0 / 130.0;
    assert!(
        (processor.current_stretch_ratio() - target_ratio).abs() < 0.05,
        "After set_tempo(130), ratio should be ~{}, got {}",
        target_ratio,
        processor.current_stretch_ratio()
    );
}

#[test]
fn test_streaming_set_tempo_without_source_returns_false() {
    let params = StretchParams::new(1.0)
        .with_sample_rate(44100)
        .with_channels(1);
    let mut processor = StreamProcessor::new(params);

    // set_tempo requires from_tempo to have been used
    assert!(!processor.set_tempo(128.0));
}

#[test]
fn test_streaming_from_tempo_slowdown() {
    // Slow down: 130 BPM → 120 BPM (ratio > 1.0, output longer)
    let sample_rate = 44100u32;
    let signal = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let mut processor = StreamProcessor::from_tempo(130.0, 120.0, sample_rate, 1);

    let mut total_output = Vec::new();
    for chunk in signal.chunks(4096) {
        total_output.extend_from_slice(&processor.process(chunk).unwrap());
    }
    total_output.extend_from_slice(&processor.flush().unwrap());

    assert!(!total_output.is_empty());
    // 130/120 ≈ 1.083 → output should be longer
    let output_ratio = total_output.len() as f64 / signal.len() as f64;
    assert!(
        output_ratio > 1.0,
        "130→120 BPM should stretch, got ratio {}",
        output_ratio
    );
}

// ===================== WINDOW TYPE STREAMING TESTS =====================

#[test]
fn test_streaming_blackman_harris_produces_output() {
    let sample_rate = 44100u32;
    let signal = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_window_type(WindowType::BlackmanHarris);

    let output = stream_stretch(&signal, params, 4096);
    assert!(!output.is_empty(), "BH streaming should produce output");

    let output_rms = rms(&output);
    assert!(
        output_rms > 0.1,
        "BH streaming output should have energy, got RMS={}",
        output_rms
    );
}

#[test]
fn test_streaming_kaiser_produces_output() {
    let sample_rate = 44100u32;
    let signal = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_window_type(WindowType::Kaiser(800));

    let output = stream_stretch(&signal, params, 4096);
    assert!(!output.is_empty(), "Kaiser streaming should produce output");

    let output_rms = rms(&output);
    assert!(
        output_rms > 0.1,
        "Kaiser streaming output should have energy, got RMS={}",
        output_rms
    );
}

#[test]
fn test_streaming_different_windows_preserve_frequency() {
    let sample_rate = 44100u32;
    let freq = 440.0;
    let signal = sine_wave(freq, sample_rate, sample_rate as usize * 2);

    let windows = [
        WindowType::Hann,
        WindowType::BlackmanHarris,
        WindowType::Kaiser(800),
    ];

    for &win in &windows {
        let params = StretchParams::new(1.0)
            .with_sample_rate(sample_rate)
            .with_channels(1)
            .with_window_type(win);

        let output = stream_stretch(&signal, params, 4096);
        if output.len() < 4096 {
            continue; // Not enough output to analyze
        }

        // Skip edge effects
        let skip = 4096;
        let end = output.len().saturating_sub(4096);
        if end <= skip {
            continue;
        }
        let trimmed = &output[skip..end];

        let energy_440 = spectral_energy_at_freq(trimmed, sample_rate, freq);
        let energy_880 = spectral_energy_at_freq(trimmed, sample_rate, freq * 2.0);

        // 440 Hz should dominate over 880 Hz
        assert!(
            energy_440 > energy_880 * 2.0,
            "Window {:?}: 440 Hz energy ({:.4}) should dominate over 880 Hz ({:.4})",
            win,
            energy_440,
            energy_880
        );
    }
}

#[test]
fn test_streaming_window_ratio_change() {
    // Verify that window type persists through ratio changes
    let sample_rate = 44100u32;
    let signal = sine_wave(440.0, sample_rate, sample_rate as usize * 4);

    let params = StretchParams::new(1.0)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_window_type(WindowType::BlackmanHarris);

    let mut processor = StreamProcessor::new(params);
    let mut output = Vec::new();

    // Process first half
    for chunk in signal[..signal.len() / 2].chunks(4096) {
        if let Ok(out) = processor.process(chunk) {
            output.extend_from_slice(&out);
        }
    }

    // Change ratio mid-stream
    processor
        .set_stretch_ratio(1.05)
        .expect("valid stretch ratio");

    // Process second half
    for chunk in signal[signal.len() / 2..].chunks(4096) {
        if let Ok(out) = processor.process(chunk) {
            output.extend_from_slice(&out);
        }
    }

    if let Ok(remaining) = processor.flush() {
        output.extend_from_slice(&remaining);
    }

    assert!(
        !output.is_empty(),
        "BH window with ratio change should produce output"
    );

    // Check for clicks (sudden jumps)
    let mut max_diff = 0.0f32;
    for i in 1..output.len() {
        max_diff = max_diff.max((output[i] - output[i - 1]).abs());
    }

    assert!(
        max_diff < 1.0,
        "BH window ratio change should not produce clicks: max_diff={}",
        max_diff
    );
}

#[test]
fn test_streaming_ambient_preset_uses_blackman_harris() {
    let sample_rate = 44100u32;
    let signal = sine_wave(440.0, sample_rate, sample_rate as usize * 2);

    let params = StretchParams::new(2.0)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::Ambient);

    // Verify the preset set Blackman-Harris
    assert_eq!(params.window_type, WindowType::BlackmanHarris);

    let output = stream_stretch(&signal, params, 4096);
    assert!(
        !output.is_empty(),
        "Ambient preset streaming should produce output"
    );

    // Output should be approximately 2x longer
    let ratio = output.len() as f64 / signal.len() as f64;
    assert!(
        (ratio - 2.0).abs() < 0.5,
        "Ambient preset stream ratio {} too far from 2.0",
        ratio
    );
}

#[test]
fn test_streaming_normalize_with_window() {
    // Test that batch stretch with normalize produces consistent RMS
    // regardless of window type
    let sample_rate = 44100u32;
    let num_samples = sample_rate as usize * 2;
    let signal: Vec<f32> = (0..num_samples)
        .map(|i| 0.7 * (2.0 * PI * 440.0 * i as f32 / sample_rate as f32).sin())
        .collect();

    let input_rms = rms(&signal);

    let windows = [WindowType::Hann, WindowType::BlackmanHarris];

    for &win in &windows {
        let params = StretchParams::new(1.5)
            .with_sample_rate(sample_rate)
            .with_channels(1)
            .with_window_type(win)
            .with_normalize(true);

        let output = stretch(&signal, &params).unwrap();
        let output_rms = rms(&output);

        assert!(
            (output_rms - input_rms).abs() < input_rms * 0.1,
            "Window {:?} with normalize: RMS mismatch input={:.4} output={:.4}",
            win,
            input_rms,
            output_rms
        );
    }
}

// ===================== REALTIME PITCH MODULATION =====================

/// Sweeping the pitch control every callback must not produce clicks or
/// zipper discontinuities: pitch changes glide instead of hard-resetting the
/// pitch resampler state.
///
/// Runs at several stream lengths: the residual input left in the ring at
/// flush time depends on the total length, and a flush splice bug (vocoder
/// tails once bypassed the engaged pitch resampler) only manifested at some
/// residue phases.
#[test]
fn test_streaming_pitch_sweep_no_zipper() {
    for extra in [0usize, 512, 1536, 2560] {
        run_pitch_sweep_no_zipper(extra);
    }
}

fn run_pitch_sweep_no_zipper(extra_samples: usize) {
    let sample_rate = 44100u32;
    let freq = 1000.0f32;
    let num_samples = sample_rate as usize * 2 + extra_samples;
    let input = sine_wave(freq, sample_rate, num_samples);

    let params = StretchParams::new(1.0)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_fft_size(1024)
        .with_hop_size(256);
    let mut processor = StreamProcessor::new(params);

    let chunk = 256usize;
    let n_chunks = num_samples / chunk;
    let mut output: Vec<f32> = Vec::with_capacity(num_samples * 3);
    for (ci, block) in input.chunks(chunk).enumerate() {
        // Ramp the pitch control from 1.0 to 1.12 across the stream.
        let scale = 1.0 + 0.12 * (ci as f64 / (n_chunks - 1) as f64);
        processor.set_pitch_scale(scale).unwrap();
        processor.process_into(block, &mut output).unwrap();
    }
    processor.flush_into(&mut output).unwrap();

    // Max sample-to-sample slew of a 1 kHz sine at <= 1.12x pitch, with
    // headroom for PV overlap-add ripple. A resampler-reset click is a
    // near-full-scale jump and blows well past this bound. The scan covers
    // the FULL output including the end-of-stream flush region.
    let max_slew = 2.0 * PI * freq * 1.12 / sample_rate as f32 * 2.5;
    let skip = 8192; // settle PV warmup and gain EMA
    for (i, w) in output[skip..].windows(2).enumerate() {
        let d = (w[1] - w[0]).abs();
        assert!(
            d <= max_slew,
            "extra={}: zipper/click at output sample {}: |delta| = {:.4} > {:.4}",
            extra_samples,
            skip + i,
            d,
            max_slew
        );
    }

    // The tail of the stream should sit near the final shifted frequency.
    let tail_start = output.len().saturating_sub(sample_rate as usize / 2);
    let tail = &output[tail_start..output.len().saturating_sub(2048)];
    let e_shifted = spectral_energy_at_freq(tail, sample_rate, freq * 1.12);
    let e_original = spectral_energy_at_freq(tail, sample_rate, freq);
    assert!(
        e_shifted > e_original * 2.0,
        "extra={}: expected pitch-shifted tone to dominate at stream tail: shifted={:.4} original={:.4}",
        extra_samples,
        e_shifted,
        e_original
    );
}

/// Mono streams must get the same transient-driven phase resets as stereo:
/// the scheduler previously only ran for 2-channel streams, leaving mono
/// transients to smear.
#[test]
fn test_streaming_mono_transient_phase_resets() {
    let sample_rate = 44100u32;
    let num_samples = sample_rate as usize * 2;

    // Click train over a quiet tonal bed (EDM-style four-on-the-floor).
    let mut input: Vec<f32> = (0..num_samples)
        .map(|i| 0.2 * (2.0 * PI * 220.0 * i as f32 / sample_rate as f32).sin())
        .collect();
    let click_period = sample_rate as usize / 2; // 120 BPM
    for start in (click_period / 2..num_samples).step_by(click_period) {
        for s in input.iter_mut().skip(start).take(24) {
            *s += 1.5;
        }
    }

    let params = StretchParams::new(1.25)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_fft_size(1024)
        .with_hop_size(256);
    let mut processor = StreamProcessor::new(params);

    let mut output: Vec<f32> = Vec::with_capacity(num_samples * 3);
    for chunk in input.chunks(256) {
        processor.process_into(chunk, &mut output).unwrap();
    }
    processor.flush_into(&mut output).unwrap();

    let stats = processor.transient_reset_stats();
    assert!(
        stats.events_detected_total > 0,
        "mono stream should schedule transient phase resets, got {:?}",
        stats
    );
    assert!(!output.is_empty());
}