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
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
use crate::composition::{Composition, Tempo};
use crate::error::{Result, TunesError};
use crate::synthesis::spatial::{
ListenerConfig, SoundCone, SpatialParams, SpatialPosition, calculate_spatial_with_cone,
};
use crate::track::Mixer;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use crossbeam::channel::{Receiver, Sender, unbounded};
use crossbeam::epoch::{self, Atomic, Owned}; // Lock-free epoch-based reclamation
use ringbuf::{
HeapRb,
traits::{Consumer, Observer, Producer, Split},
};
use dashmap::DashMap;
use std::fs::File;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
// Threading only available on native platforms
#[cfg(not(target_arch = "wasm32"))]
use std::thread::{self, JoinHandle};
use symphonia::core::audio::{AudioBufferRef, Signal};
use symphonia::core::codecs::DecoderOptions;
use symphonia::core::conv::IntoSample;
use symphonia::core::formats::FormatOptions;
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
use symphonia::core::sample::Sample as SymphoniaSample;
/// Unique identifier for playing sounds
pub type SoundId = u64;
/// Commands sent from main thread to audio thread
enum AudioCommand {
Play {
id: SoundId,
mixer: Box<Mixer>,
looping: bool,
},
Stop {
id: SoundId,
},
SetVolume {
id: SoundId,
volume: f32,
},
SetPan {
id: SoundId,
pan: f32, // -1.0 (left) to 1.0 (right)
},
SetPlaybackRate {
id: SoundId,
rate: f32, // 1.0 = normal, 2.0 = double speed/pitch
},
Pause {
id: SoundId,
},
Resume {
id: SoundId,
},
PauseAll,
ResumeAll,
StopAll,
FadeOut {
id: SoundId,
duration: f32, // Duration in seconds
},
FadeIn {
id: SoundId,
duration: f32, // Duration in seconds
target_volume: f32, // Target volume (0.0-1.0)
},
TweenPan {
id: SoundId,
target_pan: f32, // Target pan (-1.0 to 1.0)
duration: f32, // Duration in seconds
},
TweenPlaybackRate {
id: SoundId,
target_rate: f32, // Target playback rate
duration: f32, // Duration in seconds
},
SetSoundPosition {
id: SoundId,
position: SpatialPosition,
},
SetSoundVelocity {
id: SoundId,
vx: f32,
vy: f32,
vz: f32,
},
SetListenerPosition {
x: f32,
y: f32,
z: f32,
},
SetListenerVelocity {
vx: f32,
vy: f32,
vz: f32,
},
SetListenerForward {
x: f32,
y: f32,
z: f32,
},
SetSpatialParams {
params: SpatialParams,
},
SetSoundCone {
id: SoundId,
cone: Option<SoundCone>,
},
SetSoundOcclusion {
id: SoundId,
occlusion: f32,
},
// Streaming commands (only available on native platforms - no FS on web)
#[cfg(not(target_arch = "wasm32"))]
StreamFile {
id: SoundId,
path: PathBuf,
looping: bool,
volume: f32,
pan: f32,
},
#[cfg(not(target_arch = "wasm32"))]
StopStream {
id: SoundId,
},
#[cfg(not(target_arch = "wasm32"))]
PauseStream {
id: SoundId,
},
#[cfg(not(target_arch = "wasm32"))]
ResumeStream {
id: SoundId,
},
#[cfg(not(target_arch = "wasm32"))]
SetStreamVolume {
id: SoundId,
volume: f32,
},
#[cfg(not(target_arch = "wasm32"))]
SetStreamPan {
id: SoundId,
pan: f32,
},
}
/// State for an actively playing sound
struct ActiveSound {
mixer: Mixer,
sample_clock: f32,
elapsed_time: f32,
volume: f32,
pan: f32,
playback_rate: f32, // 1.0 = normal, 2.0 = double speed/pitch
paused: bool,
looping: bool,
spatial_position: Option<SpatialPosition>, // 3D position for spatial audio
spatial_cone: Option<SoundCone>, // Optional directional cone
occlusion: f32, // Occlusion amount (0.0 = none, 1.0 = fully occluded)
// Spatial audio caching (avoid recalculating every frame)
cached_spatial_volume: f32,
cached_spatial_pan: f32,
cached_spatial_pitch: f32,
spatial_dirty: bool, // True when position/cone/occlusion changed
// Volume fade state
fade_start_time: Option<f32>,
fade_duration: f32,
fade_start_volume: f32,
fade_target_volume: f32,
// Pan tween state
pan_tween_start_time: Option<f32>,
pan_tween_duration: f32,
pan_tween_start_value: f32,
pan_tween_target_value: f32,
// Playback rate tween state
rate_tween_start_time: Option<f32>,
rate_tween_duration: f32,
rate_tween_start_value: f32,
rate_tween_target_value: f32,
}
/// State for a streaming audio source (native only)
///
/// Streams audio from disk using a background decoder thread and lock-free ring buffer.
/// This allows playing long audio files (background music, ambience) without loading
/// the entire file into memory.
#[cfg(not(target_arch = "wasm32"))]
struct StreamingSound {
/// Ring buffer consumer (audio thread reads from this)
ring_consumer: ringbuf::HeapCons<f32>,
/// Decoder thread handle (for cleanup on stop)
decoder_thread: Option<JoinHandle<()>>,
/// Signal to stop the decoder thread
stop_signal: Arc<AtomicBool>,
/// Pause signal for decoder thread
pause_signal: Arc<AtomicBool>,
/// Current volume
volume: f32,
/// Current pan (-1.0 left, 0.0 center, 1.0 right)
pan: f32,
/// Whether the stream is looping
#[allow(dead_code)]
looping: bool,
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for StreamingSound {
fn drop(&mut self) {
// Signal thread to stop and wait for it to finish
self.stop_signal.store(true, Ordering::Relaxed);
if let Some(handle) = self.decoder_thread.take() {
let _ = handle.join();
}
}
}
/// Audio callback state (allocation-free mixing)
///
/// Holds pre-allocated buffers to avoid allocations in the real-time audio thread.
/// All buffers are reused across callback invocations.
struct AudioCallbackState {
/// Active sounds being mixed (sparse vector indexed by SoundId for cache-friendly iteration)
/// Uses Vec<Option<>> instead of HashMap for sequential memory access (better cache locality)
active_sounds: Vec<Option<ActiveSound>>,
/// Streaming sounds (separate from pre-rendered sounds, native only)
#[cfg(not(target_arch = "wasm32"))]
streaming_sounds: Vec<Option<StreamingSound>>,
/// Pre-allocated temp buffer for mixing (stereo interleaved)
/// Size is determined by the maximum buffer size we expect
temp_buffer: Vec<f32>,
/// Pre-allocated list for tracking finished sounds (avoids allocation during cleanup)
finished_sounds: Vec<SoundId>,
/// Pre-allocated list for tracking finished streams (native only)
#[cfg(not(target_arch = "wasm32"))]
finished_streams: Vec<SoundId>,
}
impl AudioCallbackState {
fn new() -> Self {
Self {
// Pre-allocate space for 128 concurrent sounds (typical max for games)
active_sounds: Vec::with_capacity(128),
#[cfg(not(target_arch = "wasm32"))]
streaming_sounds: Vec::with_capacity(16),
// Pre-allocate for a reasonably large buffer (2048 frames stereo = 4096 samples)
temp_buffer: vec![0.0; 4096],
finished_sounds: Vec::with_capacity(16),
#[cfg(not(target_arch = "wasm32"))]
finished_streams: Vec::with_capacity(16),
}
}
/// Ensure temp buffer is large enough for the given size
#[allow(dead_code)]
fn ensure_temp_buffer_size(&mut self, required_size: usize) {
if self.temp_buffer.len() < required_size {
self.temp_buffer.resize(required_size, 0.0);
}
}
}
/// Decoder thread function for streaming audio (native only)
///
/// Runs in a background thread, decodes audio from file, and pushes samples to ring buffer.
/// The audio callback reads from the ring buffer, creating a lock-free streaming pipeline.
#[cfg(not(target_arch = "wasm32"))]
fn decoder_thread_func(
path: PathBuf,
mut ring_producer: ringbuf::HeapProd<f32>,
stop_signal: Arc<AtomicBool>,
pause_signal: Arc<AtomicBool>,
looping: bool,
) {
// Helper function to convert symphonia audio buffer to f32 samples
fn convert_audio_buffer(decoded: &AudioBufferRef, samples: &mut Vec<f32>) {
fn convert_samples<S>(buf: &symphonia::core::audio::AudioBuffer<S>, samples: &mut Vec<f32>)
where
S: SymphoniaSample + IntoSample<f32>,
{
let num_channels = buf.spec().channels.count();
let num_frames = buf.frames();
samples.clear();
samples.reserve(num_frames * num_channels);
// Convert planar to interleaved
for frame_idx in 0..num_frames {
for ch in 0..num_channels {
let sample: f32 = buf.chan(ch)[frame_idx].into_sample();
samples.push(sample);
}
}
}
match decoded {
AudioBufferRef::U8(buf) => convert_samples(buf, samples),
AudioBufferRef::U16(buf) => convert_samples(buf, samples),
AudioBufferRef::U24(buf) => convert_samples(buf, samples),
AudioBufferRef::U32(buf) => convert_samples(buf, samples),
AudioBufferRef::S8(buf) => convert_samples(buf, samples),
AudioBufferRef::S16(buf) => convert_samples(buf, samples),
AudioBufferRef::S24(buf) => convert_samples(buf, samples),
AudioBufferRef::S32(buf) => convert_samples(buf, samples),
AudioBufferRef::F32(buf) => convert_samples(buf, samples),
AudioBufferRef::F64(buf) => convert_samples(buf, samples),
}
}
loop {
// Check stop signal
if stop_signal.load(Ordering::Relaxed) {
break;
}
// If paused, sleep briefly and continue
if pause_signal.load(Ordering::Relaxed) {
thread::sleep(std::time::Duration::from_millis(10));
continue;
}
// Open and decode file
let file = match File::open(&path) {
Ok(f) => f,
Err(e) => {
eprintln!("Streaming: Failed to open file {:?}: {}", path, e);
break;
}
};
let mss = MediaSourceStream::new(Box::new(file), Default::default());
let mut hint = Hint::new();
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
hint.with_extension(ext);
}
let format_opts = FormatOptions::default();
let metadata_opts = MetadataOptions::default();
let decoder_opts = DecoderOptions::default();
let probed = match symphonia::default::get_probe().format(
&hint,
mss,
&format_opts,
&metadata_opts,
) {
Ok(p) => p,
Err(e) => {
eprintln!("Streaming: Failed to probe file {:?}: {}", path, e);
break;
}
};
let mut format = probed.format;
let track = match format.default_track() {
Some(t) => t,
None => {
eprintln!("Streaming: No default track found in {:?}", path);
break;
}
};
let mut decoder =
match symphonia::default::get_codecs().make(&track.codec_params, &decoder_opts) {
Ok(d) => d,
Err(e) => {
eprintln!("Streaming: Failed to create decoder for {:?}: {}", path, e);
break;
}
};
let mut samples = Vec::new();
// Decode loop
loop {
// Check stop/pause signals
if stop_signal.load(Ordering::Relaxed) {
return; // Exit thread entirely
}
if pause_signal.load(Ordering::Relaxed) {
thread::sleep(std::time::Duration::from_millis(10));
continue;
}
// Get next packet
let packet = match format.next_packet() {
Ok(p) => p,
Err(symphonia::core::errors::Error::IoError(e))
if e.kind() == std::io::ErrorKind::UnexpectedEof =>
{
// End of file
if looping {
break; // Break inner loop, restart outer loop
} else {
return; // Exit thread
}
}
Err(e) => {
eprintln!("Streaming: Error reading packet: {}", e);
return;
}
};
// Decode packet
let decoded = match decoder.decode(&packet) {
Ok(d) => d,
Err(e) => {
eprintln!("Streaming: Decode error: {}", e);
continue;
}
};
// Convert to f32 samples
convert_audio_buffer(&decoded, &mut samples);
// Push samples to ring buffer (blocking if buffer is full)
let mut offset = 0;
while offset < samples.len() {
// Check stop signal even while pushing
if stop_signal.load(Ordering::Relaxed) {
return;
}
// Try to push as much as possible
let pushed = ring_producer.push_slice(&samples[offset..]);
offset += pushed;
// If we couldn't push everything, the buffer is full - sleep briefly
if pushed == 0 {
thread::sleep(std::time::Duration::from_millis(1));
}
}
}
// If not looping, we exit after one playthrough
if !looping {
break;
}
}
}
/// Central audio engine that manages playback with concurrent mixing
pub struct AudioEngine {
command_tx: Sender<AudioCommand>,
next_id: Arc<AtomicU64>,
callback_state: Arc<Mutex<AudioCallbackState>>,
#[allow(dead_code)] // Reserved for future spatial audio runtime control
listener_config: Arc<Atomic<ListenerConfig>>, // Lock-free reads via epoch-based reclamation
#[allow(dead_code)] // Reserved for future spatial audio runtime control
spatial_params: Arc<Atomic<SpatialParams>>, // Lock-free reads via epoch-based reclamation
sample_rate: f32,
sample_cache: Arc<DashMap<String, crate::synthesis::Sample>>, // Lock-free sample caching
_stream: cpal::Stream, // Persistent stream, kept alive
// Info for optional printing
device_name: String,
buffer_size: u32,
channels: usize,
// GPU acceleration flag for play_sample()
#[allow(dead_code)]
enable_gpu_for_samples: bool,
// Monitor callback for real-time audio visualization and analysis
monitor_callback: Arc<Mutex<Option<Box<dyn Fn(&[f32]) + Send + 'static>>>>,
}
impl AudioEngine {
/// Create a new audio engine with default output device
///
/// Uses a moderate buffer size (4096 samples) optimized for pre-rendered playback.
/// Since play_mixer() pre-renders audio, buffer size only affects latency, not stability.
/// For lower latency, use `with_buffer_size()`.
///
/// # Performance
/// Default performance: 50-200x realtime (SIMD + Rayon automatic)
pub fn new() -> Result<Self> {
Self::with_buffer_size_and_gpu(4096, false)
}
/// Create a new audio engine with GPU acceleration enabled
///
/// Enables transparent GPU acceleration for synthesis and export operations.
/// GPU performance scales with hardware capabilities - discrete GPUs show
/// significantly better performance than integrated GPUs.
///
/// Automatically enables GPU for `export_wav()`, `export_flac()`, and
/// `play_mixer_realtime()` operations without requiring manual `enable_gpu()` calls.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// let engine = AudioEngine::new_with_gpu()?;
///
/// // Transparent GPU acceleration for export and playback
/// let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("synth").note(&[440.0], 1.0);
/// let mut mixer = comp.into_mixer();
/// engine.export_wav(&mut mixer, "output.wav")?; // GPU accelerated
/// # Ok::<(), anyhow::Error>(())
/// ```
///
/// # Performance
/// - Integrated GPUs: 1.0-1.2x speedup (measured on Intel HD 530)
/// - Discrete GPUs: Performance scales with compute capacity and memory bandwidth
/// - CPU fallback: Automatic if GPU unavailable
/// - Warning: Auto-detects integrated GPUs and displays performance advisory
pub fn new_with_gpu() -> Result<Self> {
Self::with_buffer_size_and_gpu(4096, true)
}
/// Create a new audio engine with custom buffer size
///
/// Creates a persistent audio stream that can play multiple sounds concurrently.
///
/// # Arguments
/// * `buffer_size` - Buffer size in samples
/// - Smaller (512-1024): Lower latency, may underrun with complex synthesis
/// - Medium (2048-4096): Balanced
/// - Large (8192-16384): Very stable for most cases
pub fn with_buffer_size(buffer_size: u32) -> Result<Self> {
Self::with_buffer_size_and_gpu(buffer_size, false)
}
/// Create a new audio engine with custom buffer size and GPU flag (internal)
fn with_buffer_size_and_gpu(buffer_size: u32, enable_gpu: bool) -> Result<Self> {
let host = cpal::default_host();
let device = host.default_output_device().ok_or_else(|| {
TunesError::AudioEngineError("No output device available".to_string())
})?;
let config = device.default_output_config().map_err(|e| {
TunesError::AudioEngineError(format!("Failed to get default config: {}", e))
})?;
let sample_rate = config.sample_rate().0 as f32;
let channels = config.channels() as usize;
let device_name = device.name().unwrap_or_else(|_| "Unknown".to_string());
// Create command channel for communication with audio thread
let (command_tx, command_rx): (Sender<AudioCommand>, Receiver<AudioCommand>) = unbounded();
// Shared state for audio callback (includes pre-allocated buffers)
let callback_state: Arc<Mutex<AudioCallbackState>> =
Arc::new(Mutex::new(AudioCallbackState::new()));
let callback_state_for_stream = Arc::clone(&callback_state);
// Lock-free shared state for spatial audio (epoch-based reclamation)
let listener_config = Arc::new(Atomic::new(ListenerConfig::new()));
let listener_config_for_stream = Arc::clone(&listener_config);
let spatial_params = Arc::new(Atomic::new(SpatialParams::default()));
let spatial_params_for_stream = Arc::clone(&spatial_params);
// Monitor callback for audio visualization/analysis
let monitor_callback: Arc<Mutex<Option<Box<dyn Fn(&[f32]) + Send + 'static>>>> =
Arc::new(Mutex::new(None));
let monitor_callback_for_stream = Arc::clone(&monitor_callback);
// Build stream configuration
let mut stream_config: cpal::StreamConfig = config.clone().into();
stream_config.buffer_size = cpal::BufferSize::Fixed(buffer_size);
// Error handler
let err_fn = |err| eprintln!("Audio stream error: {}", err);
// Build the persistent output stream
let stream = device
.build_output_stream(
&stream_config,
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
// Lock only AudioCallbackState (one lock instead of three!)
// If mutex is poisoned, output silence and return early
let mut state = match callback_state_for_stream.lock() {
Ok(state) => state,
Err(e) => {
eprintln!("Audio callback: mutex poisoned: {}", e);
// Fill buffer with silence
for sample in data.iter_mut() {
*sample = 0.0;
}
return;
}
};
// Lock-free reads of spatial audio config via epoch-based reclamation
let guard = epoch::pin();
// Use defaults if atomic loads return null (graceful degradation)
let default_listener = ListenerConfig::default();
let listener = unsafe {
listener_config_for_stream
.load(Ordering::Acquire, &guard)
.as_ref()
};
let listener = listener.unwrap_or(&default_listener);
let default_spatial = SpatialParams::default();
let spatial = unsafe {
spatial_params_for_stream
.load(Ordering::Acquire, &guard)
.as_ref()
};
let spatial = spatial.unwrap_or(&default_spatial);
// Destructure state FIRST to get separate mutable references (satisfies borrow checker)
let AudioCallbackState {
ref mut active_sounds,
#[cfg(not(target_arch = "wasm32"))]
ref mut streaming_sounds,
ref mut temp_buffer,
ref mut finished_sounds,
#[cfg(not(target_arch = "wasm32"))]
ref mut finished_streams,
} = *state;
// Process all pending commands (non-blocking)
while let Ok(cmd) = command_rx.try_recv() {
Self::handle_command(
cmd,
active_sounds,
#[cfg(not(target_arch = "wasm32"))]
streaming_sounds,
&listener_config_for_stream,
&spatial_params_for_stream,
sample_rate,
);
}
// Mix all active sounds into the output buffer (allocation-free)
Self::mix_sounds(
data,
active_sounds,
temp_buffer,
finished_sounds,
listener,
spatial,
sample_rate,
channels,
);
// Mix streaming sounds into the output buffer
#[cfg(not(target_arch = "wasm32"))]
Self::mix_streaming_sounds(data, streaming_sounds, finished_streams, channels);
// Call monitor callback if set (for visualization/analysis)
if let Ok(callback_guard) = monitor_callback_for_stream.lock() {
if let Some(ref callback) = *callback_guard {
callback(data);
}
}
// Guard dropped here - safe to reclaim old epochs
},
err_fn,
None,
)
.map_err(|e| {
TunesError::AudioEngineError(format!("Failed to build output stream: {}", e))
})?;
// Start the stream
stream.play().map_err(|e| {
TunesError::AudioEngineError(format!("Failed to start audio stream: {}", e))
})?;
Ok(Self {
command_tx,
next_id: Arc::new(AtomicU64::new(1)),
callback_state,
listener_config,
spatial_params,
sample_rate,
sample_cache: Arc::new(DashMap::new()),
_stream: stream,
device_name,
buffer_size,
channels,
enable_gpu_for_samples: enable_gpu,
monitor_callback,
})
}
/// Print audio engine initialization information
///
/// Displays device name, sample rate, buffer size, latency, and configuration.
/// This is an opt-in method - call it if you want to see engine initialization details.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
/// engine.print_info(); // Optional - only if you want to see initialization info
/// # Ok(())
/// # }
/// ```
pub fn print_info(&self) {
use crate::synthesis::simd::{SIMD, SimdWidth};
let latency_ms = (self.buffer_size as f32 / self.sample_rate) * 1000.0;
let simd_width = SIMD.simd_width();
let simd_lanes = SIMD.width();
let simd_name = match simd_width {
SimdWidth::X8 => "AVX2",
SimdWidth::X4 => {
#[cfg(target_arch = "x86_64")]
{
"SSE"
}
#[cfg(not(target_arch = "x86_64"))]
{
"NEON"
}
}
SimdWidth::Scalar => "Scalar (no SIMD)",
};
println!("Audio Engine initialized:");
println!(" Device: {}", self.device_name);
println!(" Sample rate: {} Hz", self.sample_rate as u32);
println!(
" Buffer size: {} samples ({:.1}ms latency)",
self.buffer_size, latency_ms
);
println!(" Channels: {}", self.channels);
println!(" SIMD: {} ({} lanes)", simd_name, simd_lanes);
println!(" Concurrent mixing: enabled");
}
/// Handle commands from the main thread (called from audio thread)
fn handle_command(
cmd: AudioCommand,
active_sounds: &mut Vec<Option<ActiveSound>>,
#[cfg(not(target_arch = "wasm32"))] streaming_sounds: &mut Vec<Option<StreamingSound>>,
listener_atomic: &Arc<Atomic<ListenerConfig>>,
spatial_atomic: &Arc<Atomic<SpatialParams>>,
sample_rate: f32,
) {
match cmd {
AudioCommand::Play { id, mixer, looping } => {
// Ensure Vec has enough capacity (sparse vector indexed by SoundId)
let index = id as usize;
while active_sounds.len() <= index {
active_sounds.push(None);
}
active_sounds[index] = Some(ActiveSound {
mixer: *mixer,
sample_clock: 0.0,
elapsed_time: 0.0,
volume: 1.0,
pan: 0.0,
playback_rate: 1.0,
paused: false,
looping,
spatial_position: None,
spatial_cone: None,
occlusion: 0.0,
// Initialize spatial cache (will be calculated on first frame)
cached_spatial_volume: 1.0,
cached_spatial_pan: 0.0,
cached_spatial_pitch: 1.0,
spatial_dirty: true, // Force calculation on first frame
fade_start_time: None,
fade_duration: 0.0,
fade_start_volume: 1.0,
fade_target_volume: 1.0,
pan_tween_start_time: None,
pan_tween_duration: 0.0,
pan_tween_start_value: 0.0,
pan_tween_target_value: 0.0,
rate_tween_start_time: None,
rate_tween_duration: 0.0,
rate_tween_start_value: 1.0,
rate_tween_target_value: 1.0,
});
}
AudioCommand::Stop { id } => {
let index = id as usize;
if index < active_sounds.len() {
active_sounds[index] = None;
}
}
AudioCommand::SetVolume { id, volume } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.volume = volume.clamp(0.0, 1.0);
}
}
AudioCommand::SetPan { id, pan } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.pan = pan.clamp(-1.0, 1.0);
}
}
AudioCommand::SetPlaybackRate { id, rate } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
// Clamp to reasonable range (0.1x to 4.0x speed)
sound.playback_rate = rate.clamp(0.1, 4.0);
}
}
AudioCommand::Pause { id } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.paused = true;
}
}
AudioCommand::Resume { id } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.paused = false;
}
}
AudioCommand::SetSoundPosition { id, position } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.spatial_position = Some(position);
sound.spatial_dirty = true; // Mark for recalculation
}
}
AudioCommand::SetSoundVelocity { id, vx, vy, vz } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
if let Some(pos) = &mut sound.spatial_position {
pos.set_velocity(vx, vy, vz);
}
}
}
AudioCommand::SetListenerPosition { x, y, z } => {
// Lock-free update: load, clone, modify, store
let guard = epoch::pin();
let current = unsafe { listener_atomic.load(Ordering::Acquire, &guard).as_ref().unwrap() };
let mut new_config = *current;
new_config.position.x = x;
new_config.position.y = y;
new_config.position.z = z;
listener_atomic.store(Owned::new(new_config), Ordering::Release);
}
AudioCommand::SetListenerVelocity { vx, vy, vz } => {
let guard = epoch::pin();
let current = unsafe { listener_atomic.load(Ordering::Acquire, &guard).as_ref().unwrap() };
let mut new_config = *current;
new_config.velocity.x = vx;
new_config.velocity.y = vy;
new_config.velocity.z = vz;
listener_atomic.store(Owned::new(new_config), Ordering::Release);
}
AudioCommand::SetListenerForward { x, y, z } => {
use crate::synthesis::spatial::Vec3;
let guard = epoch::pin();
let current = unsafe { listener_atomic.load(Ordering::Acquire, &guard).as_ref().unwrap() };
let mut new_config = *current;
new_config.forward = Vec3::new(x, y, z).normalize();
listener_atomic.store(Owned::new(new_config), Ordering::Release);
}
AudioCommand::SetSpatialParams { params } => {
// Direct replacement - just store the new params
spatial_atomic.store(Owned::new(params), Ordering::Release);
}
AudioCommand::SetSoundCone { id, cone } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.spatial_cone = cone;
sound.spatial_dirty = true; // Mark for recalculation
}
}
AudioCommand::SetSoundOcclusion { id, occlusion } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.occlusion = occlusion.clamp(0.0, 1.0);
sound.spatial_dirty = true; // Mark for recalculation
}
}
AudioCommand::PauseAll => {
for sound in active_sounds.iter_mut().flatten() {
sound.paused = true;
}
}
AudioCommand::ResumeAll => {
for sound in active_sounds.iter_mut().flatten() {
sound.paused = false;
}
}
AudioCommand::StopAll => {
active_sounds.iter_mut().for_each(|slot| *slot = None); // Clear all slots
}
AudioCommand::FadeOut { id, duration } => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.fade_start_time = Some(sound.elapsed_time);
sound.fade_duration = duration;
sound.fade_start_volume = sound.volume;
sound.fade_target_volume = 0.0;
}
}
AudioCommand::FadeIn {
id,
duration,
target_volume,
} => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.fade_start_time = Some(sound.elapsed_time);
sound.fade_duration = duration;
sound.fade_start_volume = sound.volume;
sound.fade_target_volume = target_volume.clamp(0.0, 1.0);
}
}
AudioCommand::TweenPan {
id,
target_pan,
duration,
} => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.pan_tween_start_time = Some(sound.elapsed_time);
sound.pan_tween_duration = duration;
sound.pan_tween_start_value = sound.pan;
sound.pan_tween_target_value = target_pan.clamp(-1.0, 1.0);
}
}
AudioCommand::TweenPlaybackRate {
id,
target_rate,
duration,
} => {
let index = id as usize; if let Some(Some(sound)) = active_sounds.get_mut(index) {
sound.rate_tween_start_time = Some(sound.elapsed_time);
sound.rate_tween_duration = duration;
sound.rate_tween_start_value = sound.playback_rate;
sound.rate_tween_target_value = target_rate.max(0.1); // Prevent division by zero
}
}
// Streaming commands (native only)
#[cfg(not(target_arch = "wasm32"))]
AudioCommand::StreamFile {
id,
path,
looping,
volume,
pan,
} => {
// Create ring buffer (5 seconds of stereo audio at 44.1kHz = ~441000 samples)
let ring_buffer_size = (sample_rate * 5.0 * 2.0) as usize;
let ring_buffer = HeapRb::<f32>::new(ring_buffer_size);
let (ring_producer, ring_consumer) = ring_buffer.split();
// Create control signals
let stop_signal = Arc::new(AtomicBool::new(false));
let pause_signal = Arc::new(AtomicBool::new(false));
// Spawn decoder thread
let stop_signal_clone = Arc::clone(&stop_signal);
let pause_signal_clone = Arc::clone(&pause_signal);
let decoder_thread = thread::spawn(move || {
decoder_thread_func(
path,
ring_producer,
stop_signal_clone,
pause_signal_clone,
looping,
);
});
// Add to streaming sounds (sparse vector)
let index = id as usize;
while streaming_sounds.len() <= index {
streaming_sounds.push(None);
}
streaming_sounds[index] = Some(StreamingSound {
ring_consumer,
decoder_thread: Some(decoder_thread),
stop_signal,
pause_signal,
volume,
pan,
looping,
});
}
#[cfg(not(target_arch = "wasm32"))]
AudioCommand::StopStream { id } => {
// Setting to None will trigger Drop, which signals thread to stop
let index = id as usize;
if index < streaming_sounds.len() {
streaming_sounds[index] = None;
}
}
#[cfg(not(target_arch = "wasm32"))]
AudioCommand::PauseStream { id } => {
let index = id as usize;
if let Some(Some(stream)) = streaming_sounds.get_mut(index) {
stream.pause_signal.store(true, Ordering::Relaxed);
}
}
#[cfg(not(target_arch = "wasm32"))]
AudioCommand::ResumeStream { id } => {
let index = id as usize;
if let Some(Some(stream)) = streaming_sounds.get_mut(index) {
stream.pause_signal.store(false, Ordering::Relaxed);
}
}
#[cfg(not(target_arch = "wasm32"))]
AudioCommand::SetStreamVolume { id, volume } => {
let index = id as usize;
if let Some(Some(stream)) = streaming_sounds.get_mut(index) {
stream.volume = volume.clamp(0.0, 1.0);
}
}
#[cfg(not(target_arch = "wasm32"))]
AudioCommand::SetStreamPan { id, pan } => {
let index = id as usize;
if let Some(Some(stream)) = streaming_sounds.get_mut(index) {
stream.pan = pan.clamp(-1.0, 1.0);
}
}
}
}
/// Mix all active sounds into the output buffer (called from audio thread)
///
/// This function is ALLOCATION-FREE - all buffers are pre-allocated and reused.
#[allow(clippy::too_many_arguments)]
fn mix_sounds(
output: &mut [f32],
active_sounds: &mut [Option<ActiveSound>],
temp_buffer: &mut Vec<f32>,
finished_sounds: &mut Vec<SoundId>,
listener: &ListenerConfig,
spatial_params: &SpatialParams,
sample_rate: f32,
channels: usize,
) {
// Clear output buffer
output.fill(0.0);
// Clear finished sounds list (reuse allocation)
finished_sounds.clear();
// Ensure temp buffer is large enough (may resize on first call, then reuses)
let num_frames = output.len() / channels;
let required_size = num_frames * 2;
if temp_buffer.len() < required_size {
temp_buffer.resize(required_size, 0.0);
}
// Mix each active sound using block processing (cache-friendly sequential iteration)
for (idx, sound_opt) in active_sounds.iter_mut().enumerate() {
let sound = match sound_opt {
Some(s) => s,
None => continue, // Skip empty slots
};
if sound.paused {
continue;
}
let duration = sound.mixer.total_duration();
// Check if sound will finish during this block
let time_delta = 1.0 / sample_rate;
let block_duration = num_frames as f32 * time_delta * sound.playback_rate;
if sound.elapsed_time >= duration {
if sound.looping {
sound.elapsed_time = 0.0;
sound.sample_clock = 0.0;
} else {
finished_sounds.push(idx as u64);
continue;
}
}
// Only apply composition-time spatial audio if NO runtime position is set
let (listener_for_mixer, params_for_mixer) = if sound.spatial_position.is_some() {
(None, None) // Runtime position will handle spatial audio
} else {
(Some(listener), Some(spatial_params)) // Use composition-time position
};
// Process entire block at once
// Note: process_block fully overwrites the buffer, no need to clear it first
sound.mixer.process_block(
&mut temp_buffer[..required_size],
sample_rate,
sound.elapsed_time,
listener_for_mixer,
params_for_mixer,
);
// Apply pan tween if active (before calculating spatial audio)
if let Some(tween_start) = sound.pan_tween_start_time {
let tween_elapsed = sound.elapsed_time - tween_start;
if tween_elapsed >= sound.pan_tween_duration {
// Tween complete
sound.pan = sound.pan_tween_target_value;
sound.pan_tween_start_time = None;
} else {
// Interpolate
let t = (tween_elapsed / sound.pan_tween_duration).clamp(0.0, 1.0);
sound.pan = sound.pan_tween_start_value
+ (sound.pan_tween_target_value - sound.pan_tween_start_value) * t;
}
}
// Apply playback rate tween if active
if let Some(tween_start) = sound.rate_tween_start_time {
let tween_elapsed = sound.elapsed_time - tween_start;
if tween_elapsed >= sound.rate_tween_duration {
// Tween complete
sound.playback_rate = sound.rate_tween_target_value;
sound.rate_tween_start_time = None;
} else {
// Interpolate
let t = (tween_elapsed / sound.rate_tween_duration).clamp(0.0, 1.0);
sound.playback_rate = sound.rate_tween_start_value
+ (sound.rate_tween_target_value - sound.rate_tween_start_value) * t;
}
}
// Calculate spatial audio if runtime position is set
// Use cached values if nothing changed, otherwise recalculate
let (mut spatial_volume, spatial_pan, spatial_pitch, spatial_occlusion) =
if let Some(pos) = &sound.spatial_position {
if sound.spatial_dirty {
// Recalculate spatial audio
let result = calculate_spatial_with_cone(
pos,
listener,
spatial_params,
sound.spatial_cone.as_ref(),
sound.occlusion,
);
// Cache the results
sound.cached_spatial_volume = result.volume;
sound.cached_spatial_pan = result.pan;
sound.cached_spatial_pitch = result.pitch;
sound.spatial_dirty = false; // Mark as clean
(result.volume, result.pan, result.pitch, result.occlusion)
} else {
// Use cached values
(
sound.cached_spatial_volume,
sound.cached_spatial_pan,
sound.cached_spatial_pitch,
sound.occlusion, // Occlusion is just read directly, not cached
)
}
} else {
(1.0, sound.pan, 1.0, 0.0)
};
// Apply occlusion as volume reduction
// 0.0 = no occlusion (full volume), 1.0 = fully occluded (silent)
spatial_volume *= 1.0 - spatial_occlusion;
// Apply doppler pitch shift to playback rate
let effective_playback_rate = sound.playback_rate * spatial_pitch;
// Mix temp buffer into output with volume/pan/fade applied
// Use SIMD fast path when no fade is active (common case)
if sound.fade_start_time.is_none() && channels == 2 {
// SIMD fast path: no fade, stereo output
use wide::f32x8;
use crate::synthesis::simd::{SIMD, SimdWidth};
let combined_volume = sound.volume * spatial_volume;
let num_frames = temp_buffer.len() / 2;
// Calculate pan multipliers once
let (left_pan, right_pan) = if spatial_pan < 0.0 {
(1.0, 1.0 + spatial_pan)
} else {
(1.0 - spatial_pan, 1.0)
};
match SIMD.simd_width() {
SimdWidth::X8 => {
// Process 8 stereo frames (16 samples) at once
// But only if we have enough room in the output buffer
let max_frames_in_output = output.len() / 2;
let safe_frames = num_frames.min(max_frames_in_output);
let chunks_of_16 = safe_frames / 8;
let remainder_start = chunks_of_16 * 8;
let vol_vec = f32x8::splat(combined_volume);
let left_pan_vec = f32x8::splat(left_pan);
let right_pan_vec = f32x8::splat(right_pan);
// Pre-allocate temp arrays for SIMD operations (stack allocated, fast)
let mut input_left = [0.0f32; 8];
let mut input_right = [0.0f32; 8];
let mut output_left = [0.0f32; 8];
let mut output_right = [0.0f32; 8];
for chunk_idx in 0..chunks_of_16 {
let frame_start = chunk_idx * 8;
let temp_start = frame_start * 2;
let out_start = frame_start * 2;
// Deinterleave input using SIMD (dispatches to AVX2/SSE/scalar)
SIMD.deinterleave_stereo(&temp_buffer[temp_start..], &mut input_left, &mut input_right);
// Deinterleave output using SIMD
SIMD.deinterleave_stereo(&output[out_start..], &mut output_left, &mut output_right);
// Load into SIMD vectors for processing
let left = f32x8::from(input_left);
let right = f32x8::from(input_right);
let out_left = f32x8::from(output_left);
let out_right = f32x8::from(output_right);
// Apply volume and pan
let left_out = left * vol_vec * left_pan_vec;
let right_out = right * vol_vec * right_pan_vec;
// Add (mix)
let mixed_left = out_left + left_out;
let mixed_right = out_right + right_out;
// Store back to arrays
output_left = mixed_left.to_array();
output_right = mixed_right.to_array();
// Interleave and store using SIMD (dispatches to AVX2/SSE/scalar)
SIMD.interleave_stereo(&output_left, &output_right, &mut output[out_start..]);
}
// Handle remainder frames with scalar code
for frame_idx in remainder_start..num_frames {
let temp_idx = frame_idx * 2;
let out_idx = frame_idx * 2;
if temp_idx + 1 < temp_buffer.len() && out_idx + 1 < output.len() {
let left = temp_buffer[temp_idx] * combined_volume * left_pan;
let right = temp_buffer[temp_idx + 1] * combined_volume * right_pan;
output[out_idx] += left;
output[out_idx + 1] += right;
}
}
}
_ => {
// Fallback: scalar path
for frame_idx in 0..num_frames {
let temp_idx = frame_idx * 2;
let out_idx = frame_idx * 2;
let left = temp_buffer[temp_idx] * combined_volume * left_pan;
let right = temp_buffer[temp_idx + 1] * combined_volume * right_pan;
if out_idx + 1 < output.len() {
output[out_idx] += left;
output[out_idx + 1] += right;
}
}
}
}
} else {
// Scalar path: fade is active or mono output
for (frame_idx, temp_frame) in temp_buffer.chunks(2).enumerate() {
let frame_time =
sound.elapsed_time + (frame_idx as f32 * time_delta * effective_playback_rate);
// Apply fade if active
let effective_volume = if let Some(fade_start) = sound.fade_start_time {
let fade_elapsed = frame_time - fade_start;
if fade_elapsed >= sound.fade_duration {
// Fade complete
if frame_idx == 0 {
sound.volume = sound.fade_target_volume;
sound.fade_start_time = None;
}
sound.fade_target_volume
} else {
// Interpolate
let t = (fade_elapsed / sound.fade_duration).clamp(0.0, 1.0);
sound.fade_start_volume
+ (sound.fade_target_volume - sound.fade_start_volume) * t
}
} else {
sound.volume
};
let mut left = temp_frame[0];
let mut right = temp_frame[1];
// Apply volume
left *= effective_volume * spatial_volume;
right *= effective_volume * spatial_volume;
// Apply pan
if spatial_pan < 0.0 {
right *= 1.0 + spatial_pan;
} else if spatial_pan > 0.0 {
left *= 1.0 - spatial_pan;
}
// Mix into output
let out_idx = frame_idx * channels;
if out_idx + 1 < output.len() {
if channels == 1 {
output[out_idx] += (left + right) * 0.5;
} else {
output[out_idx] += left;
output[out_idx + 1] += right;
}
}
}
}
// Advance time with doppler-adjusted playback rate
// This ensures mixer renders samples at the correct pitch
sound.elapsed_time += block_duration * effective_playback_rate;
sound.sample_clock =
(sound.sample_clock + (num_frames as f32 * effective_playback_rate)) % sample_rate;
}
// Remove finished sounds (set slots to None)
for id in finished_sounds {
let index = *id as usize;
if index < active_sounds.len() {
active_sounds[index] = None;
}
}
// Clamp output to prevent distortion
for sample in output.iter_mut() {
*sample = sample.clamp(-1.0, 1.0);
}
}
#[cfg(not(target_arch = "wasm32"))]
/// Mix streaming sounds into the output buffer (called from audio thread)
///
/// Reads decoded samples from ring buffers and mixes them into the output.
/// This is ALLOCATION-FREE and lock-free (uses lockless ring buffer).
fn mix_streaming_sounds(
output: &mut [f32],
streaming_sounds: &mut [Option<StreamingSound>],
finished_streams: &mut Vec<SoundId>,
channels: usize,
) {
// Clear finished streams list
finished_streams.clear();
// Mix each streaming sound (cache-friendly sequential iteration)
for (idx, stream_opt) in streaming_sounds.iter_mut().enumerate() {
let stream = match stream_opt {
Some(s) => s,
None => continue, // Skip empty slots
};
// Check if the decoder thread has finished
if let Some(handle) = &stream.decoder_thread {
if handle.is_finished() {
// Thread finished - mark for removal
finished_streams.push(idx as u64);
continue;
}
}
// Read available samples from ring buffer
let available = stream.ring_consumer.occupied_len();
if available == 0 {
// Buffer underrun - could happen at start or if decoding is slow
continue;
}
// Calculate how many samples we need (limited by output buffer size)
let samples_needed = output.len().min(available);
// Mix samples into output
for i in (0..samples_needed).step_by(channels) {
// Pop samples from ring buffer
let left = stream.ring_consumer.try_pop().unwrap_or(0.0);
let right = if channels == 2 {
stream.ring_consumer.try_pop().unwrap_or(0.0)
} else {
left // Mono - use same sample for both channels
};
// Apply volume and pan
let pan = stream.pan;
let left_gain = if pan <= 0.0 { 1.0 } else { 1.0 - pan } * stream.volume;
let right_gain = if pan >= 0.0 { 1.0 } else { 1.0 + pan } * stream.volume;
// Mix into output (additively)
if i < output.len() {
output[i] += left * left_gain;
}
if i + 1 < output.len() {
output[i + 1] += right * right_gain;
}
}
}
// Remove finished streams (set slots to None)
for id in finished_streams.iter() {
let index = *id as usize;
if index < streaming_sounds.len() {
streaming_sounds[index] = None;
}
}
}
/// Play a composition and block until it finishes
///
/// This is the main method for simple use cases, examples, and scripts.
/// It plays the composition and blocks until playback is complete.
///
/// For non-blocking playback (games, interactive use), use `play_mixer_realtime()`.
///
/// # Returns
/// `Ok(())` on successful playback. Note that this returns success even if the
/// mixer is empty - check with `mixer.is_empty()` first if you want to detect this.
pub fn play_mixer(&self, mixer: &Mixer) -> Result<()> {
let id = self.play_mixer_realtime(mixer)?;
self.wait_for(id, mixer.is_empty())
}
/// Play a composition in real-time mode, returns immediately
///
/// **BREAKING CHANGE:** This method now returns `SoundId` instead of blocking.
/// This enables concurrent playback for games and interactive applications.
///
/// # Returns
/// `SoundId` - Unique identifier for this sound, use with control methods
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// let engine = AudioEngine::new()?;
///
/// // Non-blocking - returns immediately
/// let sound_id = engine.play_mixer_realtime(&comp.into_mixer())?;
///
/// // Control the sound while it plays
/// engine.set_volume(sound_id, 0.5)?;
/// engine.set_pan(sound_id, -0.5)?; // Pan left
/// # Ok(())
/// # }
/// ```
pub fn play_mixer_realtime(&self, mixer: &Mixer) -> Result<SoundId> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
// Clone mixer and automatically enable GPU if engine was created with GPU support
#[cfg(feature = "gpu")]
let mut mixer_clone = mixer.clone();
#[cfg(not(feature = "gpu"))]
let mixer_clone = mixer.clone();
#[cfg(feature = "gpu")]
if self.enable_gpu_for_samples {
mixer_clone.enable_gpu();
}
self.command_tx
.send(AudioCommand::Play {
id,
mixer: Box::new(mixer_clone),
looping: false,
})
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(id)
}
/// Play a mixer at a custom playback rate and block until finished
///
/// This is a convenience method that combines `play_mixer_realtime()` and
/// `set_playback_rate()` for the common case of playing at a different speed.
///
/// # Arguments
/// * `mixer` - The mixer to play
/// * `rate` - Playback rate multiplier (1.0 = normal, 2.0 = double speed, 0.5 = half speed)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// let engine = AudioEngine::new()?;
/// let mixer = comp.into_mixer();
///
/// // Play at 2x speed (chipmunk effect)
/// engine.play_mixer_at_rate(&mixer, 2.0)?;
///
/// // Play at half speed (slow motion)
/// engine.play_mixer_at_rate(&mixer, 0.5)?;
/// # Ok(())
/// # }
/// ```
pub fn play_mixer_at_rate(&self, mixer: &Mixer, rate: f32) -> Result<()> {
let id = self.play_mixer_realtime(mixer)?;
self.set_playback_rate(id, rate)?;
self.wait_for(id, mixer.is_empty())
}
/// Play a mixer at a custom playback rate and return immediately
///
/// Returns a `SoundId` for controlling the playing instance. The playback rate
/// is set immediately after starting playback.
///
/// # Arguments
/// * `mixer` - The mixer to play
/// * `rate` - Playback rate multiplier (1.0 = normal, 2.0 = double speed, 0.5 = half speed)
///
/// # Returns
/// `SoundId` - Unique identifier for this sound, use with control methods
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// let engine = AudioEngine::new()?;
/// let mixer = comp.into_mixer();
///
/// // Start playing at 1.5x speed, non-blocking
/// let id = engine.play_mixer_realtime_at_rate(&mixer, 1.5)?;
///
/// // Can still control it further
/// engine.set_volume(id, 0.7)?;
/// # Ok(())
/// # }
/// ```
pub fn play_mixer_realtime_at_rate(&self, mixer: &Mixer, rate: f32) -> Result<SoundId> {
let id = self.play_mixer_realtime(mixer)?;
self.set_playback_rate(id, rate)?;
Ok(id)
}
/// Play a composition with pre-rendering, blocks until finished
///
/// Currently behaves the same as `play_mixer()` but reserved for future
/// pre-rendering optimizations.
pub fn play_mixer_prerender(&self, mixer: &Mixer) -> Result<()> {
// For now, same as play_mixer - concurrent engine handles this efficiently
// In the future, could pre-render to buffer for guaranteed zero glitches
self.play_mixer(mixer)
}
/// Play a composition in a loop
///
/// Returns immediately with a `SoundId`. The sound will loop until stopped.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// let engine = AudioEngine::new()?;
/// let loop_id = engine.play_looping(&comp.into_mixer())?;
///
/// // Later: stop the loop
/// engine.stop(loop_id)?;
/// # Ok(())
/// # }
/// ```
pub fn play_looping(&self, mixer: &Mixer) -> Result<SoundId> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
// Clone mixer and automatically enable GPU if engine was created with GPU support
#[cfg(feature = "gpu")]
let mut mixer_clone = mixer.clone();
#[cfg(not(feature = "gpu"))]
let mixer_clone = mixer.clone();
#[cfg(feature = "gpu")]
if self.enable_gpu_for_samples {
mixer_clone.enable_gpu();
}
self.command_tx
.send(AudioCommand::Play {
id,
mixer: Box::new(mixer_clone),
looping: true,
})
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(id)
}
/// Play a one-shot sample immediately (convenience method with automatic caching)
///
/// Returns a builder that allows you to chain effects, volume, pan, speed, and more.
/// The sample plays automatically when the builder drops (fire-and-forget).
///
/// **Automatic caching:** Samples are automatically cached by path on first load. Subsequent
/// calls with the same path reuse the cached sample (cheap Arc clone), making repeated sounds
/// efficient without any extra code.
///
/// # Arguments
/// * `path` - Path to the sample file (WAV, OGG, MP3, FLAC supported)
///
/// # Returns
/// `SamplePlaybackBuilder` - Builder for chaining effects and parameters
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Simple playback
/// engine.play_sample("assets/footstep.wav");
///
/// // With effects (still fire-and-forget!)
/// engine.play_sample("assets/explosion.wav")
/// .volume(0.8)
/// .speed(1.2)
/// .reverb(Reverb::new(0.5, 0.3, 0.2));
///
/// // Spatial audio
/// engine.play_sample("assets/gunshot.wav")
/// .spatial(5.0, 0.0, 10.0) // 5m right, 10m forward
/// .volume(0.9);
///
/// // Chain multiple effects
/// engine.play_sample("assets/voice.wav")
/// .speed(0.8)
/// .reverb(Reverb::hall())
/// .delay(Delay::new(0.3, 0.4, 0.5))
/// .filter(Filter::low_pass(1200.0, 0.7));
/// # Ok(())
/// # }
/// ```
///
/// # Performance
/// - **First call per unique path:** Loads from disk (~1-10ms depending on file size)
/// - **Subsequent calls:** Instant (Arc clone from cache)
/// - **Memory:** Cached samples remain in memory until cleared with `clear_sample_cache()`
///
/// # Note
/// This method is **non-blocking** and returns immediately. The sound plays when the builder
/// drops, which happens at the end of the statement. Multiple sounds can play concurrently.
///
/// For cache management, see `preload_sample()`, `clear_sample_cache()`, and `remove_cached_sample()`.
///
/// For more control over synthesis or timing, use the full Composition API.
pub fn play_sample(&self, path: &str) -> SamplePlaybackBuilder<'_> {
SamplePlaybackBuilder::new(self, path)
}
/// Preload a sample into the cache without playing it
///
/// Useful for loading frequently-used samples during initialization to avoid
/// any loading delay on first playback.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Load samples during game initialization
/// engine.preload_sample("assets/footstep.wav")?;
/// engine.preload_sample("assets/jump.wav")?;
/// engine.preload_sample("assets/explosion.wav")?;
///
/// // Later: instant playback (already cached)
/// engine.play_sample("assets/footstep.wav");
/// # Ok(())
/// # }
/// ```
pub fn preload_sample(&self, path: &str) -> Result<()> {
use crate::synthesis::Sample;
if !self.sample_cache.contains_key(path) {
let sample = Sample::from_file(path).map_err(|e| {
TunesError::AudioEngineError(format!("Failed to preload sample '{}': {}", path, e))
})?;
// Use entry API to avoid race condition
self.sample_cache.entry(path.to_string()).or_insert(sample);
}
Ok(())
}
/// Remove a specific sample from the cache
///
/// Useful for freeing memory when a sample is no longer needed.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Use sample during level
/// engine.play_sample("level1_music.wav");
///
/// // Level complete - free the memory
/// engine.remove_cached_sample("level1_music.wav")?;
/// # Ok(())
/// # }
/// ```
pub fn remove_cached_sample(&self, path: &str) -> Result<()> {
self.sample_cache.remove(path);
Ok(())
}
/// Clear all cached samples to free memory
///
/// Useful for freeing memory between levels or game states.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Play various sounds during level
/// engine.play_sample("sound1.wav");
/// engine.play_sample("sound2.wav");
///
/// // Level complete - clear all cached samples
/// engine.clear_sample_cache()?;
/// # Ok(())
/// # }
/// ```
pub fn clear_sample_cache(&self) -> Result<()> {
self.sample_cache.clear();
Ok(())
}
/// Stop a playing sound
pub fn stop(&self, id: SoundId) -> Result<()> {
self.command_tx
.send(AudioCommand::Stop { id })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Set the volume of a playing sound
///
/// # Arguments
/// * `id` - The sound to modify
/// * `volume` - Volume level (0.0 = silence, 1.0 = full volume)
pub fn set_volume(&self, id: SoundId, volume: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetVolume { id, volume })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Set the stereo pan of a playing sound
///
/// # Arguments
/// * `id` - The sound to modify
/// * `pan` - Pan position (-1.0 = full left, 0.0 = center, 1.0 = full right)
pub fn set_pan(&self, id: SoundId, pan: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetPan { id, pan })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Set the playback rate (speed and pitch) of a playing sound
///
/// Changes both the speed and pitch of the sound. Higher values = faster/higher,
/// lower values = slower/lower. Clamped to 0.1x - 4.0x for stability.
///
/// # Arguments
/// * `id` - The sound to modify
/// * `rate` - Playback rate multiplier (1.0 = normal, 2.0 = double speed/octave up, 0.5 = half speed/octave down)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// # comp.track("sfx").note(&[440.0], 1.0);
/// let engine = AudioEngine::new()?;
/// let sound_id = engine.play_mixer_realtime(&comp.into_mixer())?;
///
/// // Play at double speed (one octave higher)
/// engine.set_playback_rate(sound_id, 2.0)?;
///
/// // Play at half speed (one octave lower)
/// engine.set_playback_rate(sound_id, 0.5)?;
/// # Ok(())
/// # }
/// ```
///
/// # Common use cases
/// - Footstep variations (0.9 - 1.1 for subtle variation)
/// - Impact sounds based on velocity (0.8 - 1.5)
/// - Voice pitch shifting
/// - Retro game sound effects
pub fn set_playback_rate(&self, id: SoundId, rate: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetPlaybackRate { id, rate })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Pause a playing sound
pub fn pause(&self, id: SoundId) -> Result<()> {
self.command_tx
.send(AudioCommand::Pause { id })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Resume a paused sound
pub fn resume(&self, id: SoundId) -> Result<()> {
self.command_tx
.send(AudioCommand::Resume { id })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Pause all currently playing sounds
///
/// Useful for game pause menus or when the application loses focus.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let engine = AudioEngine::new()?;
/// // Pause all audio when game pauses
/// engine.pause_all()?;
/// # Ok(())
/// # }
/// ```
pub fn pause_all(&self) -> Result<()> {
self.command_tx
.send(AudioCommand::PauseAll)
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Resume all paused sounds
///
/// Useful for resuming from a pause menu.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let engine = AudioEngine::new()?;
/// // Resume all audio when game unpauses
/// engine.resume_all()?;
/// # Ok(())
/// # }
/// ```
pub fn resume_all(&self) -> Result<()> {
self.command_tx
.send(AudioCommand::ResumeAll)
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Stop all currently playing sounds
///
/// Immediately stops and removes all active sounds. Useful for level transitions
/// or when you need to clear all audio.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let engine = AudioEngine::new()?;
/// // Clear all audio when transitioning levels
/// engine.stop_all()?;
/// # Ok(())
/// # }
/// ```
pub fn stop_all(&self) -> Result<()> {
self.command_tx
.send(AudioCommand::StopAll)
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Set a callback function to monitor the audio output stream
///
/// The callback receives the final mixed audio buffer that will be sent to the speakers.
/// This is useful for real-time visualization (oscilloscopes, waveforms, spectrum analyzers),
/// audio recording, or analysis. The callback is called from the audio thread, so it should
/// be fast and non-blocking.
///
/// **Performance note:** The callback is called once per audio buffer (typically every 10-20ms).
/// Keep processing minimal to avoid audio dropouts. For heavy processing, copy the data
/// and process it in a separate thread.
///
/// # Arguments
/// * `callback` - Function that receives audio samples. Set to `None` to disable monitoring.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # use std::sync::{Arc, Mutex};
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
/// let sample_buffer = Arc::new(Mutex::new(Vec::new()));
/// let buffer_clone = sample_buffer.clone();
///
/// // Set up monitoring for oscilloscope visualization
/// engine.set_monitor_callback(Some(Box::new(move |samples: &[f32]| {
/// let mut buffer = buffer_clone.lock().unwrap();
/// buffer.clear();
/// buffer.extend_from_slice(samples);
/// })));
///
/// // Now play audio and visualize it
/// let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("synth").note(&[440.0], 1.0);
/// engine.play_mixer(&comp.into_mixer())?;
/// # Ok(())
/// # }
/// ```
pub fn set_monitor_callback(&self, callback: Option<Box<dyn Fn(&[f32]) + Send + 'static>>) {
if let Ok(mut guard) = self.monitor_callback.lock() {
*guard = callback;
}
}
/// Fade out a playing sound to silence
///
/// Gradually reduces the volume to 0 over the specified duration, creating a
/// smooth fade out effect. The sound will stop automatically when the fade completes.
///
/// # Arguments
/// * `id` - The sound to fade
/// * `duration` - Fade duration in seconds
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// # let engine = AudioEngine::new()?;
/// let id = engine.play_mixer_realtime(&comp.into_mixer())?;
///
/// // Fade out over 2 seconds
/// engine.fade_out(id, 2.0)?;
/// # Ok(())
/// # }
/// ```
pub fn fade_out(&self, id: SoundId, duration: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::FadeOut { id, duration })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Fade in a playing sound from current volume to target volume
///
/// Gradually increases the volume from its current level to the target volume,
/// creating a smooth fade in effect.
///
/// # Arguments
/// * `id` - The sound to fade
/// * `duration` - Fade duration in seconds
/// * `target_volume` - Target volume (0.0-1.0)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// # let engine = AudioEngine::new()?;
/// let id = engine.play_mixer_realtime(&comp.into_mixer())?;
/// engine.set_volume(id, 0.0)?; // Start silent
///
/// // Fade in to 80% volume over 3 seconds
/// engine.fade_in(id, 3.0, 0.8)?;
/// # Ok(())
/// # }
/// ```
pub fn fade_in(&self, id: SoundId, duration: f32, target_volume: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::FadeIn {
id,
duration,
target_volume,
})
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Smoothly tween the pan of a playing sound
///
/// Gradually changes the pan from its current position to the target pan position
/// over the specified duration. Perfect for creating smooth panning effects like
/// sounds moving from left to right.
///
/// # Arguments
/// * `id` - The sound to pan
/// * `target_pan` - Target pan position (-1.0 = full left, 0.0 = center, 1.0 = full right)
/// * `duration` - Tween duration in seconds
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// # let engine = AudioEngine::new()?;
/// let id = engine.play_mixer_realtime(&comp.into_mixer())?;
///
/// // Smoothly pan from left to right over 5 seconds (helicopter flyby effect)
/// engine.set_pan(id, -1.0)?; // Start at full left
/// engine.tween_pan(id, 1.0, 5.0)?; // Pan to full right over 5 seconds
/// # Ok(())
/// # }
/// ```
pub fn tween_pan(&self, id: SoundId, target_pan: f32, duration: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::TweenPan {
id,
target_pan,
duration,
})
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Smoothly tween the playback rate (pitch and speed) of a playing sound
///
/// Gradually changes the playback rate from its current value to the target rate
/// over the specified duration. Since playback rate affects both pitch and speed,
/// this creates effects like engine sounds ramping up or slowing down.
///
/// # Arguments
/// * `id` - The sound to modify
/// * `target_rate` - Target playback rate (1.0 = normal, 2.0 = double speed/pitch, 0.5 = half speed/pitch)
/// * `duration` - Tween duration in seconds
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// # let engine = AudioEngine::new()?;
/// let id = engine.play_mixer_realtime(&comp.into_mixer())?;
///
/// // Smoothly speed up engine sound over 3 seconds (acceleration)
/// engine.tween_playback_rate(id, 2.0, 3.0)?;
///
/// // Later: slow down over 2 seconds (deceleration)
/// engine.tween_playback_rate(id, 0.5, 2.0)?;
/// # Ok(())
/// # }
/// ```
pub fn tween_playback_rate(&self, id: SoundId, target_rate: f32, duration: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::TweenPlaybackRate {
id,
target_rate,
duration,
})
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
/// Check if a sound is still playing
pub fn is_playing(&self, id: SoundId) -> bool {
let state = self.callback_state.lock().unwrap();
let index = id as usize;
index < state.active_sounds.len() && state.active_sounds[index].is_some()
}
// ============================================================================
// Spatial Audio Control Methods
// ============================================================================
/// Set the 3D position of a playing sound
///
/// Updates the spatial position of a sound in real-time. The sound will be
/// automatically panned and attenuated based on its position relative to the listener.
///
/// # Arguments
/// * `id` - The sound ID returned from `play_mixer_realtime()`
/// * `x` - X coordinate (left/right: negative = left, positive = right)
/// * `y` - Y coordinate (up/down: negative = below, positive = above)
/// * `z` - Z coordinate (forward/back: negative = behind, positive = in front)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
/// let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("guitar").note(&[440.0], 2.0);
///
/// let sound_id = engine.play_mixer_realtime(&comp.into_mixer())?;
///
/// // Move sound to the right over time
/// for i in 0..10 {
/// engine.set_sound_position(sound_id, i as f32, 0.0, 5.0)?;
/// std::thread::sleep(std::time::Duration::from_millis(100));
/// }
/// # Ok(())
/// # }
/// ```
pub fn set_sound_position(&self, id: SoundId, x: f32, y: f32, z: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetSoundPosition {
id,
position: SpatialPosition::new(x, y, z),
})
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
/// Set the listener's 3D position
///
/// The listener represents the "ears" or camera position in your 3D world.
/// All spatial audio is calculated relative to the listener's position and orientation.
///
/// # Arguments
/// * `x` - X coordinate
/// * `y` - Y coordinate
/// * `z` - Z coordinate
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Set listener at standing height
/// engine.set_listener_position(0.0, 1.7, 0.0)?;
/// # Ok(())
/// # }
/// ```
pub fn set_listener_position(&self, x: f32, y: f32, z: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetListenerPosition { x, y, z })
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
/// Set the listener's forward direction
///
/// Controls which direction the listener is facing. This affects how sounds
/// are panned (sounds in front are centered, sounds to the right are panned right, etc.).
///
/// The vector will be automatically normalized.
///
/// # Arguments
/// * `x` - X component of forward direction
/// * `y` - Y component of forward direction
/// * `z` - Z component of forward direction
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Face forward (+Z direction)
/// engine.set_listener_forward(0.0, 0.0, 1.0)?;
///
/// // Face right (+X direction)
/// engine.set_listener_forward(1.0, 0.0, 0.0)?;
/// # Ok(())
/// # }
/// ```
pub fn set_listener_forward(&self, x: f32, y: f32, z: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetListenerForward { x, y, z })
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
/// Set the velocity of a sound source for Doppler effect
///
/// The velocity determines the Doppler shift for moving sound sources.
/// Sounds moving toward the listener will have higher pitch, sounds moving
/// away will have lower pitch.
///
/// Velocity is in units per second (typically meters/second).
///
/// # Arguments
/// * `id` - The sound to modify
/// * `vx` - X velocity component (units per second)
/// * `vy` - Y velocity component (units per second)
/// * `vz` - Z velocity component (units per second)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
/// let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("car").note(&[110.0], 5.0);
/// let car_id = engine.play_mixer_realtime(&comp.into_mixer())?;
///
/// // Set position and velocity for a car passing by
/// engine.set_sound_position(car_id, -20.0, 0.0, 5.0)?;
/// engine.set_sound_velocity(car_id, 30.0, 0.0, 0.0)?; // 30 m/s to the right
///
/// // You'll hear the pitch shift as it approaches and passes
/// # Ok(())
/// # }
/// ```
pub fn set_sound_velocity(&self, id: SoundId, vx: f32, vy: f32, vz: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetSoundVelocity { id, vx, vy, vz })
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
/// Set the listener's velocity for Doppler effect
///
/// The listener velocity affects Doppler calculations for all sounds.
/// Useful when the player/camera is moving through the world.
///
/// Velocity is in units per second (typically meters/second).
///
/// # Arguments
/// * `vx` - X velocity component (units per second)
/// * `vy` - Y velocity component (units per second)
/// * `vz` - Z velocity component (units per second)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Player is moving forward at 5 m/s
/// engine.set_listener_velocity(0.0, 0.0, 5.0)?;
/// # Ok(())
/// # }
/// ```
pub fn set_listener_velocity(&self, vx: f32, vy: f32, vz: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetListenerVelocity { vx, vy, vz })
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
/// Configure spatial audio parameters
///
/// Controls how spatial audio behaves, including distance attenuation model,
/// maximum audible distance, Doppler effect, etc.
///
/// # Arguments
/// * `params` - Spatial audio parameters
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// let mut params = SpatialParams::default();
/// params.max_distance = 50.0; // Sounds silent beyond 50 units
/// params.attenuation_model = AttenuationModel::Linear;
///
/// engine.set_spatial_params(params)?;
/// # Ok(())
/// # }
/// ```
pub fn set_spatial_params(&self, params: SpatialParams) -> Result<()> {
self.command_tx
.send(AudioCommand::SetSpatialParams { params })
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
/// Set directional cone for a sound source
///
/// Makes a sound source directional, so it's louder when the listener is
/// in front of the source and quieter when behind or to the sides.
///
/// # Arguments
/// * `id` - Sound ID
/// * `cone` - Optional sound cone (None for omnidirectional)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let engine = AudioEngine::new()?;
/// # let sound_id = 1;
/// use tunes::synthesis::spatial::{SoundCone, Vec3};
///
/// // Create a narrow directional cone (like a megaphone)
/// let cone = SoundCone::narrow().with_direction(0.0, 0.0, 1.0);
/// engine.set_sound_cone(sound_id, Some(cone))?;
///
/// // Remove directionality (make omnidirectional)
/// engine.set_sound_cone(sound_id, None)?;
/// # Ok(())
/// # }
/// ```
pub fn set_sound_cone(&self, id: SoundId, cone: Option<SoundCone>) -> Result<()> {
self.command_tx
.send(AudioCommand::SetSoundCone { id, cone })
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
/// Set occlusion amount for a sound
///
/// Occlusion represents how much a sound is blocked by geometry/obstacles.
/// The game should use raycasting or other detection to determine occlusion
/// and then set this value.
///
/// # Arguments
/// * `id` - Sound ID
/// * `occlusion` - Occlusion amount (0.0 = no occlusion, 1.0 = fully occluded)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// # let engine = AudioEngine::new()?;
/// # let sound_id = 1;
/// // No occlusion (sound has clear path to listener)
/// engine.set_sound_occlusion(sound_id, 0.0)?;
///
/// // Partial occlusion (sound is partially blocked)
/// engine.set_sound_occlusion(sound_id, 0.6)?;
///
/// // Full occlusion (sound is completely blocked)
/// engine.set_sound_occlusion(sound_id, 1.0)?;
/// # Ok(())
/// # }
/// ```
pub fn set_sound_occlusion(&self, id: SoundId, occlusion: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetSoundOcclusion { id, occlusion })
.map_err(|_| TunesError::AudioEngineError("Failed to send command".to_string()))
}
// ============================================================================
// End Spatial Audio Control Methods
// ============================================================================
// ============================================================================
// Streaming Audio Methods
// ============================================================================
#[cfg(not(target_arch = "wasm32"))]
/// Stream an audio file from disk without loading it entirely into memory
///
/// Ideal for long background music, ambient sounds, or any audio where memory
/// usage is a concern. The file is decoded on-the-fly in a background thread
/// and streamed through a lock-free ring buffer.
///
/// Supports MP3, OGG, FLAC, WAV, and AAC formats via symphonia.
///
/// # Arguments
/// * `path` - Path to the audio file to stream
///
/// # Returns
/// `SoundId` - Unique identifier for controlling this stream
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Stream a long background music file
/// let music_id = engine.stream_file("assets/background_music.mp3")?;
///
/// // Control the stream
/// engine.set_stream_volume(music_id, 0.5)?;
/// engine.pause_stream(music_id)?;
/// engine.resume_stream(music_id)?;
/// engine.stop_stream(music_id)?;
/// # Ok(())
/// # }
/// ```
pub fn stream_file<P: Into<PathBuf>>(&self, path: P) -> Result<SoundId> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
self.command_tx
.send(AudioCommand::StreamFile {
id,
path: path.into(),
looping: false,
volume: 1.0,
pan: 0.0,
})
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(id)
}
#[cfg(not(target_arch = "wasm32"))]
/// Stream an audio file in a loop
///
/// Like `stream_file()`, but automatically restarts the file from the beginning
/// when it finishes. Perfect for looping background music.
///
/// # Arguments
/// * `path` - Path to the audio file to stream
///
/// # Returns
/// `SoundId` - Unique identifier for controlling this stream
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Loop background music forever
/// let music_id = engine.stream_file_looping("assets/music_loop.mp3")?;
///
/// // Stop when done
/// engine.stop_stream(music_id)?;
/// # Ok(())
/// # }
/// ```
pub fn stream_file_looping<P: Into<PathBuf>>(&self, path: P) -> Result<SoundId> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
self.command_tx
.send(AudioCommand::StreamFile {
id,
path: path.into(),
looping: true,
volume: 1.0,
pan: 0.0,
})
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(id)
}
#[cfg(not(target_arch = "wasm32"))]
/// Stop a streaming audio file
///
/// Stops the decoder thread and removes the stream. The sound will stop immediately.
///
/// # Arguments
/// * `id` - The stream ID returned by `stream_file()` or `stream_file_looping()`
pub fn stop_stream(&self, id: SoundId) -> Result<()> {
self.command_tx
.send(AudioCommand::StopStream { id })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
/// Pause a streaming audio file
///
/// Pauses playback without stopping the decoder thread. Use `resume_stream()` to continue.
///
/// # Arguments
/// * `id` - The stream ID to pause
pub fn pause_stream(&self, id: SoundId) -> Result<()> {
self.command_tx
.send(AudioCommand::PauseStream { id })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
/// Resume a paused streaming audio file
///
/// Resumes playback of a stream that was paused with `pause_stream()`.
///
/// # Arguments
/// * `id` - The stream ID to resume
pub fn resume_stream(&self, id: SoundId) -> Result<()> {
self.command_tx
.send(AudioCommand::ResumeStream { id })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
/// Set the volume of a streaming audio file
///
/// # Arguments
/// * `id` - The stream ID to modify
/// * `volume` - Volume level (0.0 = silence, 1.0 = full volume)
pub fn set_stream_volume(&self, id: SoundId, volume: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetStreamVolume { id, volume })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
/// Set the stereo pan of a streaming audio file
///
/// # Arguments
/// * `id` - The stream ID to modify
/// * `pan` - Pan position (-1.0 = full left, 0.0 = center, 1.0 = full right)
pub fn set_stream_pan(&self, id: SoundId, pan: f32) -> Result<()> {
self.command_tx
.send(AudioCommand::SetStreamPan { id, pan })
.map_err(|_| TunesError::AudioEngineError("Audio engine stopped".to_string()))?;
Ok(())
}
// ============================================================================
// End Streaming Audio Methods
// ============================================================================
/// Block until a sound finishes playing
///
/// Used internally by `play_mixer()` to provide blocking behavior.
///
/// # Arguments
/// * `id` - The sound ID to wait for
/// * `is_empty` - Whether the mixer is known to be empty (improves error messages)
fn wait_for(&self, id: SoundId, is_empty: bool) -> Result<()> {
use std::thread;
use std::time::Duration;
// Wait for sound to start playing (avoid race condition)
// The audio thread needs time to process the Play command
let mut started = false;
for _ in 0..100 {
// Try for up to 1 second
if self.is_playing(id) {
started = true;
break;
}
thread::sleep(Duration::from_millis(10));
}
if !started {
// Sound never started - could be:
// 1. Empty mixer (no events) - expected, not an error
// 2. Very short sound (< 10ms, finished before we checked) - expected
// 3. Audio thread not processing commands - critical failure
if is_empty {
// Empty mixer - this is expected, no warning needed
return Ok(());
} else {
// Non-empty mixer didn't play - unexpected
eprintln!(
"Warning: Sound {} never started or finished very quickly (< 10ms)",
id
);
return Ok(());
}
}
// Now wait for it to finish
while self.is_playing(id) {
thread::sleep(Duration::from_millis(10));
}
Ok(())
}
/// Export mixer to WAV file using the engine's sample rate
///
/// This is a convenience method that automatically uses the AudioEngine's sample rate,
/// ensuring the exported audio matches what you hear during playback.
///
/// # Arguments
/// * `mixer` - The mixer to export
/// * `path` - Output file path (e.g., "output.wav")
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
/// let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("piano").note(&[440.0], 1.0);
///
/// let mut mixer = comp.into_mixer();
/// engine.export_wav(&mut mixer, "output.wav")?;
/// # Ok(())
/// # }
/// ```
///
/// # Note
/// If you need a specific sample rate (e.g., for upsampling/downsampling),
/// use `mixer.export_wav(path, sample_rate)` directly.
pub fn export_wav(&self, mixer: &mut crate::track::Mixer, path: &str) -> anyhow::Result<()> {
// Automatically enable GPU if engine was created with GPU support
#[cfg(feature = "gpu")]
if self.enable_gpu_for_samples {
mixer.enable_gpu();
}
mixer.export_wav(path, self.sample_rate as u32)
}
/// Export mixer to FLAC file using the engine's sample rate
///
/// This is a convenience method that automatically uses the AudioEngine's sample rate.
/// FLAC provides lossless compression (typically 50-60% of WAV size).
///
/// # Arguments
/// * `mixer` - The mixer to export
/// * `path` - Output file path (e.g., "output.flac")
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
/// let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("piano").note(&[440.0], 1.0);
///
/// let mut mixer = comp.into_mixer();
/// engine.export_flac(&mut mixer, "output.flac")?;
/// # Ok(())
/// # }
/// ```
///
/// # Note
/// If you need a specific sample rate, use `mixer.export_flac(path, sample_rate)` directly.
pub fn export_flac(&self, mixer: &mut crate::track::Mixer, path: &str) -> anyhow::Result<()> {
// Automatically enable GPU if engine was created with GPU support
#[cfg(feature = "gpu")]
if self.enable_gpu_for_samples {
mixer.enable_gpu();
}
mixer.export_flac(path, self.sample_rate as u32)
}
/// Render mixer to an in-memory buffer using the engine's sample rate
///
/// Useful for pre-rendering sounds for later playback or further processing.
///
/// # Returns
/// Stereo interleaved samples as `Vec<f32>` (left, right, left, right, ...)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
/// let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("sfx").note(&[440.0], 0.1);
///
/// let mut mixer = comp.into_mixer();
/// let buffer = engine.render_to_buffer(&mut mixer);
/// println!("Rendered {} samples", buffer.len());
/// # Ok(())
/// # }
/// ```
pub fn render_to_buffer(&self, mixer: &mut crate::track::Mixer) -> Vec<f32> {
mixer.render_to_buffer(self.sample_rate)
}
}
/// Sample transformation operations that can be applied before playback
#[derive(Clone)]
enum SampleTransform {
Normalize,
Gain(f32),
Reverse,
FadeIn(f32),
FadeOut(f32),
TimeStretch(f32),
PitchShift(f32),
}
/// Builder for ergonomic one-shot sample playback with effects
///
/// Created by `AudioEngine::play_sample()`. Automatically plays on drop (fire-and-forget).
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = AudioEngine::new()?;
///
/// // Fire and forget with effects!
/// engine.play_sample("explosion.wav")
/// .volume(0.8)
/// .speed(1.2)
/// .reverb(Reverb::new(0.5, 0.3, 0.2));
///
/// // Auto-plays when builder drops
/// # Ok(())
/// # }
/// ```
pub struct SamplePlaybackBuilder<'a> {
engine: &'a AudioEngine,
path: String,
volume: f32,
pan: f32,
speed: f32,
spatial_position: Option<SpatialPosition>,
filter: Option<crate::synthesis::filter::Filter>,
effects: crate::synthesis::effects::EffectChain,
sample_transforms: Vec<SampleTransform>,
}
impl<'a> SamplePlaybackBuilder<'a> {
/// Create a new builder (internal - use AudioEngine::play_sample())
fn new(engine: &'a AudioEngine, path: impl Into<String>) -> Self {
Self {
engine,
path: path.into(),
volume: 1.0,
pan: 0.0,
speed: 1.0,
spatial_position: None,
filter: None,
effects: crate::synthesis::effects::EffectChain::new(),
sample_transforms: Vec::new(),
}
}
/// Set playback volume (0.0 to 2.0, default: 1.0)
pub fn volume(mut self, volume: f32) -> Self {
self.volume = volume.clamp(0.0, 2.0);
self
}
/// Set stereo pan (-1.0 = left, 0.0 = center, 1.0 = right, default: 0.0)
pub fn pan(mut self, pan: f32) -> Self {
self.pan = pan.clamp(-1.0, 1.0);
self
}
/// Set playback speed/pitch (1.0 = normal, 2.0 = double speed, 0.5 = half speed)
pub fn speed(mut self, speed: f32) -> Self {
self.speed = speed.max(0.01); // Prevent zero/negative speeds
self
}
/// Set 3D spatial position (x, y, z coordinates)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// // Position sound 5 meters to the right and 3 meters forward
/// engine.play_sample("footstep.wav")
/// .spatial(5.0, 0.0, 3.0);
/// ```
pub fn spatial(mut self, x: f32, y: f32, z: f32) -> Self {
self.spatial_position = Some(SpatialPosition::new(x, y, z));
self
}
/// Apply a filter to the sample
pub fn filter(mut self, filter: crate::synthesis::filter::Filter) -> Self {
self.filter = Some(filter);
self
}
/// Add reverb effect
pub fn reverb(mut self, reverb: crate::synthesis::effects::Reverb) -> Self {
self.effects.reverb = Some(reverb);
self.effects.compute_effect_order();
self
}
/// Add delay effect
pub fn delay(mut self, delay: crate::synthesis::effects::Delay) -> Self {
self.effects.delay = Some(delay);
self.effects.compute_effect_order();
self
}
/// Add distortion effect
pub fn distortion(mut self, distortion: crate::synthesis::effects::Distortion) -> Self {
self.effects.distortion = Some(distortion);
self.effects.compute_effect_order();
self
}
/// Add chorus effect
pub fn chorus(mut self, chorus: crate::synthesis::effects::Chorus) -> Self {
self.effects.chorus = Some(chorus);
self.effects.compute_effect_order();
self
}
/// Add phaser effect
pub fn phaser(mut self, phaser: crate::synthesis::effects::Phaser) -> Self {
self.effects.phaser = Some(phaser);
self.effects.compute_effect_order();
self
}
/// Add flanger effect
pub fn flanger(mut self, flanger: crate::synthesis::effects::Flanger) -> Self {
self.effects.flanger = Some(flanger);
self.effects.compute_effect_order();
self
}
/// Add tremolo effect
pub fn tremolo(mut self, tremolo: crate::synthesis::effects::Tremolo) -> Self {
self.effects.tremolo = Some(tremolo);
self.effects.compute_effect_order();
self
}
/// Add bitcrusher effect
pub fn bitcrusher(mut self, bitcrusher: crate::synthesis::effects::BitCrusher) -> Self {
self.effects.bitcrusher = Some(bitcrusher);
self.effects.compute_effect_order();
self
}
/// Add saturation effect
pub fn saturation(mut self, saturation: crate::synthesis::effects::Saturation) -> Self {
self.effects.saturation = Some(saturation);
self.effects.compute_effect_order();
self
}
/// Add compressor effect
pub fn compressor(mut self, compressor: crate::synthesis::effects::Compressor) -> Self {
self.effects.compressor = Some(compressor);
self.effects.compute_effect_order();
self
}
/// Add limiter effect
pub fn limiter(mut self, limiter: crate::synthesis::effects::Limiter) -> Self {
self.effects.limiter = Some(limiter);
self.effects.compute_effect_order();
self
}
/// Add convolution reverb effect
pub fn convolution_reverb(
mut self,
conv_reverb: crate::synthesis::effects::ConvolutionReverb,
) -> Self {
self.effects.convolution_reverb = Some(conv_reverb);
self.effects.compute_effect_order();
self
}
/// Add EQ effect
pub fn eq(mut self, eq: crate::synthesis::effects::EQ) -> Self {
self.effects.eq = Some(eq);
self.effects.compute_effect_order();
self
}
/// Add ring modulator effect
pub fn ring_mod(mut self, ring_mod: crate::synthesis::effects::RingModulator) -> Self {
self.effects.ring_mod = Some(ring_mod);
self.effects.compute_effect_order();
self
}
/// Add auto-pan effect
pub fn autopan(mut self, autopan: crate::synthesis::effects::AutoPan) -> Self {
self.effects.autopan = Some(autopan);
self.effects.compute_effect_order();
self
}
/// Add gate effect
pub fn gate(mut self, gate: crate::synthesis::effects::Gate) -> Self {
self.effects.gate = Some(gate);
self.effects.compute_effect_order();
self
}
// ========== Spectral Effects ==========
/// Add phase vocoder effect for time-stretching and pitch-shifting
pub fn phase_vocoder(
mut self,
phase_vocoder: crate::synthesis::effects::PhaseVocoder,
) -> Self {
self.effects.phase_vocoder = Some(phase_vocoder);
self.effects.compute_effect_order();
self
}
/// Add spectral freeze effect
pub fn spectral_freeze(
mut self,
spectral_freeze: crate::synthesis::effects::SpectralFreeze,
) -> Self {
self.effects.spectral_freeze = Some(spectral_freeze);
self.effects.compute_effect_order();
self
}
/// Add spectral gate effect for frequency-selective noise gating
pub fn spectral_gate(
mut self,
spectral_gate: crate::synthesis::effects::SpectralGate,
) -> Self {
self.effects.spectral_gate = Some(spectral_gate);
self.effects.compute_effect_order();
self
}
/// Add spectral compressor effect for frequency-selective compression
pub fn spectral_compressor(
mut self,
spectral_compressor: crate::synthesis::effects::SpectralCompressor,
) -> Self {
self.effects.spectral_compressor = Some(spectral_compressor);
self.effects.compute_effect_order();
self
}
/// Add spectral robotize effect for robotic voice transformation
pub fn spectral_robotize(
mut self,
spectral_robotize: crate::synthesis::effects::SpectralRobotize,
) -> Self {
self.effects.spectral_robotize = Some(spectral_robotize);
self.effects.compute_effect_order();
self
}
/// Add spectral delay effect for frequency-dependent delay
pub fn spectral_delay(
mut self,
spectral_delay: crate::synthesis::effects::SpectralDelay,
) -> Self {
self.effects.spectral_delay = Some(spectral_delay);
self.effects.compute_effect_order();
self
}
/// Add spectral filter effect for frequency-domain filtering
pub fn spectral_filter(
mut self,
spectral_filter: crate::synthesis::effects::SpectralFilter,
) -> Self {
self.effects.spectral_filter = Some(spectral_filter);
self.effects.compute_effect_order();
self
}
/// Add spectral blur effect for frequency smearing
pub fn spectral_blur(
mut self,
spectral_blur: crate::synthesis::effects::SpectralBlur,
) -> Self {
self.effects.spectral_blur = Some(spectral_blur);
self.effects.compute_effect_order();
self
}
/// Add spectral shift effect for frequency shifting
pub fn spectral_shift(
mut self,
spectral_shift: crate::synthesis::effects::SpectralShift,
) -> Self {
self.effects.spectral_shift = Some(spectral_shift);
self.effects.compute_effect_order();
self
}
/// Add spectral exciter effect for harmonic enhancement
pub fn spectral_exciter(
mut self,
spectral_exciter: crate::synthesis::effects::SpectralExciter,
) -> Self {
self.effects.spectral_exciter = Some(spectral_exciter);
self.effects.compute_effect_order();
self
}
/// Add spectral invert effect for frequency spectrum reversal
pub fn spectral_invert(
mut self,
spectral_invert: crate::synthesis::effects::SpectralInvert,
) -> Self {
self.effects.spectral_invert = Some(spectral_invert);
self.effects.compute_effect_order();
self
}
/// Add spectral widen effect for stereo widening
pub fn spectral_widen(
mut self,
spectral_widen: crate::synthesis::effects::SpectralWiden,
) -> Self {
self.effects.spectral_widen = Some(spectral_widen);
self.effects.compute_effect_order();
self
}
/// Add spectral morph effect for morphing spectrum toward target shapes
pub fn spectral_morph(
mut self,
spectral_morph: crate::synthesis::effects::SpectralMorph,
) -> Self {
self.effects.spectral_morph = Some(spectral_morph);
self.effects.compute_effect_order();
self
}
/// Add spectral dynamics effect for frequency-dependent compression/expansion
pub fn spectral_dynamics(
mut self,
spectral_dynamics: crate::synthesis::effects::SpectralDynamics,
) -> Self {
self.effects.spectral_dynamics = Some(spectral_dynamics);
self.effects.compute_effect_order();
self
}
/// Add spectral scramble effect for glitchy frequency bin randomization
pub fn spectral_scramble(
mut self,
spectral_scramble: crate::synthesis::effects::SpectralScramble,
) -> Self {
self.effects.spectral_scramble = Some(spectral_scramble);
self.effects.compute_effect_order();
self
}
/// Add formant shifter effect for vocal character transformation
pub fn formant_shifter(
mut self,
formant_shifter: crate::synthesis::effects::FormantShifter,
) -> Self {
self.effects.formant_shifter = Some(formant_shifter);
self.effects.compute_effect_order();
self
}
/// Add spectral harmonizer effect for pitch-shifted harmonies
pub fn spectral_harmonizer(
mut self,
spectral_harmonizer: crate::synthesis::effects::SpectralHarmonizer,
) -> Self {
self.effects.spectral_harmonizer = Some(spectral_harmonizer);
self.effects.compute_effect_order();
self
}
/// Add spectral resonator effect for resonant frequency peaks
pub fn spectral_resonator(
mut self,
spectral_resonator: crate::synthesis::effects::SpectralResonator,
) -> Self {
self.effects.spectral_resonator = Some(spectral_resonator);
self.effects.compute_effect_order();
self
}
/// Add spectral panner effect for frequency-based spatial positioning
pub fn spectral_panner(
mut self,
spectral_panner: crate::synthesis::effects::SpectralPanner,
) -> Self {
self.effects.spectral_panner = Some(spectral_panner);
self.effects.compute_effect_order();
self
}
// ========== Sample Transformation Methods ==========
/// Normalize the sample to peak amplitude
///
/// Scales the sample so the loudest point reaches ±1.0 without clipping.
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// engine.play_sample("quiet_sound.wav")
/// .normalize()
/// .volume(0.8);
/// ```
pub fn normalize(mut self) -> Self {
self.sample_transforms.push(SampleTransform::Normalize);
self
}
/// Apply gain to the sample data itself (pre-effect)
///
/// This is different from `.volume()` - it modifies the sample data before effects,
/// while `.volume()` adjusts the track volume after effects.
///
/// # Arguments
/// * `gain` - Gain multiplier (1.0 = unchanged, 0.5 = half, 2.0 = double)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// engine.play_sample("quiet.wav")
/// .gain(2.0) // Double the sample amplitude
/// .reverb(Reverb::hall());
/// ```
pub fn gain(mut self, gain: f32) -> Self {
self.sample_transforms.push(SampleTransform::Gain(gain));
self
}
/// Reverse the sample
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// // Play backwards cymbal
/// engine.play_sample("cymbal.wav")
/// .reverse();
/// ```
pub fn reverse(mut self) -> Self {
self.sample_transforms.push(SampleTransform::Reverse);
self
}
/// Fade in over a duration
///
/// # Arguments
/// * `duration` - Fade in duration in seconds
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// engine.play_sample("ambience.wav")
/// .fade_in(2.0); // 2 second fade in
/// ```
pub fn fade_in(mut self, duration: f32) -> Self {
self.sample_transforms
.push(SampleTransform::FadeIn(duration));
self
}
/// Fade out over a duration
///
/// # Arguments
/// * `duration` - Fade out duration in seconds
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// engine.play_sample("music.wav")
/// .fade_out(3.0); // 3 second fade out
/// ```
pub fn fade_out(mut self, duration: f32) -> Self {
self.sample_transforms
.push(SampleTransform::FadeOut(duration));
self
}
/// Time-stretch the sample without changing pitch
///
/// Uses WSOLA algorithm to change duration while preserving pitch.
///
/// # Arguments
/// * `factor` - Time stretch factor (0.5 = half duration, 2.0 = double duration)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// // Make footstep twice as long without changing pitch
/// engine.play_sample("footstep.wav")
/// .time_stretch(2.0);
/// ```
pub fn time_stretch(mut self, factor: f32) -> Self {
self.sample_transforms
.push(SampleTransform::TimeStretch(factor));
self
}
/// Pitch shift the sample
///
/// Changes the pitch while maintaining duration using time-stretch + resample.
///
/// # Arguments
/// * `semitones` - Pitch shift in semitones (12 = one octave up, -12 = one octave down)
///
/// # Example
/// ```no_run
/// # use tunes::prelude::*;
/// # let engine = AudioEngine::new().unwrap();
/// // Play voice one octave higher
/// engine.play_sample("voice.wav")
/// .pitch_shift(12.0);
/// ```
pub fn pitch_shift(mut self, semitones: f32) -> Self {
self.sample_transforms
.push(SampleTransform::PitchShift(semitones));
self
}
/// Internal method to execute playback
fn execute_play(&self) -> Result<SoundId> {
use crate::synthesis::Sample;
// Check cache first, load if not present (lock-free with DashMap)
let mut sample = if let Some(cached) = self.engine.sample_cache.get(&self.path) {
cached.clone()
} else {
let loaded = Sample::from_file(&self.path).map_err(|e| {
TunesError::AudioEngineError(format!(
"Failed to load sample '{}': {}",
self.path, e
))
})?;
self.engine
.sample_cache
.entry(self.path.clone())
.or_insert(loaded)
.clone()
};
// Apply sample transformations in order
for transform in &self.sample_transforms {
sample = match transform {
SampleTransform::Normalize => sample.normalize(),
SampleTransform::Gain(gain) => sample.with_gain(*gain),
SampleTransform::Reverse => sample.reverse(),
SampleTransform::FadeIn(duration) => sample.with_fade_in(*duration),
SampleTransform::FadeOut(duration) => sample.with_fade_out(*duration),
SampleTransform::TimeStretch(factor) => sample.time_stretch(*factor),
SampleTransform::PitchShift(semitones) => sample.pitch_shift(*semitones),
};
}
// Create composition with all the builder settings
let mut comp = Composition::new(Tempo::new(120.0));
let mut track = comp.track("_oneshot");
// Apply all settings
track = track.volume(self.volume).pan(self.pan);
if let Some(pos) = self.spatial_position {
track = track.spatial_position(pos.position.x, pos.position.y, pos.position.z);
}
if let Some(filter) = &self.filter {
track = track.filter(*filter);
}
// Apply effects
if self.effects.reverb.is_some() {
track = track.reverb(self.effects.reverb.clone().unwrap());
}
if self.effects.delay.is_some() {
track = track.delay(self.effects.delay.clone().unwrap());
}
if self.effects.distortion.is_some() {
track = track.distortion(self.effects.distortion.clone().unwrap());
}
if self.effects.chorus.is_some() {
track = track.chorus(self.effects.chorus.clone().unwrap());
}
if self.effects.phaser.is_some() {
track = track.phaser(self.effects.phaser.clone().unwrap());
}
if self.effects.flanger.is_some() {
track = track.flanger(self.effects.flanger.clone().unwrap());
}
if self.effects.tremolo.is_some() {
track = track.tremolo(self.effects.tremolo.clone().unwrap());
}
if self.effects.bitcrusher.is_some() {
track = track.bitcrusher(self.effects.bitcrusher.clone().unwrap());
}
if self.effects.saturation.is_some() {
track = track.saturation(self.effects.saturation.clone().unwrap());
}
if self.effects.compressor.is_some() {
track = track.compressor(self.effects.compressor.clone().unwrap());
}
if self.effects.limiter.is_some() {
track = track.limiter(self.effects.limiter.clone().unwrap());
}
if self.effects.convolution_reverb.is_some() {
track = track.convolution_reverb(self.effects.convolution_reverb.clone().unwrap());
}
if self.effects.eq.is_some() {
track = track.eq(self.effects.eq.clone().unwrap());
}
if self.effects.ring_mod.is_some() {
track = track.ring_mod(self.effects.ring_mod.clone().unwrap());
}
if self.effects.autopan.is_some() {
track = track.autopan(self.effects.autopan.clone().unwrap());
}
if self.effects.gate.is_some() {
track = track.gate(self.effects.gate.clone().unwrap());
}
// Apply spectral effects
if self.effects.phase_vocoder.is_some() {
track = track.phase_vocoder(self.effects.phase_vocoder.clone().unwrap());
}
if self.effects.spectral_freeze.is_some() {
track = track.spectral_freeze(self.effects.spectral_freeze.clone().unwrap());
}
if self.effects.spectral_gate.is_some() {
track = track.spectral_gate(self.effects.spectral_gate.clone().unwrap());
}
if self.effects.spectral_compressor.is_some() {
track = track.spectral_compressor(self.effects.spectral_compressor.clone().unwrap());
}
if self.effects.spectral_robotize.is_some() {
track = track.spectral_robotize(self.effects.spectral_robotize.clone().unwrap());
}
if self.effects.spectral_delay.is_some() {
track = track.spectral_delay(self.effects.spectral_delay.clone().unwrap());
}
if self.effects.spectral_filter.is_some() {
track = track.spectral_filter(self.effects.spectral_filter.clone().unwrap());
}
if self.effects.spectral_blur.is_some() {
track = track.spectral_blur(self.effects.spectral_blur.clone().unwrap());
}
if self.effects.spectral_shift.is_some() {
track = track.spectral_shift(self.effects.spectral_shift.clone().unwrap());
}
if self.effects.spectral_exciter.is_some() {
track = track.spectral_exciter(self.effects.spectral_exciter.clone().unwrap());
}
if self.effects.spectral_invert.is_some() {
track = track.spectral_invert(self.effects.spectral_invert.clone().unwrap());
}
if self.effects.spectral_widen.is_some() {
track = track.spectral_widen(self.effects.spectral_widen.clone().unwrap());
}
if self.effects.spectral_morph.is_some() {
track = track.spectral_morph(self.effects.spectral_morph.clone().unwrap());
}
if self.effects.spectral_dynamics.is_some() {
track = track.spectral_dynamics(self.effects.spectral_dynamics.clone().unwrap());
}
if self.effects.spectral_scramble.is_some() {
track = track.spectral_scramble(self.effects.spectral_scramble.clone().unwrap());
}
if self.effects.formant_shifter.is_some() {
track = track.formant_shifter(self.effects.formant_shifter.clone().unwrap());
}
if self.effects.spectral_harmonizer.is_some() {
track = track.spectral_harmonizer(self.effects.spectral_harmonizer.clone().unwrap());
}
if self.effects.spectral_resonator.is_some() {
track = track.spectral_resonator(self.effects.spectral_resonator.clone().unwrap());
}
if self.effects.spectral_panner.is_some() {
track = track.spectral_panner(self.effects.spectral_panner.clone().unwrap());
}
// Play the sample
track.play_sample(&sample, self.speed);
// Convert to mixer
#[cfg(feature = "gpu")]
let mut mixer = comp.into_mixer();
#[cfg(not(feature = "gpu"))]
let mixer = comp.into_mixer();
#[cfg(feature = "gpu")]
{
if self.engine.enable_gpu_for_samples {
mixer.enable_cache_and_gpu();
}
}
self.engine.play_mixer_realtime(&mixer)
}
}
impl<'a> Drop for SamplePlaybackBuilder<'a> {
fn drop(&mut self) {
// Fire and forget - play on drop, but report errors
if let Err(e) = self.execute_play() {
eprintln!("Failed to play sample '{}': {}", self.path, e);
}
}
}
// Note: Full integration tests requiring audio devices should be placed in
// tests/integration_tests.rs with #[ignore] attribute for CI environments
// without audio hardware.