mlua-pulse 0.1.0

Lua-friendly music composition and audio export bindings built on tunes and mlua
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
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
//! Song, phrase, sequence, and sample-clip builders used by the Lua DSL.

use crate::drums::PulseDrumGrid;
use crate::effects::PulseEffect;
use crate::error::{PulseError, PulseResult};
use crate::instruments::instrument_by_name;
use crate::synthesis::PulseSynth;
use crate::theory::transpose_notes;
use tunes::composition::{Composition, Tempo};
use tunes::synthesis::sample::Sample;
use tunes::track::{AudioEvent, Mixer, Track};

/// One monophonic or polyphonic sequence event.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseNoteEvent {
    frequencies: Vec<f32>,
    duration: f32,
}

impl PulseNoteEvent {
    /// Creates one note or chord event.
    pub fn new(frequencies: Vec<f32>, duration: f32) -> PulseResult<Self> {
        validate_event_frequencies(&frequencies)?;
        validate_sequence_duration(duration)?;
        Ok(Self {
            frequencies,
            duration,
        })
    }

    /// Returns event frequencies.
    pub fn frequencies(&self) -> &[f32] {
        &self.frequencies
    }

    /// Returns event duration.
    pub fn duration(&self) -> f32 {
        self.duration
    }
}

/// A Lua-friendly melodic sequence with one duration per event.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseSequence {
    notes: Vec<f32>,
    chords: Vec<Vec<f32>>,
    durations: Vec<f32>,
    instrument: String,
    synth: Option<PulseSynth>,
    effects: Vec<PulseEffect>,
    start_at: f32,
    volume: f32,
    pan: f32,
    velocity: f32,
}

impl Default for PulseSequence {
    fn default() -> Self {
        Self::new()
    }
}

impl PulseSequence {
    /// Creates an empty sequence using `electric_piano`.
    pub fn new() -> Self {
        Self {
            notes: Vec::new(),
            chords: Vec::new(),
            durations: Vec::new(),
            instrument: "electric_piano".to_string(),
            synth: None,
            effects: Vec::new(),
            start_at: 0.0,
            volume: 1.0,
            pan: 0.0,
            velocity: 0.8,
        }
    }

    /// Replaces the sequence note frequencies.
    #[must_use]
    pub fn with_notes(mut self, notes: Vec<f32>) -> Self {
        self.notes = notes;
        self.chords.clear();
        self
    }

    /// Replaces the sequence with polyphonic note events.
    #[must_use]
    pub fn with_chords(mut self, chords: Vec<Vec<f32>>) -> Self {
        self.chords = chords;
        self.notes.clear();
        self
    }

    /// Replaces the sequence durations.
    #[must_use]
    pub fn with_durations(mut self, durations: Vec<f32>) -> Self {
        self.durations = durations;
        self
    }

    /// Sets the instrument alias for this sequence.
    #[must_use]
    pub fn with_instrument(mut self, instrument: impl Into<String>) -> Self {
        self.instrument = instrument.into();
        self
    }

    /// Sets an explicit synthesis algorithm for this sequence.
    #[must_use]
    pub fn with_synth(mut self, synth: PulseSynth) -> Self {
        self.synth = Some(synth);
        self
    }

    /// Sets a sequence start offset relative to the song or phrase placement.
    pub fn with_start_at(mut self, start_at: f32) -> PulseResult<Self> {
        validate_non_negative_sequence_option("at", start_at)?;
        self.start_at = start_at;
        Ok(self)
    }

    /// Sets track volume for this sequence.
    pub fn with_volume(mut self, volume: f32) -> PulseResult<Self> {
        validate_sequence_range("volume", volume, 0.0, 2.0)?;
        self.volume = volume;
        Ok(self)
    }

    /// Sets stereo pan for this sequence.
    pub fn with_pan(mut self, pan: f32) -> PulseResult<Self> {
        validate_sequence_range("pan", pan, -1.0, 1.0)?;
        self.pan = pan;
        Ok(self)
    }

    /// Sets velocity for notes exported from this sequence.
    pub fn with_velocity(mut self, velocity: f32) -> PulseResult<Self> {
        validate_sequence_range("velocity", velocity, 0.0, 1.0)?;
        self.velocity = velocity;
        Ok(self)
    }

    /// Returns a transposed copy without mutating the original sequence.
    #[must_use]
    pub fn transposed(&self, semitones: i32) -> Self {
        let mut sequence = self.clone();
        sequence.notes = transpose_notes(&sequence.notes, semitones);
        sequence.chords = sequence
            .chords
            .iter()
            .map(|chord| transpose_notes(chord, semitones))
            .collect();
        sequence
    }

    /// Appends a track-level effect to the sequence.
    #[must_use]
    pub fn with_effect(mut self, effect: PulseEffect) -> Self {
        self.effects.push(effect);
        self
    }

    /// Validates sequence shape and instrument name.
    pub fn validate(&self) -> PulseResult<()> {
        let event_count = self.event_count();
        if event_count != self.durations.len() {
            return Err(PulseError::DurationCountMismatch {
                notes: event_count,
                durations: self.durations.len(),
            });
        }

        for &duration in &self.durations {
            validate_sequence_duration(duration)?;
        }

        if !self.chords.is_empty() {
            for chord in &self.chords {
                validate_event_frequencies(chord)?;
            }
        } else {
            for &frequency in &self.notes {
                validate_note_frequency(frequency)?;
            }
        }

        if matches!(self.synth, Some(PulseSynth::KarplusStrong(_)))
            && self.chords.iter().any(|chord| chord.len() > 1)
        {
            return Err(PulseError::InvalidSynthOption {
                synth: "karplus_strong".to_string(),
                option: "chords".to_string(),
                value: "polyphonic".to_string(),
            });
        }

        validate_non_negative_sequence_option("at", self.start_at)?;
        validate_sequence_range("volume", self.volume, 0.0, 2.0)?;
        validate_sequence_range("pan", self.pan, -1.0, 1.0)?;
        validate_sequence_range("velocity", self.velocity, 0.0, 1.0)?;
        instrument_by_name(&self.instrument)?;
        Ok(())
    }

    /// Returns note/chord events with the current durations applied.
    pub fn events(&self) -> PulseResult<Vec<PulseNoteEvent>> {
        self.validate()?;
        if !self.chords.is_empty() {
            return self
                .chords
                .iter()
                .cloned()
                .zip(self.durations.iter().copied())
                .map(|(frequencies, duration)| PulseNoteEvent::new(frequencies, duration))
                .collect();
        }

        self.notes
            .iter()
            .copied()
            .zip(self.durations.iter().copied())
            .map(|(frequency, duration)| PulseNoteEvent::new(vec![frequency], duration))
            .collect()
    }

    /// Returns note frequencies.
    pub fn notes(&self) -> &[f32] {
        &self.notes
    }

    /// Returns polyphonic event frequencies.
    pub fn chords(&self) -> &[Vec<f32>] {
        &self.chords
    }

    /// Returns durations in beats.
    pub fn durations(&self) -> &[f32] {
        &self.durations
    }

    /// Returns the instrument alias.
    pub fn instrument(&self) -> &str {
        &self.instrument
    }

    /// Returns the explicit synthesis algorithm, if one was selected.
    pub fn synth(&self) -> Option<&PulseSynth> {
        self.synth.as_ref()
    }

    /// Returns track-level effects in insertion order.
    pub fn effects(&self) -> &[PulseEffect] {
        &self.effects
    }

    /// Returns the sequence start offset.
    pub fn start_at(&self) -> f32 {
        self.start_at
    }

    /// Returns sequence track volume.
    pub fn volume(&self) -> f32 {
        self.volume
    }

    /// Returns sequence track pan.
    pub fn pan(&self) -> f32 {
        self.pan
    }

    /// Returns sequence note velocity.
    pub fn velocity(&self) -> f32 {
        self.velocity
    }

    /// Returns the sequence duration in the same timeline units used by `tunes`.
    pub fn duration(&self) -> f32 {
        if let Some(PulseSynth::Granular(synth)) = self.synth() {
            return self.start_at + synth.duration;
        }
        self.start_at + self.durations.iter().sum::<f32>()
    }

    fn event_count(&self) -> usize {
        if self.chords.is_empty() {
            self.notes.len()
        } else {
            self.chords.len()
        }
    }
}

fn validate_sequence_duration(duration: f32) -> PulseResult<()> {
    if duration.is_finite() && duration > 0.0 {
        Ok(())
    } else {
        Err(PulseError::InvalidDuration { duration })
    }
}

fn validate_note_frequency(frequency: f32) -> PulseResult<()> {
    if frequency.is_finite() && frequency > 0.0 {
        Ok(())
    } else {
        Err(PulseError::InvalidFrequency { frequency })
    }
}

fn validate_event_frequencies(frequencies: &[f32]) -> PulseResult<()> {
    if frequencies.is_empty() || frequencies.len() > 8 {
        return Err(PulseError::InvalidChordVoiceCount {
            count: frequencies.len(),
        });
    }

    for &frequency in frequencies {
        validate_note_frequency(frequency)?;
    }

    Ok(())
}

fn validate_sequence_range(option: &str, value: f32, min: f32, max: f32) -> PulseResult<()> {
    if value.is_finite() && value >= min && value <= max {
        Ok(())
    } else {
        Err(invalid_sequence_option(option, value))
    }
}

fn validate_non_negative_sequence_option(option: &str, value: f32) -> PulseResult<()> {
    if value.is_finite() && value >= 0.0 {
        Ok(())
    } else {
        Err(invalid_sequence_option(option, value))
    }
}

fn invalid_sequence_option(option: &str, value: f32) -> PulseError {
    PulseError::InvalidSequenceOption {
        option: option.to_string(),
        value: value.to_string(),
    }
}

/// A Lua-friendly sample clip that renders into offline audio exports.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseSampleClip {
    path: String,
    playback_rate: f32,
    gain: f32,
    pitch_shift: f32,
    time_stretch: f32,
    start_at: f32,
    track_name: Option<String>,
    volume: f32,
    pan: f32,
    effects: Vec<PulseEffect>,
    slice_range: Option<(f32, f32)>,
    reverse: bool,
    loop_for: Option<f32>,
    normalize: bool,
    fade_in: f32,
    fade_out: f32,
}

impl PulseSampleClip {
    /// Creates a sample clip from an audio file path.
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            playback_rate: 1.0,
            gain: 1.0,
            pitch_shift: 0.0,
            time_stretch: 1.0,
            start_at: 0.0,
            track_name: None,
            volume: 1.0,
            pan: 0.0,
            effects: Vec::new(),
            slice_range: None,
            reverse: false,
            loop_for: None,
            normalize: false,
            fade_in: 0.0,
            fade_out: 0.0,
        }
    }

    /// Sets sample playback rate. Values above 1 play faster and higher.
    pub fn with_playback_rate(mut self, playback_rate: f32) -> PulseResult<Self> {
        validate_positive_sample_option("rate", playback_rate)?;
        self.playback_rate = playback_rate;
        Ok(self)
    }

    /// Sets sample gain before the clip is inserted into the composition.
    pub fn with_gain(mut self, gain: f32) -> PulseResult<Self> {
        if !gain.is_finite() || gain < 0.0 {
            return Err(invalid_sample_option("gain", gain));
        }
        self.gain = gain;
        Ok(self)
    }

    /// Shifts pitch in semitones without intentionally changing duration.
    pub fn with_pitch_shift(mut self, semitones: f32) -> PulseResult<Self> {
        if !semitones.is_finite() {
            return Err(invalid_sample_option("pitch_shift", semitones));
        }
        self.pitch_shift = semitones;
        Ok(self)
    }

    /// Stretches time without intentionally changing pitch.
    pub fn with_time_stretch(mut self, factor: f32) -> PulseResult<Self> {
        validate_positive_sample_option("time_stretch", factor)?;
        self.time_stretch = factor;
        Ok(self)
    }

    /// Sets clip start offset relative to the song or phrase placement.
    pub fn with_start_at(mut self, start_at: f32) -> PulseResult<Self> {
        if !start_at.is_finite() || start_at < 0.0 {
            return Err(invalid_sample_option("at", start_at));
        }
        self.start_at = start_at;
        Ok(self)
    }

    /// Sets the track name used when this sample clip is inserted into a song or phrase.
    #[must_use]
    pub fn with_track(mut self, track_name: impl Into<String>) -> Self {
        self.track_name = Some(track_name.into());
        self
    }

    /// Sets track-level volume for the sample clip.
    pub fn with_volume(mut self, volume: f32) -> PulseResult<Self> {
        validate_sample_volume(volume)?;
        self.volume = volume;
        Ok(self)
    }

    /// Sets track-level stereo pan for the sample clip.
    pub fn with_pan(mut self, pan: f32) -> PulseResult<Self> {
        validate_sample_pan(pan)?;
        self.pan = pan;
        Ok(self)
    }

    /// Appends one track-level effect to this sample clip.
    #[must_use]
    pub fn with_effect(mut self, effect: PulseEffect) -> Self {
        self.effects.push(effect);
        self
    }

    /// Selects a source audio time range before pitch, stretch, gain, and rate transforms.
    pub fn with_slice(mut self, start: f32, end: f32) -> PulseResult<Self> {
        validate_sample_slice(start, end)?;
        self.slice_range = Some((start, end));
        Ok(self)
    }

    /// Reverses the selected source sample range before fades, pitch, stretch, gain, and rate transforms.
    pub fn with_reverse(mut self) -> Self {
        self.reverse = true;
        self
    }

    /// Repeats the selected source sample range to a fixed offline render duration.
    pub fn with_loop_for(mut self, duration: f32) -> PulseResult<Self> {
        validate_positive_sample_option("loop_for", duration)?;
        self.loop_for = Some(duration);
        Ok(self)
    }

    /// Normalizes the selected source sample peak before fades and final gain.
    pub fn with_normalize(mut self) -> Self {
        self.normalize = true;
        self
    }

    /// Applies a fade-in to the rendered source sample before pitch, stretch, gain, and rate transforms.
    pub fn with_fade_in(mut self, duration: f32) -> PulseResult<Self> {
        validate_non_negative_sample_option("fade_in", duration)?;
        self.fade_in = duration;
        Ok(self)
    }

    /// Applies a fade-out to the rendered source sample before pitch, stretch, gain, and rate transforms.
    pub fn with_fade_out(mut self, duration: f32) -> PulseResult<Self> {
        validate_non_negative_sample_option("fade_out", duration)?;
        self.fade_out = duration;
        Ok(self)
    }

    /// Returns the source audio file path.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns the sample playback rate.
    pub fn playback_rate(&self) -> f32 {
        self.playback_rate
    }

    /// Returns clip start offset relative to the song or phrase placement.
    pub fn start_at(&self) -> f32 {
        self.start_at
    }

    /// Returns the explicit track name, if one was set.
    pub fn track_name(&self) -> Option<&str> {
        self.track_name.as_deref()
    }

    /// Returns track-level volume.
    pub fn volume(&self) -> f32 {
        self.volume
    }

    /// Returns track-level pan.
    pub fn pan(&self) -> f32 {
        self.pan
    }

    /// Returns track-level effects in insertion order.
    pub fn effects(&self) -> &[PulseEffect] {
        &self.effects
    }

    /// Returns selected source slice range, if any.
    pub fn slice_range(&self) -> Option<(f32, f32)> {
        self.slice_range
    }

    /// Returns whether the selected source sample range is reversed before rendering.
    pub fn reverse(&self) -> bool {
        self.reverse
    }

    /// Returns the requested offline loop duration, if any.
    pub fn loop_for(&self) -> Option<f32> {
        self.loop_for
    }

    /// Returns whether the rendered source sample is normalized before final gain.
    pub fn normalize(&self) -> bool {
        self.normalize
    }

    /// Returns fade-in duration in seconds.
    pub fn fade_in(&self) -> f32 {
        self.fade_in
    }

    /// Returns fade-out duration in seconds.
    pub fn fade_out(&self) -> f32 {
        self.fade_out
    }

    /// Returns rendered clip duration after sample transforms and playback rate.
    pub fn duration(&self) -> PulseResult<f32> {
        if let Ok(duration) = self.metadata_duration() {
            return Ok(duration);
        }

        let sample = self.transformed_sample()?;
        Ok(self.start_at + sample.duration / self.playback_rate)
    }

    fn metadata_duration(&self) -> PulseResult<f32> {
        validate_sample_timing_options(self)?;

        let source_duration = wav_duration_seconds(&self.path)?;
        let mut duration = if let Some((start, end)) = self.slice_range {
            if end > source_duration {
                return Err(PulseError::SampleLoadFailed {
                    message: format!("slice end {end} exceeds sample duration {source_duration}"),
                });
            }
            end - start
        } else {
            source_duration
        };

        if let Some(loop_for) = self.loop_for {
            validate_positive_sample_option("loop_for", loop_for)?;
            duration = loop_for;
        }

        if (self.time_stretch - 1.0).abs() >= 0.01 {
            duration *= self.time_stretch;
        }

        Ok(self.start_at + duration / self.playback_rate)
    }

    fn transformed_sample(&self) -> PulseResult<Sample> {
        validate_sample_timing_options(self)?;
        validate_sample_volume(self.volume)?;
        validate_sample_pan(self.pan)?;
        validate_non_negative_sample_option("fade_in", self.fade_in)?;
        validate_non_negative_sample_option("fade_out", self.fade_out)?;
        validate_non_negative_sample_option("gain", self.gain)?;
        validate_finite_sample_option("pitch_shift", self.pitch_shift)?;

        let mut sample =
            Sample::from_file(&self.path).map_err(|error| PulseError::SampleLoadFailed {
                message: error.to_string(),
            })?;

        if let Some((start, end)) = self.slice_range {
            sample = sample
                .slice(start, end)
                .map_err(|error| PulseError::SampleLoadFailed {
                    message: error.to_string(),
                })?;
        }
        if self.reverse {
            sample = sample.reverse();
        }
        if let Some(duration) = self.loop_for {
            validate_positive_sample_option("loop_for", duration)?;
            sample = loop_sample_for_duration(&sample, duration)?;
        }
        if self.normalize {
            sample = sample.normalize();
        }
        if self.fade_in > 0.0 {
            sample = sample.with_fade_in(self.fade_in);
        }
        if self.fade_out > 0.0 {
            sample = sample.with_fade_out(self.fade_out);
        }
        if self.pitch_shift.abs() >= 0.01 {
            sample = sample.pitch_shift(self.pitch_shift);
        }
        // Match the 0.01 threshold used by metadata_duration and tunes' own
        // time_stretch, so duration predictions stay in lock-step with rendering.
        if (self.time_stretch - 1.0).abs() >= 0.01 {
            sample = sample.time_stretch(self.time_stretch);
        }
        if (self.gain - 1.0).abs() >= 0.001 {
            sample = sample.with_gain(self.gain);
        }

        Ok(sample)
    }
}

fn loop_sample_for_duration(sample: &Sample, duration: f32) -> PulseResult<Sample> {
    validate_positive_sample_option("loop_for", duration)?;
    if sample.duration <= 0.0 || !sample.duration.is_finite() {
        return Err(PulseError::SampleLoadFailed {
            message: "sample duration must be positive before loop_for".to_string(),
        });
    }

    let sample_rate = sample.sample_rate();
    let frame_count = sample_frame_count("loop_for", duration, sample_rate)?;
    if frame_count == 0 {
        return Err(invalid_sample_option("loop_for", duration));
    }

    let mut data = Vec::with_capacity(frame_count);
    for frame in 0..frame_count {
        let time = frame as f32 / sample_rate as f32;
        let source_time = time % sample.duration;
        let (left, right) = sample.sample_at_interpolated(source_time, 1.0);
        data.push((left + right) * 0.5);
    }

    Ok(Sample::from_mono(data, sample_rate))
}

fn sample_frame_count(option: &str, duration: f32, sample_rate: u32) -> PulseResult<usize> {
    let frames = f64::from(duration) * f64::from(sample_rate);
    let max_frames = isize::MAX as usize / std::mem::size_of::<f32>();
    if !frames.is_finite() || frames <= 0.0 || frames > max_frames as f64 {
        return Err(invalid_sample_option(option, duration));
    }

    Ok(frames.round() as usize)
}

fn wav_duration_seconds(path: &str) -> PulseResult<f32> {
    let reader = hound::WavReader::open(path).map_err(|error| PulseError::SampleLoadFailed {
        message: error.to_string(),
    })?;
    let spec = reader.spec();
    if spec.sample_rate == 0 {
        return Err(PulseError::SampleLoadFailed {
            message: "wav sample rate must be positive".to_string(),
        });
    }

    Ok(reader.duration() as f32 / spec.sample_rate as f32)
}

fn validate_sample_timing_options(sample_clip: &PulseSampleClip) -> PulseResult<()> {
    if sample_clip.path.trim().is_empty() {
        return Err(PulseError::InvalidSampleOption {
            option: "path".to_string(),
            value: "empty".to_string(),
        });
    }
    validate_positive_sample_option("rate", sample_clip.playback_rate)?;
    validate_positive_sample_option("time_stretch", sample_clip.time_stretch)?;
    if !sample_clip.start_at.is_finite() || sample_clip.start_at < 0.0 {
        return Err(invalid_sample_option("at", sample_clip.start_at));
    }
    if let Some((start, end)) = sample_clip.slice_range {
        validate_sample_slice(start, end)?;
    }
    Ok(())
}

fn validate_positive_sample_option(option: &str, value: f32) -> PulseResult<()> {
    if value.is_finite() && value > 0.0 {
        Ok(())
    } else {
        Err(invalid_sample_option(option, value))
    }
}

fn validate_non_negative_sample_option(option: &str, value: f32) -> PulseResult<()> {
    if value.is_finite() && value >= 0.0 {
        Ok(())
    } else {
        Err(invalid_sample_option(option, value))
    }
}

fn validate_finite_sample_option(option: &str, value: f32) -> PulseResult<()> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(invalid_sample_option(option, value))
    }
}

fn validate_sample_volume(value: f32) -> PulseResult<()> {
    if value.is_finite() && (0.0..=2.0).contains(&value) {
        Ok(())
    } else {
        Err(invalid_sample_option("volume", value))
    }
}

fn validate_sample_pan(value: f32) -> PulseResult<()> {
    if value.is_finite() && (-1.0..=1.0).contains(&value) {
        Ok(())
    } else {
        Err(invalid_sample_option("pan", value))
    }
}

fn invalid_sample_option(option: &str, value: f32) -> PulseError {
    PulseError::InvalidSampleOption {
        option: option.to_string(),
        value: value.to_string(),
    }
}

fn validate_sample_slice(start: f32, end: f32) -> PulseResult<()> {
    if start.is_finite() && end.is_finite() && start >= 0.0 && end > start {
        Ok(())
    } else {
        Err(PulseError::InvalidSampleOption {
            option: "slice".to_string(),
            value: format!("{start}..{end}"),
        })
    }
}

/// A MIDI file arranged as a reusable song or phrase clip.
#[derive(Debug, Clone)]
pub struct PulseMidiClip {
    mixer: Mixer,
    start_at: f32,
    track_name: Option<String>,
    volume: f32,
    pan: Option<f32>,
    repeat_times: usize,
    effects: Vec<PulseEffect>,
}

impl PartialEq for PulseMidiClip {
    fn eq(&self, other: &Self) -> bool {
        self.start_at == other.start_at
            && self.track_name == other.track_name
            && self.volume == other.volume
            && self.pan == other.pan
            && self.repeat_times == other.repeat_times
            && self.effects == other.effects
            && self.mixer.total_duration() == other.mixer.total_duration()
    }
}

impl PulseMidiClip {
    /// Creates a MIDI clip from a `tunes` mixer.
    pub fn new(mixer: Mixer) -> Self {
        Self {
            mixer,
            start_at: 0.0,
            track_name: None,
            volume: 1.0,
            pan: None,
            repeat_times: 1,
            effects: Vec::new(),
        }
    }

    /// Sets the clip start offset relative to its song or phrase placement.
    pub fn with_start_at(mut self, start_at: f32) -> PulseResult<Self> {
        validate_midi_clip_non_negative("at", start_at)?;
        self.start_at = start_at;
        Ok(self)
    }

    /// Sets the track-name prefix used when imported MIDI tracks are merged.
    #[must_use]
    pub fn with_track(mut self, track_name: impl Into<String>) -> Self {
        self.track_name = Some(track_name.into());
        self
    }

    /// Sets a clip-level volume multiplier for all imported MIDI tracks.
    pub fn with_volume(mut self, volume: f32) -> PulseResult<Self> {
        validate_midi_clip_volume(volume)?;
        self.volume = volume;
        Ok(self)
    }

    /// Overrides the stereo pan for all imported MIDI tracks.
    pub fn with_pan(mut self, pan: f32) -> PulseResult<Self> {
        validate_midi_clip_pan(pan)?;
        self.pan = Some(pan);
        Ok(self)
    }

    /// Sets how many total times the imported MIDI material should play inside this clip.
    pub fn with_repeat_times(mut self, repeat_times: usize) -> PulseResult<Self> {
        if repeat_times == 0 {
            return Err(PulseError::InvalidRepeatTimes { repeat_times });
        }
        self.repeat_times = repeat_times;
        Ok(self)
    }

    /// Appends one track-level effect to every imported MIDI track.
    #[must_use]
    pub fn with_effect(mut self, effect: PulseEffect) -> Self {
        self.effects.push(effect);
        self
    }

    /// Returns the clip start offset.
    pub fn start_at(&self) -> f32 {
        self.start_at
    }

    /// Returns the explicit track-name prefix, if one was set.
    pub fn track_name(&self) -> Option<&str> {
        self.track_name.as_deref()
    }

    /// Returns the clip-level volume multiplier.
    pub fn volume(&self) -> f32 {
        self.volume
    }

    /// Returns the pan override, if one was set.
    pub fn pan(&self) -> Option<f32> {
        self.pan
    }

    /// Returns how many total times the imported MIDI material plays inside this clip.
    pub fn repeat_times(&self) -> usize {
        self.repeat_times
    }

    /// Returns track-level effects in insertion order.
    pub fn effects(&self) -> &[PulseEffect] {
        &self.effects
    }

    /// Returns clip duration including start offset and internal repeats.
    pub fn duration(&self) -> PulseResult<f32> {
        self.validate()?;
        let repeated_duration =
            repeated_timeline_duration(self.mixer.total_duration(), self.repeat_times)?;
        timeline_offset_duration(self.start_at, repeated_duration, self.repeat_times)
    }

    fn validate(&self) -> PulseResult<()> {
        validate_midi_clip_non_negative("at", self.start_at)?;
        validate_midi_clip_volume(self.volume)?;
        if let Some(pan) = self.pan {
            validate_midi_clip_pan(pan)?;
        }
        if self.repeat_times == 0 {
            return Err(PulseError::InvalidRepeatTimes {
                repeat_times: self.repeat_times,
            });
        }
        repeated_timeline_duration(self.mixer.total_duration(), self.repeat_times)?;
        Ok(())
    }

    fn arranged_tracks(&self, start_at: f32, default_name: &str) -> PulseResult<Vec<Track>> {
        self.validate()?;

        let source_tracks = self.mixer.all_tracks();
        let source_track_count = source_tracks.len();
        let source_duration = self.mixer.total_duration();
        let mut arranged = Vec::with_capacity(source_track_count);

        for (track_index, source_track) in source_tracks.into_iter().enumerate() {
            let event_capacity =
                midi_repeat_event_capacity(source_track.events.len(), self.repeat_times)?;
            let mut events = Vec::with_capacity(event_capacity);
            let should_expand_events =
                repeat_expansion_capacity(source_track.events.len(), self.repeat_times)? > 0;

            if should_expand_events {
                for repeat_index in 0..self.repeat_times {
                    let repeat_offset =
                        start_at + self.start_at + source_duration * repeat_index as f32;
                    for event in &source_track.events {
                        let mut event = event.clone();
                        offset_audio_event(&mut event, repeat_offset);
                        events.push(event);
                    }
                }
            }
            events.sort_by(|left, right| {
                left.start_time()
                    .partial_cmp(&right.start_time())
                    .unwrap_or(std::cmp::Ordering::Equal)
            });

            let mut track = Track::new();
            track.events = events;
            track.name =
                Some(self.arranged_track_name(default_name, track_index, source_track_count));
            track.midi_program = source_track.midi_program;
            track.volume = (source_track.volume * self.volume).clamp(0.0, 2.0);
            track.pan = source_track.pan;
            track.filter = source_track.filter;
            track.effects = source_track.effects.clone();
            track.modulation = source_track.modulation.clone();
            if let Some(pan) = self.pan {
                track.pan = pan;
            }
            for effect in &self.effects {
                effect.apply_to_track(&mut track);
            }
            arranged.push(track);
        }

        Ok(arranged)
    }

    fn arranged_track_name(
        &self,
        default_name: &str,
        track_index: usize,
        source_track_count: usize,
    ) -> String {
        let base_name = self
            .track_name
            .as_deref()
            .unwrap_or(default_name)
            .trim()
            .to_string();
        let base_name = if base_name.is_empty() {
            default_name.to_string()
        } else {
            base_name
        };

        if source_track_count == 1 {
            base_name
        } else {
            format!("{base_name}_{track_index}")
        }
    }
}

fn midi_repeat_event_capacity(event_count: usize, repeat_times: usize) -> PulseResult<usize> {
    let capacity = repeat_expansion_capacity(event_count, repeat_times)?;
    let max_events = isize::MAX as usize / std::mem::size_of::<AudioEvent>();
    if capacity > max_events {
        return Err(PulseError::InvalidRepeatTimes { repeat_times });
    }
    Ok(capacity)
}

fn repeat_expansion_capacity(item_count: usize, repeat_times: usize) -> PulseResult<usize> {
    let capacity = item_count
        .checked_mul(repeat_times)
        .ok_or(PulseError::InvalidRepeatTimes { repeat_times })?;
    if capacity > isize::MAX as usize {
        return Err(PulseError::InvalidRepeatTimes { repeat_times });
    }
    Ok(capacity)
}

fn repeated_timeline_duration(duration: f32, repeat_times: usize) -> PulseResult<f32> {
    if repeat_times == 0 {
        return Err(PulseError::InvalidRepeatTimes { repeat_times });
    }

    let repeated = duration * repeat_times as f32;
    if duration.is_finite() && repeated.is_finite() {
        Ok(repeated)
    } else {
        Err(PulseError::InvalidRepeatTimes { repeat_times })
    }
}

fn timeline_offset_duration(start_at: f32, duration: f32, repeat_times: usize) -> PulseResult<f32> {
    let total = start_at + duration;
    if start_at.is_finite() && duration.is_finite() && total.is_finite() {
        Ok(total)
    } else {
        Err(PulseError::InvalidRepeatTimes { repeat_times })
    }
}

fn offset_audio_event(event: &mut AudioEvent, offset: f32) {
    match event {
        AudioEvent::Note(note) => note.start_time += offset,
        AudioEvent::Drum(drum) => drum.start_time += offset,
        AudioEvent::Sample(sample) => sample.start_time += offset,
        AudioEvent::TempoChange(tempo) => tempo.start_time += offset,
        AudioEvent::TimeSignature(time_signature) => time_signature.start_time += offset,
        AudioEvent::KeySignature(key_signature) => key_signature.start_time += offset,
    }
}

fn validate_midi_clip_non_negative(option: &str, value: f32) -> PulseResult<()> {
    if value.is_finite() && value >= 0.0 {
        Ok(())
    } else {
        Err(invalid_midi_clip_option(option, value))
    }
}

fn validate_midi_clip_volume(value: f32) -> PulseResult<()> {
    if value.is_finite() && (0.0..=2.0).contains(&value) {
        Ok(())
    } else {
        Err(invalid_midi_clip_option("volume", value))
    }
}

fn validate_midi_clip_pan(value: f32) -> PulseResult<()> {
    if value.is_finite() && (-1.0..=1.0).contains(&value) {
        Ok(())
    } else {
        Err(invalid_midi_clip_option("pan", value))
    }
}

fn invalid_midi_clip_option(option: &str, value: f32) -> PulseError {
    PulseError::InvalidMidiClipOption {
        option: option.to_string(),
        value: value.to_string(),
    }
}

/// A reusable phrase containing layered sequences and drum grids.
#[derive(Debug, Clone, PartialEq)]
pub struct PulsePhrase {
    sequences: Vec<PulseSequence>,
    drum_grids: Vec<PulseDrumGrid>,
    sample_clips: Vec<PulseSampleClip>,
    midi_clips: Vec<PulseMidiClip>,
    repeat_times: usize,
}

impl Default for PulsePhrase {
    fn default() -> Self {
        Self::new()
    }
}

impl PulsePhrase {
    /// Creates an empty phrase that plays once.
    pub fn new() -> Self {
        Self {
            sequences: Vec::new(),
            drum_grids: Vec::new(),
            sample_clips: Vec::new(),
            midi_clips: Vec::new(),
            repeat_times: 1,
        }
    }

    /// Appends one melodic sequence to this phrase.
    #[must_use]
    pub fn add_sequence(mut self, sequence: PulseSequence) -> Self {
        self.sequences.push(sequence);
        self
    }

    /// Appends one drum grid to this phrase.
    #[must_use]
    pub fn add_drum_grid(mut self, grid: PulseDrumGrid) -> Self {
        self.drum_grids.push(grid);
        self
    }

    /// Appends one sample clip to this phrase.
    #[must_use]
    pub fn add_sample_clip(mut self, sample_clip: PulseSampleClip) -> Self {
        self.sample_clips.push(sample_clip);
        self
    }

    /// Appends one imported MIDI clip to this phrase.
    #[must_use]
    pub fn add_midi_clip(mut self, midi_clip: PulseMidiClip) -> Self {
        self.midi_clips.push(midi_clip);
        self
    }

    /// Sets how many total times the phrase should play.
    pub fn with_repeat_times(mut self, repeat_times: usize) -> PulseResult<Self> {
        if repeat_times == 0 {
            return Err(PulseError::InvalidRepeatTimes { repeat_times });
        }
        self.repeat_times = repeat_times;
        Ok(self)
    }

    /// Returns phrase duration for one play-through.
    pub fn duration(&self) -> PulseResult<f32> {
        let sequence_duration = self
            .sequences
            .iter()
            .map(PulseSequence::duration)
            .fold(0.0, f32::max);
        let drum_duration = self
            .drum_grids
            .iter()
            .map(PulseDrumGrid::duration)
            .fold(0.0, f32::max);
        let mut sample_duration = 0.0_f32;
        for sample_clip in &self.sample_clips {
            sample_duration = sample_duration.max(sample_clip.duration()?);
        }
        let mut midi_duration = 0.0_f32;
        for midi_clip in &self.midi_clips {
            midi_duration = midi_duration.max(midi_clip.duration()?);
        }
        Ok(sequence_duration
            .max(drum_duration)
            .max(sample_duration)
            .max(midi_duration))
    }

    /// Returns phrase duration including repeats.
    pub fn total_duration(&self) -> PulseResult<f32> {
        repeated_timeline_duration(self.duration()?, self.repeat_times)
    }

    /// Returns all melodic sequences.
    pub fn sequences(&self) -> &[PulseSequence] {
        &self.sequences
    }

    /// Returns all drum grids.
    pub fn drum_grids(&self) -> &[PulseDrumGrid] {
        &self.drum_grids
    }

    /// Returns all sample clips.
    pub fn sample_clips(&self) -> &[PulseSampleClip] {
        &self.sample_clips
    }

    /// Returns all imported MIDI clips.
    pub fn midi_clips(&self) -> &[PulseMidiClip] {
        &self.midi_clips
    }

    /// Returns how many total times this phrase plays.
    pub fn repeat_times(&self) -> usize {
        self.repeat_times
    }
}

/// A Lua-friendly song container that can be converted to `tunes`.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseSong {
    tempo: f32,
    sequences: Vec<PulseSequence>,
    drum_grids: Vec<PulseDrumGrid>,
    phrases: Vec<PulsePhrase>,
    sample_clips: Vec<PulseSampleClip>,
    midi_clips: Vec<PulseMidiClip>,
    master_effects: Vec<PulseEffect>,
}

impl Default for PulseSong {
    fn default() -> Self {
        Self::new()
    }
}

impl PulseSong {
    /// Creates an empty song at 120 BPM.
    pub fn new() -> Self {
        Self {
            tempo: 120.0,
            sequences: Vec::new(),
            drum_grids: Vec::new(),
            phrases: Vec::new(),
            sample_clips: Vec::new(),
            midi_clips: Vec::new(),
            master_effects: Vec::new(),
        }
    }

    /// Sets the song tempo in beats per minute.
    pub fn with_tempo(mut self, bpm: f32) -> PulseResult<Self> {
        if !bpm.is_finite() || bpm <= 0.0 {
            return Err(PulseError::InvalidTempo { bpm });
        }
        self.tempo = bpm;
        Ok(self)
    }

    /// Appends one sequence.
    #[must_use]
    pub fn add_sequence(mut self, sequence: PulseSequence) -> Self {
        self.sequences.push(sequence);
        self
    }

    /// Appends one drum grid.
    #[must_use]
    pub fn add_drum_grid(mut self, grid: PulseDrumGrid) -> Self {
        self.drum_grids.push(grid);
        self
    }

    /// Appends one reusable phrase to the song arrangement.
    #[must_use]
    pub fn add_phrase(mut self, phrase: PulsePhrase) -> Self {
        self.phrases.push(phrase);
        self
    }

    /// Appends one sample clip to the song.
    #[must_use]
    pub fn add_sample_clip(mut self, sample_clip: PulseSampleClip) -> Self {
        self.sample_clips.push(sample_clip);
        self
    }

    /// Appends one imported MIDI clip to the song.
    #[must_use]
    pub fn add_midi_clip(mut self, midi_clip: PulseMidiClip) -> Self {
        self.midi_clips.push(midi_clip);
        self
    }

    /// Appends a master effect to the song.
    #[must_use]
    pub fn with_master_effect(mut self, effect: PulseEffect) -> Self {
        self.master_effects.push(effect);
        self
    }

    /// Converts the wrapper DSL into a `tunes` composition.
    pub fn to_tunes_composition(&self) -> PulseResult<Composition> {
        let mut composition = Composition::new(Tempo::new(self.tempo));

        for (index, sequence) in self.sequences.iter().enumerate() {
            let track_name = format!("sequence_{index}");
            apply_sequence_to_composition(&mut composition, &track_name, sequence, 0.0)?;
        }

        for grid in &self.drum_grids {
            grid.apply_to_composition(&mut composition)?;
        }

        for (index, sample_clip) in self.sample_clips.iter().enumerate() {
            let track_name = format!("sample_{index}");
            apply_sample_clip_to_composition(&mut composition, &track_name, sample_clip, 0.0)?;
        }

        let mut phrase_start = 0.0;
        for (phrase_index, phrase) in self.phrases.iter().enumerate() {
            let phrase_duration = phrase.duration()?;
            let repeat_times = phrase.repeat_times();
            let phrase_total_duration = repeated_timeline_duration(phrase_duration, repeat_times)?;
            let arrangement_count =
                phrase.sequences().len() + phrase.drum_grids().len() + phrase.sample_clips().len();
            let should_expand_phrase =
                repeat_expansion_capacity(arrangement_count, repeat_times)? > 0;

            if should_expand_phrase {
                for repeat_index in 0..repeat_times {
                    let repeat_start = phrase_start + phrase_duration * repeat_index as f32;

                    for (sequence_index, sequence) in phrase.sequences().iter().enumerate() {
                        let track_name = format!("phrase_{phrase_index}_sequence_{sequence_index}");
                        apply_sequence_to_composition(
                            &mut composition,
                            &track_name,
                            sequence,
                            repeat_start,
                        )?;
                    }

                    for grid in phrase.drum_grids() {
                        grid.apply_to_composition_at(&mut composition, repeat_start)?;
                    }

                    for (sample_index, sample_clip) in phrase.sample_clips().iter().enumerate() {
                        let track_name = format!("phrase_{phrase_index}_sample_{sample_index}");
                        apply_sample_clip_to_composition(
                            &mut composition,
                            &track_name,
                            sample_clip,
                            repeat_start,
                        )?;
                    }
                }
            }
            phrase_start =
                timeline_offset_duration(phrase_start, phrase_total_duration, repeat_times)?;
        }

        Ok(composition)
    }

    /// Converts the wrapper DSL into a `tunes` mixer and applies master effects.
    pub fn to_mixer(&self) -> PulseResult<Mixer> {
        let mut mixer = self.to_arranged_mixer()?;
        for effect in &self.master_effects {
            effect.apply_to_master(&mut mixer)?;
        }
        Ok(mixer)
    }

    /// Converts the wrapper DSL into a `tunes` mixer without applying master effects.
    pub(crate) fn to_arranged_mixer(&self) -> PulseResult<Mixer> {
        let mut mixer = self.to_tunes_composition()?.into_mixer();
        self.apply_midi_clips_to_mixer(&mut mixer)?;
        Ok(mixer)
    }

    fn apply_midi_clips_to_mixer(&self, mixer: &mut Mixer) -> PulseResult<()> {
        let mut next_track_id = next_mixer_track_id(mixer);

        for (index, midi_clip) in self.midi_clips.iter().enumerate() {
            append_midi_clip_to_mixer(
                mixer,
                midi_clip,
                0.0,
                &format!("midi_{index}"),
                &mut next_track_id,
            )?;
        }

        let mut phrase_start = 0.0;
        for (phrase_index, phrase) in self.phrases.iter().enumerate() {
            let phrase_duration = phrase.duration()?;
            let repeat_times = phrase.repeat_times();
            let phrase_total_duration = repeated_timeline_duration(phrase_duration, repeat_times)?;
            let should_expand_midi =
                repeat_expansion_capacity(phrase.midi_clips().len(), repeat_times)? > 0;

            if should_expand_midi {
                for repeat_index in 0..repeat_times {
                    let repeat_start = phrase_start + phrase_duration * repeat_index as f32;
                    for (midi_index, midi_clip) in phrase.midi_clips().iter().enumerate() {
                        append_midi_clip_to_mixer(
                            mixer,
                            midi_clip,
                            repeat_start,
                            &format!("phrase_{phrase_index}_midi_{midi_index}"),
                            &mut next_track_id,
                        )?;
                    }
                }
            }
            phrase_start =
                timeline_offset_duration(phrase_start, phrase_total_duration, repeat_times)?;
        }

        Ok(())
    }

    /// Returns the song tempo in beats per minute.
    pub fn tempo(&self) -> f32 {
        self.tempo
    }

    /// Returns all sequences.
    pub fn sequences(&self) -> &[PulseSequence] {
        &self.sequences
    }

    /// Returns all drum grids.
    pub fn drum_grids(&self) -> &[PulseDrumGrid] {
        &self.drum_grids
    }

    /// Returns all phrases.
    pub fn phrases(&self) -> &[PulsePhrase] {
        &self.phrases
    }

    /// Returns all sample clips.
    pub fn sample_clips(&self) -> &[PulseSampleClip] {
        &self.sample_clips
    }

    /// Returns all imported MIDI clips.
    pub fn midi_clips(&self) -> &[PulseMidiClip] {
        &self.midi_clips
    }

    /// Returns master effects in insertion order.
    pub fn master_effects(&self) -> &[PulseEffect] {
        &self.master_effects
    }
}

fn apply_sequence_to_composition(
    composition: &mut Composition,
    track_name: &str,
    sequence: &PulseSequence,
    start_at: f32,
) -> PulseResult<()> {
    sequence.validate()?;
    let instrument = instrument_by_name(sequence.instrument())?;
    let mut builder = composition
        .instrument(track_name, &instrument)
        .at(start_at + sequence.start_at())
        .volume(sequence.volume())
        .pan(sequence.pan())
        .velocity(sequence.velocity());
    let events = sequence.events()?;

    match sequence.synth() {
        Some(PulseSynth::KarplusStrong(synth)) => {
            for event in &events {
                let sample = synth.to_sample(event.frequencies()[0], event.duration(), 44_100)?;
                builder = builder.play_sample(&sample, 1.0);
            }
        }
        Some(PulseSynth::Granular(synth)) => {
            tunes::synthesis::sample::Sample::from_file(&synth.source).map_err(|error| {
                PulseError::InvalidSynthOption {
                    synth: "granular".to_string(),
                    option: "source".to_string(),
                    value: error.to_string(),
                }
            })?;
            builder = builder.granular(&synth.source, synth.params.clone(), synth.duration);
        }
        synth => {
            if let Some(synth) = synth {
                builder = synth.apply_to_track_builder(builder);
            }

            for event in &events {
                builder = builder.note(event.frequencies(), event.duration());
            }
        }
    }

    for effect in sequence.effects() {
        builder = effect.apply_to_track_builder(builder);
    }
    let _ = builder;

    Ok(())
}

fn append_midi_clip_to_mixer(
    mixer: &mut Mixer,
    midi_clip: &PulseMidiClip,
    start_at: f32,
    default_name: &str,
    next_track_id: &mut u32,
) -> PulseResult<()> {
    for mut track in midi_clip.arranged_tracks(start_at, default_name)? {
        track.id = *next_track_id;
        *next_track_id = (*next_track_id).saturating_add(1);
        track.bus_id = 0;
        mixer.add_track(track);
    }
    Ok(())
}

fn next_mixer_track_id(mixer: &Mixer) -> u32 {
    mixer
        .all_tracks()
        .into_iter()
        .map(|track| track.id)
        .max()
        .unwrap_or(0)
        .saturating_add(1)
}

fn apply_sample_clip_to_composition(
    composition: &mut Composition,
    track_name: &str,
    sample_clip: &PulseSampleClip,
    start_at: f32,
) -> PulseResult<()> {
    let sample = sample_clip.transformed_sample()?;
    let effective_track_name = sample_clip.track_name().unwrap_or(track_name);
    let mut builder = composition
        .track(effective_track_name)
        .at(start_at + sample_clip.start_at())
        .volume(sample_clip.volume())
        .pan(sample_clip.pan())
        .play_sample(&sample, sample_clip.playback_rate());
    for effect in sample_clip.effects() {
        builder = effect.apply_to_track_builder(builder);
    }
    let _ = builder;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theory::parse_note_frequency;
    use tunes::track::AudioEvent;

    fn test_delay_effect() -> crate::effects::PulseEffect {
        crate::effects::effect_from_options("delay", crate::effects::EffectOptions::Default)
            .expect("default delay should parse")
    }

    fn test_eq_effect() -> crate::effects::PulseEffect {
        crate::effects::effect_from_options("eq", crate::effects::EffectOptions::Default)
            .expect("default eq should parse")
    }

    fn test_filter_effect() -> crate::effects::PulseEffect {
        crate::effects::effect_from_options("filter", crate::effects::EffectOptions::Default)
            .expect("default filter should parse")
    }

    #[test]
    fn sequence_validates_duration_count_and_positive_values() {
        let c4 = parse_note_frequency("C4").unwrap();
        let sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.5])
            .with_instrument("electric_piano");

        assert!(sequence.validate().is_ok());

        let mismatch = PulseSequence::new()
            .with_notes(vec![c4, c4])
            .with_durations(vec![0.5])
            .with_instrument("electric_piano");
        assert_eq!(
            mismatch
                .validate()
                .expect_err("mismatch should fail")
                .to_string(),
            "duration count mismatch: 2 notes and 1 durations"
        );

        let invalid_duration = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.0])
            .with_instrument("electric_piano");
        assert_eq!(
            invalid_duration
                .validate()
                .expect_err("zero duration should fail")
                .to_string(),
            "invalid duration: 0"
        );
    }

    #[test]
    fn sequence_transposes_without_mutating_original() {
        let c4 = parse_note_frequency("C4").unwrap();
        let sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.5])
            .with_instrument("electric_piano");

        let transposed = sequence.transposed(12);

        assert!(transposed.notes()[0] > sequence.notes()[0] * 1.99);
        assert!(sequence.notes()[0] < transposed.notes()[0]);
    }

    #[test]
    fn sequence_can_render_polyphonic_chords_with_mix_controls() {
        let c4 = parse_note_frequency("C4").unwrap();
        let e4 = parse_note_frequency("E4").unwrap();
        let g4 = parse_note_frequency("G4").unwrap();
        let f4 = parse_note_frequency("F4").unwrap();
        let a4 = parse_note_frequency("A4").unwrap();
        let c5 = parse_note_frequency("C5").unwrap();

        let sequence = PulseSequence::new()
            .with_chords(vec![vec![c4, e4, g4], vec![f4, a4, c5]])
            .with_durations(vec![0.5, 0.5])
            .with_instrument("electric_piano")
            .with_start_at(0.25)
            .unwrap()
            .with_volume(0.7)
            .unwrap()
            .with_pan(-0.25)
            .unwrap()
            .with_velocity(0.6)
            .unwrap();

        let mixer = PulseSong::new().add_sequence(sequence).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].volume, 0.7);
        assert_eq!(tracks[0].pan, -0.25);

        let AudioEvent::Note(note) = &tracks[0].events[0] else {
            panic!("expected note event");
        };

        assert_eq!(note.start_time, 0.25);
        assert_eq!(note.duration, 0.5);
        assert_eq!(note.num_freqs, 3);
        assert_eq!(note.frequencies[0], c4);
        assert_eq!(note.frequencies[1], e4);
        assert_eq!(note.frequencies[2], g4);
        assert_eq!(note.velocity, 0.6);
    }

    #[test]
    fn song_rejects_invalid_tempo() {
        let error = PulseSong::new()
            .with_tempo(0.0)
            .expect_err("zero tempo should fail");

        assert_eq!(error.to_string(), "invalid tempo: 0");
    }

    #[test]
    fn song_converts_valid_sequence_to_tunes_composition() {
        let c4 = parse_note_frequency("C4").unwrap();
        let sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.25])
            .with_instrument("electric_piano");

        let song = PulseSong::new()
            .with_tempo(120.0)
            .unwrap()
            .add_sequence(sequence);

        let composition = song.to_tunes_composition();
        assert!(composition.is_ok());
    }

    #[test]
    fn song_converts_drum_grid_to_tunes_composition() {
        let drum_grid = crate::drums::PulseDrumGrid::new()
            .with_steps(16)
            .unwrap()
            .with_step_duration(0.125)
            .unwrap()
            .sound("kick_808", vec![0, 4, 8, 12])
            .unwrap();

        let song = PulseSong::new().add_drum_grid(drum_grid);

        assert!(song.to_tunes_composition().is_ok());
        assert_eq!(song.drum_grids().len(), 1);
    }

    #[test]
    fn phrase_repeats_sequences_and_drums_on_the_song_timeline() {
        let c4 = parse_note_frequency("C4").unwrap();
        let sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.25])
            .with_instrument("electric_piano");
        let drum_grid = crate::drums::PulseDrumGrid::new()
            .with_steps(4)
            .unwrap()
            .with_step_duration(0.25)
            .unwrap()
            .sound("kick_808", vec![0])
            .unwrap();

        let phrase = PulsePhrase::new()
            .add_sequence(sequence)
            .add_drum_grid(drum_grid)
            .with_repeat_times(2)
            .unwrap();

        assert_eq!(phrase.repeat_times(), 2);
        assert_eq!(phrase.duration().unwrap(), 1.0);

        let mixer = PulseSong::new().add_phrase(phrase).to_mixer().unwrap();
        let mut note_times = Vec::new();
        let mut drum_times = Vec::new();

        for track in mixer.all_tracks() {
            for event in &track.events {
                match event {
                    AudioEvent::Note(note) => note_times.push(note.start_time),
                    AudioEvent::Drum(drum) => drum_times.push(drum.start_time),
                    _ => {}
                }
            }
        }

        note_times.sort_by(|left, right| left.partial_cmp(right).unwrap());
        drum_times.sort_by(|left, right| left.partial_cmp(right).unwrap());

        assert_eq!(note_times, vec![0.0, 1.0]);
        assert_eq!(drum_times, vec![0.0, 1.0]);
    }

    #[test]
    fn sequence_stores_and_applies_track_effects() {
        let c4 = parse_note_frequency("C4").unwrap();
        let sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.25])
            .with_instrument("electric_piano")
            .with_effect(test_delay_effect())
            .with_effect(test_filter_effect());

        assert_eq!(sequence.effects().len(), 2);

        let mixer = PulseSong::new().add_sequence(sequence).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        assert_eq!(tracks.len(), 1);
        assert!(tracks[0].effects.delay.is_some());
        assert!(matches!(
            tracks[0].filter.filter_type,
            tunes::synthesis::filter::FilterType::LowPass
        ));
    }

    #[test]
    fn song_stores_and_applies_master_effects() {
        let song = PulseSong::new().with_master_effect(test_eq_effect());

        assert_eq!(song.master_effects().len(), 1);

        let mixer = song.to_mixer().expect("song with master eq should build");
        assert!(mixer.master.eq.is_some());
    }

    #[test]
    fn song_rejects_track_only_filter_on_master() {
        let error = PulseSong::new()
            .with_master_effect(test_filter_effect())
            .to_mixer()
            .expect_err("filter is not a master effect");

        assert_eq!(error.to_string(), "invalid effect scope filter: master");
    }

    #[test]
    fn sequence_applies_fm_synth_to_exported_notes() {
        let c4 = parse_note_frequency("C4").unwrap();
        let synth = crate::synthesis::synth_from_options(
            "fm",
            crate::synthesis::SynthOptions::Preset("bell".to_string()),
        )
        .expect("fm bell preset should parse");
        let sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.25])
            .with_instrument("electric_piano")
            .with_synth(synth);

        assert_eq!(
            sequence.synth().map(crate::synthesis::PulseSynth::name),
            Some("fm")
        );

        let mixer = PulseSong::new().add_sequence(sequence).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        assert_eq!(tracks.len(), 1);

        let AudioEvent::Note(note) = &tracks[0].events[0] else {
            panic!("expected note event");
        };
        assert_eq!(
            note.fm_params.mod_index,
            tunes::synthesis::fm_synthesis::FMParams::bell().mod_index
        );
    }

    #[test]
    fn sequence_applies_additive_and_wavetable_synths_to_exported_notes() {
        let c4 = parse_note_frequency("C4").unwrap();
        let additive = crate::synthesis::synth_from_options(
            "additive",
            crate::synthesis::SynthOptions::Harmonics(vec![1.0, 0.5, 0.25]),
        )
        .expect("additive harmonics should parse");
        let wavetable = crate::synthesis::synth_from_options(
            "wavetable",
            crate::synthesis::SynthOptions::Default,
        )
        .expect("wavetable should parse");

        let additive_sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.25])
            .with_instrument("electric_piano")
            .with_synth(additive);
        let wavetable_sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.25])
            .with_instrument("electric_piano")
            .with_synth(wavetable);

        let mixer = PulseSong::new()
            .add_sequence(additive_sequence)
            .add_sequence(wavetable_sequence)
            .to_mixer()
            .unwrap();
        let tracks = mixer.all_tracks();
        assert_eq!(tracks.len(), 2);

        for track in tracks {
            let AudioEvent::Note(note) = &track.events[0] else {
                panic!("expected note event");
            };
            assert!(note.custom_wavetable.is_some());
        }
    }

    #[test]
    fn sequence_renders_karplus_strong_synth_as_sample_events() {
        let c4 = parse_note_frequency("C4").unwrap();
        let synth = crate::synthesis::synth_from_options(
            "karplus_strong",
            crate::synthesis::SynthOptions::Default,
        )
        .expect("karplus-strong should parse");
        let sequence = PulseSequence::new()
            .with_notes(vec![c4])
            .with_durations(vec![0.25])
            .with_instrument("electric_piano")
            .with_synth(synth);

        assert_eq!(
            sequence.synth().map(crate::synthesis::PulseSynth::name),
            Some("karplus_strong")
        );

        let mixer = PulseSong::new().add_sequence(sequence).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        assert_eq!(tracks.len(), 1);

        let AudioEvent::Sample(sample) = &tracks[0].events[0] else {
            panic!("expected karplus-strong sample event");
        };
        assert_eq!(sample.start_time, 0.0);
        assert_eq!(sample.sample.sample_rate, 44_100);
        assert!((sample.sample.duration - 0.25).abs() < 0.001);
    }

    #[test]
    fn midi_clip_rejects_unrenderable_repeat_expansion() {
        let c4 = parse_note_frequency("C4").unwrap();
        let source_mixer = PulseSong::new()
            .add_sequence(
                PulseSequence::new()
                    .with_notes(vec![c4])
                    .with_durations(vec![0.25])
                    .with_instrument("electric_piano"),
            )
            .to_mixer()
            .unwrap();
        let clip = PulseMidiClip::new(source_mixer)
            .with_repeat_times(usize::MAX)
            .unwrap();

        let error = clip
            .arranged_tracks(0.0, "midi")
            .expect_err("unrenderable repeat expansion should return an error");

        assert!(matches!(error, PulseError::InvalidRepeatTimes { .. }));
    }

    #[test]
    fn granular_sequence_duration_uses_output_duration_for_phrase_timing() {
        let synth = crate::synthesis::synth_from_options(
            "granular",
            crate::synthesis::SynthOptions::Params(std::collections::BTreeMap::from([
                (
                    "source".to_string(),
                    crate::synthesis::SynthOption::Text("source.wav".to_string()),
                ),
                (
                    "duration".to_string(),
                    crate::synthesis::SynthOption::Number(0.75),
                ),
            ])),
        )
        .expect("granular should parse");
        let sequence = PulseSequence::new().with_synth(synth);
        let phrase = PulsePhrase::new()
            .add_sequence(sequence)
            .with_repeat_times(2)
            .unwrap();

        assert_eq!(phrase.duration().unwrap(), 0.75);
        assert_eq!(phrase.total_duration().unwrap(), 1.5);
    }

    #[test]
    fn phrase_rejects_unrenderable_repeat_expansion_before_looping() {
        let c4 = parse_note_frequency("C4").unwrap();
        let phrase = PulsePhrase::new()
            .add_sequence(
                PulseSequence::new()
                    .with_notes(vec![c4])
                    .with_durations(vec![0.25])
                    .with_instrument("electric_piano"),
            )
            .with_repeat_times(usize::MAX)
            .unwrap();

        let error = match PulseSong::new().add_phrase(phrase).to_tunes_composition() {
            Ok(_) => panic!("unrenderable phrase repeat expansion should return an error"),
            Err(error) => error,
        };

        assert!(matches!(error, PulseError::InvalidRepeatTimes { .. }));
    }

    #[test]
    fn song_converts_sample_clips_to_sample_events() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 4_410], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_pitch_shift(12.0)
            .unwrap()
            .with_time_stretch(1.5)
            .unwrap()
            .with_playback_rate(0.5)
            .unwrap();

        let mixer = PulseSong::new().add_sample_clip(clip).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        assert_eq!(tracks.len(), 1);

        let AudioEvent::Sample(sample) = &tracks[0].events[0] else {
            panic!("expected sample event");
        };
        assert_eq!(sample.start_time, 0.0);
        assert_eq!(sample.playback_rate, 0.5);
        assert!(sample.sample.duration > 0.1);
    }

    #[test]
    fn sample_clip_applies_track_name_volume_pan_and_effects() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("mix-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25, 0.5, 0.25, -0.25], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_track("loop_bus")
            .with_volume(0.42)
            .unwrap()
            .with_pan(-0.25)
            .unwrap()
            .with_effect(test_delay_effect());

        let mixer = PulseSong::new().add_sample_clip(clip).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].name.as_deref(), Some("loop_bus"));
        assert!((tracks[0].volume - 0.42).abs() < f32::EPSILON);
        assert!((tracks[0].pan + 0.25).abs() < f32::EPSILON);
        assert!(tracks[0].effects.delay.is_some());
    }

    #[test]
    fn sample_clip_rejects_invalid_track_volume_and_pan() {
        assert!(PulseSampleClip::new("source.wav")
            .with_volume(-0.01)
            .is_err());
        assert!(PulseSampleClip::new("source.wav")
            .with_volume(2.01)
            .is_err());
        assert!(PulseSampleClip::new("source.wav").with_pan(-1.01).is_err());
        assert!(PulseSampleClip::new("source.wav").with_pan(1.01).is_err());
    }

    #[test]
    fn phrase_repeats_sample_clips_on_the_song_timeline() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("phrase-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 4_410], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref());
        let phrase = PulsePhrase::new()
            .add_sample_clip(clip)
            .with_repeat_times(2)
            .unwrap();

        assert!((phrase.duration().unwrap() - 0.1).abs() < 0.001);
        assert!((phrase.total_duration().unwrap() - 0.2).abs() < 0.001);

        let mixer = PulseSong::new().add_phrase(phrase).to_mixer().unwrap();
        let mut sample_times = Vec::new();

        for track in mixer.all_tracks() {
            for event in &track.events {
                if let AudioEvent::Sample(sample) = event {
                    sample_times.push(sample.start_time);
                }
            }
        }

        sample_times.sort_by(|left, right| left.partial_cmp(right).unwrap());
        assert_eq!(sample_times, vec![0.0, 0.1]);
    }

    #[test]
    fn sample_clip_offset_places_song_and_phrase_events_on_the_timeline() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("offset-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 4_410], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let song_clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_start_at(0.25)
            .unwrap();
        let phrase_clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_start_at(0.5)
            .unwrap();
        let phrase = PulsePhrase::new()
            .add_sample_clip(phrase_clip)
            .with_repeat_times(2)
            .unwrap();

        let mixer = PulseSong::new()
            .add_sample_clip(song_clip)
            .add_phrase(phrase)
            .to_mixer()
            .unwrap();
        let mut sample_times = Vec::new();

        for track in mixer.all_tracks() {
            for event in &track.events {
                if let AudioEvent::Sample(sample) = event {
                    sample_times.push(sample.start_time);
                }
            }
        }

        sample_times.sort_by(|left, right| left.partial_cmp(right).unwrap());
        assert_eq!(sample_times, vec![0.25, 0.5, 1.1]);
    }

    #[test]
    fn sample_clip_slice_uses_only_the_selected_source_range() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("slice-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 44_100], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_slice(0.25, 0.5)
            .unwrap()
            .with_start_at(0.125)
            .unwrap();

        assert!((clip.duration().unwrap() - 0.375).abs() < 0.01);

        let mixer = PulseSong::new().add_sample_clip(clip).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        let AudioEvent::Sample(sample) = &tracks[0].events[0] else {
            panic!("expected sliced sample event");
        };

        assert_eq!(sample.start_time, 0.125);
        assert!((sample.sample.duration - 0.25).abs() < 0.01);
    }

    #[test]
    fn sample_clip_fade_in_and_out_shape_exported_sample_edges() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("fade-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![1.0; 44_100], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_slice(0.0, 0.25)
            .unwrap()
            .with_fade_in(0.05)
            .unwrap()
            .with_fade_out(0.05)
            .unwrap();

        let mixer = PulseSong::new().add_sample_clip(clip).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        let AudioEvent::Sample(sample) = &tracks[0].events[0] else {
            panic!("expected faded sample event");
        };

        let first = sample.sample.data[0];
        let middle = sample.sample.data[sample.sample.data.len() / 2];
        let last = *sample
            .sample
            .data
            .last()
            .expect("sample should not be empty");

        assert!(first.abs() < 0.001);
        assert!(middle > 0.9);
        assert!(last.abs() < 0.01);
    }

    #[test]
    fn sample_clip_reverse_flips_the_selected_source_range() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("reverse-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.1, 0.2, 0.8, 1.0], 4)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_slice(0.0, 0.75)
            .unwrap()
            .with_reverse();

        let mixer = PulseSong::new().add_sample_clip(clip).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        let AudioEvent::Sample(sample) = &tracks[0].events[0] else {
            panic!("expected reversed sample event");
        };

        assert_eq!(sample.sample.data.len(), 3);
        assert!((sample.sample.data[0] - 0.8).abs() < 0.01);
        assert!((sample.sample.data[1] - 0.2).abs() < 0.01);
        assert!((sample.sample.data[2] - 0.1).abs() < 0.01);
    }

    #[test]
    fn sample_clip_loop_for_expands_source_to_requested_duration() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("loop-for-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.1, 0.2], 4)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_loop_for(1.25)
            .unwrap();

        assert!((clip.duration().unwrap() - 1.25).abs() < 0.01);

        let mixer = PulseSong::new().add_sample_clip(clip).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        let AudioEvent::Sample(sample) = &tracks[0].events[0] else {
            panic!("expected looped sample event");
        };

        assert!((sample.sample.duration - 1.25).abs() < 0.01);
        assert_eq!(sample.sample.data.len(), 5);
        assert!((sample.sample.data[0] - 0.1).abs() < 0.01);
        assert!((sample.sample.data[1] - 0.2).abs() < 0.01);
        assert!((sample.sample.data[2] - 0.1).abs() < 0.01);
        assert!((sample.sample.data[3] - 0.2).abs() < 0.01);
        assert!((sample.sample.data[4] - 0.1).abs() < 0.01);
    }

    #[test]
    fn sample_clip_loop_for_rejects_unrenderable_durations() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("huge-loop-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.1, 0.2], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_loop_for(f32::MAX)
            .unwrap();

        let error = PulseSong::new()
            .add_sample_clip(clip)
            .to_mixer()
            .expect_err("unrenderable loop duration should return an error");

        assert!(matches!(
            error,
            PulseError::InvalidSampleOption { ref option, .. } if option == "loop_for"
        ));
    }

    #[test]
    fn sample_frame_count_rejects_vec_capacity_overflow() {
        let sample_rate = 44_100;
        let max_vec_frames = isize::MAX as usize / std::mem::size_of::<f32>();
        let duration = (max_vec_frames as f32 / sample_rate as f32) * 2.0;

        let error = sample_frame_count("loop_for", duration, sample_rate)
            .expect_err("frame count should reject Vec capacity overflow");

        assert!(matches!(
            error,
            PulseError::InvalidSampleOption { ref option, .. } if option == "loop_for"
        ));
    }

    #[test]
    fn sample_clip_duration_accounts_for_loop_stretch_and_playback_rate() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("duration-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 44_100], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_start_at(0.25)
            .unwrap()
            .with_slice(0.1, 0.6)
            .unwrap()
            .with_loop_for(0.75)
            .unwrap()
            .with_time_stretch(2.0)
            .unwrap()
            .with_playback_rate(0.5)
            .unwrap();

        assert!((clip.duration().unwrap() - 3.25).abs() < 0.001);
    }

    #[test]
    fn sample_clip_metadata_duration_matches_public_duration_for_wav_transforms() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("metadata-duration.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 22_050], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_start_at(0.125)
            .unwrap()
            .with_slice(0.1, 0.4)
            .unwrap()
            .with_time_stretch(1.5)
            .unwrap()
            .with_playback_rate(0.75)
            .unwrap()
            .with_pitch_shift(12.0)
            .unwrap()
            .with_reverse()
            .with_normalize()
            .with_fade_in(0.01)
            .unwrap()
            .with_fade_out(0.02)
            .unwrap()
            .with_gain(0.8)
            .unwrap();

        let metadata_duration = clip.metadata_duration().unwrap();
        let public_duration = clip.duration().unwrap();

        assert!((metadata_duration - public_duration).abs() < 0.01);
        assert!((metadata_duration - 0.725).abs() < 0.01);
    }

    #[test]
    fn sample_clip_duration_matches_rendered_sample_for_subtle_time_stretch() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("subtle-stretch.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 441_000], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        // time_stretch in the [0.001, 0.01) band: metadata_duration used a
        // different threshold than transformed_sample, so they disagreed.
        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_time_stretch(1.009)
            .unwrap();

        let rendered_duration = clip
            .transformed_sample()
            .expect("sample should transform")
            .duration
            / clip.playback_rate();
        let metadata_duration = clip.metadata_duration().unwrap();

        assert!(
            (rendered_duration - metadata_duration).abs() < 0.01,
            "metadata duration {metadata_duration} must match rendered duration {rendered_duration} for subtle time_stretch"
        );
    }

    #[test]
    fn sample_clip_duration_rejects_slice_beyond_wav_duration() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("short-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.25; 4_410], 44_100)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_slice(0.0, 0.2)
            .unwrap();

        assert!(clip.duration().is_err());
    }

    #[test]
    fn sample_clip_normalize_scales_source_peak_before_gain() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let source = temp_dir.path().join("normalize-sample.wav");
        tunes::synthesis::sample::Sample::from_mono(vec![0.1, -0.25, 0.5], 3)
            .export_wav(&source)
            .expect("test sample should be written");

        let clip = PulseSampleClip::new(source.to_string_lossy().as_ref())
            .with_normalize()
            .with_gain(0.5)
            .unwrap();

        let mixer = PulseSong::new().add_sample_clip(clip).to_mixer().unwrap();
        let tracks = mixer.all_tracks();
        let AudioEvent::Sample(sample) = &tracks[0].events[0] else {
            panic!("expected normalized sample event");
        };

        let peak = sample
            .sample
            .data
            .iter()
            .fold(0.0_f32, |current, value| current.max(value.abs()));
        assert!((peak - 0.5).abs() < 0.01);
    }
}