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
use crate::composition::TrackBuilder;
use rand::Rng;
use std::f32::consts::PI;
impl<'a> TrackBuilder<'a> {
/// Add a sequence of chords with equal duration starting at the current cursor position
pub fn chords(mut self, chord_sequence: &[&[f32]], chord_duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
for chord in chord_sequence {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
chord,
cursor,
chord_duration,
waveform,
envelope,
pitch_bend,
);
// Store this chord for voice leading
self.last_chord = Some(chord.to_vec());
let swung_duration = self.apply_swing(chord_duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Play a chord progression using scale degrees with triads
///
/// This is a convenient one-liner for creating and playing chord progressions.
/// Combines `progression()` and `.chords_from()` into a single method call.
///
/// # Arguments
/// * `root` - The root note frequency (e.g., C4, G3)
/// * `scale_pattern` - The scale to build chords from (e.g., ScalePattern::MAJOR)
/// * `degrees` - Scale degrees to play (e.g., &[1, 5, 6, 4] for I-V-vi-IV)
/// * `chord_duration` - How long to play each chord
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::theory::core::ScalePattern;
///
/// // Play a classic pop progression: I-V-vi-IV in C major
/// comp.instrument("chords", &Instrument::warm_pad())
/// .progression(C4, &ScalePattern::MAJOR, &[1, 5, 6, 4], 1.5);
/// ```
pub fn progression(
self,
root: f32,
scale_pattern: &crate::theory::core::ScalePattern,
degrees: &[usize],
chord_duration: f32,
) -> Self {
let prog = crate::theory::core::progression(
root,
scale_pattern,
degrees,
crate::theory::core::ProgressionType::Triads,
);
self.chords_from(&prog, chord_duration)
}
/// Play a chord progression using scale degrees with 7th chords
///
/// Same as `.progression()` but uses 7th chords instead of triads for a jazzier sound.
///
/// # Arguments
/// * `root` - The root note frequency (e.g., C4, G3)
/// * `scale_pattern` - The scale to build chords from (e.g., ScalePattern::MAJOR)
/// * `degrees` - Scale degrees to play (e.g., &[2, 5, 1] for ii-V-I)
/// * `chord_duration` - How long to play each chord
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::theory::core::ScalePattern;
///
/// // Play a jazz progression: ii7-V7-Imaj7 in C major
/// comp.instrument("jazz", &Instrument::electric_piano())
/// .progression_7th(C4, &ScalePattern::MAJOR, &[2, 5, 1], 2.0);
/// ```
pub fn progression_7th(
self,
root: f32,
scale_pattern: &crate::theory::core::ScalePattern,
degrees: &[usize],
chord_duration: f32,
) -> Self {
let prog = crate::theory::core::progression(
root,
scale_pattern,
degrees,
crate::theory::core::ProgressionType::Sevenths,
);
self.chords_from(&prog, chord_duration)
}
/// Add a sequence of chords from Vec format (e.g. from progression()) with equal duration
///
/// This is a convenience method for playing chord progressions generated by theory::progression()
/// which returns Vec<Vec<f32>> instead of &[&[f32]].
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::theory::core::{progression, ScalePattern, ProgressionType};
/// use tunes::consts::notes::C4;
///
/// let pop_prog = progression(C4, &ScalePattern::MAJOR, &[1, 5, 6, 4], ProgressionType::Triads);
/// comp.instrument("chords", &Instrument::warm_pad())
/// .chords_from(&pop_prog, 1.5); // I-V-vi-IV progression
/// ```
pub fn chords_from(mut self, chord_vecs: &[Vec<f32>], chord_duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
for chord in chord_vecs {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
chord.as_slice(),
cursor,
chord_duration,
waveform,
envelope,
pitch_bend,
);
// Store this chord for voice leading
self.last_chord = Some(chord.clone());
let swung_duration = self.apply_swing(chord_duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Play a scale upward (ascending)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::scales::C4_MAJOR_SCALE;
/// comp.instrument("run", &Instrument::pluck())
/// .scale(&C4_MAJOR_SCALE, 0.1); // Plays C4, D4, E4, F4, G4, A4, B4, C5
/// ```
pub fn scale(self, scale: &[f32], note_duration: f32) -> Self {
self.notes(scale, note_duration)
}
/// Play a scale downward (descending)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::scales::C4_MAJOR_SCALE;
/// comp.instrument("run", &Instrument::pluck())
/// .scale_reverse(&C4_MAJOR_SCALE, 0.1); // Plays C5, B4, A4, G4, F4, E4, D4, C4
/// ```
pub fn scale_reverse(mut self, scale: &[f32], note_duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Play the scale in reverse order
for &freq in scale.iter().rev() {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Play a scale up then down without doubling the peak note
///
/// Unlike calling scale() then scale_reverse(), this avoids repeating
/// the highest note, creating a smooth melodic contour.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::scales::C4_MAJOR_SCALE;
/// comp.instrument("run", &Instrument::pluck())
/// .scale_updown(&C4_MAJOR_SCALE, 0.1); // Plays C4, D4, E4, F4, G4, F4, E4, D4, C4
/// ```
pub fn scale_updown(mut self, scale: &[f32], note_duration: f32) -> Self {
if scale.is_empty() {
return self;
}
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Play ascending
for &freq in scale.iter() {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
// Play descending, skipping the first note (which was the peak)
for &freq in scale.iter().rev().skip(1) {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Play a scale down then up without doubling the bottom note
///
/// The reverse of scale_updown(), starting from the top and avoiding
/// repetition at the bottom.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::scales::C4_MAJOR_SCALE;
/// comp.instrument("run", &Instrument::pluck())
/// .scale_downup(&C4_MAJOR_SCALE, 0.1); // Plays G4, F4, E4, D4, C4, D4, E4, F4, G4
/// ```
pub fn scale_downup(mut self, scale: &[f32], note_duration: f32) -> Self {
if scale.is_empty() {
return self;
}
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Play descending
for &freq in scale.iter().rev() {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
// Play ascending, skipping the first note (which was the bottom)
for &freq in scale.iter().skip(1) {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Play a chord as an ascending arpeggio
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::chords::C4_MAJOR;
/// comp.instrument("arp", &Instrument::pluck())
/// .arpeggiate(C4_MAJOR, 0.125); // Plays C4, E4, G4 sequentially
/// ```
pub fn arpeggiate(self, chord: &[f32], note_duration: f32) -> Self {
self.notes(chord, note_duration)
}
/// Play a chord as a descending arpeggio
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::chords::C4_MAJOR;
/// comp.instrument("arp", &Instrument::pluck())
/// .arpeggiate_reverse(C4_MAJOR, 0.125); // Plays G4, E4, C4 sequentially
/// ```
pub fn arpeggiate_reverse(mut self, chord: &[f32], note_duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Play the chord notes in reverse order
for &freq in chord.iter().rev() {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Play an arpeggio up then down without doubling the top note
///
/// Unlike calling arpeggiate() then arpeggiate_reverse(), this avoids
/// repeating the highest note, creating a smoother arpeggio pattern.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::chords::C4_MAJOR;
/// comp.instrument("arp", &Instrument::pluck())
/// .arpeggiate_updown(C4_MAJOR, 0.125); // Plays C4, E4, G4, E4, C4 (no double G4)
/// ```
pub fn arpeggiate_updown(mut self, chord: &[f32], note_duration: f32) -> Self {
if chord.is_empty() {
return self;
}
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Play ascending
for &freq in chord.iter() {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
// Play descending, skipping the first note (which was the top)
for &freq in chord.iter().rev().skip(1) {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Play an arpeggio down then up without doubling the bottom note
///
/// The reverse of arpeggiate_updown(), starting from the top and avoiding
/// repetition at the bottom.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::consts::chords::C4_MAJOR;
/// comp.instrument("arp", &Instrument::pluck())
/// .arpeggiate_downup(C4_MAJOR, 0.125); // Plays G4, E4, C4, E4, G4 (no double C4)
/// ```
pub fn arpeggiate_downup(mut self, chord: &[f32], note_duration: f32) -> Self {
if chord.is_empty() {
return self;
}
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Play descending
for &freq in chord.iter().rev() {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
// Play ascending, skipping the first note (which was the bottom)
for &freq in chord.iter().skip(1) {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Play notes with octave doubling
///
/// Each note is played simultaneously with a copy shifted by the specified number of octaves.
/// Positive values double above, negative values double below.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("thicc", &Instrument::saw_lead())
/// .octaves(&[C4, D4, E4], -1, 0.25); // Each note plays with octave below
/// // Plays: C4+C3, D4+D3, E4+E3
/// ```
pub fn octaves(mut self, notes: &[f32], octave_offset: i32, note_duration: f32) -> Self {
let multiplier = 2.0f32.powi(octave_offset);
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
for &freq in notes {
let doubled_freq = freq * multiplier;
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq, doubled_freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Play notes with harmonic interval doubling
///
/// Each note is played simultaneously with a copy shifted by the specified number of semitones.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("harmony", &Instrument::pluck())
/// .harmonize(&[C4, D4, E4], 7, 0.25); // Add perfect fifth (7 semitones) above
/// // Plays: C4+G4, D4+A4, E4+B4
pub fn harmonize(mut self, notes: &[f32], semitones: i32, note_duration: f32) -> Self {
let multiplier = 2.0f32.powf(semitones as f32 / 12.0);
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
for &freq in notes {
let harmony_freq = freq * multiplier;
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq, harmony_freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Pedal point - sustained note with melody above
///
/// Adds a sustained bass note (pedal point) while playing a melody on top.
/// Common in organ music, drone-based music, and creating harmonic tension.
///
/// # Arguments
/// * `pedal_note` - The sustained bass note frequency
/// * `melody_notes` - Notes to play above the pedal point
/// * `note_duration` - Duration of each melody note
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("organ", &Instrument::warm_pad())
/// .pedal(C2, &[E4, F4, G4, A4], 0.5); // C pedal with melody above
/// ```
pub fn pedal(mut self, pedal_note: f32, melody_notes: &[f32], note_duration: f32) -> Self {
let start_cursor = self.cursor;
let total_melody_duration = melody_notes.len() as f32 * note_duration;
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Add sustained pedal note
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[pedal_note],
start_cursor,
total_melody_duration,
waveform,
envelope,
pitch_bend,
);
// Add melody notes on top
for &freq in melody_notes {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Generate notes from a mathematical sequence mapped to a scale
///
/// Takes a mathematical sequence (Fibonacci, primes, etc.) and maps each value
/// to notes from a scale/chord by using the sequence values as indices (modulo scale length).
///
/// # Arguments
/// * `sequence` - The mathematical sequence values
/// * `notes` - Scale or chord to map sequence indices to
/// * `note_duration` - Duration for each note
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::instruments::Instrument;
/// # use tunes::composition::timing::Tempo;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// use tunes::sequences;
/// use tunes::consts::scales::C4_MAJOR_SCALE;
///
/// let fib = sequences::fibonacci::generate(16);
/// comp.instrument("fib", &Instrument::pluck())
/// .sequence_from(&fib, &C4_MAJOR_SCALE, 0.125); // Maps Fibonacci to C major scale
///
/// // Fibonacci: 1,1,2,3,5,8,13,21...
/// // Plays: D4, D4, E4, F4, A4, C5, A4, E4... (wrapping around the scale)
pub fn sequence_from(mut self, sequence: &[u32], notes: &[f32], note_duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
for &value in sequence {
// Map sequence value to note index (wrapping around if needed)
let note_index = (value as usize) % notes.len();
let freq = notes[note_index];
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
note_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(note_duration);
self.cursor += swung_duration;
}
self
}
/// Generate notes in an orbital pattern around a center pitch
///
/// Creates a smooth sinusoidal pattern of pitches that oscillate around a center frequency,
/// like a planet orbiting a star.
///
/// # Arguments
/// * `center` - The center pitch to orbit around (e.g., C4, A4)
/// * `radius_semitones` - Maximum distance from center in semitones (e.g., 7 for a fifth, 12 for an octave)
/// * `steps_per_rotation` - Number of notes in one complete orbit (resolution)
/// * `step_duration` - Duration of each note in seconds
/// * `rotations` - Number of complete orbits (can be fractional, e.g., 1.0, 2.5, 0.5)
/// * `clockwise` - Direction: true = start ascending, false = start descending
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("orbit", &Instrument::synth_lead())
/// .orbit(C4, 7.0, 16, 0.125, 2.0, true); // Two complete orbits, 16 steps each
/// ```
pub fn orbit(
mut self,
center: f32,
radius_semitones: f32,
steps_per_rotation: usize,
step_duration: f32,
rotations: f32,
clockwise: bool,
) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Calculate total number of notes
let total_steps = (steps_per_rotation as f32 * rotations) as usize;
for i in 0..total_steps {
// Calculate angle for this step (spans multiple rotations)
let angle = (i as f32 / steps_per_rotation as f32) * 2.0 * PI;
// Use sine wave to create smooth oscillation
// Clockwise: start at 0, go positive (up in pitch)
// Counter-clockwise: start at 0, go negative (down in pitch)
let direction = if clockwise { 1.0 } else { -1.0 };
let semitone_offset = radius_semitones * (angle.sin() * direction);
// Convert semitone offset to frequency multiplier
let freq = center * 2.0_f32.powf(semitone_offset / 12.0);
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
step_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(step_duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Generate a bouncing pitch pattern that settles toward a floor frequency
///
/// Simulates a bouncing ball in pitch space with damping. Starts at a high pitch,
/// falls to a floor, then bounces back up with decreasing height each time.
///
/// # Arguments
/// * `start` - Starting frequency (e.g., 440.0 for A4)
/// * `stop` - Floor frequency where bounces occur (e.g., 220.0 for A3)
/// * `ratio` - Damping ratio for each bounce (0.0-1.0, e.g., 0.5 = each bounce is 50% of previous height)
/// * `bounces` - Number of times to bounce back up
/// * `steps_per_segment` - Number of notes in each rise/fall segment
/// * `step_duration` - Duration of each note in seconds
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("bounce", &Instrument::synth_lead())
/// .bounce(440.0, 220.0, 0.6, 3, 8, 0.0625); // Bouncing ball effect
/// ```
pub fn bounce(
mut self,
start: f32,
stop: f32,
ratio: f32,
bounces: usize,
steps_per_segment: usize,
step_duration: f32,
) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
// Initial fall from start to stop
for i in 0..steps_per_segment {
let t = i as f32 / (steps_per_segment - 1) as f32;
let freq = start + (stop - start) * t;
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
step_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(step_duration);
self.cursor += swung_duration;
}
// Calculate initial bounce height
let initial_height = start - stop;
// Generate each bounce
for bounce in 1..=bounces {
// Calculate bounce height with damping
let bounce_height = initial_height * ratio.powi(bounce as i32);
let peak = stop + bounce_height;
// Rise from floor to peak
for i in 0..steps_per_segment {
let t = i as f32 / (steps_per_segment - 1) as f32;
let freq = stop + (peak - stop) * t;
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
step_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(step_duration);
self.cursor += swung_duration;
}
// Fall from peak back to floor
for i in 0..steps_per_segment {
let t = i as f32 / (steps_per_segment - 1) as f32;
let freq = peak + (stop - peak) * t;
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
step_duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(step_duration);
self.cursor += swung_duration;
}
}
self.update_section_duration();
self
}
/// Generate random notes scattered across a frequency range
///
/// Creates a sequence of random pitches within a specified range. Each note
/// has a random frequency uniformly distributed between min and max.
///
/// # Arguments
/// * `min` - Minimum frequency in Hz (e.g., 220.0 for A3)
/// * `max` - Maximum frequency in Hz (e.g., 880.0 for A5)
/// * `count` - Number of random notes to generate
/// * `duration` - Duration of each note in seconds
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("scatter", &Instrument::synth_lead())
/// .scatter(200.0, 800.0, 32, 0.0625); // 32 random notes in that range
/// ```
pub fn scatter(mut self, min: f32, max: f32, count: usize, duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
let mut rng = rand::rng();
for _ in 0..count {
// Generate random frequency in range
let freq = rng.random_range(min..=max);
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Generate a stream of repeated notes at a single frequency
///
/// Creates a sequence of identical notes - perfect for drones, ostinatos,
/// or as a base pattern for transforms.
///
/// # Arguments
/// * `freq` - Frequency in Hz (e.g., 440.0 for A4)
/// * `count` - Number of notes to generate
/// * `duration` - Duration of each note in seconds
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("stream", &Instrument::synth_lead())
/// .stream(440.0, 16, 0.125); // 16 repeated A4 notes
/// ```
pub fn stream(mut self, freq: f32, count: usize, duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
for _ in 0..count {
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Generate random notes picked from a provided set
///
/// Randomly selects notes from a provided array with equal probability.
/// Perfect for generative music within a scale, chord, or any custom note set.
///
/// # Arguments
/// * `notes` - Array of frequencies to randomly choose from (e.g., scale or chord tones)
/// * `count` - Number of random notes to generate
/// * `duration` - Duration of each note in seconds
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("random", &Instrument::synth_lead())
/// .random_notes(&[C4, E4, G4, C5], 16, 0.125); // Random notes from C major triad
/// ```
pub fn random_notes(mut self, notes: &[f32], count: usize, duration: f32) -> Self {
if notes.is_empty() {
return self;
}
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
let mut rng = rand::rng();
for _ in 0..count {
// Pick a random note from the array
let idx = rng.random_range(0..notes.len());
let freq = notes[idx];
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
/// Generate completely random frequencies within a range
///
/// Creates random f32 frequencies with no snapping or quantization.
/// Unlike discrete note selection, this produces truly continuous pitch values.
///
/// # Arguments
/// * `min` - Minimum frequency (Hz)
/// * `max` - Maximum frequency (Hz)
/// * `count` - Number of random notes to generate
/// * `duration` - Duration of each note in seconds
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.instrument("sprinkle", &Instrument::synth_lead())
/// .sprinkle(220.0, 440.0, 8, 0.125); // Random f32 frequencies between A3-A4
/// ```
pub fn sprinkle(mut self, min: f32, max: f32, count: usize, duration: f32) -> Self {
let waveform = self.waveform;
let envelope = self.envelope;
let pitch_bend = self.pitch_bend;
let mut rng = rand::rng();
for _ in 0..count {
// Generate completely random f32 frequency
let freq = rng.random_range(min..=max);
let cursor = self.cursor;
self.get_track_mut()
.add_note_with_waveform_envelope_and_bend(
&[freq],
cursor,
duration,
waveform,
envelope,
pitch_bend,
);
let swung_duration = self.apply_swing(duration);
self.cursor += swung_duration;
}
self.update_section_duration();
self
}
}
#[cfg(test)]
mod tests {
use crate::composition::Composition;
use crate::composition::timing::Tempo;
use crate::consts::notes::*;
use crate::prelude::Instrument;
use crate::track::AudioEvent;
#[test]
fn test_chords_plays_sequence() {
let mut comp = Composition::new(Tempo::new(120.0));
let chords: Vec<&[f32]> = vec![&[C4, E4, G4], &[F4, A4, C5]];
comp.track("chords").chords(&chords, 1.0);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 2);
// First chord
if let AudioEvent::Note(note) = &track.events[0] {
assert_eq!(note.num_freqs, 3);
assert_eq!(note.start_time, 0.0);
assert_eq!(note.duration, 1.0);
}
// Second chord
if let AudioEvent::Note(note) = &track.events[1] {
assert_eq!(note.num_freqs, 3);
assert_eq!(note.start_time, 1.0);
}
}
#[test]
fn test_chords_from_vec_format() {
let mut comp = Composition::new(Tempo::new(120.0));
let chords = vec![vec![C4, E4, G4], vec![F4, A4, C5]];
comp.track("chords").chords_from(&chords, 0.5);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 2);
}
#[test]
fn test_scale_ascending() {
let mut comp = Composition::new(Tempo::new(120.0));
let scale = [C4, D4, E4, F4, G4];
comp.track("scale").scale(&scale, 0.2);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 5);
// Verify ascending order
for (i, &expected) in scale.iter().enumerate() {
if let AudioEvent::Note(note) = &track.events[i] {
assert_eq!(note.frequencies[0], expected);
}
}
}
#[test]
fn test_scale_reverse_descending() {
let mut comp = Composition::new(Tempo::new(120.0));
let scale = [C4, D4, E4, F4, G4];
comp.track("scale").scale_reverse(&scale, 0.2);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 5);
// Verify descending order (reversed)
for (i, &expected) in scale.iter().rev().enumerate() {
if let AudioEvent::Note(note) = &track.events[i] {
assert_eq!(note.frequencies[0], expected);
}
}
}
#[test]
fn test_scale_updown_no_peak_double() {
let mut comp = Composition::new(Tempo::new(120.0));
let scale = [C4, D4, E4];
comp.track("scale").scale_updown(&scale, 0.1);
let track = &comp.into_mixer().tracks()[0];
// Should be: C4, D4, E4 (up), then D4, C4 (down, skipping E4)
// Total = 5 notes
assert_eq!(track.events.len(), 5);
if let AudioEvent::Note(note) = &track.events[2] {
assert_eq!(note.frequencies[0], E4); // Peak
}
if let AudioEvent::Note(note) = &track.events[3] {
assert_eq!(note.frequencies[0], D4); // First note going down
}
}
#[test]
fn test_scale_updown_with_empty_scale() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("scale").scale_updown(&[], 0.1);
assert_eq!(builder.cursor, 0.0);
}
#[test]
fn test_scale_downup_no_bottom_double() {
let mut comp = Composition::new(Tempo::new(120.0));
let scale = [C4, D4, E4];
comp.track("scale").scale_downup(&scale, 0.1);
let track = &comp.into_mixer().tracks()[0];
// Should be: E4, D4, C4 (down), then D4, E4 (up, skipping C4)
// Total = 5 notes
assert_eq!(track.events.len(), 5);
if let AudioEvent::Note(note) = &track.events[2] {
assert_eq!(note.frequencies[0], C4); // Bottom
}
if let AudioEvent::Note(note) = &track.events[3] {
assert_eq!(note.frequencies[0], D4); // First note going up
}
}
#[test]
fn test_arpeggiate_ascending() {
let mut comp = Composition::new(Tempo::new(120.0));
let chord = [C4, E4, G4];
comp.track("arp").arpeggiate(&chord, 0.125);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 3);
// Verify ascending order
for (i, &expected) in chord.iter().enumerate() {
if let AudioEvent::Note(note) = &track.events[i] {
assert_eq!(note.frequencies[0], expected);
}
}
}
#[test]
fn test_arpeggiate_reverse_descending() {
let mut comp = Composition::new(Tempo::new(120.0));
let chord = [C4, E4, G4];
comp.track("arp").arpeggiate_reverse(&chord, 0.125);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 3);
// Verify descending order
for (i, &expected) in chord.iter().rev().enumerate() {
if let AudioEvent::Note(note) = &track.events[i] {
assert_eq!(note.frequencies[0], expected);
}
}
}
#[test]
fn test_arpeggiate_updown_no_top_double() {
let mut comp = Composition::new(Tempo::new(120.0));
let chord = [C4, E4, G4];
comp.track("arp").arpeggiate_updown(&chord, 0.1);
let track = &comp.into_mixer().tracks()[0];
// Should be: C4, E4, G4 (up), then E4, C4 (down, skipping G4)
// Total = 5 notes
assert_eq!(track.events.len(), 5);
if let AudioEvent::Note(note) = &track.events[2] {
assert_eq!(note.frequencies[0], G4); // Top
}
if let AudioEvent::Note(note) = &track.events[3] {
assert_eq!(note.frequencies[0], E4); // First note going down
}
}
#[test]
fn test_arpeggiate_downup_no_bottom_double() {
let mut comp = Composition::new(Tempo::new(120.0));
let chord = [C4, E4, G4];
comp.track("arp").arpeggiate_downup(&chord, 0.1);
let track = &comp.into_mixer().tracks()[0];
// Should be: G4, E4, C4 (down), then E4, G4 (up, skipping C4)
// Total = 5 notes
assert_eq!(track.events.len(), 5);
if let AudioEvent::Note(note) = &track.events[2] {
assert_eq!(note.frequencies[0], C4); // Bottom
}
if let AudioEvent::Note(note) = &track.events[3] {
assert_eq!(note.frequencies[0], E4); // First note going up
}
}
#[test]
fn test_octaves_doubles_each_note() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("thick").octaves(&[C4, E4], 1, 0.5); // Octave above
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 2);
// First note should have 2 frequencies (C4 + C5)
if let AudioEvent::Note(note) = &track.events[0] {
assert_eq!(note.num_freqs, 2);
assert_eq!(note.frequencies[0], C4);
// Octave above should be 2x frequency
assert!((note.frequencies[1] - C4 * 2.0).abs() < 0.1);
}
}
#[test]
fn test_octaves_negative_offset() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("thick").octaves(&[C4], -1, 0.5); // Octave below
let track = &comp.into_mixer().tracks()[0];
if let AudioEvent::Note(note) = &track.events[0] {
assert_eq!(note.num_freqs, 2);
assert_eq!(note.frequencies[0], C4);
// Octave below should be 0.5x frequency
assert!((note.frequencies[1] - C4 * 0.5).abs() < 0.1);
}
}
#[test]
fn test_harmonize_adds_interval() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("harmony").harmonize(&[C4], 7, 0.5); // Perfect fifth (7 semitones)
let track = &comp.into_mixer().tracks()[0];
if let AudioEvent::Note(note) = &track.events[0] {
assert_eq!(note.num_freqs, 2);
assert_eq!(note.frequencies[0], C4);
// G4 is 7 semitones above C4
let expected_g4 = C4 * 2.0f32.powf(7.0 / 12.0);
assert!((note.frequencies[1] - expected_g4).abs() < 0.1);
}
}
#[test]
fn test_harmonize_multiple_notes() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("harmony").harmonize(&[C4, D4, E4], 4, 0.25); // Major third
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 3);
// Each note should be doubled with harmony
for event in &track.events {
if let AudioEvent::Note(note) = event {
assert_eq!(note.num_freqs, 2);
}
}
}
#[test]
fn test_pedal_sustains_bass() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("pedal").pedal(C4, &[E4, G4, B4], 0.5);
let track = &comp.into_mixer().tracks()[0];
// Should have 1 pedal note + 3 melody notes = 4 events
assert_eq!(track.events.len(), 4);
// First note should be the long pedal note
if let AudioEvent::Note(pedal) = &track.events[0] {
assert_eq!(pedal.frequencies[0], C4);
assert_eq!(pedal.duration, 1.5); // 3 notes * 0.5
assert_eq!(pedal.start_time, 0.0);
}
// Melody notes should follow
if let AudioEvent::Note(note) = &track.events[1] {
assert_eq!(note.frequencies[0], E4);
assert_eq!(note.start_time, 0.0);
}
if let AudioEvent::Note(note) = &track.events[2] {
assert_eq!(note.frequencies[0], G4);
assert_eq!(note.start_time, 0.5);
}
}
#[test]
fn test_pedal_advances_cursor_correctly() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("pedal").pedal(C4, &[E4, G4], 0.5);
// 2 melody notes * 0.5 = 1.0
assert_eq!(builder.cursor, 1.0);
}
#[test]
fn test_sequence_from_maps_values() {
let mut comp = Composition::new(Tempo::new(120.0));
let sequence = [0, 1, 2, 3, 4];
let scale = [C4, D4, E4, F4, G4];
comp.track("seq").sequence_from(&sequence, &scale, 0.1);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 5);
// Should map directly: sequence[i] -> scale[i]
for (i, &seq_val) in sequence.iter().enumerate() {
if let AudioEvent::Note(note) = &track.events[i] {
assert_eq!(note.frequencies[0], scale[seq_val as usize]);
}
}
}
#[test]
fn test_sequence_from_wraps_around() {
let mut comp = Composition::new(Tempo::new(120.0));
let sequence = [0, 3, 6, 9]; // Larger than scale length
let scale = [C4, D4, E4]; // Length 3
comp.track("seq").sequence_from(&sequence, &scale, 0.1);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 4);
// Values should wrap: 0->C4, 3->C4, 6->C4, 9->C4
for event in &track.events {
if let AudioEvent::Note(note) = event {
assert_eq!(note.frequencies[0], C4);
}
}
}
#[test]
fn test_sequence_from_fibonacci_pattern() {
let mut comp = Composition::new(Tempo::new(120.0));
let fib = [1, 1, 2, 3, 5, 8];
let scale = [C4, D4, E4, F4, G4];
comp.track("fib").sequence_from(&fib, &scale, 0.1);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 6);
// Verify mapping: 1->D4, 1->D4, 2->E4, 3->F4, 5->C4(wrapped), 8->F4(wrapped)
let expected = [D4, D4, E4, F4, C4, F4];
for (i, &exp) in expected.iter().enumerate() {
if let AudioEvent::Note(note) = &track.events[i] {
assert_eq!(note.frequencies[0], exp);
}
}
}
#[test]
fn test_chaining_musical_patterns() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("combo")
.scale(&[C4, D4, E4], 0.1)
.arpeggiate(&[C4, E4, G4], 0.1)
.scale_reverse(&[C4, D4, E4], 0.1);
let track = &comp.into_mixer().tracks()[0];
// 3 scale + 3 arp + 3 reverse = 9 total
assert_eq!(track.events.len(), 9);
}
#[test]
fn test_empty_chord_sequences() {
let mut comp = Composition::new(Tempo::new(120.0));
let empty: Vec<&[f32]> = vec![];
let builder = comp.track("empty").chords(&empty, 1.0);
assert_eq!(builder.cursor, 0.0);
}
#[test]
fn test_single_note_updown_patterns() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("single").scale_updown(&[C4], 0.1);
let track = &comp.into_mixer().tracks()[0];
// Single note: up (1 note), down (skip first = 0 notes) = 1 total
assert_eq!(track.events.len(), 1);
}
#[test]
fn test_progression_creates_triads() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("prog").progression(
C4,
&crate::theory::core::ScalePattern::MAJOR,
&[1, 4, 5, 1],
1.0,
);
let track = &comp.into_mixer().tracks()[0];
// Should have 4 chords (I-IV-V-I)
assert_eq!(track.events.len(), 4);
// Each chord should have 3 notes (triads)
for event in &track.events {
if let AudioEvent::Note(note) = event {
assert_eq!(note.num_freqs, 3);
}
}
}
#[test]
fn test_progression_7th_creates_seventh_chords() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("jazz").progression_7th(
C4,
&crate::theory::core::ScalePattern::MAJOR,
&[2, 5, 1],
2.0,
);
let track = &comp.into_mixer().tracks()[0];
// Should have 3 chords (ii7-V7-Imaj7)
assert_eq!(track.events.len(), 3);
// Each chord should have 4 notes (7th chords)
for event in &track.events {
if let AudioEvent::Note(note) = event {
assert_eq!(note.num_freqs, 4);
}
}
}
#[test]
fn test_progression_advances_cursor() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("prog").progression(
C4,
&crate::theory::core::ScalePattern::MAJOR,
&[1, 5, 6, 4],
1.5,
);
// 4 chords * 1.5 duration = 6.0
assert_eq!(builder.cursor, 6.0);
}
#[test]
fn test_progression_with_different_scales() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("minor").progression(
A3,
&crate::theory::core::ScalePattern::MINOR,
&[1, 4, 5],
1.0,
);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 3);
}
#[test]
fn test_progression_chain_with_other_methods() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("combo")
.note(&[C4], 0.5)
.progression(C4, &crate::theory::core::ScalePattern::MAJOR, &[1, 5], 1.0)
.note(&[G4], 0.5);
let track = &comp.into_mixer().tracks()[0];
// 1 note + 2 chords + 1 note = 4 events
assert_eq!(track.events.len(), 4);
}
#[test]
fn test_orbit_generates_correct_number_of_notes() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("orbit").orbit(C4, 7.0, 16, 0.125, 1.0, true);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 16);
}
#[test]
fn test_orbit_advances_cursor() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("orbit").orbit(C4, 12.0, 8, 0.25, 1.0, false);
// 8 steps * 0.25 duration = 2.0
assert_eq!(builder.cursor, 2.0);
}
#[test]
fn test_orbit_with_generator_namespace() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("orbit_ns")
.generator(|g| g.orbit(A4, 5.0, 12, 0.1, 1.0, true));
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 12);
}
#[test]
fn test_orbit_clockwise_vs_counterclockwise() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("cw").orbit(C4, 12.0, 4, 0.25, 1.0, true);
comp.track("ccw").orbit(C4, 12.0, 4, 0.25, 1.0, false);
let mixer = comp.into_mixer();
let cw_track = &mixer.tracks()[0];
let ccw_track = &mixer.tracks()[1];
// Both should have same number of notes
assert_eq!(cw_track.events.len(), 4);
assert_eq!(ccw_track.events.len(), 4);
// Pitches should be different (opposite directions)
if let (AudioEvent::Note(cw_note), AudioEvent::Note(ccw_note)) =
(&cw_track.events[1], &ccw_track.events[1])
{
// At step 1, clockwise goes up, counterclockwise goes down
// They should have different pitches
assert_ne!(cw_note.frequencies[0], ccw_note.frequencies[0]);
}
}
#[test]
fn test_orbit_multiple_rotations() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("double").orbit(C4, 7.0, 8, 0.125, 2.0, true); // 2 complete rotations
let track = &comp.into_mixer().tracks()[0];
// 8 steps per rotation * 2 rotations = 16 notes
assert_eq!(track.events.len(), 16);
}
#[test]
fn test_orbit_fractional_rotations() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("half").orbit(C4, 12.0, 16, 0.0625, 0.5, true); // Half rotation
let track = &comp.into_mixer().tracks()[0];
// 16 steps per rotation * 0.5 = 8 notes
assert_eq!(track.events.len(), 8);
}
#[test]
fn test_bounce_generates_correct_number_of_notes() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("bounce").bounce(440.0, 220.0, 0.5, 2, 4, 0.125);
let track = &comp.into_mixer().tracks()[0];
// Initial fall (4) + bounce1 up (4) + bounce1 down (4) + bounce2 up (4) + bounce2 down (4) = 20
assert_eq!(track.events.len(), 20);
}
#[test]
fn test_bounce_pitch_descends_initially() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("bounce").bounce(440.0, 220.0, 0.6, 1, 8, 0.0625);
let track = &comp.into_mixer().tracks()[0];
// Check first note is near start frequency
if let AudioEvent::Note(first_note) = &track.events[0] {
assert!((first_note.frequencies[0] - 440.0).abs() < 1.0);
}
// Check that pitch generally descends in first segment
if let (AudioEvent::Note(note1), AudioEvent::Note(note2)) =
(&track.events[0], &track.events[4])
{
assert!(note1.frequencies[0] > note2.frequencies[0]);
}
}
#[test]
fn test_bounce_with_generator_namespace() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("bounce_ns")
.generator(|g| g.bounce(330.0, 165.0, 0.7, 3, 4, 0.1));
let track = &comp.into_mixer().tracks()[0];
// Initial fall (4) + 3 bounces * 2 segments each * 4 notes = 4 + 24 = 28
assert_eq!(track.events.len(), 28);
}
#[test]
fn test_bounce_zero_bounces() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("fall").bounce(440.0, 220.0, 0.5, 0, 8, 0.125);
let track = &comp.into_mixer().tracks()[0];
// Only the initial fall, no bounces
assert_eq!(track.events.len(), 8);
}
#[test]
fn test_scatter_generates_correct_count() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("scatter").scatter(200.0, 800.0, 24, 0.125);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 24);
}
#[test]
fn test_scatter_stays_in_range() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("scatter").scatter(300.0, 600.0, 50, 0.0625);
let track = &comp.into_mixer().tracks()[0];
// All notes should be within range
for event in &track.events {
if let AudioEvent::Note(note) = event {
assert!(note.frequencies[0] >= 300.0);
assert!(note.frequencies[0] <= 600.0);
}
}
}
#[test]
fn test_scatter_with_generator_namespace() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("scatter_ns")
.generator(|g| g.scatter(220.0, 880.0, 16, 0.1));
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 16);
}
#[test]
fn test_scatter_advances_cursor() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("scatter").scatter(400.0, 800.0, 10, 0.25);
// 10 notes * 0.25 duration = 2.5
assert_eq!(builder.cursor, 2.5);
}
#[test]
fn test_stream_generates_correct_count() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("stream").stream(440.0, 16, 0.125);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 16);
}
#[test]
fn test_stream_all_same_frequency() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("stream").stream(523.25, 8, 0.25);
let track = &comp.into_mixer().tracks()[0];
// All notes should be the same frequency
for event in &track.events {
if let AudioEvent::Note(note) = event {
assert!((note.frequencies[0] - 523.25).abs() < 0.01);
}
}
}
#[test]
fn test_stream_with_generator_namespace() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("stream_ns")
.generator(|g| g.stream(330.0, 12, 0.1));
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 12);
}
#[test]
fn test_stream_advances_cursor() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("stream").stream(880.0, 8, 0.125);
// 8 notes * 0.125 duration = 1.0
assert_eq!(builder.cursor, 1.0);
}
#[test]
fn test_random_notes_generates_correct_count() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("random")
.random_notes(&[C4, E4, G4, C5], 20, 0.125);
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 20);
}
#[test]
fn test_random_notes_only_picks_from_set() {
let mut comp = Composition::new(Tempo::new(120.0));
let note_set = vec![261.63, 329.63, 392.0]; // C4, E4, G4
comp.track("random").random_notes(¬e_set, 30, 0.0625);
let track = &comp.into_mixer().tracks()[0];
// All notes should be from the provided set
for event in &track.events {
if let AudioEvent::Note(note) = event {
let freq = note.frequencies[0];
assert!(
(freq - 261.63).abs() < 0.1
|| (freq - 329.63).abs() < 0.1
|| (freq - 392.0).abs() < 0.1,
"Note {} not in set",
freq
);
}
}
}
#[test]
fn test_random_notes_with_generator_namespace() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("random_ns")
.generator(|g| g.random_notes(&[D4, F4, A4], 12, 0.1));
let track = &comp.into_mixer().tracks()[0];
assert_eq!(track.events.len(), 12);
}
#[test]
fn test_random_notes_empty_array() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("empty").random_notes(&[], 10, 0.125);
// Should return without advancing cursor if array is empty
assert_eq!(builder.cursor, 0.0);
}
#[test]
fn test_random_notes_advances_cursor() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("random").random_notes(&[C4, E4, G4], 8, 0.25);
// 8 notes * 0.25 duration = 2.0
assert_eq!(builder.cursor, 2.0);
}
#[test]
fn test_sprinkle_generates_correct_count() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.instrument("sprinkle", &Instrument::synth_lead())
.sprinkle(200.0, 800.0, 12, 0.125);
let mixer = comp.into_mixer();
let track = &mixer.tracks()[0];
// 12 notes
assert_eq!(track.events.len(), 12);
}
#[test]
fn test_sprinkle_within_range() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.instrument("sprinkle", &Instrument::synth_lead())
.sprinkle(220.0, 440.0, 20, 0.1);
let mixer = comp.into_mixer();
let track = &mixer.tracks()[0];
// All frequencies should be within range
for event in &track.events {
if let AudioEvent::Note(note) = event {
let freq = note.frequencies[0];
assert!(
(220.0..=440.0).contains(&freq),
"Frequency {} outside range 220-440",
freq
);
}
}
}
#[test]
fn test_sprinkle_with_generator_namespace() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.instrument("sprinkle", &Instrument::synth_lead())
.generator(|g| g.sprinkle(300.0, 600.0, 8, 0.125));
let mixer = comp.into_mixer();
let track = &mixer.tracks()[0];
assert_eq!(track.events.len(), 8);
}
#[test]
fn test_sprinkle_advances_cursor() {
let mut comp = Composition::new(Tempo::new(120.0));
let builder = comp.track("sprinkle").sprinkle(100.0, 1000.0, 16, 0.0625);
// 16 notes * 0.0625 duration = 1.0
assert_eq!(builder.cursor, 1.0);
}
#[test]
fn test_sprinkle_generates_continuous_values() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.instrument("sprinkle", &Instrument::synth_lead())
.sprinkle(220.0, 440.0, 50, 0.05);
let mixer = comp.into_mixer();
let track = &mixer.tracks()[0];
// Check that we get variety (not all the same frequency)
let mut freqs = std::collections::HashSet::new();
for event in &track.events {
if let AudioEvent::Note(note) = event {
let freq = note.frequencies[0];
freqs.insert((freq * 100.0) as i32); // Discretize for comparison
}
}
// With 50 random samples, we should get many different values
assert!(
freqs.len() > 10,
"Expected diverse frequencies, got only {} unique values",
freqs.len()
);
}
}