euphorium 0.4.0

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

use rodio::{Source, source::SeekError};
use web_time::Duration;

fn get_symmetric_hanning_window(window_length: usize) -> Vec<f32> {
    let mut window = vec![0.0_f32; window_length];
    let scale = 2.0 * std::f32::consts::PI / window_length as f32;
    for (index, value) in window.iter_mut().enumerate() {
        *value = 0.5 * (1.0 - (index as f32 * scale).cos());
    }
    window
}

fn dot_product_multi(
    a: &[Vec<f32>],
    frame_offset_a: usize,
    b: &[Vec<f32>],
    frame_offset_b: usize,
    channels: usize,
    num_frames: usize,
    dot_product: &mut [f32],
) {
    for k in 0..channels {
        let ch_a = &a[k][frame_offset_a..frame_offset_a + num_frames];
        let ch_b = &b[k][frame_offset_b..frame_offset_b + num_frames];
        let mut sum = 0.0_f32;
        for n in 0..num_frames {
            sum += ch_a[n] * ch_b[n];
        }
        dot_product[k] = sum;
    }
}

fn similarity_measure(
    dot_prod: &[f32],
    energy_target: &[f32],
    energy_candidate: &[f32],
    channels: usize,
) -> f32 {
    let epsilon = 1e-12_f32;
    let mut sum = 0.0_f32;
    for n in 0..channels {
        sum += dot_prod[n] * energy_target[n]
            / (energy_target[n] * energy_candidate[n] + epsilon).sqrt();
    }
    sum
}

fn quadratic_interpolation(y_values: &[f32; 3], extremum: &mut f32, extremum_value: &mut f32) {
    let a = 0.5 * (y_values[2] + y_values[0]) - y_values[1];
    let b = 0.5 * (y_values[2] - y_values[0]);
    let c = y_values[1];

    if a == 0.0 {
        *extremum = 0.0;
        *extremum_value = y_values[1];
    } else {
        *extremum = -b / (2.0 * a);
        *extremum_value = a * (*extremum) * (*extremum) + b * (*extremum) + c;
    }
}

struct SimilaritySearch<'a> {
    exclude_interval: (isize, isize),
    target_block: &'a [Vec<f32>],
    target_block_frames: usize,
    search_block: &'a [Vec<f32>],
    search_block_frames: usize,
    channels: usize,
    energy_target_block: &'a [f32],
    energy_candidate_blocks: &'a [f32],
}

fn decimated_search(
    search: &SimilaritySearch<'_>,
    decimation: usize,
    dot_prod: &mut [f32],
) -> usize {
    let num_candidate_blocks = search.search_block_frames - (search.target_block_frames - 1);
    let mut similarity = [0.0_f32; 3];

    let mut n = 0;
    dot_product_multi(
        search.target_block,
        0,
        search.search_block,
        n,
        search.channels,
        search.target_block_frames,
        dot_prod,
    );
    similarity[0] = similarity_measure(
        dot_prod,
        search.energy_target_block,
        &search.energy_candidate_blocks[0..search.channels],
        search.channels,
    );

    let mut best_similarity = similarity[0];
    let mut optimal_index = 0;

    n += decimation;
    if n >= num_candidate_blocks {
        return 0;
    }

    dot_product_multi(
        search.target_block,
        0,
        search.search_block,
        n,
        search.channels,
        search.target_block_frames,
        dot_prod,
    );
    similarity[1] = similarity_measure(
        dot_prod,
        search.energy_target_block,
        &search.energy_candidate_blocks[n * search.channels..(n + 1) * search.channels],
        search.channels,
    );

    n += decimation;
    if n >= num_candidate_blocks {
        return if similarity[1] > similarity[0] {
            decimation.min(num_candidate_blocks - 1)
        } else {
            0
        };
    }

    while n < num_candidate_blocks {
        dot_product_multi(
            search.target_block,
            0,
            search.search_block,
            n,
            search.channels,
            search.target_block_frames,
            dot_prod,
        );
        similarity[2] = similarity_measure(
            dot_prod,
            search.energy_target_block,
            &search.energy_candidate_blocks[n * search.channels..(n + 1) * search.channels],
            search.channels,
        );

        if (similarity[1] > similarity[0] && similarity[1] >= similarity[2])
            || (similarity[1] >= similarity[0] && similarity[1] > similarity[2])
        {
            let mut normalized_candidate_index = 0.0_f32;
            let mut candidate_similarity = 0.0_f32;
            quadratic_interpolation(
                &similarity,
                &mut normalized_candidate_index,
                &mut candidate_similarity,
            );

            let candidate_index = (n - decimation) as isize
                + (normalized_candidate_index * decimation as f32 + 0.5).floor() as isize;

            let in_exclude = candidate_index >= search.exclude_interval.0
                && candidate_index <= search.exclude_interval.1;
            if candidate_similarity > best_similarity && !in_exclude {
                optimal_index = (candidate_index.max(0) as usize).min(num_candidate_blocks - 1);
                best_similarity = candidate_similarity;
            }
        } else if n + decimation >= num_candidate_blocks {
            let in_exclude = (n as isize) >= search.exclude_interval.0
                && (n as isize) <= search.exclude_interval.1;
            if similarity[2] > best_similarity && !in_exclude {
                optimal_index = n.min(num_candidate_blocks - 1);
                best_similarity = similarity[2];
            }
        }

        similarity[0] = similarity[1];
        similarity[1] = similarity[2];
        n += decimation;
    }

    optimal_index.min(num_candidate_blocks - 1)
}

fn full_search(
    low_limit: usize,
    high_limit: usize,
    search: &SimilaritySearch<'_>,
    dot_prod: &mut [f32],
) -> usize {
    let mut best_similarity = -f32::MAX;
    let mut optimal_index = 0;

    for n in low_limit..=high_limit {
        let n_isize = n as isize;
        if n_isize >= search.exclude_interval.0 && n_isize <= search.exclude_interval.1 {
            continue;
        }

        dot_product_multi(
            search.target_block,
            0,
            search.search_block,
            n,
            search.channels,
            search.target_block_frames,
            dot_prod,
        );

        let similarity = similarity_measure(
            dot_prod,
            search.energy_target_block,
            &search.energy_candidate_blocks[n * search.channels..(n + 1) * search.channels],
            search.channels,
        );

        if similarity > best_similarity {
            best_similarity = similarity;
            optimal_index = n;
        }
    }

    optimal_index
}

struct OptimalIndexSearch<'a> {
    search_block: &'a [Vec<f32>],
    search_block_frames: usize,
    target_block: &'a [Vec<f32>],
    target_block_frames: usize,
    channels: usize,
    exclude_interval: (isize, isize),
}

fn compute_optimal_index(
    search: OptimalIndexSearch<'_>,
    energy_candidate_blocks: &mut [f32],
    energy_target_block: &mut [f32],
    dot_prod: &mut [f32],
) -> usize {
    let num_candidate_blocks = search.search_block_frames - (search.target_block_frames - 1);
    let search_decimation = 5;

    multi_channel_moving_block_energies(
        search.search_block,
        search.channels,
        search.target_block_frames,
        energy_candidate_blocks,
    );

    dot_product_multi(
        search.target_block,
        0,
        search.target_block,
        0,
        search.channels,
        search.target_block_frames,
        energy_target_block,
    );

    let similarity_search = SimilaritySearch {
        exclude_interval: search.exclude_interval,
        target_block: search.target_block,
        target_block_frames: search.target_block_frames,
        search_block: search.search_block,
        search_block_frames: search.search_block_frames,
        channels: search.channels,
        energy_target_block,
        energy_candidate_blocks,
    };
    let optimal_index = decimated_search(&similarity_search, search_decimation, dot_prod);

    let lim_low = optimal_index.saturating_sub(search_decimation);
    let lim_high = (optimal_index + search_decimation).min(num_candidate_blocks - 1);

    full_search(lim_low, lim_high, &similarity_search, dot_prod)
}

fn multi_channel_moving_block_energies(
    input: &[Vec<f32>],
    channels: usize,
    frames_per_block: usize,
    energy: &mut [f32],
) {
    let input_frames = input[0].len();
    let num_blocks = input_frames - (frames_per_block - 1);

    for k in 0..channels {
        let input_channel = &input[k];

        // First block of channel k.
        let mut sum = 0.0_f32;
        for &val in input_channel.iter().take(frames_per_block) {
            sum += val * val;
        }
        energy[k] = sum;

        for n in 1..num_blocks {
            let slide_out = input_channel[n - 1];
            let slide_in = input_channel[n + frames_per_block - 1];
            energy[k + n * channels] =
                energy[k + (n - 1) * channels] - slide_out * slide_out + slide_in * slide_in;
        }
    }
}

fn peek_audio_with_zero_prepend(
    input_buffer: &[Vec<f32>],
    start_idx: usize,
    channels: usize,
    read_offset_frames: isize,
    dest: &mut [Vec<f32>],
    dest_frames: usize,
) {
    let mut write_offset = 0;
    let mut num_frames_to_read = dest_frames;
    let mut actual_read_offset = read_offset_frames;

    if read_offset_frames < 0 {
        let num_zero_frames_appended = (-read_offset_frames) as usize;
        let num_zero_frames_appended = num_zero_frames_appended.min(num_frames_to_read);
        actual_read_offset = 0;
        num_frames_to_read -= num_zero_frames_appended;
        write_offset = num_zero_frames_appended;

        for dest_channel in dest.iter_mut().take(channels) {
            dest_channel[0..num_zero_frames_appended].fill(0.0);
        }
    }

    if num_frames_to_read > 0 {
        for (dest_channel, input_channel) in dest.iter_mut().zip(input_buffer).take(channels) {
            let actual_start = (actual_read_offset as usize) + start_idx;
            dest_channel[write_offset..write_offset + num_frames_to_read]
                .copy_from_slice(&input_channel[actual_start..actual_start + num_frames_to_read]);
        }
    }
}

#[allow(dead_code)]
struct WsolaState {
    min_playback_rate: f32,
    max_playback_rate: f32,
    ola_window_size_ms: f32,
    wsola_search_interval_ms: f32,

    channels: usize,
    sample_rate: u32,

    muted_partial_frame: f64,
    output_time: f64,
    search_block_center_offset: usize,
    search_block_index: isize,
    num_candidate_blocks: usize,
    target_block_index: isize,
    ola_window_size: usize,
    ola_hop_size: usize,
    num_complete_frames: usize,
    wsola_output_started: bool,

    ola_window: Vec<f32>,
    transition_window: Vec<f32>,

    wsola_output: Vec<Vec<f32>>,
    wsola_output_size: usize,
    optimal_block: Vec<Vec<f32>>,
    search_block: Vec<Vec<f32>>,
    search_block_size: usize,
    target_block: Vec<Vec<f32>>,
    input_buffer: Vec<Vec<f32>>,
    input_buffer_start_idx: usize,

    input_buffer_final_frames: usize,
    input_buffer_added_silence: usize,
    energy_candidate_blocks: Vec<f32>,
    optimal_index: usize,
    is_final: bool,

    energy_target_block: Vec<f32>,
    dot_prod: Vec<f32>,
}

impl WsolaState {
    fn new(
        channels: usize,
        sample_rate: u32,
        min_playback_rate: f32,
        max_playback_rate: f32,
        ola_window_size_ms: f32,
        wsola_search_interval_ms: f32,
    ) -> Self {
        let mut num_candidate_blocks =
            (wsola_search_interval_ms * sample_rate as f32 / 1000.0) as usize;
        num_candidate_blocks = num_candidate_blocks.max(1);
        let mut ola_window_size = (ola_window_size_ms * sample_rate as f32 / 1000.0) as usize;
        ola_window_size = ola_window_size.max(2);
        ola_window_size += ola_window_size & 1;
        let ola_hop_size = ola_window_size / 2;

        let search_block_center_offset = num_candidate_blocks / 2 + (ola_window_size / 2 - 1);
        let ola_window = get_symmetric_hanning_window(ola_window_size);
        let transition_window = get_symmetric_hanning_window(2 * ola_window_size);

        let wsola_output_size = ola_window_size + ola_hop_size;

        let wsola_output = vec![vec![0.0_f32; wsola_output_size]; channels];
        let optimal_block = vec![vec![0.0_f32; ola_window_size]; channels];
        let search_block_size = num_candidate_blocks + (ola_window_size - 1);
        let search_block = vec![vec![0.0_f32; search_block_size]; channels];
        let target_block = vec![vec![0.0_f32; ola_window_size]; channels];

        let initial_size = 4 * ola_window_size.max(search_block_size);
        let input_buffer = vec![Vec::with_capacity(initial_size); channels];

        let energy_candidate_blocks = vec![0.0_f32; channels * num_candidate_blocks];
        let energy_target_block = vec![0.0_f32; channels];
        let dot_prod = vec![0.0_f32; channels];

        WsolaState {
            min_playback_rate,
            max_playback_rate,
            ola_window_size_ms,
            wsola_search_interval_ms,
            channels,
            sample_rate,
            muted_partial_frame: 0.0,
            output_time: 0.0,
            search_block_center_offset,
            search_block_index: 0,
            num_candidate_blocks,
            target_block_index: 0,
            ola_window_size,
            ola_hop_size,
            num_complete_frames: 0,
            wsola_output_started: false,
            ola_window,
            transition_window,
            wsola_output,
            wsola_output_size,
            optimal_block,
            search_block,
            search_block_size,
            target_block,
            input_buffer,
            input_buffer_start_idx: 0,
            input_buffer_final_frames: 0,
            input_buffer_added_silence: 0,
            energy_candidate_blocks,
            optimal_index: 0,
            is_final: false,
            energy_target_block,
            dot_prod,
        }
    }

    fn reset(&mut self) {
        for ch in 0..self.channels {
            self.input_buffer[ch].clear();
            self.wsola_output[ch].fill(0.0);
        }
        self.input_buffer_start_idx = 0;
        self.input_buffer_final_frames = 0;
        self.input_buffer_added_silence = 0;
        self.output_time = 0.0;
        self.search_block_index = 0;
        self.target_block_index = 0;
        self.num_complete_frames = 0;
        self.wsola_output_started = false;
        self.muted_partial_frame = 0.0;
        self.is_final = false;
    }

    fn input_buffer_frames(&self) -> usize {
        self.input_buffer[0].len() - self.input_buffer_start_idx
    }

    fn seek_buffer(&mut self, frames: usize) {
        assert!(self.input_buffer_frames() >= frames);
        if self.input_buffer_final_frames > 0 {
            self.input_buffer_final_frames = self.input_buffer_final_frames.saturating_sub(frames);
        }
        self.input_buffer_start_idx += frames;

        // Amortized shift to prevent unbounded growth.
        let threshold = 4096.max(2 * self.ola_window_size.max(self.search_block_size));
        if self.input_buffer_start_idx >= threshold {
            self.compact_input_buffer();
        }
    }

    fn compact_input_buffer(&mut self) {
        if self.input_buffer_start_idx == 0 {
            return;
        }
        let start = self.input_buffer_start_idx;
        for i in 0..self.channels {
            let len = self.input_buffer[i].len();
            self.input_buffer[i].copy_within(start..len, 0);
            self.input_buffer[i].truncate(len - start);
        }
        self.input_buffer_start_idx = 0;
    }

    fn set_final(&mut self) {
        if !self.is_final {
            self.input_buffer_final_frames = self.input_buffer_frames();
            self.is_final = true;
        }
    }

    fn target_is_within_search_region(&self) -> bool {
        self.target_block_index >= self.search_block_index
            && self.target_block_index + self.ola_window_size as isize
                <= self.search_block_index + self.search_block_size as isize
    }

    fn get_optimal_block(&mut self) {
        let exclude_interval_length_frames = 160;
        if self.target_is_within_search_region() {
            self.optimal_index = self.target_block_index as usize;
            peek_audio_with_zero_prepend(
                &self.input_buffer,
                self.input_buffer_start_idx,
                self.channels,
                self.target_block_index,
                &mut self.optimal_block,
                self.ola_window_size,
            );
        } else {
            peek_audio_with_zero_prepend(
                &self.input_buffer,
                self.input_buffer_start_idx,
                self.channels,
                self.target_block_index,
                &mut self.target_block,
                self.ola_window_size,
            );
            peek_audio_with_zero_prepend(
                &self.input_buffer,
                self.input_buffer_start_idx,
                self.channels,
                self.search_block_index,
                &mut self.search_block,
                self.search_block_size,
            );

            let last_optimal =
                self.target_block_index - self.ola_hop_size as isize - self.search_block_index;
            let exclude_interval = (
                last_optimal - exclude_interval_length_frames / 2,
                last_optimal + exclude_interval_length_frames / 2,
            );

            let mut optimal_index = compute_optimal_index(
                OptimalIndexSearch {
                    search_block: &self.search_block,
                    search_block_frames: self.search_block_size,
                    target_block: &self.target_block,
                    target_block_frames: self.ola_window_size,
                    channels: self.channels,
                    exclude_interval,
                },
                &mut self.energy_candidate_blocks,
                &mut self.energy_target_block,
                &mut self.dot_prod,
            );

            optimal_index = (optimal_index as isize + self.search_block_index) as usize;
            peek_audio_with_zero_prepend(
                &self.input_buffer,
                self.input_buffer_start_idx,
                self.channels,
                optimal_index as isize,
                &mut self.optimal_block,
                self.ola_window_size,
            );

            for k in 0..self.channels {
                let opt = &mut self.optimal_block[k];
                let tgt = &self.target_block[k];
                for n in 0..self.ola_window_size {
                    opt[n] = opt[n] * self.transition_window[n]
                        + tgt[n] * self.transition_window[self.ola_window_size + n];
                }
            }
            self.optimal_index = optimal_index;
        }

        self.target_block_index = (self.optimal_index + self.ola_hop_size) as isize;
    }

    fn clamp_playback_rate(&self, rate: f32) -> f32 {
        if rate.is_nan() || rate <= 0.0 {
            1.0
        } else {
            rate.clamp(self.min_playback_rate, self.max_playback_rate)
        }
    }

    fn get_updated_time(&self, playback_rate: f32) -> f64 {
        let playback_rate = self.clamp_playback_rate(playback_rate);
        self.output_time + self.ola_hop_size as f64 * playback_rate as f64
    }

    fn get_search_block_index(&self, output_time: f64) -> isize {
        (output_time - self.search_block_center_offset as f64 + 0.5).floor() as isize
    }

    fn frames_needed(&self, playback_rate: f32) -> isize {
        let playback_rate = self.clamp_playback_rate(playback_rate);
        let next_time = self.get_updated_time(playback_rate);
        let search_idx = self.get_search_block_index(next_time);

        let target_needed = self.target_block_index + self.ola_window_size as isize
            - self.input_buffer_frames() as isize;
        let search_needed =
            search_idx + self.search_block_size as isize - self.input_buffer_frames() as isize;

        target_needed.max(search_needed).max(0)
    }

    fn can_perform_wsola(&self, playback_rate: f32) -> bool {
        let playback_rate = self.clamp_playback_rate(playback_rate);
        self.frames_needed(playback_rate) <= 0
    }

    fn add_input_buffer_final_silence(&mut self, playback_rate: f32) {
        let playback_rate = self.clamp_playback_rate(playback_rate);
        let needed = self.frames_needed(playback_rate);
        if needed <= 0 {
            return;
        }

        let needed_usize = needed as usize;
        for ch in 0..self.channels {
            let len = self.input_buffer[ch].len();
            self.input_buffer[ch].resize(len + needed_usize, 0.0);
        }
        self.input_buffer_added_silence += needed_usize;
    }

    fn run_one_wsola_iteration(&mut self, playback_rate: f32) -> bool {
        let playback_rate = self.clamp_playback_rate(playback_rate);
        if !self.can_perform_wsola(playback_rate) {
            return false;
        }

        let next_output_time = self.output_time + self.ola_hop_size as f64 * playback_rate as f64;
        self.output_time = next_output_time;
        self.search_block_index =
            (next_output_time - self.search_block_center_offset as f64 + 0.5).floor() as isize;

        self.remove_old_input_frames();

        assert!(
            self.search_block_index + self.search_block_size as isize
                <= self.input_buffer_frames() as isize
        );

        self.get_optimal_block();

        for k in 0..self.channels {
            if self.wsola_output_started {
                for n in 0..self.ola_hop_size {
                    let out_idx = self.num_complete_frames + n;
                    self.wsola_output[k][out_idx] = self.wsola_output[k][out_idx]
                        * self.ola_window[self.ola_hop_size + n]
                        + self.optimal_block[k][n] * self.ola_window[n];
                }
                let dest_start = self.num_complete_frames + self.ola_hop_size;
                self.wsola_output[k][dest_start..dest_start + self.ola_hop_size].copy_from_slice(
                    &self.optimal_block[k][self.ola_hop_size..self.ola_window_size],
                );
            } else {
                self.wsola_output[k]
                    [self.num_complete_frames..self.num_complete_frames + self.ola_window_size]
                    .copy_from_slice(&self.optimal_block[k][0..self.ola_window_size]);
            }
        }

        self.num_complete_frames += self.ola_hop_size;
        self.wsola_output_started = true;
        true
    }

    fn remove_old_input_frames(&mut self) {
        let earliest_used_index = self.target_block_index.min(self.search_block_index);
        if earliest_used_index <= 0 {
            return;
        }

        let frames = earliest_used_index as usize;
        self.seek_buffer(frames);
        self.target_block_index -= earliest_used_index;
        self.output_time -= earliest_used_index as f64;
        self.search_block_index -= earliest_used_index;
    }

    fn write_completed_frames_to(
        &mut self,
        requested_frames: usize,
        dest: &mut [Vec<f32>],
        dest_offset: usize,
    ) -> usize {
        let rendered_frames = self.num_complete_frames.min(requested_frames);
        if rendered_frames == 0 {
            return 0;
        }

        for (dest_channel, output_channel) in dest
            .iter_mut()
            .zip(&mut self.wsola_output)
            .take(self.channels)
        {
            dest_channel[dest_offset..dest_offset + rendered_frames]
                .copy_from_slice(&output_channel[..rendered_frames]);
            output_channel.copy_within(rendered_frames..self.wsola_output_size, 0);
            output_channel[self.wsola_output_size - rendered_frames..self.wsola_output_size]
                .fill(0.0);
        }

        self.num_complete_frames -= rendered_frames;
        rendered_frames
    }

    fn read_input_buffer(&mut self, dest_size: usize, dest: &mut [Vec<f32>]) -> usize {
        let target_idx = self.target_block_index.max(0) as usize;
        let frames_to_copy = dest_size.min(self.input_buffer_frames().saturating_sub(target_idx));
        if frames_to_copy == 0 {
            return 0;
        }

        let start_idx = self.input_buffer_start_idx;
        for (dest_channel, input_channel) in
            dest.iter_mut().zip(&self.input_buffer).take(self.channels)
        {
            let actual_start = target_idx + start_idx;
            dest_channel[0..frames_to_copy]
                .copy_from_slice(&input_channel[actual_start..actual_start + frames_to_copy]);
        }
        self.seek_buffer(frames_to_copy);
        frames_to_copy
    }

    fn fill_buffer(
        &mut self,
        dest: &mut [Vec<f32>],
        dest_size: usize,
        playback_rate: f32,
    ) -> usize {
        let playback_rate = self.clamp_playback_rate(playback_rate);

        if self.input_buffer_final_frames > 0 {
            self.add_input_buffer_final_silence(playback_rate);
        }

        let slower_step = (self.ola_window_size as f32 * playback_rate).ceil() as usize;
        let faster_step = (self.ola_window_size as f32 / playback_rate).ceil() as usize;

        if self.ola_window_size <= faster_step && slower_step >= self.ola_window_size {
            if self.wsola_output_started {
                self.wsola_output_started = false;
                let sync_time = self.target_block_index;
                self.output_time = sync_time as f64;
                self.search_block_index = self.get_search_block_index(self.output_time);
                self.remove_old_input_frames();
            }

            return self.read_input_buffer(dest_size, dest);
        }

        let mut rendered_frames = 0;
        loop {
            let wrote =
                self.write_completed_frames_to(dest_size - rendered_frames, dest, rendered_frames);
            rendered_frames += wrote;

            if rendered_frames >= dest_size {
                break;
            }

            if !self.run_one_wsola_iteration(playback_rate) {
                break;
            }
        }
        rendered_frames
    }

    #[allow(dead_code)]
    fn frames_available(&self, playback_rate: f32) -> bool {
        (self.input_buffer_final_frames > self.target_block_index.max(0) as usize
            && self.input_buffer_final_frames > 0)
            || self.can_perform_wsola(playback_rate)
            || self.num_complete_frames > 0
    }
}

/// A WSOLA time-stretching source for inputs with fixed channel count and sample rate.
///
/// The input format must not change while the source is being consumed. Such a change
/// cannot be represented by this source because its output format is fixed at construction.
pub struct Wsola<I>
where
    I: Source,
{
    input: I,
    speed: f32,

    min_playback_rate: f32,
    max_playback_rate: f32,
    ola_window_size_ms: f32,
    wsola_search_interval_ms: f32,

    channels: rodio::ChannelCount,
    sample_rate: rodio::SampleRate,

    state: Option<WsolaState>,

    output_samples: Vec<rodio::Sample>,
    output_samples_pos: usize,

    inner_eof: bool,

    // Reusable buffers to avoid allocations in `next()`
    temp_buffer: Vec<Vec<f32>>,
    temp_frame: Vec<f32>,
    fill_dest: Vec<Vec<f32>>,
}

impl<I> Wsola<I>
where
    I: Source,
{
    /// Creates a WSOLA source that plays `input` at the requested speed while preserving pitch.
    pub fn new(input: I, speed: f32) -> Self {
        let channels = input.channels();
        let sample_rate = input.sample_rate();
        let speed = if speed.is_nan() || speed <= 0.0 {
            1.0
        } else {
            speed
        };
        let min_playback_rate = 0.25;
        let max_playback_rate = 8.0;
        let speed = speed.clamp(min_playback_rate, max_playback_rate);

        let channels_usize = channels.get() as usize;
        let state = WsolaState::new(
            channels_usize,
            sample_rate.get(),
            min_playback_rate,
            max_playback_rate,
            12.0,
            40.0,
        );
        let temp_capacity = state.search_block_size + state.ola_window_size;
        let temp_buffer = (0..channels_usize)
            .map(|_| Vec::with_capacity(temp_capacity))
            .collect();
        let temp_frame = vec![0.0; channels_usize];
        let chunk_size = 256;
        let fill_dest = vec![vec![0.0; chunk_size]; channels_usize];

        Self {
            input,
            speed,
            min_playback_rate,
            max_playback_rate,
            ola_window_size_ms: 12.0,
            wsola_search_interval_ms: 40.0,
            channels,
            sample_rate,
            state: Some(state),
            output_samples: Vec::with_capacity(chunk_size * channels_usize),
            output_samples_pos: 0,
            inner_eof: false,
            temp_buffer,
            temp_frame,
            fill_dest,
        }
    }

    /// Creates a WSOLA source with custom playback-rate and analysis-window limits.
    pub fn with_params(
        input: I,
        mut speed: f32,
        mut min_playback_rate: f32,
        mut max_playback_rate: f32,
        mut ola_window_size_ms: f32,
        mut wsola_search_interval_ms: f32,
    ) -> Self {
        let channels = input.channels();
        let sample_rate = input.sample_rate();

        if !min_playback_rate.is_finite() || min_playback_rate <= 0.0 {
            min_playback_rate = 0.25;
        } else {
            min_playback_rate = min_playback_rate.clamp(0.01, 32.0);
        }

        if !max_playback_rate.is_finite() || max_playback_rate <= 0.0 {
            max_playback_rate = 8.0;
        }
        max_playback_rate = max_playback_rate.max(min_playback_rate).min(32.0);

        if speed.is_nan() || speed <= 0.0 {
            speed = 1.0;
        }
        speed = speed.clamp(min_playback_rate, max_playback_rate);

        if !ola_window_size_ms.is_finite() || ola_window_size_ms <= 0.0 {
            ola_window_size_ms = 12.0;
        } else {
            ola_window_size_ms = ola_window_size_ms.clamp(1.0, 1000.0);
        }

        if !wsola_search_interval_ms.is_finite() || wsola_search_interval_ms <= 0.0 {
            wsola_search_interval_ms = 40.0;
        } else {
            wsola_search_interval_ms = wsola_search_interval_ms.clamp(1.0, 1000.0);
        }

        let channels_usize = channels.get() as usize;
        let state = WsolaState::new(
            channels_usize,
            sample_rate.get(),
            min_playback_rate,
            max_playback_rate,
            ola_window_size_ms,
            wsola_search_interval_ms,
        );
        let temp_capacity = state.search_block_size + state.ola_window_size;
        let temp_buffer = (0..channels_usize)
            .map(|_| Vec::with_capacity(temp_capacity))
            .collect();
        let temp_frame = vec![0.0; channels_usize];
        let chunk_size = 256;
        let fill_dest = vec![vec![0.0; chunk_size]; channels_usize];

        Self {
            input,
            speed,
            min_playback_rate,
            max_playback_rate,
            ola_window_size_ms,
            wsola_search_interval_ms,
            channels,
            sample_rate,
            state: Some(state),
            output_samples: Vec::with_capacity(chunk_size * channels_usize),
            output_samples_pos: 0,
            inner_eof: false,
            temp_buffer,
            temp_frame,
            fill_dest,
        }
    }

    /// Changes the playback speed while preserving pitch.
    pub fn set_speed(&mut self, speed: f32) {
        let speed = if speed.is_nan() || speed <= 0.0 {
            1.0
        } else {
            speed
        };
        self.speed = speed.clamp(self.min_playback_rate, self.max_playback_rate);
    }

    /// Returns the current playback speed.
    pub fn playback_speed(&self) -> f32 {
        self.speed
    }

    /// Consumes this wrapper and returns the input source.
    pub fn into_inner(self) -> I {
        self.input
    }

    fn ensure_state(&mut self) -> &mut WsolaState {
        let channels = self.input.channels().get() as usize;
        let sample_rate = self.input.sample_rate().get();

        assert_eq!(
            channels,
            self.channels.get() as usize,
            "Wsola: input source channel count changed mid-stream"
        );
        assert_eq!(
            sample_rate,
            self.sample_rate.get(),
            "Wsola: input source sample rate changed mid-stream"
        );

        if self.state.is_none() {
            self.state = Some(WsolaState::new(
                channels,
                sample_rate,
                self.min_playback_rate,
                self.max_playback_rate,
                self.ola_window_size_ms,
                self.wsola_search_interval_ms,
            ));
            self.output_samples.clear();
            self.output_samples_pos = 0;
            self.inner_eof = false;
        }

        self.state.as_mut().unwrap()
    }
}

impl<I> Iterator for Wsola<I>
where
    I: Source,
{
    type Item = rodio::Sample;

    fn next(&mut self) -> Option<Self::Item> {
        if self.output_samples_pos < self.output_samples.len() {
            let sample = self.output_samples[self.output_samples_pos];
            self.output_samples_pos += 1;
            return Some(sample);
        }

        self.output_samples.clear();
        self.output_samples_pos = 0;

        let speed = self.speed;
        let channels = self.input.channels().get() as usize;

        let needed = {
            let state = self.ensure_state();
            state.frames_needed(speed)
        };

        for ch in 0..channels {
            self.temp_buffer[ch].clear();
        }
        let mut pulled_frames = 0;

        if needed > 0 && !self.inner_eof {
            for _ in 0..needed {
                self.temp_frame.fill(0.0);
                let mut read_ok = true;
                for ch in 0..channels {
                    if let Some(sample) = self.input.next() {
                        self.temp_frame[ch] = sample;
                    } else {
                        read_ok = false;
                        break;
                    }
                }

                if read_ok {
                    for ch in 0..channels {
                        self.temp_buffer[ch].push(self.temp_frame[ch]);
                    }
                    pulled_frames += 1;
                } else {
                    self.inner_eof = true;
                    break;
                }
            }
        }

        let inner_eof = self.inner_eof;
        self.ensure_state();
        let state = self.state.as_mut().unwrap();
        if pulled_frames > 0 {
            for ch in 0..channels {
                state.input_buffer[ch].extend_from_slice(&self.temp_buffer[ch]);
            }
        }
        if inner_eof {
            state.set_final();
        }

        let chunk_size = 256;
        let rendered_frames = state.fill_buffer(&mut self.fill_dest, chunk_size, speed);

        if rendered_frames > 0 {
            self.output_samples.reserve(rendered_frames * channels);
            for f in 0..rendered_frames {
                for ch in 0..channels {
                    self.output_samples
                        .push(self.fill_dest[ch][f] as rodio::Sample);
                }
            }

            let sample = self.output_samples[0];
            self.output_samples_pos = 1;
            Some(sample)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let buffered = self
            .output_samples
            .len()
            .saturating_sub(self.output_samples_pos);
        // The input may already be prefetched into the WSOLA state, and the final
        // overlap adds a speed-dependent tail. Only the output cache is a guaranteed
        // lower bound; without exposing the internal state as an iterator contract,
        // an upper bound cannot be computed safely here.
        (buffered, None)
    }
}

impl<I> Source for Wsola<I>
where
    I: Source,
{
    fn current_span_len(&self) -> Option<usize> {
        None
    }

    fn channels(&self) -> rodio::ChannelCount {
        self.channels
    }

    fn sample_rate(&self) -> rodio::SampleRate {
        self.sample_rate
    }

    fn total_duration(&self) -> Option<Duration> {
        self.input.total_duration().map(|d| d.div_f32(self.speed))
    }

    fn try_seek(&mut self, pos: Duration) -> Result<(), SeekError> {
        let pos_accounting_for_speedup = pos.mul_f32(self.speed);
        self.input.try_seek(pos_accounting_for_speedup)?;
        if let Some(state) = &mut self.state {
            state.reset();
        }
        self.output_samples.clear();
        self.output_samples_pos = 0;
        self.inner_eof = false;
        Ok(())
    }
}

/// Extension methods for wrapping a rodio source with WSOLA time stretching.
pub trait WsolaSourceExt: Source + Sized {
    /// Plays this source at `speed` while preserving its pitch.
    fn wsola(self, speed: f32) -> Wsola<Self> {
        Wsola::new(self, speed)
    }
}

impl<I: Source> WsolaSourceExt for I {}

#[cfg(test)]
mod tests {
    use super::*;

    struct MockSource {
        samples: Vec<rodio::Sample>,
        pos: usize,
        channels: u16,
        sample_rate: u32,
    }

    impl Iterator for MockSource {
        type Item = rodio::Sample;
        fn next(&mut self) -> Option<Self::Item> {
            if self.pos < self.samples.len() {
                let s = self.samples[self.pos];
                self.pos += 1;
                Some(s)
            } else {
                None
            }
        }
        fn size_hint(&self) -> (usize, Option<usize>) {
            let remaining = self.samples.len().saturating_sub(self.pos);
            (remaining, Some(remaining))
        }
    }

    impl Source for MockSource {
        fn current_span_len(&self) -> Option<usize> {
            Some(self.samples.len().saturating_sub(self.pos))
        }
        fn channels(&self) -> rodio::ChannelCount {
            rodio::ChannelCount::new(self.channels).unwrap()
        }
        fn sample_rate(&self) -> rodio::SampleRate {
            rodio::SampleRate::new(self.sample_rate).unwrap()
        }
        fn total_duration(&self) -> Option<Duration> {
            None
        }
        fn try_seek(&mut self, _pos: Duration) -> Result<(), SeekError> {
            self.pos = 0;
            Ok(())
        }
    }

    struct ChangingMockSource {
        samples: Vec<rodio::Sample>,
        pos: usize,
        channels: u16,
        sample_rate: u32,
        change_at: usize,
        new_channels: u16,
    }

    impl Iterator for ChangingMockSource {
        type Item = rodio::Sample;
        fn next(&mut self) -> Option<Self::Item> {
            if self.pos < self.samples.len() {
                let s = self.samples[self.pos];
                self.pos += 1;
                Some(s)
            } else {
                None
            }
        }
    }

    impl Source for ChangingMockSource {
        fn current_span_len(&self) -> Option<usize> {
            None
        }
        fn channels(&self) -> rodio::ChannelCount {
            if self.pos >= self.change_at {
                rodio::ChannelCount::new(self.new_channels).unwrap()
            } else {
                rodio::ChannelCount::new(self.channels).unwrap()
            }
        }
        fn sample_rate(&self) -> rodio::SampleRate {
            rodio::SampleRate::new(self.sample_rate).unwrap()
        }
        fn total_duration(&self) -> Option<Duration> {
            None
        }
        fn try_seek(&mut self, _pos: Duration) -> Result<(), SeekError> {
            Ok(())
        }
    }

    #[test]
    fn test_parameter_sanitization() {
        let input = MockSource {
            samples: vec![0.0 as rodio::Sample; 1000],
            pos: 0,
            channels: 2,
            sample_rate: 44100,
        };

        // Negative/NaN/Zero speed clamps to 1.0 or bounds
        let wsola_neg = Wsola::new(input, -1.5);
        assert_eq!(wsola_neg.playback_speed(), 1.0); // Defaults to 1.0 for <= 0.0

        let input = MockSource {
            samples: vec![0.0 as rodio::Sample; 1000],
            pos: 0,
            channels: 2,
            sample_rate: 44100,
        };
        let wsola_nan = Wsola::new(input, f32::NAN);
        assert_eq!(wsola_nan.playback_speed(), 1.0); // Default to 1.0

        let input = MockSource {
            samples: vec![0.0 as rodio::Sample; 1000],
            pos: 0,
            channels: 2,
            sample_rate: 44100,
        };
        let wsola_with_params = Wsola::with_params(
            input, 12.0, // speed
            0.5,  // min
            4.0,  // max
            -5.0, // window (invalid)
            0.0,  // search (invalid)
        );
        assert_eq!(wsola_with_params.playback_speed(), 4.0); // Clamped to max
        assert_eq!(wsola_with_params.ola_window_size_ms, 12.0); // default
        assert_eq!(wsola_with_params.wsola_search_interval_ms, 40.0); // default

        let input = MockSource {
            samples: vec![0.0 as rodio::Sample; 1000],
            pos: 0,
            channels: 1,
            sample_rate: 44100,
        };
        let wsola_infinite = Wsola::with_params(
            input,
            f32::INFINITY,
            f32::INFINITY,
            f32::INFINITY,
            f32::INFINITY,
            f32::INFINITY,
        );
        assert!(wsola_infinite.playback_speed().is_finite());
        assert!(wsola_infinite.ola_window_size_ms.is_finite());
        assert!(wsola_infinite.wsola_search_interval_ms.is_finite());
    }

    #[test]
    fn test_speed_clamping() {
        let input = MockSource {
            samples: vec![0.0 as rodio::Sample; 4000],
            pos: 0,
            channels: 1,
            sample_rate: 16000,
        };

        // Create Wsola with speed 10.0 (max is 8.0 by default)
        let wsola = Wsola::new(input, 10.0);
        assert_eq!(wsola.playback_speed(), 8.0); // Clamped to max

        // Verify it runs and produces samples instead of silence or panic
        let count = wsola.count();
        assert!(count > 0);
    }

    #[test]
    #[should_panic(expected = "Wsola: input source channel count changed mid-stream")]
    fn test_channel_mismatch_panic() {
        let input = ChangingMockSource {
            samples: vec![0.0 as rodio::Sample; 1000],
            pos: 0,
            channels: 2,
            sample_rate: 16000,
            change_at: 200,
            new_channels: 1,
        };

        let wsola = Wsola::new(input, 1.5);
        // This will process samples and eventually panic when it crosses change_at
        for _ in wsola {}
    }

    #[test]
    fn test_size_hint() {
        let input = MockSource {
            samples: vec![0.0 as rodio::Sample; 2000],
            pos: 0,
            channels: 2,
            sample_rate: 44100,
        };

        let mut wsola = Wsola::new(input, 2.0);
        let hint = wsola.size_hint();
        assert_eq!(hint, (0, None));
        let _ = wsola.next();
        assert_eq!(wsola.size_hint().1, None);
    }

    #[test]
    fn test_amortized_compaction() {
        // Create a large input (e.g. 60,000 stereo frames) to trigger compaction multiple times.
        let mut samples = Vec::new();
        for i in 0..60000 {
            let val = (i as f32).sin() * 0.5;
            samples.push(val);
            samples.push(val);
        }

        let input = MockSource {
            samples: samples.clone(),
            pos: 0,
            channels: 2,
            sample_rate: 44100,
        };

        let wsola = Wsola::new(input, 1.5);
        let output: Vec<_> = wsola.collect();

        // input has 120,000 samples. Output should be roughly 120,000 / 1.5 = 80,000 samples.
        assert!(output.len() > 70000 && output.len() < 90000);
        // Verify output contains non-silent samples (not corrupted/cleared incorrectly)
        assert!(output.iter().any(|&x| x.abs() > 0.01));
    }
}