synthie 0.8.0

Chiptune-focused synthesizer engine: dual OSC, ring mod, filters, envelopes, LFO, arpeggiator, and FX (reverb, delay, chorus, bitcrusher)
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
//! Tracker-style pattern sequencer for game music.
//!
//! A [`Song`] is a set of lanes that advance one row at a time at a fixed
//! tempo. Each lane is written in a compact text notation and plays on one
//! synthesis channel. [`SongPlayer`] implements [`Sequencer`], so a song
//! plays sample-accurately on any host that drives a
//! [`SequencedProcessor`](crate::audio::sequencer::SequencedProcessor),
//! including the cpal engine.
//!
//! # Notation
//!
//! A lane is a whitespace-separated list of cells, one per row. Line breaks
//! are whitespace too, so long patterns can be laid out a few bars per line.
//!
//! | Cell | Meaning |
//! |---|---|
//! | `C4`, `F#3`, `Bb2` | Note on (C4 is middle C, MIDI 60). Releases the lane's previous note. |
//! | `C4^047` | Chip arpeggio: cycle the notes at the given hex semitone offsets from the root (2-4 digits) on the channel's arpeggiator. Needs the `arp` feature. |
//! | `E2+B2+E3` | Chord: start 2-4 notes together, one per voice of the channel. Releases the lane's previous note(s). |
//! | `E2^07c!` | Interval chord: hold the notes at the given hex semitone offsets from the root (2-4 digits) together, like an arpeggio that does not cycle. |
//! | `.` | Hold: nothing changes. |
//! | `-` | Note off: release the lane's note. |
//! | `k` `s` `h` `o` `c` `x` | Kick, snare, closed hi-hat, open hi-hat, crash, clap. |
//! | `lt` `mt` `ht` | Low, mid, high tom. |
//! | `k+c`, `s+h` | Several drum hits on the same row. |
//! | `@2`, `C4@2` | Switch the lane's channel to patch 2 of the song (then play the note). |
//! | `\|` | Bar line; ignored, for readability. |
//!
//! Each lane is monophonic like a sound-chip channel: a new note releases the
//! lane's previous one. Chords are the exception: a chord cell starts all its
//! notes at once, and the lane's next note, chord or `-` releases all of them.
//! A chord takes one of the channel's four voices per note, so it holds at
//! most four; lanes that share its channel steal the oldest voices. `@n`
//! works on chord cells too (`E2+B2+E3@1`). Drum hits ring out on the drum
//! machine independently of the lane.
//!
//! ```
//! use synthie::params::ChannelNo;
//! use synthie::pattern::{Song, Tempo};
//!
//! // A power-chord riff (root, fifth, octave) from a single lane.
//! let riff = Song::new(Tempo::bpm(140.0, 2))
//!     .lane(ChannelNo(0), "E2+B2+E3 . G2+D3+G3 . | A2^07c! . . -")?;
//! # Ok::<(), synthie::pattern::ParseError>(())
//! ```
//!
//! ```
//! use synthie::params::ChannelNo;
//! use synthie::pattern::{Song, Tempo};
//!
//! // One row per eighth note at 152 bpm.
//! let song = Song::new(Tempo::bpm(152.0, 2))
//!     .lane(ChannelNo(0), "E4 . G4 . A4 . B4 . | E5 . . . - . . .")?
//!     .lane(ChannelNo(1), "E2 E2 E2 E2 G2 A2 . . | E2 . . . - . . .")?
//!     .lane(ChannelNo(3), "k+c h s h k k s h | k h s h k k s o")?;
//! assert_eq!(song.len(), 16);
//! # Ok::<(), synthie::pattern::ParseError>(())
//! ```
//!
//! # Timing
//!
//! Rows last `60 / rows_per_minute` seconds. The player carries the
//! fractional frames of each row over to the next, so the tempo does not
//! drift however the row length divides the sample rate. Lanes shorter than
//! the song hold their last state until it loops.

use core::fmt;

use crate::audio::sequencer::Sequencer;
use crate::params::{AudioEvent, ChannelNo, DrumHit, MidiNote, SynthParams};

/// Most notes an arpeggio cell can cycle through (the arpeggiator's limit).
pub const MAX_ARP_NOTES: usize = 4;

/// Most notes a chord cell can hold: one per voice of its channel.
pub const MAX_CHORD_NOTES: usize = crate::audio::processor::POLYPHONY;

/// How fast a song advances.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Tempo {
    rows_per_minute: f32,
}

impl Tempo {
    /// `bpm` beats per minute with `rows_per_beat` rows to a beat, e.g. 2
    /// for one row per eighth note or 4 for sixteenths.
    ///
    /// # Panics
    ///
    /// Panics unless the resulting row rate is finite and positive.
    #[must_use]
    pub fn bpm(bpm: f32, rows_per_beat: u16) -> Self {
        Self::rows_per_minute(bpm * f32::from(rows_per_beat))
    }

    /// A raw row rate.
    ///
    /// # Panics
    ///
    /// Panics unless `rows_per_minute` is finite and positive.
    #[must_use]
    pub fn rows_per_minute(rows_per_minute: f32) -> Self {
        assert!(
            rows_per_minute.is_finite() && rows_per_minute > 0.0,
            "tempo must be finite and positive, got {rows_per_minute} rows per minute"
        );
        Self { rows_per_minute }
    }

    /// Rows per minute.
    #[must_use]
    pub fn as_rows_per_minute(self) -> f32 {
        self.rows_per_minute
    }

    /// Length of one row in frames at `sample_rate`.
    #[must_use]
    pub fn frames_per_row(self, sample_rate: f32) -> f64 {
        f64::from(sample_rate) * 60.0 / f64::from(self.rows_per_minute)
    }
}

/// A set of drum hits that fire on the same row.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DrumHits(u16);

impl DrumHits {
    /// No hits.
    pub const NONE: Self = Self(0);

    /// Add `hit` to the set.
    #[must_use]
    pub fn with(self, hit: DrumHit) -> Self {
        Self(self.0 | 1 << Self::index(hit))
    }

    /// Whether `hit` is in the set.
    #[must_use]
    pub fn contains(self, hit: DrumHit) -> bool {
        self.0 & (1 << Self::index(hit)) != 0
    }

    /// Whether the set is empty.
    #[must_use]
    pub fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// The hits in kit order.
    pub fn iter(self) -> impl Iterator<Item = DrumHit> {
        DrumHit::ALL
            .into_iter()
            .filter(move |&hit| self.contains(hit))
    }

    fn index(hit: DrumHit) -> usize {
        DrumHit::ALL
            .iter()
            .position(|&h| h == hit)
            .expect("DrumHit::ALL lists every hit")
    }
}

impl FromIterator<DrumHit> for DrumHits {
    fn from_iter<I: IntoIterator<Item = DrumHit>>(iter: I) -> Self {
        iter.into_iter().fold(Self::NONE, Self::with)
    }
}

/// What a cell does to its lane.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    /// `.`: nothing changes.
    Hold,
    /// `-`: release the lane's note.
    Off,
    /// Note on, releasing the lane's previous note.
    Note(MidiNote),
    /// Note on as a chip arpeggio over `notes[..count]`.
    Arp {
        /// The notes to cycle through; only `..count` are used.
        notes: [MidiNote; MAX_ARP_NOTES],
        /// Number of notes, `2..=4`.
        count: u8,
    },
    /// Note on for every note of `notes[..count]` at once, releasing the
    /// lane's previous note(s).
    Chord {
        /// The chord tones; only `..count` are used.
        notes: [MidiNote; MAX_CHORD_NOTES],
        /// Number of notes, `2..=MAX_CHORD_NOTES`.
        count: u8,
    },
    /// One or more drum hits.
    Drums(DrumHits),
}

/// One row of a lane.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cell {
    /// Switch the lane's channel to this patch of the song first.
    pub patch: Option<u16>,
    /// What the cell plays.
    pub action: Action,
}

impl Cell {
    /// A cell that holds.
    pub const HOLD: Self = Self {
        patch: None,
        action: Action::Hold,
    };
}

/// One track of a song: the channel it plays on and its rows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Lane {
    /// The synthesis channel the lane's notes play on.
    pub channel: ChannelNo,
    /// One cell per row.
    pub rows: Vec<Cell>,
}

impl Lane {
    /// Parse a lane written in the [notation](self#notation).
    ///
    /// # Errors
    ///
    /// Fails on the first token that is not a valid cell; the error locates
    /// it in `pattern`. Its `lane` is 0.
    pub fn parse(channel: ChannelNo, pattern: &str) -> Result<Self, ParseError> {
        let mut rows = Vec::new();
        for (offset, token) in tokens(pattern) {
            if token == "|" {
                continue;
            }
            let cell = parse_cell(token).map_err(|e| {
                let (at, token) = match e.span {
                    Some((start, len)) => (offset + start, &token[start..start + len]),
                    None => (offset, token),
                };
                ParseError::new(pattern, at, token, e.kind)
            })?;
            rows.push(cell);
        }
        Ok(Self { channel, rows })
    }
}

/// Whitespace-separated tokens with their byte offsets.
fn tokens(pattern: &str) -> impl Iterator<Item = (usize, &str)> {
    let mut rest = pattern;
    core::iter::from_fn(move || {
        let start = rest.find(|c: char| !c.is_whitespace())?;
        let len = rest[start..]
            .find(char::is_whitespace)
            .unwrap_or(rest.len() - start);
        let offset = pattern.len() - rest.len() + start;
        let token = &rest[start..start + len];
        rest = &rest[start + len..];
        Some((offset, token))
    })
}

/// A cell's parse error, optionally narrowed to part of the token (such as
/// one note of a chord) by its byte offset and length within the token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CellError {
    kind: ParseErrorKind,
    span: Option<(usize, usize)>,
}

impl From<ParseErrorKind> for CellError {
    fn from(kind: ParseErrorKind) -> Self {
        Self { kind, span: None }
    }
}

fn parse_cell(token: &str) -> Result<Cell, CellError> {
    let (body, patch) = match token.split_once('@') {
        Some((body, index)) => {
            let index = index
                .parse::<u16>()
                .map_err(|_| ParseErrorKind::InvalidPatch)?;
            (body, Some(index))
        }
        None => (token, None),
    };

    let action = match body {
        "" if patch.is_some() => Action::Hold,
        "." => Action::Hold,
        "-" => Action::Off,
        _ if body.starts_with(|c: char| c.is_ascii_uppercase()) => {
            if body.contains('+') {
                parse_chord(body)?
            } else {
                parse_note_or_arp(body)?
            }
        }
        _ => {
            if patch.is_some() {
                return Err(ParseErrorKind::PatchOnDrums.into());
            }
            Action::Drums(parse_drums(body)?)
        }
    };
    Ok(Cell { patch, action })
}

fn parse_drums(body: &str) -> Result<DrumHits, ParseErrorKind> {
    body.split('+')
        .map(|name| match name {
            "k" => Ok(DrumHit::Kick),
            "s" => Ok(DrumHit::Snare),
            "h" => Ok(DrumHit::HiHatClosed),
            "o" => Ok(DrumHit::HiHatOpen),
            "c" => Ok(DrumHit::Crash),
            "x" => Ok(DrumHit::Clap),
            "lt" => Ok(DrumHit::TomLow),
            "mt" => Ok(DrumHit::TomMid),
            "ht" => Ok(DrumHit::TomHigh),
            _ => Err(ParseErrorKind::UnknownToken),
        })
        .collect()
}

/// A note, an arpeggio (`C4^047`) or an interval chord (`C4^047!`).
fn parse_note_or_arp(body: &str) -> Result<Action, ParseErrorKind> {
    let Some((name, offsets)) = body.split_once('^') else {
        return parse_note(body).map(Action::Note);
    };
    let root = parse_note(name)?;
    if let Some(offsets) = offsets.strip_suffix('!') {
        let (notes, count) = offset_notes::<MAX_CHORD_NOTES>(root, offsets)
            .ok_or(ParseErrorKind::InvalidChord)??;
        if has_duplicates(&notes[..usize::from(count)]) {
            return Err(ParseErrorKind::DuplicateChordNote);
        }
        return Ok(Action::Chord { notes, count });
    }
    if !cfg!(feature = "arp") {
        return Err(ParseErrorKind::ArpUnsupported);
    }
    let (notes, count) =
        offset_notes::<MAX_ARP_NOTES>(root, offsets).ok_or(ParseErrorKind::InvalidArp)??;
    Ok(Action::Arp { notes, count })
}

/// `root` plus each hex digit of `offsets` as semitones. `None` if `offsets`
/// is not 2..=N hex digits, `Some(Err)` if a note leaves the MIDI range.
fn offset_notes<const N: usize>(
    root: MidiNote,
    offsets: &str,
) -> Option<Result<([MidiNote; N], u8), ParseErrorKind>> {
    if !(2..=N).contains(&offsets.len()) {
        return None;
    }
    let mut notes = [root; N];
    for (slot, digit) in notes.iter_mut().zip(offsets.chars()) {
        let midi = u32::from(root.0) + digit.to_digit(16)?;
        match u8::try_from(midi).ok().filter(|&m| m <= 127) {
            Some(m) => *slot = MidiNote(m),
            None => return Some(Err(ParseErrorKind::NoteOutOfRange)),
        }
    }
    #[allow(clippy::cast_possible_truncation, reason = "at most N <= 4 offsets")]
    let count = offsets.len() as u8;
    Some(Ok((notes, count)))
}

fn has_duplicates(notes: &[MidiNote]) -> bool {
    notes
        .iter()
        .enumerate()
        .any(|(i, n)| notes[..i].contains(n))
}

/// A chord cell such as `E2+B2+E3`. Errors point at the offending note.
fn parse_chord(body: &str) -> Result<Action, CellError> {
    let mut notes = [MidiNote(0); MAX_CHORD_NOTES];
    let mut count = 0;
    let mut start = 0;
    for name in body.split('+') {
        let at = |kind| CellError {
            kind,
            span: Some((start, name.len())),
        };
        let note = parse_note(name).map_err(at)?;
        if count == MAX_CHORD_NOTES {
            return Err(at(ParseErrorKind::TooManyChordNotes));
        }
        if notes[..count].contains(&note) {
            return Err(at(ParseErrorKind::DuplicateChordNote));
        }
        notes[count] = note;
        count += 1;
        start += name.len() + 1;
    }
    #[allow(clippy::cast_possible_truncation, reason = "at most MAX_CHORD_NOTES")]
    let count = count as u8;
    Ok(Action::Chord { notes, count })
}

/// Parse a note name such as `C4`, `F#3`, `Bb2` or `C-1` (C4 is MIDI 60).
///
/// # Errors
///
/// Fails on a malformed name or a note outside MIDI 0..=127.
pub fn parse_note(name: &str) -> Result<MidiNote, ParseErrorKind> {
    let mut chars = name.chars();
    let semitone: i32 = match chars.next() {
        Some('C') => 0,
        Some('D') => 2,
        Some('E') => 4,
        Some('F') => 5,
        Some('G') => 7,
        Some('A') => 9,
        Some('B') => 11,
        _ => return Err(ParseErrorKind::InvalidNote),
    };
    let rest = chars.as_str();
    let (accidental, octave) = match rest.as_bytes().first() {
        Some(b'#') => (1, &rest[1..]),
        Some(b'b') => (-1, &rest[1..]),
        _ => (0, rest),
    };
    let octave: i32 = octave.parse().map_err(|_| ParseErrorKind::InvalidNote)?;
    let midi = (octave + 1) * 12 + semitone + accidental;
    u8::try_from(midi)
        .ok()
        .filter(|&m| m <= 127)
        .map(MidiNote)
        .ok_or(ParseErrorKind::NoteOutOfRange)
}

/// Why a token could not be parsed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseErrorKind {
    /// Not a note, drum, `.`, `-`, `@` or `|`.
    UnknownToken,
    /// Starts like a note (`A`-`G`) but is not one.
    InvalidNote,
    /// A note, or an arpeggio note, outside MIDI 0..=127.
    NoteOutOfRange,
    /// An arpeggio suffix that is not 2-4 hex digits.
    InvalidArp,
    /// An arpeggio without the `arp` feature.
    ArpUnsupported,
    /// An `@` not followed by a patch number.
    InvalidPatch,
    /// A patch change on a drum cell; drums have no patch.
    PatchOnDrums,
    /// A chord with more notes than its channel has voices.
    TooManyChordNotes,
    /// A chord that names the same note twice.
    DuplicateChordNote,
    /// An interval chord suffix that is not 2-4 hex digits and `!`.
    InvalidChord,
}

impl fmt::Display for ParseErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::UnknownToken => {
                "unknown token; expected a note, `.`, `-`, a drum (k s h o c x lt mt ht), `@n` or `|`"
            }
            Self::InvalidNote => "invalid note; expected e.g. `C4`, `F#3` or `Bb2`",
            Self::NoteOutOfRange => "note outside MIDI range C-1..G9",
            Self::InvalidArp => "invalid arpeggio; expected 2-4 hex semitone offsets, e.g. `C4^047`",
            Self::ArpUnsupported => "arpeggios need the `arp` feature",
            Self::InvalidPatch => "invalid patch change; expected `@` and a number, e.g. `@2`",
            Self::PatchOnDrums => "drum cells cannot change the patch",
            Self::TooManyChordNotes => "too many chord notes; a channel plays at most 4 at once",
            Self::DuplicateChordNote => "chord repeats a note",
            Self::InvalidChord => {
                "invalid interval chord; expected 2-4 hex semitone offsets and `!`, e.g. `E2^07c!`"
            }
        })
    }
}

/// A token in a lane that could not be parsed, with its location.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    /// Index of the lane in the song (0 for [`Lane::parse`]).
    pub lane: usize,
    /// 1-based line of the token within the pattern.
    pub line: usize,
    /// 1-based column (in characters) of the token within its line.
    pub column: usize,
    /// Byte offset of the token within the pattern.
    pub offset: usize,
    /// The offending token.
    pub token: String,
    /// What is wrong with it.
    pub kind: ParseErrorKind,
}

impl ParseError {
    fn new(pattern: &str, offset: usize, token: &str, kind: ParseErrorKind) -> Self {
        let before = &pattern[..offset];
        let line_start = before.rfind('\n').map_or(0, |i| i + 1);
        Self {
            lane: 0,
            line: before.matches('\n').count() + 1,
            column: before[line_start..].chars().count() + 1,
            offset,
            token: token.into(),
            kind,
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "lane {}, line {}, column {}: `{}`: {}",
            self.lane, self.line, self.column, self.token, self.kind
        )
    }
}

impl core::error::Error for ParseError {}

/// A piece of music: lanes played in lockstep at a fixed tempo.
#[derive(Debug, Clone, PartialEq)]
pub struct Song {
    /// How fast rows advance.
    pub tempo: Tempo,
    /// Whether to jump back to the first row after the last (music) or stop
    /// and release every note (jingles).
    pub looped: bool,
    /// Patches that `@n` cells switch to.
    pub patches: Vec<SynthParams>,
    /// The tracks.
    pub lanes: Vec<Lane>,
}

impl Song {
    /// An empty, looping song.
    #[must_use]
    pub fn new(tempo: Tempo) -> Self {
        Self {
            tempo,
            looped: true,
            patches: Vec::new(),
            lanes: Vec::new(),
        }
    }

    /// Play once and release every note at the end instead of looping.
    #[must_use]
    pub fn one_shot(mut self) -> Self {
        self.looped = false;
        self
    }

    /// Add a patch for `@n` cells; the first one added is `@0`.
    #[must_use]
    pub fn patch(mut self, params: SynthParams) -> Self {
        self.patches.push(params);
        self
    }

    /// Parse and add a lane playing on `channel`.
    ///
    /// # Errors
    ///
    /// Fails on the first invalid token; the error names the lane by its
    /// index in the song.
    pub fn lane(mut self, channel: ChannelNo, pattern: &str) -> Result<Self, ParseError> {
        let lane = Lane::parse(channel, pattern).map_err(|e| ParseError {
            lane: self.lanes.len(),
            ..e
        })?;
        self.lanes.push(lane);
        Ok(self)
    }

    /// Length in rows: that of the longest lane.
    #[must_use]
    pub fn len(&self) -> usize {
        self.lanes.iter().map(|l| l.rows.len()).max().unwrap_or(0)
    }

    /// Whether the song has no rows.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Length of one pass in seconds, without release tails.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn duration_secs(&self) -> f32 {
        self.len() as f32 * 60.0 / self.tempo.rows_per_minute
    }
}

/// What a lane is currently holding.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum Sounding {
    #[default]
    Nothing,
    Note(ChannelNo, MidiNote),
    Chord(ChannelNo, [MidiNote; MAX_CHORD_NOTES], u8),
    #[cfg(feature = "arp")]
    Arp(ChannelNo, [MidiNote; MAX_ARP_NOTES], u8),
}

/// Plays a [`Song`] as a [`Sequencer`].
///
/// Hand it to a
/// [`SequencedProcessor`](crate::audio::sequencer::SequencedProcessor) or
/// to the cpal engine's `setup_audio_*_with_sequencer`. The first row plays
/// on the first tick.
///
/// Patch changes (`@n`) clone the patch into a boxed
/// [`AudioEvent::LoadPatchChannel`], so they allocate on the audio thread;
/// everything else does not.
#[derive(Debug, Clone)]
pub struct SongPlayer {
    song: Song,
    /// Next row to play; `song.len()` once a one-shot song has ended.
    row: usize,
    /// Fractional frames owed to the next row.
    frame_error: f64,
    lanes: Vec<Sounding>,
    finished: bool,
}

impl SongPlayer {
    /// Prepare to play `song` from the top.
    #[must_use]
    pub fn new(song: Song) -> Self {
        let lanes = vec![Sounding::Nothing; song.lanes.len()];
        Self {
            song,
            row: 0,
            frame_error: 0.0,
            lanes,
            finished: false,
        }
    }

    /// The song being played.
    #[must_use]
    pub fn song(&self) -> &Song {
        &self.song
    }

    /// The row that plays on the next tick.
    #[must_use]
    pub fn row(&self) -> usize {
        self.row
    }

    /// Whether a one-shot song has played its last row and released its
    /// notes. Always `false` for a looping song.
    #[must_use]
    pub fn is_finished(&self) -> bool {
        self.finished
    }

    /// Change the tempo; takes effect from the next row.
    pub fn set_tempo(&mut self, tempo: Tempo) {
        self.song.tempo = tempo;
    }

    /// Jump to `row` on the next tick, keeping held notes.
    pub fn seek(&mut self, row: usize) {
        self.row = row;
        self.finished = false;
    }

    fn release(lane: &mut Sounding, out: &mut Vec<AudioEvent>) {
        match core::mem::take(lane) {
            Sounding::Nothing => {}
            Sounding::Note(ch, note) => out.push(AudioEvent::NoteOffChannel(ch, note)),
            Sounding::Chord(ch, notes, count) => {
                for &note in &notes[..usize::from(count)] {
                    out.push(AudioEvent::NoteOffChannel(ch, note));
                }
            }
            #[cfg(feature = "arp")]
            Sounding::Arp(ch, notes, count) => {
                for &note in &notes[..usize::from(count)] {
                    out.push(AudioEvent::NoteOffChannel(ch, note));
                }
                out.push(AudioEvent::ArpEnabled(ch, false));
            }
        }
    }

    fn play_row(&mut self, out: &mut Vec<AudioEvent>) {
        for (lane, state) in self.song.lanes.iter().zip(&mut self.lanes) {
            let cell = lane.rows.get(self.row).copied().unwrap_or(Cell::HOLD);
            let ch = lane.channel;
            if let Some(params) = cell
                .patch
                .and_then(|i| self.song.patches.get(usize::from(i)))
            {
                out.push(AudioEvent::LoadPatchChannel(ch, Box::new(params.clone())));
            }
            match cell.action {
                Action::Hold => {}
                Action::Off => Self::release(state, out),
                Action::Note(note) => {
                    Self::release(state, out);
                    out.push(AudioEvent::NoteOnChannel(ch, note));
                    *state = Sounding::Note(ch, note);
                }
                Action::Chord { notes, count } => {
                    Self::release(state, out);
                    for &note in &notes[..usize::from(count)] {
                        out.push(AudioEvent::NoteOnChannel(ch, note));
                    }
                    *state = Sounding::Chord(ch, notes, count);
                }
                #[cfg(feature = "arp")]
                Action::Arp { notes, count } => {
                    Self::release(state, out);
                    out.push(AudioEvent::ArpEnabled(ch, true));
                    for &note in &notes[..usize::from(count)] {
                        out.push(AudioEvent::NoteOnChannel(ch, note));
                    }
                    *state = Sounding::Arp(ch, notes, count);
                }
                #[cfg(not(feature = "arp"))]
                Action::Arp { .. } => {}
                Action::Drums(hits) => out.extend(hits.iter().map(AudioEvent::Drum)),
            }
        }
    }
}

impl Sequencer for SongPlayer {
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "a row is a positive number of frames well below usize::MAX"
    )]
    fn tick(&mut self, sample_rate: f32, out: &mut Vec<AudioEvent>) -> usize {
        if self.finished {
            return usize::MAX;
        }
        let len = self.song.len();
        if self.row >= len {
            if self.song.looped && len > 0 {
                self.row = 0;
            } else {
                for state in &mut self.lanes {
                    Self::release(state, out);
                }
                self.finished = true;
                return usize::MAX;
            }
        }

        self.play_row(out);
        self.row += 1;

        let frames = self.song.tempo.frames_per_row(sample_rate) + self.frame_error;
        let whole = frames.floor().max(1.0);
        self.frame_error = frames - whole;
        whole as usize
    }

    fn is_finished(&self) -> bool {
        self.finished
    }
}

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

    const CH0: ChannelNo = ChannelNo(0);
    const CH1: ChannelNo = ChannelNo(1);

    fn note(n: &str) -> MidiNote {
        parse_note(n).unwrap()
    }

    fn cell(token: &str) -> Result<Cell, ParseErrorKind> {
        parse_cell(token).map_err(|e| e.kind)
    }

    #[test]
    fn note_names() {
        assert_eq!(note("C4"), MidiNote(60));
        assert_eq!(note("A4"), MidiNote(69));
        assert_eq!(note("F#3"), MidiNote(54));
        assert_eq!(note("Bb2"), MidiNote(46));
        assert_eq!(note("C-1"), MidiNote(0));
        assert_eq!(note("G9"), MidiNote(127));
        assert_eq!(parse_note("G#9"), Err(ParseErrorKind::NoteOutOfRange));
        assert_eq!(parse_note("Cb-1"), Err(ParseErrorKind::NoteOutOfRange));
        assert_eq!(parse_note("H4"), Err(ParseErrorKind::InvalidNote));
        assert_eq!(parse_note("C"), Err(ParseErrorKind::InvalidNote));
        assert_eq!(parse_note("C#"), Err(ParseErrorKind::InvalidNote));
        assert_eq!(parse_note("Cx4"), Err(ParseErrorKind::InvalidNote));
    }

    #[test]
    fn cells() {
        assert_eq!(cell("."), Ok(Cell::HOLD));
        assert_eq!(cell("-").unwrap().action, Action::Off);
        assert_eq!(cell("E2").unwrap().action, Action::Note(note("E2")));
        assert_eq!(
            cell("k+c").unwrap().action,
            Action::Drums([DrumHit::Kick, DrumHit::Crash].into_iter().collect())
        );
        assert_eq!(
            cell("lt+mt+ht+x+o+h+s").unwrap().action,
            Action::Drums(
                [
                    DrumHit::TomLow,
                    DrumHit::TomMid,
                    DrumHit::TomHigh,
                    DrumHit::Clap,
                    DrumHit::HiHatOpen,
                    DrumHit::HiHatClosed,
                    DrumHit::Snare
                ]
                .into_iter()
                .collect()
            )
        );
        assert_eq!(
            cell("C4@2"),
            Ok(Cell {
                patch: Some(2),
                action: Action::Note(MidiNote(60))
            })
        );
        assert_eq!(
            cell("@3"),
            Ok(Cell {
                patch: Some(3),
                action: Action::Hold
            })
        );
        assert_eq!(cell("@"), Err(ParseErrorKind::InvalidPatch));
        assert_eq!(cell("C4@x"), Err(ParseErrorKind::InvalidPatch));
        assert_eq!(cell("k@1"), Err(ParseErrorKind::PatchOnDrums));
        assert_eq!(cell("q"), Err(ParseErrorKind::UnknownToken));
        assert_eq!(cell("k+"), Err(ParseErrorKind::UnknownToken));
        assert_eq!(cell("K"), Err(ParseErrorKind::InvalidNote));
    }

    #[cfg(feature = "arp")]
    #[test]
    fn arpeggio_cells() {
        assert_eq!(
            cell("C4^047").unwrap().action,
            Action::Arp {
                notes: [MidiNote(60), MidiNote(64), MidiNote(67), MidiNote(60)],
                count: 3
            }
        );
        assert_eq!(
            cell("A3^037c").unwrap().action,
            Action::Arp {
                notes: [MidiNote(57), MidiNote(60), MidiNote(64), MidiNote(69)],
                count: 4
            }
        );
        assert_eq!(cell("C4^0"), Err(ParseErrorKind::InvalidArp));
        assert_eq!(cell("C4^01234"), Err(ParseErrorKind::InvalidArp));
        assert_eq!(cell("C4^0g"), Err(ParseErrorKind::InvalidArp));
        assert_eq!(cell("G9^04"), Err(ParseErrorKind::NoteOutOfRange));
    }

    #[cfg(not(feature = "arp"))]
    #[test]
    fn arpeggios_need_the_arp_feature() {
        assert_eq!(cell("C4^047"), Err(ParseErrorKind::ArpUnsupported));
    }

    #[test]
    fn chord_cells() {
        let n = MidiNote;
        assert_eq!(
            cell("E2+B2+E3"),
            Ok(Cell {
                patch: None,
                action: Action::Chord {
                    notes: [n(40), n(47), n(52), n(0)],
                    count: 3
                }
            })
        );
        assert_eq!(
            cell("E2+B2+E3@1"),
            Ok(Cell {
                patch: Some(1),
                action: Action::Chord {
                    notes: [n(40), n(47), n(52), n(0)],
                    count: 3
                }
            })
        );
        assert_eq!(
            cell("C4+E4+G4+B4").unwrap().action,
            Action::Chord {
                notes: [n(60), n(64), n(67), n(71)],
                count: 4
            }
        );
        assert_eq!(
            cell("C4+E4+G4+B4+D5"),
            Err(ParseErrorKind::TooManyChordNotes)
        );
        assert_eq!(cell("C4+C4"), Err(ParseErrorKind::DuplicateChordNote));
        assert_eq!(cell("C4+"), Err(ParseErrorKind::InvalidNote));
        assert_eq!(cell("C4+k"), Err(ParseErrorKind::InvalidNote));
        assert_eq!(cell("C4+G#9+C10"), Err(ParseErrorKind::NoteOutOfRange));
    }

    #[test]
    fn interval_chord_cells() {
        let n = MidiNote;
        assert_eq!(
            cell("E2^07c!").unwrap().action,
            Action::Chord {
                notes: [n(40), n(47), n(52), n(40)],
                count: 3
            }
        );
        assert_eq!(
            cell("A3^07!@2"),
            Ok(Cell {
                patch: Some(2),
                action: Action::Chord {
                    notes: [n(57), n(64), n(57), n(57)],
                    count: 2
                }
            })
        );
        assert_eq!(cell("C4^0!"), Err(ParseErrorKind::InvalidChord));
        assert_eq!(cell("C4^04790!"), Err(ParseErrorKind::InvalidChord));
        assert_eq!(cell("C4^0z!"), Err(ParseErrorKind::InvalidChord));
        assert_eq!(cell("C4^00!"), Err(ParseErrorKind::DuplicateChordNote));
        assert_eq!(cell("G9^07!"), Err(ParseErrorKind::NoteOutOfRange));
    }

    #[test]
    fn chord_errors_point_at_the_bad_note() {
        let err = Lane::parse(CH0, "E2 . G2+D3+H3 .").unwrap_err();
        assert_eq!((err.column, err.offset, err.token.as_str()), (12, 11, "H3"));
        assert_eq!(err.kind, ParseErrorKind::InvalidNote);

        let err = Lane::parse(CH0, "C4+E4+G4+B4+D5@1").unwrap_err();
        assert_eq!((err.column, err.token.as_str()), (13, "D5"));
        assert_eq!(err.kind, ParseErrorKind::TooManyChordNotes);

        let err = Lane::parse(CH0, ". C4+E4+C4").unwrap_err();
        assert_eq!((err.column, err.token.as_str()), (9, "C4"));
        assert_eq!(err.kind, ParseErrorKind::DuplicateChordNote);
    }

    #[test]
    fn bar_lines_are_ignored() {
        let lane = Lane::parse(CH0, "C4 . | - .\n|\tk").unwrap();
        assert_eq!(lane.rows.len(), 5);
    }

    #[test]
    fn errors_point_at_the_offending_token() {
        let err = Song::new(Tempo::bpm(120.0, 2))
            .lane(CH0, "C4 . . .")
            .unwrap()
            .lane(CH1, "C4 . . . |\n  E4 H4 . .")
            .unwrap_err();
        assert_eq!(err.lane, 1);
        assert_eq!((err.line, err.column), (2, 6));
        assert_eq!(err.offset, 16);
        assert_eq!(err.token, "H4");
        assert_eq!(err.kind, ParseErrorKind::InvalidNote);
        assert_eq!(
            err.to_string(),
            "lane 1, line 2, column 6: `H4`: invalid note; expected e.g. `C4`, `F#3` or `Bb2`"
        );
    }

    #[test]
    fn columns_count_characters_not_bytes() {
        let err = Lane::parse(CH0, "C4 ü ?").unwrap_err();
        assert_eq!((err.line, err.column, err.token.as_str()), (1, 4, "ü"));
    }

    /// `AudioEvent` has no `PartialEq`; compare the debug output.
    macro_rules! assert_events {
        ($a:expr, $b:expr $(,)?) => {
            assert_eq!(format!("{:?}", $a), format!("{:?}", $b))
        };
    }

    /// Tick `player` `rows` times; returns the events of each row.
    fn play(player: &mut SongPlayer, rows: usize) -> Vec<Vec<AudioEvent>> {
        (0..rows)
            .map(|_| {
                let mut out = Vec::new();
                player.tick(44_100.0, &mut out);
                out
            })
            .collect()
    }

    #[test]
    fn lanes_are_monophonic_and_release_on_off() {
        let song = Song::new(Tempo::bpm(120.0, 2))
            .lane(CH0, "C4 . E4 - .")
            .unwrap()
            .lane(CH1, "k . k+h . .")
            .unwrap();
        let rows = play(&mut SongPlayer::new(song), 5);
        let (c4, e4) = (MidiNote(60), MidiNote(64));
        assert_events!(
            rows,
            vec![
                vec![
                    AudioEvent::NoteOnChannel(CH0, c4),
                    AudioEvent::Drum(DrumHit::Kick)
                ],
                vec![],
                vec![
                    AudioEvent::NoteOffChannel(CH0, c4),
                    AudioEvent::NoteOnChannel(CH0, e4),
                    AudioEvent::Drum(DrumHit::Kick),
                    AudioEvent::Drum(DrumHit::HiHatClosed),
                ],
                vec![AudioEvent::NoteOffChannel(CH0, e4)],
                vec![],
            ]
        );
    }

    #[test]
    fn patch_changes_load_before_the_note() {
        let mut lead = SynthParams::default();
        lead.global.volume = 0.25;
        let song = Song::new(Tempo::bpm(120.0, 2))
            .patch(SynthParams::default())
            .patch(lead.clone())
            .lane(CH1, "C4@1 @0 @9")
            .unwrap();
        let rows = play(&mut SongPlayer::new(song), 3);
        assert_events!(
            rows[0],
            vec![
                AudioEvent::LoadPatchChannel(CH1, Box::new(lead)),
                AudioEvent::NoteOnChannel(CH1, MidiNote(60)),
            ]
        );
        assert_events!(
            rows[1],
            vec![AudioEvent::LoadPatchChannel(
                CH1,
                Box::<SynthParams>::default()
            )]
        );
        assert!(rows[2].is_empty(), "unknown patches are ignored");
    }

    #[test]
    fn chords_start_and_release_together() {
        let song = Song::new(Tempo::bpm(120.0, 2))
            .lane(CH0, "E2+B2+E3 . G2+D3 C4 E2^07! -")
            .unwrap();
        let rows = play(&mut SongPlayer::new(song), 6);
        let n = MidiNote;
        let on = |m| AudioEvent::NoteOnChannel(CH0, n(m));
        let off = |m| AudioEvent::NoteOffChannel(CH0, n(m));
        assert_events!(
            rows,
            vec![
                vec![on(40), on(47), on(52)],
                vec![],
                vec![off(40), off(47), off(52), on(43), on(50)],
                vec![off(43), off(50), on(60)],
                vec![off(60), on(40), on(47)],
                vec![off(40), off(47)],
            ]
        );
    }

    #[test]
    fn one_shot_songs_release_held_chords() {
        let song = Song::new(Tempo::bpm(120.0, 2))
            .one_shot()
            .lane(CH0, "C4+G4")
            .unwrap();
        let mut player = SongPlayer::new(song);
        play(&mut player, 1);
        let mut out = Vec::new();
        player.tick(44_100.0, &mut out);
        assert_events!(
            out,
            vec![
                AudioEvent::NoteOffChannel(CH0, MidiNote(60)),
                AudioEvent::NoteOffChannel(CH0, MidiNote(67)),
            ]
        );
    }

    #[test]
    fn a_full_chord_sounds_every_voice() {
        use crate::audio::processor::SynthProcessor;
        use crate::audio::sequencer::SequencedProcessor;

        let song = Song::new(Tempo::bpm(120.0, 2))
            .lane(CH0, "C4+E4+G4+B4 .")
            .unwrap();
        let mut synth =
            SequencedProcessor::new(SynthProcessor::<1>::new(44_100.0), SongPlayer::new(song));
        let mut out = vec![0.0f32; 512];
        synth.process_block(&[], &mut out, 1);
        assert_eq!(synth.processor().active_voices(), MAX_CHORD_NOTES);
    }

    #[cfg(feature = "arp")]
    #[test]
    fn arpeggios_drive_the_channels_arpeggiator() {
        let song = Song::new(Tempo::bpm(120.0, 2))
            .lane(CH0, "C4^047 G4 -")
            .unwrap();
        let rows = play(&mut SongPlayer::new(song), 3);
        let n = MidiNote;
        assert_events!(
            rows[0],
            vec![
                AudioEvent::ArpEnabled(CH0, true),
                AudioEvent::NoteOnChannel(CH0, n(60)),
                AudioEvent::NoteOnChannel(CH0, n(64)),
                AudioEvent::NoteOnChannel(CH0, n(67)),
            ]
        );
        assert_events!(
            rows[1],
            vec![
                AudioEvent::NoteOffChannel(CH0, n(60)),
                AudioEvent::NoteOffChannel(CH0, n(64)),
                AudioEvent::NoteOffChannel(CH0, n(67)),
                AudioEvent::ArpEnabled(CH0, false),
                AudioEvent::NoteOnChannel(CH0, n(67)),
            ]
        );
        assert_events!(rows[2], vec![AudioEvent::NoteOffChannel(CH0, n(67))]);
    }

    #[test]
    fn looping_songs_wrap_and_short_lanes_hold() {
        let song = Song::new(Tempo::bpm(120.0, 2))
            .lane(CH0, "C4 - . .")
            .unwrap()
            .lane(CH1, "k")
            .unwrap();
        let mut player = SongPlayer::new(song);
        let rows = play(&mut player, 6);
        assert_events!(rows[4], rows[0]);
        assert_events!(rows[5], rows[1]);
        assert!(rows[2].is_empty() && rows[3].is_empty());
        assert!(!player.is_finished());
    }

    #[test]
    fn one_shot_songs_release_everything_and_stop() {
        let song = Song::new(Tempo::bpm(120.0, 2))
            .one_shot()
            .lane(CH0, "C4 .")
            .unwrap()
            .lane(CH1, "E4 G4")
            .unwrap();
        let mut player = SongPlayer::new(song);
        play(&mut player, 2);
        assert!(!player.is_finished());
        let mut out = Vec::new();
        assert_eq!(player.tick(44_100.0, &mut out), usize::MAX);
        assert_events!(
            out,
            vec![
                AudioEvent::NoteOffChannel(CH0, MidiNote(60)),
                AudioEvent::NoteOffChannel(CH1, MidiNote(67)),
            ]
        );
        assert!(player.is_finished());
        out.clear();
        assert_eq!(player.tick(44_100.0, &mut out), usize::MAX);
        assert!(out.is_empty());
    }

    #[test]
    fn an_empty_song_finishes_at_once() {
        let mut player = SongPlayer::new(Song::new(Tempo::bpm(120.0, 2)));
        assert_eq!(player.tick(44_100.0, &mut Vec::new()), usize::MAX);
        assert!(player.is_finished());
    }

    #[test]
    fn the_tempo_does_not_drift() {
        // 152 bpm in eighths at 44.1 kHz: 8 703.9... frames per row.
        let song = Song::new(Tempo::bpm(152.0, 2)).lane(CH0, "C4").unwrap();
        let mut player = SongPlayer::new(song);
        let total: usize = (0..304)
            .map(|_| player.tick(44_100.0, &mut Vec::new()))
            .sum();
        assert_eq!(total, 44_100 * 60, "304 rows at 304 rows/min is one minute");
    }

    #[test]
    #[should_panic(expected = "tempo must be finite and positive")]
    fn a_zero_tempo_is_rejected() {
        let _ = Tempo::bpm(0.0, 4);
    }

    #[test]
    fn songs_play_through_the_processor_independent_of_buffer_size() {
        use crate::audio::processor::SynthProcessor;
        use crate::audio::sequencer::SequencedProcessor;
        use crate::presets::sid::default_patches;

        let patches = default_patches();
        let song = || {
            Song::new(Tempo::bpm(150.0, 4))
                .patch(patches[0].params.clone())
                .patch(patches[3].params.clone())
                .lane(CH0, "E2@0 . E2 . G2 . A2 . | E2 . E2 . - . . .")
                .unwrap()
                .lane(CH1, "E4@1 . G4 . A4 . B4 . | E5 . . . . . - .")
                .unwrap()
                .lane(ChannelNo(3), "k+c h s h k h s o | k h s h k x s+h ht")
                .unwrap()
        };
        let render = |block: usize| {
            let mut synth = SequencedProcessor::new(
                SynthProcessor::<4>::new(44_100.0),
                SongPlayer::new(song()),
            );
            let mut out = vec![0.0f32; 44_100];
            for chunk in out.chunks_mut(block) {
                synth.process_block(&[], chunk, 1);
            }
            out
        };
        let a = render(4_096);
        assert!(a.iter().any(|s| s.abs() > 0.05), "song is silent");
        let b = render(97);
        assert!(a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()));
    }
}