e_midi 0.1.13

An interactive/CLI/library MIDI player with advanced playback options, looping, and scan modes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
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
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
use e_midi_shared::play_media_file;
use e_midi_shared::types::SongSource;
use log::trace;
use midir::MidiOutput;
use midly::{MidiMessage, Smf, TrackEventKind};
use std::collections::HashSet;
use std::error::Error;
use std::fs;
use std::io::{stdin, stdout, Write};
use std::path::Path;
use std::sync::{
    atomic::{AtomicBool, AtomicU32, Ordering},
    mpsc, Arc, Mutex,
};
use std::thread::{self, sleep, JoinHandle};
use std::time::{Duration, Instant};
// Import the IPC module (now fixed)
pub use e_midi_shared::ipc;
pub use e_midi_shared::types::{Note, SongInfo, SongType, TrackInfo, XmlSongInfo, XmlTrackInfo};
#[cfg(feature = "uses_rodio")]
use rodio::Decoder;
#[cfg(feature = "uses_rodio")]
use rodio::OutputStream;
#[cfg(feature = "uses_rodio")]
use rodio::Sink;
#[cfg(feature = "uses_rodio")]
use std::io::Cursor;
// Global shutdown flag for graceful Ctrl+C handling
static SHUTDOWN: AtomicBool = AtomicBool::new(false);

pub fn set_shutdown_flag() {
    SHUTDOWN.store(true, Ordering::Relaxed);
}

pub fn should_shutdown() -> bool {
    SHUTDOWN.load(Ordering::Relaxed)
}
/// Format duration in milliseconds to a readable string
pub fn format_duration(duration_ms: u32) -> String {
    let seconds = duration_ms / 1000;
    let minutes = seconds / 60;
    let remaining_seconds = seconds % 60;

    if minutes > 0 {
        format!("{}m{:02}s", minutes, remaining_seconds)
    } else {
        format!("{}s", remaining_seconds)
    }
}
// MIDI command messages for the background thread
#[derive(Debug, Clone)]
pub enum MidiCommand {
    NoteOn {
        channel: u8,
        pitch: u8,
        velocity: u8,
    },
    NoteOff {
        channel: u8,
        pitch: u8,
    },
    SendMessage(Vec<u8>),
    AllNotesOff,
    Shutdown,
    Stop,
    PlaySongResumeAware {
        song_index: Option<usize>,
        position_ms: Option<u32>,
        tracks: Option<Vec<usize>>,
        tempo_bpm: Option<u32>,
    },
}

#[derive(Debug, Clone)]
pub struct MidiPlayerCore {
    pub static_songs: Vec<SongInfo>,
    pub dynamic_songs: Vec<SongInfo>,
    pub dynamic_midi_data: Vec<Vec<u8>>,
    pub config: LoopConfig,
}
// Bring in the generated static song data and get_songs() function
// (SongData struct is now only defined in lib.rs, not generated)
// include!(concat!(env!("OUT_DIR"), "/midi_data.rs"));
include!(concat!(env!("OUT_DIR"), "/embedded_midi.rs"));

/// Calculate the total duration of a song in milliseconds
pub fn calculate_song_duration_ms(events: &[Note]) -> u32 {
    events
        .iter()
        .map(|note| note.start_ms + note.dur_ms)
        .max()
        .unwrap_or(0)
}

pub mod cli;
mod tui;

#[derive(Clone, Debug)]
/// Configuration for looping and playback behavior
pub struct LoopConfig {
    /// Whether to loop the entire playlist continuously
    pub loop_playlist: bool,
    /// Whether to loop individual songs
    pub loop_individual_songs: bool,
    /// Duration of each scan segment in milliseconds
    pub scan_segment_duration_ms: u32,
    /// Whether to start scan segments at random positions
    pub scan_random_start: bool,
    /// Delay between songs in milliseconds
    pub delay_between_songs_ms: u32,
}

impl Default for LoopConfig {
    fn default() -> Self {
        LoopConfig {
            loop_playlist: false,
            loop_individual_songs: false,
            scan_segment_duration_ms: 30000, // 30 seconds
            scan_random_start: false,
            delay_between_songs_ms: 0, // No delay between songs by default
        }
    }
}

pub struct MidiPlayer {
    // Channel for sending commands to the background thread
    midi_sender: mpsc::Sender<MidiCommand>,
    _midi_thread: JoinHandle<()>,

    // Playback state for read/query by API and examples
    pub static_songs: Vec<SongInfo>,
    pub dynamic_songs: Vec<SongInfo>,
    pub dynamic_midi_data: Vec<Vec<u8>>,
    pub config: LoopConfig,
    pub ipc_manager: Option<ipc::IpcServiceManager>,
    playback_stop_flag: Arc<AtomicBool>,
    is_playing: Arc<AtomicBool>,
    current_song_index: Option<usize>,
    elapsed_ms: Option<u32>,
    current_tick: Option<u32>,
    start_instant: Option<Instant>,
}

impl MidiPlayer {
    pub fn new() -> Result<Self, Box<dyn Error>> {
        let midi_out = MidiOutput::new("e_midi")?;
        let ports = midi_out.ports();

        // Debug: List available MIDI ports
        println!("🎹 Available MIDI ports:");
        if ports.is_empty() {
            println!("❌ No MIDI output ports found!");
            println!("💡 To hear sound, you need:");

            #[cfg(target_os = "windows")]
            {
                println!("   - Windows built-in MIDI synthesizer (usually available)");
                println!("   - A software synthesizer (like VirtualMIDISynth)");
                println!("   - Or a hardware MIDI device");
            }

            #[cfg(target_os = "macos")]
            {
                println!("   - Enable IAC Driver in Audio MIDI Setup:");
                println!("     1. Open Audio MIDI Setup (Applications → Utilities)");
                println!("     2. Window → Show MIDI Studio");
                println!("     3. Double-click IAC Driver and check 'Device is online'");
                println!("   - Install a software synthesizer:");
                println!("     • SimpleSynth: https://notahat.com/simplesynth/");
                println!("     • FluidSynth: brew install fluidsynth");
                println!("   - Or connect a hardware MIDI device");
            }

            #[cfg(target_os = "linux")]
            {
                println!("   - Install and configure ALSA MIDI or JACK");
                println!("   - Software synthesizer (like FluidSynth, TiMidity++)");
                println!("   - Or a hardware MIDI device");
            }
        } else {
            for (i, port) in ports.iter().enumerate() {
                match midi_out.port_name(port) {
                    Ok(name) => println!("  {}: {}", i, name),
                    Err(_) => println!("  {}: <Unknown>", i),
                }
            }
        }

        let port = ports.first().ok_or("missing MIDI output port")?;
        let port_name = midi_out
            .port_name(port)
            .unwrap_or_else(|_| "Unknown".to_string());
        let conn = midi_out.connect(port, "e_midi")?;
        println!("🔌 Connected to MIDI port: {}", port_name);

        // Create the channel for sending MIDI commands to the background thread
        let (sender, receiver) = mpsc::channel::<MidiCommand>();

        // Initialize playback state for both the API and the background thread
        let static_songs = get_songs();
        let dynamic_songs = Vec::new();
        let dynamic_midi_data = Vec::new();
        let config = LoopConfig::default();
        let ipc_manager = None;

        // Copy for background thread
        let core_state = MidiPlayerCore {
            static_songs: static_songs.clone(),
            dynamic_songs: dynamic_songs.clone(),
            dynamic_midi_data: dynamic_midi_data.clone(),
            config: config.clone(),
        };

        // Spawn the background MIDI thread, move core into it
        let midi_thread = thread::spawn(move || {
            Self::midi_thread_loop(conn, receiver, core_state);
        });

        Ok(MidiPlayer {
            midi_sender: sender,
            _midi_thread: midi_thread,
            static_songs,
            dynamic_songs,
            dynamic_midi_data,
            config,
            ipc_manager,
            playback_stop_flag: Arc::new(AtomicBool::new(false)),
            is_playing: Arc::new(AtomicBool::new(false)),
            current_song_index: None,
            elapsed_ms: None,
            current_tick: None,
            start_instant: None,
        })
    }

    /// Play a song with IPC event publishing for TUI integration
    pub fn play_song_with_ipc(&mut self, song_index: usize) -> Result<(), Box<dyn Error>> {
        if song_index >= self.get_total_song_count() {
            return Err("Invalid song index".into());
        }

        let selected_song = self.get_song(song_index).ok_or("Invalid song index")?;
        let track_indices: Vec<usize> = selected_song.tracks.iter().map(|t| t.index).collect();
        let tempo = selected_song.default_tempo;

        // Publish playback started event
        self.publish_midi_event(crate::ipc::Event::MidiPlaybackStarted {
            song_index,
            song_name: selected_song.name.clone(),
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        });

        let events = get_events_for_song_tracks(song_index, &track_indices, tempo);
        if events.is_empty() {
            // Publish stopped event immediately if no events
            self.publish_midi_event(crate::ipc::Event::MidiPlaybackStopped {
                timestamp: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis() as u64,
            });
            return Err("No events to play! Check track selection.".into());
        } // Use the non-blocking playback method to avoid blocking the TUI
        let handle = self.play_song_with_ipc_nonblocking(song_index)?;
        let _ = handle.join();

        Ok(())
    }

    /// Non-blocking version of play_song_with_ipc that spawns playback in a background thread
    pub fn play_song_with_ipc_nonblocking(
        &mut self,
        song_index: usize,
    ) -> Result<JoinHandle<()>, Box<dyn Error>> {
        if song_index >= self.get_total_song_count() {
            return Err("Invalid song index".into());
        }

        let selected_song = self.get_song(song_index).ok_or("Invalid song index")?;
        let track_indices: Vec<usize> = selected_song.tracks.iter().map(|t| t.index).collect();
        let tempo = selected_song.default_tempo;

        // Publish playback started event
        self.publish_midi_event(crate::ipc::Event::MidiPlaybackStarted {
            song_index,
            song_name: selected_song.name.clone(),
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        });

        let events = get_events_for_song_tracks(song_index, &track_indices, tempo);
        if events.is_empty() {
            // Publish stopped event immediately if no events
            self.publish_midi_event(crate::ipc::Event::MidiPlaybackStopped {
                timestamp: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis() as u64,
            });
            return Err("No events to play! Check track selection.".into());
        }
        // Reset the stop flag before starting new playback
        self.reset_stop_flag();
        self.is_playing.store(true, Ordering::Relaxed);

        // Clone the MIDI sender and stop flag for the background thread
        let midi_sender = self.midi_sender.clone();
        let stop_flag = Arc::clone(&self.playback_stop_flag);
        let playing_state = Arc::clone(&self.is_playing);
        let events_clone = events.clone();

        // Spawn playback in a background thread and return the handle
        let handle = thread::spawn(move || {
            if let Err(e) = Self::play_events_in_background(
                events_clone,
                tempo,
                midi_sender,
                stop_flag,
                playing_state,
            ) {
                eprintln!("Background playback error: {}", e);
            }
        });

        Ok(handle)
    }

    fn publish_midi_event(&self, event: crate::ipc::Event) {
        if let Some(ref ipc_manager) = self.ipc_manager {
            let _ = ipc_manager.publish_event(event); // Silently ignore errors
        }
    }
    /// Initialize IPC publisher for event-driven communication
    pub fn init_ipc_publisher(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if self.ipc_manager.is_none() {
            match ipc::IpcServiceManager::new(ipc::AppId::EMidi) {
                Ok(manager) => {
                    self.ipc_manager = Some(manager);
                    // // Automatically set the global relay if available
                    // if let Some(sender) = self
                    //     .ipc_manager
                    //     .as_ref()
                    //     .and_then(|mgr| mgr.get_event_sender())
                    // {
                    //     // Set the global OnceCell if it hasn't been set yet
                    //     let _ = crate::ipc::IPC_EVENT_SENDER.set(sender.clone());
                    // }
                    // // --- NEW: Set the global IPC_SERVICE_MANAGER for static publishing ---
                    // #[allow(unused_imports)]
                    // use e_midi_shared::ipc::IPC_SERVICE_MANAGER;
                    // if let Some(ipc_manager) = self.ipc_manager.as_ref() {
                    //     let _ = IPC_SERVICE_MANAGER.set(ipc_manager.clone());
                    // }
                    // IPC initialized silently - no output to avoid TUI corruption
                    Ok(())
                }
                Err(_) => {
                    // Silently fail - IPC is optional for the MIDI player
                    Ok(())
                }
            }
        } else {
            Ok(()) // Already initialized
        }
    }

    /// Static method to play events in a background thread
    fn play_events_in_background(
        events: Vec<Note>,
        _tempo_bpm: u32,
        midi_sender: std::sync::mpsc::Sender<MidiCommand>,
        stop_flag: Arc<AtomicBool>,
        playing_state: Arc<AtomicBool>,
    ) -> Result<(), Box<dyn Error>> {
        use std::thread;
        use std::time::Instant;

        #[derive(Copy, Clone)]
        enum Kind {
            On,
            Off,
        }

        struct Scheduled {
            t: u32,
            kind: Kind,
            chan: u8,
            p: u8,
            v: u8,
            track: u8, // propagate track for debug
        }

        let mut timeline = Vec::with_capacity(events.len() * 2);
        for n in &events {
            timeline.push(Scheduled {
                t: n.start_ms,
                kind: Kind::On,
                chan: n.chan,
                p: n.pitch,
                v: n.vel,
                track: n.track,
            });
            timeline.push(Scheduled {
                t: n.start_ms + n.dur_ms,
                kind: Kind::Off,
                chan: n.chan,
                p: n.pitch,
                v: 0,
                track: n.track,
            });
        }
        timeline.sort_by_key(|e| e.t);

        // --- IPC: create zero-copy publisher for MidiNoteEvent ---
        // let mut publisher = iceoryx2::port::publisher::Publisher::<iceoryx2::service::ipc::Service, e_midi_shared::ipc_protocol::MidiNoteEvent, ()>::create("e_midi_midi_note_events").expect("Failed to create MidiNoteEvent publisher");
        let node =
            iceoryx2::node::NodeBuilder::new().create::<iceoryx2::service::ipc::Service>()?;

        let service = node
            .service_builder(&iceoryx2::prelude::ServiceName::new(
                ipc::EMIDI_EVENTS_SERVICE,
            )?)
            .publish_subscribe::<e_midi_shared::ipc_protocol::MidiNoteEvent>()
            .max_publishers(16)
            .max_subscribers(16)
            .open_or_create()?;
        let publisher = service.publisher_builder().create()?;
        let start = Instant::now();
        let mut idx = 0;

        while idx < timeline.len() {
            // Check for global shutdown or local stop flag
            if should_shutdown() || stop_flag.load(Ordering::Relaxed) {
                break;
            }

            let event = &timeline[idx];
            let target_time_ms = event.t.saturating_sub(0) as u64;
            let elapsed_ms = start.elapsed().as_millis() as u64;
            if elapsed_ms < target_time_ms {
                let sleep_ms = target_time_ms - elapsed_ms;
                println!("[PLAYBACK DEBUG] idx={} target_time_ms={} elapsed_ms={} sleep_ms={} chan={} pitch={} v={} track={}", idx, target_time_ms, elapsed_ms, sleep_ms, event.chan, event.p, event.v, event.track);
                thread::sleep(Duration::from_millis(std::cmp::min(sleep_ms, 50)));
                continue;
            }
            // Send MIDI event through the channel
            let msg = match event.kind {
                Kind::On => vec![0x90 | event.chan, event.p, event.v],
                Kind::Off => vec![0x80 | event.chan, event.p, 0],
            };
            // --- IPC: publish note-level event ---
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64;
            let midi_note_event = e_midi_shared::ipc_protocol::MidiNoteEvent {
                channel: event.chan,
                pitch: event.p,
                velocity: if let Kind::On = event.kind {
                    event.v
                } else {
                    0
                },
                kind: match event.kind {
                    Kind::On => 0,
                    Kind::Off => 1,
                },
                timestamp: now,
                _reserved: [0; 4],
            };
            if let Err(e) = publisher.send_copy(midi_note_event) {
                eprintln!("[IPC ERROR] Failed to send MidiNoteEvent: {:?}", e);
            }

            if midi_sender.send(MidiCommand::SendMessage(msg)).is_err() {
                // MIDI thread is probably shutdown, exit gracefully
                println!("[ERROR] Failed to send MIDI message, shutting down playback thread");
                break;
            }
            idx += 1;
        }
        // Mark playback as finished
        playing_state.store(false, Ordering::Relaxed);
        Ok(())
    }
    /// Get a clone of the MIDI command sender for non-blocking, lock-free command queuing
    pub fn get_command_sender(&self) -> std::sync::mpsc::Sender<MidiCommand> {
        self.midi_sender.clone()
    }
    pub fn command_sender(&self) -> std::sync::mpsc::Sender<MidiCommand> {
        self.midi_sender.clone()
    }
    // Background MIDI thread that handles all MIDI output and playback
    fn midi_thread_loop(
        conn: midir::MidiOutputConnection,
        receiver: std::sync::mpsc::Receiver<MidiCommand>,
        core_state: MidiPlayerCore,
    ) {
        use std::sync::{
            atomic::{AtomicBool, Ordering},
            Arc,
        };
        use std::time::{Duration, Instant};

        println!("🎹 MIDI background thread started");
        // Playback state for the background thread
        let playback_stop_flag = Arc::new(AtomicBool::new(false));
        let mut playback_thread: Option<
            std::thread::JoinHandle<(midir::MidiOutputConnection, u32)>,
        > = None;
        // Track last stopped position for each song
        use std::collections::HashMap;
        let mut last_positions: HashMap<usize, u32> = HashMap::new();
        let mut current_playing: Option<(usize, u32)> = None; // (song_index, start_ms)
                                                              // Helper to stop playback
        let stop_playback = |stop_flag: &Arc<AtomicBool>,
                             playback_thread: &mut Option<
            std::thread::JoinHandle<(midir::MidiOutputConnection, u32)>,
        >,
                             current_playing: &mut Option<(usize, u32)>,
                             last_positions: &mut HashMap<usize, u32>| {
            stop_flag.store(true, Ordering::Relaxed);
            // Wait for playback thread to finish and return the connection and last played ms
            if let Some(handle) = playback_thread.take() {
                if let Ok((conn_back, last_ms)) = handle.join() {
                    // Record last position if possible
                    if let Some((song_idx, _)) = current_playing.take() {
                        last_positions.insert(song_idx, last_ms);
                    }
                    return Some(conn_back);
                }
            }
            // If not joined, still clear current_playing
            current_playing.take();
            None
        };
        let node = iceoryx2::node::NodeBuilder::new()
            .create::<iceoryx2::service::ipc::Service>()
            .expect("Failed to create IPC node");

        let service = node
            .service_builder(
                &iceoryx2::prelude::ServiceName::new(ipc::EMIDI_EVENTS_SERVICE)
                    .expect("Failed to create service name"),
            )
            .publish_subscribe::<e_midi_shared::ipc_protocol::MidiNoteEvent>()
            .max_publishers(16)
            .max_subscribers(16)
            .open_or_create();
        let publisher = service
            .expect("service bad")
            .publisher_builder()
            .create()
            .expect("Failed to create publisher");
        // Move conn into the playback thread, get it back after join
        let mut conn_opt = Some(conn);
        while let Ok(command) = receiver.recv() {
            trace!("🎹 [MIDI THREAD] Received command: {:?}", command); // DEBUG
            match command {
                MidiCommand::NoteOn {
                    channel,
                    pitch,
                    velocity,
                } => {
                    // --- IPC: publish note-on event ---
                    let event = e_midi_shared::ipc::Event::MidiNoteOn {
                        channel,
                        pitch,
                        velocity,
                        timestamp: std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_millis() as u64,
                    };
                    println!(
                        "[IPC DEBUG] Publishing MidiNoteOn: channel={}, pitch={}, velocity={}",
                        channel, pitch, velocity
                    );
                    e_midi_shared::ipc::IpcServiceManager::publish_ipc_event(event);
                    // if let Err(e) = res {
                    //     eprintln!("[IPC ERROR] Failed to publish MidiNoteOn: {}", e);
                    // }
                    if let Some(conn) = conn_opt.as_mut() {
                        let msg = [0x90 | (channel & 0x0F), pitch, velocity];
                        let _ = conn.send(&msg);
                    }
                }
                MidiCommand::NoteOff { channel, pitch } => {
                    if let Some(conn) = conn_opt.as_mut() {
                        let msg = [0x80 | (channel & 0x0F), pitch, 0];
                        let _ = conn.send(&msg);
                    }
                }
                MidiCommand::SendMessage(msg) => {
                    if let Some(conn) = conn_opt.as_mut() {
                        let _ = conn.send(&msg);
                    }
                }
                MidiCommand::AllNotesOff => {
                    if let Some(conn) = conn_opt.as_mut() {
                        for channel in 0..16 {
                            let msg = [0xB0 | channel, 123, 0];
                            let _ = conn.send(&msg);
                        }
                    }
                }
                MidiCommand::Shutdown => {
                    println!("🎹 MIDI background thread shutting down");
                    stop_playback(
                        &playback_stop_flag,
                        &mut playback_thread,
                        &mut current_playing,
                        &mut last_positions,
                    );
                    break;
                }
                MidiCommand::Stop => {
                    println!("🎹 [MIDI THREAD] Processing STOP command"); // DEBUG
                    conn_opt = stop_playback(
                        &playback_stop_flag,
                        &mut playback_thread,
                        &mut current_playing,
                        &mut last_positions,
                    )
                    .or(conn_opt);
                }
                MidiCommand::PlaySongResumeAware {
                    song_index,
                    position_ms,
                    tracks,
                    tempo_bpm,
                } => {
                    println!(
                        "🎹 [MIDI THREAD] Processing PlaySongResumeAware: song_index={:?}",
                        song_index
                    ); // DEBUG
                       // Stop any current playback and get the connection back
                    conn_opt = stop_playback(
                        &playback_stop_flag,
                        &mut playback_thread,
                        &mut current_playing,
                        &mut last_positions,
                    )
                    .or(conn_opt);
                    // Reset stop flag for new playback
                    playback_stop_flag.store(false, Ordering::Relaxed);
                    let stop_flag = Arc::clone(&playback_stop_flag);
                    if let (Some(idx), Some(mut conn)) = (song_index, conn_opt.take()) {
                        let static_count = core_state.static_songs.len();
                        // --- PATCH: Always play all tracks if tracks is None ---
                        let (song, _is_static) = if idx < static_count {
                            (&core_state.static_songs[idx], true)
                        } else {
                            let dyn_idx = idx - static_count;
                            if dyn_idx < core_state.dynamic_songs.len() {
                                (&core_state.dynamic_songs[dyn_idx], false)
                            } else {
                                println!("[ERROR] Song index {} out of range", idx);
                                return;
                            }
                        };
                        // Always use user-facing track indices (track.index) for all tracks
                        let track_indices: Vec<usize> = match &tracks {
                            Some(t) => t.clone(),
                            None => (0..song.tracks.len()).collect(), // Always use dense indices
                        };
                        let tempo = tempo_bpm.unwrap_or(song.default_tempo);
                        let events = get_events_for_song_tracks(idx, &track_indices, tempo);
                        println!("[DEBUG][MIDI THREAD] events.len() = {}", events.len());
                        if let Some(first) = events.first() {
                            println!("[DEBUG][MIDI THREAD] first event: start_ms={}, dur_ms={}, chan={}, pitch={}, vel={}", first.start_ms, first.dur_ms, first.chan, first.pitch, first.vel);
                        }
                        // Determine start_ms: if position_ms is Some, use it; else use last_positions, but clamp to song duration
                        let song_duration = events
                            .iter()
                            .map(|e| e.start_ms + e.dur_ms)
                            .max()
                            .unwrap_or(0);
                        let start_ms = match position_ms {
                            Some(ms) => ms,
                            None => {
                                let pos = last_positions.get(&idx).copied().unwrap_or(0);
                                if pos >= song_duration {
                                    0
                                } else {
                                    pos
                                }
                            }
                        };
                        // Update current_playing
                        current_playing = Some((idx, start_ms));
                        let timeline = {
                            let mut timeline = Vec::with_capacity(events.len() * 2);
                            for n in &events {
                                timeline.push((n.start_ms, true, n.chan, n.pitch, n.vel));
                                timeline.push((n.start_ms + n.dur_ms, false, n.chan, n.pitch, 0));
                            }
                            timeline.sort_by_key(|e| e.0);
                            timeline
                        };
                        println!("[DEBUG][MIDI THREAD] timeline.len() = {}", timeline.len());
                        // Move only the MIDI connection into the thread.
                        // All IPC publisher usage must remain in the parent thread due to !Send/!Sync.
                        let stop_flag_clone = Arc::clone(&stop_flag);
                        let timeline_clone = timeline.clone();

                        playback_thread = Some(std::thread::spawn(move || {
                            let start = Instant::now();
                            let mut idx_tl = 0;
                            // Send all events at or before start_ms immediately (fix for short songs)
                            let mut sent_first = false;
                            let mut last_played_ms = start_ms;
                            while idx_tl < timeline_clone.len()
                                && timeline_clone[idx_tl].0 <= start_ms
                            {
                                let (t, on, chan, pitch, vel) = timeline_clone[idx_tl];
                                let msg = if on {
                                    [0x90 | (chan & 0x0F), pitch, vel]
                                } else {
                                    [0x80 | (chan & 0x0F), pitch, 0]
                                };
                                if !sent_first && on {
                                    println!("[DEBUG][MIDI THREAD] Sending first note: chan={}, pitch={}, vel={}", chan, pitch, vel);
                                    sent_first = true;
                                }
                                let _ = conn.send(&msg);
                                last_played_ms = t;
                                idx_tl += 1;
                            }
                            // Now continue with timed playback for remaining events
                            while idx_tl < timeline_clone.len() {
                                if stop_flag_clone.load(Ordering::Relaxed) {
                                    println!(
                                        "🎹 [MIDI THREAD] Stop flag set, breaking playback loop"
                                    );
                                    break;
                                }
                                let now = start.elapsed().as_millis() as u32 + start_ms;
                                while idx_tl < timeline_clone.len()
                                    && timeline_clone[idx_tl].0 <= now
                                {
                                    let (t, on, chan, pitch, vel) = timeline_clone[idx_tl];
                                    let msg = if on {
                                        [0x90 | (chan & 0x0F), pitch, vel]
                                    } else {
                                        [0x80 | (chan & 0x0F), pitch, 0]
                                    };
                                    let _ = conn.send(&msg);
                                    last_played_ms = t;
                                    idx_tl += 1;
                                }
                                std::thread::sleep(Duration::from_millis(1));
                            }
                            // All notes off at end
                            for channel in 0..16 {
                                let msg = [0xB0 | channel, 123, 0];
                                let _ = conn.send(&msg);
                            }
                            (conn, last_played_ms)
                        }));
                        // Send IPC events for the timeline in the parent thread (non-blocking, best-effort)
                        for (_t, on, chan, pitch, vel) in &timeline {
                            let now = std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .unwrap_or_default()
                                .as_millis() as u64;
                            let midi_note_event = e_midi_shared::ipc_protocol::MidiNoteEvent {
                                channel: *chan,
                                pitch: *pitch,
                                velocity: if *on { *vel } else { 0 },
                                kind: if *on { 0 } else { 1 },
                                timestamp: now,
                                _reserved: [0; 4],
                            };
                            if let Err(e) = publisher.send_copy(midi_note_event) {
                                eprintln!("[IPC ERROR] Failed to send MidiNoteEvent: {:?}", e);
                            }
                        }
                    }
                }
            }
        }
        // Clean up on exit
        stop_playback(
            &playback_stop_flag,
            &mut playback_thread,
            &mut current_playing,
            &mut last_positions,
        );
        println!("🎹 MIDI background thread finished");
    } // Send a MIDI command to the background thread
    fn send_midi_command(&self, command: MidiCommand) -> Result<(), Box<dyn Error>> {
        self.midi_sender
            .send(command)
            .map_err(|e| format!("Failed to send MIDI command: {}", e).into())
    }
    /// Stop any currently playing background playback
    pub fn stop_playback(&mut self) {
        self.playback_stop_flag.store(true, Ordering::Relaxed);
        self.is_playing.store(false, Ordering::Relaxed);

        // Always record resume state if a song was ever started
        if let (Some(_idx), Some(start)) = (self.current_song_index, self.start_instant) {
            let elapsed = start.elapsed().as_millis();
            // Clamp to u32::MAX
            let elapsed_ms = if elapsed > u32::MAX as u128 {
                u32::MAX
            } else {
                elapsed as u32
            };
            self.elapsed_ms = Some(elapsed_ms);
            // self.current_song_index is already set
        }

        // Send all notes off command through the MIDI channel
        if self.send_midi_command(MidiCommand::AllNotesOff).is_err() {
            eprintln!("Failed to send all notes off command");
        }
    }

    /// Reset the stop flag (called before starting new playback)
    fn reset_stop_flag(&mut self) {
        self.playback_stop_flag.store(false, Ordering::Relaxed);
    }

    /// Check if currently playing
    pub fn is_playing(&self) -> bool {
        self.is_playing.load(Ordering::Relaxed)
    }

    /// Get a clone of the playing state atomic bool for sharing with TUI
    pub fn get_playing_state(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.is_playing)
    }

    /// Get count of static songs
    pub fn get_static_song_count(&self) -> usize {
        self.static_songs.len()
    }

    /// Get count of dynamic songs
    pub fn get_dynamic_song_count(&self) -> usize {
        self.dynamic_songs.len()
    }

    /// Get total count of all songs (static + dynamic)
    pub fn get_total_song_count(&self) -> usize {
        self.static_songs.len() + self.dynamic_songs.len()
    }

    /// Get a song by index (static songs first, then dynamic)
    pub fn get_song(&self, index: usize) -> Option<&SongInfo> {
        let static_count = self.static_songs.len();
        if index < static_count {
            self.static_songs.get(index)
        } else {
            self.dynamic_songs.get(index - static_count)
        }
    }

    /// Get all songs as a single slice (creates a new vector)
    pub fn get_all_songs(&self) -> Vec<&SongInfo> {
        let mut all_songs = Vec::new();
        all_songs.extend(self.static_songs.iter());
        all_songs.extend(self.dynamic_songs.iter());
        all_songs
    }

    pub fn get_songs(&self) -> Vec<&SongInfo> {
        self.get_all_songs()
    }

    pub fn get_config(&self) -> &LoopConfig {
        &self.config
    }

    pub fn get_config_mut(&mut self) -> &mut LoopConfig {
        &mut self.config
    }

    /// Helper to format duration_ms as mm:ss or seconds
    fn format_duration(duration_ms: Option<u32>) -> String {
        match duration_ms {
            Some(ms) => {
                if ms == 0 {
                    "0".to_string()
                } else if ms < 1000 {
                    format!("{}ms", ms)
                } else {
                    let total_seconds = ms / 1000;
                    let minutes = total_seconds / 60;
                    let seconds = total_seconds % 60;
                    if minutes > 0 {
                        format!("{:02}:{:02}", minutes, seconds)
                    } else {
                        format!("{}s", seconds)
                    }
                }
            }
            None => "--".to_string(),
        }
    }

    pub fn list_songs(&self) {
        println!("🎵 Available Songs:");
        let all_songs = self.get_all_songs();
        for (i, song) in all_songs.iter().enumerate() {
            let duration_str = Self::format_duration(song.duration_ms);
            println!(
                "{}: {} ({} tracks, default tempo: {} BPM, duration: {})",
                i,
                song.name,
                song.tracks.len(),
                song.default_tempo,
                duration_str
            );
        }
    }

    /// List only dynamic songs
    pub fn list_dynamic_songs(&self) {
        let static_count = self.get_static_song_count();
        let dynamic_count = self.get_dynamic_song_count();

        if dynamic_count == 0 {
            println!("📭 No dynamic songs loaded");
            return;
        }

        println!("🎶 Dynamic Songs ({} total):", dynamic_count);
        for (i, song) in self.dynamic_songs.iter().enumerate() {
            let actual_index = static_count + i;
            let duration_str = Self::format_duration(song.duration_ms);
            println!(
                "  {}: {} ({} tracks, default tempo: {} BPM, duration: {})",
                actual_index,
                song.name,
                song.tracks.len(),
                song.default_tempo,
                duration_str
            );
        }
    }

    /// List only static songs
    pub fn list_static_songs(&self) {
        let static_count = self.get_static_song_count();

        if static_count == 0 {
            println!("📭 No static songs available");
            return;
        }

        println!("📀 Static Songs ({} total):", static_count);
        for (i, song) in self.static_songs.iter().enumerate() {
            let duration_str = Self::format_duration(song.duration_ms);
            println!(
                "  {}: {} ({} tracks, default tempo: {} BPM, duration: {})",
                i,
                song.name,
                song.tracks.len(),
                song.default_tempo,
                duration_str
            );
        }
    }

    pub fn play_song(
        &mut self,
        song_index: usize,
        tracks: Option<Vec<usize>>,
        tempo_bpm: Option<u32>,
    ) -> Result<bool, Box<dyn Error>> {
        if song_index >= self.get_total_song_count() {
            return Err("Invalid song index".into());
        }
        self.current_song_index = Some(song_index);
        let selected_song = self.get_song(song_index).ok_or("Invalid song index")?;
        let tempo = tempo_bpm.unwrap_or(selected_song.default_tempo);
        // --- Map user-facing track indices to dense indices ---
        let track_indices = Self::get_dense_indices_for_song(selected_song, tracks.as_deref());
        let user_indices: Vec<_> = track_indices
            .iter()
            .filter_map(|dense| {
                selected_song
                    .tracks
                    .iter()
                    .find(|t| selected_song.track_index_map.get(&t.index) == Some(dense))
                    .map(|t| t.index)
            })
            .collect();
        println!(
            "\n▶️  Playing {} - user tracks: {:?} (dense: {:?}) at {} BPM",
            selected_song.name, user_indices, track_indices, tempo
        );
        println!("🎮 Controls: 't' = change tempo (or type BPM directly), 'n' = next song, 'q' = quit to menu\n");

        // --- AUDIO/VIDEO/URL HANDLING ---
        match selected_song.song_type {
            SongType::Ogg | SongType::Mp3 | SongType::Mp4 | SongType::Webm => {
                use std::io::{self, Read};
                use std::sync::{
                    atomic::{AtomicBool, Ordering},
                    Arc,
                };
                use std::thread;
                let stop_flag = Arc::new(AtomicBool::new(false));
                let stop_flag2 = stop_flag.clone();
                let song_name = selected_song.name.clone();
                let bytes = get_embedded_audio_bytes(song_index, &selected_song.song_type)
                    .map(|b| b.to_vec());
                if let Some(bytes) = bytes {
                    println!("▶️  Playing embedded audio: {}", selected_song.name);
                    let handle = thread::spawn(move || {
                        let _ = play_media_file(&song_name, None, Some(&bytes), stop_flag2);
                    });
                    // Listen for user input
                    println!("🎮 Controls: 'n' = next song, 'q' = quit to menu");
                    loop {
                        let mut buf = [0u8; 1];
                        if let Ok(n) = io::stdin().read(&mut buf) {
                            if n > 0 {
                                let c = buf[0] as char;
                                if c == 'n' || c == 'q' {
                                    stop_flag.store(true, Ordering::Relaxed);
                                    break;
                                }
                            }
                        }
                        if stop_flag.load(Ordering::Relaxed) {
                            break;
                        }
                        std::thread::sleep(std::time::Duration::from_millis(50));
                    }
                    let _ = handle.join();
                    println!("✅ Done!");
                    return Ok(true);
                } else {
                    println!("❌ No embedded audio data found for this song.");
                    return Ok(false);
                }
            }
            SongType::YouTube => {
                println!("🌐 YouTube/URL song: {}", selected_song.name);
                println!(
                    "Open this URL in your browser: {}",
                    selected_song.source.url().unwrap_or("(no url)".to_string())
                );
                return Ok(true);
            }
            _ => {}
        }
        // --- MIDI/MusicXML (default) ---
        let events = self.get_events_for_song(song_index, &track_indices, tempo);
        if events.is_empty() {
            println!("⚠️  No events to play! Check track selection.");
            return Ok(false);
        }
        let continue_playing = self.play_events_with_tempo_control(&events, tempo)?;
        println!("✅ Done!");
        Ok(continue_playing)
    }

    pub fn play_all_songs(&mut self) -> Result<(), Box<dyn Error>> {
        let songs_count = self.get_total_song_count();
        println!("\n🎮 Controls: 't' = change tempo (or type BPM directly), 'n' = next song, 'q' = quit to menu\n");
        loop {
            for i in 0..songs_count {
                self.current_song_index = Some(i);
                let song = self.get_song(i).ok_or("Invalid song index")?;
                println!(
                    "\n🔀 Playing song {} of {}: {}",
                    i + 1,
                    songs_count,
                    song.name
                );
                match song.song_type {
                    SongType::Midi | SongType::MusicXml => {
                        // Map user-facing indices to dense indices
                        let dense_indices = Self::get_dense_indices_for_song(song, None);
                        let events =
                            self.get_events_for_song(i, &dense_indices, song.default_tempo);
                        if !events.is_empty() {
                            let continue_playing =
                                self.play_events_with_tempo_control(&events, song.default_tempo)?;
                            if !continue_playing {
                                return Ok(());
                            }
                        }
                    }
                    _ => {
                        // For OGG/MP3/MP4/YouTube, just play the song (no event logic)
                        self.play_song(i, None, None)?;
                    }
                }
                if self.config.delay_between_songs_ms > 0 {
                    println!(
                        "⏸️  Waiting {}ms before next song...",
                        self.config.delay_between_songs_ms
                    );
                    sleep(Duration::from_millis(
                        self.config.delay_between_songs_ms as u64,
                    ));
                }
            }
            if !self.config.loop_playlist {
                break;
            }
            println!("🔄 Restarting playlist...");
        }
        Ok(())
    }

    pub fn play_random_song(&mut self) -> Result<(), Box<dyn Error>> {
        use rand::seq::SliceRandom;
        let mut indices: Vec<usize> = (0..self.get_total_song_count()).collect();
        let mut rng = rand::rng();
        indices.shuffle(&mut rng);
        for &song_index in &indices {
            self.current_song_index = Some(song_index);
            let song = self.get_song(song_index).ok_or("Invalid song index")?;
            println!("\n🎲 Random song {}: {}", song_index, song.name);
            match song.song_type {
                SongType::Midi | SongType::MusicXml => {
                    let dense_indices = Self::get_dense_indices_for_song(song, None);
                    let events =
                        self.get_events_for_song(song_index, &dense_indices, song.default_tempo);
                    if !events.is_empty() {
                        let continue_playing =
                            self.play_events_with_tempo_control(&events, song.default_tempo)?;
                        if !continue_playing {
                            break;
                        }
                    }
                }
                _ => {
                    self.play_song(song_index, None, None)?;
                }
            }
            if self.config.delay_between_songs_ms > 0 {
                sleep(Duration::from_millis(
                    self.config.delay_between_songs_ms as u64,
                ));
            }
        }
        Ok(())
    }
    pub fn scan_mode(&mut self, scan_duration: u32, scan_mode: u32) -> Result<(), Box<dyn Error>> {
        self.scan_mode_internal(scan_duration, scan_mode, true)
    }

    pub fn scan_mode_non_interactive(
        &mut self,
        scan_duration: u32,
        scan_mode: u32,
    ) -> Result<(), Box<dyn Error>> {
        self.scan_mode_internal(scan_duration, scan_mode, false)
    }
    fn scan_mode_internal(
        &mut self,
        scan_duration: u32,
        scan_mode: u32,
        interactive: bool,
    ) -> Result<(), Box<dyn Error>> {
        let songs_count = self.get_total_song_count();
        println!(
            "\n🎵 Scanning {} songs ({} seconds each)...",
            songs_count, scan_duration
        );
        if interactive {
            println!("🎮 Controls: 't' = change tempo (or type BPM directly), 'n' = next song, 'q' = quit to menu\n");
        }
        // Progressive scan mode automatically enables playlist looping
        let original_loop_setting = self.config.loop_playlist;
        if scan_mode == 3 {
            self.config.loop_playlist = true;
        }
        let mut positions = if scan_mode == 3 {
            // Progressive scan - start with positions for each song
            vec![0u32; songs_count]
        } else {
            Vec::new()
        };
        loop {
            if should_shutdown() {
                println!("🛑 Shutdown requested, exiting scan mode");
                break;
            }
            #[allow(clippy::needless_range_loop)]
            // Clippy suggests using enumerate/iter_mut, but we need song_index for both indexing positions and as an argument to get_song().
            // Refactoring to use enumerate or iter_mut causes borrow checker issues due to multiple mutable borrows of positions.
            for song_index in 0..songs_count {
                if should_shutdown() {
                    println!("🛑 Shutdown requested during scan");
                    return Ok(());
                }
                self.current_song_index = Some(song_index);
                let song = self.get_song(song_index).ok_or("Invalid song index")?;
                match song.song_type {
                    SongType::Midi | SongType::MusicXml => {
                        // Map user-facing indices to dense indices
                        let dense_indices = Self::get_dense_indices_for_song(song, None);
                        let song_duration = calculate_song_duration_ms(&self.get_events_for_song(
                            song_index,
                            &dense_indices,
                            song.default_tempo,
                        ));
                        let start_position = match scan_mode {
                            1 => 0, // Sequential - always start from beginning
                            2 => {
                                // Random positions
                                if self.config.scan_random_start
                                    && song_duration > scan_duration * 1000
                                {
                                    use std::collections::hash_map::DefaultHasher;
                                    use std::hash::{Hash, Hasher};
                                    let mut hasher = DefaultHasher::new();
                                    song_index.hash(&mut hasher);
                                    (hasher.finish() as u32)
                                        % (song_duration - scan_duration * 1000)
                                } else {
                                    0
                                }
                            }
                            3 => {
                                // Progressive scan
                                let pos = positions[song_index];
                                if pos + scan_duration * 1000 >= song_duration {
                                    positions[song_index] = 0; // Reset to start if we've reached the end
                                    0
                                } else {
                                    positions[song_index] += scan_duration * 1000; // Advance by full scan duration
                                    pos
                                }
                            }
                            _ => 0,
                        };
                        println!(
                            "\n▶️  Scanning: {} ({}/{})",
                            song.name,
                            song_index + 1,
                            songs_count
                        );
                        let events = self.get_events_for_song(
                            song_index,
                            &dense_indices,
                            song.default_tempo,
                        );
                        if !events.is_empty() {
                            // Calculate full song duration first
                            let full_duration_ms = calculate_song_duration_ms(&events);
                            let full_duration_str = format_duration(full_duration_ms);

                            let end_time_ms = std::cmp::min(scan_duration * 1000, full_duration_ms);
                            let percentage = if full_duration_ms > 0 {
                                (start_position as f32 / full_duration_ms as f32 * 100.0) as u32
                            } else {
                                0
                            };

                            match scan_mode {
                                2 => {
                                    // Random scan
                                    println!(
                                        "🎲 Random start: {}% ({}) of {} total",
                                        percentage,
                                        format_duration(start_position),
                                        full_duration_str
                                    );
                                }
                                3 => {
                                    // Progressive scan
                                    let end_pos = std::cmp::min(
                                        start_position + scan_duration * 1000,
                                        full_duration_ms,
                                    );
                                    println!(
                                        "🎯 Progressive scan: {}% ({} to {}) of {} total",
                                        percentage,
                                        format_duration(start_position),
                                        format_duration(end_pos),
                                        full_duration_str
                                    );
                                }
                                _ => {
                                    // Sequential scan
                                    println!(
                                        "📏 Sequential scan: 0% (0s to {}) of {} total",
                                        format_duration(end_time_ms),
                                        full_duration_str
                                    );
                                }
                            }

                            // Filter events to start from the calculated position
                            let filtered_events: Vec<Note> = if start_position > 0 {
                                events
                                    .iter()
                                    .filter(|note| note.start_ms >= start_position)
                                    .map(|note| Note {
                                        start_ms: note.start_ms,
                                        dur_ms: note.dur_ms,
                                        chan: note.chan,
                                        pitch: note.pitch,
                                        vel: note.vel,
                                        track: note.track,
                                    })
                                    .collect()
                            } else {
                                events
                            };
                            if interactive {
                                self.play_events_with_tempo_control_and_scan_limit(
                                    &filtered_events,
                                    song.default_tempo,
                                    scan_duration * 1000,
                                )?;
                            } else {
                                // For non-interactive scan mode, just play the events with simple timing
                                self.play_events_simple(
                                    &filtered_events,
                                    song.default_tempo,
                                    scan_duration * 1000,
                                )?;
                            }
                        }
                    }
                    _ => {
                        // For OGG/MP3/MP4/YouTube, just play the song (no event logic)
                        self.play_song(song_index, None, None)?;
                    }
                }
                if self.config.delay_between_songs_ms > 0 {
                    sleep(Duration::from_millis(
                        self.config.delay_between_songs_ms as u64,
                    ));
                }
            }
            if !self.config.loop_playlist {
                break;
            }
            println!("🔄 Restarting scan...");
        }

        // Restore original loop setting
        self.config.loop_playlist = original_loop_setting;

        Ok(())
    }
    pub fn run_interactive(&mut self) -> Result<(), Box<dyn Error>> {
        loop {
            if should_shutdown() {
                println!("🛑 Shutdown requested, exiting interactive mode");
                break;
            }
            self.show_main_menu()?;
        }
        Ok(())
    }
    pub fn run_tui_mode(&mut self) -> Result<(), Box<dyn Error>> {
        crate::tui::run_tui_mode(self)
    }
    fn show_main_menu(&mut self) -> Result<(), Box<dyn Error>> {
        println!("\n🎵 e_midi - Interactive MIDI Player");
        println!("══════════════════════════════════");

        // Song management
        let static_count = self.get_static_song_count();
        let dynamic_count = self.get_dynamic_song_count();
        let total_count = self.get_total_song_count();

        println!(
            "\n📚 Song Management ({} total: {} static + {} dynamic):",
            total_count, static_count, dynamic_count
        );
        println!("1: List all songs");
        println!("2: List static songs only");
        println!("3: List dynamic songs only");
        println!("4: Load MIDI file(s) or directory");
        println!("5: Clear dynamic songs");

        // Settings display
        println!("\n⚙️  Settings:");
        println!(
            "6: Loop playlist: {}",
            if self.config.loop_playlist {
                "✅ ON"
            } else {
                "❌ OFF"
            }
        );
        println!(
            "7: Loop individual songs: {}",
            if self.config.loop_individual_songs {
                "✅ ON"
            } else {
                "❌ OFF"
            }
        );
        println!(
            "8: Delay between songs: {}s",
            self.config.delay_between_songs_ms / 1000
        );
        println!(
            "9: Scan segment duration: {}s",
            self.config.scan_segment_duration_ms / 1000
        );
        println!(
            "10: Random scan start: {}",
            if self.config.scan_random_start {
                "✅ ON"
            } else {
                "❌ OFF"
            }
        );

        // Playback options
        println!("\n🎵 Playback Options:");
        println!("11: Play a specific song");
        println!("12: Play all songs");
        println!("13: Play random song");
        println!("14: Scan mode (play portions of songs)");

        // Control options
        println!("\n🎮 Controls:");
        println!("q: Main menu (you are here)");
        println!("x: Exit program");

        if self.config.loop_playlist || self.config.loop_individual_songs {
            println!("\n💡 During playback: 'n' = next song, 'q' = quit to menu");
        }

        print!("\nSelect option (1-14, q, x): ");
        stdout().flush()?;
        let mut input = String::new();
        let bytes_read = stdin().read_line(&mut input)?;

        // If no bytes were read, stdin is closed (EOF), so exit gracefully
        if bytes_read == 0 {
            println!("👋 Goodbye!");
            std::process::exit(0);
        }

        let input = input.trim();

        // Skip empty input silently and continue to next iteration
        if input.is_empty() {
            return Ok(());
        }

        match input {
            "1" => {
                self.list_songs();
            }
            "2" => {
                self.list_static_songs();
            }
            "3" => {
                self.list_dynamic_songs();
            }
            "4" => {
                self.load_midi_interactive()?;
            }
            "5" => {
                self.clear_dynamic_songs();
            }
            "6" => {
                self.config.loop_playlist = !self.config.loop_playlist;
                println!(
                    "🔄 Playlist looping: {}",
                    if self.config.loop_playlist {
                        "ON"
                    } else {
                        "OFF"
                    }
                );
            }
            "7" => {
                self.config.loop_individual_songs = !self.config.loop_individual_songs;
                println!(
                    "🔄 Individual song looping: {}",
                    if self.config.loop_individual_songs {
                        "ON"
                    } else {
                        "OFF"
                    }
                );
            }
            "8" => {
                print!(
                    "⏱️  Enter delay between songs in seconds (current: {}): ",
                    self.config.delay_between_songs_ms / 1000
                );
                stdout().flush()?;
                let mut delay_input = String::new();
                stdin().read_line(&mut delay_input)?;
                if let Ok(delay_seconds) = delay_input.trim().parse::<u32>() {
                    self.config.delay_between_songs_ms = delay_seconds * 1000;
                    println!("⏱️  Delay set to {}s", delay_seconds);
                }
            }
            "9" => {
                print!(
                    "🔍 Enter scan segment duration in seconds (current: {}): ",
                    self.config.scan_segment_duration_ms / 1000
                );
                stdout().flush()?;
                let mut scan_input = String::new();
                stdin().read_line(&mut scan_input)?;
                if let Ok(scan_seconds) = scan_input.trim().parse::<u32>() {
                    self.config.scan_segment_duration_ms = scan_seconds * 1000;
                    println!("🔍 Scan duration set to {}s", scan_seconds);
                }
            }
            "10" => {
                self.config.scan_random_start = !self.config.scan_random_start;
                println!(
                    "🎲 Random scan start: {}",
                    if self.config.scan_random_start {
                        "ON"
                    } else {
                        "OFF"
                    }
                );
            }
            "11" => self.play_single_song_interactive()?,
            "12" => self.play_all_songs()?,
            "13" => self.play_random_song()?,
            "14" => self.scan_mode_interactive()?,
            "q" => {
                println!("📍 Already at main menu");
            }
            "x" => {
                println!("👋 Goodbye!");
                std::process::exit(0);
            }
            _ => {
                println!("❌ Invalid option. Please select 1-14, q, or x.");
            }
        }

        Ok(())
    }
    fn play_single_song_interactive(&mut self) -> Result<(), Box<dyn Error>> {
        self.list_songs();

        print!("\nSelect song number: ");
        stdout().flush()?;
        let mut input = String::new();
        stdin().read_line(&mut input)?;

        // Check for quit command
        if input.trim() == "q" {
            return Ok(());
        }

        let song_index: usize = input.trim().parse().unwrap_or(0);

        if song_index >= self.get_total_song_count() {
            println!("Invalid song selection.");
            return Ok(());
        }

        let selected_song = self.get_song(song_index).ok_or("Invalid song index")?;
        println!("\n🎹 Selected: {}", selected_song.name);

        // Only show track/tempo selection for MIDI and MusicXML
        match selected_song.song_type {
            SongType::Midi | SongType::MusicXml => {
                if self.config.loop_individual_songs {
                    println!("🔄 Looping enabled for this song. Press 'q' + Enter to stop.");
                }
                // Track selection
                println!("\n🎹 Available Tracks:");
                for track in &selected_song.tracks {
                    println!(
                        "{}: {} - notes: {} - channels: {:?} - pitch: {}{} - sample: {:?}",
                        track.index,
                        track.guess.as_ref().unwrap_or(&"-".to_string()),
                        track.note_count,
                        track.channels,
                        track.pitch_range.0,
                        track.pitch_range.1,
                        track.sample_notes
                    );
                }
                print!(
                    "\nEnter track numbers to play (comma separated, 0 for all tracks, or ENTER for all): "
                );
                stdout().flush()?;
                let mut track_input = String::new();
                stdin().read_line(&mut track_input)?;

                // Check for quit command
                if track_input.trim() == "q" {
                    return Ok(());
                }

                let mut tracks: Vec<usize> = if track_input.trim().is_empty() {
                    selected_song.tracks.iter().map(|t| t.index).collect()
                } else {
                    track_input
                        .trim()
                        .split(',')
                        .filter_map(|s| s.trim().parse::<usize>().ok())
                        .collect()
                };

                if tracks.contains(&0) {
                    tracks = selected_song.tracks.iter().map(|t| t.index).collect();
                    println!("🎵 Playing all tracks!");
                } else if tracks.is_empty() {
                    println!("🎵 No valid tracks specified, playing all tracks!");
                    tracks = selected_song.tracks.iter().map(|t| t.index).collect();
                } else {
                    let mut valid_tracks = Vec::new();
                    for user_track in &tracks {
                        if selected_song.tracks.iter().any(|t| t.index == *user_track) {
                            valid_tracks.push(*user_track);
                        } else {
                            println!("⚠️  Track {} not found, skipping.", user_track);
                        }
                    }
                    tracks = valid_tracks;

                    if tracks.is_empty() {
                        println!("🎵 No valid tracks found, playing all tracks!");
                        tracks = selected_song.tracks.iter().map(|t| t.index).collect();
                    }
                }

                // Tempo selection
                print!(
                    "\nEnter tempo in BPM (default {} or ENTER for default): ",
                    selected_song.default_tempo
                );
                stdout().flush()?;
                let mut tempo_input = String::new();
                stdin().read_line(&mut tempo_input)?;

                // Check for quit command
                if tempo_input.trim() == "q" {
                    return Ok(());
                }

                let tempo_bpm = if tempo_input.trim().is_empty() {
                    selected_song.default_tempo
                } else {
                    tempo_input
                        .trim()
                        .parse()
                        .unwrap_or(selected_song.default_tempo)
                };

                self.play_song(song_index, Some(tracks), Some(tempo_bpm))?;
                Ok(())
            }
            _ => {
                // For OGG/MP3/MP4/YouTube, just play the song (no track/tempo selection)
                self.play_song(song_index, None, None)?;
                Ok(())
            }
        }
    }
    fn scan_mode_interactive(&mut self) -> Result<(), Box<dyn Error>> {
        print!("\n⏱️  Enter scan duration in seconds (default 30): ");
        stdout().flush()?;
        let mut input = String::new();
        stdin().read_line(&mut input)?;

        // Check for quit command
        if input.trim() == "q" {
            return Ok(());
        }

        let scan_duration: u32 = input.trim().parse().unwrap_or(30);

        println!("🔀 Scan mode options:");
        println!("1: Sequential (play from start of each song)");
        println!("2: Random positions in each song");
        println!("3: Progressive scan (advance through each song on each loop)");

        print!("Select scan mode (1-3): ");
        stdout().flush()?;
        let mut mode_input = String::new();
        stdin().read_line(&mut mode_input)?;

        // Check for quit command
        if mode_input.trim() == "q" {
            return Ok(());
        }

        let scan_mode: u32 = mode_input.trim().parse().unwrap_or(1);

        self.scan_mode(scan_duration, scan_mode)
    }
    /// Add a single MIDI file to the dynamic song list
    pub fn add_song_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Box<dyn Error>> {
        let path = path.as_ref();
        let ext = path
            .extension()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        if ext == "mid" {
            let midi_data = fs::read(path)?;
            let song_info = self.parse_midi_file_from_data(&midi_data, path)?;
            println!("{:?}", song_info);
            println!(
                "✅ Parsed MIDI file: {} ({} tracks, default tempo: {} BPM)",
                song_info.name,
                song_info.tracks.len(),
                song_info.default_tempo
            );
            self.dynamic_songs.push(song_info);
            println!(
                "✅ Added song: {} (index {})",
                self.dynamic_songs.last().unwrap().name,
                self.get_static_song_count() + self.dynamic_songs.len() - 1
            );
            self.dynamic_midi_data.push(midi_data);
            println!(
                "✅ Added song: {} (index {})",
                self.dynamic_songs.last().unwrap().name,
                self.get_static_song_count() + self.dynamic_songs.len() - 1
            );
            Ok(())
        } else if ext == "xml" || ext == "musicxml" {
            // Try to parse as MusicXML
            match musicxml::read_score_partwise(&path.to_string_lossy()) {
                Ok(_score) => {
                    // Use the same extraction logic as embed_musicxml.rs
                    let xml_song = e_midi_shared::embed_musicxml::extract_musicxml_songs(
                        path.parent().unwrap_or_else(|| std::path::Path::new(".")),
                    )
                    .into_iter()
                    .find(|s| s.filename == path.file_name().unwrap().to_string_lossy());
                    if let Some(xml) = xml_song {
                        let song_info = xml_song_to_song_info(&xml);
                        self.dynamic_songs.push(song_info);
                        // For MusicXML, push empty Vec to dynamic_midi_data to keep indices aligned
                        self.dynamic_midi_data.push(Vec::new());
                        println!(
                            "✅ Added MusicXML song: {} (index {})",
                            self.dynamic_songs.last().unwrap().name,
                            self.get_static_song_count() + self.dynamic_songs.len() - 1
                        );
                        Ok(())
                    } else {
                        Err("Failed to extract MusicXML song info".into())
                    }
                }
                Err(e) => Err(format!("Failed to parse MusicXML: {}", e).into()),
            }
        } else {
            Err("Unsupported file type (must be .mid, .xml, or .musicxml)".into())
        }
    }

    /// Scan a directory and add all MIDI files to the dynamic song list
    pub fn scan_directory<P: AsRef<Path>>(&mut self, dir_path: P) -> Result<usize, Box<dyn Error>> {
        let dir_path = dir_path.as_ref();
        let mut added_count = 0;
        let mut visited = HashSet::new();

        fn scan(
            player: &mut MidiPlayer,
            path: &Path,
            visited: &mut HashSet<String>,
            added_count: &mut usize,
        ) -> Result<(), Box<dyn Error>> {
            let canonical = match fs::canonicalize(path) {
                Ok(p) => p,
                Err(_) => return Ok(()), // skip unreadable
            };
            let canonical_str = canonical.to_string_lossy().to_string();
            if !visited.insert(canonical_str) {
                // already visited
                return Ok(());
            }
            if path.is_file() {
                let ext = path
                    .extension()
                    .and_then(|s| s.to_str())
                    .unwrap_or("")
                    .to_ascii_lowercase();
                if ext == "mid" || ext == "xml" || ext == "musicxml" {
                    match player.add_song_from_file(path) {
                        Ok(()) => *added_count += 1,
                        Err(e) => println!("❌ Failed to load {}: {}", path.display(), e),
                    }
                }
            } else if path.is_dir() {
                for entry in fs::read_dir(path)? {
                    let entry = entry?;
                    let entry_path = entry.path();
                    scan(player, &entry_path, visited, added_count)?;
                }
            }
            Ok(())
        }

        if !dir_path.is_dir() {
            return Err(format!("Path is not a directory: {}", dir_path.display()).into());
        }

        println!("🔍 Recursively scanning directory: {}", dir_path.display());
        scan(self, dir_path, &mut visited, &mut added_count)?;
        println!("🎵 Added {} songs from directory (recursive)", added_count);
        Ok(added_count)
    }

    /// Clear all dynamic songs
    pub fn clear_dynamic_songs(&mut self) {
        let count = self.dynamic_songs.len();
        self.dynamic_songs.clear();
        self.dynamic_midi_data.clear();
        println!("🧹 Cleared {} dynamic songs", count);
    }

    /// Parse a MIDI file and create a SongInfo structure
    fn parse_midi_file_from_data<P: AsRef<Path>>(
        &self,
        data: &[u8],
        path: P,
    ) -> Result<SongInfo, Box<dyn Error>> {
        let path = path.as_ref();
        let smf = Smf::parse(data)?;

        let song_name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("Unknown")
            .to_string();

        // Parse tracks and extract information
        let mut tracks = Vec::new();
        let mut default_tempo = 120u32; // Default tempo
        let ticks_per_q = match smf.header.timing {
            midly::Timing::Metrical(ticks) => ticks.as_int() as u32,
            midly::Timing::Timecode(fps, ticks) => (fps.as_int() as u32) * (ticks as u32),
        };

        for (track_index, track) in smf.tracks.iter().enumerate() {
            let mut track_info = TrackInfo {
                index: track_index,
                program: None,
                guess: None,
                channels: Vec::new(),
                note_count: 0,
                pitch_range: (127, 0), // min, max
                sample_notes: Vec::new(),
            };

            for event in track.iter() {
                match &event.kind {
                    TrackEventKind::Midi { channel, message } => {
                        let ch = channel.as_int();
                        if !track_info.channels.contains(&ch) {
                            track_info.channels.push(ch);
                        }

                        match message {
                            MidiMessage::NoteOn { key, vel: _ } => {
                                track_info.note_count += 1;
                                let pitch = key.as_int();
                                track_info.pitch_range.0 = track_info.pitch_range.0.min(pitch);
                                track_info.pitch_range.1 = track_info.pitch_range.1.max(pitch);

                                if track_info.sample_notes.len() < 5 {
                                    track_info.sample_notes.push(pitch);
                                }
                            }
                            MidiMessage::ProgramChange { program } => {
                                track_info.program = Some(program.as_int());
                            }
                            _ => {}
                        }
                    }
                    TrackEventKind::Meta(midly::MetaMessage::Tempo(tempo)) => {
                        // Convert microseconds per quarter note to BPM
                        default_tempo = 60_000_000 / tempo.as_int();
                    }
                    _ => {}
                }
            }

            // Only add tracks that have notes
            if track_info.note_count > 0 {
                // Make a simple guess about the instrument
                track_info.guess = match track_info.program {
                    Some(0..=7) => Some("Piano".to_string()),
                    Some(8..=15) => Some("Chromatic".to_string()),
                    Some(16..=23) => Some("Organ".to_string()),
                    Some(24..=31) => Some("Guitar".to_string()),
                    Some(32..=39) => Some("Bass".to_string()),
                    Some(40..=47) => Some("Strings".to_string()),
                    Some(48..=55) => Some("Ensemble".to_string()),
                    Some(56..=63) => Some("Brass".to_string()),
                    Some(64..=71) => Some("Reed".to_string()),
                    Some(72..=79) => Some("Pipe".to_string()),
                    Some(80..=87) => Some("Synth Lead".to_string()),
                    Some(88..=95) => Some("Synth Pad".to_string()),
                    Some(96..=103) => Some("Synth Effects".to_string()),
                    Some(104..=111) => Some("Ethnic".to_string()),
                    Some(112..=119) => Some("Percussive".to_string()),
                    Some(120..=127) => Some("Sound Effects".to_string()),
                    _ => Some("Unknown".to_string()),
                };

                tracks.push(track_info);
            }
        }

        // Build a sparse-to-dense track index map: user index (original track index) -> dense index in tracks vec
        let mut track_index_map = std::collections::HashMap::new();
        for (dense_idx, track_info) in tracks.iter().enumerate() {
            track_index_map.insert(track_info.index, dense_idx);
        }

        // Compute duration_ms as the max end time of all notes
        let mut duration_ms = 0u32;
        for track in smf.tracks.iter() {
            let mut current_time = 0u32;
            for event in track.iter() {
                current_time += event.delta.as_int();
                if let midly::TrackEventKind::Midi {
                    message: midly::MidiMessage::NoteOn { .. },
                    ..
                } = &event.kind
                {
                    // NoteOn event, check if this is the latest event
                    if current_time > duration_ms {
                        duration_ms = current_time;
                    }
                }
            }
        }

        Ok(SongInfo {
            filename: path.to_string_lossy().to_string(),
            name: song_name,
            tracks,
            default_tempo,
            ticks_per_q: Some(ticks_per_q),
            source: SongSource::None,
            song_type: SongType::Midi,
            track_index_map,
            duration_ms: Some(duration_ms),
        })
    }

    /// Get events for any song (static or dynamic) by index
    pub fn get_events_for_song(
        &self,
        song_index: usize,
        track_indices: &[usize],
        tempo_bpm: u32,
    ) -> Vec<Note> {
        let static_count = self.get_static_song_count();

        if song_index < static_count {
            // Static song - use the generated function
            get_events_for_song_tracks(song_index, track_indices, tempo_bpm)
        } else {
            // Dynamic song
            let dynamic_index = song_index - static_count;
            println!(
                "🔄 Fetching events for dynamic song index {} (global index {})",
                dynamic_index, song_index
            );
            self.get_events_for_dynamic_song(dynamic_index, track_indices, tempo_bpm)
        }
    }

    /// Get events for dynamic songs
    fn get_events_for_dynamic_song(
        &self,
        dynamic_song_index: usize,
        track_indices: &[usize],
        fallback_bpm: u32,
    ) -> Vec<Note> {
        if dynamic_song_index >= self.dynamic_midi_data.len() {
            println!("❌ Invalid dynamic song index: {}", dynamic_song_index);
            return Vec::new();
        }

        let midi_data = &self.dynamic_midi_data[dynamic_song_index];
        let smf = match Smf::parse(midi_data) {
            Ok(smf) => smf,
            Err(err) => {
                println!("❌ Failed to parse MIDI data: {:?}", err);
                return Vec::new();
            }
        };

        let ticks_per_q = match smf.header.timing {
            midly::Timing::Metrical(t) => t.as_int() as u32,
            other => {
                println!(
                    "⚠️  Non-metrical timing: {:?}, using fallback 96 ticks_per_q",
                    other
                );
                96
            }
        };

        // Extract tempo from meta events, fallback to provided BPM
        let mut tempo_usec_per_q = 500_000; // 120 BPM default
        for track in &smf.tracks {
            for event in track.iter() {
                if let TrackEventKind::Meta(midly::MetaMessage::Tempo(t)) = event.kind {
                    tempo_usec_per_q = t.as_int();
                    break;
                }
            }
            if tempo_usec_per_q != 500_000 {
                break;
            }
        }

        let _bpm = 60_000_000 / tempo_usec_per_q;
        let tempo_usec_per_q = if fallback_bpm > 0 {
            60_000_000 / fallback_bpm
        } else {
            tempo_usec_per_q
        };

        // If no track indices given, auto-select best ones
        let selected_indices = if track_indices.is_empty() {
            // If no track indices given, select all tracks (do not filter)
            (0..smf.tracks.len()).collect::<Vec<_>>()
        } else {
            println!("🔄 Using provided track indices: {:?}", track_indices);
            //track_indices.to_vec()
            (0..smf.tracks.len()).collect::<Vec<_>>()
        };

        let mut events = Vec::new();
        println!("{:?}", selected_indices);
        // Debug: Print all tracks in the SMF for inspection
        let debug_path = format!("debug_midi_tracks_{}.txt", dynamic_song_index);
        if let Ok(mut file) = std::fs::File::create(&debug_path) {
            let _ = writeln!(file, "{:#?}", smf.tracks);
            println!("Debug: Wrote SMF tracks to {}", debug_path);
        } else {
            println!("Debug: Failed to write SMF tracks to file");
        }

        //std::process::exit(0);
        for &track_index in &selected_indices {
            if let Some(track) = smf.tracks.get(track_index) {
                println!(
                    "🎵 Processing track {} with {} events",
                    track_index,
                    track.len()
                );

                let mut current_tick = 0u32;
                let mut note_ons = std::collections::HashMap::new();
                println!(
                    "🔄 Processing track {} with {} events",
                    track_index,
                    track.len()
                );
                for event in track {
                    let delta = event.delta.as_int();
                    current_tick = current_tick.wrapping_add(delta);
                    println!(
                        "{:?} - Delta: {}, Current Tick: {}",
                        event, delta, current_tick
                    );
                    if let TrackEventKind::Midi { channel, message } = &event.kind {
                        let ch = channel.as_int();
                        match message {
                            MidiMessage::NoteOn { key, vel } if *vel > 0 => {
                                note_ons.insert((ch, key.as_int()), current_tick);
                            }
                            MidiMessage::NoteOff { key, .. }
                            | MidiMessage::NoteOn { key, vel: _ } => {
                                let pitch = key.as_int();
                                if let Some(start_tick) = note_ons.remove(&(ch, pitch)) {
                                    let dur_ticks = current_tick.saturating_sub(start_tick);
                                    let start_ms = (start_tick as u64 * tempo_usec_per_q as u64
                                        / ticks_per_q as u64
                                        / 1000)
                                        as u32;
                                    let dur_ms = (dur_ticks as u64 * tempo_usec_per_q as u64
                                        / ticks_per_q as u64
                                        / 1000)
                                        .max(50)
                                        as u32;

                                    events.push(Note {
                                        start_ms,
                                        dur_ms,
                                        chan: ch,
                                        pitch,
                                        vel: 64,
                                        track: track_index as u8,
                                    });
                                }
                            }
                            _ => {
                                println!(
                                    "⚠️  Unsupported MIDI message in track {}: {:?}",
                                    track_index, message
                                );
                            }
                        }
                    }
                }

                // Handle dangling NoteOns
                for ((ch, pitch), start_tick) in note_ons {
                    let start_ms = (start_tick as u64 * tempo_usec_per_q as u64
                        / ticks_per_q as u64
                        / 1000) as u32;
                    events.push(Note {
                        start_ms,
                        dur_ms: 500,
                        chan: ch,
                        pitch,
                        vel: 127,
                        track: track_index as u8,
                    });
                }
            }
        }

        events.sort_by_key(|n| n.start_ms);
        println!("✅ Emitted {} note events", events.len());
        events
    }
    /// Get or create an IPC event subscriber for a given source AppId
    pub fn get_event_subscriber(
        &mut self,
        source_app: ipc::AppId,
    ) -> Option<&mut ipc::EventSubscriber> {
        // Ensure IPC manager is initialized
        if self.ipc_manager.is_none() {
            println!("🔄 WRONG: Initializing IPC service manager for e_midi...");
            if let Ok(manager) = ipc::IpcServiceManager::new(ipc::AppId::EMidi) {
                self.ipc_manager = Some(manager);
            } else {
                return None;
            }
        }
        if let Some(manager) = self.ipc_manager.as_mut() {
            // Subscribe if not already
            let _ = manager.subscribe_to(source_app);
            return manager.subscriber(source_app);
        }
        None
    }
    /// Play a custom list of notes, overriding channel/voice as needed
    pub fn play_notes(
        &mut self,
        notes: Vec<e_midi_shared::types::Note>,
        tempo_bpm: Option<u32>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let _tempo = tempo_bpm.unwrap_or(120);
        // Use the same logic as play_events_in_background, but for the provided notes
        let midi_sender = self.midi_sender.clone();
        let stop_flag = Arc::clone(&self.playback_stop_flag);
        let playing_state = Arc::clone(&self.is_playing);
        thread::spawn(move || {
            #[derive(Copy, Clone)]
            enum Kind {
                On,
                Off,
            }
            struct Scheduled {
                t: u32,
                kind: Kind,
                chan: u8,
                p: u8,
                v: u8,
                // track: u8, // removed unused field
            }
            let mut timeline = Vec::with_capacity(notes.len() * 2);
            for n in &notes {
                timeline.push(Scheduled {
                    t: n.start_ms,
                    kind: Kind::On,
                    chan: n.chan,
                    p: n.pitch,
                    v: n.vel,
                });
                timeline.push(Scheduled {
                    t: n.start_ms + n.dur_ms,
                    kind: Kind::Off,
                    chan: n.chan,
                    p: n.pitch,
                    v: 0,
                });
            }
            timeline.sort_by_key(|e| e.t);

            let start = std::time::Instant::now();
            let mut idx = 0;
            while idx < timeline.len() {
                if stop_flag.load(Ordering::Relaxed) {
                    break;
                }
                let event = &timeline[idx];
                let target_time_ms = event.t as u64;
                let elapsed_ms = start.elapsed().as_millis() as u64;
                if elapsed_ms < target_time_ms {
                    let sleep_ms = target_time_ms - elapsed_ms;
                    std::thread::sleep(Duration::from_millis(std::cmp::min(sleep_ms, 50)));
                    continue;
                }
                let msg = match event.kind {
                    Kind::On => vec![0x90 | event.chan, event.p, event.v],
                    Kind::Off => vec![0x80 | event.chan, event.p, 0],
                };
                let _ = midi_sender.send(MidiCommand::SendMessage(msg));
                idx += 1;
            }
            playing_state.store(false, Ordering::Relaxed);
        });
        Ok(())
    }

    fn play_events_with_tempo_control(
        &mut self,
        events: &[Note],
        initial_tempo_bpm: u32,
    ) -> Result<bool, Box<dyn Error>> {
        // --- PATCH: Send Program Change for MusicXML ---
        if let Some(song_index) = self.current_song_index {
            if let Some(song) = self.get_song(song_index) {
                if song.song_type == SongType::MusicXml {
                    for track in song.tracks.iter() {
                        if let Some(program) = track.program {
                            // Find the first note in events for this track and use its channel
                            let note_channel = events
                                .iter()
                                .map(|n| n.chan)
                                .next()
                                .or_else(|| track.channels.first().copied())
                                .unwrap_or(0);
                            let msg = vec![0xC0 | note_channel, program];
                            println!(
                                "🎶 Sending Program Change for MusicXML: Channel {}, Program {}",
                                note_channel, program
                            );
                            let _ = self.send_midi_command(MidiCommand::SendMessage(msg));
                        }
                    }
                }
            }
        }

        #[derive(Copy, Clone)]
        enum Kind {
            On,
            Off,
        }

        struct Scheduled {
            t: u32,
            kind: Kind,
            chan: u8,
            p: u8,
            v: u8,
        }

        let mut timeline = Vec::with_capacity(events.len() * 2);
        for n in events {
            timeline.push(Scheduled {
                t: n.start_ms,
                kind: Kind::On,
                chan: n.chan,
                p: n.pitch,
                v: n.vel,
            });
            timeline.push(Scheduled {
                t: n.start_ms + n.dur_ms,
                kind: Kind::Off,
                chan: n.chan,
                p: n.pitch,
                v: 0,
            });
        }
        timeline.sort_by_key(|e| e.t);

        let tempo_multiplier = Arc::new(AtomicU32::new((initial_tempo_bpm as f32 * 1000.0) as u32));
        let should_quit = Arc::new(AtomicBool::new(false));
        let should_next = Arc::new(AtomicBool::new(false));
        let playback_finished = Arc::new(Mutex::new(false));

        // Spawn input handling thread
        let tempo_clone = Arc::clone(&tempo_multiplier);
        let quit_clone = Arc::clone(&should_quit);
        let next_clone = Arc::clone(&should_next);
        let finished_clone = Arc::clone(&playback_finished);
        let input_thread = thread::spawn(move || {
            let stdin = stdin();
            loop {
                // Check if playback has finished before trying to read input
                if let Ok(finished) = finished_clone.lock() {
                    if *finished {
                        break;
                    }
                }

                let mut input = String::new();
                if stdin.read_line(&mut input).is_ok() {
                    // Check again after reading - playback might have finished while we were reading
                    if let Ok(finished) = finished_clone.lock() {
                        if *finished {
                            break;
                        }
                    }

                    let input = input.trim();
                    if input.is_empty() {
                        // Empty input (just Enter) - check if playback finished and exit if so
                        continue;
                    }

                    if input == "q" {
                        quit_clone.store(true, Ordering::SeqCst);
                        break;
                    } else if input == "n" {
                        next_clone.store(true, Ordering::SeqCst);
                        break;
                    } else if let Some(stripped) = input.strip_prefix("t") {
                        // Handle both "t" alone and "t<number>" (e.g. "t120")
                        let tempo_str = if stripped.is_empty() {
                            // Prompt for tempo input
                            println!("Enter new tempo (BPM): ");
                            let mut tempo_input = String::new();
                            if stdin.read_line(&mut tempo_input).is_ok() {
                                tempo_input.trim().to_string()
                            } else {
                                continue;
                            }
                        } else {
                            // Extract tempo from "t<number>" format
                            stripped.to_string()
                        };
                        if let Ok(new_tempo) = tempo_str.parse::<u32>() {
                            if new_tempo > 0 && new_tempo <= 500 {
                                // Reasonable tempo range
                                tempo_clone
                                    .store((new_tempo as f32 * 1000.0) as u32, Ordering::Relaxed);
                                println!("⏱️  Tempo changed to {} BPM", new_tempo);
                            } else {
                                println!("⚠️  Invalid tempo: {} (must be 1-500 BPM)", new_tempo);
                            }
                        } else {
                            println!("⚠️  Invalid tempo format. Use 't' then enter BPM, or 't<BPM>' (e.g. 't120')");
                        }
                    } else if let Ok(new_tempo) = input.parse::<u32>() {
                        if new_tempo > 0 && new_tempo <= 500 {
                            // Reasonable tempo range
                            tempo_clone
                                .store((new_tempo as f32 * 1000.0) as u32, Ordering::Relaxed);
                            println!("⏱️  Tempo changed to {} BPM", new_tempo);
                        } else {
                            println!("⚠️  Invalid tempo: {} (must be 1-500 BPM)", new_tempo);
                        }
                    }
                } else {
                    // If read_line fails (e.g., stdin closed), break the loop
                    break;
                }
            }
        });

        let start = Instant::now();
        let mut idx = 0;
        let mut last_tempo = initial_tempo_bpm as f32 * 1000.0;
        let mut time_offset = 0.0;
        let mut last_real_time = 0.0;
        let mut last_print_time = 0u32;

        // Calculate total song duration for progress display
        let total_duration_ms = if let Some(last_event) = timeline.last() {
            last_event.t
        } else {
            0
        };

        println!("🎵 Starting playback with {} events...", timeline.len());
        while idx < timeline.len() {
            // Check if we should quit or go to next song
            if should_shutdown() {
                println!("🛑 Shutdown requested, stopping playback");
                break;
            }
            if should_quit.load(Ordering::SeqCst) {
                println!("🛑 Playback stopped by user");
                break;
            }
            if should_next.load(Ordering::SeqCst) {
                println!("⏭️  Skipping to next song...");
                // Send all notes off before moving to next
                for _channel in 0..16 {
                    self.send_midi_command(MidiCommand::AllNotesOff)?;
                }
                return Ok(true);
            }

            let current_tempo = tempo_multiplier.load(Ordering::Relaxed) as f32 / 1000.0;
            let real_elapsed = start.elapsed().as_millis() as f32;

            // If tempo changed, adjust our time calculations
            if (current_tempo - last_tempo).abs() > 0.1 {
                let tempo_ratio = current_tempo / last_tempo;
                time_offset += (real_elapsed - last_real_time) * (1.0 - tempo_ratio);
                last_tempo = current_tempo;
            }
            let tempo_ratio = current_tempo / (initial_tempo_bpm as f32);
            let adjusted_time = ((real_elapsed - time_offset) * tempo_ratio) as u32;
            last_real_time = real_elapsed;

            // Print time progress every 100ms (similar to scan mode)
            if adjusted_time / 100 != last_print_time / 100 {
                let progress_seconds = adjusted_time / 1000;
                let total_seconds = total_duration_ms / 1000;
                let progress_percentage = if total_duration_ms > 0 {
                    (adjusted_time as f32 / total_duration_ms as f32 * 100.0) as u32
                } else {
                    0
                };
                print!(
                    "\r🎵 Playing: {}s/{}s ({}%) @ {} BPM",
                    progress_seconds, total_seconds, progress_percentage, current_tempo
                );
                stdout().flush().unwrap_or(());
                last_print_time = adjusted_time;
            }

            // --- FIX: Use absolute event scheduling ---
            if idx < timeline.len() {
                let e = &timeline[idx];
                let target_time_ms = e.t as u64;
                let elapsed_ms = start.elapsed().as_millis() as u64;
                if elapsed_ms < target_time_ms {
                    std::thread::sleep(std::time::Duration::from_millis(
                        target_time_ms - elapsed_ms,
                    ));
                    continue;
                }
                let msg = match e.kind {
                    Kind::On => [0x90 | (e.chan & 0x0F), e.p, e.v],
                    Kind::Off => [0x80 | (e.chan & 0x0F), e.p, 0],
                };

                // --- IPC: publish note-level event ---
                match e.kind {
                    Kind::On => {
                        e_midi_shared::ipc::IpcServiceManager::publish_ipc_event(
                            e_midi_shared::ipc::Event::MidiNoteOn {
                                channel: e.chan,
                                pitch: e.p,
                                velocity: e.v,
                                timestamp: std::time::SystemTime::now()
                                    .duration_since(std::time::UNIX_EPOCH)
                                    .unwrap_or_default()
                                    .as_millis() as u64,
                            },
                        );
                    }
                    Kind::Off => {
                        e_midi_shared::ipc::IpcServiceManager::publish_ipc_event(
                            e_midi_shared::ipc::Event::MidiNoteOff {
                                channel: e.chan,
                                pitch: e.p,
                                timestamp: std::time::SystemTime::now()
                                    .duration_since(std::time::UNIX_EPOCH)
                                    .unwrap_or_default()
                                    .as_millis() as u64,
                            },
                        );
                    }
                }

                self.send_midi_command(MidiCommand::SendMessage(msg.to_vec()))?;
                idx += 1;
            }
        }

        println!("🎼 Playbook loop finished, sending all notes off");
        for channel in 0..16 {
            self.send_midi_command(MidiCommand::SendMessage(vec![0xB0 | channel, 123, 0]))?;
        }
        if let Ok(mut finished) = playback_finished.lock() {
            *finished = true;
        }
        println!("✅ Playback complete!");
        drop(input_thread);
        self.publish_midi_event(crate::ipc::Event::MidiPlaybackStopped {
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        });
        let user_quit = should_quit.load(Ordering::SeqCst);
        Ok(!user_quit)
    }

    fn play_events_with_tempo_control_and_scan_limit(
        &mut self,
        events: &[Note],
        initial_tempo_bpm: u32,
        max_duration_ms: u32,
    ) -> Result<bool, Box<dyn Error>> {
        self.play_events_with_tempo_control_and_scan_limit_internal(
            events,
            initial_tempo_bpm,
            max_duration_ms,
            true,
        )
    }

    #[allow(dead_code)]
    fn play_events_with_tempo_control_and_scan_limit_non_interactive(
        &mut self,
        events: &[Note],
        initial_tempo_bpm: u32,
        max_duration_ms: u32,
    ) -> Result<bool, Box<dyn Error>> {
        self.play_events_with_tempo_control_and_scan_limit_internal(
            events,
            initial_tempo_bpm,
            max_duration_ms,
            false,
        )
    }

    fn play_events_with_tempo_control_and_scan_limit_internal(
        &mut self,
        events: &[Note],
        initial_tempo_bpm: u32,
        max_duration_ms: u32,
        interactive: bool,
    ) -> Result<bool, Box<dyn Error>> {
        #[derive(Copy, Clone)]
        enum Kind {
            On,
            Off,
        }

        struct Event {
            t: u32,
            kind: Kind,
            chan: u8,
            p: u8,
            v: u8,
        }

        let mut timeline = Vec::with_capacity(events.len() * 2);
        for note in events {
            if note.start_ms > max_duration_ms {
                continue;
            }

            timeline.push(Event {
                t: note.start_ms,
                kind: Kind::On,
                chan: note.chan,
                p: note.pitch,
                v: note.vel,
            });

            let end_time = note.start_ms + note.dur_ms;
            timeline.push(Event {
                t: if end_time <= max_duration_ms {
                    end_time
                } else {
                    max_duration_ms
                },
                kind: Kind::Off,
                chan: note.chan,
                p: note.pitch,
                v: note.vel,
            });
        }
        timeline.sort_by_key(|e| e.t);

        let tempo_multiplier = Arc::new(AtomicU32::new((initial_tempo_bpm as f32 * 1000.0) as u32));
        let should_quit = Arc::new(AtomicBool::new(false));
        let should_next = Arc::new(AtomicBool::new(false));

        // Spawn input handling thread
        let tempo_clone = Arc::clone(&tempo_multiplier);
        let quit_clone = Arc::clone(&should_quit);
        let next_clone = Arc::clone(&should_next);

        let input_thread = if interactive {
            Some(thread::spawn(move || {
                let stdin = stdin();
                loop {
                    let mut input = String::new();
                    if stdin.read_line(&mut input).is_ok() {
                        let input = input.trim();
                        if input.is_empty() {
                            continue;
                        }
                        if input == "q" {
                            quit_clone.store(true, Ordering::SeqCst);
                            break;
                        } else if input == "n" {
                            next_clone.store(true, Ordering::SeqCst);
                            break;
                        } else if let Some(stripped) = input.strip_prefix("t") {
                            let tempo_str = if stripped.is_empty() {
                                println!("Enter new tempo (BPM): ");
                                let mut tempo_input = String::new();
                                if stdin.read_line(&mut tempo_input).is_ok() {
                                    tempo_input.trim().to_string()
                                } else {
                                    continue;
                                }
                            } else {
                                stripped.to_string()
                            };
                            if let Ok(new_tempo) = tempo_str.parse::<u32>() {
                                if new_tempo > 0 && new_tempo <= 500 {
                                    tempo_clone.store(
                                        (new_tempo as f32 * 1000.0) as u32,
                                        Ordering::Relaxed,
                                    );
                                    println!("⏱️  Tempo changed to {} BPM", new_tempo);
                                } else {
                                    println!(
                                        "⚠️  Invalid tempo: {} (must be 1-500 BPM)",
                                        new_tempo
                                    );
                                }
                            } else {
                                println!("⚠️  Invalid tempo format. Use 't' then enter BPM, or 't<BPM>' (e.g. 't120')");
                            }
                        } else if let Ok(new_tempo) = input.parse::<u32>() {
                            tempo_clone
                                .store((new_tempo as f32 * 1000.0) as u32, Ordering::Relaxed);
                            println!("⏱️   Tempo changed to {} BPM", new_tempo);
                        }
                    }
                }
            }))
        } else {
            None
        };

        let start = Instant::now();
        let mut idx = 0;
        let mut last_tempo = initial_tempo_bpm as f32 * 1000.0;
        let mut time_offset = 0.0;
        let mut last_real_time = 0.0;
        let mut last_print_time = 0u32;
        while idx < timeline.len() {
            let real_elapsed = start.elapsed().as_millis() as u32;

            if real_elapsed >= max_duration_ms {
                break;
            }

            if should_shutdown() {
                println!("🛑 Shutdown requested, stopping scan playback");
                break;
            }

            if should_quit.load(Ordering::SeqCst) || should_next.load(Ordering::SeqCst) {
                println!("🛑 User requested quit/next");
                break;
            }

            let current_tempo = tempo_multiplier.load(Ordering::Relaxed) as f32 / 1000.0;
            let real_elapsed_f = real_elapsed as f32;

            if (current_tempo - last_tempo).abs() > 0.1 {
                let tempo_ratio = current_tempo / last_tempo;
                time_offset += (real_elapsed_f - last_real_time) * (1.0 - tempo_ratio);
                last_tempo = current_tempo;
            }

            let tempo_ratio = current_tempo / (initial_tempo_bpm as f32);
            let adjusted_time = ((real_elapsed_f - time_offset) * tempo_ratio) as u32;
            last_real_time = real_elapsed_f;

            // Print time progress every 100ms
            if real_elapsed / 100 != last_print_time / 100 {
                let progress_seconds = real_elapsed / 1000;
                let total_seconds = max_duration_ms / 1000;
                let progress_percentage =
                    (real_elapsed as f32 / max_duration_ms as f32 * 100.0) as u32;
                print!(
                    "\r🎵 Playing: {}s/{}s ({}%) @ {} BPM",
                    progress_seconds, total_seconds, progress_percentage, current_tempo
                );
                stdout().flush().unwrap_or(());
                last_print_time = real_elapsed;
            }
            while idx < timeline.len() && timeline[idx].t <= adjusted_time {
                let e = &timeline[idx];
                let msg = match e.kind {
                    Kind::On => [0x90 | (e.chan & 0x0F), e.p, e.v],
                    Kind::Off => [0x80 | (e.chan & 0x0F), e.p, 0],
                };
                self.send_midi_command(MidiCommand::SendMessage(msg.to_vec()))?;
                idx += 1;
            }
        }

        // Print final newline to end the progress line

        // Send all notes off
        for channel in 0..16 {
            self.send_midi_command(MidiCommand::SendMessage(vec![0xB0 | channel, 123, 0]))?;
        }

        // Wait for input thread to finish if it was spawned
        if let Some(thread) = input_thread {
            let _ = thread.join();
        }

        println!("🏁 Playback function completed");

        // Return false if user quit, true if song finished naturally or next was pressed
        let quit_flag = should_quit.load(Ordering::SeqCst);
        Ok(!quit_flag)
    }
    /// Simple playback method for non-interactive scan mode - no input handling, just plays for the specified duration
    fn play_events_simple(
        &mut self,
        events: &[Note],
        tempo_bpm: u32,
        max_duration_ms: u32,
    ) -> Result<(), Box<dyn Error>> {
        #[derive(Copy, Clone)]
        enum Kind {
            On,
            Off,
        }

        struct Event {
            t: u32,
            kind: Kind,
            chan: u8,
            p: u8,
            v: u8,
        }

        let mut timeline = Vec::with_capacity(events.len() * 2);
        for note in events {
            if note.start_ms > max_duration_ms {
                continue;
            }

            timeline.push(Event {
                t: note.start_ms,
                kind: Kind::On,
                chan: note.chan,
                p: note.pitch,
                v: note.vel,
            });

            let end_time = note.start_ms + note.dur_ms;
            timeline.push(Event {
                t: if end_time <= max_duration_ms {
                    end_time
                } else {
                    max_duration_ms
                },
                kind: Kind::Off,
                chan: note.chan,
                p: note.pitch,
                v: note.vel,
            });
        }
        timeline.sort_by_key(|e| e.t);

        let start = Instant::now();
        let mut idx = 0;
        let mut last_print_time = 0u32;

        while idx < timeline.len() {
            let real_elapsed = start.elapsed().as_millis() as u32;

            // Stop if we've reached the maximum duration
            if real_elapsed >= max_duration_ms {
                break;
            }

            // Check for shutdown signal
            if should_shutdown() {
                println!("🛑 Shutdown requested, stopping scan playback");
                break;
            }

            // Print time progress every 100ms
            if real_elapsed / 100 != last_print_time / 100 {
                let progress_seconds = real_elapsed / 1000;
                let total_seconds = max_duration_ms / 1000;
                let progress_percentage =
                    (real_elapsed as f32 / max_duration_ms as f32 * 100.0) as u32;
                print!(
                    "\r🎵 Playing: {}s/{}s ({}%) @ {} BPM",
                    progress_seconds, total_seconds, progress_percentage, tempo_bpm
                );
                stdout().flush().unwrap_or(());
                last_print_time = real_elapsed;
            } // Play all events scheduled for this time
            while idx < timeline.len() && timeline[idx].t <= real_elapsed {
                let e = &timeline[idx];
                let msg = match e.kind {
                    Kind::On => [0x90 | (e.chan & 0x0F), e.p, e.v],
                    Kind::Off => [0x80 | (e.chan & 0x0F), e.p, 0],
                };
                self.send_midi_command(MidiCommand::SendMessage(msg.to_vec()))?;
                idx += 1;
            }

            sleep(Duration::from_millis(1));
        }
        // Print final newline to end the progress line
        println!();

        // Send all notes off
        for channel in 0..16 {
            self.send_midi_command(MidiCommand::SendMessage(vec![0xB0 | channel, 123, 0]))?;
        }

        Ok(())
    }

    /// Interactive method to load MIDI files or directories
    fn load_midi_interactive(&mut self) -> Result<(), Box<dyn Error>> {
        println!("\n📁 Load MIDI Files or Directories");
        println!("Enter path(s) separated by spaces (files or directories):");
        print!("Path(s): ");
        stdout().flush()?;

        let mut input = String::new();
        stdin().read_line(&mut input)?;
        let input = input.trim();

        if input.is_empty() {
            println!("❌ No path provided");
            return Ok(());
        }

        let paths: Vec<&str> = input.split_whitespace().collect();
        let mut total_added = 0;

        for path_str in paths {
            // Strip surrounding quotes if present
            let cleaned_path = if (path_str.starts_with('"') && path_str.ends_with('"'))
                || (path_str.starts_with('\'') && path_str.ends_with('\''))
            {
                &path_str[1..path_str.len() - 1]
            } else {
                path_str
            };

            let path = std::path::Path::new(cleaned_path);

            if !path.exists() {
                println!("❌ Path does not exist: {}", cleaned_path);
                continue;
            }

            if path.is_file() {
                if path.extension().and_then(|s| s.to_str()) == Some("mid") {
                    match self.add_song_from_file(path) {
                        Ok(()) => total_added += 1,
                        Err(e) => println!("❌ Failed to load {}: {}", cleaned_path, e),
                    }
                } else if path.extension().and_then(|s| s.to_str()) == Some("xml")
                    || path.extension().and_then(|s| s.to_str()) == Some("musicxml")
                {
                    // Try to parse as MusicXML
                    match musicxml::read_score_partwise(&path.to_string_lossy()) {
                        Ok(_score) => {
                            // Use the same extraction logic as embed_musicxml.rs
                            let xml_song = e_midi_shared::embed_musicxml::extract_musicxml_songs(
                                path.parent().unwrap_or_else(|| std::path::Path::new(".")),
                            )
                            .into_iter()
                            .find(|s| s.filename == path.file_name().unwrap().to_string_lossy());
                            if let Some(xml) = xml_song {
                                let song_info = xml_song_to_song_info(&xml);
                                self.dynamic_songs.push(song_info);
                                // For MusicXML, push empty Vec to dynamic_midi_data to keep indices aligned
                                self.dynamic_midi_data.push(Vec::new());
                                println!(
                                    "✅ Added MusicXML song: {} (index {})",
                                    self.dynamic_songs.last().unwrap().name,
                                    self.get_static_song_count() + self.dynamic_songs.len() - 1
                                );
                            } else {
                                println!("❌ Failed to extract MusicXML song info");
                            }
                        }
                        Err(e) => {
                            println!("❌ Failed to parse MusicXML: {}", e);
                        }
                    }
                } else {
                    println!("❌ Not a MIDI or MusicXML file: {}", cleaned_path);
                }
            } else if path.is_dir() {
                match self.scan_directory(path) {
                    Ok(count) => total_added += count,
                    Err(e) => println!("❌ Failed to scan directory {}: {}", cleaned_path, e),
                }
            }
        }
        if total_added > 0 {
            println!("✅ Successfully loaded {} songs total", total_added);
        } else {
            println!("❌ No songs were loaded");
        }

        Ok(())
    }
    /// Run TUI mode with IPC relay
    pub fn run_tui_mode_with_ipc(&mut self) -> Result<(), Box<dyn Error>> {
        // Initialize IPC publisher for status events
        self.init_ipc_publisher()?;

        // Run TUI mode normally - it will handle its own IPC communication
        crate::tui::run_tui_mode(self)
    }

    /// Process IPC commands from TUI and execute them
    #[allow(dead_code)]
    fn run_ipc_command_loop(
        &mut self,
        mut subscriber: crate::ipc::EventSubscriber,
    ) -> Result<(), Box<dyn Error>> {
        println!("🔗 IPC command loop started, listening for TUI commands...");

        loop {
            if should_shutdown() {
                break;
            }

            // Check for commands from TUI
            match subscriber.try_receive() {
                Ok(events) => {
                    for event in events {
                        self.handle_ipc_command(event)?;
                    }
                }
                Err(_) => {
                    // No events available - continue
                }
            }

            // Small delay to prevent busy waiting
            thread::sleep(Duration::from_millis(10));
        }

        println!("🔗 IPC command loop finished");
        Ok(())
    }

    /// Handle individual IPC commands
    fn handle_ipc_command(&mut self, event: crate::ipc::Event) -> Result<(), Box<dyn Error>> {
        match event {
            crate::ipc::Event::MidiCommandPlay { song_index, .. } => {
                println!("🎵 Received play command for song {}", song_index);
                if song_index < self.get_total_song_count() {
                    // Use the IPC-enabled playback method
                    self.play_song_with_ipc(song_index)?;
                } else {
                    println!("❌ Invalid song index: {}", song_index);
                }
            }
            crate::ipc::Event::MidiCommandStop { .. } => {
                println!("⏹️ Received stop command");
                // Send all notes off
                for channel in 0..16 {
                    self.send_midi_command(MidiCommand::SendMessage(vec![0xB0 | channel, 123, 0]))?;
                }
                self.publish_midi_event(crate::ipc::Event::MidiPlaybackStopped {
                    timestamp: std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_millis() as u64,
                });
            }
            crate::ipc::Event::MidiCommandNext { .. } => {
                println!("⏭️ Received next command");
                // TODO: Implement next song logic
            }
            crate::ipc::Event::MidiCommandPrevious { .. } => {
                println!("⏮️ Received previous command");
                // TODO: Implement previous song logic
            }
            _ => {
                // Ignore other events
            }
        }

        Ok(())
    }

    /// Play a song with resume support. All state is managed internally.
    /// If song_index is None, resumes last song. If position_ms is None, resumes last position.
    /// If tracks or tempo_bpm are None, uses defaults.
    pub fn play_song_resume_aware(
        &mut self,
        song_index: Option<usize>,
        position_ms: Option<u32>,
        tracks: Option<Vec<usize>>,
        tempo_bpm: Option<u32>,
    ) -> Result<bool, Box<dyn Error>> {
        // Determine which song to play
        let idx = match song_index.or(self.current_song_index) {
            Some(i) => i,
            None => {
                println!("[DIAG][resume] No song index provided and no previous song to resume");
                return Err("No song index provided and no previous song to resume".into());
            }
        };
        // let is_resume = position_ms.is_some()
        //     || (Some(idx) == self.current_song_index
        //         && (self.elapsed_ms.is_some() || self.current_tick.is_some()));
        // Always clear resume state before starting new playback
        self.elapsed_ms = None;
        self.current_tick = None;
        self.current_song_index = None;
        // Ensure MIDI device is reset before playback
        let _ = self.send_midi_command(MidiCommand::AllNotesOff);
        // Always clear resume state before starting new playback
        self.elapsed_ms = None;
        self.current_tick = None;
        self.current_song_index = None;
        // Ensure MIDI device is reset before playback
        let _ = self.send_midi_command(MidiCommand::AllNotesOff);
        // Set channel volume (CC#7) and expression (CC#11) to max (127) for all channels before playback
        for channel in 0..16 {
            let _ = self.send_midi_command(MidiCommand::SendMessage(vec![0xB0 | channel, 7, 127]));
            let _ = self.send_midi_command(MidiCommand::SendMessage(vec![0xB0 | channel, 11, 127]));
        }
        // Always clear resume state before starting new playback
        self.elapsed_ms = None;
        self.current_tick = None;
        self.current_song_index = None;
        // Ensure MIDI device is reset before playback
        let _ = self.send_midi_command(MidiCommand::AllNotesOff);
        // Diagnostics: log entry and state
        println!("[DIAG][resume] play_song_resume_aware called: song_index={:?}, position_ms={:?}, tracks={:?}, tempo_bpm={:?}, current_song_index={:?}, elapsed_ms={:?}, current_tick={:?}, is_playing={}",
            song_index, position_ms, tracks, tempo_bpm, self.current_song_index, self.elapsed_ms, self.current_tick, self.is_playing());
        // Always treat as a new play unless position_ms is Some (explicit resume)
        // let is_resume = position_ms.is_some();
        if idx >= self.get_total_song_count() {
            println!("[DIAG][resume] Invalid song index: {}", idx);
            return Err("Invalid song index".into());
        }
        let selected_song = self.get_song(idx).ok_or("Invalid song index")?;
        let tempo = tempo_bpm.unwrap_or(selected_song.default_tempo);
        let track_indices = if let Some(ref tracks) = tracks {
            if tracks.contains(&0) {
                // 0 means all tracks
                selected_song
                    .tracks
                    .iter()
                    .map(|t| t.index)
                    .collect::<Vec<_>>()
            } else {
                // Map user-supplied indices through track_index_map
                tracks
                    .iter()
                    .filter_map(|user_idx| selected_song.track_index_map.get(user_idx).copied())
                    .collect::<Vec<_>>()
            }
        } else {
            // Default to all tracks
            selected_song
                .tracks
                .iter()
                .map(|t| t.index)
                .collect::<Vec<_>>()
        };
        // Get events for the song
        let events = self.get_events_for_song(idx, &track_indices, tempo);
        println!(
            "[DIAG][resume] Got {} events for song {} (tempo {}), tracks={:?}",
            events.len(),
            idx,
            tempo,
            track_indices
        );
        if events.is_empty() {
            println!("[DIAG][resume] No events found for song, cannot resume");
            return Err("No events found for song".into());
        }
        if !events.is_empty() {
            println!(
                "[DIAG][resume] First event: start_ms={}, dur_ms={}, pitch={}",
                events[0].start_ms, events[0].dur_ms, events[0].pitch
            );
            println!(
                "[DIAG][resume] Last event: start_ms={}, dur_ms={}, pitch={}",
                events[events.len() - 1].start_ms,
                events[events.len() - 1].dur_ms,
                events[events.len() - 1].pitch
            );
        }
        // Determine resume position
        let start_ms = position_ms
            .or(self.elapsed_ms)
            .or(self.current_tick)
            .unwrap_or_default();
        // Snap to the closest event (not just >= start_ms)
        let resume_event_time = {
            if events.is_empty() {
                0
            } else {
                // Find the event with start_ms closest to start_ms
                let mut min_diff = u32::MAX;
                let mut closest = events[0].start_ms;
                for e in &events {
                    let diff = e.start_ms.abs_diff(start_ms);
                    if diff < min_diff {
                        min_diff = diff;
                        closest = e.start_ms;
                    }
                }
                closest
            }
        };
        println!(
            "[DEBUG][resume] Requested start_ms={}, snapped to event start_ms={}",
            start_ms, resume_event_time
        );
        // Filter events for resume
        let filtered_events: Vec<Note> = events
            .into_iter()
            .filter(|e| e.start_ms >= resume_event_time)
            .collect();
        let events = if filtered_events.is_empty() {
            // If resume position is at/past end, reset to beginning
            self.current_tick = Some(0);
            self.elapsed_ms = Some(0);
            println!("[DEBUG][resume] Resume position at/past end, resetting to beginning");
            self.get_events_for_song(idx, &track_indices, tempo)
        } else {
            filtered_events
        };
        // Interpolated resume: build new event list
        let mut interpolated_events = Vec::new();
        for note in &events {
            let note_end = note.start_ms + note.dur_ms;
            if note.start_ms <= start_ms && start_ms < note_end {
                // Note is sounding at resume time
                let remaining = note_end.saturating_sub(start_ms);
                if remaining > 0 {
                    interpolated_events.push(Note {
                        start_ms: 0,
                        dur_ms: remaining,
                        chan: note.chan,
                        pitch: note.pitch,
                        vel: note.vel,
                        track: note.track,
                    });
                }
            } else if note.start_ms > start_ms {
                interpolated_events.push(Note {
                    start_ms: note.start_ms - start_ms,
                    dur_ms: note.dur_ms,
                    chan: note.chan,
                    pitch: note.pitch,
                    vel: note.vel,
                    track: note.track,
                });
            }
        }
        if interpolated_events.is_empty() {
            // If resume position is at/past end, reset to beginning
            self.current_tick = Some(0);
            self.elapsed_ms = Some(0);
            println!("[DEBUG][resume] Interpolated resume: at/past end, resetting to beginning");
            interpolated_events = self.get_events_for_song(idx, &track_indices, tempo);
        }
        println!(
            "[DEBUG][resume] Interpolated resume: requested start_ms={}, events after interpolation: {}",
            start_ms, interpolated_events.len()
        );
        if !interpolated_events.is_empty() {
            println!(
                "[DIAG][resume] First interpolated event: start_ms={}, dur_ms={}, pitch={}",
                interpolated_events[0].start_ms,
                interpolated_events[0].dur_ms,
                interpolated_events[0].pitch
            );
            println!(
                "[DIAG][resume] Last interpolated event: start_ms={}, dur_ms={}, pitch={}",
                interpolated_events[interpolated_events.len() - 1].start_ms,
                interpolated_events[interpolated_events.len() - 1].dur_ms,
                interpolated_events[interpolated_events.len() - 1].pitch
            );
        }
        // Update internal state
        self.current_song_index = Some(idx);
        self.current_tick = Some(resume_event_time);
        self.elapsed_ms = Some(resume_event_time);
        self.start_instant = Some(Instant::now());
        self.reset_stop_flag();
        self.is_playing.store(true, Ordering::Relaxed);
        // Do NOT clear resume state here! Only clear after playback is finished.
        let midi_sender = self.midi_sender.clone();
        let stop_flag = Arc::clone(&self.playback_stop_flag);
        let playing_state = Arc::clone(&self.is_playing);
        // Spawn background thread for playback and high-precision resume
        let start_ms_clone = resume_event_time;
        println!("[DIAG][resume] Spawning background playback thread: events={}, tempo={}, start_ms_clone={}", interpolated_events.len(), tempo, start_ms_clone);
        use std::sync::mpsc;
        let (done_tx, done_rx) = mpsc::channel();
        thread::spawn(move || {
            let _ = Self::play_events_in_background_with_tick(
                interpolated_events,
                tempo,
                midi_sender,
                stop_flag,
                playing_state,
                start_ms_clone,
            );
            let _ = done_tx.send(());
        });
        // Wait for playback to finish before cleanup
        let _ = done_rx.recv();
        // After playback is finished, send all notes off and clear resume state
        for channel in 0..16 {
            let _ = self.send_midi_command(MidiCommand::SendMessage(vec![0xB0 | channel, 123, 0]));
        }
        self.elapsed_ms = None;
        self.current_tick = None;
        self.current_song_index = None;
        Ok(true)
    }

    /// Static method to play events in a background thread and update tick (for resume-aware playback)
    fn play_events_in_background_with_tick(
        events: Vec<Note>,
        tempo_bpm: u32,
        midi_sender: std::sync::mpsc::Sender<MidiCommand>,
        stop_flag: Arc<AtomicBool>,
        playing_state: Arc<AtomicBool>,
        start_ms: u32,
    ) -> Result<(), Box<dyn Error>> {
        #[derive(Copy, Clone, Debug)]
        enum Kind {
            On,
            Off,
        }
        #[derive(Debug)]
        struct Scheduled {
            t: u32,
            kind: Kind,
            chan: u8,
            p: u8,
            v: u8,
            // track: u8, // removed unused field
        }
        let mut timeline = Vec::with_capacity(events.len() * 2);
        for n in &events {
            timeline.push(Scheduled {
                t: n.start_ms,
                kind: Kind::On,
                chan: n.chan,
                p: n.pitch,
                v: n.vel,
            });
            timeline.push(Scheduled {
                t: n.start_ms + n.dur_ms,
                kind: Kind::Off,
                chan: n.chan,
                p: n.pitch,
                v: 0,
            });
        }
        timeline.sort_by_key(|e| e.t);
        println!("[DIAG][bg] play_events_in_background_with_tick: timeline events={}, tempo_bpm={}, start_ms={}", timeline.len(), tempo_bpm, start_ms);
        if !timeline.is_empty() {
            println!(
                "[DIAG][bg] First event: t={}, kind={:?}, chan={}, p={}, v={}",
                timeline[0].t, timeline[0].kind, timeline[0].chan, timeline[0].p, timeline[0].v
            );
            println!(
                "[DIAG][bg] Last event: t={}, kind={:?}, chan={}, p={}, v={}",
                timeline[timeline.len() - 1].t,
                timeline[timeline.len() - 1].kind,
                timeline[timeline.len() - 1].chan,
                timeline[timeline.len() - 1].p,
                timeline[timeline.len() - 1].v
            );
        }
        let start = Instant::now();
        let mut idx = 0;
        // Skip events before start_ms
        while idx < timeline.len() && timeline[idx].t < start_ms {
            idx += 1;
        }
        println!(
            "[DIAG][bg] Starting playback loop at idx={}, timeline.len()={}, start_ms={}",
            idx,
            timeline.len(),
            start_ms
        );
        while idx < timeline.len() {
            if should_shutdown() || stop_flag.load(Ordering::Relaxed) {
                println!("[DIAG][bg] Playback stopped: should_shutdown or stop_flag");
                break;
            }
            let event = &timeline[idx];
            let target_time_ms = event.t.saturating_sub(start_ms) as u64;
            let elapsed_ms = start.elapsed().as_millis() as u64;
            if elapsed_ms < target_time_ms {
                thread::sleep(Duration::from_millis(std::cmp::min(
                    target_time_ms - elapsed_ms,
                    50,
                )));
                continue;
            }
            // Send MIDI event through the channel
            let msg = match event.kind {
                Kind::On => vec![0x90 | event.chan, event.p, event.v],
                Kind::Off => vec![0x80 | event.chan, event.p, 0],
            };
            // --- IPC: publish note-level event ---
            #[allow(unused_mut)]
            let mut publish_ipc_event = |evt: crate::ipc::Event| {
                println!("[DIAG][bg] publish_ipc_event called");
                if let Some(sender) = crate::ipc::IPC_EVENT_SENDER.get() {
                    println!("[DIAG][bg] Publishing IPC event: {:?}", evt);
                    let _ = sender.send(evt);
                } else {
                    println!("[DIAG][bg] IPC_EVENT_SENDER not set");
                }
            };
            match event.kind {
                Kind::On => {
                    publish_ipc_event(crate::ipc::Event::MidiNoteOn {
                        channel: event.chan,
                        pitch: event.p,
                        velocity: event.v,
                        timestamp: std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_millis() as u64,
                    });
                }
                Kind::Off => {
                    publish_ipc_event(crate::ipc::Event::MidiNoteOff {
                        channel: event.chan,
                        pitch: event.p,
                        timestamp: std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_millis() as u64,
                    });
                }
            }

            if midi_sender.send(MidiCommand::SendMessage(msg)).is_err() {
                // MIDI thread is probably shutdown, exit gracefully
                break;
            }
            idx += 1;
        }
        println!("[DIAG][bg] Playback loop finished, setting playing_state to false");
        playing_state.store(false, Ordering::Relaxed);
        Ok(())
    }

    /// Helper: Map user-facing track indices to dense indices for a song
    fn get_dense_indices_for_song(song: &SongInfo, user_indices: Option<&[usize]>) -> Vec<usize> {
        if let Some(indices) = user_indices {
            let mut dense_indices = Vec::new();
            if indices.contains(&0) {
                dense_indices = (0..song.tracks.len()).collect();
            } else {
                for user_index in indices {
                    if let Some(&dense) = song.track_index_map.get(user_index) {
                        dense_indices.push(dense);
                    }
                }
                if dense_indices.is_empty() {
                    dense_indices = (0..song.tracks.len()).collect();
                }
            }
            dense_indices
        } else {
            (0..song.tracks.len()).collect()
        }
    }

    /// Play embedded audio data (OGG/MP3/MP4) from static bytes
    pub fn play_embedded_audio(_data: &'static [u8]) -> Result<(), Box<dyn std::error::Error>> {
        #[cfg(feature = "uses_rodio")]
        {
            let (_stream, stream_handle) = OutputStream::try_default()?;
            let sink = Sink::try_new(&stream_handle)?;
            let cursor = Cursor::new(_data);
            let source = Decoder::new(cursor)?;
            sink.append(source);
            sink.sleep_until_end();
        }
        Ok(())
    }
}

/// Converts an XmlSongInfo (from MusicXML) into a SongInfo and its notes, for playback.
pub fn xml_song_to_song_info(xml: &XmlSongInfo) -> SongInfo {
    // Build track index map: user index -> dense index (identity for XML)
    let mut track_index_map = std::collections::HashMap::new();
    for t in &xml.tracks {
        track_index_map.insert(t.index, t.index);
    }
    // Convert XmlTrackInfo to TrackInfo
    let tracks: Vec<TrackInfo> = xml
        .tracks
        .iter()
        .map(|t| TrackInfo {
            index: t.index,
            program: Some(t.program),
            guess: Some(t.name.clone()),
            channels: if t.channels.is_empty() {
                vec![0]
            } else {
                t.channels.clone()
            },
            note_count: t.note_count,
            pitch_range: t.pitch_range,
            sample_notes: t.sample_notes.clone(),
        })
        .collect();
    // Flatten all notes into a Vec<Note>, with track field set and correct channel
    let mut notes = Vec::new();
    for (track_idx, timeline) in xml.track_notes.iter().enumerate() {
        let chan = xml
            .tracks
            .get(track_idx)
            .and_then(|t| t.channels.first())
            .copied()
            .unwrap_or(0);
        for &(start, dur, _voice, midi_pitch, velocity) in timeline {
            notes.push(Note {
                start_ms: start, // You may want to convert ticks to ms elsewhere
                dur_ms: dur,     // You may want to convert ticks to ms elsewhere
                chan,            // Use correct channel for this track
                pitch: midi_pitch,
                vel: velocity,
                track: track_idx as u8,
            });
        }
    }
    SongInfo {
        filename: xml.filename.clone(),
        name: xml.name.clone(),
        tracks,
        default_tempo: xml.default_tempo,
        ticks_per_q: Some(xml.ticks_per_q),
        source: SongSource::None,
        song_type: SongType::MusicXml,
        track_index_map,
        duration_ms: None, // Add this field, or compute from notes if needed
    }
}