medias 0.4.0

TV media player on bare DRM/KMS: Vulkan UI plane over libmpv video, for local files, UPnP/DLNA servers and YouTube, controlled by HDMI-CEC remote, evdev or terminal
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
mod browser;
mod console;
mod egl;
mod gbm;
mod history;
mod input;
mod kms;
mod library;
mod metadata;
mod mpv;
mod shell;
mod thumbs;
mod upnp;
mod ui;
mod vk;
mod youtube;

use std::time::{Duration, Instant};

use drm::Device as BasicDevice;
use drm::buffer::DrmFourcc;
use drm::control::Device as ControlDevice;

use crate::gbm::{Allocator, BufferObjectFlags as Use, Scanout};
use kms::{Card, Output};
use youtube::auth::Account;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if matches!(args.get(1).map(String::as_str), Some("--help" | "-h" | "help")) {
        print_help();
        return;
    }
    if args.get(1).map(String::as_str) == Some("mpv") {
        let url = args.get(2).cloned().unwrap_or_else(default_test_media);
        if let Err(e) = run_mpv(&url) {
            fail(&format!("mpv: {e}"));
        }
        return;
    }
    if args.get(1).map(String::as_str) == Some("metadata") {
        if let Err(e) = metadata::run(&args[2..]) {
            fail(&format!("metadata: {e}"));
        }
        return;
    }
    if args.get(1).map(String::as_str) == Some("video") {
        let dev = args.get(3).map(String::as_str);
        let url = args.get(2).cloned().unwrap_or_else(default_test_media);
        if let Err(e) = run_video(dev, &url) {
            fail(&format!("video: {e}"));
        }
        return;
    }
    if args.get(1).map(String::as_str) == Some("input") {
        run_input(args.get(2).map(String::as_str));
        return;
    }
    if args.get(1).map(String::as_str) == Some("shell") {
        if let Err(e) = run_shell(args.get(2).map(String::as_str)) {
            fail(&format!("shell: {e}"));
        }
        return;
    }
    if args.get(1).map(String::as_str) == Some("comp") {
        let dev = args.get(3).map(String::as_str);
        let url = args.get(2).cloned().unwrap_or_else(default_test_media);
        if let Err(e) = run_compositor(dev, &url) {
            fail(&format!("compositor: {e}"));
        }
        return;
    }
    if args.get(1).map(String::as_str) == Some("bench") {
        if let Err(error) = run_bench(args.get(2).map(String::as_str)) {
            fail(&format!("bench: {error}"));
        }
        return;
    }

    // Default: the media player app. Roots come from --videos/--music flags
    // (repeatable); a /-prefixed arg overrides the display device.
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    let base = std::path::PathBuf::from(home).join("medias");
    let mut roots: Vec<(String, std::path::PathBuf)> = Vec::new();
    let mut dev: Option<String> = None;
    for a in &args[1..] {
        if let Some(v) = a.strip_prefix("--videos") {
            roots.push(parse_root(v, "Videos", &base));
        } else if let Some(v) = a.strip_prefix("--music") {
            roots.push(parse_root(v, "Music", &base));
        } else if a.starts_with('/') {
            dev = Some(a.clone());
        } else {
            fail(&format!("unknown argument: {a}  (try --help)"));
        }
    }
    if roots.is_empty() {
        roots = vec![
            ("Videos".into(), base.join("Videos")),
            ("Music".into(), base.join("Music")),
        ];
    }
    if let Err(e) = run_app(dev.as_deref(), roots) {
        fail(&format!("app: {e}"));
    }
}

fn open_display(dev: Option<&str>) -> Result<(Card, Output, kms::DisplaySession), String> {
    let (card, path) = match dev {
        Some(p) => (Card::open(p).map_err(|e| format!("open {p}: {e}"))?, p.to_string()),
        None => kms::open_primary().map_err(e2s)?,
    };
    println!("display: {path}");
    let output = Output::discover(&card).map_err(|e| format!("discover on {path}: {e}"))?;
    card.acquire_master_lock().map_err(|e| {
        format!(
            "acquire DRM master on {path}: {e}\n\
             Use an active console VT with access to this device and no \
             desktop/compositor holding it."
        )
    })?;
    let session = kms::DisplaySession::new(&card, &output)
        .map_err(|e| format!("console session: {e}"))?;
    Ok((card, output, session))
}

/// Parse a `--videos`/`--music` value into (label, path). `v` is "" (bare),
/// "=PATH" (label from basename), or "=LABEL=PATH". Relative paths resolve
/// under `base` (~/medias).
fn parse_root(v: &str, default_label: &str, base: &std::path::Path) -> (String, std::path::PathBuf) {
    let spec = v.strip_prefix('=').unwrap_or("");
    if spec.is_empty() {
        return (default_label.to_string(), base.join(default_label));
    }
    // "~" and "~/x" expand to $HOME (the shell does not expand "--videos=~/x").
    let resolve = |p: &str| {
        let home = || std::path::PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into()));
        let pb = match p.strip_prefix('~') {
            Some("") => home(),
            Some(rest) if rest.starts_with('/') => home().join(&rest[1..]),
            _ => std::path::PathBuf::from(p),
        };
        if pb.is_absolute() { pb } else { base.join(pb) }
    };
    match spec.split_once('=') {
        Some((label, path)) => (label.to_string(), resolve(path)),
        None => {
            let path = resolve(spec);
            let label = path
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_else(|| default_label.to_string());
            (label, path)
        }
    }
}

/// Graphics bring-up benchmarks (milestones 2-3).
fn run_bench(dev: Option<&str>) -> Result<(), String> {
    let (card, output, mut display) = open_display(dev)?;
    let alloc = Allocator::new(&card).map_err(|e| format!("gbm: {e}"))?;

    let (w, h) = output.mode.size();
    println!("mode {}x{}@{}  ui {:?} video {:?}", w, h, output.mode.vrefresh(), output.ui_plane, output.video_plane);

    println!("\n=== Vulkan ===");
    let gpu = match vk::Gpu::new() {
        Ok(g) => {
            println!("chosen: {}  queue_family={}", g.name, g.queue_family);
            Some(g)
        }
        Err(e) => {
            eprintln!("vulkan bring-up failed: {e}");
            None
        }
    };

    println!("\n=== KMS present (CPU) ===");
    run_cpu(&card, &output, &alloc, w.into(), h.into()).map_err(|e| format!("present: {e}"))?;

    if let Some(gpu) = gpu.filter(|_| !console::stopping()) {
        println!("\n=== KMS present (Vulkan render into scanout dmabuf) ===");
        if let Err(e) = run_gpu(&card, &output, &alloc, &gpu, w.into(), h.into()) {
            eprintln!("gpu present: {e}");
        }
    }
    display.restore();
    Ok(())
}

/// Milestone 4a: libmpv engine bring-up. Decode + control plane only (no
/// display, no audio device) — proves create/init/load/events/properties.
fn run_mpv(url: &str) -> Result<(), String> {
    println!("=== libmpv ({url}) ===");
    let m = mpv::Mpv::new()?;
    m.set_option("vo", "null")?; // 4b wires video to a KMS plane
    m.set_option("ao", "null")?;
    m.set_option("hwdec", "no")?; // Pi: drm-prime / v4l2
    m.set_option("msg-level", "all=error")?;
    m.init()?;
    m.loadfile(url)?;

    let start = Instant::now();
    let mut last = -1.0;
    loop {
        match m.wait_event(0.2) {
            mpv::Event::FileLoaded => {
                println!("file loaded: duration={:.2}s", m.get_f64("duration").unwrap_or(0.0));
            }
            mpv::Event::EndFile(_) | mpv::Event::PlaybackError => {
                println!("end-file");
                break;
            }
            mpv::Event::Shutdown => break,
            _ => {}
        }
        if let Some(t) = m.get_f64("time-pos") {
            if t - last >= 0.5 {
                println!("  time-pos {t:.2}s");
                last = t;
            }
        }
        if start.elapsed().as_secs() > 20 {
            println!("timeout");
            break;
        }
    }
    println!("done in {:.1}s", start.elapsed().as_secs_f64());
    Ok(())
}

/// A browsable node: filesystem, UPnP/DLNA or YouTube.
enum Node {
    Dir(std::path::PathBuf),
    Media(std::path::PathBuf),
    UpnpRoot,                                       // discovered UPnP/DLNA media servers
    UpnpDir(std::sync::Arc<upnp::Server>, String),  // a server container (object id; "0" is the root)
    UpnpMedia(String, upnp::Kind),                  // an item's HTTP resource URL
    YtRoot,              // the YouTube app home
    #[cfg(feature = "youtube-tv")]
    YtForYou,            // YouTube's recommendations (YouTube TV sign-in)
    #[cfg(feature = "youtube-tv")]
    YtTvHistory,         // the account's watch history (YouTube TV sign-in)
    #[cfg(feature = "youtube-tv")]
    YtTvPlaylists,       // own and saved playlists (YouTube TV sign-in)
    #[cfg(feature = "youtube-tv")]
    YtTvPlaylist(String), // a playlist's videos via TV browse (playlist id)
    YtFromHistory,       // related videos of recently watched YouTube videos
    YtSubsLatest,        // signed-in: recent uploads from subscriptions, interleaved
    YtSearch,            // opens the query keyboard; submitting runs a live search
    YtTrending,          // most-popular chart (public)
    YtSubs,              // signed-in: subscribed channels
    YtChannel(String),   // a channel's latest uploads (channel id)
    #[cfg_attr(feature = "youtube-tv", allow(dead_code))] // youtube-tv: YtTvPlaylists
    YtPlaylists,         // signed-in: the account's playlists
    YtPlaylist(String),  // a playlist's videos (playlist id)
    YtLiked,             // signed-in: liked videos
    YtSource(String),    // youtube.txt query resolved via yt-dlp (anonymous fallback)
    YtVideo(String),     // a watch URL; played via direct InnerTube streams
    YtSignIn(Account),   // begin the device-auth flow for an account
    YtSignOut(Account),  // drop an account's stored session
}

/// In-progress device-auth sign-in: the account, its OAuth client, the code
/// shown to the user, and the polling schedule.
struct SignIn {
    account: Account,
    creds: youtube::auth::Credentials,
    device: youtube::auth::DeviceCode,
    qr: Option<(usize, Vec<bool>)>, // (side in modules, row-major dark grid)
    status: String,
    next_poll: Instant,
    expires_at: Instant,
}

struct Item {
    name: String,
    node: Node,
    container: bool, // descends on Select (shown with a trailing '/')
    meta: String,    // right-column text (e.g. a video's duration); else history date
    sub: String,     // secondary line (e.g. a video's channel)
    thumb: String,   // thumbnail URL; empty for none
}

impl Item {
    fn new(name: impl Into<String>, node: Node, container: bool) -> Item {
        Item { name: name.into(), node, container, meta: String::new(), sub: String::new(), thumb: String::new() }
    }

    /// A YouTube watch URL; the thumbnail derives from its video id.
    fn video(title: impl Into<String>, url: String) -> Item {
        let thumb = youtube::video_id(&url).map(|id| youtube::thumb_url(&id)).unwrap_or_default();
        Item { thumb, ..Item::new(title, Node::YtVideo(url), false) }
    }
}

struct Level {
    title: String,
    items: Vec<Item>,
    browse: browser::Browser,
    thumbs: bool, // some item has a thumbnail, or a tile menu: shown as a thumbnail list or grid
}

impl Level {
    fn new(title: impl Into<String>, items: Vec<Item>) -> Self {
        // Filter text: name plus the secondary line (title and channel).
        let names: Vec<String> = items
            .iter()
            .map(|item| if item.sub.is_empty() { item.name.clone() } else { format!("{} {}", item.name, item.sub) })
            .collect();
        let browse = browser::Browser::new(names.iter().map(String::as_str));
        let thumbs = items.iter().any(|item| !item.thumb.is_empty());
        Self { title: title.into(), items, browse, thumbs }
    }

    /// A query-entry level: an on-screen keyboard whose text is submitted for a
    /// live YouTube search.
    fn query(title: impl Into<String>) -> Self {
        Self { title: title.into(), items: Vec::new(), browse: browser::Browser::query_input(), thumbs: false }
    }

    /// A menu shown as labelled tiles (grid) or rows (list) instead of text.
    fn tiles(title: impl Into<String>, items: Vec<Item>) -> Self {
        Self { thumbs: true, ..Self::new(title, items) }
    }

    fn layout(&self, wide: bool) -> shell::Layout {
        match (self.thumbs, wide) {
            (false, _) => shell::Layout::Text,
            (true, false) => shell::Layout::List,
            (true, true) => shell::Layout::Grid,
        }
    }
}

/// The wide (grid) view preference, persisted in ~/medias/.view as "grid" or "list"; default grid.
fn view_path() -> Option<std::path::PathBuf> {
    Some(std::path::PathBuf::from(std::env::var("HOME").ok()?).join("medias/.view"))
}

/// Grid unless ~/medias/.view says "list".
fn load_wide_view() -> bool {
    view_path().and_then(|p| std::fs::read_to_string(p).ok()).is_none_or(|s| s.trim() != "list")
}

fn autoplay_path() -> Option<std::path::PathBuf> {
    Some(std::path::PathBuf::from(std::env::var("HOME").ok()?).join("medias/.autoplay"))
}

/// Play next in folder: on unless ~/medias/.autoplay says "off".
fn load_autoplay() -> bool {
    autoplay_path().and_then(|p| std::fs::read_to_string(p).ok()).is_none_or(|s| s.trim() != "off")
}

fn save_autoplay(on: bool) {
    if let Some(p) = autoplay_path() {
        let _ = std::fs::write(p, if on { "on\n" } else { "off\n" });
    }
}

fn save_wide_view(wide: bool) {
    if let Some(p) = view_path() {
        let _ = std::fs::write(p, if wide { "grid\n" } else { "list\n" });
    }
}

/// Format whole seconds as "H:MM:SS" or "M:SS".
fn fmt_dur(secs: u32) -> String {
    let (h, m, s) = (secs / 3600, (secs % 3600) / 60, secs % 60);
    if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") }
}

// ---- YouTube level builders -----------------------------------------------

fn yt_video_items(videos: Vec<youtube::model::Video>) -> Vec<Item> {
    videos
        .into_iter()
        .map(|v| {
            let meta = if v.duration > 0 { fmt_dur(v.duration) } else { String::new() };
            Item { meta, sub: v.sub(), thumb: youtube::thumb_url(&v.id), ..Item::new(v.title.clone(), Node::YtVideo(v.watch_url()), false) }
        })
        .collect()
}

fn yt_channel_items(channels: Vec<youtube::model::Channel>) -> Vec<Item> {
    channels
        .into_iter()
        .map(|c| Item { thumb: c.thumbs.list().into(), ..Item::new(c.title, Node::YtChannel(c.id), true) })
        .collect()
}

fn yt_playlist_items(playlists: Vec<youtube::model::Playlist>) -> Vec<Item> {
    yt_playlist_items_as(playlists, Node::YtPlaylist)
}

/// Playlist rows opening `node(id)`; the right column is the video count.
fn yt_playlist_items_as(playlists: Vec<youtube::model::Playlist>, node: fn(String) -> Node) -> Vec<Item> {
    playlists
        .into_iter()
        .map(|p| {
            let meta = if p.count > 0 { p.count.to_string() } else { String::new() };
            Item { meta, thumb: p.thumbs.list().into(), ..Item::new(p.title, node(p.id), true) }
        })
        .collect()
}

/// YouTube home: For you, Watched and Playlists (YouTube TV sign-in on
/// first open), Like your watched when YouTube videos were played, Search,
/// Trending, the Data API account sections when signed in, the youtube.txt
/// sources, and the sign-in/out rows.
fn yt_home_items(yt: &youtube::Service, has_history: bool) -> Vec<Item> {
    let mut items = Vec::new();
    #[cfg(feature = "youtube-tv")]
    {
        items.push(Item::new("For you", Node::YtForYou, true));
        items.push(Item::new("Watched", Node::YtTvHistory, true));
        items.push(Item::new("Playlists", Node::YtTvPlaylists, true));
    }
    if has_history {
        items.push(Item::new("Like your watched", Node::YtFromHistory, true));
    }
    if yt.signed_in() {
        items.push(Item::new("Latest from subscriptions", Node::YtSubsLatest, true));
    }
    items.push(Item::new("Search", Node::YtSearch, true));
    if yt.data_api_available() {
        items.push(Item::new("Trending", Node::YtTrending, true));
    }
    if yt.signed_in() {
        items.push(Item::new("Subscriptions", Node::YtSubs, true));
        // youtube-tv builds list playlists via TV browse (includes saved playlists).
        #[cfg(not(feature = "youtube-tv"))]
        items.push(Item::new("Playlists", Node::YtPlaylists, true));
        items.push(Item::new("Liked videos", Node::YtLiked, true));
    }
    for source in youtube::sources() {
        items.push(Item::new(source.label, Node::YtSource(source.query), true));
    }
    if yt.signed_in() {
        let label = match yt.account() {
            Some(name) => format!("Sign out ({name})"),
            None => "Sign out".into(),
        };
        items.push(Item::new(label, Node::YtSignOut(Account::DataApi), false));
    } else {
        // Shown even without credentials; opening it then explains the one-time
        // OAuth client setup rather than silently doing nothing.
        items.push(Item::new("Sign in", Node::YtSignIn(Account::DataApi), false));
    }
    #[cfg(feature = "youtube-tv")]
    if yt.tv_signed_in() {
        items.push(Item::new("Sign out of YouTube TV", Node::YtSignOut(Account::Tv), false));
    }
    items
}

fn yt_home(yt: &youtube::Service, history: &history::History) -> Level {
    Level::tiles("YouTube", yt_home_items(yt, !yt_history_ids(history).is_empty()))
}

/// Result of a background load (`spawn_load`).
enum Loaded {
    Level(Level),
    /// Start playback: `key` is the history key and `target` (+ `audio`) what mpv opens.
    Play { key: String, name: String, target: String, audio: Vec<String>, subs: Vec<String> }, // edl:// tracks
    Failed(String),
}

/// A load running on a worker thread; the browser shows a spinner until it
/// arrives and Back abandons it.
struct Pending {
    label: String,
    rx: std::sync::mpsc::Receiver<Loaded>,
    started: Instant,
}

fn spawn_load(label: impl Into<String>, job: impl FnOnce() -> Loaded + Send + 'static) -> Pending {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(job());
    });
    Pending { label: label.into(), rx, started: Instant::now() }
}

fn level_or_failed(title: String, items: Result<Vec<Item>, String>) -> Loaded {
    match items {
        Ok(items) if items.is_empty() => Loaded::Failed(format!("{title}: nothing found")),
        Ok(items) => Loaded::Level(Level::new(title, items)),
        Err(error) => Loaded::Failed(format!("{title}: {error}")),
    }
}

/// YouTube TV lists opened from the YouTube home.
#[cfg(feature = "youtube-tv")]
#[derive(Clone, Copy)]
enum TvList {
    ForYou,
    History,
    Playlists,
}

#[cfg(feature = "youtube-tv")]
fn yt_tv_open(yt: &mut youtube::Service, list: TvList) -> Pending {
    use youtube::innertube as it;
    match list {
        TvList::ForYou => yt_tv_fetch(yt, "For you", |t| Ok(yt_video_items(it::recommendations(t)?))),
        TvList::History => yt_tv_fetch(yt, "Watched", |t| Ok(yt_video_items(it::tv_videos(t, it::HISTORY_BROWSE_ID)?))),
        TvList::Playlists => {
            yt_tv_fetch(yt, "Playlists", |t| Ok(yt_playlist_items_as(it::tv_playlists(t)?, Node::YtTvPlaylist)))
        }
    }
}

/// Load a level with the YouTube TV token (InnerTube browse) in the background.
#[cfg(feature = "youtube-tv")]
fn yt_tv_fetch(
    yt: &mut youtube::Service,
    title: &str,
    build: impl FnOnce(&str) -> Result<Vec<Item>, String> + Send + 'static,
) -> Pending {
    let (title, token) = (title.to_string(), yt.tv_access_token());
    spawn_load(title.clone(), move || {
        let Some(token) = token else { return Loaded::Failed(format!("{title}: YouTube TV sign-in unavailable")) };
        let items = build(&token);
        if matches!(&items, Ok(v) if v.is_empty()) {
            eprintln!("youtube: {title} empty (MEDIAS_YT_DEBUG=1 dumps the responses to ~/medias)");
        }
        level_or_failed(title, items)
    })
}

/// yt-dlp `sub-langs` raw option for the fallback hook ("de(-.*)?,en(-.*)?",
/// `%len%`-quoted); None keeps the hook's default of all languages.
fn ytdl_sub_langs(langs: &[String]) -> Option<String> {
    let list = langs.iter().map(|l| format!("{l}(-.*)?")).collect::<Vec<_>>().join(",");
    (!list.is_empty()).then(|| format!("sub-langs=%{}%{list}", list.len()))
}

/// Direct InnerTube streams for a watch URL; on failure mpv gets the watch URL
/// (yt-dlp hook). History keys by the watch URL either way.
fn yt_play(url: String, name: String, prefs: youtube::innertube::StreamPrefs) -> Pending {
    spawn_load(name.clone(), move || {
        let direct = youtube::video_id(&url)
            .ok_or_else(|| "no video id in URL".to_string())
            .and_then(|id| youtube::innertube::streams(&id, &prefs));
        let (target, audio, subs) = match direct {
            Ok(streams) => {
                let audio = streams.audio.iter().map(|a| mpv::edl_track(&a.url, &a.lang, &a.title)).collect();
                let subs = streams.subs.iter().map(|s| mpv::edl_sub_track(&s.url, &s.lang, &s.title)).collect();
                (streams.video, audio, subs)
            }
            Err(err) => {
                eprintln!("youtube: direct stream failed ({err}); trying yt-dlp");
                (url.clone(), Vec::new(), Vec::new())
            }
        };
        Loaded::Play { key: url, name, target, audio, subs }
    })
}

/// Request a device code for an account. None (logged on failure) when the
/// request fails or the account has no OAuth client configured.
fn start_sign_in(yt: &youtube::Service, account: Account) -> Option<SignIn> {
    let creds = yt.sign_in_credentials(account)?;
    match youtube::auth::request_device_code(&creds, account.scope()) {
        Ok(device) => {
            let now = Instant::now();
            Some(SignIn {
                account,
                creds,
                qr: youtube::auth::qr_matrix(&device.scan_url()),
                status: "Waiting for approval…".into(),
                next_poll: now + Duration::from_secs(device.interval.max(1)),
                expires_at: now + Duration::from_secs(device.expires_in.max(60)),
                device,
            })
        }
        Err(error) => {
            eprintln!("youtube sign-in: {error}");
            None
        }
    }
}

/// YouTube video ids in the playback history, most recent first.
fn yt_history_ids(history: &history::History) -> Vec<String> {
    history.recent().into_iter().filter_map(youtube::video_id).collect()
}

/// Recent uploads from the subscribed channels, interleaved round-robin.
/// Bounded in channels and per-channel depth to limit latency; playlistItems is
/// 1 quota unit per call and each page is cached.
fn yt_subs_latest(client: &youtube::api::Client) -> Result<Vec<Item>, String> {
    let lists = client
        .subscriptions()?
        .iter()
        .take(12)
        .filter_map(|c| client.playlist_videos(&youtube::api::uploads_playlist_id(&c.id)).ok())
        .map(|mut videos| {
            videos.truncate(4);
            videos
        })
        .collect();
    let videos = youtube::interleave(lists, &Default::default());
    if videos.is_empty() {
        return Err("no subscription uploads found".into());
    }
    Ok(yt_video_items(videos))
}

/// Fetch a YouTube video/channel/playlist level through the Data API client on
/// a worker thread (the token refresh, if due, runs here).
fn yt_fetch(
    yt: &mut youtube::Service,
    title: &str,
    build: impl FnOnce(&youtube::api::Client) -> Result<Vec<Item>, String> + Send + 'static,
) -> Pending {
    let (title, client) = (title.to_string(), yt.client());
    spawn_load(title.clone(), move || level_or_failed(title, client.and_then(|client| build(&client))))
}

/// yt-dlp-resolved videos of a youtube.txt source or an anonymous search.
fn ytdl_items(query: &str) -> Result<Vec<Item>, String> {
    let videos = youtube::resolve(query).map_err(|e| e.to_string())?;
    Ok(videos.into_iter().map(|v| Item::video(v.title, v.url)).collect())
}

/// Live search: Data API when available, else a yt-dlp `ytsearch` fallback so
/// anonymous users can still search.
fn yt_search(yt: &mut youtube::Service, query: String) -> Pending {
    let client = yt.client().ok().filter(|client| client.usable());
    spawn_load(format!("results for “{query}”"), move || {
        let items = match client {
            Some(client) => client.search(&query).map(yt_video_items),
            None => ytdl_items(&format!("ytsearch25:{query}")),
        };
        level_or_failed(query, items)
    })
}

/// Card secondary line: the item's own (channel), "Folder" for a directory, plus
/// the last-played date.
fn card_sub(it: &Item, played: Option<String>) -> String {
    let folder = matches!(it.node, Node::Dir(_) | Node::UpnpDir(..)) && it.sub.is_empty();
    let base = if folder { "Folder" } else { it.sub.as_str() };
    match played {
        Some(date) if base.is_empty() => format!("Watched {date}"),
        Some(date) => format!("{base} · watched {date}"),
        None => base.to_string(),
    }
}

/// Placeholder symbol for a card without a thumbnail.
fn card_icon(it: &Item) -> shell::Icon {
    match &it.node {
        Node::Media(p) if library::classify(p) == Some(library::Kind::Audio) => shell::Icon::Audio,
        Node::UpnpMedia(_, upnp::Kind::Audio) => shell::Icon::Audio,
        Node::Media(_) | Node::YtVideo(_) | Node::UpnpMedia(..) => shell::Icon::Video,
        Node::Dir(_) | Node::UpnpDir(..) | Node::UpnpRoot => shell::Icon::Folder,
        Node::YtRoot | Node::YtSearch | Node::YtSignIn(_) | Node::YtSignOut(_) => shell::Icon::Label,
        Node::YtFromHistory | Node::YtSubsLatest | Node::YtTrending | Node::YtSubs | Node::YtLiked => shell::Icon::Label,
        Node::YtPlaylists | Node::YtSource(_) => shell::Icon::Label,
        #[cfg(feature = "youtube-tv")]
        Node::YtForYou | Node::YtTvHistory | Node::YtTvPlaylists => shell::Icon::Label,
        _ => shell::Icon::None,
    }
}

/// Build a level from a filesystem directory listing. Thumbnail keys are the
/// absolute paths (`thumbs` renders a frame, cover art, or a folder image).
fn lib_items(entries: Vec<library::Entry>) -> Vec<Item> {
    entries
        .into_iter()
        .map(|e| {
            let container = e.kind == library::Kind::Dir;
            let thumb = std::path::absolute(&e.path).unwrap_or_else(|_| e.path.clone()).to_string_lossy().into_owned();
            let node = if container { Node::Dir(e.path) } else { Node::Media(e.path) };
            Item { thumb, ..Item::new(e.name, node, container) }
        })
        .collect()
}

/// One Info press in playback: (bar shown, Info hid it, screen black) after,
/// given the bar's visibility and the two flags before. A bar that timed out
/// counts as not yet hidden by Info, so Info shows it first.
fn info_step(bar: bool, hidden: bool, blank: bool) -> (bool, bool, bool) {
    match (blank, bar, hidden) {
        (true, ..) | (false, false, false) => (true, false, false),
        (false, true, _) => (false, true, false),
        (false, false, true) => (false, false, true),
    }
}

// ---- folder playback queue ------------------------------------------------

/// The playable items (local files, UPnP resources) of the level at stack
/// index `depth`, in its filtered order; `pos` indexes the current one.
struct Queue {
    depth: usize,
    items: Vec<(usize, String, String)>, // (source index, name, path or URL)
    pos: usize,
}

impl Queue {
    fn new(level: &Level, depth: usize, current: usize) -> Option<Queue> {
        let items: Vec<(usize, String, String)> = (0..level.browse.count())
            .filter_map(|filtered| {
                let src = level.browse.source_index(filtered)?;
                let item = &level.items[src];
                let target = match &item.node {
                    Node::Media(path) => path.to_string_lossy().into_owned(),
                    Node::UpnpMedia(url, _) => url.clone(),
                    _ => return None,
                };
                Some((src, item.name.clone(), target))
            })
            .collect();
        let pos = items.iter().position(|(src, ..)| *src == current)?;
        Some(Queue { depth, items, pos })
    }

    /// Move by `step` and return the play request, or None past either end.
    fn step(&mut self, step: isize) -> Option<Loaded> {
        let pos = self.pos.checked_add_signed(step).filter(|&p| p < self.items.len())?;
        self.pos = pos;
        Some(self.play())
    }

    fn play(&self) -> Loaded {
        let (_, name, target) = &self.items[self.pos];
        Loaded::Play { key: target.clone(), name: name.clone(), target: target.clone(), audio: Vec::new(), subs: Vec::new() }
    }

    /// Select the current item in its level if that level is still on the stack.
    fn sync_selection(&self, stack: &mut [Level]) {
        let (src, name, _) = &self.items[self.pos];
        if let Some(level) = stack.get_mut(self.depth)
            && level.items.get(*src).is_some_and(|item| item.name == *name)
        {
            level.browse.select_source(*src);
        }
    }
}

// ---- UPnP/DLNA level builders ---------------------------------------------

fn upnp_server_items(servers: Vec<upnp::Server>) -> Vec<Item> {
    servers
        .into_iter()
        .map(|server| {
            let thumb = server.icon.clone();
            let name = server.name.clone();
            let node = Node::UpnpDir(std::sync::Arc::new(server), "0".into());
            Item { thumb, sub: "Media server".into(), ..Item::new(name, node, true) }
        })
        .collect()
}

/// Containers keep the server; items show duration (meta) and artist · album (sub).
fn upnp_items(server: &std::sync::Arc<upnp::Server>, entries: Vec<upnp::Entry>) -> Vec<Item> {
    entries
        .into_iter()
        .map(|entry| match entry {
            upnp::Entry::Container { id, title, .. } => Item::new(title, Node::UpnpDir(server.clone(), id), true),
            upnp::Entry::Item { title, url, kind, art, duration, artist, album } => {
                let sub = [artist, album].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
                let meta = if duration > 0 { fmt_dur(duration) } else { String::new() };
                Item { thumb: art, sub, meta, ..Item::new(title, Node::UpnpMedia(url, kind), false) }
            }
        })
        .collect()
}

// ---- playback menu (overlaid on the paused video) -------------------------

#[derive(Clone)]
enum Pb {
    Resume,
    Library,
    Stop,
    SeekMenu,
    AudioMenu,
    SubMenu,
    SeekAbs(f64),
    SeekRel(f64),
    SetAid(String),
    SetSid(String),
    Autoplay,
}

struct PbItem {
    name: String,
    node: Pb,
}

struct PbLevel {
    title: String,
    items: Vec<PbItem>,
    selected: usize,
    horizontal: bool, // seek row: Left/Right navigate, OSD stays, repeatable
}

fn pb(name: &str, node: Pb) -> PbItem {
    PbItem { name: name.into(), node }
}

fn pb_root(autoplay: bool) -> PbLevel {
    PbLevel {
        title: "Playback".into(),
        selected: 0,
        horizontal: false,
        items: vec![
            pb("Resume", Pb::Resume),
            pb("Seek", Pb::SeekMenu),
            pb("Audio", Pb::AudioMenu),
            pb("Subtitles", Pb::SubMenu),
            pb(if autoplay { "Play next in folder: on" } else { "Play next in folder: off" }, Pb::Autoplay),
            pb("Browse library", Pb::Library),
            pb("Stop", Pb::Stop),
        ],
    }
}

fn pb_seek() -> PbLevel {
    PbLevel {
        title: "Seek".into(),
        selected: 0,
        horizontal: true,
        items: vec![
            pb("Beginning", Pb::SeekAbs(0.0)),
            pb("-10m", Pb::SeekRel(-600.0)),
            pb("-1m", Pb::SeekRel(-60.0)),
            pb("+1m", Pb::SeekRel(60.0)),
            pb("+10m", Pb::SeekRel(600.0)),
        ],
    }
}

/// mpv track-list entry (audio or subtitle).
fn track_items(m: &mpv::Mpv, kind: &str, off: Option<&str>) -> PbLevel {
    let n = m.get_f64("track-list/count").unwrap_or(0.0) as i64;
    let mut items = Vec::new();
    if let Some(label) = off {
        items.push(pb(label, Pb::SetSid("no".into())));
    }
    for i in 0..n {
        if m.get_string(&format!("track-list/{i}/type")).as_deref() != Some(kind) {
            continue;
        }
        let id = m.get_string(&format!("track-list/{i}/id")).unwrap_or_default();
        let lang = m.get_string(&format!("track-list/{i}/lang")).unwrap_or_default();
        let title = m.get_string(&format!("track-list/{i}/title")).unwrap_or_default();
        let selected = m.get_string(&format!("track-list/{i}/selected")).as_deref() == Some("yes");
        let mut name = format!("{id}");
        if !lang.is_empty() {
            name.push_str(&format!("  {lang}"));
        }
        if !title.is_empty() {
            name.push_str(&format!("  {title}"));
        }
        if selected {
            name.push_str("   *");
        }
        let node = if kind == "audio" { Pb::SetAid(id) } else { Pb::SetSid(id) };
        items.push(pb(&name, node));
    }
    let title = if kind == "audio" { "Audio" } else { "Subtitles" };
    PbLevel { title: title.into(), items, selected: 0, horizontal: false }
}

fn run_app(dev: Option<&str>, roots: Vec<(String, std::path::PathBuf)>) -> Result<(), String> {
    use std::sync::mpsc;

    #[derive(PartialEq)]
    enum Mode {
        Browse, // the content library (opaque)
        Play,   // video on screen + transport
        Menu,   // playback menu overlaid on the paused video
        SignIn, // YouTube device-auth screen (opaque)
    }
    use youtube::auth::Poll;

    println!("=== medias ===");
    for (label, path) in &roots {
        println!("root: {label} -> {}", path.display());
    }

    let (card, mut output, mut display) = open_display(dev)?;
    if output.video_plane.is_none() {
        return Err("need two planes for the app".into());
    }
    let alloc = Allocator::new(&card).map_err(|e| format!("gbm: {e}"))?;
    let (w, h) = (u32::from(output.mode.size().0), u32::from(output.mode.size().1));
    println!("mode: {w}x{h}@{}", output.mode.vrefresh());
    println!("planes: {}", output.describe_planes());
    let mut rates: Vec<f64> = output.rate_modes.iter().map(kms::refresh_hz).collect();
    rates.sort_by(f64::total_cmp);
    rates.dedup_by(|a, b| (*a - *b).abs() < 1e-3);
    println!("refresh rates at {w}x{h}: {}", rates.iter().map(|r| format!("{r:.3}")).collect::<Vec<_>>().join(" "));
    // Display refresh follows the video frame rate (MEDIAS_MATCH_RATE=0 disables).
    let match_rate = std::env::var("MEDIAS_MATCH_RATE").map_or(true, |v| v != "0" && v != "no");
    let mut video_mode = output.base_mode; // mode while a video is playing
    // Playback pauses this long after a switch to a video rate (TV HDMI resync).
    let rate_delay = std::env::var("MEDIAS_MATCH_RATE_DELAY").ok().and_then(|v| v.parse::<f64>().ok())
        .map_or(Duration::from_secs(3), |s| Duration::from_secs_f64(s.max(0.0)));
    let mut sync_until: Option<Instant> = None; // resume playback at this time
    // The sync message is shown at the old rate (the TV is blank during the switch).
    const ANNOUNCE: Duration = Duration::from_secs(1);
    let mut announce_until: Option<Instant> = None; // switch to `video_mode` at this time
    let mut switched = false; // mode changed this iteration; set before the OSD pass

    // Render video at ~1080p and let the display hardware scale it to the mode.
    // On 4K this is ~4x less work for the GPU per frame; invisible for video.
    let vscale = (h / 1080).max(1);
    let (mut vw, mut vh) = (w / vscale, h / vscale);

    let video = egl::VideoGl::new(&alloc)?;
    let (mut ui, text) = ui::UiPlane::new(&alloc, &card, &output, w, h, 2)?;

    // Double-buffered per plane: we always render into the buffer that is NOT
    // currently being scanned out, then flip to it. Single-buffering flickered.
    let mut vbufs = Vec::new(); // video scanout buffers (gbm)
    let mut _vfbos = Vec::new(); // keep the GL FBO imports alive
    let mut vfbo_ids = Vec::new();
    let alloc_video = |vw: u32, vh: u32, vbufs: &mut Vec<_>, vfbos: &mut Vec<_>, ids: &mut Vec<_>| {
        for _ in 0..2 {
            let vb = alloc.alloc(&card, vw, vh, DrmFourcc::Xrgb8888, Use::SCANOUT | Use::RENDERING).map_err(|e| format!("video alloc: {e}"))?;
            let gf = video.import(&vb)?;
            ids.push(video.fbo_id(&gf));
            vfbos.push(gf);
            vbufs.push(vb);
        }
        Ok::<(), String>(())
    };
    alloc_video(vw, vh, &mut vbufs, &mut _vfbos, &mut vfbo_ids)?;
    // Plane scaling is driver-dependent (rejected with EINVAL on NVIDIA GTX
    // 1080 Ti at 3840x2160); fall back to rendering video at the mode size.
    if vscale > 1 {
        match output.test_two(&card, vbufs[0].fb, (vw as u16, vh as u16), ui.fb(0)) {
            Ok(()) => println!("video render: {vw}x{vh} -> hw-scaled to {w}x{h}"),
            Err(e) => {
                println!("video render: {w}x{h} (plane scaling from {vw}x{vh} rejected: {e})");
                for f in _vfbos.drain(..) {
                    video.release(f);
                }
                for b in vbufs.drain(..) {
                    let _ = card.destroy_framebuffer(b.fb);
                }
                vfbo_ids.clear();
                (vw, vh) = (w, h);
                alloc_video(vw, vh, &mut vbufs, &mut _vfbos, &mut vfbo_ids)?;
            }
        }
    }

    let m = mpv::Mpv::new()?;
    m.set_option("vo", "libmpv")?;
    // mpv tries the list in order. PipeWire fails at connect without a session
    // socket (e.g. root), then ALSA. ALSA "default" may route to pipewire-pulse.
    let ao = std::env::var("MEDIAS_AO").unwrap_or_else(|_| "pipewire,alsa,null".into());
    m.set_option("ao", &ao)?;
    // Silence during seek/pause keeps the HDMI audio stream running; a direct
    // ALSA device is otherwise stopped and restarted (clicks, receiver dropouts).
    m.set_option("audio-stream-silence", "yes")?;
    // HDMI audio device varies; let the user pin it (`aplay -L` to find it),
    // e.g. MEDIAS_AUDIO_DEVICE=alsa/sysdefault:CARD=vc4hdmi0
    if let Ok(dev) = std::env::var("MEDIAS_AUDIO_DEVICE") {
        m.set_option("audio-device", &dev)?;
    }
    // Hardware decode (Pi 5: HEVC via v4l2; H.264 is software). Override with
    // MEDIAS_HWDEC=no if interop misbehaves.
    let hwdec = std::env::var("MEDIAS_HWDEC").unwrap_or_else(|_| "auto".into());
    m.set_option("hwdec", &hwdec)?;
    m.set_option("idle", "yes")?;
    // YouTube plays direct InnerTube stream URLs. mpv's yt-dlp hook is only the
    // fallback: without try_ytdl_first it runs after a direct open fails, so it
    // never delays the direct URLs. Absolute path: independent of launch PATH.
    let ytdl_path = youtube::ytdl_path();
    m.set_option("ytdl", "yes")?;
    m.set_option("script-opts", &format!("ytdl_hook-ytdl_path={ytdl_path}"))?;
    let ytdl_format =
        std::env::var("MEDIAS_YTDL_FORMAT").unwrap_or_else(|_| "bestvideo[height<=?1080]+bestaudio/best".into());
    m.set_option("ytdl-format", &ytdl_format)?;
    if let Some(langs) = ytdl_sub_langs(&youtube::innertube::StreamPrefs::from_env().sub_langs) {
        m.set_option("ytdl-raw-options", &langs)?;
    }
    // MEDIAS_MPV_LOG=<path> captures mpv's own verbose log (hook/decode errors).
    if let Ok(path) = std::env::var("MEDIAS_MPV_LOG")
        && !path.is_empty()
    {
        m.set_option("log-file", &path)?;
        m.set_option("msg-level", "all=v")?;
    } else {
        m.set_option("msg-level", "all=error")?;
    }
    // MEDIAS_MPV_CONF=<path>: `key=value` lines ('#' comments) applied last.
    if let Ok(path) = std::env::var("MEDIAS_MPV_CONF")
        && !path.is_empty()
    {
        let conf = std::fs::read_to_string(&path).map_err(|e| format!("MEDIAS_MPV_CONF {path}: {e}"))?;
        for line in conf.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
            let (key, value) = line.split_once('=').unwrap_or((line, "yes"));
            m.set_option(key.trim(), value.trim()).map_err(|e| format!("MEDIAS_MPV_CONF {path}: {line}: {e}"))?;
        }
    }
    m.init()?;
    let rc = gl_render_context(&m)?;

    let mut root_items: Vec<Item> = roots
        .into_iter()
        .map(|(label, path)| Item::new(label, Node::Dir(path), true))
        .collect();
    root_items.push(Item::new("Media servers", Node::UpnpRoot, true));
    root_items.push(Item::new("YouTube", Node::YtRoot, true));
    let mut stack = vec![Level::new("medias", root_items)];
    let mut pbstack: Vec<PbLevel> = Vec::new(); // playback menu
    let mut mode = Mode::Browse;
    let mut now_title = String::new();
    let mut current_path = String::new(); // path/url of the loaded file
    let mut resume_to: Option<f64> = None; // retained until the resume seek finishes
    let mut resume_seek_started = false;
    let mut history = history::History::load();
    let mut yt = youtube::Service::load();
    #[cfg(feature = "youtube-tv")]
    let mut yt_sync = youtube::sync::enabled().then(youtube::sync::Reporter::new);
    #[cfg(feature = "youtube-tv")]
    let mut tv_next = TvList::ForYou; // list opened after a TV sign-in completes
    let stream_prefs = youtube::innertube::StreamPrefs::from_env();
    let mut signin: Option<SignIn> = None;
    let mut thumb_cache = thumbs::Thumbs::new();
    let mut pending: Option<Pending> = None; // background load behind a spinner
    let mut ready: Option<Loaded> = None; // a result to apply this iteration
    let mut notice: Option<(String, Instant)> = None; // failure message until the Instant
    let mut play_started = Instant::now(); // spinner over the black plane until video_live
    let mut spin_phase = usize::MAX; // last rendered spinner step; MAX: hidden
    let spin_epoch = Instant::now();
    const SPIN_DELAY: Duration = Duration::from_millis(150); // no flash for instant loads
    const NOTICE_SECS: Duration = Duration::from_secs(5);
    let mut wide = load_wide_view(); // thumbnail levels: grid instead of list
    let mut autoplay = load_autoplay(); // natural EOF plays the next queue item
    let mut queue: Option<Queue> = None; // folder of the playing local/UPnP item

    let (tx, rx) = mpsc::channel::<input::Key>();
    let sources = input::spawn(tx, display.owns_vt());
    if !sources.available() {
        return Err("no keyboard or CEC input available; check access to /dev/input/event* and /dev/cec0".into());
    }

    let mut frame = vk::Frame::default();
    let mut vfront = 0usize; // video buffer holding the latest frame (shown now)
    // False from a load until mpv's PLAYBACK_RESTART (after any resume seek): frames
    // are rendered but not flipped, so neither the previous file's last frame nor
    // the pre-resume frame at 0:00 is shown; the plane stays black.
    let mut video_live = false;
    let mut video_redraw = false; // render the current frame even without an update
    let mut modeset = false;

    let mut ui_front = 0usize; // last presented UI buffer
    let mut ui_dirty = true; // re-render the UI only when its content changes
    let mut last_sec = u64::MAX;
    let mut playing = false; // media is loaded (menu pauses it, doesn't unload)
    let mut loaded = false; // false until the pending load reaches FILE_LOADED
    let mut osd_until = Instant::now(); // now-playing bar visible until this time
    let mut info_hidden = false; // Info hid the bar; the next Info blanks the screen
    let mut blank = false; // Play: black UI plane over the video, OSD suppressed
    let mut vol_until = Instant::now(); // volume pill visible until this time
    let mut toast_until = Instant::now(); // transient message (track changes)
    let mut toast = String::new();
    let mut last_vis = (false, false, false); // (bar, vol, toast) last rendered
    let osd_secs = Duration::from_secs(10);
    let stats = std::env::var("MEDIAS_STATS").is_ok();
    let (mut presents, mut vrenders, mut uirenders) = (0u32, 0u32, 0u32);
    let (mut vrender_time, mut ui_time) = (Duration::ZERO, Duration::ZERO); // per stats interval
    let mut last_stats = Instant::now();

    let playback_result = (|| -> Result<(), String> {
    'app: loop {
        if console::stopping() {
            break;
        }
        loop {
            match m.wait_event(0.0) {
                mpv::Event::None => break,
                // The file is ready: resume from the saved position, if any.
                mpv::Event::FileLoaded => {
                    loaded = true;
                    resume_seek_started = false;
                    if let Some(d) = m.get_f64("duration") {
                        history.set_duration(&current_path, d);
                    }
                    if match_rate {
                        // container-fps is unavailable without a video track; cover art is a still.
                        let still = m.get_string("current-tracks/video/image").as_deref() == Some("yes");
                        let fps = m.get_f64("container-fps").filter(|_| !still);
                        video_mode = fps.map_or(output.base_mode, |f| output.mode_for_fps(f));
                        if let Some(f) = fps {
                            println!("display: {f:.3} fps -> {:.3} Hz", kms::refresh_hz(&video_mode));
                        }
                    }
                    if let Some(t) = resume_to {
                        if let Err(error) = m.command(&["seek", &t.to_string(), "absolute+exact"]) {
                            eprintln!("resume seek: {error}");
                            resume_to = None;
                        }
                    }
                }
                mpv::Event::Seek if loaded && resume_to.is_some() => resume_seek_started = true,
                mpv::Event::PlaybackRestart => {
                    if loaded && resume_seek_started {
                        resume_to = None;
                        resume_seek_started = false;
                    }
                    // Going live redraws the current frame (a still image renders only once).
                    if !video_live && resume_to.is_none() {
                        video_live = true;
                        video_redraw = true;
                    }
                }
                // Only return to the menu on a natural end; ignore the END_FILE
                // mpv emits when we replace/stop the file ourselves.
                mpv::Event::EndFile(true) if loaded => {
                    loaded = false;
                    history.set_pos(&current_path, 0.0); // watched to the end
                    history.save();
                    playing = false;
                    match queue.as_mut().filter(|_| autoplay).and_then(|q| q.step(1)) {
                        Some(next) => {
                            queue.as_ref().unwrap().sync_selection(&mut stack);
                            ready = Some(next);
                        }
                        None => {
                            mode = Mode::Browse;
                            blank = false;
                        }
                    }
                    ui_dirty = true;
                }
                mpv::Event::PlaybackError => {
                    eprintln!("play: could not open {current_path} (MEDIAS_MPV_LOG=<path> logs mpv's reason)");
                    notice = Some((format!("Could not play {now_title}"), Instant::now() + NOTICE_SECS));
                    loaded = false;
                    playing = false;
                    resume_to = None;
                    mode = Mode::Browse;
                    blank = false;
                    ui_dirty = true;
                    history.save();
                }
                mpv::Event::Shutdown => break 'app,
                _ => {}
            }
        }

        let mut acted = false;
        for key in rx.try_iter() {
            let key = if mode != Mode::Browse && key == input::Key::Char(' ') {
                input::Key::Play
            } else { key };
            acted = true;
            match mode {
                Mode::Browse if pending.is_some() => {
                    // A load is running: Back abandons it; other keys wait.
                    if key == input::Key::Back {
                        pending = None;
                    }
                }
                Mode::Browse => {
                    notice = None;
                    let level = stack.last_mut().unwrap();
                    // Yellow/Info/F4 toggles the list and wide views of thumbnail levels.
                    if key == input::Key::Info && level.thumbs && !level.browse.searching() {
                        wide = !wide;
                        save_wide_view(wide);
                        continue;
                    }
                    let keyboard = level.browse.keyboard().is_some();
                    let (cols, capacity) = shell::browse_shape(w as f32, h as f32, keyboard, level.layout(wide));
                    level.browse.set_columns(cols);
                    match level.browse.handle(key, capacity) {
                        browser::Action::Open(index) => {
                            let l = stack.last().unwrap();
                            let item = &l.items[index];
                            let (name, label) = (item.name.clone(), item.name.clone());
                            match &item.node {
                                Node::Dir(p) => {
                                    let p = p.clone();
                                    pending = Some(spawn_load(name.clone(), move || match library::list(&p) {
                                        Ok(e) => Loaded::Level(Level::new(name, lib_items(e))),
                                        Err(err) => Loaded::Failed(format!("open {}: {err}", p.display())),
                                    }));
                                }
                                Node::UpnpRoot => {
                                    pending = Some(spawn_load("Media servers", || {
                                        match upnp::discover(Duration::from_millis(1500)) {
                                            servers if servers.is_empty() => {
                                                Loaded::Failed("No UPnP/DLNA media servers found".into())
                                            }
                                            servers => Loaded::Level(Level::new("Media servers", upnp_server_items(servers))),
                                        }
                                    }));
                                }
                                Node::UpnpDir(server, id) => {
                                    let (server, id) = (server.clone(), id.clone());
                                    pending = Some(spawn_load(name.clone(), move || {
                                        let items = upnp::browse(&server, &id).map(|e| upnp_items(&server, e));
                                        level_or_failed(name, items)
                                    }));
                                }
                                Node::YtRoot => {
                                    // Fetch the account name once, on first entry while signed in.
                                    if yt.signed_in() && yt.account().is_none() {
                                        yt.refresh_account();
                                    }
                                    stack.push(yt_home(&yt, &history));
                                }
                                #[cfg(feature = "youtube-tv")]
                                Node::YtForYou | Node::YtTvHistory | Node::YtTvPlaylists if !yt.tv_signed_in() => {
                                    tv_next = match &l.items[index].node {
                                        Node::YtTvHistory => TvList::History,
                                        Node::YtTvPlaylists => TvList::Playlists,
                                        _ => TvList::ForYou,
                                    };
                                    // First open: sign in with the YouTube TV client.
                                    signin = start_sign_in(&yt, Account::Tv);
                                    if signin.is_some() {
                                        mode = Mode::SignIn;
                                    }
                                }
                                #[cfg(feature = "youtube-tv")]
                                Node::YtForYou => pending = Some(yt_tv_open(&mut yt, TvList::ForYou)),
                                #[cfg(feature = "youtube-tv")]
                                Node::YtTvHistory => pending = Some(yt_tv_open(&mut yt, TvList::History)),
                                #[cfg(feature = "youtube-tv")]
                                Node::YtTvPlaylists => pending = Some(yt_tv_open(&mut yt, TvList::Playlists)),
                                #[cfg(feature = "youtube-tv")]
                                Node::YtTvPlaylist(id) => {
                                    let browse_id = format!("VL{id}");
                                    pending = Some(yt_tv_fetch(&mut yt, &label, move |t| {
                                        Ok(yt_video_items(youtube::innertube::tv_videos(t, &browse_id)?))
                                    }));
                                }
                                Node::YtFromHistory => {
                                    // Related videos of the last 10 watched, excluding all watched.
                                    let ids = yt_history_ids(&history);
                                    pending = Some(spawn_load("Like your watched", move || {
                                        let watched = ids.iter().cloned().collect();
                                        let videos = youtube::innertube::from_history(&ids[..ids.len().min(10)], &watched);
                                        level_or_failed("Like your watched".into(), Ok(yt_video_items(videos)))
                                    }));
                                }
                                Node::YtSubsLatest => {
                                    pending = Some(yt_fetch(&mut yt, "Latest from subscriptions", yt_subs_latest));
                                }
                                Node::YtSearch => stack.push(Level::query("Search")),
                                Node::YtTrending => {
                                    pending = Some(yt_fetch(&mut yt, "Trending", |c| Ok(yt_video_items(c.trending()?))));
                                }
                                Node::YtSubs => {
                                    pending = Some(yt_fetch(&mut yt, "Subscriptions", |c| Ok(yt_channel_items(c.subscriptions()?))));
                                }
                                Node::YtChannel(id) => {
                                    let id = id.clone();
                                    pending = Some(yt_fetch(&mut yt, &label, move |c| Ok(yt_video_items(c.channel_uploads(&id)?))));
                                }
                                Node::YtPlaylists => {
                                    pending = Some(yt_fetch(&mut yt, "Playlists", |c| Ok(yt_playlist_items(c.playlists()?))));
                                }
                                Node::YtPlaylist(id) => {
                                    let id = id.clone();
                                    pending = Some(yt_fetch(&mut yt, &label, move |c| Ok(yt_video_items(c.playlist_videos(&id)?))));
                                }
                                Node::YtLiked => {
                                    pending = Some(yt_fetch(&mut yt, "Liked videos", |c| {
                                        Ok(yt_video_items(c.playlist_videos(youtube::api::LIKED_PLAYLIST)?))
                                    }));
                                }
                                Node::YtSource(q) => {
                                    let q = q.clone();
                                    pending = Some(spawn_load(label.clone(), move || level_or_failed(label, ytdl_items(&q))));
                                }
                                Node::YtSignIn(account) => {
                                    let account = *account;
                                    signin = start_sign_in(&yt, account);
                                    // signin is None without an OAuth client (the Data API
                                    // setup screen) or when the request failed (stay).
                                    if signin.is_some() || yt.sign_in_credentials(account).is_none() {
                                        mode = Mode::SignIn;
                                    }
                                }
                                Node::YtSignOut(account) => {
                                    let account = *account;
                                    yt.sign_out(account);
                                    *stack.last_mut().unwrap() = yt_home(&yt, &history);
                                }
                                Node::Media(_) | Node::UpnpMedia(..) => {
                                    queue = Queue::new(l, stack.len() - 1, index);
                                    ready = queue.as_ref().map(Queue::play);
                                }
                                Node::YtVideo(url) => {
                                    queue = None;
                                    pending = Some(yt_play(url.clone(), name, stream_prefs.clone()));
                                }
                            }
                        }
                        browser::Action::Submit(query) => pending = Some(yt_search(&mut yt, query)),
                        browser::Action::Back => {
                            if stack.len() > 1 {
                                stack.pop();
                            } else if playing {
                                mode = Mode::Play;
                                let _ = m.set_property("pause", "no");
                                osd_until = Instant::now() + osd_secs;
                            } else {
                                break 'app;
                            }
                        }
                        browser::Action::Resume if playing => {
                            mode = Mode::Play;
                            let _ = m.set_property("pause", "no");
                            osd_until = Instant::now() + osd_secs;
                        }
                        _ => {}
                    }
                }
                Mode::Play => {
                    // Info cycles: bar shown -> hidden -> screen black -> bar shown.
                    if key == input::Key::Info {
                        let show;
                        (show, info_hidden, blank) = info_step(Instant::now() < osd_until, info_hidden, blank);
                        osd_until = if show { Instant::now() + osd_secs } else { Instant::now() };
                        ui_dirty = true;
                        continue;
                    }
                    // Volume keeps the screen black; any other key lights it.
                    if blank && !matches!(key, input::Key::Up | input::Key::Down) {
                        blank = false;
                        ui_dirty = true;
                    }
                    if !blank {
                        osd_until = Instant::now() + osd_secs; // any key reveals the OSD
                        info_hidden = false;
                    }
                    match key {
                        // Back opens the content library (video stays loaded, paused).
                        input::Key::Back => {
                            mode = Mode::Browse;
                            let _ = m.set_property("pause", "yes");
                            checkpoint_playback(&m, &mut history, &current_path, loaded && resume_to.is_none());
                        }
                        // OK / Pause open the playback menu (pauses).
                        input::Key::Select | input::Key::Pause => {
                            mode = Mode::Menu;
                            pbstack = vec![pb_root(autoplay)];
                            let _ = m.set_property("pause", "yes");
                            checkpoint_playback(&m, &mut history, &current_path, loaded && resume_to.is_none());
                        }
                        input::Key::Play => {
                            let _ = m.command(&["cycle", "pause"]);
                        }
                        input::Key::Stop => {
                            checkpoint_playback(&m, &mut history, &current_path, loaded && resume_to.is_none());
                            loaded = false;
                            let _ = m.command(&["stop"]);
                            playing = false;
                            mode = Mode::Browse;
                        }
                        input::Key::Audio => {
                            let _ = m.command(&["cycle", "audio"]);
                            let title = m.get_string("current-tracks/audio/title")
                                .or_else(|| m.get_string("current-tracks/audio/lang"))
                                .or_else(|| m.get_string("aid"))
                                .unwrap_or_else(|| "?".into());
                            toast = format!("Audio track: {title}");
                            toast_until = Instant::now() + Duration::from_secs(2);
                        }
                        input::Key::Subtitle => {
                            let _ = m.command(&["cycle", "sub"]);
                            toast = format!("Subtitles: {}", m.get_string("sid").unwrap_or_else(|| "off".into()));
                            toast_until = Instant::now() + Duration::from_secs(2);
                        }
                        input::Key::Left => {
                            let _ = m.command(&["seek", "-10"]);
                        }
                        input::Key::Right => {
                            let _ = m.command(&["seek", "10"]);
                        }
                        input::Key::Prev => {
                            let _ = m.command(&["seek", "-60"]); // CEC rewind
                        }
                        input::Key::Next => {
                            let _ = m.command(&["seek", "60"]); // CEC fast-forward
                        }
                        input::Key::SkipNext | input::Key::Char('>') => {
                            if let Some(next) = queue.as_mut().and_then(|q| q.step(1)) {
                                queue.as_ref().unwrap().sync_selection(&mut stack);
                                ready = Some(next);
                            }
                        }
                        // Previous restarts the item after its first 5 s, as music players do.
                        input::Key::SkipPrev | input::Key::Char('<') => {
                            if m.get_f64("time-pos").unwrap_or(0.0) > 5.0 {
                                let _ = m.command(&["seek", "0", "absolute"]);
                            } else if let Some(prev) = queue.as_mut().and_then(|q| q.step(-1)) {
                                queue.as_ref().unwrap().sync_selection(&mut stack);
                                ready = Some(prev);
                            }
                        }
                        input::Key::Up => {
                            let _ = m.command(&["add", "volume", "5"]);
                            vol_until = Instant::now() + Duration::from_secs(2);
                        }
                        input::Key::Down => {
                            let _ = m.command(&["add", "volume", "-5"]);
                            vol_until = Instant::now() + Duration::from_secs(2);
                        }
                        input::Key::Menu => {
                            mode = Mode::Menu;
                            pbstack = vec![pb_root(autoplay)];
                            let _ = m.set_property("pause", "yes");
                        }
                        _ => {}
                    }
                }
                Mode::Menu => {
                    let (n, horizontal) = {
                        let l = pbstack.last().unwrap();
                        (l.items.len(), l.horizontal)
                    };
                    // Vertical lists navigate Up/Down; the seek row Left/Right.
                    let (prev, next) = if horizontal {
                        (input::Key::Left, input::Key::Right)
                    } else {
                        (input::Key::Up, input::Key::Down)
                    };
                    match key {
                        k if k == prev && n > 0 => {
                            let l = pbstack.last_mut().unwrap();
                            l.selected = (l.selected + n - 1) % n;
                        }
                        k if k == next && n > 0 => {
                            let l = pbstack.last_mut().unwrap();
                            l.selected = (l.selected + 1) % n;
                        }
                        input::Key::PageUp | input::Key::Prev if !horizontal => {
                            let l = pbstack.last_mut().unwrap();
                            l.selected = l.selected.saturating_sub(shell::playback_capacity(w as f32, h as f32));
                        }
                        input::Key::PageDown | input::Key::Next if !horizontal => {
                            let l = pbstack.last_mut().unwrap();
                            l.selected = l.selected.saturating_add(shell::playback_capacity(w as f32, h as f32))
                                .min(n.saturating_sub(1));
                        }
                        input::Key::Home => pbstack.last_mut().unwrap().selected = 0,
                        input::Key::End => pbstack.last_mut().unwrap().selected = n.saturating_sub(1),
                        input::Key::Back => {
                            if pbstack.len() > 1 {
                                pbstack.pop();
                            } else {
                                mode = Mode::Play;
                                let _ = m.set_property("pause", "no");
                                osd_until = Instant::now() + osd_secs;
                            }
                        }
                        // Exits so you're never trapped: resume or stop.
                        input::Key::Play | input::Key::Pause | input::Key::Menu => {
                            mode = Mode::Play;
                            let _ = m.set_property("pause", "no");
                            osd_until = Instant::now() + osd_secs;
                        }
                        input::Key::Stop => {
                            checkpoint_playback(&m, &mut history, &current_path, loaded && resume_to.is_none());
                            loaded = false;
                            let _ = m.command(&["stop"]);
                            playing = false;
                            mode = Mode::Browse;
                        }
                        input::Key::Select if n > 0 => {
                            let node = pbstack.last().unwrap().items[pbstack.last().unwrap().selected].node.clone();
                            match node {
                                Pb::Resume => {
                                    let _ = m.set_property("pause", "no");
                                    mode = Mode::Play;
                                    osd_until = Instant::now() + osd_secs;
                                }
                                Pb::Library => {
                                    checkpoint_playback(&m, &mut history, &current_path, loaded && resume_to.is_none());
                                    mode = Mode::Browse; // stays paused
                                }
                                Pb::Stop => {
                                    checkpoint_playback(&m, &mut history, &current_path, loaded && resume_to.is_none());
                                    loaded = false;
                                    let _ = m.command(&["stop"]);
                                    playing = false;
                                    mode = Mode::Browse;
                                }
                                Pb::Autoplay => {
                                    autoplay = !autoplay;
                                    save_autoplay(autoplay);
                                    let sel = pbstack[0].selected;
                                    pbstack[0] = pb_root(autoplay);
                                    pbstack[0].selected = sel;
                                }
                                Pb::SeekMenu => pbstack.push(pb_seek()),
                                Pb::AudioMenu => pbstack.push(track_items(&m, "audio", None)),
                                Pb::SubMenu => pbstack.push(track_items(&m, "sub", Some("Off"))),
                                // Jump to the start and return to the video.
                                Pb::SeekAbs(t) => {
                                    let _ = m.command(&["seek", &t.to_string(), "absolute"]);
                                    let _ = m.set_property("pause", "no");
                                    mode = Mode::Play;
                                    osd_until = Instant::now() + osd_secs;
                                }
                                // Relative seek stays in the row so it repeats.
                                Pb::SeekRel(d) => {
                                    let _ = m.command(&["seek", &d.to_string()]);
                                }
                                Pb::SetAid(id) => {
                                    let _ = m.set_property("aid", &id);
                                    let sel = pbstack.last().map(|l| l.selected).unwrap_or(0);
                                    if let Some(l) = pbstack.last_mut() {
                                        *l = track_items(&m, "audio", None);
                                        l.selected = sel.min(l.items.len().saturating_sub(1));
                                    }
                                }
                                Pb::SetSid(id) => {
                                    let _ = m.set_property("sid", &id);
                                    let sel = pbstack.last().map(|l| l.selected).unwrap_or(0);
                                    if let Some(l) = pbstack.last_mut() {
                                        *l = track_items(&m, "sub", Some("Off"));
                                        l.selected = sel.min(l.items.len().saturating_sub(1));
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                }
                Mode::SignIn => {
                    // Back cancels; everything else is ignored while polling.
                    if key == input::Key::Back {
                        signin = None;
                        mode = Mode::Browse;
                        ui_dirty = true;
                    }
                }
            }
        }

        ui_dirty |= acted;

        // Apply a finished background load (or an immediate local play).
        if ready.is_none() && let Some(polled) = pending.as_ref().map(|p| (p.rx.try_recv(), p.label.clone())) {
            match polled {
                (Ok(result), _) => ready = Some(result),
                (Err(std::sync::mpsc::TryRecvError::Disconnected), label) => {
                    ready = Some(Loaded::Failed(format!("{label}: load failed")));
                }
                (Err(std::sync::mpsc::TryRecvError::Empty), _) => {}
            }
            if ready.is_some() {
                pending = None;
            }
        }
        match ready.take() {
            Some(Loaded::Level(level)) => {
                stack.push(level);
                ui_dirty = true;
            }
            Some(Loaded::Failed(message)) => {
                eprintln!("{message}");
                notice = Some((message, Instant::now() + NOTICE_SECS));
                ui_dirty = true;
            }
            Some(Loaded::Play { key, name, target, audio, subs }) => {
                if playing && loaded && resume_to.is_none() {
                    if let Some(t) = m.get_f64("time-pos") {
                        history.set_pos(&current_path, t);
                    }
                    history.save();
                }
                // Replaces (or, for local files, clears) any YouTube audio and
                // caption tracks. mpv selects external subtitles unconditionally;
                // sid=no keeps captions off until chosen.
                let audio: Vec<&str> = audio.iter().map(String::as_str).collect();
                let subs: Vec<&str> = subs.iter().map(String::as_str).collect();
                let load = || if subs.is_empty() { m.loadfile(&target) } else { m.loadfile_with(&target, "sid=no") };
                match m.set_audio_files(&audio).and_then(|()| m.set_sub_files(&subs)).and_then(|()| load()) {
                    Ok(()) => {
                        resume_to = history.pos(&key);
                        now_title = name;
                        current_path = key.clone();
                        playing = true;
                        loaded = false;
                        resume_seek_started = false;
                        mode = Mode::Play;
                        vfront ^= 1;
                        video.clear(vfbo_ids[vfront]);
                        video_live = false;
                        play_started = Instant::now();
                        let _ = m.set_property("pause", "no");
                        history.touch(&key);
                        history.save();
                        osd_until = Instant::now() + osd_secs;
                    }
                    Err(err) => {
                        eprintln!("play: {err}");
                        notice = Some((format!("Could not play {name}: {err}"), Instant::now() + NOTICE_SECS));
                    }
                }
                ui_dirty = true;
            }
            None => {}
        }

        // Spinner: a 12-step turn per second, shown once a load or a video start
        // has taken SPIN_DELAY; re-render only when the step changes.
        if notice.as_ref().is_some_and(|(_, until)| Instant::now() >= *until) {
            notice = None;
            ui_dirty = true;
        }
        let spinning = pending.as_ref().is_some_and(|p| p.started.elapsed() >= SPIN_DELAY)
            || (mode == Mode::Play && playing && !video_live && play_started.elapsed() >= SPIN_DELAY);
        let phase = if spinning { (spin_epoch.elapsed().as_millis() / 83) as usize % 12 } else { usize::MAX };
        if phase != spin_phase {
            spin_phase = phase;
            ui_dirty = true;
        }
        if thumb_cache.pump(|slot, tw, th, rgba| ui.upload_thumb(&text, slot, tw, th, rgba)) && mode == Mode::Browse {
            ui_dirty = true;
        }

        // Device-auth: poll for the user's approval on the server's interval.
        if mode == Mode::SignIn && let Some(si) = signin.as_mut() {
            let now = Instant::now();
            if now >= si.expires_at {
                si.status = "Code expired — press Back".into();
                ui_dirty = true;
            } else if now >= si.next_poll {
                match youtube::auth::poll_once(&si.creds, &si.device.device_code) {
                    Poll::Pending => si.next_poll = now + Duration::from_secs(si.device.interval),
                    Poll::SlowDown => {
                        si.device.interval += 5;
                        si.next_poll = now + Duration::from_secs(si.device.interval);
                    }
                    Poll::Granted(tokens) => {
                        let account = si.account;
                        yt.complete_sign_in(account, tokens);
                        signin = None;
                        *stack.last_mut().unwrap() = yt_home(&yt, &history);
                        // Continue into the TV list that started the sign-in.
                        #[cfg(feature = "youtube-tv")]
                        if account == Account::Tv {
                            pending = Some(yt_tv_open(&mut yt, tv_next));
                        }
                        mode = Mode::Browse;
                        ui_dirty = true;
                    }
                    Poll::Denied => {
                        si.status = "Access denied — press Back".into();
                        ui_dirty = true;
                    }
                    Poll::Expired => {
                        si.status = "Code expired — press Back".into();
                        ui_dirty = true;
                    }
                    Poll::Error(err) => {
                        si.status = format!("Error: {err} — press Back");
                        ui_dirty = true;
                    }
                }
            }
        }

        // Video: render a newly decoded frame into the free buffer and promote
        // it, whenever the video is visible (Play, or the menu overlaid on it —
        // so seeking previews the frame). The opaque library (Browse) skips it.
        if matches!(mode, Mode::Play | Mode::Menu) && (std::mem::take(&mut video_redraw) || rc.frame_ready()) {
            let vback = vfront ^ 1;
            let t0 = Instant::now();
            video.mpv_render(|| rc.render(vfbo_ids[vback], vw as i32, vh as i32))?;
            video.finish();
            vrender_time += t0.elapsed();
            if video_live {
                vfront = vback;
            }
            vrenders += 1;
        }

        // Track the live position for resume (memory only; saved at transitions
        // to avoid per-second SD writes).
        if playing && loaded && resume_to.is_none() {
            if let Some(t) = m.get_f64("time-pos") {
                history.set_pos(&current_path, t);
            }
        }
        #[cfg(feature = "youtube-tv")]
        if let Some(sync) = yt_sync.as_mut() {
            let video = (playing && loaded && resume_to.is_none()).then(|| youtube::video_id(&current_path)).flatten();
            sync.update(video.as_deref(), m.get_f64("time-pos"), || yt.tv_access_token());
        }

        // Video rate while playing or between autoplay entries (mode stays Play);
        // the preferred mode once stopped in the library. Same size: buffers stay.
        // A switch to a video rate pauses, shows the message for ANNOUNCE, then
        // hides it and switches; playback resumes `rate_delay` later.
        if !playing && mode == Mode::Browse {
            video_mode = output.base_mode;
        }
        switched = false;
        if output.mode == video_mode {
            announce_until = None;
        } else {
            let now = Instant::now();
            if playing && video_mode != output.base_mode && !rate_delay.is_zero() && announce_until.is_none() {
                let _ = m.set_property("pause", "yes");
                announce_until = Some(now + ANNOUNCE);
                toast = format!("Syncing display: {:.3} Hz", kms::refresh_hz(&video_mode));
                toast_until = now + ANNOUNCE;
            }
            if announce_until.is_none_or(|t| now >= t) {
                switched = true;
                output.mode = video_mode;
                modeset = false;
                toast_until = now;
            }
        }

        // OSD visibility (Play only): bar auto-hides after `osd_secs`, the volume
        // pill and track toast after 2s. Re-render on any visibility change.
        let now = Instant::now();
        let show_bar = mode == Mode::Play && !blank && now < osd_until;
        let show_vol = mode == Mode::Play && !blank && now < vol_until;
        let show_toast = mode == Mode::Play && !blank && now < toast_until;
        if (show_bar, show_vol, show_toast) != last_vis {
            ui_dirty = true;
            last_vis = (show_bar, show_vol, show_toast);
        }
        if show_bar {
            let sec = m.get_f64("time-pos").unwrap_or(0.0) as u64;
            if sec != last_sec {
                last_sec = sec;
                ui_dirty = true;
            }
        }

        // UI: rebuild + re-render only when it changed.
        if ui_dirty {
            match mode {
                Mode::Browse => {
                    let l = stack.last_mut().unwrap();
                    let layout = l.layout(wide);
                    let (cols, capacity) = shell::browse_shape(w as f32, h as f32, l.browse.keyboard().is_some(), layout);
                    l.browse.set_columns(cols);
                    let range = l.browse.window(capacity);
                    let first = range.start;
                    let key = |it: &Item| match &it.node {
                        Node::Media(p) => Some(p.to_string_lossy().into_owned()),
                        Node::YtVideo(u) | Node::UpnpMedia(u, _) => Some(u.clone()),
                        _ => None,
                    };
                    let played = |it: &Item| key(it).and_then(|k| history.date(&k));
                    let progress = |it: &Item| key(it).and_then(|k| history.progress(&k));
                    let (mut rows, mut row_progress, mut cards) = (Vec::new(), Vec::new(), Vec::new());
                    if layout == shell::Layout::Text {
                        (rows, row_progress) = range
                            .map(|index| {
                                let it = &l.items[l.browse.source_index(index).unwrap()];
                                let label = if it.container { format!("{}/", it.name) } else { it.name.clone() };
                                // Right column: an item's own meta (e.g. duration), else its last-played date.
                                let right = if !it.meta.is_empty() { it.meta.clone() } else { played(it).unwrap_or_default() };
                                ((label, right), progress(it))
                            })
                            .unzip();
                    } else {
                        // Fetch order is newest-first: the next page, then the visible
                        // items last to first, so the first visible item loads first.
                        thumb_cache.begin_frame();
                        let next = range.end..(range.end + capacity).min(l.browse.count());
                        for index in next.rev() {
                            thumb_cache.prefetch(&l.items[l.browse.source_index(index).unwrap()].thumb);
                        }
                        for index in range.rev() {
                            let it = &l.items[l.browse.source_index(index).unwrap()];
                            let sub = card_sub(it, played(it));
                            let thumb = thumb_cache.get(&it.thumb);
                            cards.push(shell::Card {
                                title: it.name.clone(), sub, meta: it.meta.clone(), thumb, icon: card_icon(it), progress: progress(it),
                            });
                        }
                        cards.reverse();
                    }
                    let view = shell::BrowseView {
                        title: &l.title, layout, rows: &rows, progress: &row_progress, cards: &cards, first,
                        selected: l.browse.selected(), matches: l.browse.count(),
                        total: l.browse.total(), query: l.browse.query(),
                        searching: l.browse.searching(), keyboard: l.browse.keyboard(),
                        search_focused: l.browse.search_focused(),
                    };
                    shell::render_browse(&mut frame, &text, &view, w as f32, h as f32);
                    if let Some(p) = pending.as_ref().filter(|_| spin_phase != usize::MAX) {
                        shell::render_status(&mut frame, &text, &format!("Loading {}…", p.label), Some(spin_phase), w as f32, h as f32);
                    } else if let Some((message, _)) = &notice {
                        shell::render_status(&mut frame, &text, message, None, w as f32, h as f32);
                    }
                }
                Mode::Play if blank => shell::render_blank(&mut frame, &text, w as f32, h as f32),
                Mode::Play => {
                    let pos = m.get_f64("time-pos").unwrap_or(0.0);
                    let dur = m.get_f64("duration").unwrap_or(0.0);
                    let vol = m.get_f64("volume").unwrap_or(0.0);
                    let toast_opt = if show_toast { Some(toast.as_str()) } else { None };
                    shell::render_osd(&mut frame, &text, &now_title, pos, dur, vol, show_bar, show_vol, toast_opt, w as f32, h as f32);
                    if spin_phase != usize::MAX {
                        shell::render_status(&mut frame, &text, &format!("Loading {now_title}…"), Some(spin_phase), w as f32, h as f32);
                    }
                }
                Mode::Menu => {
                    let l = pbstack.last().unwrap();
                    let items: Vec<String> = l.items.iter().map(|it| it.name.clone()).collect();
                    if l.horizontal {
                        let pos = m.get_f64("time-pos").unwrap_or(0.0);
                        let dur = m.get_f64("duration").unwrap_or(0.0);
                        shell::render_seek(&mut frame, &text, &now_title, pos, dur, &items, l.selected, w as f32, h as f32);
                    } else {
                        shell::render_overlay(&mut frame, &text, &l.title, &items, l.selected, w as f32, h as f32);
                    }
                }
                Mode::SignIn => match &signin {
                    Some(si) => shell::render_signin(
                        &mut frame, &text,
                        &si.device.user_code, &si.device.verification_url, &si.status,
                        si.qr.as_ref().map(|(n, m)| (*n, m.as_slice())),
                        w as f32, h as f32,
                    ),
                    None => shell::render_signin_setup(&mut frame, &text, w as f32, h as f32),
                },
            }
            let ui_back = ui_front ^ 1;
            let t0 = Instant::now();
            ui.render(&card, &text, ui_back, &frame)?;
            ui_time += t0.elapsed();
            uirenders += 1;
            ui_front = ui_back;
            ui_dirty = false;
        }
        if console::stopping() {
            break;
        }
        // Resume after the resync delay; not behind the playback menu (its Resume unpauses).
        if let Some(t) = sync_until
            && (!playing || Instant::now() >= t)
        {
            sync_until = None;
            if playing && mode == Mode::Play {
                let _ = m.set_property("pause", "no");
            }
        }
        if modeset {
            output.present_two(&card, vbufs[vfront].fb, (vw as u16, vh as u16), ui.fb(ui_front)).map_err(e2s)?;
        } else {
            let mut result = output.modeset_two(&card, vbufs[vfront].fb, (vw as u16, vh as u16), ui.fb(ui_front));
            if let Err(error) = &result
                && output.mode != output.base_mode
            {
                eprintln!("display: {:.3} Hz rejected ({error}); keeping the preferred mode", kms::refresh_hz(&output.mode));
                (output.mode, video_mode) = (output.base_mode, output.base_mode);
                result = output.modeset_two(&card, vbufs[vfront].fb, (vw as u16, vh as u16), ui.fb(ui_front));
            }
            result.map_err(|e| format!("modeset (video {vw}x{vh}, UI {w}x{h}): {e}"))?;
            modeset = true;
        }
        if switched && announce_until.take().is_some() {
            // A rejected mode (fallback to base) resumes at once.
            let delay = if output.mode != output.base_mode { rate_delay } else { Duration::ZERO };
            sync_until = Some(Instant::now() + delay);
        }
        presents += 1;

        if stats && last_stats.elapsed() >= Duration::from_secs(1) {
            let secs = last_stats.elapsed().as_secs_f64();
            let vf_fps = m.get_f64("estimated-vf-fps").unwrap_or(0.0);
            let drops = m.get_f64("frame-drop-count").unwrap_or(0.0);
            let hwdec = m.get_string("hwdec-current").unwrap_or_default();
            let avg = |t: Duration, n: u32| if n == 0 { 0.0 } else { t.as_secs_f64() * 1e3 / n as f64 };
            println!(
                "stats: present {:.0}/s  video-render {:.0}/s ({:.1} ms)  ui-render {:.0}/s ({:.1} ms)  mpv vf-fps {vf_fps:.1}  drops {drops:.0}  hwdec {}",
                presents as f64 / secs,
                vrenders as f64 / secs,
                avg(vrender_time, vrenders),
                uirenders as f64 / secs,
                avg(ui_time, uirenders),
                if hwdec.is_empty() { "no" } else { &hwdec },
            );
            (presents, vrenders, uirenders) = (0, 0, 0);
            (vrender_time, ui_time) = (Duration::ZERO, Duration::ZERO);
            last_stats = Instant::now();
        }
    }

    Ok(())
    })();
    finish_playback(&m, &mut history, &current_path, loaded, resume_to.is_some());
    #[cfg(feature = "youtube-tv")]
    if let Some(sync) = yt_sync {
        sync.finish(|| yt.tv_access_token());
    }
    drop(sources);
    display.restore();
    drop(rc);
    drop(m);
    ui.destroy(text, &card);
    for b in vbufs {
        let _ = card.destroy_framebuffer(b.fb);
    }
    playback_result
}

/// Menu demo; auto-advances for ten seconds if no input source is available.
fn run_shell(dev: Option<&str>) -> Result<(), String> {
    use std::sync::mpsc;

    println!("=== shell ===");
    let (card, output, mut display) = open_display(dev)?;
    let alloc = Allocator::new(&card).map_err(|e| format!("gbm: {e}"))?;
    let (w, h) = (u32::from(output.mode.size().0), u32::from(output.mode.size().1));

    let (mut ui, text) = ui::UiPlane::new(&alloc, &card, &output, w, h, 2)?;

    let (tx, rx) = mpsc::channel::<input::Key>();
    let sources = input::spawn(tx, display.owns_vt());
    let have_input = sources.available();
    println!("input source: {}", if have_input { "device" } else { "none (auto-demo)" });

    let mut menu = shell::Menu::new("medias", &["Movies", "Series", "Music", "YouTube", "Settings"]);
    let mut frame = vk::Frame::default();
    shell::render(&mut frame, &text, &menu, w as f32, h as f32);
    ui.render(&card, &text, 0, &frame)?;
    output.modeset(&card, ui.fb(0)).map_err(e2s)?;
    let mut front = 0usize;

    let start = Instant::now();
    let mut last_auto = Instant::now();
    'ui: loop {
        if console::stopping() {
            break;
        }
        for key in rx.try_iter() {
            match menu.handle_with_page(key, shell::list_capacity(w as f32, h as f32)) {
                shell::Action::Open(i) => println!("open: {}", menu.items[i]),
                shell::Action::Exit => break 'ui,
                shell::Action::None => {}
            }
        }
        if !have_input && last_auto.elapsed() > Duration::from_millis(1200) {
            menu.handle(input::Key::Down);
            last_auto = Instant::now();
        }
        shell::render(&mut frame, &text, &menu, w as f32, h as f32);
        let back = front ^ 1;
        ui.render(&card, &text, back, &frame)?;
        if console::stopping() {
            break;
        }
        output.present(&card, ui.fb(back)).map_err(e2s)?;
        front = back;
        if !have_input && start.elapsed().as_secs() > 10 {
            break;
        }
    }

    drop(sources);
    display.restore();
    ui.destroy(text, &card);
    Ok(())
}

/// Milestone 6: read navigation keys from CEC and/or evdev. Reads from the
/// first available source (CEC preferred — it's the TV remote) and prints keys.
fn run_input(evdev_path: Option<&str>) {
    println!("=== input ===");

    match input::Cec::open("/dev/cec0") {
        Ok(mut cec) => {
            println!("CEC /dev/cec0 open; press remote keys (Ctrl-C to stop)");
            loop {
                match cec.next() {
                    Ok(Some(k)) => println!("CEC {k:?}"),
                    Ok(None) => {}
                    Err(e) => {
                        eprintln!("CEC: {e}");
                        break;
                    }
                }
            }
            return;
        }
        Err(e) => println!("CEC /dev/cec0: {e}"),
    }

    let path = evdev_path.unwrap_or("/dev/input/event0");
    match input::Evdev::open(path) {
        Ok(mut dev) => {
            println!("evdev {path} open; press keys (Ctrl-C to stop)");
            loop {
                match dev.next() {
                    Ok(Some(k)) => println!("key {k:?}"),
                    Ok(None) => {}
                    Err(e) => {
                        eprintln!("evdev: {e}");
                        break;
                    }
                }
            }
        }
        Err(e) => {
            println!("evdev {path}: {e}");
            println!("no input source available (expected off-target; CEC/evdev live on the Pi)");
        }
    }
}

/// Synthetic lavfi source: no asset file needed.
fn default_test_media() -> String {
    "av://lavfi:testsrc=size=640x480:rate=30:duration=3".into()
}

/// mpv's OpenGL render API writes a dmabuf-backed FBO scanned out on one plane.
fn run_video(dev: Option<&str>, url: &str) -> Result<(), String> {
    println!("=== video ({url}) ===");
    let (card, output, mut display) = open_display(dev)?;
    let alloc = Allocator::new(&card).map_err(|e| format!("gbm: {e}"))?;
    let (w, h) = output.mode.size();

    let video = egl::VideoGl::new(&alloc)?;
    let mut buffers = Vec::new();
    let mut fbos = Vec::new();
    for _ in 0..2 {
        let buffer = alloc.alloc(&card, w.into(), h.into(), DrmFourcc::Xrgb8888, Use::SCANOUT | Use::RENDERING)
            .map_err(|e| format!("alloc: {e}"))?;
        fbos.push(video.import(&buffer)?);
        buffers.push(buffer);
    }
    println!("mpv -> double-buffered GL -> KMS plane, {w}x{h}");

    let m = mpv::Mpv::new()?;
    m.set_option("vo", "libmpv")?; // required for the render API
    m.set_option("ao", "null")?;
    m.set_option("hwdec", "no")?;
    m.set_option("msg-level", "all=error")?;
    m.init()?;
    let rc = gl_render_context(&m)?;
    m.loadfile(url)?;

    let start = Instant::now();
    let mut frames = 0u32;
    let mut front = 0usize;
    let mut modeset = false;
    'play: loop {
        if console::stopping() {
            break;
        }
        loop {
            match m.wait_event(0.0) {
                mpv::Event::None => break,
                mpv::Event::EndFile(_) | mpv::Event::PlaybackError | mpv::Event::Shutdown => break 'play,
                mpv::Event::FileLoaded => println!("playing: {:.1}s", m.get_f64("duration").unwrap_or(0.0)),
                _ => {}
            }
        }
        if rc.frame_ready() {
            let back = front ^ 1;
            video.mpv_render(|| rc.render(video.fbo_id(&fbos[back]), w.into(), h.into()))?;
            video.finish();
            front = back;
            frames += 1;
        }
        if console::stopping() {
            break;
        }
        if modeset {
            output.present(&card, buffers[front].fb).map_err(|e| format!("present: {e}"))?;
        } else if frames > 0 {
            output.modeset(&card, buffers[front].fb).map_err(|e| format!("modeset: {e}"))?;
            modeset = true;
        } else {
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        if start.elapsed().as_secs() > 20 {
            break;
        }
    }
    let secs = start.elapsed().as_secs_f64();
    println!("rendered {frames} frames in {secs:.1}s ({:.1} fps)", frames as f64 / secs);

    display.restore();
    drop(rc);
    drop(m);
    for buffer in buffers {
        card.destroy_framebuffer(buffer.fb).map_err(|e| format!("destroy fb: {e}"))?;
    }
    Ok(())
}

/// mpv video and the Vulkan UI occupy separate planes in one atomic commit.
fn run_compositor(dev: Option<&str>, url: &str) -> Result<(), String> {
    println!("=== compositor ({url}) ===");
    let (card, output, mut display) = open_display(dev)?;
    if output.video_plane.is_none() {
        return Err("CRTC exposes only one plane; need two for compositing".into());
    }
    let alloc = Allocator::new(&card).map_err(|e| format!("gbm: {e}"))?;
    let (w, h) = (u32::from(output.mode.size().0), u32::from(output.mode.size().1));

    let video = egl::VideoGl::new(&alloc)?;
    let gpu = vk::Gpu::new()?;
    let renderer = gpu.create_renderer()?;
    let mut video_buffers = Vec::new();
    let mut video_fbos = Vec::new();
    let mut ui_buffers = Vec::new();
    let mut ui_targets = Vec::new();
    let mut ui_fbs = Vec::new();
    for _ in 0..2 {
        let buffer = alloc.alloc(&card, w, h, DrmFourcc::Xrgb8888, Use::SCANOUT | Use::RENDERING)
            .map_err(|e| format!("video alloc: {e}"))?;
        video_fbos.push(video.import(&buffer)?);
        video_buffers.push(buffer);
        let (buffer, target) = gpu.create_scanout_target(&alloc, &card, &output, w, h, DrmFourcc::Argb8888)?;
        ui_fbs.push(gpu.framebuffer(&renderer, &target)?);
        ui_targets.push(target);
        ui_buffers.push(buffer);
    }
    println!("double-buffered video and UI planes; {w}x{h}");

    let m = mpv::Mpv::new()?;
    m.set_option("vo", "libmpv")?;
    m.set_option("ao", "null")?;
    m.set_option("hwdec", "no")?;
    m.set_option("loop", "inf")?; // keep video running while we show the UI
    m.set_option("msg-level", "all=error")?;
    m.init()?;
    let rc = gl_render_context(&m)?;
    m.loadfile(url)?;

    let start = Instant::now();
    let mut frames = 0u32;
    let mut video_front = 0usize;
    let mut ui_front = 0usize;
    let mut video_ready = false;
    let mut modeset = false;
    'play: loop {
        if console::stopping() {
            break;
        }
        loop {
            match m.wait_event(0.0) {
                mpv::Event::None => break,
                mpv::Event::Shutdown => break 'play,
                _ => {}
            }
        }
        if rc.frame_ready() {
            let back = video_front ^ 1;
            video.mpv_render(|| rc.render(video.fbo_id(&video_fbos[back]), w as i32, h as i32))?;
            video.finish();
            video_front = back;
            video_ready = true;
        }
        if !video_ready {
            if start.elapsed().as_secs() > 10 {
                return Err("no video frame decoded".into());
            }
            std::thread::sleep(std::time::Duration::from_millis(1));
            continue;
        }
        let t = (start.elapsed().as_secs_f32() * 1.5).sin() * 0.5 + 0.5;
        let back = ui_front ^ 1;
        gpu.draw(&renderer, &ui_targets[back], ui_fbs[back], t)?;
        if console::stopping() {
            break;
        }
        let video_fb = video_buffers[video_front].fb;
        let ui_fb = ui_buffers[back].fb;
        if modeset {
            output.present_two(&card, video_fb, (w as u16, h as u16), ui_fb).map_err(e2s)?;
        } else {
            output.modeset_two(&card, video_fb, (w as u16, h as u16), ui_fb).map_err(e2s)?;
            modeset = true;
        }
        ui_front = back;
        frames += 1;
        if start.elapsed().as_secs() > 10 {
            break;
        }
    }
    let secs = start.elapsed().as_secs_f64();
    println!("composited {frames} frames in {secs:.1}s ({:.1} fps)", frames as f64 / secs);

    display.restore();
    drop(rc);
    drop(m);
    for fb in ui_fbs {
        gpu.destroy_framebuffer(fb);
    }
    gpu.destroy_renderer(renderer);
    for target in ui_targets {
        gpu.destroy_target(target);
    }
    for buffer in video_buffers.into_iter().chain(ui_buffers) {
        card.destroy_framebuffer(buffer.fb).map_err(e2s)?;
    }
    Ok(())
}

fn finish_playback(m: &mpv::Mpv, history: &mut history::History, path: &str, mut loaded: bool, pending_resume: bool) {
    // File properties can disappear before the corresponding END_FILE is queued.
    let drain_timeout = if loaded && m.get_f64("time-pos").is_none() { 0.1 } else { 0.0 };
    loop {
        match m.wait_event(drain_timeout) {
            mpv::Event::None => break,
            mpv::Event::EndFile(true) if loaded => {
                history.set_pos(path, 0.0);
                loaded = false;
            }
            mpv::Event::PlaybackError => loaded = false,
            _ => {}
        }
    }
    checkpoint_playback(m, history, path, loaded && !pending_resume);
}

fn checkpoint_playback(m: &mpv::Mpv, history: &mut history::History, path: &str, loaded: bool) {
    // time-pos disappears after stop/end-file; pending loads retain the cached position.
    if loaded && m.get_string("seeking").as_deref() != Some("yes")
        && let Some(position) = m.get_f64("time-pos") {
        history.set_pos(path, position);
    }
    history.save();
}

/// mpv OpenGL render context. Below mpv 0.42 (or an unparsed version),
/// glFenceSync is wrapped to delete mpv's per-frame leak: see `egl::wrap_fence_sync`.
fn gl_render_context(m: &mpv::Mpv) -> Result<mpv::RenderContext<'_>, String> {
    let version = m.get_string("mpv-version").unwrap_or_default();
    let leaks = mpv_version(&version).is_none_or(|v| v < (0, 42));
    if leaks {
        println!("{version}: deleting mpv's per-frame GL fence (leak, mpv #17217)");
    }
    egl::wrap_fence_sync(leaks);
    m.render_context(egl::mpv_get_proc_address)
}

/// (major, minor) of mpv's `mpv-version`, e.g. "mpv 0.40.0" or "mpv v0.42.0-12-gabc".
fn mpv_version(s: &str) -> Option<(u32, u32)> {
    let v = s.strip_prefix("mpv ")?.trim_start_matches('v');
    let mut parts = v.split(|c: char| !c.is_ascii_digit());
    Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
}

fn e2s(e: std::io::Error) -> String {
    e.to_string()
}

/// Milestone 2c: allocate a GPU-renderable scanout buffer, import it into
/// Vulkan, clear it on the GPU each frame, and scan it out.
fn run_gpu(
    card: &Card,
    output: &Output,
    alloc: &Allocator,
    gpu: &vk::Gpu,
    w: u32,
    h: u32,
) -> std::io::Result<()> {
    let (s, target) = gpu.create_scanout_target(alloc, card, output, w, h, DrmFourcc::Xrgb8888)
        .map_err(std::io::Error::other)?;
    println!("scanout bo: modifier={:#x} stride={} offset={}", s.modifier(), s.stride(), s.offset());

    let renderer = gpu.create_renderer().map_err(std::io::Error::other)?;
    let fb = gpu.framebuffer(&renderer, &target).map_err(std::io::Error::other)?;
    println!("imported dmabuf; pipeline + framebuffer ready");

    output.modeset(card, s.fb)?;

    let n = 300;
    let start = Instant::now();
    for i in 0..n {
        if console::stopping() {
            break;
        }
        let t = (i as f32 / n as f32 * std::f32::consts::TAU).sin() * 0.5 + 0.5;
        gpu.draw(&renderer, &target, fb, t).map_err(std::io::Error::other)?;
        output.present(card, s.fb)?;
    }
    report("draw+flip", start, n);

    gpu.destroy_framebuffer(fb);
    gpu.destroy_renderer(renderer);
    gpu.destroy_target(target);
    card.destroy_framebuffer(s.fb)?;
    Ok(())
}

fn run_cpu(card: &Card, output: &Output, alloc: &Allocator, w: u32, h: u32) -> std::io::Result<()> {
    // CPU-filled linear scanout buffers (milestone 2a). The Vulkan render path
    // (2c) will use SCANOUT|RENDERING instead. NVIDIA rejects RENDERING|WRITE
    // together; keep CPU and GPU buffers separate.
    let flags = Use::SCANOUT | Use::WRITE | Use::LINEAR;
    let mut front = alloc.alloc(card, w, h, DrmFourcc::Xrgb8888, flags)?;
    let mut back = alloc.alloc(card, w, h, DrmFourcc::Xrgb8888, flags)?;
    println!("allocated 2x {w}x{h} XRGB8888 scanout buffers");

    fill_gradient(&mut front, 0)?;
    fill_gradient(&mut back, 128)?;

    output.modeset(card, front.fb)?;
    println!("modeset ok\n");

    bench_flips(card, output, &front, &back, 300)?;
    bench_fill_flip(card, output, &mut back, 120)?;

    card.destroy_framebuffer(front.fb)?;
    card.destroy_framebuffer(back.fb)?;
    Ok(())
}

/// Flip between two pre-filled buffers; measures sustained vsync-locked flips.
fn bench_flips(card: &Card, o: &Output, a: &Scanout, b: &Scanout, n: u32) -> std::io::Result<()> {
    let start = Instant::now();
    for i in 0..n {
        if console::stopping() {
            break;
        }
        let fb = if i % 2 == 0 { a.fb } else { b.fb };
        o.present(card, fb)?;
    }
    report("flip only", start, n);
    Ok(())
}

/// Refill then flip each frame; measures CPU fill + commit cost per frame.
fn bench_fill_flip(card: &Card, o: &Output, buf: &mut Scanout, n: u32) -> std::io::Result<()> {
    let start = Instant::now();
    for i in 0..n {
        if console::stopping() {
            break;
        }
        fill_gradient(buf, (i * 4) as u8)?;
        o.present(card, buf.fb)?;
    }
    report("fill+flip", start, n);
    Ok(())
}

fn report(label: &str, start: Instant, n: u32) {
    let secs = start.elapsed().as_secs_f64();
    println!(
        "{label:10} {n} frames in {secs:.3}s  =>  {:.1} fps  ({:.2} ms/frame)",
        n as f64 / secs,
        secs * 1000.0 / n as f64,
    );
}

/// XRGB8888 gradient, `phase` shifts the blue channel for visible animation.
fn fill_gradient(s: &mut Scanout, phase: u8) -> std::io::Result<()> {
    let (w, h) = (s.width as usize, s.height as usize);
    s.fill(|buf, stride| {
        for y in 0..h {
            let row = &mut buf[y * stride..y * stride + w * 4];
            for x in 0..w {
                let p = x * 4;
                row[p] = (x * 255 / w) as u8 ^ phase; // B
                row[p + 1] = (y * 255 / h) as u8; // G
                row[p + 2] = 64; // R
                row[p + 3] = 0; // X
            }
        }
    })
}

fn print_help() {
    print!(
        "\
medias - media player for Raspberry Pi (DRM/KMS + Vulkan + libmpv, no X11)

USAGE:
    medias [OPTIONS] [DEVICE]
                           run the player (default; DEVICE e.g. /dev/dri/card1
                           overrides the auto-detected KMS display node)
    medias <SUBCOMMAND>

OPTIONS (repeatable; each adds a top-menu entry; default: Videos + Music):
    --videos[=[LABEL=]PATH]   a video library root
    --music[=[LABEL=]PATH]    a music library root
       bare            -> Videos / Music under ~/medias
       =PATH           -> entry labeled from PATH's name (relative to ~/medias)
       =LABEL=PATH     -> entry labeled LABEL
    e.g. --videos=Movies=/mnt/movies --videos=Series=series --music=/mnt/music

SUBCOMMANDS:
    (none)                  the media player app: browse + play
    bench [DEVICE]          graphics bring-up benchmarks (KMS/Vulkan present)
    comp [FILE|URL] [DEVICE]  two-plane compositor demo (video + UI overlay)
    video [FILE|URL] [DEVICE] play one file/URL full screen (mpv -> KMS)
    mpv [FILE|URL]           headless libmpv decode/control test (no display)
    metadata FILE|URL...    print container, codecs, resolution, fps, bit
                            depth, colorimetry, audio channels, bitrates
    shell [DEVICE]          UI shell / menu demo (no video)
    input [EVDEV]           print input events from CEC or evdev
    --help, -h, help        this message

CONTENT (under $HOME/medias):
    Videos/                scanned into the Videos menu
    Music/                 scanned into the Music menu
    upnp.txt               UPnP/DLNA servers outside multicast reach: one
                           description URL per line (e.g.
                           http://10.0.0.5:8200/rootDesc.xml); \"Media
                           servers\" also finds servers via SSDP (1.5 s)
    youtube.txt            YouTube sources, one per line: \"Label | query\"
                           query = ytsearchN:terms, or a channel/playlist URL
    youtube_oauth.json     YouTube sign-in: {{\"client_id\",\"client_secret\",
                           \"api_key\"?}}. The OAuth client must be of type
                           \"TVs and Limited Input devices\". Without it, search
                           still works anonymously via yt-dlp. Credentials may
                           also come from MEDIAS_YT_CLIENT_ID / _CLIENT_SECRET /
                           _API_KEY. The session is stored in .youtube_auth.
    .youtube_tv_auth       \"For you\" session: a second QR sign-in with
                           YouTube's TV client (as the Kodi plugin does), no
                           configuration needed. Only in builds with
                           --features youtube-tv.
    .view                  thumbnail view: \"list\" or \"grid\"
    .cache/thumbs/         thumbnails (YouTube: 30-day reuse; local files:
                           until the file changes)

REMOTE / KEYS:
    menu:  Up/Down move, OK/Enter select, Back up a level
           (at root: back to video, or exit if none is loaded)
           Lists scroll automatically. Left/Right, Channel +/-, or PgUp/PgDn
           move by a page; Home/End select the first/last entry.
    search: Type to filter the current directory, or press / or Ctrl-F.
            Up from the first result focuses search; OK opens the keyboard.
            Down from search returns to results.
           Matching ignores case. Backspace deletes; Enter opens the selection.
           Blue/Menu opens an on-screen keyboard: arrows move, OK types,
           Done returns to results. Back closes the keyboard, leaves the
           search bar, then clears the filter before leaving the directory.
           Search is not recursive.
    thumbnails: library folders and YouTube lists show thumbnails (video frame
           at 15%, embedded or folder cover art, cover/folder/poster image or
           first file for folders). Yellow/Info/F4 toggles a small-thumbnail
           list and a wide grid (4 x 2 at 16:9; arrows move by card, Up from
           the top row focuses search).
    loading: folders, YouTube lists and stream lookups load in the background
           behind a spinner; Back abandons the load. Failures show briefly.
    play:  Left/Right seek +/-10s, Rewind/Fast-Forward +/-60s, Up/Down volume,
           Play toggles pause, Audio/Subtitle quick-cycle tracks, Stop stops.
           OK or Pause open the playback menu; Back opens the file list.
           The now-playing bar hides after 10s. Yellow/Info cycles: bar shown,
           hidden, screen black (audio keeps playing; volume keys keep it
           black, other keys light it), bar shown.
           Next/Previous track (CEC Forward/Backward, terminal > and <) play
           the next/previous file of the folder; Previous after 5s restarts.
           At the end of a local or UPnP file the next one in its folder (in
           the filtered order) plays, unless turned off.
    menu (playback):  Up/Down navigate, OK select, Back up a level / resume.
           Entries: Resume, Seek, Audio and Subtitles (choose track), Play
           next in folder (on/off, kept in ~/medias/.autoplay), Browse
           library, Stop. The Seek row is horizontal (Left/Right); relative
           jumps repeat without closing and keep the time on screen.
    colored/extra buttons: Red=subtitles, Green=audio, Blue=menu, Yellow=info,
           Channel Up/Down = seek +/-60s.
    Playback resumes from the saved per-file position in ~/medias/.history.
    Ctrl-C / Ctrl-Z save the current playback position before cleanup.
    Sources: terminal keyboard text/navigation, HDMI-CEC, and evdev keys.
    Unmapped remote/media key codes are printed to stderr.

ENVIRONMENT:
    MEDIAS_HWDEC=auto|no|...   mpv hardware decode (default auto; `no` = software)
    MEDIAS_UI=cpu              draw the UI with the CPU rasterizer instead of Vulkan
                               (automatic when no Vulkan device imports dmabufs)
    MEDIAS_AO=<list>           mpv audio output list (default pipewire,alsa,null;
                               e.g. alsa)
    MEDIAS_AUDIO_DEVICE=<dev>  mpv audio device (`aplay -L` for names,
                               e.g. alsa/sysdefault:CARD=vc4hdmi0)
    MEDIAS_STATS=1             print per-second playback stats
    MEDIAS_MATCH_RATE=0        keep the display refresh rate; default: switch
                               to a same-size mode at a multiple of the video
                               frame rate during playback (23.976 fps -> 23.976
                               Hz, 25 -> 50, 29.97 -> 59.94)
    MEDIAS_MATCH_RATE_DELAY=<s>
                               pause after a refresh switch while the TV
                               resyncs (default 3; 0: no pause)
    MEDIAS_YT_MAX_HEIGHT=<px>  YouTube stream height cap (default 1080)
    MEDIAS_YT_CODECS=<list>    allowed YouTube video codecs, preferred first
                               (default av01,vp9,avc1; Pi: avc1)
    MEDIAS_YT_AUDIO_LANGS=<l>  languages whose YouTube dubs are offered beside
                               the original audio, e.g. de,en (default: from
                               LANGUAGE/LC_ALL/LC_MESSAGES/LANG)
    MEDIAS_YT_SUB_LANGS=<l>    caption languages offered beside the spoken
                               language's (default: MEDIAS_YT_AUDIO_LANGS);
                               off until chosen
    MEDIAS_YTDL_PATH=<path>    yt-dlp for the playback fallback and anonymous
                               search/sources (default: found in /usr/bin etc.)
    MEDIAS_MPV_LOG=<path>      write mpv's verbose log (playback diagnosis)
    MEDIAS_GL_SYNC=flush       glFlush instead of glFinish after each video frame
                               (relies on kernel implicit sync; diagnosis)
    MEDIAS_MPV_CONF=<path>     mpv options, one key=value per line, applied last
                               (e.g. profile=fast for slow GPUs)
    MEDIAS_YT_DEBUG=1          dump the InnerTube browse responses to
                               ~/medias/innertube-<browseId>[-N].json
    MEDIAS_YT_SYNC=1           report YouTube playback to the YouTube TV account's
                               watch history (youtube-tv builds)

NOTES:
    - All display commands auto-detect the KMS node; DEVICE overrides detection.
    - Run with access to /dev/dri and input devices.
      DRM master requires that no desktop/compositor owns the display.
    - The same command works directly from SSH, Zellij, or a Linux console.
      SSH/Zellij startup does not require sudo or a separate VT launcher.
      On a real console, medias manages graphics mode and VT switching.
    - Ctrl-C, Ctrl-Z, and termination signals exit and restore display state.
      VT switches exit the player when it owns a real console VT.
    - Optional: scripts/medias-vt uses sudo to launch on a separate VT.
    - Video renders at <=1080p and the display scales it (big win at 4K).
    - To use a user PipeWire from root: XDG_RUNTIME_DIR=/run/user/<uid>
"
    );
}

fn fail(msg: &str) -> ! {
    eprintln!("{msg}");
    std::process::exit(1);
}

#[cfg(test)]
mod playback_tests {
    use super::*;
    use std::os::unix::process::CommandExt;
    use std::process::{Command, Stdio};
    use std::time::{SystemTime, UNIX_EPOCH};

    struct Fixture(std::path::PathBuf);

    impl Fixture {
        fn new() -> Self {
            let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
            let dir = std::env::temp_dir().join(format!("medias-resume-{}-{stamp}", std::process::id()));
            std::fs::create_dir(&dir).unwrap();
            let size = 30u32 * 8000 * 2;
            let mut wave = Vec::new();
            wave.extend(b"RIFF"); wave.extend((size + 36).to_le_bytes()); wave.extend(b"WAVEfmt ");
            wave.extend(16u32.to_le_bytes()); wave.extend(1u16.to_le_bytes()); wave.extend(1u16.to_le_bytes());
            wave.extend(8000u32.to_le_bytes()); wave.extend(16000u32.to_le_bytes());
            wave.extend(2u16.to_le_bytes()); wave.extend(16u16.to_le_bytes());
            wave.extend(b"data"); wave.extend(size.to_le_bytes());
            wave.resize(44 + size as usize, 0);
            std::fs::write(dir.join("silence.wav"), wave).unwrap();
            Self(dir)
        }

        fn media(&self) -> String { self.0.join("silence.wav").to_str().unwrap().to_owned() }
        fn history(&self) -> history::History { history::History::load_from(self.0.join(".history")) }
    }

    impl Drop for Fixture {
        fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
    }

    fn headless() -> mpv::Mpv {
        let m = mpv::Mpv::new().unwrap();
        for (name, value) in [("config", "no"), ("load-scripts", "no"), ("terminal", "no"), ("vo", "null"), ("ao", "null"), ("hwdec", "no"), ("idle", "yes"), ("pause", "yes"), ("ytdl", "no")] {
            m.set_option(name, value).unwrap();
        }
        m.init().unwrap();
        m
    }

    /// Network: InnerTube direct streams load in libmpv with scripts and yt-dlp
    /// disabled. `cargo test -- --ignored direct_youtube`.
    #[test]
    #[ignore]
    fn direct_youtube_streams_load_without_ytdlp() {
        // 0e3GPea1Tyg: English original with ~23 dubs.
        let prefs = youtube::innertube::StreamPrefs {
            max_height: 1080,
            codecs: vec!["av01".into(), "vp9".into(), "avc1".into()],
            audio_langs: vec!["de".into()],
            sub_langs: vec!["de".into()],
        };
        let streams = youtube::innertube::streams("0e3GPea1Tyg", &prefs).unwrap();
        let titles: Vec<&str> = streams.audio.iter().map(|a| a.title.as_str()).collect();
        assert_eq!(titles, ["English (US) (original)", "German (dubbed)"]);
        let titles: Vec<&str> = streams.subs.iter().map(|s| s.title.as_str()).collect();
        assert_eq!(titles, ["German", "English"]);
        let m = headless();
        let audio: Vec<String> = streams.audio.iter().map(|a| mpv::edl_track(&a.url, &a.lang, &a.title)).collect();
        let subs: Vec<String> = streams.subs.iter().map(|s| mpv::edl_sub_track(&s.url, &s.lang, &s.title)).collect();
        m.set_audio_files(&audio.iter().map(String::as_str).collect::<Vec<_>>()).unwrap();
        m.set_sub_files(&subs.iter().map(String::as_str).collect::<Vec<_>>()).unwrap();
        m.loadfile_with(&streams.video, "sid=no").unwrap();
        let deadline = Instant::now() + Duration::from_secs(30);
        loop {
            match m.wait_event(0.5) {
                mpv::Event::FileLoaded => break,
                mpv::Event::PlaybackError => panic!("direct stream failed to load"),
                _ => assert!(Instant::now() < deadline, "timed out waiting for FileLoaded"),
            }
        }
        assert_eq!(m.get_string("track-list/count").as_deref(), Some("5"));
        assert_eq!(m.get_string("current-tracks/audio/title").as_deref(), Some("English (US) (original)"));
        assert_eq!(m.get_string("track-list/2/lang").as_deref(), Some("de"));
        assert_eq!(m.get_string("sid").as_deref(), Some("no"));
        assert_eq!(m.get_string("track-list/3/title").as_deref(), Some("German"));
        // The caption file is fetched on selection; cues start at 0.13 s.
        m.set_property("sid", "1").unwrap();
        m.set_property("pause", "no").unwrap();
        while m.get_string("sub-text").is_none_or(|t| t.trim().is_empty()) {
            m.wait_event(0.1);
            assert!(Instant::now() < deadline, "no caption text");
        }
    }

    fn load(m: &mpv::Mpv, path: &str) {
        m.loadfile(path).unwrap();
        let start = Instant::now();
        while m.wait_event(0.01) != mpv::Event::FileLoaded {
            assert!(start.elapsed() < Duration::from_secs(5));
        }
    }

    fn seek(m: &mpv::Mpv, position: f64) {
        m.command(&["seek", &position.to_string(), "absolute+exact"]).unwrap();
        let start = Instant::now();
        loop {
            if m.get_f64("time-pos").is_some_and(|t| (t - position).abs() < 0.2)
                && m.get_string("seeking").as_deref() != Some("yes") { return; }
            m.wait_event(0.01);
            assert!(start.elapsed() < Duration::from_secs(5));
        }
    }

    #[test]
    fn shutdown_signals_persist_latest_position_before_mpv_destruction() {
        const CHILD: &str = "MEDIAS_RESUME_SIGNAL";
        let Some(number) = std::env::var_os(CHILD) else {
            for signal in [libc::SIGINT, libc::SIGTSTP] {
                let mut command = Command::new(std::env::current_exe().unwrap());
                command.args(["--exact", "playback_tests::shutdown_signals_persist_latest_position_before_mpv_destruction"])
                    .env(CHILD, signal.to_string()).env_remove("SUDO_TTY").stdin(Stdio::null());
                unsafe {
                    command.pre_exec(|| {
                        if libc::setsid() < 0 { return Err(std::io::Error::last_os_error()); }
                        Ok(())
                    });
                }
                assert!(command.status().unwrap().success());
            }
            return;
        };
        let signal: i32 = number.to_str().unwrap().parse().unwrap();
        let console = console::Console::acquire().unwrap();
        assert!(!console.owns_vt());
        let fixture = Fixture::new();
        let path = fixture.media();
        let m = headless();
        load(&m, &path);
        seek(&m, 12.75);
        let mut history = fixture.history();
        history.set_pos(&path, 8.0);
        history.save();
        assert_eq!(unsafe { libc::raise(signal) }, 0);
        assert!(console::stopping());
        finish_playback(&m, &mut history, &path, true, false);
        drop(m);
        let resume = fixture.history().pos(&path).unwrap();
        assert_eq!(resume, 12.0);
        drop(console);
        let m = headless();
        load(&m, &path);
        seek(&m, resume);
        assert!(m.get_f64("time-pos").unwrap() >= 11.8);
    }

    #[test]
    fn paused_resume_seek_reports_completion_before_later_backward_seek() {
        let fixture = Fixture::new();
        let path = fixture.media();
        let m = headless();
        load(&m, &path);
        let start = Instant::now();
        while m.wait_event(0.01) != mpv::Event::PlaybackRestart {
            assert!(start.elapsed() < Duration::from_secs(5));
        }
        m.command(&["seek", "21.5", "absolute+exact"]).unwrap();
        let mut seek_seen = false;
        let start = Instant::now();
        loop {
            match m.wait_event(0.01) {
                mpv::Event::Seek => seek_seen = true,
                mpv::Event::PlaybackRestart => { assert!(seek_seen); break; }
                _ => {}
            }
            assert!(start.elapsed() < Duration::from_secs(5));
        }
        let mut history = fixture.history();
        finish_playback(&m, &mut history, &path, true, false);
        assert_eq!(fixture.history().pos(&path), Some(21.0));
        seek(&m, 9.25);
        finish_playback(&m, &mut history, &path, true, false);
        assert_eq!(fixture.history().pos(&path), Some(9.0));
    }

    #[test]
    fn pending_load_or_resume_retains_cached_position() {
        let fixture = Fixture::new();
        let m = headless();
        load(&m, &fixture.media());
        seek(&m, 12.75);
        let mut history = fixture.history();
        history.set_pos("next-file", 24.0);
        finish_playback(&m, &mut history, "next-file", false, false);
        assert_eq!(fixture.history().pos("next-file"), Some(24.0));
        history.set_pos(&fixture.media(), 21.0);
        finish_playback(&m, &mut history, &fixture.media(), true, true);
        assert_eq!(fixture.history().pos(&fixture.media()), Some(21.0));
    }

    #[test]
    fn stop_preserves_latest_position_and_playback_error_is_not_eof() {
        let fixture = Fixture::new();
        let path = fixture.media();
        let m = headless();
        load(&m, &path);
        seek(&m, 16.5);
        let mut history = fixture.history();
        checkpoint_playback(&m, &mut history, &path, true);
        m.command(&["stop"]).unwrap();
        assert_eq!(fixture.history().pos(&path), Some(16.0));
        m.loadfile(fixture.0.join("missing.wav").to_str().unwrap()).unwrap();
        let start = Instant::now();
        loop {
            let event = m.wait_event(0.01);
            assert_ne!(event, mpv::Event::EndFile(true));
            if event == mpv::Event::PlaybackError { break; }
            assert!(start.elapsed() < Duration::from_secs(5));
        }
        finish_playback(&m, &mut history, &path, false, false);
        assert_eq!(fixture.history().pos(&path), Some(16.0));
    }

    #[test]
    fn pending_natural_eof_clears_resume_on_shutdown() {
        let fixture = Fixture::new();
        let path = fixture.media();
        let m = headless();
        load(&m, &path);
        seek(&m, 29.9);
        let mut history = fixture.history();
        history.set_pos(&path, 29.0);
        m.set_property("pause", "no").unwrap();
        let start = Instant::now();
        while m.get_f64("time-pos").is_some() {
            assert!(start.elapsed() < Duration::from_secs(5));
            std::thread::sleep(Duration::from_millis(5));
        }
        finish_playback(&m, &mut history, &path, true, false);
        assert_eq!(fixture.history().pos(&path), None);
    }
}

#[cfg(test)]
mod render_tests {
    use super::*;

    /// Live + GPU: renders the thumbnail list and grid for related videos of a real
    /// video offscreen; writes BGRA dumps to MEDIAS_SNAPSHOT_DIR (default /tmp).
    #[test]
    #[ignore]
    fn thumbnail_layouts_render_offscreen() {
        let (w, h) = (1920u32, 1080u32);
        let gpu = vk::Gpu::new().unwrap();
        let text = gpu.create_text().unwrap();
        let target = gpu.offscreen_target(w, h).unwrap();
        let fb = text.framebuffer(&gpu, &target).unwrap();
        let videos = youtube::innertube::related("V_uq3v6xK-4").unwrap();
        assert!(videos.len() >= 8, "{} related videos", videos.len());
        let items = yt_video_items(videos);
        let mut cache = thumbs::Thumbs::new();
        let start = Instant::now();
        loop {
            cache.begin_frame();
            let ready = items.iter().take(8).filter(|it| cache.get(&it.thumb).is_some()).count();
            if ready == 8 || start.elapsed() > Duration::from_secs(20) {
                break;
            }
            cache.pump(|slot, w, h, rgba| text.upload_thumb(&gpu, slot, w, h, rgba));
            std::thread::sleep(Duration::from_millis(50));
        }
        let dir = std::env::var("MEDIAS_SNAPSHOT_DIR").unwrap_or_else(|_| "/tmp".into());
        let mut frame = vk::Frame::default();
        for (name, layout) in [("list", shell::Layout::List), ("grid", shell::Layout::Grid)] {
            cache.begin_frame();
            let cards: Vec<shell::Card> = items
                .iter()
                .map(|it| shell::Card { title: it.name.clone(), sub: it.sub.clone(), meta: it.meta.clone(), thumb: cache.get(&it.thumb), icon: card_icon(it), progress: None })
                .collect();
            assert!(cards.iter().take(8).all(|c| c.thumb.is_some()), "thumbnails not loaded");
            let view = shell::BrowseView {
                title: "Like your watched", layout, rows: &[], progress: &[], cards: &cards, first: 0, selected: 1,
                matches: cards.len(), total: cards.len(), query: "", searching: false,
                search_focused: false, keyboard: None,
            };
            shell::render_browse(&mut frame, &text, &view, w as f32, h as f32);
            text.render(&gpu, &target, fb, &frame).unwrap();
            let pixels = gpu.read_target(&target).unwrap();
            std::fs::write(format!("{dir}/medias-{name}-{w}x{h}.bgra"), &pixels).unwrap();
        }
        gpu.destroy_framebuffer(fb);
        text.destroy(&gpu);
        gpu.destroy_target(target);
    }

    /// GPU: a grid of thumbnail cards rendered by Vulkan and by the CPU
    /// rasterizer; compares BGRA output and prints the CPU frame time.
    #[test]
    #[ignore]
    fn cpu_raster_matches_vulkan() {
        let (w, h) = (1920u32, 1080u32);
        let gpu = vk::Gpu::new().unwrap();
        let text = gpu.create_text().unwrap();
        let target = gpu.offscreen_target(w, h).unwrap();
        let fb = text.framebuffer(&gpu, &target).unwrap();
        let mut canvas = ui::raster::Canvas::new(w, h);
        let rgba: Vec<u8> = (0..vk::THUMB_W * vk::THUMB_H)
            .flat_map(|i| [(i % 251) as u8, (i / 480 % 256) as u8, 90, 255])
            .collect();
        let thumb = text.upload_thumb(&gpu, 5, vk::THUMB_W, vk::THUMB_H, &rgba).unwrap();
        assert_eq!(canvas.upload_thumb(5, vk::THUMB_W, vk::THUMB_H, &rgba).unwrap(), thumb);
        let cards: Vec<shell::Card> = (0..10)
            .map(|i| shell::Card {
                title: format!("Video number {i} with a fairly long title that wraps over lines"),
                sub: "Channel · 3 days ago · 12K views".into(),
                meta: "12:34".into(),
                thumb: (i % 3 != 2).then_some(thumb),
                icon: shell::Icon::None,
                progress: (i % 4 == 1).then_some(0.4),
            })
            .collect();
        let view = shell::BrowseView {
            title: "For you", layout: shell::Layout::Grid, rows: &[], progress: &[], cards: &cards, first: 0, selected: 3,
            matches: cards.len(), total: cards.len(), query: "", searching: false, search_focused: false, keyboard: None,
        };
        let mut frame = vk::Frame::default();
        shell::render_browse(&mut frame, &text, &view, w as f32, h as f32);
        text.render(&gpu, &target, fb, &frame).unwrap();
        let want = gpu.read_target(&target).unwrap();
        let start = Instant::now();
        let runs = 20;
        let mut got = vec![0u8; (w * h * 4) as usize];
        for _ in 0..runs {
            canvas.render(&text, &frame);
            canvas.write(&mut got, (w * 4) as usize);
        }
        println!("cpu raster: {:.1} ms/frame at {w}x{h}", start.elapsed().as_secs_f64() * 1e3 / runs as f64);
        let diff: Vec<u32> = want.iter().zip(&got).map(|(a, b)| a.abs_diff(*b) as u32).collect();
        let mean = diff.iter().sum::<u32>() as f64 / diff.len() as f64;
        let over = diff.iter().filter(|&&d| d > 8).count() as f64 / diff.len() as f64;
        println!("mean |diff| {mean:.4}, share > 8: {:.5}", over);
        let dir = std::env::var("MEDIAS_SNAPSHOT_DIR").unwrap_or_else(|_| "/tmp".into());
        std::fs::write(format!("{dir}/medias-raster-vk-{w}x{h}.bgra"), &want).unwrap();
        std::fs::write(format!("{dir}/medias-raster-cpu-{w}x{h}.bgra"), &got).unwrap();
        assert!(mean < 0.5 && over < 0.002, "mean {mean}, share {over}");
        gpu.destroy_framebuffer(fb);
        text.destroy(&gpu);
        gpu.destroy_target(target);
    }

    /// GPU: the loading panel over a text level at three spinner steps.
    #[test]
    #[ignore]
    fn loading_spinner_renders_offscreen() {
        let (w, h) = (1920u32, 1080u32);
        let gpu = vk::Gpu::new().unwrap();
        let text = gpu.create_text().unwrap();
        let target = gpu.offscreen_target(w, h).unwrap();
        let fb = text.framebuffer(&gpu, &target).unwrap();
        let rows: Vec<shell::Row> = ["For you", "Search", "Trending"].iter().map(|s| (s.to_string(), String::new())).collect();
        let dir = std::env::var("MEDIAS_SNAPSHOT_DIR").unwrap_or_else(|_| "/tmp".into());
        let mut frame = vk::Frame::default();
        for step in [0, 4, 8] {
            let view = shell::BrowseView {
                title: "YouTube", layout: shell::Layout::Text, rows: &rows, progress: &[], cards: &[], first: 0, selected: 0,
                matches: rows.len(), total: rows.len(), query: "", searching: false, search_focused: false, keyboard: None,
            };
            shell::render_browse(&mut frame, &text, &view, w as f32, h as f32);
            shell::render_status(&mut frame, &text, "Loading For you…", Some(step), w as f32, h as f32);
            text.render(&gpu, &target, fb, &frame).unwrap();
            std::fs::write(format!("{dir}/medias-spinner{step}-{w}x{h}.bgra"), gpu.read_target(&target).unwrap()).unwrap();
        }
        gpu.destroy_framebuffer(fb);
        text.destroy(&gpu);
        gpu.destroy_target(target);
    }

    /// GPU + ffmpeg fixtures: a local directory (video, album folder with
    /// embedded art, track without art) in both views; dumps as above.
    #[test]
    #[ignore]
    fn local_thumbnails_render_offscreen() {
        let root = std::env::temp_dir().join(format!("medias-local-{}", std::process::id()));
        let album = root.join("Some Album");
        std::fs::create_dir_all(&album).unwrap();
        let ffmpeg = |args: &[&str]| {
            assert!(std::process::Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).status().unwrap().success())
        };
        let path = |p: &std::path::Path| p.to_str().unwrap().to_string();
        ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=1920x1080:rate=25:duration=20", "-c:v", "libx264", "-preset", "ultrafast", &path(&root.join("A Movie.mkv"))]);
        ffmpeg(&["-f", "lavfi", "-i", "mandelbrot=size=1280x720:rate=25", "-t", "20", "-c:v", "libx264", "-preset", "ultrafast", &path(&root.join("Another Movie.mp4"))]);
        ffmpeg(&["-f", "lavfi", "-i", "sine=duration=5", &path(&root.join("No Art.mp3"))]);
        let art = std::env::temp_dir().join(format!("medias-art-{}.jpg", std::process::id()));
        ffmpeg(&["-f", "lavfi", "-i", "cellauto=s=600x600", "-frames:v", "1", &path(&art)]);
        ffmpeg(&["-i", &path(&root.join("No Art.mp3")), "-i", &path(&art), "-map", "0", "-map", "1", "-c", "copy",
            "-disposition:v", "attached_pic", &path(&album.join("01 Track.mp3"))]);
        std::fs::remove_file(&art).unwrap();
        std::fs::create_dir_all(root.join("Empty Folder")).unwrap();

        let (w, h) = (1920u32, 1080u32);
        let gpu = vk::Gpu::new().unwrap();
        let text = gpu.create_text().unwrap();
        let target = gpu.offscreen_target(w, h).unwrap();
        let fb = text.framebuffer(&gpu, &target).unwrap();
        let items = lib_items(library::list(&root).unwrap());
        assert_eq!(items.len(), 5);
        let mut cache = thumbs::Thumbs::new();
        let start = Instant::now();
        while start.elapsed() < Duration::from_secs(20) {
            cache.begin_frame();
            if items.iter().filter(|it| cache.get(&it.thumb).is_some()).count() == 3 {
                break; // all but "Empty Folder" and "No Art.mp3"
            }
            cache.pump(|slot, w, h, rgba| text.upload_thumb(&gpu, slot, w, h, rgba));
            std::thread::sleep(Duration::from_millis(50));
        }
        let dir = std::env::var("MEDIAS_SNAPSHOT_DIR").unwrap_or_else(|_| "/tmp".into());
        let mut frame = vk::Frame::default();
        for (name, layout) in [("local-list", shell::Layout::List), ("local-grid", shell::Layout::Grid)] {
            cache.begin_frame();
            let cards: Vec<shell::Card> = items
                .iter()
                .map(|it| shell::Card { title: it.name.clone(), sub: card_sub(it, None), meta: String::new(), thumb: cache.get(&it.thumb), icon: card_icon(it), progress: None })
                .collect();
            assert_eq!(cards.iter().filter(|c| c.thumb.is_some()).count(), 3, "thumbnails not loaded");
            let view = shell::BrowseView {
                title: "Videos", layout, rows: &[], progress: &[], cards: &cards, first: 0, selected: 0,
                matches: cards.len(), total: cards.len(), query: "", searching: false,
                search_focused: false, keyboard: None,
            };
            shell::render_browse(&mut frame, &text, &view, w as f32, h as f32);
            text.render(&gpu, &target, fb, &frame).unwrap();
            std::fs::write(format!("{dir}/medias-{name}-{w}x{h}.bgra"), gpu.read_target(&target).unwrap()).unwrap();
        }
        gpu.destroy_framebuffer(fb);
        text.destroy(&gpu);
        gpu.destroy_target(target);
        std::fs::remove_dir_all(&root).unwrap();
    }
}


#[cfg(test)]
mod queue_tests {
    use super::*;

    fn level() -> Level {
        let server = std::sync::Arc::new(upnp::Server {
            name: "nas".into(),
            udn: "uuid:1".into(),
            control: "http://h/ctl".into(),
            service_type: String::new(),
            icon: String::new(),
        });
        Level::new("Album", vec![
            Item::new("CD2", Node::Dir("/m/CD2".into()), true),
            Item::new("01 Intro", Node::Media("/m/01.flac".into()), false),
            Item::new("02 Song", Node::Media("/m/02.flac".into()), false),
            Item::new("03 Remote", Node::UpnpMedia("http://h/3.flac".into(), upnp::Kind::Audio), false),
            Item::video("Clip", "https://www.youtube.com/watch?v=abcdefghijk".into()),
            Item::new("Sub", Node::UpnpDir(server, "9".into()), true),
        ])
    }

    fn target(loaded: Option<Loaded>) -> Option<String> {
        match loaded? {
            Loaded::Play { key, target, .. } => {
                assert_eq!(key, target);
                Some(target)
            }
            _ => None,
        }
    }

    #[test]
    fn queue_steps_through_playable_folder_items_only() {
        let mut stack = vec![level()];
        let mut q = Queue::new(&stack[0], 0, 1).unwrap();
        assert_eq!(q.items.len(), 3); // directories and YouTube are skipped
        assert_eq!(target(Some(q.play())).as_deref(), Some("/m/01.flac"));
        assert_eq!(target(q.step(-1)), None);
        assert_eq!(target(q.step(1)).as_deref(), Some("/m/02.flac"));
        assert_eq!(target(q.step(1)).as_deref(), Some("http://h/3.flac"));
        q.sync_selection(&mut stack);
        assert_eq!(stack[0].browse.source_index(stack[0].browse.selected()), Some(3));
        assert_eq!(target(q.step(1)), None); // the end: back to the browser
        assert!(Queue::new(&stack[0], 0, 0).is_none()); // a directory is not queued
    }

    #[test]
    fn ytdl_sub_langs_quotes_the_regex_list() {
        assert_eq!(ytdl_sub_langs(&["de".into(), "en".into()]).as_deref(), Some("sub-langs=%17%de(-.*)?,en(-.*)?"));
        assert_eq!(ytdl_sub_langs(&[]), None);
    }

    #[test]
    fn info_cycles_bar_hidden_black_bar() {
        let (mut bar, mut hidden, mut blank) = (true, false, false); // just started
        let mut seen = Vec::new();
        for _ in 0..4 {
            (bar, hidden, blank) = info_step(bar, hidden, blank);
            seen.push((bar, blank));
        }
        assert_eq!(seen, [(false, false), (false, true), (true, false), (false, false)]);
        assert_eq!(info_step(false, false, false), (true, false, false)); // timed out: show first
    }

    #[test]
    fn queue_follows_the_filtered_order() {
        let mut l = level();
        for key in "song".chars().map(input::Key::Char) {
            l.browse.handle(key, 10);
        }
        let mut q = Queue::new(&l, 0, 2).unwrap();
        assert_eq!(q.items.len(), 1);
        assert_eq!(target(q.step(1)), None);
    }
}

#[cfg(test)]
mod fence_tests {
    use super::*;

    /// GPU + DRM card: libmpv GL renders into an imported GBM buffer; with
    /// mpv < 0.42 each render's leaked fence is deleted.
    /// `cargo test -- --ignored mpv_render_deletes`.
    #[test]
    #[ignore]
    fn mpv_render_deletes_per_frame_fence() {
        let path = (0..16).map(|n| format!("/dev/dri/card{n}")).find(|p| std::path::Path::new(p).exists()).unwrap();
        let card = Card::open(&path).unwrap();
        let alloc = Allocator::new(&card).unwrap();
        let video = egl::VideoGl::new(&alloc).unwrap();
        let buffer = alloc.alloc(&card, 320, 240, DrmFourcc::Xrgb8888, Use::SCANOUT | Use::RENDERING).unwrap();
        let fbo = video.import(&buffer).unwrap();
        let m = mpv::Mpv::new().unwrap();
        for (name, value) in [("config", "no"), ("vo", "libmpv"), ("ao", "null"), ("hwdec", "no"), ("msg-level", "all=error")] {
            m.set_option(name, value).unwrap();
        }
        m.init().unwrap();
        let leaks = mpv_version(&m.get_string("mpv-version").unwrap_or_default()).is_none_or(|v| v < (0, 42));
        let rc = gl_render_context(&m).unwrap();
        m.loadfile("av://lavfi:testsrc=size=320x240:rate=25").unwrap();
        let (start, mut renders) = (Instant::now(), 0);
        while renders < 20 && start.elapsed() < Duration::from_secs(10) {
            while m.wait_event(0.0) != mpv::Event::None {}
            if rc.frame_ready() {
                video.mpv_render(|| rc.render(video.fbo_id(&fbo), 320, 240)).unwrap();
                video.finish();
                renders += 1;
            } else {
                std::thread::sleep(Duration::from_millis(5));
            }
        }
        assert_eq!(renders, 20);
        let deleted = egl::DELETED_FENCES.load(std::sync::atomic::Ordering::Relaxed);
        println!("renders {renders}, fences deleted {deleted}, wrapped {leaks}");
        if leaks { assert_eq!(deleted, renders); } else { assert_eq!(deleted, 0); }
        drop(rc);
        video.release(fbo);
    }
}

#[cfg(test)]
mod root_tests {
    use super::*;
    use std::path::{Path, PathBuf};

    #[test]
    fn mpv_versions_parse_release_and_git_strings() {
        assert_eq!(mpv_version("mpv 0.40.0"), Some((0, 40)));
        assert_eq!(mpv_version("mpv v0.42.0-12-gabc1234"), Some((0, 42)));
        assert_eq!(mpv_version("mpv 1.0"), Some((1, 0)));
        assert_eq!(mpv_version("mpv git-abc"), None);
        assert_eq!(mpv_version(""), None);
    }

    #[test]
    fn parse_root_expands_tilde() {
        let home = PathBuf::from(std::env::var("HOME").unwrap());
        let base = Path::new("/b");
        assert_eq!(parse_root("=~/v", "Videos", base), ("v".into(), home.join("v")));
        assert_eq!(parse_root("=Films=~/x/y", "Videos", base), ("Films".into(), home.join("x/y")));
        assert_eq!(parse_root("=~user/v", "Videos", base).1, base.join("~user/v"));
        assert_eq!(parse_root("=rel", "Music", base), ("rel".into(), base.join("rel")));
    }
}