koan-core 0.60.6

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};

use uuid::Uuid;

use crate::remote::downloads::{ByteFeed, DownloadStore};

/// Stable identity for a queue entry. UUIDv7 — time-ordered, unique across duplicates.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct QueueItemId(pub Uuid);

impl QueueItemId {
    pub fn new() -> Self {
        Self(Uuid::now_v7())
    }
}

impl Default for QueueItemId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for QueueItemId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The tail: a v7's leading hex is its timestamp, shared by a whole batch.
        let hex = self.0.simple().to_string();
        write!(f, "QId({})", &hex[hex.len() - 8..])
    }
}

/// A step the decoder took through the queue from `after`, to `next`: the
/// item the play mode says follows it, or the end of the queue. The decoder
/// queues `next` as `chosen` when it is Ready, and stops at it when it is
/// still arriving.
#[derive(Debug, Clone)]
pub struct Lookahead {
    pub after: QueueItemId,
    pub next: Option<QueueItemId>,
    pub chosen: Option<(QueueItemId, PathBuf)>,
    /// `next` was found by going back to the top of the queue, which only
    /// repeating the queue does.
    pub wrapped: bool,
    /// The timeline boundary `chosen` opens as, if it opens: the session's
    /// boundary count when the step was taken. A step whose file fails to
    /// open leaves no boundary, and the decoder steps again for the same one,
    /// so this rather than a step's index is what places it against the
    /// playhead. Set by the decoder's cursor; 0 elsewhere.
    pub boundary: usize,
}

/// What follows a track once it ends, beyond the queue's own order.
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "lowercase")]
pub enum Repeat {
    /// The queue ends at its last item.
    #[default]
    Off,
    /// The last item runs on into the first.
    Queue,
    /// The item plays again. An explicit next or previous still moves on.
    One,
}

impl Repeat {
    pub fn is_off(&self) -> bool {
        *self == Repeat::Off
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Repeat::Off => "off",
            Repeat::Queue => "queue",
            Repeat::One => "one",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "off" => Some(Repeat::Off),
            "queue" => Some(Repeat::Queue),
            "one" => Some(Repeat::One),
            _ => None,
        }
    }

    /// The next mode a single repeat button steps to: off, the queue, one.
    pub fn cycled(self) -> Self {
        match self {
            Repeat::Off => Repeat::Queue,
            Repeat::Queue => Repeat::One,
            Repeat::One => Repeat::Off,
        }
    }
}

/// The transport's play mode. Shuffle is not an order kept beside the queue:
/// turning it on reorders the queue itself, so what is listed is what plays.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct PlayMode {
    pub shuffle: bool,
    pub repeat: Repeat,
}

impl PlayMode {
    fn to_bits(self) -> u8 {
        let repeat = match self.repeat {
            Repeat::Off => 0,
            Repeat::Queue => 1,
            Repeat::One => 2,
        };
        repeat << 1 | self.shuffle as u8
    }

    fn from_bits(bits: u8) -> Self {
        Self {
            shuffle: bits & 1 != 0,
            repeat: match bits >> 1 {
                1 => Repeat::Queue,
                2 => Repeat::One,
                _ => Repeat::Off,
            },
        }
    }
}

/// A sleep timer as asked for: stop after a while, or at the end of the
/// track or record playing. It pauses, fading out, and leaves the queue as it
/// was, so playing again carries on from there.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum SleepTimer {
    After { minutes: u32 },
    EndOfTrack,
    EndOfRecord,
}

/// A sleep timer that is set, as clients show it. A time rather than what
/// is left of one, so it says the same thing for as long as it stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Sleep {
    /// Milliseconds since the Unix epoch.
    At {
        unix_ms: u64,
    },
    EndOfTrack,
    EndOfRecord,
}

/// What follows `after` under `repeat`: `Some(None)` at the end of the queue,
/// `None` when `after` is not in it — a removed item has nothing following it,
/// whatever the mode, since wrapping from it would replay the queue from a
/// place nobody is at. The flag says the step went back to the top.
///
/// Failed items are passed over. Repeating one item plays it again unless it
/// has failed, in which case the queue carries on as it would when repeating
/// the queue.
fn follows(
    items: &[PlaylistItem],
    after: QueueItemId,
    repeat: Repeat,
) -> Option<(Option<&PlaylistItem>, bool)> {
    let at = items.iter().position(|item| item.id == after)?;
    let playable = |item: &&PlaylistItem| !matches!(item.state, ItemState::Failed(_));
    if repeat == Repeat::One && playable(&&items[at]) {
        return Some((Some(&items[at]), false));
    }
    if let Some(next) = items[at + 1..].iter().find(playable) {
        return Some((Some(next), false));
    }
    if repeat == Repeat::Off {
        return Some((None, false));
    }
    Some((items[..=at].iter().find(playable), true))
}

/// Set in `SharedPlayerState::state` beside the playback state while the
/// player waits for a track.
const WAITING: u8 = 0x80;

/// Playback state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PlaybackState {
    Stopped = 0,
    Playing = 1,
    Paused = 2,
}

impl PlaybackState {
    pub fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Playing,
            2 => Self::Paused,
            _ => Self::Stopped,
        }
    }
}

/// Audio format info for the currently playing track.
#[derive(Debug, Clone, PartialEq)]
pub struct TrackInfo {
    pub id: QueueItemId,
    pub path: PathBuf,
    pub codec: String,
    pub sample_rate: u32,
    pub bit_depth: Option<u16>,
    pub bitrate_kbps: Option<u32>,
    pub channels: u16,
    pub duration_ms: u64,
}

// --- Playlist data model ---

/// Minimum bytes written before streaming playback can begin.
pub const STREAM_THRESHOLD: u64 = 256 * 1024;

/// Held back from the seekable extent of a downloading track.
///
/// Bytes are converted to time at the average bitrate, so on VBR the estimate
/// wanders either side of the truth; landing short of the write head costs a
/// couple of seconds of reach and landing past it costs a stall.
pub const SEEK_SAFETY_MS: u64 = 2_000;

/// What a playlist item can say about itself.
///
/// Only what is true of the item regardless of any transfer: whether the bytes
/// at its path can be played. Whether one is *arriving* is the download store's
/// business, and asking the item would mean two accounts of one fact that have
/// to be kept in step. Read [`LoadState`] for the two
/// together.
///
/// Once a transfer ends, this is written before anything is woken: a reader
/// waiting on the transfer learns how it ended from here.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum ItemState {
    /// Nothing has resolved this yet.
    #[default]
    Pending,
    /// The file at `path` is there and playable.
    Ready,
    /// It cannot be made playable, and this is why. Not only download
    /// failures: a track with no local file and no remote copy fails here
    /// without a transfer ever being attempted.
    Failed(String),
}

/// An item's state, and any transfer against it, as one answer.
///
/// Derived rather than stored. `Downloading` carries the store's own figures —
/// the very same counter the downloader writes — so there is nothing to copy
/// and nothing that can drift.
#[derive(Debug, Clone)]
pub enum LoadState {
    Pending,
    Downloading {
        /// Where the bytes are going: the in-progress `.part` file, not the
        /// destination it is renamed to at the end.
        path: PathBuf,
        /// Total bytes expected, or 0 when the server sent no Content-Length.
        total: u64,
        /// How many bytes have landed. The download thread writes it per chunk
        /// without taking any lock the player holds.
        bytes_written: Arc<ByteFeed>,
    },
    Ready,
    Failed(String),
}

impl LoadState {
    /// An item's state, with whatever the download store says about it.
    ///
    /// The item's own state stands once it is anything but `Pending`: a
    /// transfer's end is written to every entry waiting on it before the
    /// transfer itself is marked settled. While it is pending, a listed
    /// transfer for its track is what is happening to it — whichever entry
    /// that transfer was started for.
    pub fn of(item: &PlaylistItem, downloads: &DownloadStore) -> Self {
        match &item.state {
            ItemState::Ready => Self::Ready,
            ItemState::Failed(reason) => Self::Failed(reason.clone()),
            ItemState::Pending => match item.db_id.and_then(|id| downloads.live(id)) {
                Some(live) => Self::Downloading {
                    path: live.source,
                    total: live.total,
                    bytes_written: live.written,
                },
                None => Self::Pending,
            },
        }
    }
}

/// Resolved playback source for a playlist item.
pub enum PlaybackSource {
    /// File fully downloaded — play from path.
    Ready(PathBuf),
    /// File being downloaded — enough data buffered to start streaming.
    Streaming {
        path: PathBuf,
        bytes_written: Arc<crate::remote::downloads::ByteFeed>,
        total: u64,
    },
}

/// A single item in the playlist. Created once when tracks are added to the playlist.
#[derive(Debug, Clone)]
pub struct PlaylistItem {
    pub id: QueueItemId,
    /// Database track ID — set for tracks loaded from DB, used for downloads.
    pub db_id: Option<i64>,
    /// The playlist entry this came from, when it came from a playlist.
    ///
    /// A playlist may hold the same track twice, and two copies are two queue
    /// items. Without this a playlist row can only ask "is my *track* playing?"
    /// and both copies answer yes. The entry id is the one thing that tells
    /// them apart, so the queue carries it.
    pub playlist_entry_id: Option<i64>,
    pub path: PathBuf,
    pub title: String,
    pub artist: String,
    pub album_artist: String,
    pub album: String,
    pub year: Option<String>,
    pub codec: Option<String>,
    pub track_number: Option<i64>,
    pub disc: Option<i64>,
    pub duration_ms: Option<u64>,
    /// What the item can say about itself. Ask [`SharedPlayerState::load_state`]
    /// for this together with any transfer against it.
    pub state: ItemState,
    /// Where the item stood in the queue before shuffle was turned on, which
    /// is where turning it off puts it back. `None` while shuffle is off, and
    /// for an item added since it was turned on, which stays where it was put.
    pub pre_shuffle: Option<u32>,
}

/// The playlist — one flat array, one cursor. Everything else derived.
#[derive(Debug, Clone, Default)]
pub struct Playlist {
    pub items: Vec<PlaylistItem>,
    pub cursor: Option<QueueItemId>,
}

// --- UI view types ---

/// Status of a track in the queue — for UI display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueueEntryStatus {
    Queued,
    Playing,
    Played,
    Downloading,
    /// User double-clicked — this track is priority, will play when ready.
    PriorityPending,
    Failed,
}

impl QueueEntryStatus {
    /// The item under the cursor. Every front end maps it through here, so
    /// the transport and the queue row agree on what it is doing.
    ///
    /// `PriorityPending` is waiting its turn with no bytes moving; once its
    /// transfer starts it is `Downloading`, with progress to draw.
    pub fn at_cursor(state: &ItemState, transferring: bool) -> Self {
        match state {
            ItemState::Ready => Self::Playing,
            ItemState::Failed(_) => Self::Failed,
            ItemState::Pending if transferring => Self::Downloading,
            ItemState::Pending => Self::PriorityPending,
        }
    }
}

/// A single entry in the UI-visible queue snapshot.
#[derive(Debug, Clone)]
pub struct QueueEntry {
    pub id: QueueItemId,
    /// Database track ID — set for tracks loaded from DB, used for downloads.
    pub db_id: Option<i64>,
    /// The playlist row this came from — see `PlaylistItem::playlist_entry_id`.
    pub playlist_entry_id: Option<i64>,
    pub path: PathBuf,
    pub title: String,
    pub artist: String,
    pub album_artist: String,
    pub album: String,
    pub year: Option<String>,
    pub codec: Option<String>,
    pub track_number: Option<i64>,
    pub disc: Option<i64>,
    pub duration_ms: Option<u64>,
    pub status: QueueEntryStatus,
    pub download_progress: Option<(u64, u64)>,
    /// Why this entry cannot play, when `status` is `Failed`.
    pub error: Option<String>,
}

/// Pre-built visible queue — single atomic snapshot for the UI.
#[derive(Debug, Clone, Default)]
pub struct VisibleQueueSnapshot {
    pub entries: Vec<QueueEntry>,
    pub finished_count: usize,
    pub has_playing: bool,
    pub queue_count: usize,
}

/// The part of a visible queue row that moves while the queue stands still.
/// See `SharedPlayerState::queue_readings`.
#[derive(Debug, Clone, PartialEq)]
pub struct QueueReading {
    pub id: QueueItemId,
    pub db_id: Option<i64>,
    pub status: QueueEntryStatus,
    pub duration_ms: Option<u64>,
    pub download_progress: Option<(u64, u64)>,
    pub error: Option<String>,
}

/// Shared player state — atomics for lock-free reads from UI thread.
///
/// The engine writes these, the UI reads them. No mutexes in the hot path.
#[derive(Debug)]
pub struct SharedPlayerState {
    /// The playback state, with `WAITING` set while the player waits for a
    /// track it was asked for. One atomic, so no reader sees one updated
    /// without the other.
    state: AtomicU8,
    /// Where a session starts, and where a stopped one stands. While one is
    /// running the playhead is read off the timeline instead.
    position_ms: AtomicU64,
    timeline: std::sync::OnceLock<Arc<crate::audio::buffer::PlaybackTimeline>>,
    track_info: parking_lot::RwLock<Option<TrackInfo>>,

    /// The playlist and its cursor, under one lock.
    playlist: parking_lot::RwLock<Playlist>,

    /// Bumped on every playlist mutation so UI can skip redundant redraws.
    playlist_version: AtomicU64,

    /// Bumped only when what a saved session holds changes: the items and
    /// their metadata, not the cursor or load states. What decides whether
    /// the saved queue has to be written again.
    content_version: AtomicU64,

    /// Bumped when the set of items still waiting for a file may have
    /// changed: items added or removed, or one put back to `Pending`. What the
    /// download queue follows; a download landing or the cursor moving does
    /// not move it.
    pending_version: AtomicU64,

    /// Every transfer this player's items are fetched by.
    downloads: Arc<DownloadStore>,

    /// Set by external signals (e.g. souvlaki Quit event) to request clean shutdown.
    quit_requested: AtomicBool,

    /// Set when metadata has been refreshed (e.g. download completed while streaming).
    /// The UI loop checks this to force a souvlaki/cover-art update without a track change.
    metadata_refresh_pending: AtomicBool,

    /// The rate the output device settled at for the current track, or 0 when
    /// nothing has played yet. Compared against the source rate, it is the one
    /// thing koan can say for certain about the path to the DAC: whether it
    /// handed the device the samples as they are, or something had to resample
    /// to reach it. Everything past that — other clients, the volume stage — is
    /// the system's, and not ours to claim.
    output_sample_rate: AtomicU64,

    /// What DSP is doing to the current session's audio. `None` is the
    /// bit-perfect path.
    dsp: parking_lot::RwLock<Option<crate::audio::dsp::DspStatus>>,
    /// The playhead of a renderer this koan is playing to, which keeps its
    /// own clock: where it was last heard to be, and since when it has been
    /// running from there. Read in place of the timeline while set.
    renderer_clock: parking_lot::Mutex<Option<RendererClock>>,

    /// The UPnP renderer playing in place of the local output, if one is.
    renderer: parking_lot::RwLock<Option<crate::upnp::Output>>,

    /// The play mode, as `PlayMode::to_bits`. Written by the player's
    /// `publish` alone; the queue's own reads (the lookahead, advancing)
    /// follow it.
    play_mode: AtomicU8,

    /// The sleep timer, while one is set. Written by the player's `publish`.
    sleep: parking_lot::RwLock<Option<Sleep>>,
    /// The sleep timer is fading playback out.
    sleep_fading: AtomicBool,
}

/// A renderer's playhead: `position_ms`, plus the time since `running` if it
/// is playing.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RendererClock {
    pub position_ms: u64,
    pub running: Option<std::time::Instant>,
}

impl RendererClock {
    pub fn now_ms(&self) -> u64 {
        self.position_ms + self.running.map_or(0, |at| at.elapsed().as_millis() as u64)
    }
}

impl SharedPlayerState {
    pub fn new() -> Arc<Self> {
        Arc::new(Self {
            state: AtomicU8::new(PlaybackState::Stopped as u8),
            position_ms: AtomicU64::new(0),
            timeline: std::sync::OnceLock::new(),
            track_info: parking_lot::RwLock::new(None),
            playlist: parking_lot::RwLock::new(Playlist::default()),
            playlist_version: AtomicU64::new(0),
            content_version: AtomicU64::new(0),
            pending_version: AtomicU64::new(0),
            downloads: DownloadStore::new(),
            quit_requested: AtomicBool::new(false),
            metadata_refresh_pending: AtomicBool::new(false),
            output_sample_rate: AtomicU64::new(0),
            dsp: parking_lot::RwLock::new(None),
            renderer_clock: parking_lot::Mutex::new(None),
            renderer: parking_lot::RwLock::new(None),
            play_mode: AtomicU8::new(0),
            sleep: parking_lot::RwLock::new(None),
            sleep_fading: AtomicBool::new(false),
        })
    }

    // --- Playback state ---

    fn transport(&self) -> (PlaybackState, bool) {
        let bits = self.state.load(Ordering::Acquire);
        (PlaybackState::from_u8(bits & !WAITING), bits & WAITING != 0)
    }

    pub fn playback_state(&self) -> PlaybackState {
        self.transport().0
    }

    pub fn set_playback_state(&self, state: PlaybackState) {
        self.set_transport(state, false);
    }

    /// Whether the player is waiting for a track it was asked for to arrive.
    /// Stopped while waiting, the track opens playing; paused, it opens paused.
    pub fn is_waiting(&self) -> bool {
        self.transport().1
    }

    /// Playing, or waiting for a track that will open playing: what a
    /// play/pause toggle pauses.
    pub fn wants_to_play(&self) -> bool {
        matches!(
            self.transport(),
            (PlaybackState::Playing, _) | (PlaybackState::Stopped, true)
        )
    }

    /// Nothing loaded and nothing waited for: where adding tracks starts them.
    pub fn is_idle(&self) -> bool {
        self.transport() == (PlaybackState::Stopped, false)
    }

    /// Publish the playback state and the wait together.
    pub fn set_transport(&self, state: PlaybackState, waiting: bool) {
        let bits = state as u8 | if waiting { WAITING } else { 0 };
        if self.state.swap(bits, Ordering::AcqRel) != bits {
            self.changed();
        }
    }

    /// Where the playhead is, read off the samples the output has played, so
    /// it is right whenever it is asked and nothing has to keep it up to date.
    pub fn position_ms(&self) -> u64 {
        let clock = *self.renderer_clock.lock();
        if let Some(clock) = clock {
            let at = clock.now_ms();
            let duration = self.duration_ms();
            return if duration > 0 { at.min(duration) } else { at };
        }
        if self.playback_state() != PlaybackState::Stopped
            && let Some(playhead) = self.timeline.get().and_then(|t| t.playhead())
        {
            return playhead.position_ms;
        }
        self.position_ms.load(Ordering::Acquire)
    }

    /// The timeline the playhead is read from. Set once, by the player.
    pub(crate) fn attach_timeline(&self, timeline: Arc<crate::audio::buffer::PlaybackTimeline>) {
        let _ = self.timeline.set(timeline);
    }

    pub fn set_position_ms(&self, pos: u64) {
        self.position_ms.store(pos, Ordering::Release);
        // Deliberately silent. The playhead advances on its own and is
        // published as an anchor rather than as a reading — a wake per
        // position would be the tick this whole arrangement removes. A seek, a
        // pause and a track change all move something else here as well, and
        // those are exactly the ones a client has to be told about.
    }

    /// Set by the player while a renderer is the output. A change to it is a
    /// change clients are told about: the clock only moves when the renderer
    /// is heard from, or when a command moved it.
    /// Whether the playhead is advancing on its own. Playing, but held, while
    /// a renderer has been told to play and has not yet started: a client
    /// counting on from the command would run ahead of the sound.
    ///
    /// A renderer playing a file keeps its clock here; one playing a stream
    /// processed here keeps it on the timeline, in time into the stream.
    pub fn playhead_moving(&self) -> bool {
        let clock =
            (*self.renderer_clock.lock()).or_else(|| self.timeline.get().and_then(|t| t.clock()));
        match clock {
            Some(clock) => clock.running.is_some(),
            None => self.playback_state() == PlaybackState::Playing,
        }
    }

    pub(crate) fn renderer_clock(&self) -> Option<RendererClock> {
        *self.renderer_clock.lock()
    }

    pub(crate) fn set_renderer_clock(&self, clock: Option<RendererClock>) {
        let mut guard = self.renderer_clock.lock();
        if *guard != clock {
            *guard = clock;
            drop(guard);
            self.changed();
        }
    }

    /// The renderer this koan is playing to, when it is not its own output.
    pub fn renderer(&self) -> Option<crate::upnp::Output> {
        self.renderer.read().clone()
    }

    pub(crate) fn set_renderer(&self, output: Option<crate::upnp::Output>) {
        *self.renderer.write() = output;
        self.changed();
    }

    pub(crate) fn update_renderer(&self, f: impl FnOnce(&mut crate::upnp::Output)) {
        let changed = match self.renderer.write().as_mut() {
            Some(out) => {
                let before = out.clone();
                f(out);
                *out != before
            }
            None => false,
        };
        if changed {
            self.changed();
        }
    }

    pub fn track_info(&self) -> Option<TrackInfo> {
        self.track_info.read().clone()
    }

    pub fn set_track_info(&self, info: Option<TrackInfo>) {
        *self.track_info.write() = info;
        self.changed();
    }

    /// How far into the currently playing track a seek can land.
    ///
    /// A track on disk is seekable end to end. One still downloading is
    /// seekable only as far as its bytes reach: bytes map to time by the
    /// average bitrate, exact for lossless and CBR and drifting on VBR, which
    /// is what `SEEK_SAFETY_MS` covers. Zero when nothing is playing.
    ///
    /// The one value both the clamp in `Player::seek` and the extent front ends
    /// draw on the seek bar come from — a bar that shows a reachable position
    /// the player then refuses is worse than no bar.
    pub fn seekable_ms(&self) -> u64 {
        let Some(info) = self.track_info.read().clone() else {
            return 0;
        };

        // Released before the playlist lock is taken: derive_visible_queue takes
        // these two in the opposite order, so holding both would close a cycle.
        let pl = self.playlist.read();
        let Some(item) = pl.items.iter().find(|item| item.id == info.id) else {
            return info.duration_ms;
        };

        let LoadState::Downloading {
            total,
            bytes_written,
            ..
        } = self.load_state(item)
        else {
            return info.duration_ms;
        };

        // A container that could not describe itself from the bytes downloaded
        // states no duration, and cannot be seeked at all until the rest of it
        // lands — there is no index to seek against and no end to seek within.
        // Ogg is the one that does this; it keeps its duration in its last page.
        if info.duration_ms == 0 {
            return 0;
        }

        let written = bytes_written.load(Ordering::Acquire);
        let reached = if total > 0 && info.duration_ms > 0 {
            ((written as f64 / total as f64) * info.duration_ms as f64) as u64
        } else if let Some(kbps) = info.bitrate_kbps.filter(|k| *k > 0) {
            // No Content-Length. Bytes still say how much audio has arrived,
            // given what the probe measured the bitrate to be: 1 kbps is
            // 1 bit per ms, so bits divided by kbps is milliseconds.
            written.saturating_mul(8) / kbps as u64
        } else {
            // Nothing to derive a position from — forward seeking would be a
            // guess, so allow only what has already been played.
            return self.position_ms();
        };

        reached.saturating_sub(SEEK_SAFETY_MS).min(info.duration_ms)
    }

    /// The duration to show for what is playing.
    ///
    /// The container's own answer wherever it gave one. A partial file that
    /// could not be read far enough to state a duration has none, and the
    /// library's figure stands in — it came from the server, it is right, and
    /// a transport that reads 0:00 for nine hours of music is worse than one
    /// reading a figure the container has not caught up with yet.
    pub fn duration_ms(&self) -> u64 {
        let Some(info) = self.track_info.read().clone() else {
            return 0;
        };
        if info.duration_ms > 0 {
            return info.duration_ms;
        }
        // Released before the playlist lock, as everywhere else here.
        self.playlist
            .read()
            .items
            .iter()
            .find(|item| item.id == info.id)
            .and_then(|item| item.duration_ms)
            .unwrap_or(0)
    }

    /// `seekable_ms`, but `None` when the whole track is reachable — which is
    /// every track that is not mid-download. What a front end draws a boundary
    /// from: no boundary is the normal case and should cost no mark.
    pub fn seek_ceiling_ms(&self) -> Option<u64> {
        let duration = self.duration_ms();
        if duration == 0 {
            return None;
        }
        let seekable = self.seekable_ms();
        (seekable < duration).then_some(seekable)
    }

    /// Download fraction (0.0..1.0) for the currently playing track, if streaming.
    /// Returns `None` for fully-downloaded or non-playing tracks.
    pub fn current_download_fraction(&self) -> Option<f64> {
        // Released before the playlist lock is taken: derive_visible_queue takes
        // these two in the opposite order, so holding both would close a cycle.
        let id = self.track_info.read().as_ref()?.id;
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .and_then(|item| match self.load_state(item) {
                LoadState::Downloading {
                    bytes_written,
                    total,
                    ..
                } => {
                    let written = bytes_written.load(Ordering::Acquire);
                    (total > 0).then(|| (written as f64 / total as f64).min(1.0))
                }
                _ => None,
            })
    }

    // --- Quit ---

    pub fn request_quit(&self) {
        self.quit_requested.store(true, Ordering::Release);
    }

    pub fn quit_requested(&self) -> bool {
        self.quit_requested.load(Ordering::Acquire)
    }

    // --- Metadata refresh ---

    /// Signal that metadata has been refreshed mid-stream (e.g. download completed).
    /// The UI loop calls `take_metadata_refresh()` to consume this flag and
    /// force a souvlaki/cover-art update without waiting for a track change.
    pub fn signal_metadata_refresh(&self) {
        self.metadata_refresh_pending.store(true, Ordering::Release);
        self.changed();
    }

    /// Returns true and clears the flag if a metadata refresh is pending.
    pub fn take_metadata_refresh(&self) -> bool {
        self.metadata_refresh_pending
            .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
    }

    // --- Output device rate ---

    /// `None` until a track has started and the device rate is known.
    pub fn output_sample_rate(&self) -> Option<u32> {
        match self.output_sample_rate.load(Ordering::Acquire) {
            0 => None,
            rate => Some(rate as u32),
        }
    }

    pub fn set_output_sample_rate(&self, rate: u32) {
        self.output_sample_rate
            .store(u64::from(rate), Ordering::Release);
        self.changed();
    }

    /// Back to "not known yet", for the window where the device is between
    /// rates. A switch takes as long as the hardware needs to reclock — the
    /// better part of a second on USB — and the previous track's rate is not
    /// an answer for this one.
    pub fn clear_output_sample_rate(&self) {
        self.output_sample_rate.store(0, Ordering::Release);
    }

    // --- DSP ---

    pub fn dsp(&self) -> Option<crate::audio::dsp::DspStatus> {
        self.dsp.read().clone()
    }

    pub fn set_dsp(&self, status: Option<crate::audio::dsp::DspStatus>) {
        let mut dsp = self.dsp.write();
        if *dsp != status {
            *dsp = status;
            drop(dsp);
            self.changed();
        }
    }

    // --- Play mode ---

    pub fn play_mode(&self) -> PlayMode {
        PlayMode::from_bits(self.play_mode.load(Ordering::Acquire))
    }

    /// The player's `publish`, and nothing else — but for a front end that
    /// mirrors another process's player into a state of its own, as it
    /// mirrors the playback state. The mode is saved with the queue, so a
    /// change moves the content version.
    pub fn set_play_mode(&self, mode: PlayMode) {
        if self.play_mode.swap(mode.to_bits(), Ordering::AcqRel) != mode.to_bits() {
            self.content_version.fetch_add(1, Ordering::AcqRel);
            self.bump_version();
        }
    }

    pub fn sleep(&self) -> Option<Sleep> {
        *self.sleep.read()
    }

    pub fn set_sleep(&self, sleep: Option<Sleep>) {
        let mut held = self.sleep.write();
        if *held != sleep {
            *held = sleep;
            drop(held);
            self.changed();
        }
    }

    pub fn sleep_fading(&self) -> bool {
        self.sleep_fading.load(Ordering::Acquire)
    }

    pub fn set_sleep_fading(&self, fading: bool) {
        if self.sleep_fading.swap(fading, Ordering::AcqRel) != fading {
            self.changed();
        }
    }

    // --- Playlist version ---

    pub fn playlist_version(&self) -> u64 {
        self.playlist_version.load(Ordering::Acquire)
    }

    fn bump_version(&self) {
        self.playlist_version.fetch_add(1, Ordering::AcqRel);
        self.changed();
    }

    pub fn content_version(&self) -> u64 {
        self.content_version.load(Ordering::Acquire)
    }

    /// `bump_version`, for a change to what a saved session holds.
    fn bump_content(&self) {
        self.content_version.fetch_add(1, Ordering::AcqRel);
        self.pending_version.fetch_add(1, Ordering::AcqRel);
        self.bump_version();
    }

    /// See the field. Moves with every content change, and when an item goes
    /// back to `Pending`.
    pub fn pending_version(&self) -> u64 {
        self.pending_version.load(Ordering::Acquire)
    }

    /// The transfers this player's items are fetched by.
    pub fn downloads(&self) -> &Arc<DownloadStore> {
        &self.downloads
    }

    fn load_state(&self, item: &PlaylistItem) -> LoadState {
        LoadState::of(item, &self.downloads)
    }

    /// Say that something here moved, without saying what.
    ///
    /// Every version and atomic in this struct stays exactly as it was — they
    /// are what a watcher consults to find out what changed. This is what
    /// spares it looking when nothing did. See `crate::signal`.
    pub fn changed(&self) {
        crate::signal::engine_changed().bump();
    }

    // --- Playlist mutations (called from player thread via commands) ---

    /// Append items to the playlist.
    pub fn add_items(&self, items: Vec<PlaylistItem>) {
        let mut pl = self.playlist.write();
        pl.items.extend(items);
        drop(pl);
        self.bump_content();
    }

    /// Insert items after a specific queue item.
    pub fn insert_items_after(&self, items: Vec<PlaylistItem>, after: QueueItemId) {
        let mut pl = self.playlist.write();
        let insert_at = match pl.items.iter().position(|item| item.id == after) {
            Some(pos) => pos + 1,
            None => pl.items.len(), // fallback: append
        };
        for (i, item) in items.into_iter().enumerate() {
            pl.items.insert(insert_at + i, item);
        }
        drop(pl);
        self.bump_content();
    }

    /// Update file paths for playlist items (after organize moves files).
    pub fn update_paths(&self, updates: &[(QueueItemId, PathBuf)]) {
        let mut pl = self.playlist.write();
        for (id, new_path) in updates {
            if let Some(item) = pl.items.iter_mut().find(|item| item.id == *id) {
                item.path = new_path.clone();
            }
        }
        drop(pl);
        self.bump_content();
    }

    /// Remove an item by ID.
    pub fn remove_item(&self, id: QueueItemId) {
        let mut pl = self.playlist.write();
        pl.items.retain(|item| item.id != id);
        // If cursor was on removed item, clear it (caller handles next_track).
        if pl.cursor == Some(id) {
            pl.cursor = None;
        }
        drop(pl);
        self.bump_content();
    }

    /// Move an item relative to another entry.
    pub fn move_item(&self, id: QueueItemId, target: QueueItemId, after: bool) {
        let mut pl = self.playlist.write();
        let Some(from) = pl.items.iter().position(|item| item.id == id) else {
            return;
        };
        let item = pl.items.remove(from);
        let Some(to) = pl.items.iter().position(|item| item.id == target) else {
            // Target gone — put it back.
            let pos = from.min(pl.items.len());
            pl.items.insert(pos, item);
            return;
        };
        let insert_at = if after { to + 1 } else { to };
        pl.items.insert(insert_at, item);
        drop(pl);
        self.bump_content();
    }

    /// Batch move: extract items by ID, reinsert them at `target` position.
    /// Preserves the relative order of the moved items.
    pub fn move_items(&self, ids: &[QueueItemId], target: QueueItemId, after: bool) {
        use std::collections::HashSet;
        let id_set: HashSet<QueueItemId> = ids.iter().copied().collect();

        let mut pl = self.playlist.write();

        // Partition: extract moved items, keep the rest.
        let mut remaining = Vec::with_capacity(pl.items.len());
        let mut moved = Vec::with_capacity(ids.len());
        for item in pl.items.drain(..) {
            if id_set.contains(&item.id) {
                moved.push(item);
            } else {
                remaining.push(item);
            }
        }

        // Find target in the remaining items.
        let insert_at = match remaining.iter().position(|item| item.id == target) {
            Some(pos) => {
                if after {
                    pos + 1
                } else {
                    pos
                }
            }
            None => remaining.len(),
        };

        // Splice moved items in at the target position.
        for (i, item) in moved.into_iter().enumerate() {
            remaining.insert(insert_at + i, item);
        }

        pl.items = remaining;
        drop(pl);
        self.bump_content();
    }

    /// Set the cursor (what's playing / should play).
    pub fn set_cursor(&self, id: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        pl.cursor = id;
        drop(pl);
        self.bump_version();
    }

    pub fn is_empty(&self) -> bool {
        self.playlist.read().items.is_empty()
    }

    pub fn cursor(&self) -> Option<QueueItemId> {
        self.playlist.read().cursor
    }

    /// The path of the item under the cursor, without copying the playlist.
    pub fn cursor_path(&self) -> Option<PathBuf> {
        let pl = self.playlist.read();
        let cursor = pl.cursor?;
        pl.items
            .iter()
            .find(|item| item.id == cursor)
            .map(|item| item.path.clone())
    }

    /// Clear the entire playlist + cursor.
    /// Swap the whole playlist for `items`, with no cursor, as one change.
    /// Returns what it held, for undo.
    ///
    /// One write and one version bump, not a clear and an add. The download
    /// queue reads the playlist on its own thread whenever it changes, and an
    /// empty playlist between the two would read as nothing wanted: every
    /// transfer for a track in both the old queue and the new one let go,
    /// cancelled, and started again.
    pub fn replace_playlist(
        &self,
        items: Vec<PlaylistItem>,
    ) -> (Vec<PlaylistItem>, Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        let old = std::mem::replace(&mut pl.items, items);
        let cursor = pl.cursor.take();
        drop(pl);
        self.bump_content();
        (old, cursor)
    }

    pub fn clear_playlist(&self) {
        let mut pl = self.playlist.write();
        pl.items.clear();
        pl.cursor = None;
        drop(pl);
        self.bump_content();
    }

    // --- Called from decode thread (gapless) ---

    /// Move the cursor to the next item that can still play — the first item
    /// after the cursor that is not `Failed`, from the top again when the
    /// queue repeats — and return its ID. An advance is a move on, so
    /// repeating one item wraps the queue here as repeating the queue does;
    /// playing the item again at its end is the player's call.
    ///
    /// An item that is still downloading parks the cursor rather than being
    /// skipped, so playback resumes from it when its data lands. Skipping it
    /// would drop it from the queue for good.
    ///
    /// With no cursor set, starts from the top. A cursor pointing at an item
    /// that is no longer in the playlist yields `None` — restarting from the
    /// top would silently replay the queue.
    pub fn advance_cursor_loadable(&self) -> Option<QueueItemId> {
        let repeat = match self.play_mode().repeat {
            Repeat::Off => Repeat::Off,
            Repeat::Queue | Repeat::One => Repeat::Queue,
        };
        let mut pl = self.playlist.write();
        let next = match pl.cursor {
            Some(cid) => follows(&pl.items, cid, repeat)?.0?.id,
            None => {
                pl.items
                    .iter()
                    .find(|item| !matches!(item.state, ItemState::Failed(_)))?
                    .id
            }
        };

        pl.cursor = Some(next);
        drop(pl);
        self.bump_version();
        Some(next)
    }

    /// One step of the decoder's gapless lookahead from `after_id`. Does not
    /// move the cursor; `update_playback_state` does that when the playhead
    /// gets there.
    ///
    /// Failed items are passed over, as `advance_cursor_loadable` passes over
    /// them. A track still arriving is not: the decoder stops at it, the
    /// session drains, and the advance that follows waits for it. Passing over
    /// it would play the track after it and move the cursor beyond it, so it
    /// would never be heard.
    ///
    /// The play mode decides what follows: the queue's next item, the first
    /// again at its end when the queue repeats, or the same item when one
    /// repeats — gapless all three.
    ///
    /// None when `after_id` has been removed: the lookahead then has nothing
    /// to follow, and starting from the top would gaplessly replay the queue.
    pub fn lookahead_after(&self, after_id: QueueItemId) -> Option<Lookahead> {
        let repeat = self.play_mode().repeat;
        let pl = self.playlist.read();
        let (next, wrapped) = follows(&pl.items, after_id, repeat)?;
        Some(Lookahead {
            after: after_id,
            next: next.map(|item| item.id),
            chosen: next
                .filter(|item| matches!(item.state, ItemState::Ready))
                .map(|item| (item.id, item.path.clone())),
            wrapped,
            boundary: 0,
        })
    }

    /// Whether the decoder would still take `step`: under the play mode now,
    /// `next` still follows `after`. A track it stopped at landing since is
    /// not a change, since the advance at the end of the session plays it in
    /// order; an edit that puts another track first is, and so is a change of
    /// mode that sends the queue elsewhere — a wrap once repeat is off, or a
    /// track appended after the one a wrap left from.
    pub fn still_follows(&self, step: &Lookahead) -> bool {
        let repeat = self.play_mode().repeat;
        let pl = self.playlist.read();
        follows(&pl.items, step.after, repeat)
            .is_some_and(|(next, _)| next.map(|item| item.id) == step.next)
    }

    /// Retreat cursor to the previous item. Returns (id, path) if found.
    /// For prev_track — goes to the item before cursor regardless of load state,
    /// and from the first to the last while repeat is on.
    pub fn retreat_cursor(&self) -> Option<(QueueItemId, PathBuf)> {
        let mut pl = self.playlist.write();
        let cursor_pos = match pl.cursor {
            Some(cid) => pl.items.iter().position(|item| item.id == cid),
            None => None,
        };

        // From the first item, round to the last while the queue repeats. A
        // queue of one has nothing to go back to: the caller restarts it.
        let wraps = self.play_mode().repeat != Repeat::Off && pl.items.len() > 1;
        let prev_pos = cursor_pos.and_then(|p| match p.checked_sub(1) {
            None if wraps => Some(pl.items.len() - 1),
            prev => prev,
        });

        match prev_pos {
            Some(pos) => {
                let item = &pl.items[pos];
                let result = (item.id, item.path.clone());
                pl.cursor = Some(item.id);
                drop(pl);
                self.bump_version();
                Some(result)
            }
            None => None,
        }
    }

    // --- Called from resolve thread ---

    /// Update the load state of a playlist item.
    pub fn update_item_state(&self, id: QueueItemId, new_state: ItemState) {
        let pending = new_state == ItemState::Pending;
        let mut pl = self.playlist.write();
        if let Some(item) = pl.items.iter_mut().find(|item| item.id == id) {
            item.state = new_state;
        }
        drop(pl);
        if pending {
            self.pending_version.fetch_add(1, Ordering::AcqRel);
        }
        self.bump_version();
    }

    /// An item's own state, without the rest of it.
    pub fn item_state(&self, id: QueueItemId) -> Option<ItemState> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .map(|item| item.state.clone())
    }

    /// Take what a finished download's own tags can add.
    ///
    /// Streaming starts on partial Symphonia tags, so an item with nothing
    /// behind it takes the lot once the whole file is there. An item that came
    /// out of the library does not: the record is what the queue was built
    /// from and what every other track on it carries, and a file whose tags
    /// disagree — a server album titled one way, the file inside titled
    /// another — would split its album in two the moment it finished
    /// downloading. The duration is the file's to know either way.
    pub fn update_item_metadata(
        &self,
        id: QueueItemId,
        title: String,
        artist: String,
        album_artist: String,
        album: String,
        duration_ms: Option<u64>,
    ) {
        let mut pl = self.playlist.write();
        let mut retagged = false;
        let mut retimed = false;
        if let Some(item) = pl.items.iter_mut().find(|item| item.id == id) {
            if item.db_id.is_none() {
                retagged = item.title != title
                    || item.artist != artist
                    || item.album_artist != album_artist
                    || item.album != album;
                item.title = title;
                item.artist = artist;
                item.album_artist = album_artist;
                item.album = album;
            }
            if let Some(dur) = duration_ms
                && item.duration_ms != Some(dur)
            {
                item.duration_ms = Some(dur);
                retimed = true;
            }
        }
        drop(pl);
        // Every download landing comes through here. A content change rewrites
        // the saved queue and has every client read the whole queue again,
        // which on a long queue is not something to do per track: so only new
        // tags are one. A duration is corrected on nearly every streamed track
        // — a server gives whole seconds, the file milliseconds — and goes to
        // clients as a change to that row alone.
        if retagged {
            self.bump_content();
        } else if retimed {
            self.bump_version();
        }
    }

    /// Get the playback source for an item if it's ready to play.
    /// Returns `None` if not enough data is available yet.
    pub fn item_playback_source(&self, id: QueueItemId) -> Option<PlaybackSource> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .and_then(|item| match self.load_state(item) {
                LoadState::Ready => Some(PlaybackSource::Ready(item.path.clone())),
                LoadState::Downloading {
                    path,
                    total,
                    bytes_written,
                } => {
                    let written = bytes_written.load(Ordering::Acquire);
                    (written >= STREAM_THRESHOLD).then_some(PlaybackSource::Streaming {
                        path,
                        bytes_written,
                        total,
                    })
                }
                _ => None,
            })
    }

    /// Put back to `Pending` every queue item whose file has gone, and say
    /// which they were so they can be fetched again.
    ///
    /// The queue holds paths, and clearing downloads deletes the files under
    /// them. An item left claiming `Ready` opens nothing when it is played —
    /// it is not broken, it is a remote track that has to be fetched a second
    /// time. Only items with a database row behind them: one without has
    /// nowhere to be fetched from, and parking the cursor on it would be worse
    /// than letting it fail honestly.
    pub fn reset_items_with_missing_files(&self) -> Vec<(i64, QueueItemId)> {
        let mut pl = self.playlist.write();
        let mut reset = Vec::new();
        for item in pl.items.iter_mut() {
            let Some(db_id) = item.db_id else { continue };
            if !matches!(item.state, ItemState::Ready) {
                continue;
            }
            if item.path.exists() {
                continue;
            }
            item.state = ItemState::Pending;
            reset.push((db_id, item.id));
        }
        drop(pl);
        if !reset.is_empty() {
            self.pending_version.fetch_add(1, Ordering::AcqRel);
            self.bump_version();
        }
        reset
    }

    /// The item's path if it is `Ready`. A caller that can stream wants `item_playback_source`.
    pub fn item_path_if_ready(&self, id: QueueItemId) -> Option<PathBuf> {
        let pl = self.playlist.read();
        pl.items.iter().find(|item| item.id == id).and_then(|item| {
            if matches!(item.state, ItemState::Ready) {
                Some(item.path.clone())
            } else {
                None
            }
        })
    }

    pub fn is_cursor(&self, id: QueueItemId) -> bool {
        self.playlist.read().cursor == Some(id)
    }

    /// Get QueueItemIds of all playlist items sharing the same album as the given item.
    /// Matches on both album name and album artist to avoid false positives
    /// (e.g. two different "Greatest Hits" by different artists).
    pub fn same_album_item_ids(&self, id: QueueItemId) -> Vec<QueueItemId> {
        let pl = self.playlist.read();
        let Some(cursor) = pl.items.iter().find(|item| item.id == id) else {
            return vec![];
        };
        let album = cursor.album.clone();
        let album_artist = cursor.album_artist.clone();
        pl.items
            .iter()
            .filter(|item| {
                item.id != id && item.album == album && item.album_artist == album_artist
            })
            .map(|item| item.id)
            .collect()
    }

    /// Every playlist item still waiting for its file that has a track to
    /// fetch, as `(db_id, QueueItemId)`, in the order the player will reach
    /// it: from the cursor to the end, then from the top. What the download
    /// queue fetches, and in that order — the tracks before the cursor are
    /// the ones least likely to be played next.
    pub fn pending_downloads(&self) -> Vec<(i64, QueueItemId)> {
        let pl = self.playlist.read();
        let from = pl
            .cursor
            .and_then(|c| pl.items.iter().position(|item| item.id == c))
            .unwrap_or(0);
        let (before, after) = pl.items.split_at(from);
        after
            .iter()
            .chain(before)
            .filter(|item| matches!(item.state, ItemState::Pending))
            .filter_map(|item| item.db_id.map(|db_id| (db_id, item.id)))
            .collect()
    }

    /// Every entry with a library track, in the order `pending_downloads`
    /// gives, whatever its state: what the cache has to hold, downloaded or
    /// not, for the player to reach it.
    pub fn playback_order(&self) -> Vec<(i64, QueueItemId)> {
        let pl = self.playlist.read();
        let from = pl
            .cursor
            .and_then(|c| pl.items.iter().position(|item| item.id == c))
            .unwrap_or(0);
        let (before, after) = pl.items.split_at(from);
        after
            .iter()
            .chain(before)
            .filter_map(|item| item.db_id.map(|db_id| (db_id, item.id)))
            .collect()
    }

    /// Get the db_id for a specific playlist item.
    pub fn item_db_id(&self, id: QueueItemId) -> Option<i64> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .and_then(|item| item.db_id)
    }

    /// Get the load state of a specific playlist item.
    pub fn item_load_state(&self, id: QueueItemId) -> Option<LoadState> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .map(|item| self.load_state(item))
    }

    // --- Snapshot helpers for undo ---

    /// Get the full playlist snapshot (items + cursor) for undo of ClearPlaylist.
    pub fn snapshot_playlist(&self) -> (Vec<PlaylistItem>, Option<QueueItemId>) {
        let pl = self.playlist.read();
        (pl.items.clone(), pl.cursor)
    }

    /// Get an item by ID (for undo of RemoveFromPlaylist).
    pub fn get_item(&self, id: QueueItemId) -> Option<PlaylistItem> {
        let pl = self.playlist.read();
        pl.items.iter().find(|item| item.id == id).cloned()
    }

    /// Get the ID of the item immediately before the given ID (None if first).
    pub fn item_before(&self, id: QueueItemId) -> Option<QueueItemId> {
        let pl = self.playlist.read();
        let pos = pl.items.iter().position(|item| item.id == id)?;
        if pos == 0 {
            None
        } else {
            Some(pl.items[pos - 1].id)
        }
    }

    /// Put the items in exactly this order.
    ///
    /// Items not named keep their relative order and follow at the end, so a
    /// stale order cannot lose anything. The items themselves are moved, not
    /// rebuilt: their ids, load states and download progress are what the rest
    /// of the player is holding on to.
    pub fn reorder_to(&self, order: &[QueueItemId]) {
        let mut pl = self.playlist.write();
        let mut taken: Vec<Option<PlaylistItem>> = pl.items.drain(..).map(Some).collect();
        let mut sorted = Vec::with_capacity(taken.len());
        for id in order {
            if let Some(slot) = taken
                .iter_mut()
                .find(|i| i.as_ref().is_some_and(|i| i.id == *id))
                && let Some(item) = slot.take()
            {
                sorted.push(item);
            }
        }
        sorted.extend(taken.into_iter().flatten());
        pl.items = sorted;
        drop(pl);
        self.bump_content();
    }

    /// Every item's id and where it stood before shuffling, in queue order:
    /// what undoing a shuffle puts back.
    pub fn shuffle_order(&self) -> Vec<(QueueItemId, Option<u32>)> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .map(|item| (item.id, item.pre_shuffle))
            .collect()
    }

    /// Put back an order `shuffle_order` read, positions before shuffling
    /// included. Items not named keep theirs and follow, as in `reorder_to`.
    pub fn restore_shuffle_order(&self, order: &[(QueueItemId, Option<u32>)]) {
        let ids: Vec<QueueItemId> = order.iter().map(|(id, _)| *id).collect();
        self.reorder_to(&ids);
        let was: HashMap<QueueItemId, Option<u32>> = order.iter().copied().collect();
        let mut pl = self.playlist.write();
        for item in pl.items.iter_mut() {
            if let Some(pre) = was.get(&item.id) {
                item.pre_shuffle = *pre;
            }
        }
        drop(pl);
        self.bump_content();
    }

    /// Note where every item stands, then put the items after the cursor in a
    /// random order — all of them with no cursor. The playing item stays
    /// where it is, so nothing that is heard changes.
    pub fn shuffle_after_cursor(&self) {
        let mut pl = self.playlist.write();
        for (at, item) in pl.items.iter_mut().enumerate() {
            item.pre_shuffle = Some(at as u32);
        }
        let from = pl
            .cursor
            .and_then(|c| pl.items.iter().position(|item| item.id == c))
            .map_or(0, |at| at + 1);
        crate::helpers::shuffle(&mut pl.items[from..]);
        drop(pl);
        self.bump_content();
    }

    /// A queue arriving whole while shuffle is on — replaced, or added to an
    /// empty one — plays shuffled: `start` first, the rest in a random order
    /// after it, each item noting where it was given so turning shuffle off
    /// puts the queue back as it came. A queue that already carries those
    /// notes, a shuffled session restored, is left as it was saved.
    pub fn shuffle_from(&self, start: QueueItemId) {
        let mut pl = self.playlist.write();
        if pl.items.iter().any(|item| item.pre_shuffle.is_some()) {
            return;
        }
        for (at, item) in pl.items.iter_mut().enumerate() {
            item.pre_shuffle = Some(at as u32);
        }
        if let Some(at) = pl.items.iter().position(|item| item.id == start) {
            let item = pl.items.remove(at);
            pl.items.insert(0, item);
        }
        crate::helpers::shuffle(&mut pl.items[1..]);
        drop(pl);
        self.bump_content();
    }

    /// Put the items shuffle moved back in the order they had before it, in
    /// the places such items occupy now. An item added since keeps its place.
    pub fn unshuffle(&self) {
        let mut pl = self.playlist.write();
        let slots: Vec<usize> = (0..pl.items.len())
            .filter(|&at| pl.items[at].pre_shuffle.is_some())
            .collect();
        let mut moved: Vec<PlaylistItem> = slots.iter().map(|&at| pl.items[at].clone()).collect();
        moved.sort_by_key(|item| item.pre_shuffle);
        for (at, mut item) in slots.into_iter().zip(moved) {
            item.pre_shuffle = None;
            pl.items[at] = item;
        }
        drop(pl);
        self.bump_content();
    }

    /// For each ID, the ID of the item before it (or None if first), returned in
    /// playlist order regardless of the order `ids` arrives in.
    ///
    /// Undo replays these left to right, so an item whose recorded predecessor is
    /// also in `ids` must come after it — otherwise the predecessor is missing at
    /// replay time and the item lands at the end of the playlist instead.
    pub fn items_before(&self, ids: &[QueueItemId]) -> Vec<(QueueItemId, Option<QueueItemId>)> {
        use std::collections::HashSet;
        let wanted: HashSet<QueueItemId> = ids.iter().copied().collect();
        let pl = self.playlist.read();
        pl.items
            .iter()
            .enumerate()
            .filter(|(_, item)| wanted.contains(&item.id))
            .map(|(pos, item)| {
                let before = if pos == 0 {
                    None
                } else {
                    Some(pl.items[pos - 1].id)
                };
                (item.id, before)
            })
            .collect()
    }

    /// The nearest item before `id` that is not itself being removed — where
    /// playback resumes from after a batch delete that takes out the cursor.
    /// `None` means resume from the top of what survives.
    pub fn surviving_item_before(
        &self,
        id: QueueItemId,
        removed: &[QueueItemId],
    ) -> Option<QueueItemId> {
        use std::collections::HashSet;
        let removed: HashSet<QueueItemId> = removed.iter().copied().collect();
        let pl = self.playlist.read();
        let pos = pl.items.iter().position(|item| item.id == id)?;
        pl.items[..pos]
            .iter()
            .rev()
            .find(|item| !removed.contains(&item.id))
            .map(|item| item.id)
    }

    /// Restore a full playlist from snapshot (for redo of ClearPlaylist undo).
    pub fn restore_playlist(&self, items: Vec<PlaylistItem>, cursor: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        pl.items = items;
        pl.cursor = cursor;
        drop(pl);
        self.bump_content();
    }

    /// Remove multiple items by IDs.
    pub fn remove_items(&self, ids: &[QueueItemId]) {
        use std::collections::HashSet;
        let id_set: HashSet<QueueItemId> = ids.iter().copied().collect();
        let mut pl = self.playlist.write();
        pl.items.retain(|item| !id_set.contains(&item.id));
        if let Some(cursor) = pl.cursor
            && id_set.contains(&cursor)
        {
            pl.cursor = None;
        }
        drop(pl);
        self.bump_content();
    }

    /// Insert a single item after a given ID (or at front if None).
    pub fn insert_item_at(&self, item: PlaylistItem, after: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        let insert_at = match after {
            Some(after_id) => {
                match pl.items.iter().position(|i| i.id == after_id) {
                    Some(pos) => pos + 1,
                    None => pl.items.len(), // fallback
                }
            }
            None => 0,
        };
        pl.items.insert(insert_at, item);
        drop(pl);
        self.bump_content();
    }

    /// Move a single item to after `after` (or to front if None).
    pub fn move_item_to(&self, id: QueueItemId, after: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        let Some(from) = pl.items.iter().position(|item| item.id == id) else {
            return;
        };
        let item = pl.items.remove(from);
        let insert_at = match after {
            Some(after_id) => match pl.items.iter().position(|i| i.id == after_id) {
                Some(pos) => pos + 1,
                None => pl.items.len(),
            },
            None => 0,
        };
        pl.items.insert(insert_at, item);
        drop(pl);
        self.bump_content();
    }

    /// Batch move: reposition each item to after its given predecessor.
    /// Processes in order so earlier insertions don't corrupt later positions.
    pub fn move_items_to(&self, entries: &[(QueueItemId, Option<QueueItemId>)]) {
        for &(id, after) in entries {
            self.move_item_to(id, after);
        }
    }

    // --- Called from UI thread (read lock) ---

    /// Derive the visible queue from the playlist + cursor. O(n), and a copy
    /// of every row's text: for a front end that draws the whole queue. One
    /// that only needs to know what moved reads `queue_readings`.
    pub fn derive_visible_queue(&self) -> VisibleQueueSnapshot {
        let mut entries = Vec::with_capacity(self.playlist.read().items.len());
        let mut finished_count = 0;
        let mut has_playing = false;
        let mut queue_count = 0;
        self.each_visible(|item, place, reading| {
            match place {
                Place::Before => finished_count += 1,
                Place::Cursor => has_playing = true,
                Place::After => queue_count += 1,
            }
            entries.push(QueueEntry {
                id: item.id,
                db_id: item.db_id,
                playlist_entry_id: item.playlist_entry_id,
                path: item.path.clone(),
                title: item.title.clone(),
                artist: item.artist.clone(),
                album_artist: item.album_artist.clone(),
                album: item.album.clone(),
                year: item.year.clone(),
                codec: item.codec.clone(),
                track_number: item.track_number,
                disc: item.disc,
                duration_ms: reading.duration_ms,
                status: reading.status,
                download_progress: reading.download_progress,
                error: reading.error,
            });
        });

        VisibleQueueSnapshot {
            entries,
            finished_count,
            has_playing,
            queue_count,
        }
    }

    /// What each row of the visible queue says that can change without the
    /// queue being edited — its status, its duration, why it failed — in
    /// queue order, and none of its text.
    ///
    /// The cursor moving and a download landing change these and nothing
    /// else. A front end holding the rows already can find what moved from
    /// this at a small fraction of what deriving the whole queue costs.
    pub fn queue_readings(&self) -> Vec<QueueReading> {
        let mut readings = Vec::with_capacity(self.playlist.read().items.len());
        self.each_visible(|_, _, reading| readings.push(reading));
        readings
    }

    /// Walk the playlist under its read lock, with each item's place relative
    /// to the cursor and its reading. The one place a row's status is decided,
    /// so the derived queue and its readings cannot disagree.
    fn each_visible(&self, mut f: impl FnMut(&PlaylistItem, Place, QueueReading)) {
        // Read before the playlist lock — see current_download_fraction.
        let playing_duration_ms = self.track_info.read().as_ref().map(|ti| ti.duration_ms);
        // One pass over the transfers rather than one lookup, and a path
        // cloned, per row.
        let transfers: HashMap<i64, (u64, u64)> = self
            .downloads
            .readings()
            .into_iter()
            .map(|r| (r.track_id, (r.written, r.total)))
            .collect();
        let pl = self.playlist.read();

        let cursor_pos = match pl.cursor {
            Some(cid) => pl.items.iter().position(|item| item.id == cid),
            None => None,
        };

        for (i, item) in pl.items.iter().enumerate() {
            let place = match cursor_pos {
                Some(cp) if i == cp => Place::Cursor,
                Some(cp) if i < cp => Place::Before,
                _ => Place::After,
            };

            // The byte count is the download thread's own counter, written per
            // chunk without the playlist lock, so a transfer never bumps the
            // playlist version.
            let download_progress = match item.state {
                ItemState::Pending => item.db_id.and_then(|id| transfers.get(&id).copied()),
                _ => None,
            };
            let transferring = download_progress.is_some();

            let status = match place {
                Place::Cursor => QueueEntryStatus::at_cursor(&item.state, transferring),
                Place::Before => match &item.state {
                    ItemState::Ready => QueueEntryStatus::Played,
                    // A spinner only while bytes are moving: a track skipped
                    // past is not being fetched just for being behind the
                    // cursor.
                    ItemState::Pending if transferring => QueueEntryStatus::Downloading,
                    ItemState::Pending => QueueEntryStatus::Queued,
                    ItemState::Failed(_) => QueueEntryStatus::Failed,
                },
                Place::After => match &item.state {
                    ItemState::Ready => QueueEntryStatus::Queued,
                    ItemState::Pending if transferring => QueueEntryStatus::Downloading,
                    // Waiting its turn, not arriving: a spinner on every one
                    // of these read as the whole album downloading at once.
                    ItemState::Pending => QueueEntryStatus::Queued,
                    ItemState::Failed(_) => QueueEntryStatus::Failed,
                },
            };

            // The playing track's duration from its stream, when the item
            // had none of its own.
            let duration_ms = if status == QueueEntryStatus::Playing && item.duration_ms.is_none() {
                playing_duration_ms
            } else {
                item.duration_ms
            };

            f(
                item,
                place,
                QueueReading {
                    id: item.id,
                    db_id: item.db_id,
                    status,
                    duration_ms,
                    download_progress,
                    error: match &item.state {
                        ItemState::Failed(reason) => Some(reason.clone()),
                        _ => None,
                    },
                },
            );
        }
    }

    /// At most `max` items from `before` ahead of the cursor, and the cursor.
    ///
    /// What a window of the queue needs, without copying the rest of it: on a
    /// queue of tens of thousands, `snapshot_playlist` is a copy of every row
    /// for the sake of a few hundred.
    pub fn playlist_window(
        &self,
        before: usize,
        max: usize,
    ) -> (Vec<PlaylistItem>, Option<QueueItemId>) {
        let pl = self.playlist.read();
        let at = pl
            .cursor
            .and_then(|c| pl.items.iter().position(|i| i.id == c))
            .unwrap_or(0);
        let start = at.saturating_sub(before);
        let end = pl.items.len().min(start + max);
        (pl.items[start..end].to_vec(), pl.cursor)
    }
}

/// Where a row stands relative to the cursor.
#[derive(Clone, Copy)]
enum Place {
    Before,
    Cursor,
    After,
}

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

    // --- helpers ---

    fn make_item(title: &str, state: ItemState) -> PlaylistItem {
        PlaylistItem {
            playlist_entry_id: None,
            id: QueueItemId::new(),
            db_id: None,
            path: PathBuf::from(format!("/music/{title}.flac")),
            title: title.to_string(),
            artist: "Artist".to_string(),
            album_artist: "Artist".to_string(),
            album: "Album".to_string(),
            year: None,
            codec: Some("FLAC".to_string()),
            track_number: None,
            disc: None,
            duration_ms: Some(200_000),
            state,
            pre_shuffle: None,
        }
    }

    /// An item with a transfer running against it, told to the state's store
    /// the way the downloader tells it. Returns the transfer's byte feed.
    fn downloading_item(
        state: &SharedPlayerState,
        title: &str,
        total: u64,
    ) -> (PlaylistItem, Arc<ByteFeed>) {
        static NEXT_TRACK: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
        let mut item = make_item(title, ItemState::Pending);
        item.db_id = Some(NEXT_TRACK.fetch_add(1, Ordering::Relaxed));
        let feed = start_transfer(state, &item, total);
        (item, feed)
    }

    /// Claim, announce and start the transfer for `item`'s track.
    fn start_transfer(state: &SharedPlayerState, item: &PlaylistItem, total: u64) -> Arc<ByteFeed> {
        let track_id = item.db_id.expect("a transfer is for a library track");
        let store = state.downloads();
        store.claim(track_id, Some(item.id));
        let feed = store.announce(
            track_id,
            item.title.clone(),
            String::new(),
            PathBuf::from(format!("/cache/{}.flac.part", item.title)),
            PathBuf::from(format!("/cache/{}.flac", item.title)),
        );
        store.started(track_id, total);
        feed
    }

    fn ready_item(title: &str) -> PlaylistItem {
        make_item(title, ItemState::Ready)
    }

    fn pending_item(title: &str) -> PlaylistItem {
        make_item(title, ItemState::Pending)
    }

    fn failed_item(title: &str) -> PlaylistItem {
        make_item(title, ItemState::Failed("nope".into()))
    }

    const DURATION_MS: u64 = 32_523_787;

    /// A nine-hour track under the cursor, `downloaded` bytes of `total` in.
    /// `total` of 0 stands for a server that sent no Content-Length.
    fn streaming_state(
        downloaded: u64,
        total: u64,
        bitrate_kbps: Option<u32>,
    ) -> Arc<SharedPlayerState> {
        streaming_state_with_duration(downloaded, total, bitrate_kbps, DURATION_MS)
    }

    /// The same, but saying what the container managed to state about itself.
    /// A partial Ogg states nothing, which is zero here.
    fn streaming_state_with_duration(
        downloaded: u64,
        total: u64,
        bitrate_kbps: Option<u32>,
        container_duration_ms: u64,
    ) -> Arc<SharedPlayerState> {
        let mut item = make_item("train", ItemState::Pending);
        item.db_id = Some(1);
        let id = item.id;
        let path = item.path.clone();

        let state = SharedPlayerState::new();
        start_transfer(&state, &item, total).set(downloaded);
        state.add_items(vec![item]);
        state.set_cursor(Some(id));
        state.set_track_info(Some(TrackInfo {
            id,
            path,
            codec: "Opus".into(),
            sample_rate: 48_000,
            bit_depth: None,
            bitrate_kbps,
            channels: 2,
            duration_ms: container_duration_ms,
        }));
        state
    }

    // --- seekable_ms ---

    #[test]
    fn a_track_on_disk_is_seekable_end_to_end() {
        let item = ready_item("done");
        let id = item.id;
        let path = item.path.clone();
        let state = SharedPlayerState::new();
        state.add_items(vec![item]);
        state.set_cursor(Some(id));
        state.set_track_info(Some(TrackInfo {
            id,
            path,
            codec: "FLAC".into(),
            sample_rate: 44_100,
            bit_depth: Some(16),
            bitrate_kbps: None,
            channels: 2,
            duration_ms: 200_000,
        }));

        assert_eq!(state.seekable_ms(), 200_000);
        // Nothing to draw a boundary for, so front ends are told there isn't one.
        assert_eq!(state.seek_ceiling_ms(), None);
    }

    #[test]
    fn a_downloading_track_is_seekable_as_far_as_its_bytes_reach() {
        // A quarter of a nine-hour file in: a quarter of the way through it,
        // less the margin the byte-to-time estimate is worth.
        let state = streaming_state(100, 400, None);
        assert_eq!(state.seekable_ms(), 32_523_787 / 4 - SEEK_SAFETY_MS);
        assert_eq!(
            state.seek_ceiling_ms(),
            Some(32_523_787 / 4 - SEEK_SAFETY_MS)
        );
    }

    #[test]
    fn a_transfer_without_a_content_length_falls_back_to_bitrate() {
        // No total to take a fraction of. 128 kbps is 128 bits per ms, so a
        // megabyte is 8 388 608 bits and a little over 65 seconds.
        let state = streaming_state(1024 * 1024, 0, Some(128));
        assert_eq!(state.seekable_ms(), 1024 * 1024 * 8 / 128 - SEEK_SAFETY_MS);
    }

    #[test]
    fn nothing_to_estimate_from_allows_no_forward_seek() {
        // Neither a length nor a bitrate: anywhere past the playhead is a
        // guess, and a guess that lands past the write head is a stall.
        let state = streaming_state(1024 * 1024, 0, None);
        state.set_position_ms(12_000);
        assert_eq!(state.seekable_ms(), 12_000);
    }

    #[test]
    fn the_seekable_extent_never_exceeds_the_track() {
        // A download reporting more bytes than it advertised must not offer a
        // seek past the end of the music.
        let state = streaming_state(500, 400, None);
        assert_eq!(state.seekable_ms(), 32_523_787);
    }

    #[test]
    fn nothing_playing_is_seekable_nowhere() {
        assert_eq!(SharedPlayerState::new().seekable_ms(), 0);
        assert_eq!(SharedPlayerState::new().seek_ceiling_ms(), None);
    }

    #[test]
    fn a_container_that_cannot_state_its_duration_cannot_be_seeked() {
        // A partial Ogg keeps its duration in a last page that has not arrived,
        // so it opens and plays but has nothing to seek against. Half the bytes
        // being present does not change that.
        let state = streaming_state_with_duration(200, 400, Some(128), 0);
        assert_eq!(state.seekable_ms(), 0);
    }

    #[test]
    fn the_library_duration_stands_in_for_a_silent_container() {
        // What is shown on the transport, so nine hours of music does not read
        // as 0:00 while it caches.
        let state = streaming_state_with_duration(200, 400, Some(128), 0);
        assert_eq!(state.duration_ms(), 200_000, "the item's own figure");
        // And it is a display figure only — it grants no seeking.
        assert_eq!(state.seekable_ms(), 0);
        assert_eq!(state.seek_ceiling_ms(), Some(0));
    }

    #[test]
    fn the_container_duration_wins_where_there_is_one() {
        let state = streaming_state(200, 400, None);
        assert_eq!(state.duration_ms(), DURATION_MS);
    }

    #[test]
    fn the_download_landing_restores_seeking() {
        // The sequence the whole design turns on: a track that opened without a
        // duration gets one when the finished file is re-read, and is seekable
        // end to end from that moment — no restart, no handover.
        let state = streaming_state_with_duration(400, 400, Some(128), 0);
        assert_eq!(state.seekable_ms(), 0);

        // What the downloader does when the bytes land: settle the transfer,
        // then say the file is playable. In that order — while the store still
        // says a transfer is running, it is.
        let id = state.cursor().expect("cursor");
        let _ =
            crate::remote::downloads::settle(&state, 1, &Ok(PathBuf::from("/cache/train.flac")));
        assert_eq!(state.item_state(id), Some(ItemState::Ready));
        let info = state.track_info().expect("track info");
        state.set_track_info(Some(TrackInfo {
            duration_ms: DURATION_MS,
            ..info
        }));

        assert_eq!(state.seekable_ms(), DURATION_MS);
        assert_eq!(state.seek_ceiling_ms(), None, "no boundary left to draw");
    }

    // --- advance_cursor_loadable ---

    #[test]
    fn advance_parks_on_a_still_downloading_track() {
        // A track that has not arrived yet must hold the cursor, not be skipped:
        // skipping it drops it from the queue for good, and it is the item whose
        // TrackReady has to resume playback.
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = pending_item("track-1");
        let item2 = ready_item("track-2");
        let (id0, id1) = (item0.id, item1.id);

        state.add_items(vec![item0, item1, item2]);

        assert_eq!(state.advance_cursor_loadable(), Some(id0));
        assert_eq!(state.advance_cursor_loadable(), Some(id1));
        assert_eq!(state.cursor(), Some(id1));
    }

    #[test]
    fn advance_skips_failed_items() {
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = failed_item("track-1");
        let item2 = ready_item("track-2");
        let (id0, id2) = (item0.id, item2.id);

        state.add_items(vec![item0, item1, item2]);
        state.set_cursor(Some(id0));

        assert_eq!(state.advance_cursor_loadable(), Some(id2));
    }

    #[test]
    fn advance_stops_at_end_of_playlist() {
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = ready_item("track-1");
        let id1 = item1.id;

        state.add_items(vec![item0, item1]);
        state.set_cursor(Some(id1));

        assert_eq!(state.advance_cursor_loadable(), None);
        assert_eq!(
            state.cursor(),
            Some(id1),
            "cursor unchanged on a failed advance"
        );
    }

    #[test]
    fn advance_with_only_failed_items_returns_none() {
        let state = SharedPlayerState::new();
        state.add_items(vec![failed_item("bad-0"), failed_item("bad-1")]);

        assert_eq!(state.advance_cursor_loadable(), None);
    }

    #[test]
    fn advance_from_a_vanished_cursor_does_not_restart_the_queue() {
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = ready_item("track-1");
        let id0 = item0.id;

        state.add_items(vec![item0, item1]);
        let ghost = QueueItemId::new();
        state.set_cursor(Some(ghost));

        assert_eq!(state.advance_cursor_loadable(), None);
        assert_ne!(state.cursor(), Some(id0));
    }

    // --- lookahead_after ---

    fn chosen_after(state: &SharedPlayerState, id: QueueItemId) -> Option<QueueItemId> {
        state
            .lookahead_after(id)
            .and_then(|step| step.chosen)
            .map(|(id, _)| id)
    }

    #[test]
    fn a_step_stops_at_a_track_still_arriving() {
        let state = SharedPlayerState::new();
        let a = ready_item("a");
        let b = PlaylistItem {
            state: ItemState::Pending,
            ..ready_item("b")
        };
        let c = ready_item("c");
        let (ida, idb) = (a.id, b.id);
        state.add_items(vec![a, b, c]);

        let step = state.lookahead_after(ida).unwrap();
        assert_eq!(step.next, Some(idb));
        assert!(step.chosen.is_none(), "c is not queued over it");

        state.update_item_state(idb, ItemState::Ready);
        assert!(
            state.still_follows(&step),
            "its landing is not an edit: the advance plays it"
        );

        state.add_items(vec![ready_item("d")]);
        assert!(state.still_follows(&step), "nor is adding after it");

        state.insert_items_after(vec![ready_item("next")], ida);
        assert!(!state.still_follows(&step), "a track put before it is");
    }

    #[test]
    fn a_step_passes_over_failed_tracks() {
        let state = SharedPlayerState::new();
        let a = ready_item("a");
        let failed = PlaylistItem {
            state: ItemState::Failed("gone".into()),
            ..ready_item("failed")
        };
        let c = ready_item("c");
        let (ida, idc) = (a.id, c.id);
        state.add_items(vec![a, failed, c]);

        let step = state.lookahead_after(ida).unwrap();
        assert_eq!(step.chosen.as_ref().map(|(id, _)| *id), Some(idc));

        let another = PlaylistItem {
            state: ItemState::Failed("gone".into()),
            ..ready_item("another")
        };
        state.insert_items_after(vec![another], ida);
        assert!(
            state.still_follows(&step),
            "another failed track before it changes nothing"
        );

        let arriving = PlaylistItem {
            state: ItemState::Pending,
            ..ready_item("arriving")
        };
        state.insert_items_after(vec![arriving], ida);
        assert!(!state.still_follows(&step), "a track still arriving does");
    }

    #[test]
    fn a_step_breaks_when_what_it_chose_moves_ahead_of_it() {
        let state = SharedPlayerState::new();
        let (a, c) = (ready_item("a"), ready_item("c"));
        let (ida, idc) = (a.id, c.id);
        state.add_items(vec![a, c]);
        let step = state.lookahead_after(ida).unwrap();
        state.move_item(idc, ida, false);
        assert!(!state.still_follows(&step));
    }

    #[test]
    fn a_step_to_the_end_of_the_queue_breaks_when_a_track_is_added() {
        let state = SharedPlayerState::new();
        let a = ready_item("a");
        let ida = a.id;
        state.add_items(vec![a]);
        let step = state.lookahead_after(ida).unwrap();
        assert!(step.chosen.is_none());
        assert!(state.still_follows(&step));
        state.add_items(vec![ready_item("b")]);
        assert!(!state.still_follows(&step));
    }

    #[test]
    fn peek_after_a_removed_item_returns_none() {
        // The decode thread's lookahead runs seconds ahead of what is audible.
        // Removing the track it is pre-decoding must end the lookahead, not send
        // it back to the top of the queue.
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = ready_item("track-1");
        let item2 = ready_item("track-2");
        let (id0, id1, id2) = (item0.id, item1.id, item2.id);

        state.add_items(vec![item0, item1, item2]);
        assert_eq!(chosen_after(&state, id1), Some(id2));

        state.remove_item(id2);
        assert!(
            state.lookahead_after(id2).is_none(),
            "a vanished reference must not resolve to the head of the queue"
        );
        assert_ne!(chosen_after(&state, id2), Some(id0));
    }

    #[test]
    fn the_lookahead_steps_over_a_track_that_failed() {
        let state = SharedPlayerState::new();
        let playing = ready_item("playing");
        let failed = failed_item("failed");
        let after = ready_item("after");
        let (playing_id, after_id) = (playing.id, after.id);
        state.add_items(vec![playing, failed, after]);

        assert_eq!(chosen_after(&state, playing_id), Some(after_id));
    }

    // --- surviving_item_before ---

    fn repeating(state: &SharedPlayerState, repeat: Repeat) {
        state.set_play_mode(PlayMode {
            shuffle: false,
            repeat,
        });
    }

    #[test]
    fn a_step_from_the_last_item_wraps_only_when_the_queue_repeats() {
        let state = SharedPlayerState::new();
        let items: Vec<_> = ["a", "b"].map(ready_item).into();
        let (a, b) = (items[0].id, items[1].id);
        state.add_items(items);

        assert_eq!(state.lookahead_after(b).unwrap().next, None);
        repeating(&state, Repeat::Queue);
        let step = state.lookahead_after(b).unwrap();
        assert_eq!((step.next, step.wrapped), (Some(a), true));
        assert!(state.still_follows(&step));

        let later = ready_item("later");
        state.add_items(vec![later.clone()]);
        assert!(!state.still_follows(&step), "something follows b now");
        state.remove_items(&[later.id]);
        repeating(&state, Repeat::Off);
        assert!(!state.still_follows(&step), "nor does repeat off wrap");
    }

    #[test]
    fn repeating_one_steps_to_the_same_item_but_an_advance_moves_on() {
        let state = SharedPlayerState::new();
        let items: Vec<_> = ["a", "b"].map(ready_item).into();
        let (a, b) = (items[0].id, items[1].id);
        state.add_items(items);
        repeating(&state, Repeat::One);

        let step = state.lookahead_after(a).unwrap();
        assert_eq!((step.next, step.wrapped), (Some(a), false));
        state.set_cursor(Some(a));
        assert_eq!(state.advance_cursor_loadable(), Some(b));
        assert_eq!(
            state.advance_cursor_loadable(),
            Some(a),
            "round, as repeating"
        );
    }

    #[test]
    fn previous_from_the_first_item_wraps_only_while_repeating() {
        let state = SharedPlayerState::new();
        let items: Vec<_> = ["a", "b", "c"].map(ready_item).into();
        let (a, c) = (items[0].id, items[2].id);
        state.add_items(items);

        state.set_cursor(Some(a));
        assert!(state.retreat_cursor().is_none());
        for repeat in [Repeat::Queue, Repeat::One] {
            repeating(&state, repeat);
            state.set_cursor(Some(a));
            assert_eq!(
                state.retreat_cursor().map(|(id, _)| id),
                Some(c),
                "{repeat:?}"
            );
        }
    }

    #[test]
    fn a_removed_item_has_nothing_after_it_even_when_the_queue_repeats() {
        let state = SharedPlayerState::new();
        let items: Vec<_> = ["a", "b"].map(ready_item).into();
        let b = items[1].id;
        state.add_items(items);
        repeating(&state, Repeat::Queue);

        state.set_cursor(Some(b));
        state.remove_item(b);
        assert!(state.lookahead_after(b).is_none());
        state.set_cursor(Some(b));
        assert_eq!(state.advance_cursor_loadable(), None);
    }

    #[test]
    fn a_wrap_passes_over_failed_items() {
        let state = SharedPlayerState::new();
        let items = vec![failed_item("a"), ready_item("b"), ready_item("c")];
        let (b, c) = (items[1].id, items[2].id);
        state.add_items(items);
        repeating(&state, Repeat::Queue);

        assert_eq!(state.lookahead_after(c).unwrap().next, Some(b));
    }

    #[test]
    fn surviving_predecessor_skips_items_being_removed() {
        let state = SharedPlayerState::new();
        let items: Vec<_> = (0..4).map(|i| ready_item(&format!("track-{i}"))).collect();
        let ids: Vec<_> = items.iter().map(|i| i.id).collect();
        state.add_items(items);

        // Deleting 1..=3 leaves 0 as the resume point for a cursor on 3.
        assert_eq!(
            state.surviving_item_before(ids[3], &ids[1..4]),
            Some(ids[0])
        );
        // Deleting everything from the top leaves nothing to resume after.
        assert_eq!(state.surviving_item_before(ids[2], &ids), None);
    }

    // --- retreat_cursor ---

    #[test]
    fn test_retreat_cursor_goes_to_previous_item() {
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = ready_item("track-1");
        let id0 = item0.id;
        let id1 = item1.id;

        state.add_items(vec![item0, item1]);
        state.set_cursor(Some(id1));

        let result = state.retreat_cursor();
        assert!(result.is_some(), "expected to retreat to previous item");
        assert_eq!(result.unwrap().0, id0, "should retreat to first item");
        assert_eq!(state.cursor(), Some(id0));
    }

    #[test]
    fn test_retreat_cursor_returns_none_when_at_first_item() {
        let state = SharedPlayerState::new();
        let item0 = ready_item("only-track");
        let id0 = item0.id;

        state.add_items(vec![item0]);
        state.set_cursor(Some(id0));

        let result = state.retreat_cursor();
        assert!(result.is_none(), "cannot retreat before the first item");
        // Cursor stays on the first item.
        assert_eq!(state.cursor(), Some(id0));
    }

    #[test]
    fn test_retreat_cursor_returns_none_when_cursor_is_unset() {
        let state = SharedPlayerState::new();
        state.add_items(vec![ready_item("track-0")]);

        let result = state.retreat_cursor();
        assert!(
            result.is_none(),
            "retreat with no cursor should return None"
        );
    }

    // --- derive_visible_queue ---

    #[test]
    fn test_derive_visible_queue_statuses() {
        // playlist: [played, playing, queued]
        let state = SharedPlayerState::new();
        let item0 = ready_item("played-track");
        let item1 = ready_item("playing-track");
        let item2 = ready_item("queued-track");
        let id1 = item1.id;

        state.add_items(vec![item0, item1, item2]);
        state.set_cursor(Some(id1));

        let snap = state.derive_visible_queue();

        assert_eq!(snap.entries.len(), 3);
        assert_eq!(snap.entries[0].status, QueueEntryStatus::Played);
        assert_eq!(snap.entries[1].status, QueueEntryStatus::Playing);
        assert_eq!(snap.entries[2].status, QueueEntryStatus::Queued);
        assert!(snap.has_playing);
        assert_eq!(snap.finished_count, 1);
        assert_eq!(snap.queue_count, 1);
    }

    #[test]
    fn test_derive_visible_queue_downloading_statuses() {
        // Downloading reads the same at the cursor as after it: bytes are
        // moving, and the row has progress to draw.
        let state = SharedPlayerState::new();
        let (dl_cursor, _) = downloading_item(&state, "downloading-at-cursor", 1_000_000);
        let (dl_queued, _) = downloading_item(&state, "downloading-queued", 500_000);
        let id_cursor = dl_cursor.id;

        state.add_items(vec![dl_cursor, dl_queued]);
        state.set_cursor(Some(id_cursor));

        let snap = state.derive_visible_queue();

        assert_eq!(snap.entries[0].status, QueueEntryStatus::Downloading);
        assert_eq!(snap.entries[1].status, QueueEntryStatus::Downloading);
    }

    #[test]
    fn a_cursor_waiting_its_turn_is_priority_pending() {
        let state = SharedPlayerState::new();
        let item = pending_item("waiting");
        let id = item.id;
        state.add_items(vec![item]);
        state.set_cursor(Some(id));

        let snap = state.derive_visible_queue();
        assert_eq!(snap.entries[0].status, QueueEntryStatus::PriorityPending);
    }

    #[test]
    fn a_second_entry_for_a_track_reads_the_transfer_running_for_it() {
        // One transfer per track: the entry queued second has none of its own,
        // and streams and reports from the first one's.
        let state = SharedPlayerState::new();
        let (first, bytes) = downloading_item(&state, "twice", 1_000_000);
        bytes.set(STREAM_THRESHOLD);
        let mut again = pending_item("twice");
        again.db_id = first.db_id;
        let again_id = again.id;
        state.add_items(vec![first, again]);

        assert!(matches!(
            state.item_load_state(again_id),
            Some(LoadState::Downloading { .. })
        ));
        assert!(matches!(
            state.item_playback_source(again_id),
            Some(PlaybackSource::Streaming { .. })
        ));
    }

    /// The saved queue is rewritten when its contents move, and only then:
    /// a track change or a download landing is a position save.
    #[test]
    fn only_a_change_to_what_is_saved_moves_the_content_version() {
        let state = SharedPlayerState::new();
        let a = make_item("a", ItemState::Pending);
        let b = make_item("b", ItemState::Ready);
        let (a_id, b_id) = (a.id, b.id);

        let start = state.content_version();
        state.add_items(vec![a, b]);
        let added = state.content_version();
        assert_ne!(added, start);

        state.set_cursor(Some(a_id));
        state.update_item_state(a_id, ItemState::Ready);
        state.advance_cursor_loadable();
        state.retreat_cursor();
        assert_eq!(state.content_version(), added);
        assert_eq!(state.cursor_path(), Some(PathBuf::from("/music/a.flac")));

        state.move_item_to(b_id, None);
        assert_ne!(state.content_version(), added);
    }

    #[test]
    fn progress_follows_the_counter_without_touching_the_playlist() {
        // The download thread writes bytes and nothing else. A queue derived
        // afterwards must see them — the version has not moved, and the load
        // state it was given is the one it still holds.
        let state = SharedPlayerState::new();
        let (item, bytes) = downloading_item(&state, "downloading", 1_000);
        state.add_items(vec![item]);

        let version = state.playlist_version();
        bytes.set(250);

        let snap = state.derive_visible_queue();
        assert_eq!(snap.entries[0].download_progress, Some((250, 1_000)));
        assert_eq!(
            state.playlist_version(),
            version,
            "progress must not read as a queue mutation"
        );
        assert_eq!(state.downloads().readings()[0].written, 250);
    }

    #[test]
    fn test_derive_visible_queue_no_cursor_all_queued() {
        let state = SharedPlayerState::new();
        state.add_items(vec![ready_item("a"), ready_item("b"), ready_item("c")]);

        let snap = state.derive_visible_queue();

        assert_eq!(snap.entries.len(), 3);
        for entry in &snap.entries {
            assert_eq!(entry.status, QueueEntryStatus::Queued);
        }
        assert!(!snap.has_playing);
        assert_eq!(snap.finished_count, 0);
        assert_eq!(snap.queue_count, 3);
    }

    // --- same_album_item_ids ---

    fn make_album_item(title: &str, album: &str, album_artist: &str) -> PlaylistItem {
        PlaylistItem {
            playlist_entry_id: None,
            id: QueueItemId::new(),
            db_id: None,
            path: PathBuf::from(format!("/music/{title}.flac")),
            title: title.to_string(),
            artist: "Artist".to_string(),
            album_artist: album_artist.to_string(),
            album: album.to_string(),
            year: None,
            codec: Some("FLAC".to_string()),
            track_number: None,
            disc: None,
            duration_ms: Some(200_000),
            state: ItemState::Ready,
            pre_shuffle: None,
        }
    }

    #[test]
    fn test_same_album_item_ids_returns_album_mates() {
        let state = SharedPlayerState::new();
        let a1 = make_album_item("A1", "Album A", "Artist A");
        let a2 = make_album_item("A2", "Album A", "Artist A");
        let b1 = make_album_item("B1", "Album B", "Artist B");
        let a3 = make_album_item("A3", "Album A", "Artist A");

        let id_a1 = a1.id;
        let id_a2 = a2.id;
        let id_a3 = a3.id;

        state.add_items(vec![a1, a2, b1, a3]);

        let mates = state.same_album_item_ids(id_a1);
        assert_eq!(mates.len(), 2);
        assert!(mates.contains(&id_a2));
        assert!(mates.contains(&id_a3));
    }

    #[test]
    fn test_same_album_item_ids_distinguishes_album_artists() {
        // Two albums named the same but by different artists — should NOT match.
        let state = SharedPlayerState::new();
        let a1 = make_album_item("A1", "Greatest Hits", "Artist A");
        let b1 = make_album_item("B1", "Greatest Hits", "Artist B");

        let id_a1 = a1.id;

        state.add_items(vec![a1, b1]);

        let mates = state.same_album_item_ids(id_a1);
        assert!(mates.is_empty(), "different album_artist should not match");
    }

    #[test]
    fn test_same_album_item_ids_unknown_id_returns_empty() {
        let state = SharedPlayerState::new();
        state.add_items(vec![ready_item("track-0")]);

        let bogus = QueueItemId::new();
        let mates = state.same_album_item_ids(bogus);
        assert!(mates.is_empty());
    }

    // --- update_item_metadata ---

    #[test]
    fn test_update_item_metadata_leaves_library_tags_alone() {
        let state = SharedPlayerState::new();
        let mut item = make_album_item("A1", "Nite Versions (mixed)", "Soulwax");
        item.db_id = Some(29615);
        let id = item.id;
        state.add_items(vec![item]);

        state.update_item_metadata(
            id,
            "[unknown]".into(),
            "Soulwax".into(),
            "Soulwax".into(),
            "Nite Versions".into(),
            Some(54_000),
        );

        let pl = state.playlist.read();
        assert_eq!(pl.items[0].album, "Nite Versions (mixed)");
        assert_eq!(pl.items[0].title, "A1");
        assert_eq!(pl.items[0].duration_ms, Some(54_000));
    }

    #[test]
    fn test_update_item_metadata_fills_in_an_item_with_nothing_behind_it() {
        let state = SharedPlayerState::new();
        let item = make_album_item("A1", "", "");
        let id = item.id;
        state.add_items(vec![item]);

        state.update_item_metadata(
            id,
            "Teachers".into(),
            "Soulwax".into(),
            "Soulwax".into(),
            "Nite Versions".into(),
            Some(148_000),
        );

        let pl = state.playlist.read();
        assert_eq!(pl.items[0].title, "Teachers");
        assert_eq!(pl.items[0].album, "Nite Versions");
        assert_eq!(pl.items[0].duration_ms, Some(148_000));
    }

    /// A download landing with tags that say what the queue already held is
    /// not an edit: nothing is saved again and no client reads the queue again.
    /// Nor is one that only corrects the duration — a server's whole seconds
    /// against the file's milliseconds — which clients take as a change to that
    /// row's reading.
    #[test]
    fn test_update_item_metadata_is_an_edit_only_for_new_tags() {
        let state = SharedPlayerState::new();
        let mut item = make_album_item("A1", "Nite Versions", "Soulwax");
        item.db_id = Some(1);
        let id = item.id;
        state.add_items(vec![item]);
        let content = state.content_version();
        let version = state.playlist_version();

        let land = |duration_ms| {
            state.update_item_metadata(
                id,
                "A1".into(),
                "Soulwax".into(),
                "Soulwax".into(),
                "Nite Versions".into(),
                Some(duration_ms),
            )
        };
        land(200_000);
        assert_eq!(state.content_version(), content);
        assert_eq!(state.playlist_version(), version);

        land(200_417);
        assert_eq!(state.content_version(), content);
        assert_ne!(state.playlist_version(), version);
        assert_eq!(state.queue_readings()[0].duration_ms, Some(200_417));

        let mut untagged = make_album_item("", "", "");
        let untagged_id = untagged.id;
        untagged.db_id = None;
        state.add_items(vec![untagged]);
        let content = state.content_version();
        state.update_item_metadata(
            untagged_id,
            "Teachers".into(),
            "Soulwax".into(),
            "Soulwax".into(),
            "Nite Versions".into(),
            None,
        );
        assert_ne!(state.content_version(), content);
    }

    // --- move_item_to ---

    #[test]
    fn test_move_item_to_reorders_playlist() {
        // Start: [A, B, C]. Move C to after A → [A, C, B].
        let state = SharedPlayerState::new();
        let item_a = ready_item("A");
        let item_b = ready_item("B");
        let item_c = ready_item("C");
        let id_a = item_a.id;
        let id_b = item_b.id;
        let id_c = item_c.id;

        state.add_items(vec![item_a, item_b, item_c]);
        state.move_item_to(id_c, Some(id_a));

        let (items, _) = state.snapshot_playlist();
        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
        assert_eq!(titles, vec!["A", "C", "B"]);
        assert_eq!(items[0].id, id_a);
        assert_eq!(items[1].id, id_c);
        assert_eq!(items[2].id, id_b);
    }

    #[test]
    fn test_move_item_to_front_when_after_is_none() {
        // Start: [A, B, C]. Move C to front (after=None) → [C, A, B].
        let state = SharedPlayerState::new();
        let item_a = ready_item("A");
        let item_b = ready_item("B");
        let item_c = ready_item("C");
        let id_c = item_c.id;

        state.add_items(vec![item_a, item_b, item_c]);
        state.move_item_to(id_c, None);

        let (items, _) = state.snapshot_playlist();
        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
        assert_eq!(titles, vec!["C", "A", "B"]);
    }

    // --- move_items (batch) ---

    #[test]
    fn test_move_items_batch_preserves_relative_order() {
        // Start: [A, B, C, D]. Move [A, C] after D → [B, D, A, C].
        let state = SharedPlayerState::new();
        let item_a = ready_item("A");
        let item_b = ready_item("B");
        let item_c = ready_item("C");
        let item_d = ready_item("D");
        let id_a = item_a.id;
        let id_b = item_b.id;
        let id_c = item_c.id;
        let id_d = item_d.id;

        state.add_items(vec![item_a, item_b, item_c, item_d]);
        state.move_items(&[id_a, id_c], id_d, true);

        let (items, _) = state.snapshot_playlist();
        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
        assert_eq!(titles, vec!["B", "D", "A", "C"]);
        assert_eq!(items[0].id, id_b);
        assert_eq!(items[1].id, id_d);
        assert_eq!(items[2].id, id_a);
        assert_eq!(items[3].id, id_c);
    }

    // --- pending_downloads ---

    #[test]
    fn test_pending_downloads_collects_pending_with_db_id() {
        let state = SharedPlayerState::new();
        let mut item_a = ready_item("local");
        item_a.db_id = None;

        let mut item_b = pending_item("remote-1");
        item_b.db_id = Some(10);
        let id_b = item_b.id;

        let mut item_c = ready_item("cached");
        item_c.db_id = Some(20);

        let mut item_d = pending_item("remote-2");
        item_d.db_id = Some(30);
        let id_d = item_d.id;

        // Pending without db_id — should NOT appear (no way to download).
        let item_e = pending_item("orphan");

        state.add_items(vec![item_a, item_b, item_c, item_d, item_e]);

        let pending = state.pending_downloads();
        assert_eq!(pending.len(), 2);
        assert_eq!(pending[0], (10, id_b));
        assert_eq!(pending[1], (30, id_d));

        // From the cursor on, then from the top: playing the fourth, the
        // tracks before it come last.
        state.set_cursor(Some(id_d));
        assert_eq!(state.pending_downloads(), vec![(30, id_d), (10, id_b)]);
    }

    #[test]
    fn test_item_db_id_and_load_state() {
        let state = SharedPlayerState::new();
        let mut item = pending_item("track");
        item.db_id = Some(42);
        let id = item.id;
        state.add_items(vec![item]);

        assert_eq!(state.item_db_id(id), Some(42));
        assert!(matches!(
            state.item_load_state(id),
            Some(LoadState::Pending)
        ));

        state.update_item_state(id, ItemState::Ready);
        assert!(matches!(state.item_load_state(id), Some(LoadState::Ready)));
    }
}