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
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
//! Pattern transformation methods
use crate::composition::TrackBuilder;
use crate::synthesis::envelope::Envelope;
use crate::synthesis::waveform::Waveform;
use crate::track::{AudioEvent, DrumEvent, NoteEvent};
/// Mutable reference to either a NoteEvent or DrumEvent
///
/// Used with `for_each_event` to allow transforms to operate on both event types
/// with full access to their fields.
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::composition::generative::transforms::EventMut;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("test")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .for_each_event(|event, note_count, drum_count| {
/// match event {
/// EventMut::Note(n) if note_count % 2 == 0 => n.velocity = 1.0,
/// EventMut::Drum(d) if drum_count % 4 == 0 => d.velocity = 1.0,
/// _ => {}
/// }
/// });
/// ```
pub enum EventMut<'a> {
/// Mutable reference to a NoteEvent
Note(&'a mut NoteEvent),
/// Mutable reference to a DrumEvent
Drum(&'a mut DrumEvent),
}
impl<'a> TrackBuilder<'a> {
/// Add human feel to pattern by randomizing timing and velocity
///
/// Makes programmed music feel more natural by adding slight random variations
/// to note timing and velocity within the pattern.
///
/// # Arguments
/// * `timing_variance` - Max timing offset in seconds (e.g., 0.02 = ±20ms)
/// * `velocity_variance` - Max velocity change (e.g., 0.1 = ±10%)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("piano")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .humanize(0.02, 0.1); // Subtle humanization
///
/// comp.track("drums")
/// .pattern_start()
/// .notes(&[C4, C4, C4, C4], 0.25)
/// .humanize(0.005, 0.15); // Tight timing, varied velocity
/// ```
pub fn humanize(mut self, timing_variance: f32, velocity_variance: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Apply humanization to notes in the pattern
for event in &mut self.get_track_mut().events {
let event_time = match event {
AudioEvent::Note(note) => note.start_time,
AudioEvent::Drum(drum) => drum.start_time,
_ => continue,
};
if event_time >= pattern_start && event_time < cursor {
match event {
AudioEvent::Note(note) => {
// Randomize timing
use rand::Rng;
let mut rng = rand::rng();
let timing_offset = rng.random_range(-timing_variance..=timing_variance);
note.start_time = (note.start_time + timing_offset).max(0.0);
// Randomize velocity
let velocity_offset =
rng.random_range(-velocity_variance..=velocity_variance);
note.velocity = (note.velocity + velocity_offset).clamp(0.0, 1.0);
}
AudioEvent::Drum(drum) => {
// Randomize drum timing and velocity
use rand::Rng;
let mut rng = rand::rng();
let timing_offset = rng.random_range(-timing_variance..=timing_variance);
drum.start_time = (drum.start_time + timing_offset).max(0.0);
let velocity_offset =
rng.random_range(-velocity_variance..=velocity_variance);
drum.velocity = (drum.velocity + velocity_offset).clamp(0.0, 1.0);
}
_ => {}
}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Rotate notes in the pattern by n positions
///
/// Cycles the pitch sequence while keeping timing the same.
/// Positive values rotate forward, negative rotate backward.
///
/// # Arguments
/// * `positions` - Number of positions to rotate (positive = forward, negative = backward)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Original: C4, E4, G4, C5
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .rotate(1); // Result: E4, G4, C5, C4
///
/// comp.track("bass")
/// .pattern_start()
/// .notes(&[C3, E3, G3], 0.5)
/// .rotate(-1); // Result: G3, C3, E3
/// ```
pub fn rotate(mut self, positions: i32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || positions == 0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect note events in the pattern
let mut note_events: Vec<(usize, [f32; 8], usize)> = Vec::new();
// Collect drum events in the pattern
let mut drum_events: Vec<(usize, f32)> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
note_events.push((idx, note.frequencies, note.num_freqs));
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
drum_events.push((idx, drum.pitch_offset));
}
}
_ => {}
}
}
// Rotate note frequencies
if !note_events.is_empty() {
let freqs: Vec<([f32; 8], usize)> =
note_events.iter().map(|(_, f, n)| (*f, *n)).collect();
let len = freqs.len() as i32;
let normalized_rotation = ((positions % len) + len) % len;
for (i, (event_idx, _, _)) in note_events.iter().enumerate() {
let rotated_idx = ((i as i32 + normalized_rotation) % len) as usize;
if let AudioEvent::Note(note) = &mut self.get_track_mut().events[*event_idx] {
note.frequencies = freqs[rotated_idx].0;
note.num_freqs = freqs[rotated_idx].1;
}
}
}
// Rotate drum pitch offsets
if !drum_events.is_empty() {
let pitch_offsets: Vec<f32> = drum_events.iter().map(|(_, p)| *p).collect();
let len = pitch_offsets.len() as i32;
let normalized_rotation = ((positions % len) + len) % len;
for (i, (event_idx, _)) in drum_events.iter().enumerate() {
let rotated_idx = ((i as i32 + normalized_rotation) % len) as usize;
if let AudioEvent::Drum(drum) = &mut self.get_track_mut().events[*event_idx] {
drum.pitch_offset = pitch_offsets[rotated_idx];
}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Mutate pitches by random semitone offsets (evolutionary variation)
///
/// Randomly adjusts each note by up to ±amount semitones, creating subtle to dramatic
/// variations while maintaining the overall melodic shape. Great for generative music
/// and creating organic variations of existing patterns.
///
/// # Arguments
/// * `max_semitones` - Maximum random shift in semitones (positive values only)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Subtle variation - like a slightly drunk pianist
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .mutate(1); // Each note shifts by -1, 0, or +1 semitones
///
/// // Dramatic variation
/// comp.track("wild")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .mutate(5); // Each note can shift by -5 to +5 semitones
/// ```
pub fn mutate(mut self, max_semitones: i32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || max_semitones == 0 {
return self;
}
let max_semitones = max_semitones.abs(); // Ensure positive
let pattern_start = self.pattern_start;
let cursor = self.cursor;
use rand::Rng;
let mut rng = rand::rng();
// Mutate notes and drums in the pattern
for event in &mut self.get_track_mut().events {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
// Apply random mutation to each frequency in the note/chord
for i in 0..note.num_freqs {
// Random offset: -max_semitones to +max_semitones
let offset = rng.random_range(-max_semitones..=max_semitones);
if offset != 0 {
let shift_ratio = 2.0_f32.powf(offset as f32 / 12.0);
note.frequencies[i] *= shift_ratio;
}
}
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
// Apply random mutation to drum pitch
let offset = rng.random_range(-max_semitones..=max_semitones);
drum.pitch_offset += offset as f32;
}
}
_ => {}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Stack harmonic layers on each note
///
/// Adds `count` additional voices to each note, each shifted by `semitones` from the previous.
/// Creates thick unison sounds, octave stacking, or complex harmonic layers - a fundamental
/// technique in music production for making sounds bigger and richer.
///
/// # Arguments
/// * `semitones` - Semitone interval between each layer (can be negative)
/// * `count` - Number of layers to add (1 = two voices, 2 = three voices, etc.)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Classic octave stacking - C4 becomes [C4, C5] playing simultaneously
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.5)
/// .stack(12, 1); // Stack octave above each note
///
/// // Thick three-octave unison - C4 becomes [C4, C5, C6]
/// comp.track("lead")
/// .pattern_start()
/// .notes(&[C4], 1.0)
/// .stack(12, 2); // Stack two octaves
///
/// // Stack perfect fifth and major ninth - C4 becomes [C4, G4, D5]
/// comp.track("chord")
/// .pattern_start()
/// .notes(&[C4], 1.0)
/// .stack(7, 2);
///
/// // Bass reinforcement - stack octave below
/// comp.track("bass")
/// .pattern_start()
/// .notes(&[C4], 1.0)
/// .stack(-12, 1);
/// ```
pub fn stack(mut self, semitones: i32, count: usize) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || count == 0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect drums in pattern to create stacked copies
let drums_to_stack: Vec<_> = self
.get_track_mut()
.events
.iter()
.filter_map(|event| {
if let AudioEvent::Drum(drum) = event {
if drum.start_time >= pattern_start && drum.start_time < cursor {
return Some(*drum);
}
}
None
})
.collect();
// Stack notes in place (notes can hold multiple frequencies)
for event in &mut self.get_track_mut().events {
if let AudioEvent::Note(note) = event {
if note.start_time >= pattern_start && note.start_time < cursor {
let original_count = note.num_freqs;
// For each duplicate layer
for layer in 1..=count {
let shift = semitones * layer as i32;
let shift_ratio = 2.0_f32.powf(shift as f32 / 12.0);
// Duplicate each original frequency
for i in 0..original_count {
if note.num_freqs < 8 {
note.frequencies[note.num_freqs] =
note.frequencies[i] * shift_ratio;
note.num_freqs += 1;
} else {
// Max 8 frequencies - silently stop if we hit the limit
break;
}
}
}
}
}
}
// Create stacked drum copies with shifted pitch
for drum in drums_to_stack {
for layer in 1..=count {
let shift = semitones * layer as i32;
self.get_track_mut()
.events
.push(AudioEvent::Drum(crate::track::DrumEvent {
drum_type: drum.drum_type,
start_time: drum.start_time,
pitch_offset: drum.pitch_offset + shift as f32,
velocity: drum.velocity,
spatial_position: drum.spatial_position,
}));
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Stretch pattern timing by a factor
///
/// Multiplies all note start times and durations within the pattern by the given factor.
/// Values > 1.0 slow down the pattern, values < 1.0 speed it up.
///
/// # Arguments
/// * `factor` - Time multiplication factor (e.g., 2.0 = half speed, 0.5 = double speed)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Original pattern at normal speed
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25);
///
/// // Same pattern at half speed (twice as long)
/// comp.track("slow")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .stretch(2.0);
///
/// // Same pattern at double speed (half duration)
/// comp.track("fast")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .stretch(0.5);
/// ```
pub fn stretch(mut self, factor: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || factor <= 0.0 || (factor - 1.0).abs() < 0.001 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Stretch all events in the pattern
for event in &mut self.get_track_mut().events {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
// Stretch timing relative to pattern start
let offset = note.start_time - pattern_start;
note.start_time = pattern_start + (offset * factor);
note.duration *= factor;
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
// Stretch timing relative to pattern start
let offset = drum.start_time - pattern_start;
drum.start_time = pattern_start + (offset * factor);
}
}
_ => {} // Ignore other event types
}
}
// Update cursor to reflect stretched duration
self.cursor = pattern_start + (pattern_duration * factor);
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Compress pattern to fit within a specific duration
///
/// Ergonomic wrapper around `.stretch()` - instead of calculating ratios manually,
/// simply specify the target duration and the pattern will be stretched to fit.
///
/// # Arguments
/// * `target_duration` - Desired duration in beats (e.g., 1.0 = one beat, 2.5 = two and a half beats)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Pattern naturally takes 0.75 beats
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .compress(0.5); // Now fits in exactly 0.5 beats
///
/// // Compress multiple notes into 1 beat
/// comp.track("fast")
/// .pattern_start()
/// .notes(&[C4, D4, E4, F4, G4], 0.5) // Naturally 2.5 beats
/// .compress(1.0); // Now exactly 1 beat
/// ```
pub fn compress(self, target_duration: f32) -> Self {
let current_duration = self.cursor - self.pattern_start;
if current_duration <= 0.0 || target_duration <= 0.0 {
return self;
}
// Calculate stretch factor to reach target duration
let factor = target_duration / current_duration;
// Reuse stretch implementation
self.stretch(factor)
}
/// Quantize note timings to a rhythmic grid
///
/// Snaps all note start times to the nearest grid position, useful for cleaning up
/// timing after humanization or ensuring tight rhythmic accuracy.
///
/// # Arguments
/// * `grid` - Grid size in beats (e.g., 0.25 = 16th notes, 0.5 = 8th notes, 1.0 = quarter notes)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Humanized pattern with timing variations
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .humanize(0.05, 0.1) // Add timing jitter
/// .quantize(0.25); // Snap back to 16th note grid
///
/// // Snap to 8th note grid (less strict)
/// comp.track("loose")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .quantize(0.5); // 8th note grid
/// ```
pub fn quantize(mut self, grid: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || grid <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Quantize all events in the pattern
for event in &mut self.get_track_mut().events {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
// Quantize to nearest grid position
let offset = note.start_time - pattern_start;
let quantized_offset = (offset / grid).round() * grid;
note.start_time = pattern_start + quantized_offset;
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
// Quantize to nearest grid position
let offset = drum.start_time - pattern_start;
let quantized_offset = (offset / grid).round() * grid;
drum.start_time = pattern_start + quantized_offset;
}
}
_ => {} // Ignore other event types
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Create a palindrome - pattern plays forward then backward
///
/// Mirrors the pattern by appending a reversed copy. Creates symmetrical musical phrases
/// that return to the starting point. Timing is reversed but pitches play in reverse order.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Original: C4, E4, G4
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .palindrome(); // Becomes: C4, E4, G4, G4, E4, C4
///
/// // Great for creating symmetrical phrases
/// comp.track("symmetrical")
/// .pattern_start()
/// .notes(&[C4, D4, E4, F4], 0.25)
/// .palindrome(); // → C4, D4, E4, F4, F4, E4, D4, C4
/// ```
pub fn palindrome(mut self) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect all events in the pattern
let mut events_to_mirror: Vec<AudioEvent> = Vec::new();
for event in &self.get_track_mut().events {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
events_to_mirror.push(event.clone());
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
events_to_mirror.push(event.clone());
}
}
_ => {}
}
}
if events_to_mirror.is_empty() {
return self;
}
// Reverse and append the mirrored events
for event in events_to_mirror.iter().rev() {
let mut mirrored_event = event.clone();
// Calculate mirrored timing (relative to end of original pattern)
let original_offset = match event {
AudioEvent::Note(note) => note.start_time - pattern_start,
AudioEvent::Drum(drum) => drum.start_time - pattern_start,
_ => 0.0,
};
let mirrored_offset = pattern_duration - original_offset;
let new_start_time = cursor + mirrored_offset;
match &mut mirrored_event {
AudioEvent::Note(note) => {
// Position reversed notes after the original pattern
note.start_time = new_start_time - note.duration;
}
AudioEvent::Drum(drum) => {
drum.start_time = new_start_time;
}
_ => {}
}
self.get_track_mut().events.push(mirrored_event);
}
// Update cursor to reflect doubled length
self.cursor = cursor + pattern_duration;
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Add random stuttering (glitch effect) - rapidly repeat notes
///
/// Randomly triggers rapid repetitions of notes, creating glitchy stuttering effects
/// popular in electronic music and trap production.
///
/// # Arguments
/// * `probability` - Chance (0.0-1.0) that each note will stutter
/// * `repeats` - Number of rapid repeats to create (typically 2-8)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // 50% chance each note stutters 4 times
/// comp.track("glitch")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.5)
/// .stutter(0.5, 4); // Random notes become: C-C-C-C or E-E-E-E (fast)
///
/// // Trap hi-hat rolls
/// comp.track("hats")
/// .pattern_start()
/// .notes(&[C4, C4, C4, C4], 0.25)
/// .stutter(0.25, 8); // Occasional 8x rolls
/// ```
pub fn stutter(mut self, probability: f32, repeats: usize) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || probability <= 0.0 || repeats == 0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
use rand::Rng;
let mut rng = rand::rng();
// Collect events that will stutter
let mut stutter_events: Vec<(usize, AudioEvent, f32)> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
let should_stutter = rng.random_range(0.0..1.0) < probability;
if !should_stutter {
continue;
}
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
stutter_events.push((idx, event.clone(), note.duration));
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
// Drums don't have duration, use small interval
stutter_events.push((idx, event.clone(), 0.05));
}
}
_ => {}
}
}
// Add stutter repeats
for (_idx, event, base_duration) in stutter_events {
// Calculate rapid repeat interval (divide duration by number of repeats)
let stutter_interval = base_duration / repeats as f32;
for i in 1..=repeats {
let mut stutter_copy = event.clone();
let offset = stutter_interval * i as f32;
match &mut stutter_copy {
AudioEvent::Note(note) => {
note.start_time += offset;
note.duration = stutter_interval * 0.8; // Slightly shorter for separation
}
AudioEvent::Drum(drum) => {
drum.start_time += offset;
}
_ => {}
}
self.get_track_mut().events.push(stutter_copy);
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Stutter every Nth note (deterministic glitch effect)
///
/// Applies stuttering to every Nth note in the pattern, creating rhythmic glitch effects.
/// Unlike `.stutter()` which is random, this version is predictable and great for
/// creating consistent rhythmic patterns like trap hi-hat rolls.
///
/// # Arguments
/// * `nth` - Which note to stutter (e.g., 4 = every 4th note)
/// * `repeats` - Number of rapid repeats to create
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Every 4th note stutters 8 times (trap hi-hat roll)
/// comp.track("hats")
/// .pattern_start()
/// .notes(&[C4, C4, C4, C4, C4, C4, C4, C4], 0.25)
/// .stutter_every(4, 8); // 4th and 8th notes roll
///
/// // Kick drum pattern with stutter on 2 and 4
/// comp.track("kicks")
/// .pattern_start()
/// .notes(&[C2, C2, C2, C2], 0.5)
/// .stutter_every(2, 4); // 2nd and 4th kicks stutter
/// ```
pub fn stutter_every(mut self, nth: usize, repeats: usize) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || nth == 0 || repeats == 0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect events to stutter (every nth event)
let mut stutter_events: Vec<(usize, AudioEvent, f32)> = Vec::new();
let mut note_count = 0;
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
note_count += 1;
if note_count % nth == 0 {
stutter_events.push((idx, event.clone(), note.duration));
}
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
note_count += 1;
if note_count % nth == 0 {
stutter_events.push((idx, event.clone(), 0.05));
}
}
}
_ => {}
}
}
// Add stutter repeats
for (_idx, event, base_duration) in stutter_events {
let stutter_interval = base_duration / repeats as f32;
for i in 1..=repeats {
let mut stutter_copy = event.clone();
let offset = stutter_interval * i as f32;
match &mut stutter_copy {
AudioEvent::Note(note) => {
note.start_time += offset;
note.duration = stutter_interval * 0.8;
}
AudioEvent::Drum(drum) => {
drum.start_time += offset;
}
_ => {}
}
self.get_track_mut().events.push(stutter_copy);
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Break each note into micro-fragments (granularize)
///
/// Splits each note into multiple tiny notes across its duration, creating granular textures.
/// Great for creating shimmering effects, especially when combined with other transformations
/// like `.mutate()` or `.shuffle()`.
///
/// # Arguments
/// * `divisions` - Number of fragments to create per note (typically 4-50)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Break each note into 10 grains
/// comp.track("texture")
/// .pattern_start()
/// .note(&[C4], 1.0)
/// .granularize(10); // → 10 tiny 0.1s notes
///
/// // Granular with pitch variation
/// comp.track("shimmer")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.5)
/// .granularize(20) // Break into 20 grains each
/// .mutate(3); // Add pitch variation to grains
/// ```
pub fn granularize(mut self, divisions: usize) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || divisions == 0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect notes to granularize and remove originals
let mut notes_to_granularize: Vec<AudioEvent> = Vec::new();
let mut indices_to_remove: Vec<usize> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
// Only granularize notes, not drums
if let AudioEvent::Note(note) = event {
if note.start_time >= pattern_start && note.start_time < cursor {
notes_to_granularize.push(event.clone());
indices_to_remove.push(idx);
}
}
}
// Remove original notes in reverse order to maintain indices
for &idx in indices_to_remove.iter().rev() {
self.get_track_mut().events.remove(idx);
}
// Create granularized versions
for event in notes_to_granularize {
if let AudioEvent::Note(note) = event {
let grain_duration = note.duration / divisions as f32;
for i in 0..divisions {
let mut grain = note.clone();
grain.start_time = note.start_time + (grain_duration * i as f32);
grain.duration = grain_duration * 0.9; // Slight gap between grains
self.get_track_mut().events.push(AudioEvent::Note(grain));
}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Snap all note pitches to the nearest note in a given scale
///
/// Quantizes pitch (not time) by snapping each note frequency to the closest
/// frequency in the provided scale. Great for forcing melodies into a specific
/// tonality or correcting out-of-scale notes.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Chromatic melody snapped to C major pentatonic (C, D, E, G, A)
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, CS4, D4, DS4, E4, F4, FS4, G4, GS4, A4], 0.25)
/// .magnetize(&[C4, D4, E4, G4, A4]); // Snap to pentatonic
/// ```
pub fn magnetize(mut self, scale_notes: &[f32]) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || scale_notes.is_empty() {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Snap each note frequency to nearest scale note
for event in &mut self.get_track_mut().events {
if let AudioEvent::Note(note) = event {
if note.start_time >= pattern_start && note.start_time < cursor {
for i in 0..note.num_freqs {
let original_freq = note.frequencies[i];
// Find nearest frequency in scale
let mut closest_freq = scale_notes[0];
let mut min_distance = (original_freq / closest_freq).log2().abs();
for &scale_freq in scale_notes.iter().skip(1) {
let distance = (original_freq / scale_freq).log2().abs();
if distance < min_distance {
min_distance = distance;
closest_freq = scale_freq;
}
}
note.frequencies[i] = closest_freq;
}
}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Apply gravitational pull toward or away from a center pitch
///
/// Notes are attracted (positive strength) or repelled (negative strength)
/// from a center frequency. The effect is proportional to distance - notes
/// closer to the center are affected more strongly.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C3, E4, G5, C6], 0.5)
/// .gravity(C4, 0.3); // Pull toward middle C (30% of distance)
/// ```
pub fn gravity(mut self, center_pitch: f32, strength: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || strength == 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Apply gravitational force to each note and drum
for event in &mut self.get_track_mut().events {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
for i in 0..note.num_freqs {
let original_freq = note.frequencies[i];
// Calculate distance in semitones
let semitone_distance = 12.0 * (original_freq / center_pitch).log2();
// Apply gravity - move by (strength * distance) toward center
let pull_semitones = -semitone_distance * strength;
let shift_ratio = 2.0_f32.powf(pull_semitones / 12.0);
note.frequencies[i] = original_freq * shift_ratio;
}
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
// Pull drum pitch_offset toward 0 (default pitch)
drum.pitch_offset -= drum.pitch_offset * strength;
}
}
_ => {}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Create cascading effects where each note influences subsequent notes
///
/// Each note creates a "ripple" that affects the timing and pitch of following
/// notes. The effect decays over time. Positive intensity pushes notes forward
/// in time and up in pitch, negative pulls them back and down.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, C4, C4, C4, C4], 0.25)
/// .ripple(0.02); // Each note pushes the next one slightly
/// ```
pub fn ripple(mut self, intensity: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || intensity == 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect all events (notes and drums) in time order
#[derive(Clone)]
enum EventType {
Note { num_freqs: usize },
Drum,
}
let mut event_data: Vec<(usize, f32, EventType)> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
event_data.push((idx, note.start_time, EventType::Note { num_freqs: note.num_freqs }));
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
event_data.push((idx, drum.start_time, EventType::Drum));
}
}
_ => {}
}
}
// Sort by time
event_data.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
// Apply cascading ripple effects
let mut accumulated_time_shift = 0.0;
let mut accumulated_pitch_shift = 0.0;
let decay = 0.7; // Each ripple decays to 70% of previous
for (i, (idx, _original_time, event_type)) in event_data.iter().enumerate() {
if i > 0 {
// Apply accumulated effects from previous events
match &self.get_track_mut().events[*idx] {
AudioEvent::Note(_) => {
if let AudioEvent::Note(note) = &mut self.get_track_mut().events[*idx] {
// Apply timing shift
note.start_time += accumulated_time_shift;
// Apply pitch shift
let pitch_shift_ratio = 2.0_f32.powf(accumulated_pitch_shift / 12.0);
if let EventType::Note { num_freqs } = event_type {
for j in 0..*num_freqs {
note.frequencies[j] *= pitch_shift_ratio;
}
}
}
}
AudioEvent::Drum(_) => {
if let AudioEvent::Drum(drum) = &mut self.get_track_mut().events[*idx] {
// Apply timing shift
drum.start_time += accumulated_time_shift;
// Apply pitch shift to pitch_offset
drum.pitch_offset += accumulated_pitch_shift;
}
}
_ => {}
}
}
// Add this event's contribution to the ripple (decayed)
accumulated_time_shift = (accumulated_time_shift + intensity) * decay;
accumulated_pitch_shift = (accumulated_pitch_shift + intensity * 2.0) * decay;
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Shuffle pitches in random order (keeps timing)
///
/// Randomly reorders the pitch sequence while maintaining the original timing.
/// Each call produces a different random ordering.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Original: C4, E4, G4, C5
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .shuffle(); // Result: random order like G4, C4, C5, E4
/// ```
pub fn shuffle(mut self) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect note events in the pattern
let mut note_events: Vec<(usize, [f32; 8], usize)> = Vec::new();
// Collect drum events in the pattern
let mut drum_events: Vec<(usize, f32)> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
note_events.push((idx, note.frequencies, note.num_freqs));
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
drum_events.push((idx, drum.pitch_offset));
}
}
_ => {}
}
}
use rand::Rng;
let mut rng = rand::rng();
// Shuffle note frequencies
if !note_events.is_empty() {
let mut freqs: Vec<([f32; 8], usize)> =
note_events.iter().map(|(_, f, n)| (*f, *n)).collect();
// Shuffle using Fisher-Yates
for i in (1..freqs.len()).rev() {
let j = rng.random_range(0..=i);
freqs.swap(i, j);
}
// Apply shuffled frequencies back to the notes
for (i, (event_idx, _, _)) in note_events.iter().enumerate() {
if let AudioEvent::Note(note) = &mut self.get_track_mut().events[*event_idx] {
note.frequencies = freqs[i].0;
note.num_freqs = freqs[i].1;
}
}
}
// Shuffle drum pitch offsets
if !drum_events.is_empty() {
let mut pitch_offsets: Vec<f32> = drum_events.iter().map(|(_, p)| *p).collect();
// Shuffle using Fisher-Yates
for i in (1..pitch_offsets.len()).rev() {
let j = rng.random_range(0..=i);
pitch_offsets.swap(i, j);
}
// Apply shuffled pitch offsets back to drums
for (i, (event_idx, _)) in drum_events.iter().enumerate() {
if let AudioEvent::Drum(drum) = &mut self.get_track_mut().events[*event_idx] {
drum.pitch_offset = pitch_offsets[i];
}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Randomly remove notes from the pattern
///
/// Reduces note density by probabilistically keeping or removing each note.
/// Great for creating space or variations with less density.
///
/// # Arguments
/// * `keep_probability` - Chance to keep each note (0.0 = remove all, 1.0 = keep all)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("hihat")
/// .pattern_start()
/// .notes(&[C4, C4, C4, C4, C4, C4, C4, C4], 0.125)
/// .thin(0.5); // Keep ~50% of notes
///
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5, E4, G4], 0.25)
/// .thin(0.7); // Keep ~70% of notes
/// ```
pub fn thin(mut self, keep_probability: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let keep_probability = keep_probability.clamp(0.0, 1.0);
// If probability is 1.0, keep everything
if keep_probability >= 1.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Remove notes based on probability
use rand::Rng;
let mut rng = rand::rng();
self.get_track_mut().events.retain(|event| {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
// Randomly decide to keep or remove
rng.random_range(0.0..1.0) < keep_probability
} else {
true // Keep notes outside pattern
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
// Randomly decide to keep or remove
rng.random_range(0.0..1.0) < keep_probability
} else {
true // Keep drums outside pattern
}
}
_ => true, // Keep other events (samples, tempo changes, etc.)
}
});
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Retrograde: reverse the melodic contour (pitches backwards, timing forward)
///
/// Classic compositional technique - plays the pitch sequence in reverse order
/// while keeping the original timing. Different from `.reverse()` which reverses time.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Original: C4 at t=0, E4 at t=0.25, G4 at t=0.5
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .retrograde(); // Result: G4 at t=0, E4 at t=0.25, C4 at t=0.5
/// ```
pub fn retrograde(mut self) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect note events in the pattern
let mut note_events: Vec<(usize, [f32; 8], usize)> = Vec::new();
// Collect drum events in the pattern
let mut drum_events: Vec<(usize, f32)> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
note_events.push((idx, note.frequencies, note.num_freqs));
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
drum_events.push((idx, drum.pitch_offset));
}
}
_ => {}
}
}
// Retrograde note frequencies
if !note_events.is_empty() {
let freqs: Vec<([f32; 8], usize)> =
note_events.iter().map(|(_, f, n)| (*f, *n)).collect();
let reversed_freqs: Vec<([f32; 8], usize)> = freqs.into_iter().rev().collect();
for (i, (event_idx, _, _)) in note_events.iter().enumerate() {
if let AudioEvent::Note(note) = &mut self.get_track_mut().events[*event_idx] {
note.frequencies = reversed_freqs[i].0;
note.num_freqs = reversed_freqs[i].1;
}
}
}
// Retrograde drum pitch offsets
if !drum_events.is_empty() {
let pitch_offsets: Vec<f32> = drum_events.iter().map(|(_, p)| *p).collect();
let reversed_offsets: Vec<f32> = pitch_offsets.into_iter().rev().collect();
for (i, (event_idx, _)) in drum_events.iter().enumerate() {
if let AudioEvent::Drum(drum) = &mut self.get_track_mut().events[*event_idx] {
drum.pitch_offset = reversed_offsets[i];
}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Shift all notes in the pattern by semitones
///
/// Transposes all notes between pattern_start and current cursor.
/// Positive values shift up, negative values shift down.
///
/// # Arguments
/// * `semitones` - Number of semitones to shift (positive = up, negative = down)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.5)
/// .shift(5); // Transpose up a perfect fourth
///
/// comp.track("bass")
/// .pattern_start()
/// .notes(&[C3, G3, C4], 0.5)
/// .shift(-12); // Transpose down an octave
/// ```
pub fn shift(mut self, semitones: i32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || semitones == 0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
let shift_ratio = 2.0_f32.powf(semitones as f32 / 12.0);
// Collect events in the pattern range - shift notes, pass through drums and samples
let shifted_events: Vec<_> = self
.get_track_mut()
.events
.iter()
.filter_map(|event| {
let event_time = event.start_time();
if event_time >= pattern_start && event_time < cursor {
match event {
AudioEvent::Note(note) => {
// Shift each frequency in the note/chord
let mut shifted_freqs = [0.0f32; 8];
for (i, freq) in
shifted_freqs.iter_mut().enumerate().take(note.num_freqs)
{
*freq = note.frequencies[i] * shift_ratio;
}
Some(AudioEvent::Note(crate::track::NoteEvent {
frequencies: shifted_freqs,
num_freqs: note.num_freqs,
start_time: note.start_time,
duration: note.duration,
waveform: note.waveform,
envelope: note.envelope,
filter_envelope: note.filter_envelope,
fm_params: note.fm_params,
pitch_bend_semitones: note.pitch_bend_semitones,
custom_wavetable: note.custom_wavetable.clone(),
velocity: note.velocity,
spatial_position: note.spatial_position,
}))
}
AudioEvent::Drum(drum) => {
// Shift drum pitch by adding to pitch_offset
Some(AudioEvent::Drum(crate::track::DrumEvent {
drum_type: drum.drum_type,
start_time: drum.start_time,
pitch_offset: drum.pitch_offset + semitones as f32,
velocity: drum.velocity,
spatial_position: drum.spatial_position,
}))
}
AudioEvent::Sample(_)
| AudioEvent::TempoChange(_)
| AudioEvent::TimeSignature(_)
| AudioEvent::KeySignature(_) => {
// Pass through samples, tempo changes, and time signatures unchanged
Some(event.clone())
}
}
} else {
None
}
})
.collect();
// Remove original pattern events
let pattern_start = self.pattern_start;
let cursor = self.cursor;
self.get_track_mut().events.retain(|event| {
let event_time = match event {
AudioEvent::Note(note) => note.start_time,
AudioEvent::Drum(drum) => drum.start_time,
AudioEvent::Sample(sample) => sample.start_time,
AudioEvent::TempoChange(tempo) => tempo.start_time,
AudioEvent::TimeSignature(time_sig) => time_sig.start_time,
AudioEvent::KeySignature(key_sig) => key_sig.start_time,
};
event_time < pattern_start || event_time >= cursor
});
// Add shifted events
self.get_track_mut().events.extend(shifted_events);
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Invert the pattern between pattern_start and current cursor
///
/// Musical inversion mirrors pitches around a center point (axis).
/// If a note was 2 semitones above the axis, it becomes 2 semitones below.
///
/// # Arguments
/// * `axis_freq` - The frequency to mirror around (typically the tonic)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4, F4], 0.5)
/// .invert(C4); // Mirror around C4
/// ```
pub fn invert(mut self, axis_freq: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect events in the pattern range - invert notes, pass through drums and samples
let inverted_events: Vec<_> = self
.get_track_mut()
.events
.iter()
.filter_map(|event| {
let event_time = event.start_time();
if event_time >= pattern_start && event_time < cursor {
match event {
AudioEvent::Note(note) => {
// Invert each frequency in the note/chord
let mut inverted_freqs = [0.0f32; 8];
for (i, inv_freq) in
inverted_freqs.iter_mut().enumerate().take(note.num_freqs)
{
let freq = note.frequencies[i];
// Calculate distance from axis in semitones
let semitones_from_axis = 12.0 * (freq / axis_freq).log2();
// Mirror it
let inverted_semitones = -semitones_from_axis;
// Convert back to frequency
*inv_freq = axis_freq * 2.0_f32.powf(inverted_semitones / 12.0);
}
Some(AudioEvent::Note(crate::track::NoteEvent {
frequencies: inverted_freqs,
num_freqs: note.num_freqs,
start_time: note.start_time,
duration: note.duration,
waveform: note.waveform,
envelope: note.envelope,
filter_envelope: note.filter_envelope,
fm_params: note.fm_params,
pitch_bend_semitones: note.pitch_bend_semitones,
custom_wavetable: note.custom_wavetable.clone(),
velocity: note.velocity,
spatial_position: note.spatial_position,
}))
}
AudioEvent::Drum(drum) => {
// Invert drum pitch_offset around 0 (default pitch)
Some(AudioEvent::Drum(crate::track::DrumEvent {
drum_type: drum.drum_type,
start_time: drum.start_time,
pitch_offset: -drum.pitch_offset,
velocity: drum.velocity,
spatial_position: drum.spatial_position,
}))
}
AudioEvent::Sample(_)
| AudioEvent::TempoChange(_)
| AudioEvent::TimeSignature(_)
| AudioEvent::KeySignature(_) => {
// Pass through samples, tempo changes, and time signatures unchanged
Some(event.clone())
}
}
} else {
None
}
})
.collect();
// Remove original pattern events
let pattern_start = self.pattern_start;
let cursor = self.cursor;
self.get_track_mut().events.retain(|event| {
let event_time = match event {
AudioEvent::Note(note) => note.start_time,
AudioEvent::Drum(drum) => drum.start_time,
AudioEvent::Sample(sample) => sample.start_time,
AudioEvent::TempoChange(tempo) => tempo.start_time,
AudioEvent::TimeSignature(time_sig) => time_sig.start_time,
AudioEvent::KeySignature(key_sig) => key_sig.start_time,
};
event_time < pattern_start || event_time >= cursor
});
// Add inverted events
self.get_track_mut().events.extend(inverted_events);
self
}
/// Invert and transpose to keep the result in a reasonable range
///
/// This is a more musical version of invert that ensures inverted notes
/// stay near the original range by octave-shifting as needed.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4, F4], 0.5)
/// .invert_constrained(C4, C3, C5); // Keep between C3 and C5
/// ```
pub fn invert_constrained(mut self, axis_freq: f32, min_freq: f32, max_freq: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect and invert events, constraining to range - pass through drums and samples
let inverted_events: Vec<_> = self
.get_track_mut()
.events
.iter()
.filter_map(|event| {
let event_time = event.start_time();
if event_time >= pattern_start && event_time < cursor {
match event {
AudioEvent::Note(note) => {
let mut inverted_freqs = [0.0f32; 8];
for (i, inv_freq_slot) in
inverted_freqs.iter_mut().enumerate().take(note.num_freqs)
{
let freq = note.frequencies[i];
let semitones_from_axis = 12.0 * (freq / axis_freq).log2();
let inverted_semitones = -semitones_from_axis;
let mut inverted_freq =
axis_freq * 2.0_f32.powf(inverted_semitones / 12.0);
// Octave-shift to keep in range
while inverted_freq < min_freq {
inverted_freq *= 2.0;
}
while inverted_freq > max_freq {
inverted_freq /= 2.0;
}
*inv_freq_slot = inverted_freq;
}
Some(AudioEvent::Note(crate::track::NoteEvent {
frequencies: inverted_freqs,
num_freqs: note.num_freqs,
start_time: note.start_time,
duration: note.duration,
waveform: note.waveform,
envelope: note.envelope,
filter_envelope: note.filter_envelope,
fm_params: note.fm_params,
pitch_bend_semitones: note.pitch_bend_semitones,
custom_wavetable: note.custom_wavetable.clone(),
velocity: note.velocity,
spatial_position: note.spatial_position,
}))
}
AudioEvent::Drum(drum) => {
// Invert drum pitch_offset around 0 (constraints don't apply to drums)
Some(AudioEvent::Drum(crate::track::DrumEvent {
drum_type: drum.drum_type,
start_time: drum.start_time,
pitch_offset: -drum.pitch_offset,
velocity: drum.velocity,
spatial_position: drum.spatial_position,
}))
}
AudioEvent::Sample(_)
| AudioEvent::TempoChange(_)
| AudioEvent::TimeSignature(_)
| AudioEvent::KeySignature(_) => {
// Pass through samples, tempo changes, and time signatures unchanged
Some(event.clone())
}
}
} else {
None
}
})
.collect();
// Remove original and add inverted
let pattern_start = self.pattern_start;
let cursor = self.cursor;
self.get_track_mut().events.retain(|event| {
let event_time = match event {
AudioEvent::Note(note) => note.start_time,
AudioEvent::Drum(drum) => drum.start_time,
AudioEvent::Sample(sample) => sample.start_time,
AudioEvent::TempoChange(tempo) => tempo.start_time,
AudioEvent::TimeSignature(time_sig) => time_sig.start_time,
AudioEvent::KeySignature(key_sig) => key_sig.start_time,
};
event_time < pattern_start || event_time >= cursor
});
self.get_track_mut().events.extend(inverted_events);
self
}
/// Filter to keep only notes within frequency range
///
/// Removes all notes whose frequencies fall outside [min_freq, max_freq].
/// Useful for isolating specific frequency bands or removing unwanted ranges.
///
/// # Examples
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Keep only bass frequencies (20-200 Hz)
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C3, E3, G3, C4, E4, G4], 0.25)
/// .sieve_inclusive(20.0, 200.0); // Only bass notes remain
/// ```
pub fn sieve_inclusive(mut self, min_freq: f32, max_freq: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Filter notes to keep only those within frequency range
self.get_track_mut().events.retain(|event| {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
// Check if any frequency in the note is within range
(0..note.num_freqs).any(|i| {
let freq = note.frequencies[i];
freq >= min_freq && freq <= max_freq
})
} else {
true // Keep notes outside pattern
}
}
_ => true, // Keep non-note events
}
});
self
}
/// Filter to remove notes within frequency range
///
/// Removes all notes whose frequencies fall within [min_freq, max_freq].
/// Useful for removing specific frequency bands (e.g., muddy midrange).
///
/// # Examples
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Remove midrange frequencies (200-800 Hz)
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C3, E3, G3, C4, E4, G4], 0.25)
/// .sieve_exclusive(200.0, 800.0); // Low and high notes remain
/// ```
pub fn sieve_exclusive(mut self, min_freq: f32, max_freq: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Filter notes to remove those within frequency range
self.get_track_mut().events.retain(|event| {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
// Keep note only if ALL frequencies are outside range
(0..note.num_freqs).all(|i| {
let freq = note.frequencies[i];
freq < min_freq || freq > max_freq
})
} else {
true // Keep notes outside pattern
}
}
_ => true, // Keep non-note events
}
});
self
}
/// Collapse all notes in the pattern into a single chord
///
/// Takes all notes from the pattern and plays them simultaneously as a chord.
/// Useful for converting melodies/arpeggios into harmonic blocks.
///
/// # Examples
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Turn arpeggio into chord
/// comp.track("arp_to_chord")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .group(2.0); // All notes play together for 2 seconds
/// ```
pub fn group(mut self, duration: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect all note frequencies from the pattern
let mut all_freqs = Vec::new();
let mut waveform = Waveform::Sine;
let mut envelope = Envelope::default();
let mut pitch_bend = 0.0;
let mut velocity = 1.0;
for event in &self.get_track_mut().events {
if let AudioEvent::Note(note) = event {
if note.start_time >= pattern_start && note.start_time < cursor {
// Collect all frequencies from this note
for i in 0..note.num_freqs {
all_freqs.push(note.frequencies[i]);
}
// Use properties from first note
if all_freqs.len() <= note.num_freqs {
waveform = note.waveform;
envelope = note.envelope;
pitch_bend = note.pitch_bend_semitones;
velocity = note.velocity;
}
}
}
}
if all_freqs.is_empty() {
return self;
}
// Remove all notes from the pattern
self.get_track_mut().events.retain(|event| {
match event {
AudioEvent::Note(note) => {
note.start_time < pattern_start || note.start_time >= cursor
}
_ => true, // Keep non-note events
}
});
// Add a single chord with all frequencies
let mut freq_array = [0.0f32; 8];
let num_freqs = all_freqs.len().min(8);
for (i, &freq) in all_freqs.iter().take(8).enumerate() {
freq_array[i] = freq;
}
let chord_event = AudioEvent::Note(crate::track::NoteEvent {
frequencies: freq_array,
num_freqs,
start_time: pattern_start,
duration,
waveform,
envelope,
filter_envelope: crate::synthesis::filter_envelope::FilterEnvelope::default(),
fm_params: crate::synthesis::fm_synthesis::FMParams::default(),
pitch_bend_semitones: pitch_bend,
custom_wavetable: None,
velocity,
spatial_position: None,
});
self.get_track_mut().events.push(chord_event);
// Update cursor to after the chord
self.cursor = pattern_start + duration;
self
}
/// Duplicate all events in the pattern
///
/// Creates a copy of all events and appends them after the pattern.
/// Unlike `.repeat()`, this allows transforms to be applied to the duplicated events.
///
/// # Examples
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Create melody with octave doubling
/// comp.track("harmony")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .duplicate()
/// .transform(|t| t.shift(12)); // Add octave above
/// ```
pub fn duplicate(mut self) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect all events in the pattern
let duplicated_events: Vec<_> = self
.get_track_mut()
.events
.iter()
.filter_map(|event| {
let event_time = event.start_time();
if event_time >= pattern_start && event_time < cursor {
// Clone and shift to end of pattern
let mut cloned = event.clone();
match &mut cloned {
AudioEvent::Note(note) => {
note.start_time = note.start_time - pattern_start + cursor;
}
AudioEvent::Drum(drum) => {
drum.start_time = drum.start_time - pattern_start + cursor;
}
AudioEvent::Sample(sample) => {
sample.start_time = sample.start_time - pattern_start + cursor;
}
AudioEvent::TempoChange(tempo) => {
tempo.start_time = tempo.start_time - pattern_start + cursor;
}
AudioEvent::TimeSignature(time_sig) => {
time_sig.start_time = time_sig.start_time - pattern_start + cursor;
}
AudioEvent::KeySignature(key_sig) => {
key_sig.start_time = key_sig.start_time - pattern_start + cursor;
}
}
Some(cloned)
} else {
None
}
})
.collect();
// Add duplicated events
self.get_track_mut().events.extend(duplicated_events);
// Update cursor and pattern_start
// Set pattern_start to beginning of duplicated section so transforms only affect duplicated notes
self.pattern_start = cursor;
self.cursor = cursor + pattern_duration;
self
}
/// Dilate (expand/compress) the pitch range around its center
///
/// Adjusts the distance of all pitches from the pattern's center pitch.
/// - `factor < 1.0` compresses toward center (0.5 = half range)
/// - `factor = 1.0` no change
/// - `factor > 1.0` expands from center (2.0 = double range)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Compress range to 70% of original
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C3, C5, C2, C6], 0.25)
/// .range_dilation(0.7);
///
/// // Expand range to 150% of original
/// comp.track("wide")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .range_dilation(1.5);
/// ```
pub fn range_dilation(mut self, factor: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || factor == 1.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Find center pitch (geometric mean for notes, arithmetic mean for drum offsets)
let mut sum_log_freq = 0.0;
let mut note_count = 0;
let mut sum_drum_offset = 0.0;
let mut drum_count = 0;
for event in &self.get_track_mut().events {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
for i in 0..note.num_freqs {
sum_log_freq += note.frequencies[i].ln();
note_count += 1;
}
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
sum_drum_offset += drum.pitch_offset;
drum_count += 1;
}
}
_ => {}
}
}
if note_count == 0 && drum_count == 0 {
return self;
}
let center_pitch = if note_count > 0 {
(sum_log_freq / note_count as f32).exp()
} else {
440.0 // Default if no notes
};
let center_drum_offset = if drum_count > 0 {
sum_drum_offset / drum_count as f32
} else {
0.0
};
// Apply dilation
for event in &mut self.get_track_mut().events {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
for i in 0..note.num_freqs {
let original_freq = note.frequencies[i];
// Calculate distance from center in semitones
let semitone_distance = 12.0 * (original_freq / center_pitch).log2();
// Scale distance by factor
let new_distance = semitone_distance * factor;
let shift_ratio = 2.0_f32.powf(new_distance / 12.0);
note.frequencies[i] = center_pitch * shift_ratio;
}
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
// Scale drum pitch_offset distance from center by factor
let distance = drum.pitch_offset - center_drum_offset;
drum.pitch_offset = center_drum_offset + distance * factor;
}
}
_ => {}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Shape melodic contour by scaling interval sizes
///
/// Modifies the size of melodic intervals (jumps between consecutive notes).
/// - `factor < 1.0` smooths (reduces interval jumps)
/// - `factor = 1.0` no change
/// - `factor > 1.0` exaggerates (increases interval jumps)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Smooth out large interval jumps
/// comp.track("smooth")
/// .pattern_start()
/// .notes(&[C4, C6, C3, C5], 0.25)
/// .shape_contour(0.5); // 50% of original intervals
///
/// // Exaggerate melodic motion
/// comp.track("dramatic")
/// .pattern_start()
/// .notes(&[C4, D4, E4, F4], 0.25)
/// .shape_contour(2.0); // Double the intervals
/// ```
pub fn shape_contour(mut self, factor: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || factor == 1.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect note and drum events in time order
let mut note_refs: Vec<(f32, usize)> = Vec::new();
let mut drum_refs: Vec<(f32, usize)> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
match event {
AudioEvent::Note(note) => {
if note.start_time >= pattern_start && note.start_time < cursor {
note_refs.push((note.start_time, idx));
}
}
AudioEvent::Drum(drum) => {
if drum.start_time >= pattern_start && drum.start_time < cursor {
drum_refs.push((drum.start_time, idx));
}
}
_ => {}
}
}
// Sort by time
note_refs.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
drum_refs.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
// Shape note intervals relative to first note
if note_refs.len() >= 2 {
let first_idx = note_refs[0].1;
let anchor_freq = if let AudioEvent::Note(note) = &self.get_track_mut().events[first_idx] {
note.frequencies[0]
} else {
440.0
};
for &(_, note_idx) in note_refs.iter().skip(1) {
if let AudioEvent::Note(note) = &mut self.get_track_mut().events[note_idx] {
for j in 0..note.num_freqs {
let original_freq = note.frequencies[j];
// Calculate interval from anchor in semitones
let semitone_interval = 12.0 * (original_freq / anchor_freq).log2();
// Scale interval by factor
let new_interval = semitone_interval * factor;
let shift_ratio = 2.0_f32.powf(new_interval / 12.0);
note.frequencies[j] = anchor_freq * shift_ratio;
}
}
}
}
// Shape drum pitch_offset intervals relative to first drum
if drum_refs.len() >= 2 {
let first_idx = drum_refs[0].1;
let anchor_offset = if let AudioEvent::Drum(drum) = &self.get_track_mut().events[first_idx] {
drum.pitch_offset
} else {
0.0
};
for &(_, drum_idx) in drum_refs.iter().skip(1) {
if let AudioEvent::Drum(drum) = &mut self.get_track_mut().events[drum_idx] {
// Calculate interval from anchor
let interval = drum.pitch_offset - anchor_offset;
// Scale interval by factor
drum.pitch_offset = anchor_offset + interval * factor;
}
}
}
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Create echo/delay trail of the pattern
///
/// Duplicates the pattern multiple times with time delay and volume decay.
///
/// # Arguments
/// * `delay` - Time between echoes in seconds
/// * `repeats` - Number of echo repetitions
/// * `decay` - Volume reduction per echo (0.0-1.0)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Create 3 echoes, 0.5s apart, each 60% volume of previous
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, E4, G4], 0.25)
/// .echo(0.5, 3, 0.6);
/// ```
pub fn echo(mut self, delay: f32, repeats: usize, decay: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || repeats == 0 || delay <= 0.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect original events
let original_events: Vec<AudioEvent> = self
.get_track_mut()
.events
.iter()
.filter(|event| {
let start_time = match event {
AudioEvent::Note(n) => n.start_time,
AudioEvent::Drum(d) => d.start_time,
AudioEvent::Sample(s) => s.start_time,
_ => return false,
};
start_time >= pattern_start && start_time < cursor
})
.cloned()
.collect();
// Create echoes
for repeat in 1..=repeats {
let time_offset = delay * repeat as f32;
let volume_scale = decay.powi(repeat as i32);
for event in &original_events {
let mut echoed_event = event.clone();
match &mut echoed_event {
AudioEvent::Note(note) => {
note.start_time += time_offset;
note.velocity *= volume_scale;
}
AudioEvent::Drum(drum) => {
drum.start_time += time_offset;
// Drums don't have velocity, decay is implicit
}
AudioEvent::Sample(sample) => {
sample.start_time += time_offset;
sample.volume *= volume_scale;
}
_ => {}
}
self.get_track_mut().events.push(echoed_event);
}
}
// Update cursor to end of last echo
let total_echo_duration = delay * repeats as f32;
self.cursor = cursor + total_echo_duration;
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Apply gradual tempo change (accelerando/ritardando) across pattern
///
/// Progressively adjusts note spacing to create tempo acceleration or deceleration.
/// - `end_factor < 1.0` ritardando (slow down - notes spread apart)
/// - `end_factor = 1.0` no change (constant tempo)
/// - `end_factor > 1.0` accelerando (speed up - notes compress together)
///
/// # Arguments
/// * `end_factor` - Target tempo multiplier at end of pattern
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Ritardando - slow down to 60% of original tempo
/// comp.track("slow")
/// .pattern_start()
/// .notes(&[C4, D4, E4, F4, G4, A4, B4, C5], 0.25)
/// .tempo_curve(0.6);
///
/// // Accelerando - speed up to 150% of original tempo
/// comp.track("fast")
/// .pattern_start()
/// .notes(&[C5, B4, A4, G4, F4, E4, D4, C4], 0.25)
/// .tempo_curve(1.5);
/// ```
pub fn tempo_curve(mut self, end_factor: f32) -> Self {
let pattern_duration = self.cursor - self.pattern_start;
if pattern_duration <= 0.0 || end_factor == 1.0 {
return self;
}
let pattern_start = self.pattern_start;
let cursor = self.cursor;
// Collect all events with their original relative times
let mut events_with_times: Vec<(usize, f32)> = Vec::new();
for (idx, event) in self.get_track_mut().events.iter().enumerate() {
let start_time = match event {
AudioEvent::Note(n) => n.start_time,
AudioEvent::Drum(d) => d.start_time,
AudioEvent::Sample(s) => s.start_time,
_ => continue,
};
if start_time >= pattern_start && start_time < cursor {
events_with_times.push((idx, start_time));
}
}
if events_with_times.is_empty() {
return self;
}
// Apply progressive time scaling
// Each event's position gets scaled by lerp(1.0, end_factor, progress)
for (idx, original_time) in events_with_times {
let relative_time = original_time - pattern_start;
let progress = relative_time / pattern_duration; // 0.0 to 1.0
// Linear interpolation from 1.0 (start) to end_factor (end)
let time_scale = 1.0 + (end_factor - 1.0) * progress;
let new_relative_time = relative_time * time_scale;
let new_time = pattern_start + new_relative_time;
// Update event timing
match &mut self.get_track_mut().events[idx] {
AudioEvent::Note(note) => note.start_time = new_time,
AudioEvent::Drum(drum) => drum.start_time = new_time,
AudioEvent::Sample(sample) => sample.start_time = new_time,
_ => {}
}
}
// Recalculate pattern end time based on last event
let new_end_time = self
.get_track_mut()
.events
.iter()
.filter_map(|event| match event {
AudioEvent::Note(n) if n.start_time >= pattern_start => Some(n.start_time),
AudioEvent::Drum(d) if d.start_time >= pattern_start => Some(d.start_time),
AudioEvent::Sample(s) if s.start_time >= pattern_start => Some(s.start_time),
_ => None,
})
.max_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap_or(cursor);
self.cursor = new_end_time.max(pattern_start);
self.get_track_mut().invalidate_time_cache();
self.update_section_duration();
self
}
/// Apply a velocity ramp (crescendo) across the pattern
///
/// Linearly interpolates velocity from `start_velocity` to `end_velocity`
/// based on each event's position in the pattern. Works on both notes and drums.
///
/// # Arguments
/// * `start_velocity` - Velocity at the beginning of the pattern (0.0-1.0)
/// * `end_velocity` - Velocity at the end of the pattern (0.0-1.0)
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Crescendo on a melodic phrase
/// comp.track("strings")
/// .pattern_start()
/// .notes(&[C4, D4, E4, F4, G4, A4, B4, C5], 0.25)
/// .crescendo(0.3, 1.0); // Build from soft to loud
/// ```
pub fn crescendo(self, start_velocity: f32, end_velocity: f32) -> Self {
self.velocity_ramp(start_velocity, end_velocity)
}
/// Apply a velocity ramp (decrescendo) across the pattern
///
/// Convenience method that's the same as `crescendo` but named for clarity
/// when going from loud to soft.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Decrescendo - fade out
/// comp.track("piano")
/// .pattern_start()
/// .notes(&[C5, B4, A4, G4, F4, E4, D4, C4], 0.25)
/// .decrescendo(1.0, 0.2); // Fade from loud to soft
/// ```
pub fn decrescendo(self, start_velocity: f32, end_velocity: f32) -> Self {
self.velocity_ramp(start_velocity, end_velocity)
}
/// Apply a velocity ramp across the pattern
///
/// Core implementation for crescendo/decrescendo. Linearly interpolates
/// velocity based on each event's temporal position in the pattern.
///
/// # Arguments
/// * `start_velocity` - Velocity at pattern start (0.0-1.0)
/// * `end_velocity` - Velocity at pattern end (0.0-1.0)
pub fn velocity_ramp(mut self, start_velocity: f32, end_velocity: f32) -> Self {
let pattern_start = self.pattern_start;
let cursor = self.cursor;
let pattern_duration = cursor - pattern_start;
if pattern_duration <= 0.0 {
return self;
}
let start_vel = start_velocity.clamp(0.0, 1.0);
let end_vel = end_velocity.clamp(0.0, 1.0);
for event in &mut self.get_track_mut().events {
let (start_time, velocity_ref) = match event {
AudioEvent::Note(note) => (note.start_time, &mut note.velocity),
AudioEvent::Drum(drum) => (drum.start_time, &mut drum.velocity),
_ => continue,
};
if start_time >= pattern_start && start_time < cursor {
// Calculate position in pattern (0.0 to 1.0)
let progress = (start_time - pattern_start) / pattern_duration;
// Linear interpolation
let new_velocity = start_vel + (end_vel - start_vel) * progress;
*velocity_ref = new_velocity;
}
}
self
}
/// Insert a gradual tempo change (tempo ramp) using TempoChangeEvents
///
/// Unlike `tempo_curve` which physically moves events, this inserts actual
/// TempoChangeEvents which are useful for MIDI export and affect all subsequent
/// music in the composition.
///
/// # Arguments
/// * `target_bpm` - Target tempo at end of the ramp
/// * `steps` - Number of tempo change events to insert
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Ritardando from 120 to 80 BPM over 4 steps
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, D4, E4, F4, G4, A4, B4, C5], 0.25)
/// .tempo_ramp(80.0, 4);
///
/// // Accelerando from 100 to 140 BPM
/// comp.track("buildup")
/// .pattern_start()
/// .notes(&[C4; 8], 0.25)
/// .tempo_ramp(140.0, 8);
/// ```
pub fn tempo_ramp(mut self, target_bpm: f32, steps: usize) -> Self {
if steps == 0 {
return self;
}
let pattern_start = self.pattern_start;
let pattern_duration = self.cursor - pattern_start;
if pattern_duration <= 0.0 {
return self;
}
// Get the current tempo from the composition
let start_bpm = self.composition.tempo().bpm;
let target_bpm = target_bpm.clamp(20.0, 500.0);
if (start_bpm - target_bpm).abs() < 0.01 {
return self;
}
// Insert tempo change events at evenly spaced intervals
let step_duration = pattern_duration / steps as f32;
for i in 0..steps {
let progress = (i + 1) as f32 / steps as f32;
let bpm = start_bpm + (target_bpm - start_bpm) * progress;
let time = pattern_start + step_duration * (i + 1) as f32;
self.get_track_mut()
.events
.push(crate::track::AudioEvent::TempoChange(
crate::track::TempoChangeEvent {
start_time: time,
bpm,
},
));
}
self.get_track_mut().invalidate_time_cache();
self
}
/// Convenience method for gradual slowdown (ritardando)
///
/// Inserts tempo change events to gradually slow down to the target BPM.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("ending")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.5)
/// .ritardando(80.0, 4); // Slow to 80 BPM over 4 steps
/// ```
pub fn ritardando(self, target_bpm: f32, steps: usize) -> Self {
self.tempo_ramp(target_bpm, steps)
}
/// Convenience method for gradual speedup (accelerando)
///
/// Inserts tempo change events to gradually speed up to the target BPM.
///
/// # Example
/// ```
/// # use tunes::composition::Composition;
/// # use tunes::composition::timing::Tempo;
/// # use tunes::consts::notes::*;
/// # let mut comp = Composition::new(Tempo::new(100.0));
/// comp.track("buildup")
/// .pattern_start()
/// .notes(&[C4; 8], 0.25)
/// .accelerando(140.0, 8); // Speed to 140 BPM over 8 steps
/// ```
pub fn accelerando(self, target_bpm: f32, steps: usize) -> Self {
self.tempo_ramp(target_bpm, steps)
}
/// Apply a closure to each event in the pattern with type-specific counters
///
/// This is the most flexible transform - it gives you mutable access to each
/// event along with counters for how many notes and drums have been seen.
/// This allows you to implement custom logic like "accent every 4th drum"
/// or "modify every 2nd note".
///
/// # Arguments
/// * `f` - Closure receiving (event, note_count, drum_count)
/// - `event` - `EventMut::Note` or `EventMut::Drum` with mutable access
/// - `note_count` - Running count of notes seen (1-indexed, 0 if this is a drum)
/// - `drum_count` - Running count of drums seen (1-indexed, 0 if this is a note)
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::composition::generative::transforms::EventMut;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Accent every 4th drum, every 2nd note
/// comp.track("mixed")
/// .pattern_start()
/// .notes(&[C4, E4, G4, C5], 0.25)
/// .drum(DrumType::Kick, 0.25)
/// .for_each_event(|event, note_count, drum_count| {
/// match event {
/// EventMut::Note(n) if note_count % 2 == 0 => n.velocity = 1.0,
/// EventMut::Drum(d) if drum_count % 4 == 0 => d.velocity = 1.0,
/// _ => {}
/// }
/// });
/// ```
pub fn for_each_event<F>(mut self, mut f: F) -> Self
where
F: FnMut(EventMut<'_>, usize, usize),
{
let pattern_start = self.pattern_start;
let cursor = self.cursor;
let mut note_count = 0usize;
let mut drum_count = 0usize;
for event in &mut self.get_track_mut().events {
let event_time = match event {
AudioEvent::Note(n) => n.start_time,
AudioEvent::Drum(d) => d.start_time,
_ => continue,
};
if event_time >= pattern_start && event_time < cursor {
match event {
AudioEvent::Note(n) => {
note_count += 1;
f(EventMut::Note(n), note_count, drum_count);
}
AudioEvent::Drum(d) => {
drum_count += 1;
f(EventMut::Drum(d), note_count, drum_count);
}
_ => {}
}
}
}
self
}
/// Apply a closure to every Nth note in the pattern
///
/// Convenience method for common "accent every Nth note" patterns.
/// Only counts and affects NoteEvents, drums are ignored.
///
/// # Arguments
/// * `n` - Apply to every Nth note (1 = every note, 2 = every other, etc.)
/// * `f` - Closure receiving mutable reference to NoteEvent
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Accent every 4th note
/// comp.track("melody")
/// .pattern_start()
/// .notes(&[C4, D4, E4, F4, G4, A4, B4, C5], 0.25)
/// .every_nth_note(4, |note| {
/// note.velocity = 1.0;
/// });
/// ```
pub fn every_nth_note<F>(self, n: usize, mut f: F) -> Self
where
F: FnMut(&mut NoteEvent),
{
if n == 0 {
return self;
}
self.for_each_event(|event, note_count, _| {
if let EventMut::Note(note) = event {
if note_count % n == 0 {
f(note);
}
}
})
}
/// Apply a closure to every Nth drum in the pattern
///
/// Convenience method for common "accent every Nth drum" patterns.
/// Only counts and affects DrumEvents, notes are ignored.
///
/// # Arguments
/// * `n` - Apply to every Nth drum (1 = every drum, 2 = every other, etc.)
/// * `f` - Closure receiving mutable reference to DrumEvent
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// // Accent every 4th hi-hat
/// comp.track("drums")
/// .drum_grid(16, 0.125, |g| g
/// .sound(DrumType::HiHatClosed, "x-x-x-x-x-x-x-x-"))
/// .every_nth_drum(4, |drum| {
/// drum.velocity = 1.0;
/// });
/// ```
pub fn every_nth_drum<F>(self, n: usize, mut f: F) -> Self
where
F: FnMut(&mut DrumEvent),
{
if n == 0 {
return self;
}
self.for_each_event(|event, _, drum_count| {
if let EventMut::Drum(drum) = event {
if drum_count % n == 0 {
f(drum);
}
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::composition::Composition;
use crate::composition::timing::Tempo;
use crate::consts::notes::*;
use crate::instruments::drums::DrumType;
#[test]
fn test_crescendo_notes() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("test")
.pattern_start()
.notes(&[C4, D4, E4, F4], 0.25)
.crescendo(0.2, 1.0);
let track = &comp.into_mixer().tracks()[0];
let velocities: Vec<f32> = track
.events
.iter()
.filter_map(|e| {
if let AudioEvent::Note(n) = e {
Some(n.velocity)
} else {
None
}
})
.collect();
// Should ramp from 0.2 to close to 1.0
assert!((velocities[0] - 0.2).abs() < 0.01, "First note should be ~0.2");
assert!(velocities[1] > velocities[0], "Should increase");
assert!(velocities[2] > velocities[1], "Should increase");
assert!(velocities[3] > velocities[2], "Should increase");
}
#[test]
fn test_decrescendo_notes() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("test")
.pattern_start()
.notes(&[C4, D4, E4, F4], 0.25)
.decrescendo(1.0, 0.3);
let track = &comp.into_mixer().tracks()[0];
let velocities: Vec<f32> = track
.events
.iter()
.filter_map(|e| {
if let AudioEvent::Note(n) = e {
Some(n.velocity)
} else {
None
}
})
.collect();
// Should ramp down from 1.0 to close to 0.3
assert!((velocities[0] - 1.0).abs() < 0.01, "First note should be ~1.0");
assert!(velocities[1] < velocities[0], "Should decrease");
assert!(velocities[2] < velocities[1], "Should decrease");
assert!(velocities[3] < velocities[2], "Should decrease");
}
#[test]
fn test_crescendo_drums() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("drums")
.drum_grid(4, 0.25, |g| g.sound(DrumType::HiHatClosed, "xxxx"))
.crescendo(0.3, 0.9);
let track = &comp.into_mixer().tracks()[0];
let velocities: Vec<f32> = track
.events
.iter()
.filter_map(|e| {
if let AudioEvent::Drum(d) = e {
Some(d.velocity)
} else {
None
}
})
.collect();
assert!((velocities[0] - 0.3).abs() < 0.01, "First drum should be ~0.3");
assert!(velocities[3] > velocities[0], "Last should be louder than first");
}
#[test]
fn test_tempo_ramp() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("test")
.pattern_start()
.notes(&[C4, D4, E4, F4], 0.25)
.tempo_ramp(80.0, 4);
let track = &comp.into_mixer().tracks()[0];
// Count tempo change events
let tempo_changes: Vec<f32> = track
.events
.iter()
.filter_map(|e| {
if let AudioEvent::TempoChange(t) = e {
Some(t.bpm)
} else {
None
}
})
.collect();
assert_eq!(tempo_changes.len(), 4, "Should have 4 tempo changes");
assert!(tempo_changes[0] < 120.0, "First tempo should be less than start");
assert!((tempo_changes[3] - 80.0).abs() < 0.01, "Last tempo should be ~80");
}
#[test]
fn test_ritardando_accelerando() {
// Test ritardando (alias for tempo_ramp)
let mut comp1 = Composition::new(Tempo::new(120.0));
comp1.track("test")
.pattern_start()
.notes(&[C4, D4], 0.5)
.ritardando(60.0, 2);
let track1 = &comp1.into_mixer().tracks()[0];
let tempos1: Vec<f32> = track1.events.iter()
.filter_map(|e| if let AudioEvent::TempoChange(t) = e { Some(t.bpm) } else { None })
.collect();
assert_eq!(tempos1.len(), 2);
// Test accelerando
let mut comp2 = Composition::new(Tempo::new(100.0));
comp2.track("test")
.pattern_start()
.notes(&[C4, D4], 0.5)
.accelerando(150.0, 2);
let track2 = &comp2.into_mixer().tracks()[0];
let tempos2: Vec<f32> = track2.events.iter()
.filter_map(|e| if let AudioEvent::TempoChange(t) = e { Some(t.bpm) } else { None })
.collect();
assert_eq!(tempos2.len(), 2);
assert!((tempos2[1] - 150.0).abs() < 0.01, "Should reach target BPM");
}
#[test]
fn test_for_each_event() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("test")
.pattern_start()
.notes(&[C4, E4, G4, C5], 0.25)
.for_each_event(|event, note_count, _drum_count| {
// Set velocity based on note count (accent every 2nd note)
if let EventMut::Note(n) = event {
if note_count % 2 == 0 {
n.velocity = 1.0;
} else {
n.velocity = 0.5;
}
}
});
let track = &comp.into_mixer().tracks()[0];
let velocities: Vec<f32> = track.events.iter()
.filter_map(|e| if let AudioEvent::Note(n) = e { Some(n.velocity) } else { None })
.collect();
assert_eq!(velocities.len(), 4);
assert_eq!(velocities[0], 0.5); // 1st note (count=1, odd)
assert_eq!(velocities[1], 1.0); // 2nd note (count=2, even)
assert_eq!(velocities[2], 0.5); // 3rd note (count=3, odd)
assert_eq!(velocities[3], 1.0); // 4th note (count=4, even)
}
#[test]
fn test_for_each_event_mixed() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("test")
.pattern_start()
.note(&[C4], 0.25)
.drum(DrumType::Kick, 0.25)
.note(&[E4], 0.25)
.drum(DrumType::Snare, 0.25)
.for_each_event(|event, note_count, drum_count| {
match event {
EventMut::Note(n) => n.velocity = note_count as f32 * 0.1,
EventMut::Drum(d) => d.velocity = drum_count as f32 * 0.2,
}
});
let track = &comp.into_mixer().tracks()[0];
let note_velocities: Vec<f32> = track.events.iter()
.filter_map(|e| if let AudioEvent::Note(n) = e { Some(n.velocity) } else { None })
.collect();
let drum_velocities: Vec<f32> = track.events.iter()
.filter_map(|e| if let AudioEvent::Drum(d) = e { Some(d.velocity) } else { None })
.collect();
assert_eq!(note_velocities, vec![0.1, 0.2]); // note_count 1 and 2
assert_eq!(drum_velocities, vec![0.2, 0.4]); // drum_count 1 and 2
}
#[test]
fn test_every_nth_note() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("test")
.pattern_start()
.notes(&[C4, D4, E4, F4, G4, A4, B4, C5], 0.125)
.every_nth_note(4, |note| {
note.velocity = 1.0;
});
let track = &comp.into_mixer().tracks()[0];
let velocities: Vec<f32> = track.events.iter()
.filter_map(|e| if let AudioEvent::Note(n) = e { Some(n.velocity) } else { None })
.collect();
assert_eq!(velocities.len(), 8);
// Default velocity is 0.8, every 4th should be 1.0
assert!((velocities[3] - 1.0).abs() < 0.01, "4th note should be accented");
assert!((velocities[7] - 1.0).abs() < 0.01, "8th note should be accented");
// Others should be default
assert!((velocities[0] - 0.8).abs() < 0.01, "1st note should be default");
assert!((velocities[1] - 0.8).abs() < 0.01, "2nd note should be default");
}
#[test]
fn test_every_nth_drum() {
let mut comp = Composition::new(Tempo::new(120.0));
comp.track("test")
.drum_grid(8, 0.125, |g| g
.sound(DrumType::HiHatClosed, "xxxxxxxx"))
.every_nth_drum(2, |drum| {
drum.velocity = 1.0;
});
let track = &comp.into_mixer().tracks()[0];
let velocities: Vec<f32> = track.events.iter()
.filter_map(|e| if let AudioEvent::Drum(d) = e { Some(d.velocity) } else { None })
.collect();
assert_eq!(velocities.len(), 8);
// Every 2nd drum (indices 1, 3, 5, 7 in 0-based, counts 2, 4, 6, 8) should be 1.0
assert!((velocities[1] - 1.0).abs() < 0.01, "2nd drum should be accented");
assert!((velocities[3] - 1.0).abs() < 0.01, "4th drum should be accented");
assert!((velocities[5] - 1.0).abs() < 0.01, "6th drum should be accented");
assert!((velocities[7] - 1.0).abs() < 0.01, "8th drum should be accented");
}
}