nidhi 1.1.0

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

use alloc::string::String;
use alloc::vec::Vec;

use crate::envelope::AdsrConfig;
use crate::error::Result;
use crate::instrument::Instrument;
use crate::loop_mode::LoopMode;
use crate::sample::SampleId;
use crate::zone::{FilterMode, Zone};

/// Parse a note name (e.g., `c4`, `f#3`, `eb5`) or numeric MIDI value to a MIDI note number.
///
/// Supports C-1 through G9 (MIDI 0–127). Accidentals: `#` or `s` for sharp, `b` for flat.
#[must_use]
pub fn parse_note_or_number(s: &str) -> Option<u8> {
    // Try numeric first
    if let Ok(v) = s.parse::<u8>() {
        return Some(v);
    }

    let bytes = s.as_bytes();
    if bytes.is_empty() {
        return None;
    }

    // Note base: c=0, d=2, e=4, f=5, g=7, a=9, b=11
    let note_base = match bytes[0].to_ascii_lowercase() {
        b'c' => 0i32,
        b'd' => 2,
        b'e' => 4,
        b'f' => 5,
        b'g' => 7,
        b'a' => 9,
        b'b' => 11,
        _ => return None,
    };

    let mut idx = 1;
    let mut accidental = 0i32;

    // Check for accidental
    if idx < bytes.len() {
        match bytes[idx] {
            b'#' | b's' => {
                accidental = 1;
                idx += 1;
            }
            b'b' if idx + 1 < bytes.len() && bytes[idx + 1].is_ascii_digit() => {
                // Only treat 'b' as flat if followed by digit (else it's note B)
                accidental = -1;
                idx += 1;
            }
            _ => {}
        }
    }

    // Parse octave (may be negative, e.g. "c-1")
    let octave_str = &s[idx..];
    let octave: i32 = octave_str.parse().ok()?;

    let midi = (octave + 1) * 12 + note_base + accidental;
    if (0..=127).contains(&midi) {
        Some(midi as u8)
    } else {
        None
    }
}

/// Intermediate representation of one SFZ section's opcodes.
///
/// Stores all parsed opcodes for a `<region>`, `<group>`, or `<global>` section.
/// Fields use `Option` or sentinel defaults so that inheritance (global → group → region)
/// can be resolved: a `None` or default value means "inherit from parent".
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[must_use]
pub struct SfzRegion {
    /// Sample filename (relative to SFZ file location).
    pub sample: Option<String>,
    /// Low key of the key range (default 0).
    pub lokey: u8,
    /// High key of the key range (default 127).
    pub hikey: u8,
    /// Low velocity of the velocity range (default 1).
    pub lovel: u8,
    /// High velocity of the velocity range (default 127).
    pub hivel: u8,
    /// Root note — the MIDI note at which the sample plays at original pitch (default 60).
    pub pitch_keycenter: u8,
    /// Fine tuning in cents.
    pub tune: i32,
    /// Volume in dB.
    pub volume: f32,
    /// Pan position (-100 to 100, mapped to -1.0..1.0 on export).
    pub pan: f32,
    /// Loop mode string: `"no_loop"`, `"loop_continuous"`, `"loop_sustain"`, `"one_shot"`.
    pub loop_mode: Option<String>,
    /// Loop start frame.
    pub loop_start: usize,
    /// Loop end frame.
    pub loop_end: usize,
    /// Round-robin group (SFZ `seq_position`).
    pub group: u32,
    /// Amplitude envelope attack time in seconds.
    pub ampeg_attack: f32,
    /// Amplitude envelope decay time in seconds.
    pub ampeg_decay: f32,
    /// Amplitude envelope sustain level (0–100, mapped to 0.0–1.0 on export).
    pub ampeg_sustain: f32,
    /// Amplitude envelope release time in seconds.
    pub ampeg_release: f32,
    /// Lowpass filter cutoff in Hz.
    pub cutoff: f32,
    /// Filter velocity tracking in cents (mapped to 0.0–1.0 on export).
    pub fil_veltrack: f32,
    /// Filter envelope attack time in seconds.
    pub fileg_attack: f32,
    /// Filter envelope decay time in seconds.
    pub fileg_decay: f32,
    /// Filter envelope sustain level (0–100).
    pub fileg_sustain: f32,
    /// Filter envelope release time in seconds.
    pub fileg_release: f32,
    /// Filter envelope depth in cents.
    pub fileg_depth: f32,
    /// Transpose in semitones.
    pub transpose: i32,
    /// Sample start offset in frames.
    pub offset: usize,
    /// Sample end position in frames (0 = full sample).
    pub end: usize,
    /// Filter resonance (Q factor).
    pub resonance: f32,
    /// Filter type string.
    pub fil_type: Option<String>,
    /// `key` shorthand (sets lokey=hikey=pitch_keycenter).
    pub key: Option<u8>,
    /// Pitch LFO rate in Hz.
    pub pitchlfo_freq: f32,
    /// Pitch LFO depth in cents.
    pub pitchlfo_depth: f32,
    /// Filter LFO rate in Hz.
    pub fillfo_freq: f32,
    /// Filter LFO depth in cents.
    pub fillfo_depth: f32,
    /// Filter key tracking in cents (0–1200).
    pub fil_keytrack: f32,
    /// Output bus index.
    pub output: u8,
    /// CC modulation entries: `(param_name, cc_number, depth)`.
    /// Parsed from SFZ v2 `param_onccN=depth` opcodes.
    pub cc_modulations: Vec<(String, u8, f32)>,
}

impl Default for SfzRegion {
    fn default() -> Self {
        Self {
            sample: None,
            lokey: 0,
            hikey: 127,
            lovel: 1,
            hivel: 127,
            pitch_keycenter: 60,
            tune: 0,
            volume: 0.0,
            pan: 0.0,
            loop_mode: None,
            loop_start: 0,
            loop_end: 0,
            group: 0,
            ampeg_attack: 0.0,
            ampeg_decay: 0.0,
            ampeg_sustain: 100.0,
            ampeg_release: 0.0,
            cutoff: 0.0,
            fil_veltrack: 0.0,
            fileg_attack: 0.0,
            fileg_decay: 0.0,
            fileg_sustain: 100.0,
            fileg_release: 0.0,
            fileg_depth: 0.0,
            transpose: 0,
            offset: 0,
            end: 0,
            resonance: 0.0,
            fil_type: None,
            key: None,
            pitchlfo_freq: 0.0,
            pitchlfo_depth: 0.0,
            fillfo_freq: 0.0,
            fillfo_depth: 0.0,
            fil_keytrack: 0.0,
            output: 0,
            cc_modulations: Vec::new(),
        }
    }
}

impl SfzRegion {
    /// Create a new `SfzRegion` with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Apply an opcode key=value pair, ignoring unknown opcodes.
    fn apply_opcode(&mut self, key: &str, value: &str) {
        match key {
            "sample" => self.sample = Some(String::from(value)),
            "lokey" => {
                if let Some(v) = parse_note_or_number(value) {
                    self.lokey = v;
                }
            }
            "hikey" => {
                if let Some(v) = parse_note_or_number(value) {
                    self.hikey = v;
                }
            }
            "key" => {
                if let Some(v) = parse_note_or_number(value) {
                    self.key = Some(v);
                }
            }
            "lovel" => {
                if let Ok(v) = value.parse::<u8>() {
                    self.lovel = v;
                }
            }
            "hivel" => {
                if let Ok(v) = value.parse::<u8>() {
                    self.hivel = v;
                }
            }
            "pitch_keycenter" => {
                if let Some(v) = parse_note_or_number(value) {
                    self.pitch_keycenter = v;
                }
            }
            "tune" => {
                if let Ok(v) = value.parse::<i32>() {
                    self.tune = v;
                }
            }
            "volume" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.volume = v;
                }
            }
            "pan" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.pan = v.clamp(-100.0, 100.0);
                }
            }
            "loop_mode" | "loopmode" => self.loop_mode = Some(String::from(value)),
            "loop_start" | "loopstart" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.loop_start = v;
                }
            }
            "loop_end" | "loopend" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.loop_end = v;
                }
            }
            "seq_position" => {
                if let Ok(v) = value.parse::<u32>() {
                    self.group = v;
                }
            }
            "group" => {
                if let Ok(v) = value.parse::<u32>() {
                    self.group = v;
                }
            }
            "ampeg_attack" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.ampeg_attack = v.max(0.0);
                }
            }
            "ampeg_decay" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.ampeg_decay = v.max(0.0);
                }
            }
            "ampeg_sustain" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.ampeg_sustain = v.clamp(0.0, 100.0);
                }
            }
            "ampeg_release" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.ampeg_release = v.max(0.0);
                }
            }
            "cutoff" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.cutoff = v.max(0.0);
                }
            }
            "fil_veltrack" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fil_veltrack = v;
                }
            }
            "fileg_attack" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fileg_attack = v.max(0.0);
                }
            }
            "fileg_decay" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fileg_decay = v.max(0.0);
                }
            }
            "fileg_sustain" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fileg_sustain = v.clamp(0.0, 100.0);
                }
            }
            "fileg_release" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fileg_release = v.max(0.0);
                }
            }
            "fileg_depth" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fileg_depth = v.clamp(-9600.0, 9600.0);
                }
            }
            "transpose" => {
                if let Ok(v) = value.parse::<i32>() {
                    self.transpose = v;
                }
            }
            "offset" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.offset = v;
                }
            }
            "end" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.end = v;
                }
            }
            "resonance" | "fil_resonance" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.resonance = v.max(0.0);
                }
            }
            "fil_type" | "filtype" => {
                self.fil_type = Some(String::from(value));
            }
            "pitchlfo_freq" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.pitchlfo_freq = v.max(0.0);
                }
            }
            "pitchlfo_depth" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.pitchlfo_depth = v;
                }
            }
            "fillfo_freq" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fillfo_freq = v.max(0.0);
                }
            }
            "fillfo_depth" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fillfo_depth = v;
                }
            }
            "fil_keytrack" => {
                if let Ok(v) = value.parse::<f32>() {
                    self.fil_keytrack = v.clamp(0.0, 1200.0);
                }
            }
            "output" => {
                if let Ok(v) = value.parse::<u8>() {
                    self.output = v;
                }
            }
            // SFZ v2 CC modulation: param_onccN=depth
            _ if key.contains("_oncc") => {
                if let Some(pos) = key.find("_oncc") {
                    let param = &key[..pos];
                    let cc_str = &key[pos + 5..];
                    if let (Ok(cc), Ok(depth)) = (cc_str.parse::<u8>(), value.parse::<f32>()) {
                        self.cc_modulations.push((String::from(param), cc, depth));
                    }
                }
            }
            // Unknown opcodes are silently ignored per SFZ spec convention.
            _ => {}
        }
    }

    /// Merge another region's non-default values onto `self` (used for inheritance).
    ///
    /// Values from `parent` are applied only where `self` still has the default value.
    /// This implements the SFZ inheritance chain: global → group → region.
    fn inherit_from(&mut self, parent: &SfzRegion) {
        if self.sample.is_none() {
            self.sample.clone_from(&parent.sample);
        }
        // For numeric fields, we inherit by checking if they are at their defaults.
        // This is a pragmatic approach — explicit zero values in a child will be kept.
        if self.lokey == 0 && parent.lokey != 0 {
            self.lokey = parent.lokey;
        }
        if self.hikey == 127 && parent.hikey != 127 {
            self.hikey = parent.hikey;
        }
        if self.lovel == 1 && parent.lovel != 1 {
            self.lovel = parent.lovel;
        }
        if self.hivel == 127 && parent.hivel != 127 {
            self.hivel = parent.hivel;
        }
        if self.pitch_keycenter == 60 && parent.pitch_keycenter != 60 {
            self.pitch_keycenter = parent.pitch_keycenter;
        }
        if self.tune == 0 && parent.tune != 0 {
            self.tune = parent.tune;
        }
        if self.volume == 0.0 && parent.volume != 0.0 {
            self.volume = parent.volume;
        }
        if self.pan == 0.0 && parent.pan != 0.0 {
            self.pan = parent.pan;
        }
        if self.loop_mode.is_none() {
            self.loop_mode.clone_from(&parent.loop_mode);
        }
        if self.loop_start == 0 && parent.loop_start != 0 {
            self.loop_start = parent.loop_start;
        }
        if self.loop_end == 0 && parent.loop_end != 0 {
            self.loop_end = parent.loop_end;
        }
        if self.group == 0 && parent.group != 0 {
            self.group = parent.group;
        }
        if self.ampeg_attack == 0.0 && parent.ampeg_attack != 0.0 {
            self.ampeg_attack = parent.ampeg_attack;
        }
        if self.ampeg_decay == 0.0 && parent.ampeg_decay != 0.0 {
            self.ampeg_decay = parent.ampeg_decay;
        }
        if self.ampeg_sustain == 100.0 && parent.ampeg_sustain != 100.0 {
            self.ampeg_sustain = parent.ampeg_sustain;
        }
        if self.ampeg_release == 0.0 && parent.ampeg_release != 0.0 {
            self.ampeg_release = parent.ampeg_release;
        }
        if self.cutoff == 0.0 && parent.cutoff != 0.0 {
            self.cutoff = parent.cutoff;
        }
        if self.fil_veltrack == 0.0 && parent.fil_veltrack != 0.0 {
            self.fil_veltrack = parent.fil_veltrack;
        }
        if self.fileg_attack == 0.0 && parent.fileg_attack != 0.0 {
            self.fileg_attack = parent.fileg_attack;
        }
        if self.fileg_decay == 0.0 && parent.fileg_decay != 0.0 {
            self.fileg_decay = parent.fileg_decay;
        }
        if self.fileg_sustain == 100.0 && parent.fileg_sustain != 100.0 {
            self.fileg_sustain = parent.fileg_sustain;
        }
        if self.fileg_release == 0.0 && parent.fileg_release != 0.0 {
            self.fileg_release = parent.fileg_release;
        }
        if self.fileg_depth == 0.0 && parent.fileg_depth != 0.0 {
            self.fileg_depth = parent.fileg_depth;
        }
        if self.transpose == 0 && parent.transpose != 0 {
            self.transpose = parent.transpose;
        }
        if self.offset == 0 && parent.offset != 0 {
            self.offset = parent.offset;
        }
        if self.end == 0 && parent.end != 0 {
            self.end = parent.end;
        }
        if self.resonance == 0.0 && parent.resonance != 0.0 {
            self.resonance = parent.resonance;
        }
        if self.fil_type.is_none() {
            self.fil_type.clone_from(&parent.fil_type);
        }
        if self.key.is_none() {
            self.key = parent.key;
        }
        if self.pitchlfo_freq == 0.0 && parent.pitchlfo_freq != 0.0 {
            self.pitchlfo_freq = parent.pitchlfo_freq;
        }
        if self.pitchlfo_depth == 0.0 && parent.pitchlfo_depth != 0.0 {
            self.pitchlfo_depth = parent.pitchlfo_depth;
        }
        if self.fillfo_freq == 0.0 && parent.fillfo_freq != 0.0 {
            self.fillfo_freq = parent.fillfo_freq;
        }
        if self.fillfo_depth == 0.0 && parent.fillfo_depth != 0.0 {
            self.fillfo_depth = parent.fillfo_depth;
        }
        if self.fil_keytrack == 0.0 && parent.fil_keytrack != 0.0 {
            self.fil_keytrack = parent.fil_keytrack;
        }
        if self.output == 0 && parent.output != 0 {
            self.output = parent.output;
        }
        if self.cc_modulations.is_empty() && !parent.cc_modulations.is_empty() {
            self.cc_modulations.clone_from(&parent.cc_modulations);
        }
    }
}

/// The current header context during parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HeaderKind {
    None,
    Control,
    Global,
    Group,
    Region,
    Curve,
}

/// A fully parsed SFZ file.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[must_use]
pub struct SfzFile {
    /// Global defaults applied to all regions.
    pub global: SfzRegion,
    /// Group-level defaults (one per `<group>` encountered).
    pub groups: Vec<SfzRegion>,
    /// All parsed `<region>` sections (before inheritance merging).
    pub regions: Vec<SfzRegion>,
    /// Which group index each region belongs to (`None` if no group was active).
    group_indices: Vec<Option<usize>>,
    /// Default path prefix for sample filenames (from `<control> default_path`).
    pub default_path: Option<String>,
    /// `#include` directives encountered during parsing (paths, in order).
    pub includes: Vec<String>,
}

impl SfzFile {
    /// Convert the parsed SFZ into a nidhi [`Instrument`] and a list of sample filenames.
    ///
    /// Sample filenames are returned in the order they appear; each region's zone uses a
    /// [`SampleId`] corresponding to the index in the returned `Vec<String>`.
    ///
    /// `sample_rate` is needed to convert ADSR times (seconds) to samples.
    #[must_use = "returns the built instrument and sample file list"]
    pub fn to_instrument(&self, name: &str, sample_rate: f32) -> (Instrument, Vec<String>) {
        let zones_and_files = self.to_zones(sample_rate);
        let mut inst = Instrument::new(name);
        let mut sample_files: Vec<String> = Vec::new();

        for (zone, filename) in zones_and_files {
            // Deduplicate: find existing or add new
            let idx = sample_files
                .iter()
                .position(|f| f == &filename)
                .unwrap_or_else(|| {
                    let i = sample_files.len();
                    sample_files.push(filename);
                    i
                });

            // Remap zone's sample_id to the deduplicated index
            let mut z = zone;
            z.sample_id = SampleId(idx as u32);
            inst.add_zone(z);
        }

        (inst, sample_files)
    }

    /// Convert the parsed SFZ into `(Zone, sample_filename)` pairs.
    ///
    /// Each region becomes a [`Zone`] with the merged (global → group → region) opcodes.
    /// The `sample_filename` is the raw `sample` opcode value.
    /// Regions without a `sample` opcode are skipped.
    ///
    /// `sample_rate` is needed to convert ADSR times (seconds) to samples.
    #[must_use]
    pub fn to_zones(&self, sample_rate: f32) -> Vec<(Zone, String)> {
        let mut result = Vec::with_capacity(self.regions.len());

        for (i, region) in self.regions.iter().enumerate() {
            // Merge inheritance: global → group → region
            let mut merged = region.clone();

            // Apply group defaults if this region belongs to a group
            if let Some(Some(group_idx)) = self.group_indices.get(i)
                && let Some(group) = self.groups.get(*group_idx)
            {
                merged.inherit_from(group);
            }

            // Apply global defaults
            merged.inherit_from(&self.global);

            // Apply `key` shorthand: sets lokey=hikey=pitch_keycenter
            if let Some(k) = merged.key {
                if merged.lokey == 0 && merged.hikey == 127 {
                    merged.lokey = k;
                    merged.hikey = k;
                }
                if merged.pitch_keycenter == 60 {
                    merged.pitch_keycenter = k;
                }
            }

            // Skip regions without a sample
            let mut filename = match merged.sample {
                Some(ref f) => f.clone(),
                None => continue,
            };

            // Prepend default_path if set
            if let Some(ref prefix) = self.default_path
                && !filename.starts_with(prefix.as_str())
            {
                let mut full = String::with_capacity(prefix.len() + filename.len());
                full.push_str(prefix);
                full.push_str(&filename);
                filename = full;
            }

            // Apply transpose to tune
            let tune_cents = merged.tune as f32 + merged.transpose as f32 * 100.0;

            // Map filter type
            let filter_type = map_fil_type(merged.fil_type.as_deref());

            // Placeholder sample ID — caller remaps after loading samples
            let mut zone = Zone::new(SampleId(i as u32))
                .with_key_range(merged.lokey, merged.hikey)
                .with_vel_range(merged.lovel, merged.hivel)
                .with_root_note(merged.pitch_keycenter)
                .with_tune(tune_cents)
                .with_volume(merged.volume)
                .with_pan(merged.pan / 100.0)
                .with_loop(
                    map_loop_mode(merged.loop_mode.as_deref()),
                    merged.loop_start,
                    merged.loop_end,
                )
                .with_filter(merged.cutoff, map_fil_veltrack(merged.fil_veltrack))
                .with_filter_type(filter_type)
                .with_group(merged.group);

            if merged.resonance > 0.0 {
                zone = zone.with_filter_resonance(merged.resonance);
            }
            if merged.offset > 0 {
                zone = zone.with_sample_offset(merged.offset);
            }
            if merged.end > 0 {
                zone = zone.with_sample_end(merged.end);
            }

            // Wire ADSR if any ampeg opcode was explicitly set
            let has_ampeg = merged.ampeg_attack != 0.0
                || merged.ampeg_decay != 0.0
                || merged.ampeg_sustain != 100.0
                || merged.ampeg_release != 0.0;

            let zone = if has_ampeg {
                let adsr = AdsrConfig::from_seconds(
                    merged.ampeg_attack,
                    merged.ampeg_decay,
                    merged.ampeg_sustain / 100.0,
                    merged.ampeg_release,
                    sample_rate,
                );
                zone.with_adsr(adsr)
            } else {
                zone
            };

            // Wire filter envelope if any fileg opcode was set
            let has_fileg = merged.fileg_depth != 0.0
                || merged.fileg_attack != 0.0
                || merged.fileg_decay != 0.0
                || merged.fileg_sustain != 100.0
                || merged.fileg_release != 0.0;

            let zone = if has_fileg {
                let fileg = AdsrConfig::from_seconds(
                    merged.fileg_attack,
                    merged.fileg_decay,
                    merged.fileg_sustain / 100.0,
                    merged.fileg_release,
                    sample_rate,
                );
                zone.with_filter_envelope(fileg, merged.fileg_depth)
            } else {
                zone
            };

            // Wire pitch LFO
            let zone = if merged.pitchlfo_freq > 0.0 && merged.pitchlfo_depth != 0.0 {
                zone.with_pitch_lfo(merged.pitchlfo_freq, merged.pitchlfo_depth)
            } else {
                zone
            };

            // Wire filter LFO
            let zone = if merged.fillfo_freq > 0.0 && merged.fillfo_depth != 0.0 {
                zone.with_filter_lfo(merged.fillfo_freq, merged.fillfo_depth)
            } else {
                zone
            };

            // Wire key tracking
            let zone = if merged.fil_keytrack > 0.0 {
                zone.with_key_tracking(merged.fil_keytrack / 1200.0)
            } else {
                zone
            };

            // Wire output bus
            let zone = if merged.output > 0 {
                zone.with_output_bus(merged.output)
            } else {
                zone
            };

            result.push((zone, filename));
        }

        result
    }
}

/// Map an SFZ `loop_mode` string to a nidhi [`LoopMode`].
#[must_use]
#[inline]
fn map_loop_mode(mode: Option<&str>) -> LoopMode {
    match mode {
        Some("loop_continuous") => LoopMode::Forward,
        Some("loop_sustain") => LoopMode::LoopSustain,
        Some("one_shot") => LoopMode::OneShot,
        Some("no_loop") | None => LoopMode::OneShot,
        Some(_) => LoopMode::OneShot,
    }
}

/// Map SFZ `fil_type` string to a nidhi [`FilterMode`].
#[must_use]
#[inline]
fn map_fil_type(fil_type: Option<&str>) -> FilterMode {
    match fil_type {
        Some("hpf_1p") | Some("hpf_2p") => FilterMode::HighPass,
        Some("bpf_2p") => FilterMode::BandPass,
        Some("brf_2p") => FilterMode::Notch,
        // lpf_1p, lpf_2p, or unknown → LowPass (default)
        _ => FilterMode::LowPass,
    }
}

/// Map SFZ `fil_veltrack` (in cents, typically 0–9600) to a 0.0–1.0 range.
#[must_use]
#[inline]
fn map_fil_veltrack(cents: f32) -> f32 {
    // SFZ fil_veltrack is in cents of filter cutoff change over velocity range.
    // 9600 cents = full range. We normalize to 0..1.
    (cents / 9600.0).clamp(0.0, 1.0)
}

/// Parse SFZ text into an [`SfzFile`].
///
/// The parser is line-based:
/// 1. Track the current header type (`<global>`, `<group>`, `<region>`)
/// 2. Split each line by whitespace into tokens
/// 3. Split each token by `=` into key/value opcode pairs
/// 4. Accumulate opcodes into the current section's [`SfzRegion`]
///
/// Unknown opcodes are silently ignored. Malformed lines (no `=`) are skipped.
/// Comments (lines starting with `//`) are stripped.
pub fn parse(input: &str) -> Result<SfzFile> {
    let mut global = SfzRegion::new();
    let mut groups: Vec<SfzRegion> = Vec::new();
    let mut regions: Vec<SfzRegion> = Vec::new();
    let mut group_indices: Vec<Option<usize>> = Vec::new();

    let mut current_header = HeaderKind::None;
    let mut current_group_idx: Option<usize> = None;
    let mut default_path: Option<String> = None;
    let mut includes: Vec<String> = Vec::new();

    for line in input.lines() {
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with("//") {
            continue;
        }

        // Handle #include directives (SFZ v2)
        if line.starts_with("#include") {
            let path = line.trim_start_matches("#include").trim().trim_matches('"');
            if !path.is_empty() {
                includes.push(String::from(path));
            }
            continue;
        }

        // Tokenize the line by whitespace
        let tokens: Vec<&str> = line.split_whitespace().collect();

        for token in &tokens {
            // Check for headers
            if let Some(header) = parse_header(token) {
                match header {
                    HeaderKind::Control => {
                        current_header = HeaderKind::Control;
                    }
                    HeaderKind::Global => {
                        current_header = HeaderKind::Global;
                    }
                    HeaderKind::Group => {
                        current_header = HeaderKind::Group;
                        groups.push(SfzRegion::new());
                        current_group_idx = Some(groups.len() - 1);
                    }
                    HeaderKind::Region => {
                        current_header = HeaderKind::Region;
                        regions.push(SfzRegion::new());
                        group_indices.push(current_group_idx);
                    }
                    HeaderKind::Curve => {
                        current_header = HeaderKind::Curve;
                        // Curve opcodes are stored but not yet used
                    }
                    HeaderKind::None => {}
                }
                continue;
            }

            // Parse opcode key=value
            if let Some((key, value)) = split_opcode(token) {
                match current_header {
                    HeaderKind::Control => {
                        if key == "default_path" {
                            default_path = Some(String::from(value));
                        }
                        // Other control opcodes ignored for now
                    }
                    HeaderKind::Global => global.apply_opcode(key, value),
                    HeaderKind::Group => {
                        if let Some(g) = groups.last_mut() {
                            g.apply_opcode(key, value);
                        }
                    }
                    HeaderKind::Region => {
                        if let Some(r) = regions.last_mut() {
                            r.apply_opcode(key, value);
                        }
                    }
                    HeaderKind::Curve => {
                        // Curve opcodes stored for future use
                    }
                    HeaderKind::None => {
                        // Opcodes before any header are treated as global
                        global.apply_opcode(key, value);
                    }
                }
            }
        }
    }

    Ok(SfzFile {
        global,
        groups,
        regions,
        group_indices,
        default_path,
        includes,
    })
}

/// Try to parse a token as a header (`<global>`, `<group>`, `<region>`).
fn parse_header(token: &str) -> Option<HeaderKind> {
    let trimmed = token.trim();
    if trimmed.starts_with('<') && trimmed.ends_with('>') {
        let name = &trimmed[1..trimmed.len() - 1];
        match name {
            "control" => Some(HeaderKind::Control),
            "global" => Some(HeaderKind::Global),
            "group" => Some(HeaderKind::Group),
            "region" => Some(HeaderKind::Region),
            "curve" => Some(HeaderKind::Curve),
            _ => None,
        }
    } else {
        None
    }
}

/// Split a token at the first `=` into (key, value).
fn split_opcode(token: &str) -> Option<(&str, &str)> {
    let idx = token.find('=')?;
    let key = &token[..idx];
    let value = &token[idx + 1..];
    if key.is_empty() || value.is_empty() {
        return None;
    }
    Some((key, value))
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;

    #[test]
    fn parse_empty_file() {
        let sfz = parse("").expect("should parse empty input");
        assert!(sfz.regions.is_empty());
        assert!(sfz.groups.is_empty());
    }

    #[test]
    fn parse_single_region() {
        let input = r#"
<region>
sample=piano_c4.wav
lokey=60 hikey=72
pitch_keycenter=66
lovel=1 hivel=100
"#;
        let sfz = parse(input).expect("should parse single region");
        assert_eq!(sfz.regions.len(), 1);

        let r = &sfz.regions[0];
        assert_eq!(r.sample.as_deref(), Some("piano_c4.wav"));
        assert_eq!(r.lokey, 60);
        assert_eq!(r.hikey, 72);
        assert_eq!(r.pitch_keycenter, 66);
        assert_eq!(r.lovel, 1);
        assert_eq!(r.hivel, 100);
    }

    #[test]
    fn parse_with_global_defaults() {
        let input = r#"
<global>
ampeg_release=0.5
volume=-6

<region>
sample=test.wav
"#;
        let sfz = parse(input).expect("should parse with globals");
        assert_eq!(sfz.regions.len(), 1);
        assert!((sfz.global.ampeg_release - 0.5).abs() < f32::EPSILON);
        assert!((sfz.global.volume - -6.0).abs() < f32::EPSILON);

        // Convert and verify inheritance
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 1);
        let (zone, filename) = &zones[0];
        assert_eq!(filename, "test.wav");
        assert!((zone.volume_db - -6.0).abs() < f32::EPSILON);
    }

    #[test]
    fn parse_with_group_inheritance() {
        let input = r#"
<global>
ampeg_release=0.3

<group>
lokey=60 hikey=72

<region>
sample=soft.wav
lovel=1 hivel=80

<region>
sample=loud.wav
lovel=81 hivel=127
"#;
        let sfz = parse(input).expect("should parse with groups");
        assert_eq!(sfz.groups.len(), 1);
        assert_eq!(sfz.regions.len(), 2);

        // Group sets key range
        assert_eq!(sfz.groups[0].lokey, 60);
        assert_eq!(sfz.groups[0].hikey, 72);

        // Regions inherit group key range
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 2);

        let (z0, f0) = &zones[0];
        assert_eq!(f0, "soft.wav");
        assert_eq!(z0.key_lo, 60);
        assert_eq!(z0.key_hi, 72);
        assert_eq!(z0.vel_lo, 1);
        assert_eq!(z0.vel_hi, 80);

        let (z1, f1) = &zones[1];
        assert_eq!(f1, "loud.wav");
        assert_eq!(z1.key_lo, 60);
        assert_eq!(z1.key_hi, 72);
        assert_eq!(z1.vel_lo, 81);
        assert_eq!(z1.vel_hi, 127);
    }

    #[test]
    fn round_trip_to_instrument() {
        let input = r#"
<region>
sample=piano.wav
lokey=48 hikey=72
pitch_keycenter=60
lovel=1 hivel=127
tune=5
volume=-3
pan=50
"#;
        let sfz = parse(input).expect("should parse");
        let (inst, files) = sfz.to_instrument("test_piano", 44100.0);

        assert_eq!(inst.name(), "test_piano");
        assert_eq!(inst.zone_count(), 1);
        assert_eq!(files.len(), 1);
        assert_eq!(files[0], "piano.wav");

        let zones = inst.zones();
        let z = &zones[0];
        assert_eq!(z.key_lo, 48);
        assert_eq!(z.key_hi, 72);
        assert_eq!(z.root_note, 60);
        assert!((z.tune_cents - 5.0).abs() < f32::EPSILON);
        assert!((z.volume_db - -3.0).abs() < f32::EPSILON);
        // pan=50 maps to 0.5
        assert!((z.pan - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn loop_mode_mapping() {
        assert_eq!(map_loop_mode(None), LoopMode::OneShot);
        assert_eq!(map_loop_mode(Some("no_loop")), LoopMode::OneShot);
        assert_eq!(map_loop_mode(Some("one_shot")), LoopMode::OneShot);
        assert_eq!(map_loop_mode(Some("loop_continuous")), LoopMode::Forward);
        assert_eq!(map_loop_mode(Some("loop_sustain")), LoopMode::LoopSustain);
        assert_eq!(map_loop_mode(Some("unknown_mode")), LoopMode::OneShot);
    }

    #[test]
    fn invalid_opcode_ignored() {
        let input = r#"
<region>
sample=test.wav
totally_fake_opcode=999
another_invalid=hello
lokey=60
"#;
        let sfz = parse(input).expect("should parse despite unknown opcodes");
        assert_eq!(sfz.regions.len(), 1);
        assert_eq!(sfz.regions[0].lokey, 60);
        assert_eq!(sfz.regions[0].sample.as_deref(), Some("test.wav"));
    }

    #[test]
    fn comments_and_blank_lines_skipped() {
        let input = r#"
// This is a comment
<region>
sample=test.wav

// Another comment
lokey=60 hikey=72
"#;
        let sfz = parse(input).expect("should parse");
        assert_eq!(sfz.regions.len(), 1);
        assert_eq!(sfz.regions[0].lokey, 60);
    }

    #[test]
    fn region_overrides_group_overrides_global() {
        let input = r#"
<global>
volume=-10
pan=25

<group>
volume=-5

<region>
sample=test.wav
volume=-2
"#;
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 1);

        let (z, _) = &zones[0];
        // Region sets volume=-2, should override group (-5) and global (-10)
        assert!((z.volume_db - -2.0).abs() < f32::EPSILON);
        // Pan inherited from global (25/100 = 0.25)
        assert!((z.pan - 0.25).abs() < f32::EPSILON);
    }

    #[test]
    fn loop_mode_parsed_in_region() {
        let input = r#"
<region>
sample=loop.wav
loop_mode=loop_continuous
loop_start=1000
loop_end=5000
"#;
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 1);

        let (z, _) = &zones[0];
        assert_eq!(z.loop_mode, LoopMode::Forward);
        assert_eq!(z.loop_start, 1000);
        assert_eq!(z.loop_end, 5000);
    }

    #[test]
    fn filter_opcodes_parsed() {
        let input = r#"
<region>
sample=test.wav
cutoff=5000
fil_veltrack=4800
"#;
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 1);

        let (z, _) = &zones[0];
        assert!((z.filter_cutoff - 5000.0).abs() < f32::EPSILON);
        // 4800/9600 = 0.5
        assert!((z.filter_vel_track - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn multiple_groups() {
        let input = r#"
<group>
lokey=36 hikey=47

<region>
sample=bass.wav

<group>
lokey=48 hikey=72

<region>
sample=mid.wav

<region>
sample=mid2.wav
"#;
        let sfz = parse(input).expect("should parse");
        assert_eq!(sfz.groups.len(), 2);
        assert_eq!(sfz.regions.len(), 3);

        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 3);

        // First region inherits from first group
        assert_eq!(zones[0].0.key_lo, 36);
        assert_eq!(zones[0].0.key_hi, 47);
        assert_eq!(zones[0].1, "bass.wav");

        // Second and third regions inherit from second group
        assert_eq!(zones[1].0.key_lo, 48);
        assert_eq!(zones[1].0.key_hi, 72);
        assert_eq!(zones[2].0.key_lo, 48);
        assert_eq!(zones[2].0.key_hi, 72);
    }

    #[test]
    fn region_without_sample_skipped() {
        let input = r#"
<region>
lokey=60 hikey=72

<region>
sample=valid.wav
"#;
        let sfz = parse(input).expect("should parse");
        assert_eq!(sfz.regions.len(), 2);

        // Only one zone produced (the one with a sample)
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 1);
        assert_eq!(zones[0].1, "valid.wav");
    }

    #[test]
    fn adsr_envelope_from_sfz() {
        let input = r#"
<global>
ampeg_attack=0.01
ampeg_decay=0.1
ampeg_sustain=70
ampeg_release=0.5

<region>
sample=test.wav
"#;
        let sfz = parse(input).expect("should parse");
        assert!((sfz.global.ampeg_attack - 0.01).abs() < f32::EPSILON);
        assert!((sfz.global.ampeg_decay - 0.1).abs() < f32::EPSILON);
        assert!((sfz.global.ampeg_sustain - 70.0).abs() < f32::EPSILON);
        assert!((sfz.global.ampeg_release - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn to_instrument_deduplicates_samples() {
        let input = r#"
<region>
sample=shared.wav
lokey=60 hikey=66

<region>
sample=shared.wav
lokey=67 hikey=72

<region>
sample=other.wav
lokey=73 hikey=84
"#;
        let sfz = parse(input).expect("should parse");
        let (inst, files) = sfz.to_instrument("dedup_test", 44100.0);

        assert_eq!(inst.zone_count(), 3);
        // Only 2 unique sample files
        assert_eq!(files.len(), 2);
        assert_eq!(files[0], "shared.wav");
        assert_eq!(files[1], "other.wav");

        // Both zones referencing shared.wav should have the same SampleId
        let zones = inst.zones();
        assert_eq!(zones[0].sample_id(), SampleId(0));
        assert_eq!(zones[1].sample_id(), SampleId(0));
        assert_eq!(zones[2].sample_id(), SampleId(1));
    }

    #[test]
    fn note_name_parsing() {
        assert_eq!(parse_note_or_number("60"), Some(60));
        assert_eq!(parse_note_or_number("c4"), Some(60));
        assert_eq!(parse_note_or_number("C4"), Some(60));
        assert_eq!(parse_note_or_number("f#3"), Some(54));
        assert_eq!(parse_note_or_number("eb4"), Some(63));
        assert_eq!(parse_note_or_number("b4"), Some(71));
        assert_eq!(parse_note_or_number("c-1"), Some(0));
        assert_eq!(parse_note_or_number("g9"), Some(127));
        assert_eq!(parse_note_or_number(""), None);
        assert_eq!(parse_note_or_number("xyz"), None);
    }

    #[test]
    fn note_names_in_opcodes() {
        let input = "<region>\nsample=test.wav\nlokey=c4 hikey=c5 pitch_keycenter=f#4\n";
        let sfz = parse(input).expect("should parse note names");
        assert_eq!(sfz.regions[0].lokey, 60);
        assert_eq!(sfz.regions[0].hikey, 72);
        assert_eq!(sfz.regions[0].pitch_keycenter, 66);
    }

    #[test]
    fn key_shorthand_opcode() {
        let input = "<region>\nsample=test.wav\nkey=60\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones.len(), 1);
        let (z, _) = &zones[0];
        assert_eq!(z.key_lo, 60);
        assert_eq!(z.key_hi, 60);
        assert_eq!(z.root_note, 60);
    }

    #[test]
    fn control_header_default_path() {
        let input = "<control>\ndefault_path=samples/piano/\n<region>\nsample=c4.wav\n";
        let sfz = parse(input).expect("should parse");
        assert_eq!(sfz.default_path.as_deref(), Some("samples/piano/"));
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones[0].1, "samples/piano/c4.wav");
    }

    #[test]
    fn curve_header_does_not_break_parsing() {
        let input = "<curve>\ncurve_index=1\nv000=0 v127=1\n<region>\nsample=test.wav\n";
        let sfz = parse(input).expect("should parse with curve header");
        assert_eq!(sfz.regions.len(), 1);
    }

    #[test]
    fn transpose_adds_to_tune() {
        let input = "<region>\nsample=test.wav\ntune=10 transpose=2\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        // tune=10 cents + transpose=2 semitones (200 cents) = 210 cents
        assert!((zones[0].0.tune_cents - 210.0).abs() < f32::EPSILON);
    }

    #[test]
    fn fil_type_maps_to_filter_mode() {
        use crate::zone::FilterMode;
        let input = "<region>\nsample=test.wav\nfil_type=hpf_2p\ncutoff=1000\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones[0].0.filter_type(), FilterMode::HighPass);
    }

    #[test]
    fn offset_and_end_opcodes() {
        let input = "<region>\nsample=test.wav\noffset=100 end=5000\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones[0].0.sample_offset(), 100);
        assert_eq!(zones[0].0.sample_end(), 5000);
    }

    #[test]
    fn resonance_opcode() {
        let input = "<region>\nsample=test.wav\ncutoff=2000 resonance=6.0\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert!((zones[0].0.filter_resonance() - 6.0).abs() < f32::EPSILON);
    }

    #[test]
    fn fileg_opcodes_wired_to_zone() {
        let input = "<region>\nsample=test.wav\ncutoff=2000\nfileg_attack=0.1 fileg_decay=0.2 fileg_sustain=50 fileg_release=0.3 fileg_depth=2400\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        let (z, _) = &zones[0];
        assert!(z.fileg().is_some());
        assert!((z.fileg_depth() - 2400.0).abs() < f32::EPSILON);
    }

    #[test]
    fn ampeg_wired_to_zone_adsr() {
        let input = "<region>\nsample=test.wav\nampeg_attack=0.05 ampeg_release=0.3\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        let (z, _) = &zones[0];
        assert!(z.adsr().is_some());
        let adsr = z.adsr().unwrap();
        assert!(adsr.attack_samples > 0);
        assert!(adsr.release_samples > 0);
    }

    #[test]
    fn loop_sustain_mode_in_sfz() {
        let input =
            "<region>\nsample=test.wav\nloop_mode=loop_sustain\nloop_start=100 loop_end=500\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones[0].0.loop_mode(), LoopMode::LoopSustain);
    }

    #[test]
    fn pitchlfo_opcodes_wired_to_zone() {
        let input = "<region>\nsample=test.wav\npitchlfo_freq=5.0 pitchlfo_depth=50\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        let (z, _) = &zones[0];
        assert!((z.pitchlfo_rate() - 5.0).abs() < f32::EPSILON);
        assert!((z.pitchlfo_depth() - 50.0).abs() < f32::EPSILON);
    }

    #[test]
    fn fillfo_opcodes_wired_to_zone() {
        let input = "<region>\nsample=test.wav\ncutoff=2000\nfillfo_freq=3.0 fillfo_depth=600\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        let (z, _) = &zones[0];
        assert!((z.fillfo_rate() - 3.0).abs() < f32::EPSILON);
        assert!((z.fillfo_depth() - 600.0).abs() < f32::EPSILON);
    }

    #[test]
    fn fil_keytrack_opcode() {
        let input = "<region>\nsample=test.wav\ncutoff=2000\nfil_keytrack=600\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        let (z, _) = &zones[0];
        // 600 / 1200 = 0.5
        assert!((z.fil_keytrack() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn include_directives_collected() {
        let input =
            "#include \"common.sfz\"\n<region>\nsample=test.wav\n#include \"velocities.sfz\"\n";
        let sfz = parse(input).expect("should parse with includes");
        assert_eq!(sfz.includes.len(), 2);
        assert_eq!(sfz.includes[0], "common.sfz");
        assert_eq!(sfz.includes[1], "velocities.sfz");
    }

    #[test]
    fn cc_modulation_opcodes_parsed() {
        let input = "<region>\nsample=test.wav\nvolume_oncc1=6 cutoff_oncc74=2400\n";
        let sfz = parse(input).expect("should parse");
        assert_eq!(sfz.regions[0].cc_modulations.len(), 2);
        let (param, cc, depth) = &sfz.regions[0].cc_modulations[0];
        assert_eq!(param, "volume");
        assert_eq!(*cc, 1);
        assert!((depth - 6.0).abs() < f32::EPSILON);
    }

    #[test]
    fn output_opcode_wired_to_bus() {
        let input = "<region>\nsample=test.wav\noutput=2\n";
        let sfz = parse(input).expect("should parse");
        let zones = sfz.to_zones(44100.0);
        assert_eq!(zones[0].0.output_bus(), 2);
    }
}