simple_src 0.4.0

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

use std::collections::VecDeque;
use std::f64::consts::PI;
use std::sync::Arc;

use super::{
    Convert, ConvertMode, Error, Quality, Ratio, Rational, Result, convert_with, output_len,
};

#[inline]
fn sinc_c(x: f64, cutoff: f64) -> f64 {
    if x != 0.0 {
        (PI * x * cutoff).sin() / (PI * x)
    } else {
        cutoff
    }
}

#[inline]
fn bessel_i0(x: f64) -> f64 {
    let mut y = 1.0;
    let mut t = 1.0;
    for k in 1..32 {
        t *= (x / (2.0 * k as f64)).powi(2);
        y += t;
        if t < 1e-10 {
            break;
        }
    }
    y
}

#[inline]
fn windowed_sinc(pos: f64, half_order: f64, beta: f64, i0_beta: f64, cutoff: f64) -> f64 {
    let ax = pos.abs();
    if ax > half_order {
        return 0.0;
    }
    let t = (1.0 - (ax / half_order).powi(2)).max(0.0).sqrt();
    sinc_c(pos, cutoff) * (bessel_i0(beta * t) / i0_beta)
}

fn generic_table_len(quan: u32, order: u32) -> usize {
    let last_real = (order as f64 * 0.5 * quan as f64).floor() as usize;
    last_real + 2
}

/// Extra dB when sizing the FIR from attenuation + transition width so the
/// realized stopband more closely meets the requested `atten`.
const ORDER_ATTEN_MARGIN_DB: f64 = 6.0;

#[inline]
fn generate_filter_table(quan: u32, order: u32, beta: f64, cutoff: f64) -> Vec<f64> {
    let i0_beta = bessel_i0(beta);
    let half_order = order as f64 * 0.5;
    let last_real = (half_order * quan as f64).floor() as usize;
    debug_assert_eq!(last_real + 2, generic_table_len(quan, order));
    let mut filter = Vec::with_capacity(generic_table_len(quan, order));
    for i in 0..=last_real {
        let pos = i as f64 / quan as f64;
        filter.push(windowed_sinc(pos, half_order, beta, i0_beta, cutoff));
    }
    filter.push(0.0);
    // Scale so the integer-delay (frac=0) impulse response has DC gain 1.
    let taps = (order + 1) as usize;
    let mut dc = 0.0;
    for j in 0..taps {
        let pos = j as f64 - half_order;
        dc += windowed_sinc(pos, half_order, beta, i0_beta, cutoff);
    }
    if dc.abs() > 1e-18 {
        let inv = 1.0 / dc;
        for c in &mut filter {
            *c *= inv;
        }
    }
    filter
}

#[inline]
fn generate_fast_lut(len: usize, order: u32, beta: f64, cutoff: f64) -> Vec<Vec<f64>> {
    let mut lut = Vec::with_capacity(len);
    let i0_beta = bessel_i0(beta);
    let half_order = order as f64 * 0.5;
    let taps = order + 1;
    for i in 0..len {
        let pos = i as f64 / len as f64;
        let mut coef_pos = Vec::with_capacity(taps as usize);
        for j in (0..taps).rev() {
            let pos = pos + j as f64 - half_order;
            coef_pos.push(windowed_sinc(pos, half_order, beta, i0_beta, cutoff));
        }
        let dc: f64 = coef_pos.iter().sum();
        if dc.abs() > 1e-18 {
            let inv = 1.0 / dc;
            for c in &mut coef_pos {
                *c *= inv;
            }
        }
        lut.push(coef_pos);
    }
    lut
}

#[inline]
fn calc_kaiser_beta(atten: f64) -> f64 {
    if atten > 50.0 {
        0.1102 * (atten - 8.7)
    } else if atten >= 21.0 {
        0.5842 * (atten - 21.0).powf(0.4) + 0.07886 * (atten - 21.0)
    } else {
        0.0
    }
}

#[inline]
fn calc_trans_width(ratio: f64, atten: f64, order: u32) -> f64 {
    // Inverse of the Kaiser length formula for the *requested* attenuation
    // (no design margin). Used when the caller fixes `order`.
    (atten - 8.0) / (2.285 * order as f64 * PI * ratio.min(1.0))
}

#[inline]
fn calc_order(ratio: f64, atten: f64, trans_width: f64) -> u32 {
    let design_atten = atten + ORDER_ATTEN_MARGIN_DB;
    let mut order =
        f64::ceil((design_atten - 8.0) / (2.285 * trans_width * PI * ratio.min(1.0))) as u32;
    if order < MIN_ORDER {
        order = MIN_ORDER;
    }
    // Prefer even order for a cleaner linear-phase response at Nyquist.
    if order % 2 == 1 {
        order += 1;
    }
    order.min(MAX_ORDER)
}

/// Ideal lowpass cutoff relative to the input sample rate.
///
/// `nyquist` is `min(fs_new, fs_old) / fs_old`. The transition of width
/// `trans_width * nyquist` is placed entirely below that Nyquist: the −6 dB
/// point sits at the pass-band edge `nyquist * (1 - trans_width)`, and the
/// stop-band edge is near `nyquist * (1 - 0.5 * trans_width)`.
#[inline]
fn design_cutoff(ratio: f64, trans_width: f64) -> f64 {
    let nyquist = ratio.min(1.0);
    // Keep within the same range enforced by with_raw / with_raw_fast.
    (nyquist * (1.0 - trans_width)).clamp(0.01, 1.0)
}

enum State {
    Normal,
    Suspend,
}

pub(crate) struct FloatConverter {
    state: State,
    buf: VecDeque<f64>,
    filter: Arc<Vec<f64>>,
    quan: f64,
    half_order: f64,
    step: f64,
    pos: f64,
}

pub(crate) struct RationalConverter {
    state: State,
    buf: VecDeque<f64>,
    filter: Arc<Vec<f64>>,
    quan: f64,
    half_order: f64,
    pos: usize,
    numer: usize,
    denom: usize,
}

pub(crate) struct RationalFastConverter {
    state: State,
    buf: VecDeque<f64>,
    pos: usize,
    numer: usize,
    denom: usize,
    lut: Arc<Vec<Vec<f64>>>,
}

enum ConverterKind {
    Float(FloatConverter),
    Rational(RationalConverter),
    RationalFast(RationalFastConverter),
}

/// Opaque sample-rate converter created by [`Manager::converter`].
pub struct Converter {
    inner: ConverterKind,
}

impl FloatConverter {
    fn new(step: f64, order: u32, quan: u32, filter: Arc<Vec<f64>>) -> Self {
        let taps = (order + 1) as usize;
        let mut buf = VecDeque::with_capacity(taps);
        buf.extend(std::iter::repeat_n(0.0, taps));
        Self {
            state: State::Normal,
            buf,
            filter,
            quan: quan as f64,
            half_order: 0.5 * order as f64,
            pos: 0.0,
            step,
        }
    }

    fn interpolate(&self) -> f64 {
        let coef = self.pos;
        let mut interp = 0.0;
        let pos_max = self.filter.len() - 1;
        let taps = self.buf.len();
        let iter_count = taps / 2;
        let mut left;
        let mut right;
        if taps % 2 == 1 {
            let pos = coef * self.quan;
            let posu = pos as usize;
            let h1 = self.filter[posu];
            let h2 = self.filter[posu + 1];
            let h = h1 + (h2 - h1) * (pos - posu as f64);
            interp += self.buf[iter_count] * h;
            left = iter_count - 1;
            right = iter_count + 1;
        } else {
            left = iter_count - 1;
            right = iter_count;
        }
        let coef = coef + self.half_order;
        for _ in 0..iter_count {
            let pos1 = (coef - left as f64).abs() * self.quan;
            let pos2 = (coef - right as f64).abs() * self.quan;
            let pos1u = pos1 as usize;
            let pos2u = pos2 as usize;
            if pos1u < pos_max {
                let h1 = self.filter[pos1u];
                let h2 = self.filter[pos1u + 1];
                let h = h1 + (h2 - h1) * (pos1 - pos1u as f64);
                interp += self.buf[left] * h;
            }
            if pos2u < pos_max {
                let h1 = self.filter[pos2u];
                let h2 = self.filter[pos2u + 1];
                let h = h1 + (h2 - h1) * (pos2 - pos2u as f64);
                interp += self.buf[right] * h;
            }
            left = left.wrapping_sub(1);
            right = right.wrapping_add(1);
        }
        interp
    }
}

impl RationalConverter {
    fn new(step: Rational, order: u32, quan: u32, filter: Arc<Vec<f64>>) -> Self {
        let taps = (order + 1) as usize;
        let mut buf = VecDeque::with_capacity(taps);
        buf.extend(std::iter::repeat_n(0.0, taps));
        Self {
            state: State::Normal,
            buf,
            filter,
            quan: quan as f64,
            half_order: 0.5 * order as f64,
            pos: 0,
            numer: *step.numer() as usize,
            denom: *step.denom() as usize,
        }
    }

    fn interpolate(&self) -> f64 {
        let coef = self.pos as f64 / self.denom as f64;
        let mut interp = 0.0;
        let pos_max = self.filter.len() - 1;
        let taps = self.buf.len();
        let iter_count = taps / 2;
        let mut left;
        let mut right;
        if taps % 2 == 1 {
            let pos = coef * self.quan;
            let posu = pos as usize;
            let h1 = self.filter[posu];
            let h2 = self.filter[posu + 1];
            let h = h1 + (h2 - h1) * (pos - posu as f64);
            interp += self.buf[iter_count] * h;
            left = iter_count - 1;
            right = iter_count + 1;
        } else {
            left = iter_count - 1;
            right = iter_count;
        }
        let coef = coef + self.half_order;
        for _ in 0..iter_count {
            let pos1 = (coef - left as f64).abs() * self.quan;
            let pos2 = (coef - right as f64).abs() * self.quan;
            let pos1u = pos1 as usize;
            let pos2u = pos2 as usize;
            if pos1u < pos_max {
                let h1 = self.filter[pos1u];
                let h2 = self.filter[pos1u + 1];
                let h = h1 + (h2 - h1) * (pos1 - pos1u as f64);
                interp += self.buf[left] * h;
            }
            if pos2u < pos_max {
                let h1 = self.filter[pos2u];
                let h2 = self.filter[pos2u + 1];
                let h = h1 + (h2 - h1) * (pos2 - pos2u as f64);
                interp += self.buf[right] * h;
            }
            left = left.wrapping_sub(1);
            right = right.wrapping_add(1);
        }
        interp
    }
}

impl RationalFastConverter {
    fn new(step: Rational, order: u32, lut: Arc<Vec<Vec<f64>>>) -> Self {
        let taps = (order + 1) as usize;
        let mut buf = VecDeque::with_capacity(taps);
        buf.extend(std::iter::repeat_n(0.0, taps));
        Self {
            state: State::Normal,
            buf,
            pos: 0,
            numer: *step.numer() as usize,
            denom: *step.denom() as usize,
            lut,
        }
    }

    fn interpolate(&self) -> f64 {
        self.lut[self.pos]
            .iter()
            .zip(self.buf.iter())
            .map(|(h, s)| h * s)
            .sum()
    }
}

impl Convert for FloatConverter {
    fn next_sample<I>(&mut self, iter: &mut I) -> Option<f64>
    where
        I: Iterator<Item = f64>,
    {
        loop {
            match self.state {
                State::Normal => {
                    while self.pos >= 1.0 {
                        self.pos -= 1.0;
                        if let Some(s) = iter.next() {
                            self.buf.pop_front();
                            self.buf.push_back(s);
                        } else {
                            self.state = State::Suspend;
                            return None;
                        }
                    }
                    let interp = self.interpolate();
                    self.pos += self.step;
                    return Some(interp);
                }
                State::Suspend => {
                    let s = iter.next()?;
                    self.buf.pop_front();
                    self.buf.push_back(s);
                    self.state = State::Normal;
                }
            }
        }
    }
}

impl Convert for RationalConverter {
    fn next_sample<I>(&mut self, iter: &mut I) -> Option<f64>
    where
        I: Iterator<Item = f64>,
    {
        loop {
            match self.state {
                State::Normal => {
                    while self.pos >= self.denom {
                        self.pos -= self.denom;
                        if let Some(s) = iter.next() {
                            self.buf.pop_front();
                            self.buf.push_back(s);
                        } else {
                            self.state = State::Suspend;
                            return None;
                        }
                    }
                    let interp = self.interpolate();
                    self.pos += self.numer;
                    return Some(interp);
                }
                State::Suspend => {
                    let s = iter.next()?;
                    self.buf.pop_front();
                    self.buf.push_back(s);
                    self.state = State::Normal;
                }
            }
        }
    }
}

impl Convert for RationalFastConverter {
    fn next_sample<I>(&mut self, iter: &mut I) -> Option<f64>
    where
        I: Iterator<Item = f64>,
        Self: Sized,
    {
        loop {
            match self.state {
                State::Normal => {
                    while self.pos >= self.denom {
                        self.pos -= self.denom;
                        if let Some(s) = iter.next() {
                            self.buf.pop_front();
                            self.buf.push_back(s);
                        } else {
                            self.state = State::Suspend;
                            return None;
                        }
                    }
                    let interp = self.interpolate();
                    self.pos += self.numer;
                    return Some(interp);
                }
                State::Suspend => {
                    let s = iter.next()?;
                    self.buf.pop_front();
                    self.buf.push_back(s);
                    self.state = State::Normal;
                }
            }
        }
    }
}

fn delay_line_empty(buf: &VecDeque<f64>) -> bool {
    buf.iter().all(|&x| x == 0.0)
}

impl Converter {
    fn delay_empty(&self) -> bool {
        match &self.inner {
            ConverterKind::Float(c) => delay_line_empty(&c.buf),
            ConverterKind::Rational(c) => delay_line_empty(&c.buf),
            ConverterKind::RationalFast(c) => delay_line_empty(&c.buf),
        }
    }
}

impl Convert for Converter {
    fn next_sample<I>(&mut self, iter: &mut I) -> Option<f64>
    where
        I: Iterator<Item = f64>,
        Self: Sized,
    {
        match &mut self.inner {
            ConverterKind::Float(float_converter) => float_converter.next_sample(iter),
            ConverterKind::Rational(rational_converter) => rational_converter.next_sample(iter),
            ConverterKind::RationalFast(rational_fast_converter) => {
                rational_fast_converter.next_sample(iter)
            }
        }
    }

    fn flush(&mut self, output: &mut [f64]) -> usize
    where
        Self: Sized,
    {
        // Overrides Convert::flush: stop when the FIR delay is empty instead of
        // filling the whole buffer. Still call until 0 if `output` fills first.
        if self.delay_empty() {
            return 0;
        }
        let mut zeros = std::iter::repeat(0.0);
        let mut produced = 0;
        while produced < output.len() {
            match self.next_sample(&mut zeros) {
                Some(sample) => {
                    output[produced] = sample;
                    produced += 1;
                    if self.delay_empty() {
                        break;
                    }
                }
                None => break,
            }
        }
        produced
    }
}

const MIN_ORDER: u32 = 1;
const MAX_ORDER: u32 = 2048;
const MIN_QUAN: u32 = 1;
const MAX_QUAN: u32 = 16384;
const MIN_ATTEN: f64 = 12.0;
const MAX_ATTEN: f64 = 180.0;

fn check_u32(name: &'static str, value: u32, min: u32, max: u32) -> Result<()> {
    if (min..=max).contains(&value) {
        Ok(())
    } else {
        Err(Error::invalid(name, value as f64, min as f64, max as f64))
    }
}

fn check_f64(name: &'static str, value: f64, min: f64, max: f64) -> Result<()> {
    if value.is_finite() && (min..=max).contains(&value) {
        Ok(())
    } else {
        Err(Error::invalid(name, value, min, max))
    }
}

fn trans_width_from_pass_freq(old_sr: u32, new_sr: u32, pass_freq: u32) -> f64 {
    let min_sr = new_sr.min(old_sr);
    min_sr.saturating_sub(pass_freq.saturating_mul(2)) as f64 / min_sr as f64
}

#[derive(Clone)]
enum Lut {
    Generic(Arc<Vec<f64>>),
    Fast(Arc<Vec<Vec<f64>>>),
}

#[derive(Clone)]
pub struct Manager {
    ratio: Ratio,
    order: u32,
    quan: u32,
    latency: usize,
    lut: Lut,
}

impl Manager {
    fn with_raw_internal(
        ratio: Ratio,
        quan: u32,
        order: u32,
        kaiser_beta: f64,
        cutoff: f64,
    ) -> Result<Self> {
        check_u32("quantify", quan, MIN_QUAN, MAX_QUAN)?;
        check_u32("order", order, MIN_ORDER, MAX_ORDER)?;
        check_f64("kaiser_beta", kaiser_beta, 0.0, 20.0)?;
        check_f64("cutoff", cutoff, 0.01, 1.0)?;
        let filter = generate_filter_table(quan, order, kaiser_beta, cutoff);
        let fratio = ratio.as_float();
        let latency = (fratio * order as f64 * 0.5).round() as usize;
        Ok(Self {
            ratio,
            order,
            quan,
            latency,
            lut: Lut::Generic(Arc::new(filter)),
        })
    }

    fn with_raw_fast_internal(
        ratio: Rational,
        order: u32,
        kaiser_beta: f64,
        cutoff: f64,
    ) -> Result<Self> {
        check_u32("order", order, MIN_ORDER, MAX_ORDER)?;
        check_f64("kaiser_beta", kaiser_beta, 0.0, 20.0)?;
        check_f64("cutoff", cutoff, 0.01, 1.0)?;
        let lut = generate_fast_lut(*ratio.numer() as usize, order, kaiser_beta, cutoff);
        let ratio = Ratio::Rational(ratio);
        let fratio = ratio.as_float();
        let latency = (fratio * order as f64 * 0.5).round() as usize;
        Ok(Self {
            ratio,
            order,
            quan: 0,
            latency,
            lut: Lut::Fast(Arc::new(lut)),
        })
    }

    fn new_internal(ratio: Ratio, atten: f64, quan: u32, trans_width: f64) -> Result<Self> {
        check_f64("attenuation", atten, MIN_ATTEN, MAX_ATTEN)?;
        check_u32("quantify", quan, MIN_QUAN, MAX_QUAN)?;
        check_f64("trans_width", trans_width, 0.01, 1.0)?;
        let kaiser_beta = calc_kaiser_beta(atten);
        let fratio = ratio.as_float();
        let order = calc_order(fratio, atten, trans_width);
        let cutoff = design_cutoff(fratio, trans_width);
        Self::with_raw_internal(ratio, quan, order, kaiser_beta, cutoff)
    }

    fn with_order_internal(ratio: Ratio, atten: f64, quan: u32, order: u32) -> Result<Self> {
        check_f64("attenuation", atten, MIN_ATTEN, MAX_ATTEN)?;
        check_u32("quantify", quan, MIN_QUAN, MAX_QUAN)?;
        check_u32("order", order, MIN_ORDER, MAX_ORDER)?;
        let fratio = ratio.as_float();
        let kaiser_beta = calc_kaiser_beta(atten);
        let trans_width = calc_trans_width(fratio, atten, order);
        let cutoff = design_cutoff(fratio, trans_width);
        Self::with_raw_internal(ratio, quan, order, kaiser_beta, cutoff)
    }

    fn fast_new_internal(ratio: Ratio, atten: f64, trans_width: f64) -> Result<Self> {
        check_f64("attenuation", atten, MIN_ATTEN, MAX_ATTEN)?;
        check_f64("trans_width", trans_width, 0.01, 1.0)?;
        let rational = ratio.require_fast()?;
        let kaiser_beta = calc_kaiser_beta(atten);
        let fratio = ratio.as_float();
        let order = calc_order(fratio, atten, trans_width);
        let cutoff = design_cutoff(fratio, trans_width);
        Self::with_raw_fast_internal(rational, order, kaiser_beta, cutoff)
    }

    fn fast_with_order_internal(ratio: Ratio, atten: f64, order: u32) -> Result<Self> {
        check_f64("attenuation", atten, MIN_ATTEN, MAX_ATTEN)?;
        check_u32("order", order, MIN_ORDER, MAX_ORDER)?;
        let rational = ratio.require_fast()?;
        let fratio = ratio.as_float();
        let kaiser_beta = calc_kaiser_beta(atten);
        let trans_width = calc_trans_width(fratio, atten, order);
        let cutoff = design_cutoff(fratio, trans_width);
        Self::with_raw_fast_internal(rational, order, kaiser_beta, cutoff)
    }

    /// Create a Generic `Manager` with raw parameters, that means all of these
    /// should be calculated in advance.
    ///
    /// Always uses half-table interpolation; `quantify` is required. For a
    /// polyphase LUT, use [`fast_with_raw`](Self::fast_with_raw).
    ///
    /// - ratio: the conversion ratio, fs_new / fs_old, support `[1/16, 16]`.
    ///   Float values may be reduced to a rational under the rules on
    ///   [`ConvertMode`]; use sample-rate constructors for exact pairs.
    /// - quan: the quantify number, usually power of 2, support `[1, 16384]`
    /// - order: the order of interpolation FIR filter, support `[1, 2048]`
    /// - kaiser_beta: the beta parameter of kaiser window method, support `[0.0, 20.0]`
    /// - cutoff: the cutoff of FIR filter, according to target sample rate, in `[0.01, 1.0]`
    pub fn with_raw(
        ratio: f64,
        quan: u32,
        order: u32,
        kaiser_beta: f64,
        cutoff: f64,
    ) -> Result<Self> {
        let ratio = Ratio::try_from_float(ratio)?;
        Self::with_raw_internal(ratio, quan, order, kaiser_beta, cutoff)
    }

    /// Create a Generic `Manager` with attenuation, quantify and transition band width.
    ///
    /// That means the order will be calculated. Always uses half-table
    /// interpolation; `quantify` is required. For a polyphase LUT, use
    /// [`fast`](Self::fast).
    ///
    /// Filter length uses the requested stop-band attenuation plus a small
    /// design margin and is rounded up to an even order. The ideal cutoff is
    /// placed at `min(1, ratio) * (1 - trans_width)` so the transition lies
    /// entirely below the applicable Nyquist (stricter anti-alias / anti-image
    /// than centering the −6 dB point on the band edge).
    ///
    /// - ratio: the conversion ratio, fs_new / fs_old, support `[1/16, 16]`.
    ///   Float values may be reduced to a rational under the rules on
    ///   [`ConvertMode`]; use sample-rate constructors for exact pairs.
    /// - atten: the attenuation in dB, support `[12.0, 180.0]`
    /// - quan: the quantify number, usually power of 2, support `[1, 16384]`
    /// - trans_width: the transition band width in `[0.01, 1.0]`
    #[inline]
    pub fn new(ratio: f64, atten: f64, quan: u32, trans_width: f64) -> Result<Self> {
        let ratio = Ratio::try_from_float(ratio)?;
        Self::new_internal(ratio, atten, quan, trans_width)
    }

    /// Create a Generic `Manager` with attenuation, quantify and order
    ///
    /// That means the transition band will be calculated.
    ///
    /// - ratio: `[1/16, 16]`
    /// - atten: `[12.0, 180.0]`
    /// - quan: `[1, 16384]`
    /// - order: `[1, 2048]`
    #[inline]
    pub fn with_order(ratio: f64, atten: f64, quan: u32, order: u32) -> Result<Self> {
        let ratio = Ratio::try_from_float(ratio)?;
        Self::with_order_internal(ratio, atten, quan, order)
    }

    /// Create a Generic `Manager` with a [`Quality`] preset.
    ///
    /// Uses both [`Quality::attenuation`] and [`Quality::quantify`].
    #[inline]
    pub fn with_quality(ratio: f64, quality: Quality, trans_width: f64) -> Result<Self> {
        Self::new(
            ratio,
            quality.attenuation(),
            quality.quantify(),
            trans_width,
        )
    }

    /// Create a Generic `Manager` with sample rate, attenuation, quantify and pass frequency
    ///
    /// - old_sr: Old sample rate, not 0
    /// - new_sr: New sample rate, not 0
    /// - atten: `[12.0, 180.0]`
    /// - quan: `[1, 16384]`
    /// - pass_freq: pass-band frequency in Hz
    ///
    /// The sample rate ratio should be in `[1/16, 16]`. Always uses half-table
    /// interpolation. For a polyphase LUT, use
    /// [`fast_with_sample_rate`](Self::fast_with_sample_rate).
    #[inline]
    pub fn with_sample_rate(
        old_sr: u32,
        new_sr: u32,
        atten: f64,
        quan: u32,
        pass_freq: u32,
    ) -> Result<Self> {
        let ratio = Ratio::try_from_integers(new_sr, old_sr)?;
        let trans_width = trans_width_from_pass_freq(old_sr, new_sr, pass_freq);
        Self::new_internal(ratio, atten, quan, trans_width)
    }

    /// Create a Generic `Manager` from sample rates and a [`Quality`] preset.
    #[inline]
    pub fn with_sample_rate_quality(
        old_sr: u32,
        new_sr: u32,
        quality: Quality,
        pass_freq: u32,
    ) -> Result<Self> {
        Self::with_sample_rate(
            old_sr,
            new_sr,
            quality.attenuation(),
            quality.quantify(),
            pass_freq,
        )
    }

    /// Create a Fast polyphase `Manager`.
    ///
    /// Requires a rational ratio whose reduced numerator is ≤ 1024; otherwise
    /// returns [`Error::FastUnavailable`]. Does not take `quantify`.
    ///
    /// - ratio: `[1/16, 16]`
    /// - atten: `[12.0, 180.0]`
    /// - trans_width: `[0.01, 1.0]`
    #[inline]
    pub fn fast(ratio: f64, atten: f64, trans_width: f64) -> Result<Self> {
        let ratio = Ratio::try_from_float(ratio)?;
        Self::fast_new_internal(ratio, atten, trans_width)
    }

    /// Create a Fast polyphase `Manager` from attenuation and order.
    #[inline]
    pub fn fast_with_order(ratio: f64, atten: f64, order: u32) -> Result<Self> {
        let ratio = Ratio::try_from_float(ratio)?;
        Self::fast_with_order_internal(ratio, atten, order)
    }

    /// Create a Fast polyphase `Manager` from raw filter parameters.
    ///
    /// Does not take `quantify`. Fails with [`Error::FastUnavailable`] if the
    /// ratio is not eligible.
    pub fn fast_with_raw(ratio: f64, order: u32, kaiser_beta: f64, cutoff: f64) -> Result<Self> {
        let ratio = Ratio::try_from_float(ratio)?;
        let rational = ratio.require_fast()?;
        Self::with_raw_fast_internal(rational, order, kaiser_beta, cutoff)
    }

    /// Create a Fast polyphase `Manager` from a [`Quality`] preset.
    ///
    /// Only [`Quality::attenuation`] is used to compute β and order.
    /// [`Quality::quantify`] is ignored.
    #[inline]
    pub fn fast_with_quality(ratio: f64, quality: Quality, trans_width: f64) -> Result<Self> {
        Self::fast(ratio, quality.attenuation(), trans_width)
    }

    /// Create a Fast polyphase `Manager` from sample rates.
    ///
    /// Typical 44100/48000 conversions should use this (or
    /// [`fast_with_sample_rate_quality`](Self::fast_with_sample_rate_quality)).
    #[inline]
    pub fn fast_with_sample_rate(
        old_sr: u32,
        new_sr: u32,
        atten: f64,
        pass_freq: u32,
    ) -> Result<Self> {
        let ratio = Ratio::try_from_integers(new_sr, old_sr)?;
        let trans_width = trans_width_from_pass_freq(old_sr, new_sr, pass_freq);
        Self::fast_new_internal(ratio, atten, trans_width)
    }

    /// Create a Fast polyphase `Manager` from sample rates and a [`Quality`] preset.
    ///
    /// Only [`Quality::attenuation`] is used; [`Quality::quantify`] is ignored.
    #[inline]
    pub fn fast_with_sample_rate_quality(
        old_sr: u32,
        new_sr: u32,
        quality: Quality,
        pass_freq: u32,
    ) -> Result<Self> {
        Self::fast_with_sample_rate(old_sr, new_sr, quality.attenuation(), pass_freq)
    }

    /// Create a `Converter` which actually implement the interpolation.
    #[inline]
    pub fn converter(&self) -> Converter {
        let inner = match (&self.ratio, &self.lut) {
            (Ratio::Float(ratio), Lut::Generic(filter)) => ConverterKind::Float(
                FloatConverter::new(ratio.recip(), self.order, self.quan, filter.clone()),
            ),
            (Ratio::Rational(ratio), Lut::Generic(filter)) => ConverterKind::Rational(
                RationalConverter::new(ratio.recip(), self.order, self.quan, filter.clone()),
            ),
            (Ratio::Rational(ratio), Lut::Fast(lut)) => ConverterKind::RationalFast(
                RationalFastConverter::new(ratio.recip(), self.order, lut.clone()),
            ),
            _ => unreachable!("LUT kind must match ratio representation"),
        };
        Converter { inner }
    }

    /// Get the latency of the FIR filter in output samples.
    #[inline]
    pub fn latency(&self) -> usize {
        self.latency
    }

    /// Get the order of the FIR filter.
    #[inline]
    pub fn order(&self) -> u32 {
        self.order
    }

    /// Conversion ratio `fs_new / fs_old` actually in use.
    ///
    /// For float constructors this is the approximated rational when one was
    /// accepted, otherwise the original float. See [`ConvertMode`].
    #[inline]
    pub fn ratio(&self) -> f64 {
        self.ratio.as_float()
    }

    /// Reduced integer ratio, if a rational mode was selected.
    ///
    /// `None` when the float could not be fit within the bounded continued-
    /// fraction rules (numerator/denominator ≤ 16384 and relative error
    /// ≤ `1e-12`). Integer sample-rate APIs always yield `Some`.
    #[inline]
    pub fn ratio_parts(&self) -> Option<(i64, i64)> {
        self.ratio.parts()
    }

    /// Which interpolation implementation this manager will construct.
    ///
    /// Float ratios become [`ConvertMode::Rational`] / [`ConvertMode::RationalFast`]
    /// only under the bounded approximation rules on [`ConvertMode`]; otherwise
    /// [`ConvertMode::Float`]. Fast LUT constructors still require an eligible
    /// rational and may return [`Error::FastUnavailable`].
    #[inline]
    pub fn mode(&self) -> ConvertMode {
        match self.lut {
            Lut::Fast(_) => ConvertMode::RationalFast,
            Lut::Generic(_) => match self.ratio {
                Ratio::Float(_) => ConvertMode::Float,
                Ratio::Rational(_) => ConvertMode::Rational,
            },
        }
    }

    /// Coefficient table length.
    ///
    /// Generic is the half Kaiser-sinc table length, including the
    /// interpolation pad. Fast is `numer * (order + 1)`.
    #[inline]
    pub fn lut_len(&self) -> usize {
        match &self.lut {
            Lut::Generic(filter) => filter.len(),
            Lut::Fast(lut) => lut.len() * (self.order as usize + 1),
        }
    }

    /// Expected output length for a complete input buffer of `input_len` samples.
    #[inline]
    pub fn output_len(&self, input_len: usize) -> usize {
        output_len(self.ratio(), input_len)
    }

    /// Convert a complete buffer.
    ///
    /// Pads the end with zeros and drops the leading FIR latency so the
    /// returned length is [`Self::output_len`].
    pub fn convert(&self, input: &[f64]) -> Vec<f64> {
        convert_with(self.converter(), self.latency, self.ratio(), input)
    }

    /// Create a `Builder` to build `Manager`
    #[inline]
    pub fn builder() -> Builder {
        Builder::default()
    }
}

/// The Builder to build `Manager`
///
/// Defaults to Generic interpolation (`quantify` is required). Call
/// [`.fast()`](Builder::fast) for a polyphase LUT; then `quantify` is ignored
/// and an ineligible ratio returns [`Error::FastUnavailable`].
///
/// ```
/// use simple_src::sinc;
///
/// let manager = sinc::Manager::builder()
///     .sample_rate(44100, 48000)
///     .quantify(32)
///     .attenuation(72)
///     .pass_freq(20000)
///     .build();
/// assert!(manager.is_ok());
/// ```
#[derive(Default)]
pub struct Builder {
    ratio: Option<Ratio>,
    ratio_error: Option<Error>,
    order: Option<u32>,
    quan: Option<u32>,
    kaiser_beta: Option<f64>,
    cutoff: Option<f64>,
    atten: Option<f64>,
    trans_width: Option<f64>,
    old_sr: Option<u32>,
    new_sr: Option<u32>,
    pass_freq: Option<u32>,
    use_fast: bool,
}

impl Builder {
    /// Set `ratio` in `[1/16, 16]`.
    ///
    /// May reduce to a bounded rational (see [`ConvertMode`]); use
    /// [`Self::sample_rate`] for an exact integer rate pair.
    pub fn ratio(mut self, ratio: f64) -> Self {
        match Ratio::try_from_float(ratio) {
            Ok(r) => {
                self.ratio = Some(r);
                self.ratio_error = None;
            }
            Err(e) => self.ratio_error = Some(e),
        }
        self
    }

    /// Set old sample rate and new sample rate
    pub fn sample_rate(mut self, old_sr: u32, new_sr: u32) -> Self {
        self.old_sr = Some(old_sr);
        self.new_sr = Some(new_sr);
        self
    }

    /// Set quantify number in `[1, 16384]`.
    ///
    /// Required for Generic. Ignored after [`.fast()`](Self::fast).
    pub fn quantify(mut self, quan: u32) -> Self {
        self.quan = Some(quan);
        self
    }

    /// Set order of filter in `[1, 2048]`
    pub fn order(mut self, order: u32) -> Self {
        self.order = Some(order);
        self
    }

    /// Set beta of kaiser window function in `[0, 20]`
    pub fn kaiser_beta<B: Into<f64>>(mut self, beta: B) -> Self {
        self.kaiser_beta = Some(beta.into());
        self
    }

    /// Set cutoff of filter in `[0.01, 1.0]`
    pub fn cutoff(mut self, cutoff: f64) -> Self {
        self.cutoff = Some(cutoff);
        self
    }

    /// Set attenuation of stop band in `[12, 180]`
    pub fn attenuation<A: Into<f64>>(mut self, atten: A) -> Self {
        self.atten = Some(atten.into());
        self
    }

    /// Set transition band width in `[0.01, 1.0]`
    pub fn trans_width(mut self, width: f64) -> Self {
        self.trans_width = Some(width);
        self
    }

    /// Set pass band width in `[0, 0.99]`
    pub fn pass_width(mut self, width: f64) -> Self {
        self.trans_width = Some(1.0 - width);
        self
    }

    /// Set pass band frequency in Hz, the calculated transition band width
    /// should not less than 0.01
    pub fn pass_freq(mut self, freq: u32) -> Self {
        self.pass_freq = Some(freq);
        self
    }

    /// Set attenuation and quantify from a [`Quality`] preset.
    ///
    /// After [`.fast()`](Self::fast), only attenuation is used; quantify is
    /// ignored.
    pub fn quality(mut self, quality: Quality) -> Self {
        self.atten = Some(quality.attenuation());
        self.quan = Some(quality.quantify());
        self
    }

    /// Build a Fast polyphase LUT. `quantify` is not required and is ignored
    /// if set. Ineligible ratios return [`Error::FastUnavailable`].
    pub fn fast(mut self) -> Self {
        self.use_fast = true;
        self
    }

    /// Build Generic half-table interpolation (the default). `quantify` is
    /// required.
    pub fn generic(mut self) -> Self {
        self.use_fast = false;
        self
    }

    fn resolved_ratio(&self) -> Result<Ratio> {
        self.ratio_error.clone().map_or(Ok(()), Err)?;
        match (self.ratio, self.old_sr, self.new_sr) {
            (Some(ratio), _, _) => Ok(ratio),
            (_, Some(old_sr), Some(new_sr)) => Ratio::try_from_integers(new_sr, old_sr),
            _ => Err(Error::missing("ratio or sample_rate")),
        }
    }

    /// Build the `Manager`, there are the following combinations in order:
    ///
    /// Generic (default; `quantify` required):
    ///
    /// - ratio, quantify, order, kaiser_beta, cutoff
    /// - ratio, attenuation, quantify, trans_width or pass_width
    /// - ratio, attenuation, quantify, order
    /// - sample_rate, attenuation, quantify, pass_freq
    ///
    /// Fast ([`.fast()`](Self::fast); `quantify` ignored):
    ///
    /// - ratio, order, kaiser_beta, cutoff
    /// - ratio, attenuation, trans_width or pass_width
    /// - ratio, attenuation, order
    /// - sample_rate, attenuation, pass_freq
    ///
    /// For example, this is the first Generic situation:
    ///
    /// ```
    /// use simple_src::sinc;
    ///
    /// let manager = sinc::Builder::default()
    ///     .ratio(0.5)
    ///     .quantify(32)
    ///     .order(32)
    ///     .kaiser_beta(7.0)
    ///     .cutoff(0.8)
    ///     .build();
    /// assert!(manager.is_ok());
    /// ```
    pub fn build(self) -> Result<Manager> {
        if self.use_fast {
            return self.build_fast();
        }
        let ratio = self.resolved_ratio()?;
        let Some(quan) = self.quan else {
            return Err(Error::missing("quantify"));
        };
        match (
            self.order,
            self.kaiser_beta,
            self.cutoff,
            self.atten,
            self.trans_width,
            self.old_sr,
            self.new_sr,
            self.pass_freq,
        ) {
            (Some(order), Some(kaiser_beta), Some(cutoff), _, _, _, _, _) => {
                Manager::with_raw_internal(ratio, quan, order, kaiser_beta, cutoff)
            }
            (_, _, _, Some(atten), Some(trans_width), _, _, _) => {
                Manager::new_internal(ratio, atten, quan, trans_width)
            }
            (Some(order), _, _, Some(atten), _, _, _, _) => {
                Manager::with_order_internal(ratio, atten, quan, order)
            }
            (_, _, _, Some(atten), _, Some(old_sr), Some(new_sr), Some(pass_freq)) => {
                Manager::with_sample_rate(old_sr, new_sr, atten, quan, pass_freq)
            }
            _ => Err(Error::missing(
                "attenuation with trans_width/order/pass_freq, or raw cutoff",
            )),
        }
    }

    fn build_fast(self) -> Result<Manager> {
        let ratio = self.resolved_ratio()?;
        match (
            self.order,
            self.kaiser_beta,
            self.cutoff,
            self.atten,
            self.trans_width,
            self.old_sr,
            self.new_sr,
            self.pass_freq,
        ) {
            (Some(order), Some(kaiser_beta), Some(cutoff), _, _, _, _, _) => {
                let rational = ratio.require_fast()?;
                Manager::with_raw_fast_internal(rational, order, kaiser_beta, cutoff)
            }
            (_, _, _, Some(atten), Some(trans_width), _, _, _) => {
                Manager::fast_new_internal(ratio, atten, trans_width)
            }
            (Some(order), _, _, Some(atten), _, _, _, _) => {
                Manager::fast_with_order_internal(ratio, atten, order)
            }
            (_, _, _, Some(atten), _, Some(old_sr), Some(new_sr), Some(pass_freq)) => {
                Manager::fast_with_sample_rate(old_sr, new_sr, atten, pass_freq)
            }
            _ => Err(Error::missing(
                "attenuation with trans_width/order/pass_freq, or raw cutoff",
            )),
        }
    }
}

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

    #[test]
    fn test_manager_with_raw() {
        assert!(Manager::with_raw(2.0, 32, 32, 5.0, 0.8).is_ok());
        assert!(Manager::with_raw(2.0, 0, 32, 5.0, 0.8).is_err());
        assert!(Manager::with_raw(2.0, 32, 0, 5.0, 0.8).is_err());
        assert!(Manager::with_raw(2.0, 32, 32, 5.0, 0.0).is_err());
        assert!(Manager::with_raw(2.0, 32, 32, 5.0, 1.1).is_err());
        assert!(Manager::with_raw(2.0, 32, 32, -0.1, 0.8).is_err());
        assert!(Manager::with_raw(2.0, 32, 32, 20.1, 0.8).is_err());
        assert!(Manager::fast_with_raw(2.0, 32, 5.0, 0.8).is_ok());
    }

    #[test]
    fn test_manager_new() {
        assert!(Manager::new(2.0, 72.0, 32, 0.1).is_ok());
        assert!(Manager::new(2.0, 72.0, 0, 0.1).is_err());
        assert!(Manager::new(2.0, 72.0, 32, 0.0).is_err());
        assert!(Manager::new(2.0, 72.0, 32, 1.1).is_err());
        assert!(Manager::new(2.0, 12.0, 32, 0.1).is_ok());
        assert!(Manager::new(2.0, 11.9, 32, 0.1).is_err());
        let generic = Manager::new(2.0, 72.0, 32, 0.1).unwrap();
        assert_eq!(generic.mode(), ConvertMode::Rational);
        assert_eq!(generic.lut_len(), generic_table_len(32, generic.order()));
    }

    #[test]
    fn test_manager_fast() {
        let fast = Manager::fast(2.0, 72.0, 0.1).unwrap();
        assert_eq!(fast.mode(), ConvertMode::RationalFast);
        assert_eq!(fast.lut_len(), 2 * (fast.order() as usize + 1));
        let sr = Manager::fast_with_sample_rate(44100, 48000, 72.0, 20000).unwrap();
        assert_eq!(sr.mode(), ConvertMode::RationalFast);
        assert_eq!(sr.ratio_parts(), Some((160, 147)));
        assert!(matches!(
            Manager::fast_with_sample_rate(1024, 1025, 72.0, 400),
            Err(Error::FastUnavailable {
                numer: Some(1025),
                ..
            })
        ));
    }

    #[test]
    fn test_quality_generic_vs_fast() {
        let quality = Quality::Bit8Better;
        let trans_width = 0.1;
        let generic = Manager::with_quality(2.0, quality, trans_width).unwrap();
        let fast = Manager::fast_with_quality(2.0, quality, trans_width).unwrap();
        assert_eq!(generic.order(), fast.order());
        assert_eq!(generic.mode(), ConvertMode::Rational);
        assert_eq!(fast.mode(), ConvertMode::RationalFast);
        assert_eq!(
            generic.lut_len(),
            generic_table_len(quality.quantify(), generic.order())
        );
    }

    #[test]
    fn test_manager_with_order() {
        assert!(Manager::with_order(2.0, 72.0, 32, 32).is_ok());
        assert!(Manager::with_order(2.0, 72.0, 32, 0).is_err());
        assert!(Manager::with_order(2.0, 72.0, 0, 32).is_err());
        assert!(Manager::with_order(2.0, 12.0, 32, 32).is_ok());
        assert!(Manager::with_order(2.0, 11.9, 32, 32).is_err());
        assert!(Manager::fast_with_order(2.0, 72.0, 32).is_ok());
    }

    #[test]
    fn test_builder() {
        assert!(Manager::builder().build().is_err());
        let manager = Manager::builder()
            .sample_rate(44100, 48000)
            .quantify(32)
            .attenuation(72)
            .pass_freq(20000)
            .build();
        assert!(manager.is_ok());
        assert_eq!(manager.unwrap().mode(), ConvertMode::Rational);
        let fast = Manager::builder()
            .sample_rate(44100, 48000)
            .attenuation(72)
            .pass_freq(20000)
            .fast()
            .build();
        assert!(fast.is_ok());
        assert_eq!(fast.unwrap().mode(), ConvertMode::RationalFast);
        let ignored_quan = Manager::builder()
            .ratio(2.0)
            .quantify(32)
            .attenuation(72)
            .trans_width(0.1)
            .fast()
            .build()
            .unwrap();
        assert_eq!(ignored_quan.mode(), ConvertMode::RationalFast);
        assert!(Manager::builder().ratio(0.0).quantify(8).build().is_err());
        let preset = Manager::with_sample_rate_quality(44100, 48000, Quality::Bit16Better, 20000);
        assert!(preset.is_ok());
        assert_eq!(preset.as_ref().unwrap().ratio_parts(), Some((160, 147)));
        assert_eq!(preset.unwrap().mode(), ConvertMode::Rational);
    }

    #[test]
    fn inexact_ratio_uses_float_phase() {
        let manager = Manager::with_quality(std::f64::consts::PI, Quality::Bit8Fast, 0.2).unwrap();
        assert_eq!(manager.mode(), ConvertMode::Float);
        assert_eq!(manager.ratio_parts(), None);
        assert!((manager.ratio() - std::f64::consts::PI).abs() < 1e-15);
        assert!(matches!(
            Manager::fast(std::f64::consts::PI, 48.0, 0.2),
            Err(Error::FastUnavailable { numer: None, .. })
        ));
        let _ = manager.convert(&[1.0, 0.0, -1.0, 0.0, 1.0]);
    }

    #[test]
    fn odd_order_odd_quantify_covers_half_table() {
        let odd = Manager::with_order(2.0, 48.0, 7, 5).unwrap();
        let even = Manager::with_order(2.0, 48.0, 8, 5).unwrap();
        assert_eq!(odd.lut_len(), generic_table_len(7, 5));
        assert_eq!(even.lut_len(), generic_table_len(8, 5));
        let input = vec![1.0; 64];
        let odd_out = odd.convert(&input);
        let even_out = even.convert(&input);
        let dc = |m: &Manager, out: &[f64]| {
            let start = m.latency().max(8);
            let end = out.len().saturating_sub(8).max(start + 1);
            let body = &out[start..end];
            body.iter().sum::<f64>() / body.len() as f64
        };
        let odd_dc = dc(&odd, &odd_out);
        let even_dc = dc(&even, &even_out);
        assert!(
            (odd_dc - even_dc).abs() < 0.02,
            "odd dc {odd_dc} vs even dc {even_dc}"
        );
    }

    #[test]
    fn flush_stops_when_delay_empty() {
        let manager = Manager::with_quality(2.0, Quality::Bit8Fast, 0.2).unwrap();
        let mut cv = manager.converter();
        assert_eq!(cv.flush(&mut [0.0; 64]), 0);
        let input: Vec<f64> = (0..32).map(|i| (i as f64).sin()).collect();
        let mut tmp = [0.0; 64];
        let mut pos = 0;
        while pos < input.len() {
            let (c, _) = cv.process_block(&input[pos..], &mut tmp);
            if c == 0 {
                break;
            }
            pos += c;
        }
        let n = cv.flush(&mut [0.0; 4096]);
        assert!(n > 0);
        assert!(n < 4096, "flush should not fill a huge buffer, got {n}");
        assert_eq!(cv.flush(&mut [0.0; 64]), 0);
    }

    #[test]
    fn calc_order_adds_margin_and_is_even() {
        let without_margin = f64::ceil((96.0 - 8.0) / (2.285 * 0.1 * PI * 1.0)) as u32;
        let with_margin = calc_order(1.0, 96.0, 0.1);
        assert!(with_margin > without_margin);
        assert_eq!(with_margin % 2, 0);
        assert!(with_margin <= MAX_ORDER);
        // Explicit order path is unchanged by the margin helper.
        assert_eq!(
            calc_trans_width(1.0, 96.0, without_margin),
            (96.0 - 8.0) / (2.285 * without_margin as f64 * PI)
        );
    }

    #[test]
    fn design_cutoff_puts_transition_below_nyquist() {
        let ratio = 44100.0 / 48000.0;
        let tw = 0.1;
        let c = design_cutoff(ratio, tw);
        let nyq = ratio.min(1.0);
        assert!((c - nyq * (1.0 - tw)).abs() < 1e-15);
        // Stop edge of a Kaiser band centered on cutoff is below Nyquist.
        let stop = c + 0.5 * tw * nyq;
        assert!(stop < nyq + 1e-15);
    }

    #[test]
    fn normalized_dc_gain_is_near_unity() {
        for (ratio, quality, tw) in [
            (2.0, Quality::Bit8Fast, 0.2),
            (0.5, Quality::Bit8Fast, 0.2),
            (2.0, Quality::Bit16Fast, 0.1),
            (48000.0 / 44100.0, Quality::Bit16Fast, 0.1),
        ] {
            let generic = Manager::with_quality(ratio, quality, tw).unwrap();
            let fast = Manager::fast_with_quality(ratio, quality, tw).unwrap();
            assert_eq!(generic.order() % 2, 0);
            assert_eq!(fast.order() % 2, 0);
            for (label, m) in [("generic", generic), ("fast", fast)] {
                let out = m.convert(&vec![1.0; 512]);
                let start = m.latency().max(32);
                let end = out.len().saturating_sub(32).max(start + 1);
                let avg = out[start..end].iter().sum::<f64>() / (end - start) as f64;
                assert!(
                    (avg - 1.0).abs() < 1e-3,
                    "{label} ratio={ratio} quality={quality:?} dc={avg}"
                );
            }
        }
    }
}