bdinfo-rs-core 2.0.0

Memory-safe Blu-ray (BDMV/M2TS) disc and stream analyzer.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
//! Disc-level orchestration: discovery plus the metadata scan.
//!
//! [`BdRom::open`] locates the BD directories case-insensitively through the
//! [`crate::vfs`] seam, reads the disc flags (3D/UHD/BD+/BD-Java/PSP), the
//! recursive byte [`size`](BdRom::size), the volume label and disc title, then
//! scans the clip and playlist metadata into the per-playlist
//! [`PlaylistSummary`] rows the report emits.
//!
//! No disc-level field depends on packet data — file sizes come from the
//! filesystem (`stat`), per-playlist stream counts from the clip-information
//! (`*.clpi`) files. The file parsing lives in [`super::clpi`]/[`super::mpls`];
//! this module is the disc-level glue over them. The optional M2TS packet scan
//! ([`super::m2ts`]) only enriches the per-stream codec detail.
//!
//! Input conventions:
//! * **Volume label** — for folder input the label is the disc-root directory name (a folder
//!   carries no real volume label). The genuine volume-label case is the `.iso`/UDF path, which
//!   reads the label from the UDF descriptors.
//! * **Disc-root resolution** — the input may be the disc root, the `BDMV` directory itself, or any
//!   directory inside it: [`walked_disc_root`] runs a bounded self/ancestor walk, committing only
//!   to a *scannable* `BDMV` — one holding `CLIPINF` + `PLAYLIST` — so a stray ancestor merely
//!   named `BDMV` can never break a scan the child lookup would satisfy. Child directories resolve
//!   case-insensitively (the `vfs` discovery).

use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, Read};
use std::sync::atomic::AtomicBool;

use super::chapters::{ChapterClip, ChapterSummary, walk_chapters};
use super::clpi::TsStreamClipFile;
use super::interleaved::TsInterleavedFile;
use super::m2ts::{TsStreamFile, bytes_to_f64, round_long};
use super::mpls::TsPlaylistFile;
use super::order::{self, PlaylistFilter};
use crate::discovery::{BdFileKind, BdmvDir};
use crate::error::{BdError, ScanError, ScanStage};
use crate::index;
use crate::primitives::Pid;
use crate::stream::{TsAudioMode, TsFrameRate, TsStream, TsStreamType};
use crate::vfs::{self, BdDir, BdFile, SearchOption};

/// The XML namespace of the BDMV disc-info metadata (`bdmt_*.xml`), bound to the
/// `di:` prefix when reading the disc title.
const DISCINFO_NS: &str = "urn:BDA:bdmv;discinfo";

/// The report-level summary of one scanned playlist.
///
/// These are the fields the `playlists` diff level emits, plus the per-stream
/// [`StreamSummary`] rows the `streams` level emits.
#[derive(Debug, Clone, PartialEq)]
pub struct PlaylistSummary {
    /// The upper-cased playlist file name, e.g. `00000.MPLS`.
    pub name: String,
    /// Total presentation length in seconds.
    pub total_length: f64,
    /// Sum of the clips' `*.m2ts` sizes in bytes.
    pub file_size: u64,
    /// Sum of the clips' interleaved `*.ssif` sizes in bytes.
    pub interleaved_file_size: u64,
    /// Number of chapter marks.
    pub chapter_count: usize,
    /// Number of presented streams, excluding SSIF-only rows
    /// ([`StreamSummary::ssif_only`]) — the count the report presents.
    pub stream_count: usize,
    /// The number of extra camera angles (0 for a single-angle playlist).
    pub angle_count: usize,
    /// Whether the playlist loops: two main (angle-0) clips replay the same
    /// clip file from the same in-time. The presentation order can filter
    /// looping playlists out (see [`super::order::PlaylistFilter`]).
    pub has_loops: bool,
    /// The presented streams, sorted by PID — the rows the `streams` diff level
    /// emits. Codec detail is only filled when the disc was opened with the
    /// packet scan (the disc/`playlists` levels are scan-free).
    pub streams: Vec<StreamSummary>,
    /// The sequenced clips with their measured tallies, in playlist order
    /// (including angle clips). One row per clip at every level; the demux
    /// tallies are zero without the packet scan.
    pub clips: Vec<ClipSummary>,
    /// Per-chapter measured video statistics, one row per chapter mark — the
    /// first video stream's per-frame diagnostics walked against the chapter
    /// boundaries (see [`walk_chapters`]). Without the packet scan the rows
    /// keep their times but all rates/sizes are `0`.
    pub chapters: Vec<ChapterSummary>,
}

impl PlaylistSummary {
    /// The playlist's packet-derived size in bytes: the sum of the main
    /// (angle-0) clips' [`ClipSummary::packet_size`] values.
    #[must_use]
    pub fn total_packet_size(&self) -> u64 {
        self.clips
            .iter()
            .filter(|clip| clip.angle_index == 0)
            .fold(0_u64, |sum, clip| sum.saturating_add(clip.packet_size()))
    }

    /// The packet-derived size in bytes over **all** clips, angle clips
    /// included.
    #[must_use]
    pub fn total_angle_packet_size(&self) -> u64 {
        self.clips.iter().fold(0_u64, |sum, clip| sum.saturating_add(clip.packet_size()))
    }

    /// The presentation length in seconds over **all** clips, angle clips
    /// included.
    #[must_use]
    pub fn total_angle_length(&self) -> f64 {
        let mut length = 0.0;
        for clip in &self.clips {
            length += clip.length;
        }
        length
    }

    /// The playlist's total bitrate in bits/s —
    /// [`total_packet_size`](Self::total_packet_size) at 8 bits per byte over
    /// `total_length`, rounded half-to-even; `0` when the playlist has no
    /// length.
    #[must_use]
    pub fn total_bit_rate(&self) -> u64 {
        rate_over(self.total_packet_size(), self.total_length)
    }

    /// The all-angles total bitrate in bits/s —
    /// [`total_angle_packet_size`](Self::total_angle_packet_size) at 8 bits
    /// per byte over [`total_angle_length`](Self::total_angle_length), rounded
    /// half-to-even; `0` when the playlist has no length.
    #[must_use]
    pub fn total_angle_bit_rate(&self) -> u64 {
        rate_over(self.total_angle_packet_size(), self.total_angle_length())
    }

    /// Whether any presented stream is hidden by this playlist (see
    /// [`StreamSummary::is_hidden`]).
    #[must_use]
    pub fn has_hidden_streams(&self) -> bool {
        self.streams.iter().any(|stream| stream.is_hidden)
    }

    /// Per-angle measurement totals, one entry per extra camera angle (angle 1
    /// first; empty for a single-angle playlist).
    ///
    /// Each angle's timeline is the main clips with the angle's own clips
    /// replacing them at the same playlist position (matched by exact start
    /// time, last write winning): `packet_size`/`length` sum the angle's own
    /// clips, `timeline_packet_size` the whole timeline.
    #[must_use]
    pub fn angle_totals(&self) -> Vec<AngleTotals> {
        let mut totals = Vec::new();
        for angle in 1..=self.angle_count {
            let angle_index = i32::try_from(angle).unwrap_or(i32::MAX);
            let mut timeline: Vec<(u64, &ClipSummary)> = Vec::new();
            for clip in &self.clips {
                if clip.angle_index == 0 || clip.angle_index == angle_index {
                    let key = clip.relative_time_in.to_bits();
                    match timeline.iter_mut().find(|(existing, _)| *existing == key) {
                        Some(slot) => slot.1 = clip,
                        None => timeline.push((key, clip)),
                    }
                }
            }
            let mut length = 0.0;
            let mut packet_size: u64 = 0;
            let mut timeline_packet_size: u64 = 0;
            for (_, clip) in &timeline {
                timeline_packet_size = timeline_packet_size.saturating_add(clip.packet_size());
                if clip.angle_index == angle_index {
                    packet_size = packet_size.saturating_add(clip.packet_size());
                    length += clip.length;
                }
            }
            totals.push(AngleTotals { length, packet_size, timeline_packet_size });
        }
        totals
    }
}

/// `size * 8 / seconds` rounded half-to-even as a bit rate, or `0` for a
/// non-positive duration.
fn rate_over(size: u64, seconds: f64) -> u64 {
    if seconds > 0.0 {
        u64::try_from(round_long(bytes_to_f64(size) * 8.0 / seconds)).unwrap_or(0)
    } else {
        0
    }
}

/// One sequenced clip's measured tallies — the per-clip slice of the packet
/// scan: what the demux attributed to this clip (packets/payload/seconds) plus
/// its stream file's whole-file per-stream tallies.
#[derive(Debug, Clone, PartialEq)]
pub struct ClipSummary {
    /// The clip's upper-cased `*.m2ts` name, e.g. `00001.M2TS`.
    pub name: String,
    /// The display name: the interleaved `*.ssif` name when the clip has one,
    /// else [`name`](Self::name).
    pub display_name: String,
    /// The clip's `*.m2ts` on-disk size in bytes (`0` when the file is absent) —
    /// the estimated (unmeasured) size.
    pub file_size: u64,
    /// The clip's interleaved `*.ssif` on-disk size in bytes (`0` when the clip
    /// has no interleaved file).
    pub interleaved_file_size: u64,
    /// Angle index; `0` is the main angle.
    pub angle_index: i32,
    /// Start time relative to the whole playlist, seconds.
    pub relative_time_in: f64,
    /// Clip duration in seconds.
    pub length: f64,
    /// Payload bytes the demux attributed to this clip.
    pub payload_bytes: u64,
    /// Transport packets the demux attributed to this clip.
    pub packet_count: u64,
    /// Demuxed clip duration in seconds.
    pub packet_seconds: f64,
    /// The stream file's whole-file presentation length in seconds (`0` when
    /// the file is absent).
    pub file_seconds: f64,
    /// The stream file's whole-file per-stream tallies, in the file's
    /// first-registration order, limited to the streams the playlist presents.
    pub streams: Vec<ClipStreamTally>,
}

impl ClipSummary {
    /// The clip's packet-derived size in bytes (`packet_count * 192`).
    #[must_use]
    pub const fn packet_size(&self) -> u64 {
        self.packet_count.wrapping_mul(192)
    }

    /// The clip's packet-derived bitrate in bits/s —
    /// [`packet_size`](Self::packet_size) at 8 bits per byte over
    /// `packet_seconds`, rounded half-to-even; `0` when nothing was demuxed.
    #[must_use]
    pub fn packet_bit_rate(&self) -> u64 {
        rate_over(self.packet_size(), self.packet_seconds)
    }
}

/// One stream's whole-file measured tallies within one clip's stream file.
///
/// Carries the demuxed payload byte and transport packet counts for that PID,
/// typed by the file's own registration (which can differ from the playlist's
/// declaration for the same PID).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClipStreamTally {
    /// The packet identifier (PID).
    pub pid: Pid,
    /// The stream type the file's table registered for this PID.
    pub stream_type: TsStreamType,
    /// The short codec label of the file's registered stream.
    pub codec_short_name: String,
    /// Payload bytes demuxed for this PID across the whole file.
    pub payload_bytes: u64,
    /// Transport packets seen on this PID across the whole file.
    pub packet_count: u64,
}

/// One extra camera angle's measurement totals (see
/// [`PlaylistSummary::angle_totals`]).
#[derive(Debug, Clone, PartialEq)]
pub struct AngleTotals {
    /// The summed length of the angle's own clips, seconds.
    pub length: f64,
    /// The summed packet-derived size of the angle's own clips, bytes.
    pub packet_size: u64,
    /// The packet-derived size of the angle's whole timeline (the main clips
    /// with the angle's replacements), bytes.
    pub timeline_packet_size: u64,
}

impl AngleTotals {
    /// The angle's own bitrate in bits/s — [`packet_size`](Self::packet_size)
    /// at 8 bits per byte over [`length`](Self::length), rounded half-to-even;
    /// `0` when the angle has no length.
    #[must_use]
    pub fn bit_rate(&self) -> u64 {
        rate_over(self.packet_size, self.length)
    }

    /// The angle's whole-timeline bitrate in bits/s —
    /// [`timeline_packet_size`](Self::timeline_packet_size) over the
    /// playlist's `total_length` (the timeline spans the whole playlist),
    /// rounded half-to-even; `0` for a zero-length playlist.
    #[must_use]
    pub fn timeline_bit_rate(&self, total_length: f64) -> u64 {
        rate_over(self.timeline_packet_size, total_length)
    }
}

/// One presented stream's report fields.
///
/// Carries the `streams` diff level's per-stream line group
/// (`stream.NNNNN.{type,codec,codecname,bitrate,lang,desc}`) plus
/// the columns the human-readable report renders (alternate codec name,
/// language code, audio channel detail, angle index).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamSummary {
    /// The packet identifier (PID), emitted zero-padded to five digits.
    pub pid: Pid,
    /// The elementary-stream type — the code that selects which report table
    /// (`VIDEO`/`AUDIO`/`SUBTITLES`/`TEXT`) the row lands in. The type itself is
    /// never printed.
    pub stream_type: TsStreamType,
    /// The short codec name, e.g. `AVC`, `DTS-HD MA`.
    pub codec_short_name: String,
    /// The long codec name, e.g. `MPEG-4 AVC Video`.
    pub codec_name: String,
    /// The alternate codec name some report tables print, e.g. `DD AC3`.
    pub codec_alt_name: &'static str,
    /// The stream's bitrate in bits/s, as the packet scan measured (or, for a
    /// constant-rate codec, decoded) it: variable-rate streams carry the
    /// demuxed payload over the playlist's demuxed seconds; constant-rate
    /// streams the coded nominal rate. An extra camera angle's video row
    /// carries that angle's own measured rate. `0` without the packet scan.
    pub bitrate: i64,
    /// The bitrate over the stream's active region in bits/s, as the packet
    /// scan measured it (video and `TrueHD` only). `0` without the packet
    /// scan.
    pub active_bitrate: i64,
    /// The language name, or empty when the stream has none.
    pub language_name: String,
    /// The ISO-639 language code (e.g. `eng`), or empty when the stream has
    /// none.
    pub language_code: String,
    /// The stream description — resolution/fps/HDR for video,
    /// channels/rate/depth for audio, empty for graphics/text on a quick scan.
    pub description: String,
    /// The description with the rates only the full packet scan knows folded
    /// in: a variable-rate audio stream's measured kbps (net of an embedded
    /// `TrueHD` core's rate), and the exact four-decimal HEVC luminance
    /// spelling. Equal to [`description`](Self::description) otherwise.
    pub full_description: String,
    /// The audio channel-layout string (e.g. `5.1`); empty for non-audio.
    pub channel_description: String,
    /// The audio sample rate in Hz; `0` for non-audio or unknown.
    pub sample_rate: i32,
    /// The audio bit depth; `0` for non-audio or unknown.
    pub bit_depth: i32,
    /// The audio channel count (LFE excluded); `0` for non-audio or unknown.
    pub channel_count: i32,
    /// The video pixel height (e.g. `1080`); `0` for non-video or unknown.
    pub height: i32,
    /// Which extra camera angle this row presents: `0` for the main
    /// presentation row, `1..=angle_count` for a video stream's per-angle
    /// copies (their measured rates are that angle's own).
    pub angle_index: usize,
    /// Whether the stream is hidden by the playlist: the clip carries it but
    /// the playlist's Stream-Number table does not declare it.
    pub is_hidden: bool,
    /// Whether the stream is presented only through the interleaved (`*.ssif`)
    /// dependent-view scan — the 3D MVC video the clip information omits
    /// ([`PlaylistSummary::stream_count`] does not count these rows).
    pub ssif_only: bool,
}

/// A scanned Blu-ray disc: discovery plus the metadata scan.
///
/// Built by [`BdRom::open`]; its fields are the disc-level values the report emits
/// (`disc.*`) plus the sorted per-playlist [`PlaylistSummary`] rows.
#[derive(Debug, Clone, PartialEq)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "the seven flags are independent disc properties (3D/50Hz/UHD/BD+/BD-Java/D-BOX/PSP), not a state machine"
)]
pub struct BdRom {
    /// Disc volume label — the genuine UDF `LogicalVolumeIdentifier` for
    /// `.iso` input, the disc-root directory name for folder input (see the
    /// module-level input conventions).
    pub volume_label: String,
    /// Disc title from `META/bdmt_eng.xml`; `None` when absent or the
    /// placeholder `"blu-ray"`.
    pub disc_title: Option<String>,
    /// Total disc size in bytes, excluding `*.ssif`.
    pub size: u64,
    /// Total byte size of the interleaved `*.ssif` files (the bytes
    /// [`size`](Self::size) excludes). Zero on a non-3D disc.
    pub interleaved_size: u64,
    /// 3D disc — a non-empty `STREAM/SSIF` directory.
    pub is_3d: bool,
    /// 50 Hz content — any playlist video stream at 25 or 50 fps.
    pub is_50hz: bool,
    /// 4K UHD disc — `index.bdmv` version magic `INDX0300`.
    pub is_uhd: bool,
    /// BD+ copy protection — a `BDSVM`/`SLYVM`/`ANYVM` directory.
    pub is_bd_plus: bool,
    /// BD-Java — a non-empty `BDJO` directory.
    pub is_bd_java: bool,
    /// D-BOX motion code — a `FilmIndex.xml` file in the disc root.
    pub is_dbox: bool,
    /// PSP / mobile content — a `*.mnv` file under `SNP`.
    pub is_psp: bool,
    /// Per-playlist summaries, sorted by name (ordinal).
    pub playlists: Vec<PlaylistSummary>,
}

/// The outcome of a resilient disc scan: the (possibly partial) [`BdRom`] plus
/// every per-file failure recorded along the way.
///
/// Built by [`BdRom::open_resilient`]. On healthy media `errors` is empty and
/// `bdrom` is identical to what [`BdRom::open`] returns; on damaged media each
/// unreadable/unparseable file is one [`ScanError`] and the readable rest is
/// still scanned — "scan completed with errors" rather than no scan at all.
#[derive(Debug)]
pub struct ScanReport {
    /// The scanned disc, missing whatever the recorded failures made unreadable.
    pub bdrom: BdRom,
    /// The per-file failures, in the order the scan hit them.
    pub errors: Vec<ScanError>,
}

/// One live-progress observation of the packet scan, handed to the callback
/// of [`BdRom::open_with`] as the demux pulls bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScanProgress<'a> {
    /// The stream file currently being demuxed (its upper-cased name; the
    /// interleaved `*.ssif` source still reports its `*.M2TS` name).
    pub file: &'a str,
    /// Bytes demuxed so far across the reported (full) pass, never decreasing
    /// and never exceeding [`total`](Self::total).
    pub done: u64,
    /// Total bytes the reported pass will demux: every selected stream file's
    /// source, once. (The quick codec-init pass reads only file heads and is
    /// neither budgeted nor reported.)
    pub total: u64,
}

/// The live bookkeeping of one packet scan: the running byte count over the
/// full pass's total, reported through the caller's callback after every
/// demux read and at every file boundary, plus the caller's cooperative
/// cancel flag the demux polls per read chunk.
struct Progress<'a> {
    /// The caller's observer; a no-op for the plain `open`s.
    callback: &'a mut dyn FnMut(ScanProgress<'_>),
    /// Bytes demuxed so far, kept within `0..=total`.
    done: u64,
    /// Total bytes the reported (full) demux pass will read over the
    /// selected files.
    total: u64,
    /// The caller's cancel flag; never set for the plain `open`s.
    cancel: &'a AtomicBool,
}

impl Progress<'_> {
    /// Advances the counter by `bytes` demuxed from `file` and reports.
    fn advance(&mut self, file: &str, bytes: u64) {
        self.done = self.done.saturating_add(bytes).min(self.total);
        (self.callback)(ScanProgress { file, done: self.done, total: self.total });
    }

    /// Snaps the counter up to `target` once `file` completes (or fails), so
    /// a short, early-finishing, or failed read never skews the running
    /// percentage of the files after it.
    fn finish_file(&mut self, file: &str, target: u64) {
        self.done = self.done.max(target).min(self.total);
        (self.callback)(ScanProgress { file, done: self.done, total: self.total });
    }
}

/// A demux source that advances the scan progress as bytes are pulled
/// through it.
struct CountingReader<'a, 'b> {
    /// The wrapped source (the `*.m2ts`, or the interleaved `*.ssif`).
    inner: Box<dyn vfs::ReadSeek>,
    /// The upper-cased stream-file name reported with each advance.
    name: String,
    /// The scan's shared progress bookkeeping.
    progress: &'a mut Progress<'b>,
}

impl Read for CountingReader<'_, '_> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let bytes = self.inner.read(buf)?;
        self.progress.advance(&self.name, u64::try_from(bytes).unwrap_or(u64::MAX));
        Ok(bytes)
    }
}

/// The byte total the reported (full) demux pass will read: per selected
/// stream file, its interleaved `*.ssif` source when one exists, else the
/// file itself, each counted once. The quick pass reads only file heads and
/// is not budgeted (nor reported), so the display runs 0→100% at the full
/// pass's steady pace.
fn scan_total(
    stream_files: &BTreeMap<String, u64>,
    interleaved_files: &BTreeMap<String, u64>,
    scan_files: Option<&BTreeSet<String>>,
) -> u64 {
    let mut total: u64 = 0;
    for (name, size) in stream_files {
        if scan_files.is_some_and(|selected| !selected.contains(name)) {
            continue;
        }
        let stem = clip_stem(name);
        let source = interleaved_files.get(&format!("{stem}.SSIF")).copied().unwrap_or(*size);
        total = total.saturating_add(source);
    }
    total
}

/// The collect-and-continue switch threaded through one scan: strict mode
/// (`errors: None`) propagates the first failure; resilient mode records it and
/// substitutes a fallback so the scan continues over the readable rest.
struct Sink<'a> {
    /// The error list to record into, or `None` for strict (abort-first) mode.
    errors: Option<&'a mut Vec<ScanError>>,
}

impl Sink<'_> {
    /// Unwraps `result`, recording a failure against `file` at `stage` and
    /// yielding `fallback` in resilient mode, or propagating it in strict mode.
    fn absorb<T>(
        &mut self,
        stage: ScanStage,
        file: &str,
        fallback: T,
        result: Result<T, BdError>,
    ) -> Result<T, BdError> {
        match result {
            Ok(value) => Ok(value),
            Err(reason) => match self.errors.as_deref_mut() {
                Some(errors) => {
                    errors.push(ScanError { file: file.to_owned(), stage, reason });
                    Ok(fallback)
                }
                None => Err(reason),
            },
        }
    }

    /// Records a `file`/`stage`/`reason` note in resilient mode; a no-op in
    /// strict mode (which has no error list to collect into). Used for notes
    /// that don't substitute a value — a recovered-from-BACKUP primary, or a
    /// tolerated-but-malformed `index.bdmv`.
    fn record(&mut self, stage: ScanStage, file: &str, reason: BdError) {
        if let Some(errors) = self.errors.as_deref_mut() {
            errors.push(ScanError { file: file.to_owned(), stage, reason });
        }
    }

    /// Like [`absorb`](Self::absorb), with a `BDMV/BACKUP` recovery attempt
    /// between a primary failure and recording it.
    ///
    /// Recovery is resilient-mode only; `discover_backups` documents why, and
    /// leaves the pools empty in strict mode so `backup` can only miss there. On
    /// a primary `Err` `backup` is invoked; `Some(Ok(value))` is returned with
    /// the *primary* failure still recorded against `file`/`stage`, so the
    /// report's `WARNING` block surfaces the bad primary even though the
    /// recovered data is present. A missing or also-failing backup falls
    /// through to the plain [`absorb`](Self::absorb) outcome (recorded
    /// `fallback`, or — in strict mode — propagation).
    fn absorb_with_backup<T>(
        &mut self,
        stage: ScanStage,
        file: &str,
        fallback: T,
        primary: Result<T, BdError>,
        backup: impl FnOnce() -> Option<Result<T, BdError>>,
    ) -> Result<T, BdError> {
        let reason = match primary {
            Ok(value) => return Ok(value),
            Err(reason) => reason,
        };
        if self.errors.is_some()
            && let Some(Ok(value)) = backup()
        {
            self.record(stage, file, reason);
            return Ok(value);
        }
        self.absorb(stage, file, fallback, Err(reason))
    }
}

/// Per-clip facts the reference-clip selection needs: the resolved clip-info and
/// stream-file facts, plus borrowed references to the clip's parsed clip-info
/// streams and (when the packet scan ran) its scanned stream file, so
/// the selected reference can build its presented streams without a second
/// lookup. Borrowing keeps [`select_reference`] pure and directly unit-testable.
struct ClipMeta<'a> {
    /// The clip's clip-info (`*.clpi`) streams.
    clip_streams: &'a BTreeMap<u16, TsStream>,
    /// The clip's scanned stream file, or `None` when the packet scan did
    /// not run (disc/`playlists` level) or the file was absent.
    scanned: Option<&'a TsStreamFile>,
    /// Whether any video stream in the clip is 25 or 50 fps (drives `is_50hz`).
    has_50hz_video: bool,
    /// The clip's duration as a fraction of the playlist.
    relative_length: f64,
    /// The clip's duration in seconds.
    length: f64,
    /// Whether the clip's `*.m2ts` exists on the disc.
    stream_file_present: bool,
}

/// How deep an [`open`](BdRom::open) reads the disc — the three-way choice that
/// trades scan cost against how much per-stream detail the summaries carry.
///
/// The packet scan is internally two passes: a **quick** pass that reads only far
/// enough into each `*.m2ts` to parse the first parameter sets (codec profile /
/// level / HDR10 / Dolby Vision), then a **full** pass that reads every byte to
/// measure bitrate. The modes expose the useful stopping points.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScanMode {
    /// Structure only — parse `MPLS`/`CLPI`, read **no** `*.m2ts` packets. The
    /// streams carry their clip-info detail (resolution / fps / aspect, channels /
    /// rate) but no scanned codec detail and no bitrate. The cheapest mode.
    Metadata,
    /// Structure **plus** the quick codec pass — reads only the head of each
    /// stream file, so the presented streams gain their full codec detail
    /// (profile / level / HDR / Dolby Vision / embedded core) but **not** measured
    /// bitrate. Bounded and fast; the disc-browse mode the GUI opens with.
    Codecs,
    /// The full measured scan — the quick codec pass then the whole-file bitrate
    /// pass. The presented streams and clips carry codec detail **and** measured
    /// bitrate. The most expensive mode (reads every selected byte).
    Full,
}

impl ScanMode {
    /// Whether this mode runs any `*.m2ts` packet scan (`Codecs` or `Full`).
    const fn scans_packets(self) -> bool {
        matches!(self, Self::Codecs | Self::Full)
    }

    /// Whether this mode runs the whole-file bitrate (full) pass — `Full` only.
    const fn measures_bitrate(self) -> bool {
        matches!(self, Self::Full)
    }
}

impl BdRom {
    /// Opens and scans the Blu-ray disc rooted at `root`.
    ///
    /// `root` is normally the disc root (the folder that contains `BDMV/`), but
    /// pointing at the `BDMV` directory itself or any directory inside it also
    /// works: the scan walks up to the implied disc root first
    /// ([`walked_disc_root`]).
    ///
    /// [`mode`](ScanMode) chooses how deep the scan reads: `Metadata` parses only
    /// the clip info (no packets), `Codecs` adds the bounded quick pass so the
    /// presented streams gain their codec detail, and `Full` adds the whole-file
    /// bitrate pass. The disc and `playlists` diff levels pass `Metadata`; no field
    /// they emit depends on the packet scan.
    ///
    /// # Errors
    /// - [`BdError::StructureNotFound`] if `root` has no `BDMV`, or `BDMV` lacks
    ///   `CLIPINF`/`PLAYLIST` ("unable to locate BD structure").
    /// - [`BdError::MissingClipFile`] if a playlist references an absent `*.clpi`.
    /// - [`BdError::UnknownFileType`]/[`BdError::UnexpectedEof`] for malformed metadata, or
    ///   [`BdError::Io`] for a filesystem error.
    pub fn open(root: &dyn BdDir, mode: ScanMode) -> Result<Self, BdError> {
        Self::open_with(root, mode, None, &mut |_| {}, &AtomicBool::new(false))
    }

    /// Opens and scans the disc like [`open`](Self::open), with the packet
    /// scan narrowed to `scan_files`, observed by `progress`, and abortable
    /// through `cancel`.
    ///
    /// `scan_files` — when `Some`, only the stream files whose upper-cased
    /// names (`00000.M2TS`) it contains are packet-scanned; the rest keep
    /// their metadata-only summaries (zero measured rates). `None` scans
    /// every stream file.
    ///
    /// `progress` is called after every demux read and at every file boundary
    /// with the running [`ScanProgress`]; it never fires without the packet
    /// scan.
    ///
    /// `cancel` — a cooperative stop flag: set it from any thread (a UI cancel
    /// button, a Ctrl+C handler, the progress callback itself) and the packet
    /// scan aborts at its next read chunk with [`BdError::ScanCancelled`],
    /// yielding no partial result. The flag is polled with one relaxed load
    /// per chunk, so the demux hot path is unaffected; a scan that reads no
    /// packets ([`ScanMode::Metadata`]) never observes it.
    ///
    /// # Errors
    /// As [`open`](Self::open), plus [`BdError::ScanCancelled`] when `cancel`
    /// was set mid-scan.
    pub fn open_with(
        root: &dyn BdDir,
        mode: ScanMode,
        scan_files: Option<&BTreeSet<String>>,
        progress: &mut dyn FnMut(ScanProgress<'_>),
        cancel: &AtomicBool,
    ) -> Result<Self, BdError> {
        Self::open_impl(root, mode, scan_files, progress, cancel, &mut Sink { errors: None })
    }

    /// Opens and scans the disc like [`open`](Self::open), but **collects** per-file
    /// failures instead of aborting on the first one — the resilient scan for
    /// damaged or partially-unreadable media.
    ///
    /// A corrupt/unreadable clip-information file, playlist, or stream file (and
    /// any failed disc-level metadata read) is recorded as a [`ScanError`] and the
    /// scan continues over the readable rest; the affected playlist (or flag) is
    /// simply absent (or its default) in the returned [`BdRom`]. On healthy media
    /// the result is identical to [`open`](Self::open) with an empty error list.
    ///
    /// # Errors
    /// Only the failures with no readable rest to degrade to: locating
    /// `BDMV`/`CLIPINF`/`PLAYLIST` failed ([`BdError::StructureNotFound`], or
    /// [`BdError::Io`] if those lookups cannot enumerate).
    pub fn open_resilient(root: &dyn BdDir, mode: ScanMode) -> Result<ScanReport, BdError> {
        Self::open_resilient_with(root, mode, None, &mut |_| {}, &AtomicBool::new(false))
    }

    /// Opens and scans the disc like [`open_resilient`](Self::open_resilient),
    /// with the packet scan narrowed to `scan_files`, observed by `progress`,
    /// and abortable through `cancel` (the [`open_with`](Self::open_with)
    /// extras).
    ///
    /// # Errors
    /// As [`open_resilient`](Self::open_resilient), plus
    /// [`BdError::ScanCancelled`] when `cancel` was set mid-scan — resilience
    /// collects disc damage, not the caller's abort, so a cancelled scan
    /// returns this error (never a partial [`ScanReport`], and never a
    /// recorded per-file failure).
    pub fn open_resilient_with(
        root: &dyn BdDir,
        mode: ScanMode,
        scan_files: Option<&BTreeSet<String>>,
        progress: &mut dyn FnMut(ScanProgress<'_>),
        cancel: &AtomicBool,
    ) -> Result<ScanReport, BdError> {
        let mut errors = Vec::new();
        let bdrom = Self::open_impl(
            root,
            mode,
            scan_files,
            progress,
            cancel,
            &mut Sink { errors: Some(&mut errors) },
        )?;
        Ok(ScanReport { bdrom, errors })
    }

    /// The shared scan body behind [`open`](Self::open) (strict `sink`) and
    /// [`open_resilient`](Self::open_resilient) (recording `sink`).
    fn open_impl(
        root: &dyn BdDir,
        mode: ScanMode,
        scan_files: Option<&BTreeSet<String>>,
        progress: &mut dyn FnMut(ScanProgress<'_>),
        cancel: &AtomicBool,
        sink: &mut Sink<'_>,
    ) -> Result<Self, BdError> {
        // Walk self+ancestors for a `BDMV` before trying the child lookup,
        // tolerating input that points at the BDMV directory itself or inside
        // it. When the walk finds a scannable BDMV ancestor, its parent becomes
        // the disc root; otherwise the input is the disc root.
        let walked = walked_disc_root(root);
        let root = walked.as_deref().unwrap_or(root);
        // Fatal in both modes: without BDMV/CLIPINF/PLAYLIST there is no readable
        // rest to degrade to.
        let bdmv = vfs::find_directory(root, BdmvDir::Bdmv)?.ok_or(BdError::StructureNotFound)?;
        let clipinf = vfs::find_directory(&*bdmv, BdmvDir::ClipInf)?;
        let playlist = vfs::find_directory(&*bdmv, BdmvDir::Playlist)?;
        let stream = vfs::find_directory(&*bdmv, BdmvDir::Stream)?;
        let ssif = match &stream {
            Some(s) => vfs::find_directory(&**s, BdmvDir::Ssif)?,
            None => None,
        };
        let meta = vfs::find_directory(&*bdmv, BdmvDir::Meta)?;
        let bdjo = vfs::find_directory(&*bdmv, BdmvDir::BdJo)?;
        let snp = vfs::find_directory(root, BdmvDir::Snp)?;

        let (Some(clipinf), Some(playlist)) = (clipinf, playlist) else {
            return Err(BdError::StructureNotFound);
        };

        // The `BDMV/BACKUP` recovery pools, consulted only when a primary read
        // fails. Strict `open` never recovers, so it skips the probe entirely
        // and the pools stay empty; on a healthy disc the primaries succeed and
        // the (resilient-built) pools are never consulted.
        let (backup_index, backup_playlist, backup_clipinf) = discover_backups(&*bdmv, sink);

        // --- disc-level flags + metadata (each isolated in resilient mode) --
        let root_name = root.name().to_owned();
        let volume_label = root_name.clone();
        let (size, interleaved_size) =
            sink.absorb(ScanStage::Discovery, &root_name, (0, 0), directory_size(root))?;
        let is_uhd = read_uhd_flag(&*bdmv, &backup_index, sink)?;
        let is_bd_plus =
            sink.absorb(ScanStage::Discovery, &root_name, false, has_bd_plus_dir(root))?;
        let is_bd_java = match &bdjo {
            Some(d) => sink.absorb(ScanStage::Discovery, d.name(), false, has_any_file(&**d))?,
            None => false,
        };
        let is_psp = match &snp {
            Some(s) => sink.absorb(ScanStage::Discovery, s.name(), false, has_mnv_file(&**s))?,
            None => false,
        };
        let is_dbox = sink.absorb(ScanStage::Discovery, &root_name, false, has_film_index(root))?;
        let is_3d = match &ssif {
            Some(s) => sink.absorb(ScanStage::Discovery, s.name(), false, has_any_file(&**s))?,
            None => false,
        };
        let disc_title = match &meta {
            Some(m) => {
                sink.absorb(ScanStage::Discovery, m.name(), None, read_disc_title_from(&**m))?
            }
            None => None,
        };

        // --- build the file maps (sizes keyed by upper-cased name) -----------
        let (stream_files, interleaved_files, clip_files) =
            build_file_maps(stream.as_deref(), ssif.as_deref(), &*clipinf, &backup_clipinf, sink)?;

        // --- parse playlists, sorted by name (ordinal) ---------------------
        let mut parsed = parse_playlists(&*playlist, &backup_playlist, sink)?;

        // --- the per-stream-file packet scans (streams level only) ---------
        // `Metadata` reads no packets; `Codecs`/`Full` both run the quick codec
        // pass, and only `Full` follows it with the whole-file bitrate pass.
        let (scanned, measured) = if mode.scans_packets() {
            run_measurement_scan(
                stream.as_deref(),
                ssif.as_deref(),
                &mut parsed,
                &clip_files,
                &stream_files,
                &interleaved_files,
                scan_files,
                mode.measures_bitrate(),
                progress,
                cancel,
                sink,
            )?
        } else {
            (BTreeMap::new(), BTreeMap::new())
        };

        // --- summarise each playlist (+ build its presented streams) -------
        let mut playlists = Vec::new();
        let mut is_50hz = false;
        for playlist in &parsed {
            let summary = build_summary(
                playlist,
                &clip_files,
                &stream_files,
                &interleaved_files,
                &scanned,
                &measured,
            );
            if let Some((summary, hz)) =
                sink.absorb(ScanStage::Playlist, &playlist.name, None, summary.map(Some))?
            {
                is_50hz = is_50hz || hz;
                playlists.push(summary);
            }
        }

        Ok(Self {
            volume_label,
            disc_title,
            size,
            interleaved_size,
            is_3d,
            is_50hz,
            is_uhd,
            is_bd_plus,
            is_bd_java,
            is_dbox,
            is_psp,
            playlists,
        })
    }
}

impl BdRom {
    /// The disc's whole-tree byte size: [`size`](Self::size) plus the
    /// interleaved `*.ssif` bytes it excludes.
    #[must_use]
    pub const fn full_size(&self) -> u64 {
        self.size.saturating_add(self.interleaved_size)
    }

    /// The playlists' presentation order under `filter` — indices into
    /// [`playlists`](Self::playlists), grouped by shared clip files and
    /// sorted longest-first (see [`order::presentation_order`]). The default
    /// filter drops short and looping playlists;
    /// [`PlaylistFilter::everything`] keeps them.
    #[must_use]
    pub fn presentation_order(&self, filter: &PlaylistFilter) -> Vec<usize> {
        order::presentation_order(&self.playlists, filter)
    }

    /// The disc's extra-feature labels, in presentation order: `Ultra HD`,
    /// `BD-Java`, `50Hz Content`, `Blu-ray 3D`, `D-BOX Motion Code`,
    /// `PSP Digital Copy` — one entry per set flag.
    #[must_use]
    pub fn extra_features(&self) -> Vec<&'static str> {
        let flags = [
            (self.is_uhd, "Ultra HD"),
            (self.is_bd_java, "BD-Java"),
            (self.is_50hz, "50Hz Content"),
            (self.is_3d, "Blu-ray 3D"),
            (self.is_dbox, "D-BOX Motion Code"),
            (self.is_psp, "PSP Digital Copy"),
        ];
        flags.into_iter().filter(|&(set, _)| set).map(|(_, label)| label).collect()
    }
}

/// Upper bound on the [`walked_disc_root`] ancestor walk — far deeper than any
/// real disc path, so a pathological [`BdDir::parent`] chain (or a cycle) can
/// never spin the scan.
const MAX_BDMV_ANCESTORS: usize = 64;

/// Whether `bdmv` is a scannable `BDMV` directory — it holds both the `CLIPINF`
/// and `PLAYLIST` children the scan requires (the same condition the main lookup
/// enforces). A lookup failure counts as "no": the probe is speculative, so an
/// unreadable candidate simply leaves the input treated as the disc root.
fn is_scannable_bdmv(bdmv: &dyn BdDir) -> bool {
    let has = |which| matches!(vfs::find_directory(bdmv, which), Ok(Some(_)));
    has(BdmvDir::ClipInf) && has(BdmvDir::Playlist)
}

/// The upward pass of the disc-root resolution: when `input` — or one of its
/// ancestors, nearest first — is a scannable `BDMV` directory, returns that
/// directory's parent, the implied disc root. Returns `None` for the common
/// disc-root input (no `BDMV` self/ancestor), when the found `BDMV` has no
/// parent, or once the walk exhausts [`MAX_BDMV_ANCESTORS`] levels.
///
/// A candidate is committed to only if it is *scannable*
/// ([`is_scannable_bdmv`]), so a stray ancestor that merely happens to be named
/// `BDMV` can never break a scan that treating the input as the disc root would
/// satisfy — e.g. a disc root itself named `BDMV` still scans. Name matching is
/// ASCII case-insensitive.
fn walked_disc_root(input: &dyn BdDir) -> Option<Box<dyn BdDir>> {
    if BdmvDir::from_name(input.name()) == Some(BdmvDir::Bdmv) && is_scannable_bdmv(input) {
        return input.parent();
    }
    let mut dir = input.parent()?;
    for _ in 0..MAX_BDMV_ANCESTORS {
        if BdmvDir::from_name(dir.name()) == Some(BdmvDir::Bdmv) && is_scannable_bdmv(&*dir) {
            return dir.parent();
        }
        dir = dir.parent()?;
    }
    None
}

/// Reads the bytes of `BDMV/index.bdmv` (case-insensitive), or `Ok(None)` when
/// the directory holds no such file. The IO failures of enumerating `bdmv` or
/// reading the file surface as `Err`.
fn read_index_bytes(bdmv: &dyn BdDir) -> Result<Option<Vec<u8>>, BdError> {
    for file in bdmv.get_files()? {
        if file.name().eq_ignore_ascii_case("index.bdmv") {
            return Ok(Some(read_file(&*file)?));
        }
    }
    Ok(None)
}

/// Resolves the disc's UHD flag from `index.bdmv`, with the resilient-path
/// extras: a failed *primary* read falls back to `BDMV/BACKUP/index.bdmv`
/// (recording the primary failure), and a present-but-untagged index — one
/// lacking the `INDX` magic — is surfaced as a `ScanReport` warning while still
/// being tolerated as non-UHD (a garbage index just means "not UHD", but a
/// corrupted one should not silently read as an SDR disc).
///
/// A *missing* `index.bdmv` (no file to open) is non-UHD with no warning and no
/// backup attempt — the same silent-false both products give "the disc says
/// nothing about UHD".
fn read_uhd_flag(
    bdmv: &dyn BdDir,
    backup_index: &BackupFiles,
    sink: &mut Sink<'_>,
) -> Result<bool, BdError> {
    let bytes = sink.absorb_with_backup(
        ScanStage::Discovery,
        "index.bdmv",
        None,
        read_index_bytes(bdmv),
        || recover_backup(backup_index, "index.bdmv", |_, bytes| Ok(Some(bytes.to_vec()))),
    )?;
    let Some(bytes) = bytes else {
        return Ok(false);
    };
    if !index::has_index_tag(&bytes) {
        sink.record(
            ScanStage::Discovery,
            "index.bdmv",
            BdError::UnknownFileType(index::read_index_version(&bytes).unwrap_or_default()),
        );
    }
    Ok(index::is_uhd(&bytes))
}

/// Whether `root` has a `BDSVM`/`SLYVM`/`ANYVM` child directory (`is_bd_plus`).
fn has_bd_plus_dir(root: &dyn BdDir) -> Result<bool, BdError> {
    for child in root.get_directories()? {
        if matches!(child.name().to_ascii_uppercase().as_str(), "BDSVM" | "SLYVM" | "ANYVM") {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Whether `dir` contains at least one file.
fn has_any_file(dir: &dyn BdDir) -> Result<bool, BdError> {
    Ok(!dir.get_files()?.is_empty())
}

/// Whether the disc root carries a `FilmIndex.xml` file (`is_dbox` — the
/// D-BOX motion-code marker), matched case-insensitively like the rest of the
/// discovery.
fn has_film_index(root: &dyn BdDir) -> Result<bool, BdError> {
    for file in root.get_files()? {
        if file.name().eq_ignore_ascii_case("FilmIndex.xml") {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Whether `dir` contains at least one `*.mnv` file (`is_psp`).
fn has_mnv_file(dir: &dyn BdDir) -> Result<bool, BdError> {
    for file in dir.get_files()? {
        if file.name().rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("mnv")) {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Recursive byte size of `dir` as `(size, interleaved_size)`: every
/// non-`*.ssif` byte in the first component, the `*.ssif` bytes in the second.
fn directory_size(dir: &dyn BdDir) -> Result<(u64, u64), BdError> {
    let mut size: u64 = 0;
    let mut interleaved: u64 = 0;
    for file in dir.get_files()? {
        if file.extension().eq_ignore_ascii_case(".ssif") {
            interleaved = interleaved.saturating_add(file.length());
        } else {
            size = size.saturating_add(file.length());
        }
    }
    for child in dir.get_directories()? {
        let (child_size, child_interleaved) = directory_size(&*child)?;
        size = size.saturating_add(child_size);
        interleaved = interleaved.saturating_add(child_interleaved);
    }
    Ok((size, interleaved))
}

/// Finds `META/**/bdmt_eng.xml` (recursively) and parses the disc title from
/// it. Returns `None` when the file is absent.
fn read_disc_title_from(meta: &dyn BdDir) -> Result<Option<String>, BdError> {
    let files = meta.get_files_pattern_option("bdmt_eng.xml", SearchOption::AllDirectories)?;
    let Some(file) = files.first() else {
        return Ok(None);
    };
    let bytes = read_file(&**file)?;
    let text = String::from_utf8_lossy(&bytes);
    Ok(read_disc_title(&text))
}

/// Parses the disc title from a `bdmt_*.xml` document: the inner text of
/// `di:discinfo/di:title/di:name` (in the `urn:BDA:bdmv;discinfo` namespace),
/// or `None` when the element is absent, the XML is malformed, or the title is
/// the placeholder `"blu-ray"`. An empty title is preserved as `Some("")` —
/// only the `"blu-ray"` placeholder is nulled.
fn read_disc_title(xml: &str) -> Option<String> {
    // Strip a leading UTF-8 BOM; roxmltree would reject it.
    let xml = xml.strip_prefix('\u{feff}').unwrap_or(xml);
    let doc = roxmltree::Document::parse(xml).ok()?;
    let name = doc
        .root_element()
        .children()
        .find(|n| n.has_tag_name((DISCINFO_NS, "discinfo")))?
        .children()
        .find(|n| n.has_tag_name((DISCINFO_NS, "title")))?
        .children()
        .find(|n| n.has_tag_name((DISCINFO_NS, "name")))?;
    // The title is the concatenation of every descendant text node.
    let title: String =
        name.descendants().filter(roxmltree::Node::is_text).filter_map(|n| n.text()).collect();
    if title.eq_ignore_ascii_case("blu-ray") {
        return None;
    }
    Some(title)
}

/// Builds a map from upper-cased file name to byte size for the files of `kind`
/// in `dir` — how clip names resolve to their `*.m2ts`/`*.ssif` sizes.
fn file_sizes(dir: Option<&dyn BdDir>, kind: BdFileKind) -> Result<BTreeMap<String, u64>, BdError> {
    let mut map = BTreeMap::new();
    if let Some(dir) = dir {
        for file in vfs::find_files(dir, kind)? {
            map.insert(file.name().to_ascii_uppercase(), file.length());
        }
    }
    Ok(map)
}

/// Scans every `*.clpi` in `clipinf` into a map keyed by upper-cased name. In
/// strict mode a malformed clip file propagates its [`BdError`]; in resilient
/// mode it is recorded and skipped, and the playlists that reference it degrade
/// accordingly.
fn scan_clip_files(
    clipinf: &dyn BdDir,
    backup: &BackupFiles,
    sink: &mut Sink<'_>,
) -> Result<BTreeMap<String, TsStreamClipFile>, BdError> {
    let mut map = BTreeMap::new();
    let files = sink.absorb(
        ScanStage::Discovery,
        clipinf.name(),
        Vec::new(),
        vfs::find_files(clipinf, BdFileKind::ClipInfo).map_err(BdError::from),
    )?;
    for file in files {
        let name = file.name();
        let scan = read_file(&*file).and_then(|bytes| TsStreamClipFile::scan(name, &bytes));
        let recovered =
            sink.absorb_with_backup(ScanStage::ClipInfo, name, None, scan.map(Some), {
                || recover_backup(backup, name, |n, b| TsStreamClipFile::scan(n, b).map(Some))
            })?;
        if let Some(parsed) = recovered {
            map.insert(name.to_ascii_uppercase(), parsed);
        }
    }
    Ok(map)
}

/// Parses every `*.mpls` under `playlist_dir`, sorted by upper-cased name. In
/// strict mode a malformed playlist propagates its [`BdError`]; in resilient
/// mode it is recorded and skipped.
fn parse_playlists(
    playlist_dir: &dyn BdDir,
    backup: &BackupFiles,
    sink: &mut Sink<'_>,
) -> Result<Vec<TsPlaylistFile>, BdError> {
    let mut playlist_handles = sink.absorb(
        ScanStage::Discovery,
        playlist_dir.name(),
        Vec::new(),
        vfs::find_files(playlist_dir, BdFileKind::Playlist).map_err(BdError::from),
    )?;
    playlist_handles.sort_by_key(|f| f.name().to_ascii_uppercase());
    let mut parsed = Vec::new();
    for handle in &playlist_handles {
        let name = handle.name();
        let scan = read_file(&**handle).and_then(|bytes| TsPlaylistFile::scan(name, &bytes));
        let recovered =
            sink.absorb_with_backup(ScanStage::Playlist, name, None, scan.map(Some), {
                || recover_backup(backup, name, |n, b| TsPlaylistFile::scan(n, b).map(Some))
            })?;
        if let Some(playlist) = recovered {
            parsed.push(playlist);
        }
    }
    Ok(parsed)
}

/// One pass's scanned stream files, keyed by upper-cased file name.
type ScannedFiles = BTreeMap<String, TsStreamFile>;

/// The scan's discovery maps: the `*.m2ts` sizes, the `*.ssif` sizes (both
/// keyed by upper-cased name), and the parsed clip-information files.
type FileMaps = (BTreeMap<String, u64>, BTreeMap<String, u64>, BTreeMap<String, TsStreamClipFile>);

/// Builds the scan's [`FileMaps`] (each lookup isolated per the `sink` mode).
///
/// # Errors
/// Propagates the per-directory failures per the `sink` mode.
fn build_file_maps(
    stream: Option<&dyn BdDir>,
    ssif: Option<&dyn BdDir>,
    clipinf: &dyn BdDir,
    backup_clipinf: &BackupFiles,
    sink: &mut Sink<'_>,
) -> Result<FileMaps, BdError> {
    let stream_files = sink.absorb(
        ScanStage::Discovery,
        stream.map_or("STREAM", BdDir::name),
        BTreeMap::new(),
        file_sizes(stream, BdFileKind::Stream),
    )?;
    let interleaved_files = sink.absorb(
        ScanStage::Discovery,
        ssif.map_or("SSIF", BdDir::name),
        BTreeMap::new(),
        file_sizes(ssif, BdFileKind::Interleaved),
    )?;
    let clip_files = scan_clip_files(clipinf, backup_clipinf, sink)?;
    Ok((stream_files, interleaved_files, clip_files))
}

/// The two-pass measurement scan over the stream files (the `streams` level's
/// packet scan): a quick pass initialises each file's codec detail and nominal
/// rates; the playlists then present their reference clip's streams (merged
/// with that detail); the clip tallies the quick pass touched are zeroed; and
/// the full pass — every packet to EOF — attributes its measurements to the
/// clips, the presented streams, and the per-angle copies. Returns the
/// `(quick, full)` scan maps, both keyed by upper-cased file name.
///
/// A playlist whose clips cannot resolve keeps empty presented streams here;
/// the summary pass reports the failure.
///
/// # Errors
/// Propagates [`scan_stream_files`]'s failures per the `sink` mode.
#[expect(
    clippy::too_many_arguments,
    reason = "the scan orchestration threads the per-open context (dirs, maps, selection, progress, sink) one level down"
)]
fn run_measurement_scan(
    stream: Option<&dyn BdDir>,
    ssif: Option<&dyn BdDir>,
    parsed: &mut [TsPlaylistFile],
    clip_files: &BTreeMap<String, TsStreamClipFile>,
    stream_files: &BTreeMap<String, u64>,
    interleaved_files: &BTreeMap<String, u64>,
    scan_files: Option<&BTreeSet<String>>,
    measure: bool,
    callback: &mut dyn FnMut(ScanProgress<'_>),
    cancel: &AtomicBool,
    sink: &mut Sink<'_>,
) -> Result<(ScannedFiles, ScannedFiles), BdError> {
    // The quick pass reads an unpredictable sliver of each file (codec
    // init), so it draws no progress; the reported budget is the full pass,
    // every selected byte once — a steady 0→100%. Cancellation reaches both
    // passes: each carries the caller's flag in its `Progress`.
    let mut warmup = |_: ScanProgress<'_>| {};
    let quick_progress = &mut Progress { callback: &mut warmup, done: 0, total: 0, cancel };
    let quick = scan_stream_files(stream, ssif, parsed, scan_files, quick_progress, sink, false)?;
    for playlist in parsed.iter_mut() {
        if let Ok(metas) = collect_clip_metas(playlist, clip_files, stream_files, &quick) {
            resolve_playlist_streams(playlist, &metas);
        }
    }
    // Discard the partial byte/packet tallies the bounded quick pass left in the
    // clips (it read only a sliver of each file); the full pass re-accumulates
    // them for real.
    clear_measurements(parsed);
    // Codec-only mode (`Codecs`) stops here: the resolved streams keep their
    // scanned codec detail, but with the tallies cleared and no full pass, every
    // bitrate and clip measurement stays zero. `measured` is left empty.
    if !measure {
        return Ok((quick, BTreeMap::new()));
    }
    let progress = &mut Progress {
        callback,
        done: 0,
        total: scan_total(stream_files, interleaved_files, scan_files),
        cancel,
    };
    let full = scan_stream_files(stream, ssif, parsed, scan_files, progress, sink, true)?;
    // The PGS caption tallies and dimensions only exist after the full pass
    // (the quick pass never reads the graphics payloads), so the presented
    // streams re-merge the reference clip's full-scanned graphics detail —
    // the classic GUI's post-scan refresh; without it every subtitle row
    // would present an empty description.
    for playlist in parsed.iter_mut() {
        if let Ok(metas) = collect_clip_metas(playlist, clip_files, stream_files, &full)
            && let Some(reference) = select_reference(&metas)
            && let Some(file) = reference.scanned
        {
            remerge_graphics_detail(playlist, &file.streams);
        }
    }
    Ok((quick, full))
}

/// Builds the reference-clip selection candidates for `playlist` — one
/// [`ClipMeta`] per clip, angle clips included (an angle clip without clip
/// info is left out; the main clips still resolve the playlist).
///
/// # Errors
/// [`BdError::MissingClipFile`] if a main (angle-0) clip has no `*.clpi`.
fn collect_clip_metas<'a>(
    playlist: &TsPlaylistFile,
    clip_files: &'a BTreeMap<String, TsStreamClipFile>,
    stream_files: &BTreeMap<String, u64>,
    scanned: &'a BTreeMap<String, TsStreamFile>,
) -> Result<Vec<ClipMeta<'a>>, BdError> {
    let mut clips: Vec<ClipMeta<'a>> = Vec::new();
    for clip in &playlist.stream_clips {
        let stem = clip_stem(&clip.name);
        let Some(clip_file) = clip_files.get(&format!("{stem}.CLPI")) else {
            if clip.angle_index == 0 {
                return Err(BdError::MissingClipFile(format!("{stem}.CLPI")));
            }
            continue;
        };
        clips.push(ClipMeta {
            clip_streams: &clip_file.streams,
            scanned: scanned.get(&clip.name),
            has_50hz_video: clip_has_50hz_video(&clip_file.streams),
            relative_length: clip.relative_length,
            length: clip.length,
            stream_file_present: stream_files.contains_key(&clip.name),
        });
    }
    Ok(clips)
}

/// The dependent-view (MVC) video PID of an interleaved 3D source. The clip
/// info omits it, so the resolution presents it from the demuxed file.
const MVC_PID: u16 = 0x1012;

/// Resolves `playlist`'s presented streams ahead of the full packet scan:
/// reset-copies of the reference clip's clip-info streams (plus the
/// interleaved dependent-view stream when the file carries one), merged with
/// the quick-scanned codec detail, and one reset-copy of each video stream per
/// extra camera angle. The full scan then accumulates its measurements into
/// these maps. A playlist with no reference clip keeps empty maps.
fn resolve_playlist_streams(playlist: &mut TsPlaylistFile, metas: &[ClipMeta<'_>]) {
    let Some(reference) = select_reference(metas) else {
        return;
    };
    let mut streams: BTreeMap<u16, TsStream> = BTreeMap::new();
    for (pid, stream) in reference.clip_streams {
        streams.insert(*pid, stream.ts_clone());
    }
    if let Some(file) = reference.scanned {
        if file.interleaved_file.is_some()
            && !streams.contains_key(&MVC_PID)
            && let Some(mvc) = file.streams.get(&MVC_PID)
        {
            streams.insert(MVC_PID, mvc.ts_clone());
        }
        for (pid, src) in &file.streams {
            if let Some(dst) = streams.get_mut(pid) {
                merge_stream(dst, src);
            }
        }
    }

    let angle_count = usize::try_from(playlist.angle_count).unwrap_or(0);
    let mut angle_streams: Vec<BTreeMap<u16, TsStream>> = vec![BTreeMap::new(); angle_count];
    for (pid, stream) in &streams {
        if stream.base().is_video_stream() {
            for (index, angle) in angle_streams.iter_mut().enumerate() {
                let mut clone = stream.ts_clone();
                clone.base_mut().angle_index =
                    i32::try_from(index.wrapping_add(1)).unwrap_or(i32::MAX);
                angle.insert(*pid, clone);
            }
        }
    }
    playlist.streams = streams;
    playlist.angle_streams = angle_streams;
}

/// Re-merges full-scanned graphics detail (PGS caption tallies, dimensions)
/// from the reference clip's `scanned` streams into the playlist's presented
/// streams. The resolution ahead of the full pass merged the quick pass's
/// detail, but the quick pass skips the PGS payloads — only the full pass
/// counts captions. Non-graphics streams keep their quick-merged detail.
fn remerge_graphics_detail(playlist: &mut TsPlaylistFile, scanned: &BTreeMap<u16, TsStream>) {
    for (pid, src) in scanned {
        if !matches!(src, TsStream::Graphics(_)) {
            continue;
        }
        if let Some(dst) = playlist.streams.get_mut(pid) {
            merge_stream(dst, src);
        }
    }
}

/// Zeroes every clip's demux tallies across `playlists` — the reset between
/// the quick pass (which attributed partial windows) and the full measurement
/// pass.
fn clear_measurements(playlists: &mut [TsPlaylistFile]) {
    for playlist in playlists.iter_mut() {
        for clip in &mut playlist.stream_clips {
            clip.payload_bytes = 0;
            clip.packet_count = 0;
            clip.packet_seconds = 0.0;
        }
    }
}

/// Builds the per-clip measurement rows for `playlist` from the full-scan
/// `measured` files: each clip's own demux tallies plus its stream file's
/// whole-file per-stream tallies, limited to the presented streams.
fn build_clip_summaries(
    playlist: &TsPlaylistFile,
    stream_files: &BTreeMap<String, u64>,
    interleaved_files: &BTreeMap<String, u64>,
    measured: &BTreeMap<String, TsStreamFile>,
) -> Vec<ClipSummary> {
    let mut clips = Vec::new();
    for clip in &playlist.stream_clips {
        let file = measured.get(&clip.name);
        let mut streams = Vec::new();
        if let Some(file) = file {
            for pid in &file.stream_order {
                let Some(file_stream) = file.streams.get(pid) else {
                    continue;
                };
                if playlist.streams.contains_key(pid) {
                    streams.push(ClipStreamTally {
                        pid: Pid::new(*pid),
                        stream_type: file_stream.stream_type(),
                        codec_short_name: file_stream.codec_short_name().to_owned(),
                        payload_bytes: file_stream.base().payload_bytes,
                        packet_count: file_stream.base().packet_count,
                    });
                }
            }
        }
        let stem = clip_stem(&clip.name);
        clips.push(ClipSummary {
            name: clip.name.clone(),
            display_name: file
                .map_or_else(|| clip.name.clone(), |f| f.display_name(true).to_owned()),
            file_size: stream_files.get(&clip.name).copied().unwrap_or(0),
            interleaved_file_size: interleaved_files
                .get(&format!("{stem}.SSIF"))
                .copied()
                .unwrap_or(0),
            angle_index: clip.angle_index,
            relative_time_in: clip.relative_time_in,
            length: clip.length,
            payload_bytes: clip.payload_bytes,
            packet_count: clip.packet_count,
            packet_seconds: clip.packet_seconds,
            file_seconds: file.map_or(0.0, |f| f.length),
            streams,
        });
    }
    clips
}

/// Summarises one parsed `playlist` into its [`PlaylistSummary`], returning
/// `(summary, is_50hz)` where the flag is the playlist's contribution to the
/// disc `is_50hz` (its reference clip carrying a 25/50 fps video stream) — the
/// cross-clip resolution over the scanned clip files.
///
/// # Errors
/// [`BdError::MissingClipFile`] if a main (angle-0) clip has no `*.clpi`.
fn build_summary(
    playlist: &TsPlaylistFile,
    clip_files: &BTreeMap<String, TsStreamClipFile>,
    stream_files: &BTreeMap<String, u64>,
    interleaved_files: &BTreeMap<String, u64>,
    scanned: &BTreeMap<String, TsStreamFile>,
    measured: &BTreeMap<String, TsStreamFile>,
) -> Result<(PlaylistSummary, bool), BdError> {
    let metas = collect_clip_metas(playlist, clip_files, stream_files, scanned)?;

    let mut file_size: u64 = 0;
    let mut interleaved_file_size: u64 = 0;
    let mut total_length: f64 = 0.0;
    for clip in &playlist.stream_clips {
        let stem = clip_stem(&clip.name);
        let stream_file_present = stream_files.contains_key(&clip.name);
        file_size = file_size.saturating_add(stream_files.get(&clip.name).copied().unwrap_or(0));
        if stream_file_present {
            interleaved_file_size = interleaved_file_size.saturating_add(
                interleaved_files.get(&format!("{stem}.SSIF")).copied().unwrap_or(0),
            );
        }
        // Angle clips (`angle_index != 0`) replay the main clip's streams; their
        // `*.m2ts` size is folded into `file_size` (above), but `total_length`
        // sums the main (angle-0) clips.
        if clip.angle_index == 0 {
            total_length += clip.length;
        }
    }

    let angle = usize::try_from(playlist.angle_count).unwrap_or(0);
    let (streams, is_50hz) = select_reference(&metas).map_or_else(
        || (Vec::new(), false),
        |r| {
            (
                build_sorted_streams(
                    r.clip_streams,
                    r.scanned.map(|f| &f.streams),
                    playlist,
                    angle,
                ),
                r.has_50hz_video,
            )
        },
    );

    Ok((
        PlaylistSummary {
            name: playlist.name.clone(),
            total_length,
            file_size,
            interleaved_file_size,
            chapter_count: playlist.chapters.len(),
            stream_count: streams.iter().filter(|stream| !stream.ssif_only).count(),
            has_loops: playlist_has_loops(playlist),
            angle_count: angle,
            streams,
            clips: build_clip_summaries(playlist, stream_files, interleaved_files, measured),
            chapters: build_chapter_summaries(playlist, measured, total_length),
        },
        is_50hz,
    ))
}

/// Walks `playlist`'s chapter marks against the measured per-frame video
/// diagnostics: the diagnostics PID is the first (lowest-PID) presented video
/// stream, and each sequenced clip contributes its measured file's list for
/// that PID (`None` — skipped whole — when the file or the PID is absent).
fn build_chapter_summaries(
    playlist: &TsPlaylistFile,
    measured: &BTreeMap<String, TsStreamFile>,
    total_length: f64,
) -> Vec<ChapterSummary> {
    let diag_pid = playlist
        .streams
        .iter()
        .find(|(_, stream)| stream.base().is_video_stream())
        .map(|(pid, _)| *pid);
    let clips: Vec<ChapterClip<'_>> = playlist
        .stream_clips
        .iter()
        .map(|clip| ChapterClip {
            angle_index: clip.angle_index,
            time_in: clip.time_in,
            relative_time_in: clip.relative_time_in,
            diagnostics: diag_pid.and_then(|pid| {
                measured
                    .get(&clip.name)
                    .and_then(|file| file.stream_diagnostics.get(&pid))
                    .map(Vec::as_slice)
            }),
        })
        .collect();
    walk_chapters(&playlist.chapters, total_length, &clips)
}

/// Whether `playlist` loops — two of its main (angle-0) clips replay the same
/// clip file from the same in-time (compared bitwise; the times come straight
/// from the parsed marks, so equal inputs are bit-equal).
fn playlist_has_loops(playlist: &TsPlaylistFile) -> bool {
    let mut seen = BTreeSet::new();
    playlist
        .stream_clips
        .iter()
        .filter(|clip| clip.angle_index == 0)
        .any(|clip| !seen.insert((clip.name.as_str(), clip.time_in.to_bits())))
}

/// Whether any video stream in `streams` is 25 or 50 fps — one playlist's
/// contribution to the disc `is_50hz` flag.
fn clip_has_50hz_video(streams: &BTreeMap<u16, TsStream>) -> bool {
    streams.values().any(|stream| {
        matches!(stream, TsStream::Video(video)
            if matches!(video.frame_rate(), TsFrameRate::Framerate25 | TsFrameRate::Framerate50))
    })
}

/// Builds a playlist's presented streams in PID order: clone the reference
/// clip's clip-info streams, merge the scanned `*.m2ts` codec detail into them,
/// repeat each video stream `1 + angle_count` times (one angle clone per extra
/// camera angle), ordered by PID (a video stream's angle clones follow its main
/// row). Each row's measured rates come from the playlist's resolved stream of
/// the same PID — the main map for a main row, the angle's own map for an
/// angle clone — and stay `0` when the playlist is unresolved (no packet
/// scan).
fn build_sorted_streams(
    clip_streams: &BTreeMap<u16, TsStream>,
    scanned: Option<&BTreeMap<u16, TsStream>>,
    playlist: &TsPlaylistFile,
    angle_count: usize,
) -> Vec<StreamSummary> {
    let mut streams = clip_streams.clone();
    if let Some(scanned) = scanned {
        for (pid, src) in scanned {
            if let Some(dst) = streams.get_mut(pid) {
                merge_stream(dst, src);
            }
        }
    }
    // Graphics detail (the PGS caption tallies and dimensions) only exists
    // after the full pass — the quick merge above carries none — so the rows
    // take it from the resolved presented streams, which
    // [`remerge_graphics_detail`] refreshed when the full pass finished (the
    // classic GUI shows the full scan's counts).
    for (pid, dst) in &mut streams {
        if !matches!(dst, TsStream::Graphics(_)) {
            continue;
        }
        if let Some(src) = playlist.streams.get(pid) {
            merge_stream(dst, src);
        }
    }
    // The interleaved dependent view: when the clip info omits the MVC PID but
    // the resolution presented it from the demuxed file (see
    // [`resolve_playlist_streams`]), it gets a row of its own — never marked
    // hidden (only clip-info streams take the hidden check).
    let ssif_pid = if !streams.contains_key(&MVC_PID)
        && let Some(mvc) = playlist.streams.get(&MVC_PID)
    {
        streams.insert(MVC_PID, mvc.ts_clone());
        Some(MVC_PID)
    } else {
        None
    };

    let mut rows = Vec::new();
    for (pid, stream) in &streams {
        let ssif_only = ssif_pid == Some(*pid);
        // A presented clip stream the playlist's Stream-Number table never
        // declared is hidden — the clip carries it, the playlist hides it.
        let is_hidden = !ssif_only && !playlist.playlist_streams.contains_key(pid);
        let mut row = stream_summary(stream);
        row.is_hidden = is_hidden;
        row.ssif_only = ssif_only;
        set_measured_rates(&mut row, playlist.streams.get(pid));
        row.full_description = full_description(stream, &row);
        rows.push(row);
        if stream.base().is_video_stream() {
            for index in 0..angle_count {
                let mut row = stream_summary(stream);
                row.is_hidden = is_hidden;
                row.ssif_only = ssif_only;
                row.angle_index = index.saturating_add(1);
                set_measured_rates(
                    &mut row,
                    playlist.angle_streams.get(index).and_then(|angle| angle.get(pid)),
                );
                row.full_description = full_description(stream, &row);
                rows.push(row);
            }
        }
    }
    rows
}

/// Copies the measured bitrates from the playlist's resolved `stream` (when
/// the playlist is resolved) into the report `row`.
const fn set_measured_rates(row: &mut StreamSummary, stream: Option<&TsStream>) {
    if let Some(stream) = stream {
        row.bitrate = stream.base().bit_rate;
        row.active_bitrate = stream.base().active_bit_rate;
    }
}

/// Composes the `row`'s full description from `stream`: an audio stream with
/// a resolved rate is respelled with that rate patched in (the description's
/// kbps then reflects the scan), a video stream takes its exact-luminance
/// variant, and everything else keeps the plain description.
fn full_description(stream: &TsStream, row: &StreamSummary) -> String {
    match stream {
        TsStream::Audio(audio) if row.bitrate > 0 => {
            let mut patched = audio.clone();
            patched.base.bit_rate = row.bitrate;
            patched.description()
        }
        TsStream::Video(video) => video.full_description(),
        _ => row.description.clone(),
    }
}

/// Merges the scanned `src` stream's codec detail into the clip-info `dst`
/// stream. The clip-info stream keeps its language and video
/// format/rate/aspect; the scan supplies the encoding profile,
/// channel/sample/bit detail, HDR extension data, and embedded core stream. A
/// type mismatch is a no-op — the clip-info declaration wins.
fn merge_stream(dst: &mut TsStream, src: &TsStream) {
    if dst.base().stream_type != src.base().stream_type {
        return;
    }
    let bit_rate = dst.base().bit_rate.max(src.base().bit_rate);
    let is_vbr = src.base().is_vbr;
    dst.base_mut().bit_rate = bit_rate;
    dst.base_mut().is_vbr = is_vbr;
    match (dst, src) {
        (TsStream::Video(dst), TsStream::Video(src)) => {
            dst.encoding_profile.clone_from(&src.encoding_profile);
            dst.extended_data.clone_from(&src.extended_data);
        }
        (TsStream::Audio(dst), TsStream::Audio(src)) => {
            dst.channel_count = dst.channel_count.max(src.channel_count);
            dst.lfe = dst.lfe.max(src.lfe);
            dst.sample_rate = dst.sample_rate.max(src.sample_rate);
            dst.bit_depth = dst.bit_depth.max(src.bit_depth);
            dst.dial_norm = dst.dial_norm.min(src.dial_norm);
            if src.audio_mode != TsAudioMode::Unknown {
                dst.audio_mode = src.audio_mode;
            }
            dst.has_extensions = src.has_extensions;
            dst.ext_data.clone_from(&src.ext_data);
            if src.core_stream.is_some() && dst.core_stream.is_none() {
                dst.core_stream.clone_from(&src.core_stream);
            }
        }
        (TsStream::Graphics(dst), TsStream::Graphics(src)) => {
            dst.captions = src.captions;
            dst.forced_captions = src.forced_captions;
            dst.width = src.width;
            dst.height = src.height;
            dst.caption_ids.clone_from(&src.caption_ids);
        }
        // Text streams carry no scanned detail (a type mismatch returned above).
        _ => {}
    }
}

/// Reads one presented stream's report fields — the type/codec/language/
/// description values the `streams` diff level emits, plus the report-table
/// columns (alternate codec name, language code, audio channel detail).
fn stream_summary(stream: &TsStream) -> StreamSummary {
    let (codec_short_name, codec_name, description) = match stream {
        TsStream::Video(video) => (
            video.codec_short_name().to_owned(),
            video.codec_name().to_owned(),
            video.description(),
        ),
        TsStream::Audio(audio) => (
            audio.codec_short_name().to_owned(),
            audio.codec_name().to_owned(),
            audio.description(),
        ),
        TsStream::Graphics(graphics) => (
            graphics.codec_short_name().to_owned(),
            graphics.codec_name().to_owned(),
            graphics.description(),
        ),
        TsStream::Text(text) => {
            (text.codec_short_name().to_owned(), text.codec_name().to_owned(), text.description())
        }
    };
    let (channel_description, sample_rate, bit_depth, channel_count) = match stream {
        TsStream::Audio(audio) => {
            (audio.channel_description(), audio.sample_rate, audio.bit_depth, audio.channel_count)
        }
        _ => (String::new(), 0, 0, 0),
    };
    let height = match stream {
        TsStream::Video(video) => video.height,
        _ => 0,
    };
    StreamSummary {
        pid: stream.pid(),
        stream_type: stream.stream_type(),
        codec_short_name,
        codec_name,
        codec_alt_name: stream.codec_alt_name(),
        bitrate: 0,
        active_bitrate: 0,
        language_name: stream.base().language_name.clone().unwrap_or_default(),
        language_code: stream.base().language_code().unwrap_or_default().to_owned(),
        full_description: description.clone(),
        description,
        channel_description,
        sample_rate,
        bit_depth,
        channel_count,
        height,
        angle_index: 0,
        is_hidden: false,
        ssif_only: false,
    }
}

/// Scans every `*.m2ts` under `stream_dir` (the [`TsStreamFile::scan`] packet
/// pass), keyed by upper-cased name. Each file is scanned once, with the
/// playlists handed in so the demux can attribute packets to their clips. A
/// file with an interleaved 3D counterpart (`SSIF/<stem>.SSIF` under
/// `ssif_dir`) is demuxed through it, so the dependent-view streams register.
/// `is_full_scan` selects the pass: the quick pass stops once every stream's
/// codec detail is initialised; the full pass demuxes every packet to EOF —
/// the measurement pass. Used only at the `streams` level; the
/// disc/`playlists` levels skip it entirely. In strict mode a failed open/scan
/// propagates; in resilient mode it is recorded and the file skipped — its
/// playlists fall back to the clip-info detail. The one exception is
/// [`BdError::ScanCancelled`] (the caller's flag in the [`Progress`]), which
/// aborts the pass in both modes without being recorded.
fn scan_stream_files(
    stream_dir: Option<&dyn BdDir>,
    ssif_dir: Option<&dyn BdDir>,
    playlists: &mut [TsPlaylistFile],
    scan_files: Option<&BTreeSet<String>>,
    progress: &mut Progress<'_>,
    sink: &mut Sink<'_>,
    is_full_scan: bool,
) -> Result<BTreeMap<String, TsStreamFile>, BdError> {
    let mut scanned = BTreeMap::new();
    let Some(dir) = stream_dir else {
        return Ok(scanned);
    };
    let files = sink.absorb(
        ScanStage::Discovery,
        dir.name(),
        Vec::new(),
        vfs::find_files(dir, BdFileKind::Stream).map_err(BdError::from),
    )?;
    let mut ssif_files: BTreeMap<String, Box<dyn BdFile>> = BTreeMap::new();
    if let Some(dir) = ssif_dir {
        let found = sink.absorb(
            ScanStage::Discovery,
            dir.name(),
            Vec::new(),
            vfs::find_files(dir, BdFileKind::Interleaved).map_err(BdError::from),
        )?;
        for file in found {
            ssif_files.insert(file.name().to_ascii_uppercase(), file);
        }
    }
    for file in files {
        let name = file.name().to_ascii_uppercase();
        if scan_files.is_some_and(|selected| !selected.contains(&name)) {
            continue;
        }
        let stem = clip_stem(&name);
        let interleaved = ssif_files.remove(&format!("{stem}.SSIF"));
        // The expected source size — what `scan_total` budgeted for this file
        // — so the progress can snap to the file boundary either way.
        let source_size = interleaved.as_ref().map_or_else(|| file.length(), |f| f.length());
        let target = progress.done.saturating_add(source_size);
        let scan = scan_one_stream_file(&*file, interleaved, playlists, is_full_scan, progress);
        // Cancellation aborts the whole open, in strict and resilient modes
        // alike — the sink collects disc damage, not the caller's abort, so
        // the cancelled error is never recorded per-file, and no further
        // progress (not even this file's boundary snap) is reported.
        if matches!(scan, Err(BdError::ScanCancelled)) {
            return Err(BdError::ScanCancelled);
        }
        progress.finish_file(&name, target);
        if let Some(stream_file) =
            sink.absorb(ScanStage::StreamFile, file.name(), None, scan.map(Some))?
        {
            scanned.insert(name, stream_file);
        }
    }
    Ok(scanned)
}

/// Opens and scans one `*.m2ts` (the per-file unit [`scan_stream_files`]
/// isolates), demuxing through its `interleaved` 3D source when it has one.
/// The demux pulls its bytes through the scan's [`Progress`].
fn scan_one_stream_file(
    file: &dyn BdFile,
    interleaved: Option<Box<dyn BdFile>>,
    playlists: &mut [TsPlaylistFile],
    is_full_scan: bool,
    progress: &mut Progress<'_>,
) -> Result<TsStreamFile, BdError> {
    let mut stream_file = TsStreamFile::new(file.name());
    stream_file.interleaved_file = interleaved.map(TsInterleavedFile::new);
    // Select the demux source the way `scan_source` would (the interleaved
    // 3D file when present), but wrapped so each read advances the progress.
    let inner = match &stream_file.interleaved_file {
        Some(interleaved) => interleaved.open_read().map_err(BdError::Io)?,
        None => file.open_read()?,
    };
    // The shared reference is copied out before the reader mutably borrows
    // the progress, so the demux can poll it alongside the counting reads.
    let cancel = progress.cancel;
    let mut reader = CountingReader { inner, name: file.name().to_ascii_uppercase(), progress };
    stream_file.scan_cancellable(&mut reader, playlists, is_full_scan, cancel)?;
    Ok(stream_file)
}

/// Picks the playlist's reference clip — the clip whose streams become the
/// presented set. Returns `None` for an empty clip list (no reference, no
/// presented streams).
fn select_reference<'a, 'b>(clips: &'b [ClipMeta<'a>]) -> Option<&'b ClipMeta<'a>> {
    let mut reference = clips.first()?;
    for clip in clips {
        // Step A: a clip whose `*.m2ts` exists beats a reference without one.
        if !reference.stream_file_present && clip.stream_file_present {
            reference = clip;
        }
        // Step B: a clip with more clip-info streams wins if it is not
        // negligibly short (`relative_length > 0.01`); otherwise a longer clip
        // with a stream file wins. Both arms assign the reference, so the two
        // conditions collapse to one short-circuiting `||` (the first is still
        // evaluated first, preserving the else-if precedence).
        if (clip.clip_streams.len() > reference.clip_streams.len() && clip.relative_length > 0.01)
            || (clip.length > reference.length && clip.stream_file_present)
        {
            reference = clip;
        }
    }
    Some(reference)
}

/// The clip stem of a stream-file/clip name — the name without its `.M2TS` or
/// `.FMTS` extension. Clips pair with their `*.clpi`/`*.ssif` siblings by this
/// stem, which the siblings share but the extension does not; an `FMTS` clip
/// (libbluray `_fill_clip`) names a `*.FMTS` stream file yet still a `*.CLPI`.
fn clip_stem(name: &str) -> &str {
    name.strip_suffix(".M2TS").or_else(|| name.strip_suffix(".FMTS")).unwrap_or(name)
}

/// The file handles of one `BDMV/BACKUP` metadata directory, keyed by
/// upper-cased name — the recovery pool a damaged primary's replacement is
/// drawn from. Empty when there is no such pool to draw from (see
/// `discover_backups`).
type BackupFiles = BTreeMap<String, Box<dyn BdFile>>;

/// The `BDMV/BACKUP` recovery pools — `(index.bdmv, PLAYLIST, CLIPINF)` — built
/// once per open and drawn from only when a primary read fails.
///
/// **Resilient mode only, and this is where that is decided.** Strict `open` is
/// the honest fail-fast path, so a recovery facility belongs to the resilient
/// scan that `open_resilient` (the CLI default) runs: a strict scan skips the
/// probe entirely (three empty pools, no extra IO, no new failure points) and
/// every downstream backup lookup therefore misses. A directory-listing failure
/// anywhere in the probe is recorded once
/// under `BACKUP` — surfaced, not silently swallowed — and leaves the pools
/// empty; a disc with no `BDMV/BACKUP` yields empty pools with nothing
/// recorded.
fn discover_backups(
    bdmv: &dyn BdDir,
    sink: &mut Sink<'_>,
) -> (BackupFiles, BackupFiles, BackupFiles) {
    let empty = || (BackupFiles::new(), BackupFiles::new(), BackupFiles::new());
    if sink.errors.is_none() {
        return empty();
    }
    match collect_backups(bdmv) {
        Ok(pools) => pools,
        Err(reason) => {
            sink.record(ScanStage::Discovery, "BACKUP", reason);
            empty()
        }
    }
}

/// Enumerates the three `BDMV/BACKUP` recovery pools, propagating the first
/// directory-listing IO error. A disc with no `BDMV/BACKUP` (or a BACKUP
/// missing the `PLAYLIST`/`CLIPINF` subdirectory) yields the corresponding
/// empty pool.
fn collect_backups(bdmv: &dyn BdDir) -> Result<(BackupFiles, BackupFiles, BackupFiles), BdError> {
    let Some(backup) = vfs::find_directory(bdmv, BdmvDir::Backup)? else {
        return Ok((BackupFiles::new(), BackupFiles::new(), BackupFiles::new()));
    };
    let index = list_backup_files(&*backup)?;
    let playlist = backup_subdir_files(&*backup, BdmvDir::Playlist)?;
    let clipinf = backup_subdir_files(&*backup, BdmvDir::ClipInf)?;
    Ok((index, playlist, clipinf))
}

/// The [`BackupFiles`] of the `which` subdirectory of a `BDMV/BACKUP` directory,
/// or an empty pool when that subdirectory is absent.
fn backup_subdir_files(backup: &dyn BdDir, which: BdmvDir) -> Result<BackupFiles, BdError> {
    vfs::find_directory(backup, which)?
        .map_or_else(|| Ok(BackupFiles::new()), |dir| list_backup_files(&*dir))
}

/// Lists `dir`'s file handles into a [`BackupFiles`] map keyed by upper-cased
/// name, propagating the directory-listing IO error.
fn list_backup_files(dir: &dyn BdDir) -> Result<BackupFiles, BdError> {
    let mut map = BackupFiles::new();
    for file in dir.get_files()? {
        map.insert(file.name().to_ascii_uppercase(), file);
    }
    Ok(map)
}

/// Reads and parses the BACKUP counterpart of `name` from a pre-listed
/// [`BackupFiles`] pool, matching the upper-cased name. Returns `None` when the
/// pool holds no such file, and `Some(Err)` when it does but the read or parse
/// failed. The backup is handed to the *same* `parse` the primary uses, so it
/// inherits every hostile-input cap — a malicious BACKUP is trusted no more
/// than a malicious primary.
fn recover_backup<T>(
    backup: &BackupFiles,
    name: &str,
    parse: impl FnOnce(&str, &[u8]) -> Result<T, BdError>,
) -> Option<Result<T, BdError>> {
    let file = backup.get(&name.to_ascii_uppercase())?;
    Some(read_file(&**file).and_then(|bytes| parse(file.name(), &bytes)))
}

/// Reads a VFS file fully into a byte vector, mapping IO errors to [`BdError::Io`].
fn read_file(file: &dyn BdFile) -> Result<Vec<u8>, BdError> {
    let mut reader = file.open_read()?;
    let mut bytes = Vec::new();
    reader.read_to_end(&mut bytes)?;
    Ok(bytes)
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeMap, BTreeSet};
    use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
    use std::path::PathBuf;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};

    use proptest::prelude::{prop_assert, prop_assert_eq, proptest};

    use super::{
        BdError, BdRom, ClipMeta, ClipSummary, MVC_PID, PlaylistFilter, PlaylistSummary, Progress,
        ScanMode, ScanProgress, ScanStage, Sink, TsPlaylistFile, TsStreamFile, backup_subdir_files,
        build_chapter_summaries, build_clip_summaries, build_sorted_streams, clear_measurements,
        clip_has_50hz_video, clip_stem, collect_backups, merge_stream, rate_over, read_disc_title,
        read_file, resolve_playlist_streams, scan_stream_files, scan_total, select_reference,
        stream_summary, walked_disc_root,
    };
    use crate::bdrom::clpi::TsStreamClip;
    use crate::bdrom::interleaved::{MemBdFile, TsInterleavedFile};
    use crate::bdrom::m2ts::packets::{packet, pat_payload, pes_dts, pes_pts, pmt_payload};
    use crate::discovery::BdmvDir;
    use crate::primitives::Pid;
    use crate::stream::{
        TsAudioMode, TsAudioStream, TsFrameRate, TsGraphicsStream, TsStream, TsStreamType,
        TsTextStream, TsVideoFormat, TsVideoStream,
    };
    use crate::vfs::fs::{FsDir, FsFile};
    use crate::vfs::{BdDir, BdFile, ReadSeek, SearchOption};

    // ── synthetic metadata builders (minimal valid `*.clpi` / `*.mpls`) ──────

    /// A valid `*.clpi`: `HDMV0300`, `ProgramInfo` at offset 16, one program
    /// sequence, one entry per `(pid, coding_type, 4-byte payload)`.
    fn clpi(entries: &[(u16, u8, [u8; 4])]) -> Vec<u8> {
        let mut clip_data = vec![0_u8, 1]; // reserved + num_prog = 1
        clip_data.extend_from_slice(&[0_u8; 6]); // spn start + program_map_pid
        clip_data.push(u8::try_from(entries.len()).unwrap()); // stream count at 8
        clip_data.push(0); // 9: num_groups; stream entries start at 10
        for &(pid, coding_type, payload) in entries {
            clip_data.extend_from_slice(&pid.to_be_bytes());
            clip_data.push(5); // coding-info length (type + 4 payload)
            clip_data.push(coding_type);
            clip_data.extend_from_slice(&payload);
        }
        let mut buf = b"HDMV0300".to_vec();
        buf.extend_from_slice(&[0_u8; 4]); // 8..12
        buf.extend_from_slice(&16_u32.to_be_bytes()); // 12..16 ProgramInfo addr
        buf.extend_from_slice(&u32::try_from(clip_data.len()).unwrap().to_be_bytes());
        buf.extend_from_slice(&clip_data);
        buf
    }

    /// A valid single-item `*.mpls` with no extra camera angles (the common case).
    fn mpls(item_name: &str, in_t: u32, out_t: u32, chapters: &[(u8, u16, u32)]) -> Vec<u8> {
        mpls_angles(item_name, in_t, out_t, &[], chapters)
    }

    /// A valid single-item `*.mpls` like [`mpls_full`], with an empty
    /// Stream-Number table.
    fn mpls_angles(
        item_name: &str,
        in_t: u32,
        out_t: u32,
        angle_names: &[&str],
        chapters: &[(u8, u16, u32)],
    ) -> Vec<u8> {
        mpls_items(&[item_name], in_t, out_t, angle_names, &[], chapters)
    }

    /// A valid single-item `*.mpls` with no angles that declares the given
    /// audio PIDs in its Stream-Number table.
    fn mpls_declared(
        item_name: &str,
        in_t: u32,
        out_t: u32,
        declared_audio: &[u16],
        chapters: &[(u8, u16, u32)],
    ) -> Vec<u8> {
        mpls_items(&[item_name], in_t, out_t, &[], declared_audio, chapters)
    }

    /// A valid `*.mpls`: `MPLS0300`, one identical `PlayItem` per name in
    /// `item_names` with the given in/out times (45 kHz ticks), `angle_names`
    /// extra camera angles, a Stream-Number table declaring `declared_audio`
    /// as AC3 audio entries, and the given `(chapter_type, file_index, tick)`
    /// marks. Repeating a name yields a looping playlist (the same clip
    /// replayed from the same in-time).
    fn mpls_items(
        item_names: &[&str],
        in_t: u32,
        out_t: u32,
        angle_names: &[&str],
        declared_audio: &[u16],
        chapters: &[(u8, u16, u32)],
    ) -> Vec<u8> {
        mpls_items_codec(*b"M2TS", item_names, in_t, out_t, angle_names, declared_audio, chapters)
    }

    /// A single-item-per-name `*.mpls` whose play items (and angles) carry the
    /// given 4-byte `codec` id — `*b"M2TS"` for ordinary clips, `*b"FMTS"` for the
    /// `*.FMTS` variant.
    fn mpls_items_codec(
        codec: [u8; 4],
        item_names: &[&str],
        in_t: u32,
        out_t: u32,
        angle_names: &[&str],
        declared_audio: &[u16],
        chapters: &[(u8, u16, u32)],
    ) -> Vec<u8> {
        let mut items = Vec::new();
        for item_name in item_names {
            let mut body = Vec::new();
            let mut name = item_name.as_bytes().to_vec();
            name.resize(5, 0);
            body.extend_from_slice(&name); // +2..7
            body.extend_from_slice(&codec); // +7..11
            body.push(0); // +11
            body.push(if angle_names.is_empty() { 0 } else { 0x10 }); // +12 multiangle flag
            body.push(0); // +13
            body.extend_from_slice(&in_t.to_be_bytes()); // +14..18
            body.extend_from_slice(&out_t.to_be_bytes()); // +18..22
            body.extend_from_slice(&[0_u8; 12]); // +22..34
            if !angle_names.is_empty() {
                body.push(u8::try_from(angle_names.len().wrapping_add(1)).unwrap()); // angle count
                body.push(0); // reserved
                for angle in angle_names {
                    let mut angle_bytes = angle.as_bytes().to_vec();
                    angle_bytes.resize(5, 0);
                    body.extend_from_slice(&angle_bytes); // angle name (5)
                    body.extend_from_slice(&codec); // angle type (4)
                    body.push(0); // reserved (1)
                }
            }
            body.extend_from_slice(&[0_u8; 2]); // stream-info length
            body.extend_from_slice(&[0_u8; 2]); // reserved
            body.push(0); // video count
            body.push(u8::try_from(declared_audio.len()).unwrap()); // audio count
            body.extend_from_slice(&[0_u8; 5]); // remaining 5 stream counts (all zero)
            body.extend_from_slice(&[0_u8; 5]); // reserved
            for pid in declared_audio {
                body.push(3); // header length (type + PID)
                body.push(1); // header type 1: the PID follows directly
                body.extend_from_slice(&pid.to_be_bytes());
                body.push(5); // stream length (type byte + format + language)
                body.push(0x81); // AC3 audio
                body.push(0x61); // 5.1 / 48 kHz
                body.extend_from_slice(b"eng");
            }
            items.extend_from_slice(&u16::try_from(body.len()).unwrap().to_be_bytes());
            items.extend_from_slice(&body);
        }

        let playlist_offset: usize = 0x3C;
        let mut playlist = Vec::new();
        playlist.extend_from_slice(&[0_u8; 4]); // PlayList length
        playlist.extend_from_slice(&[0_u8; 2]); // reserved
        playlist.extend_from_slice(&u16::try_from(item_names.len()).unwrap().to_be_bytes());
        playlist.extend_from_slice(&[0_u8; 2]); // sub-item count
        playlist.extend_from_slice(&items);
        let chapters_offset = playlist_offset.wrapping_add(playlist.len());

        let mut mark = Vec::new();
        mark.extend_from_slice(&[0_u8; 4]); // PlayListMark length
        mark.extend_from_slice(&u16::try_from(chapters.len()).unwrap().to_be_bytes());
        for &(chapter_type, file_index, tick) in chapters {
            let mut entry = vec![0_u8, chapter_type];
            entry.extend_from_slice(&file_index.to_be_bytes());
            entry.extend_from_slice(&tick.to_be_bytes());
            entry.resize(14, 0);
            mark.extend_from_slice(&entry);
        }

        let mut buf = b"MPLS0300".to_vec();
        buf.extend_from_slice(&u32::try_from(playlist_offset).unwrap().to_be_bytes());
        buf.extend_from_slice(&u32::try_from(chapters_offset).unwrap().to_be_bytes());
        buf.extend_from_slice(&[0_u8; 4]); // extensions offset
        buf.resize(0x38, 0);
        buf.push(0); // misc flags at 0x38
        buf.resize(playlist_offset, 0);
        buf.extend_from_slice(&playlist);
        buf.extend_from_slice(&mark);
        buf
    }

    /// A valid `*.mpls` with zero play items — its `stream_clips` are empty, so
    /// the reference-clip selection finds nothing.
    fn empty_mpls() -> Vec<u8> {
        let playlist_offset: usize = 0x3C;
        let mut playlist = Vec::new();
        playlist.extend_from_slice(&[0_u8; 4]); // PlayList length
        playlist.extend_from_slice(&[0_u8; 2]); // reserved
        playlist.extend_from_slice(&0_u16.to_be_bytes()); // item count = 0
        playlist.extend_from_slice(&[0_u8; 2]); // sub-item count
        let chapters_offset = playlist_offset.wrapping_add(playlist.len());

        let mut mark = Vec::new();
        mark.extend_from_slice(&[0_u8; 4]); // PlayListMark length
        mark.extend_from_slice(&0_u16.to_be_bytes()); // zero marks

        let mut buf = b"MPLS0300".to_vec();
        buf.extend_from_slice(&u32::try_from(playlist_offset).unwrap().to_be_bytes());
        buf.extend_from_slice(&u32::try_from(chapters_offset).unwrap().to_be_bytes());
        buf.extend_from_slice(&[0_u8; 4]); // extensions offset
        buf.resize(0x38, 0);
        buf.push(0); // misc flags at 0x38
        buf.resize(playlist_offset, 0);
        buf.extend_from_slice(&playlist);
        buf.extend_from_slice(&mark);
        buf
    }

    /// `bdmt_eng.xml` with the given title in the `discinfo` namespace.
    fn title_xml(name: &str) -> Vec<u8> {
        format!(
            "<disclib xmlns:di=\"urn:BDA:bdmv;discinfo\">\
             <di:discinfo><di:title><di:name>{name}</di:name></di:title></di:discinfo></disclib>"
        )
        .into_bytes()
    }

    // ── throwaway on-disk BD fixture ────────────────────────────────────────

    struct TempDisc {
        root: PathBuf,
    }

    impl TempDisc {
        /// Creates `dirs` (possibly empty) and writes `files` (paths relative to the
        /// disc root) under a unique temp directory, removed on drop.
        fn build(dirs: &[&str], files: &[(&str, Vec<u8>)]) -> Self {
            static COUNTER: AtomicU32 = AtomicU32::new(0);
            let unique = COUNTER.fetch_add(1, Ordering::Relaxed);
            let mut root = std::env::temp_dir();
            root.push(format!("bdinfo-rs-disc-{}-{unique}", std::process::id()));
            std::fs::create_dir_all(&root).expect("create root");
            for dir in dirs {
                std::fs::create_dir_all(root.join(dir)).expect("create dir");
            }
            for (path, bytes) in files {
                let full = root.join(path);
                std::fs::create_dir_all(full.parent().expect("file has parent")).expect("parents");
                std::fs::write(&full, bytes).expect("write file");
            }
            Self { root }
        }

        fn open(&self) -> Result<BdRom, BdError> {
            BdRom::open(&FsDir::new(self.root.clone()), ScanMode::Metadata)
        }

        fn open_scanned(&self) -> Result<BdRom, BdError> {
            BdRom::open(&FsDir::new(self.root.clone()), ScanMode::Full)
        }

        fn open_codecs(&self) -> Result<BdRom, BdError> {
            BdRom::open(&FsDir::new(self.root.clone()), ScanMode::Codecs)
        }
    }

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

    // ── pure helpers ────────────────────────────────────────────────────────

    #[test]
    fn read_disc_title_handles_every_case() {
        // Normal title, with a leading UTF-8 BOM (the parser strips it).
        let with_bom = format!("\u{feff}{}", String::from_utf8(title_xml("BROTHER")).unwrap());
        assert_eq!(read_disc_title(&with_bom).as_deref(), Some("BROTHER"));
        // Empty title is preserved as Some("") (only "blu-ray" is nulled).
        assert_eq!(
            read_disc_title(&String::from_utf8(title_xml("")).unwrap()).as_deref(),
            Some("")
        );
        // The "blu-ray" placeholder (any case) becomes None.
        assert_eq!(read_disc_title(&String::from_utf8(title_xml("Blu-ray")).unwrap()), None);
        // Malformed XML → None.
        assert_eq!(read_disc_title("<not xml"), None);
        // Missing discinfo / title / name nodes → None.
        assert_eq!(read_disc_title("<disclib></disclib>"), None);
        assert_eq!(
            read_disc_title(
                "<disclib xmlns:di=\"urn:BDA:bdmv;discinfo\"><di:discinfo></di:discinfo></disclib>"
            ),
            None
        );
        assert_eq!(
            read_disc_title(
                "<disclib xmlns:di=\"urn:BDA:bdmv;discinfo\">\
                 <di:discinfo><di:title></di:title></di:discinfo></disclib>"
            ),
            None
        );
    }

    /// A clip-info stream map of `n` dummy streams — controls `clip_streams.len()`,
    /// the only thing [`select_reference`] reads off it.
    fn dummy_streams(n: usize) -> BTreeMap<u16, TsStream> {
        (0..n)
            .map(|i| (u16::try_from(i).unwrap(), TsStream::Audio(TsAudioStream::default())))
            .collect()
    }

    /// A playlist with no clips and empty stream maps — the unresolved stand-in
    /// for the helpers that read `streams`/`angle_streams`.
    fn bare_playlist() -> TsPlaylistFile {
        TsPlaylistFile {
            file_type: "MPLS0300".to_owned(),
            name: "00000.MPLS".to_owned(),
            mvc_base_view_r: false,
            chapters: Vec::new(),
            playlist_streams: BTreeMap::new(),
            streams: BTreeMap::new(),
            angle_streams: Vec::new(),
            stream_clips: Vec::new(),
            angle_count: 0,
        }
    }

    /// Builds a [`ClipMeta`] borrowing `streams`, varying the reference-selection
    /// fields the selection loop reads.
    fn meta(
        streams: &BTreeMap<u16, TsStream>,
        length: f64,
        relative: f64,
        has_stream_file: bool,
    ) -> ClipMeta<'_> {
        ClipMeta {
            clip_streams: streams,
            scanned: None,
            has_50hz_video: false,
            relative_length: relative,
            length,
            stream_file_present: has_stream_file,
        }
    }

    #[test]
    fn select_reference_picks_per_the_selection_rules() {
        let s2 = dummy_streams(2);
        let s5 = dummy_streams(5);

        // Empty → None; single clip → itself.
        assert!(select_reference(&[]).is_none());
        let one = [meta(&s2, 10.0, 1.0, true)];
        assert_eq!(select_reference(&one).unwrap().clip_streams.len(), 2);

        // Step A: the first clip lacks a stream file, the second has one (equal
        // counts/length, so only step A can promote it).
        let step_a = [meta(&s2, 10.0, 1.0, false), meta(&s2, 10.0, 1.0, true)];
        assert!(select_reference(&step_a).unwrap().stream_file_present);

        // Step B (if): more clip-info streams and relative_length > 0.01 wins.
        let step_b_if = [meta(&s2, 10.0, 1.0, true), meta(&s5, 10.0, 1.0, true)];
        assert_eq!(select_reference(&step_b_if).unwrap().clip_streams.len(), 5);
        // …but relative_length == 0.01 (not > 0.01) does NOT win on stream count.
        let at_threshold = [meta(&s2, 10.0, 1.0, true), meta(&s5, 10.0, 0.01, true)];
        assert_eq!(select_reference(&at_threshold).unwrap().clip_streams.len(), 2);

        // Step B (else): equal stream counts but a longer clip with a stream file.
        let step_b_else = [meta(&s2, 10.0, 1.0, true), meta(&s2, 20.0, 1.0, true)];
        assert_eq!(select_reference(&step_b_else).unwrap().length.to_bits(), 20.0_f64.to_bits());
        // …a longer clip WITHOUT a stream file does not win.
        let longer_no_file = [meta(&s2, 10.0, 1.0, true), meta(&s2, 20.0, 1.0, false)];
        assert_eq!(select_reference(&longer_no_file).unwrap().length.to_bits(), 10.0_f64.to_bits());
    }

    #[test]
    fn clip_has_50hz_video_detects_25_and_50fps() {
        // A 25 fps video (alongside audio) → 50 Hz.
        let mut at25 = BTreeMap::new();
        let mut v = TsVideoStream::default();
        v.set_frame_rate(TsFrameRate::Framerate25);
        at25.insert(0x1011, TsStream::Video(v));
        at25.insert(0x1100, TsStream::Audio(TsAudioStream::default()));
        assert!(clip_has_50hz_video(&at25));

        // 50 fps too.
        let mut at50 = BTreeMap::new();
        let mut v = TsVideoStream::default();
        v.set_frame_rate(TsFrameRate::Framerate50);
        at50.insert(0x1011, TsStream::Video(v));
        assert!(clip_has_50hz_video(&at50));

        // A 24 fps video (and audio) → not 50 Hz.
        let mut at24 = BTreeMap::new();
        let mut v = TsVideoStream::default();
        v.set_frame_rate(TsFrameRate::Framerate24);
        at24.insert(0x1011, TsStream::Video(v));
        at24.insert(0x1100, TsStream::Audio(TsAudioStream::default()));
        assert!(!clip_has_50hz_video(&at24));
    }

    /// The video stream inside `s`, or `None` for any other variant.
    fn as_video(s: &TsStream) -> Option<&TsVideoStream> {
        if let TsStream::Video(video) = s { Some(video) } else { None }
    }

    /// The audio stream inside `s`, or `None` for any other variant.
    #[test]
    fn graphics_detail_remerges_after_the_full_pass() {
        // The presented PGS stream starts with the quick pass's empty detail;
        // the re-merge copies the full scan's caption tallies and dimensions.
        let mut playlist =
            TsPlaylistFile::scan("00000.mpls", &mpls("00000", 0, 4_500_000, &[])).unwrap();
        playlist.streams = BTreeMap::from([
            (0x1200_u16, TsStream::Graphics(TsGraphicsStream::default())),
            (0x1011, TsStream::Video(TsVideoStream::default())),
        ]);
        let scanned_pgs = TsGraphicsStream {
            captions: 837,
            width: 1920,
            height: 1080,
            ..TsGraphicsStream::default()
        };
        let mut scanned_video = TsVideoStream::default();
        scanned_video.set_video_format(TsVideoFormat::Videoformat2160p);
        let scanned = BTreeMap::from([
            (0x1200_u16, TsStream::Graphics(scanned_pgs)),
            // A non-graphics source is skipped (the quick-merged detail
            // stays), and a PID the playlist does not present adds nothing.
            (0x1011, TsStream::Video(scanned_video)),
            (0x1300, TsStream::Graphics(TsGraphicsStream::default())),
        ]);
        super::remerge_graphics_detail(&mut playlist, &scanned);

        // The summary view proves the merge: the PGS row carries the full
        // pass's dimensions and caption count; the video row kept its quick
        // detail (non-graphics sources are not re-merged).
        let graphics = stream_summary(playlist.streams.get(&0x1200).unwrap());
        assert_eq!(graphics.description, "1920x1080 / 837 Captions");
        let video = stream_summary(playlist.streams.get(&0x1011).unwrap());
        assert_eq!(video.height, 0, "non-graphics sources are not re-merged");
        assert!(!playlist.streams.contains_key(&0x1300));
    }

    fn as_audio(s: &TsStream) -> Option<&TsAudioStream> {
        if let TsStream::Audio(audio) = s { Some(audio) } else { None }
    }

    /// The graphics stream inside `s`, or `None` for any other variant.
    fn as_graphics(s: &TsStream) -> Option<&TsGraphicsStream> {
        if let TsStream::Graphics(graphics) = s { Some(graphics) } else { None }
    }

    #[test]
    fn merge_stream_copies_scanned_detail_per_kind() {
        // Video: the scanned encoding profile + extended data flow into the clip
        // stream; the clip stream's video format (not part of the merge) is kept.
        let mut dst = TsVideoStream::default();
        dst.base.stream_type = TsStreamType::AvcVideo;
        dst.set_video_format(TsVideoFormat::Videoformat1080p);
        let mut src = TsVideoStream::default();
        src.base.stream_type = TsStreamType::AvcVideo;
        src.encoding_profile = Some("High Profile 4.1".to_owned());
        src.base.bit_rate = 5;
        src.base.is_vbr = true;
        let mut video = TsStream::Video(dst);
        merge_stream(&mut video, &TsStream::Video(src));
        // The `None` arm of `as_audio` is exercised here (video is not audio).
        assert!(as_audio(&video).is_none());
        let merged = as_video(&video).unwrap();
        assert_eq!(merged.encoding_profile.as_deref(), Some("High Profile 4.1"));
        assert_eq!(merged.height, 1080); // clip-info format preserved
        assert_eq!(merged.base.bit_rate, 5); // max(0, 5)
        assert!(merged.base.is_vbr);

        // Audio: count/sample/depth take the max, dial-norm the min; mode/extension/
        // core flow in; the clip-info language survives.
        let mut dst = TsAudioStream::default();
        dst.base.stream_type = TsStreamType::DtsHdMasterAudio;
        dst.base.set_language_code("jpn");
        let mut src = TsAudioStream::default();
        src.base.stream_type = TsStreamType::DtsHdMasterAudio;
        src.channel_count = 6;
        src.lfe = 1;
        src.sample_rate = 48_000;
        src.bit_depth = 24;
        src.dial_norm = -27;
        src.audio_mode = TsAudioMode::Extended;
        src.has_extensions = true;
        src.ext_data = Some("x".to_owned());
        src.core_stream = Some(Box::new(TsAudioStream::default()));
        let mut audio = TsStream::Audio(dst);
        merge_stream(&mut audio, &TsStream::Audio(src));
        let merged = as_audio(&audio).unwrap();
        assert_eq!((merged.channel_count, merged.lfe), (6, 1));
        assert_eq!((merged.sample_rate, merged.bit_depth), (48_000, 24));
        assert_eq!(merged.dial_norm, -27); // min(0, -27)
        assert_eq!(merged.audio_mode, TsAudioMode::Extended);
        assert!(merged.has_extensions);
        assert_eq!(merged.ext_data.as_deref(), Some("x"));
        assert!(merged.core_stream.is_some());
        assert_eq!(merged.base.language_name.as_deref(), Some("Japanese"));

        // Graphics: caption tallies + resolution copied.
        let mut dst = TsGraphicsStream::default();
        dst.base.stream_type = TsStreamType::PresentationGraphics;
        let mut src = TsGraphicsStream::default();
        src.base.stream_type = TsStreamType::PresentationGraphics;
        src.width = 1920;
        src.height = 1080;
        src.captions = 5;
        src.forced_captions = 1;
        let mut graphics = TsStream::Graphics(dst);
        merge_stream(&mut graphics, &TsStream::Graphics(src));
        // The `None` arms of `as_video`/`as_graphics` are exercised across variants.
        assert!(as_video(&audio).is_none());
        assert!(as_graphics(&video).is_none());
        let merged = as_graphics(&graphics).unwrap();
        assert_eq!((merged.width, merged.height), (1920, 1080));
        assert_eq!((merged.captions, merged.forced_captions), (5, 1));
    }

    #[test]
    fn merge_stream_core_and_dialnorm_edge_cases() {
        // dial-norm min keeps the already-lower clip value; an existing core stream is
        // NOT overwritten by the source's (the `dst.core_stream.is_none()` guard). The
        // two cores carry distinct channel counts so a `&&`→`||` mutant — which would
        // overwrite — is caught: the merged core must stay the destination's.
        let mut dst = TsAudioStream::default();
        dst.base.stream_type = TsStreamType::Ac3TrueHdAudio;
        dst.dial_norm = -31; // already lower than the source's -27
        dst.core_stream =
            Some(Box::new(TsAudioStream { channel_count: 9, ..TsAudioStream::default() }));
        let mut src = TsAudioStream::default();
        src.base.stream_type = TsStreamType::Ac3TrueHdAudio;
        src.dial_norm = -27;
        src.core_stream =
            Some(Box::new(TsAudioStream { channel_count: 5, ..TsAudioStream::default() }));
        let mut audio = TsStream::Audio(dst);
        merge_stream(&mut audio, &TsStream::Audio(src));
        let merged = as_audio(&audio).unwrap();
        assert_eq!(merged.dial_norm, -31); // min(-31, -27)
        assert_eq!(merged.core_stream.as_ref().unwrap().channel_count, 9); // kept dst's core

        // A source with no core, onto a destination with no core → still none.
        let mut dst = TsAudioStream::default();
        dst.base.stream_type = TsStreamType::DtsAudio;
        let mut audio = TsStream::Audio(dst);
        merge_stream(&mut audio, &TsStream::Audio(TsAudioStream::default()));
        assert!(as_audio(&audio).unwrap().core_stream.is_none());
    }

    #[test]
    fn merge_stream_ignores_text_and_type_mismatches() {
        // Text → the `_` arm carries no codec detail, but the base bit-rate/VBR merge.
        let mut dst = TsTextStream::default();
        dst.base.stream_type = TsStreamType::Subtitle;
        let mut src = TsTextStream::default();
        src.base.stream_type = TsStreamType::Subtitle;
        src.base.is_vbr = true;
        let mut text = TsStream::Text(dst);
        merge_stream(&mut text, &TsStream::Text(src));
        assert!(text.base().is_vbr);

        // A type mismatch is a no-op — the merge bails before touching `dst`.
        let mut dst = TsAudioStream::default();
        dst.base.stream_type = TsStreamType::Ac3Audio;
        let mut src = TsVideoStream::default();
        src.base.stream_type = TsStreamType::AvcVideo;
        src.base.bit_rate = 999;
        let mut audio = TsStream::Audio(dst);
        merge_stream(&mut audio, &TsStream::Video(src));
        assert_eq!(audio.base().bit_rate, 0); // unchanged: types differ
    }

    #[test]
    fn stream_summary_reads_each_variant() {
        let mut video = TsVideoStream::default();
        video.base.pid = Pid::new(0x1011);
        video.base.stream_type = TsStreamType::AvcVideo;
        video.height = 1080;
        let summary = stream_summary(&TsStream::Video(video));
        assert_eq!(summary.pid, Pid::new(0x1011));
        assert_eq!(summary.height, 1080);
        assert_eq!(summary.stream_type.name(), "AVC_VIDEO");
        assert_eq!(summary.codec_short_name, "AVC");
        assert_eq!(summary.codec_name, "MPEG-4 AVC Video");
        assert_eq!(summary.codec_alt_name, "AVC");
        // A video row carries no audio detail and starts on the main angle.
        assert_eq!(summary.channel_description, "");
        assert_eq!((summary.sample_rate, summary.bit_depth, summary.channel_count), (0, 0, 0));
        assert_eq!(summary.angle_index, 0);
        assert_eq!(summary.language_code, "");

        let mut audio = TsAudioStream::default();
        audio.base.stream_type = TsStreamType::LpcmAudio;
        audio.base.set_language_code("jpn");
        audio.channel_count = 2;
        audio.lfe = 0;
        audio.sample_rate = 48_000;
        audio.bit_depth = 16;
        let summary = stream_summary(&TsStream::Audio(audio));
        assert_eq!(summary.height, 0);
        assert_eq!(summary.codec_short_name, "LPCM");
        assert_eq!(summary.codec_alt_name, "LPCM");
        assert_eq!(summary.language_code, "jpn");
        assert_eq!(summary.language_name, "Japanese");
        assert_eq!(summary.channel_description, "2.0");
        assert_eq!(
            (summary.sample_rate, summary.bit_depth, summary.channel_count),
            (48_000, 16, 2)
        );

        let mut graphics = TsGraphicsStream::default();
        graphics.base.stream_type = TsStreamType::PresentationGraphics;
        let summary = stream_summary(&TsStream::Graphics(graphics));
        assert_eq!(summary.codec_short_name, "PGS");
        assert_eq!(summary.codec_alt_name, "PGS");
        assert_eq!(summary.description, "");

        let mut text = TsTextStream::default();
        text.base.stream_type = TsStreamType::Subtitle;
        text.base.set_language_code("eng");
        let summary = stream_summary(&TsStream::Text(text));
        assert_eq!(
            (summary.codec_short_name.as_str(), summary.codec_name.as_str()),
            ("SUB", "Subtitle")
        );
        assert_eq!(summary.language_name, "English");
        assert_eq!(summary.language_code, "eng");
        assert_eq!(summary.codec_alt_name, "SUB");
    }

    #[test]
    fn full_description_patches_audio_respells_video_and_falls_back() {
        // Audio with a measured rate: the description is respelled with that
        // rate patched in; without one, the row's own spelling is kept AS-IS
        // (not re-derived at rate zero — the stream's 512 kbps must survive).
        let mut audio = TsAudioStream::default();
        audio.base.stream_type = TsStreamType::LpcmAudio;
        audio.channel_count = 2;
        audio.sample_rate = 48_000;
        audio.bit_depth = 16;
        audio.base.bit_rate = 512_000;
        let mut patched = audio.clone();
        patched.base.bit_rate = 256_000;
        let respelled = patched.description();
        let plain = audio.description();
        assert_ne!(respelled, plain);
        let stream = TsStream::Audio(audio);
        let mut row = stream_summary(&stream);
        row.bitrate = 256_000;
        assert_eq!(super::full_description(&stream, &row), respelled);
        row.bitrate = 0;
        assert_eq!(super::full_description(&stream, &row), plain);

        // Video takes its own full (exact-luminance) description, never the
        // row's — a sentinel row description must not leak through.
        let mut video = TsVideoStream::default();
        video.base.stream_type = TsStreamType::AvcVideo;
        video.height = 1080;
        let expected = video.full_description();
        let stream = TsStream::Video(video);
        let mut row = stream_summary(&stream);
        row.description = "sentinel".to_owned();
        assert_eq!(super::full_description(&stream, &row), expected);

        // Everything else keeps the row's description verbatim.
        let mut graphics = TsGraphicsStream::default();
        graphics.base.stream_type = TsStreamType::PresentationGraphics;
        let stream = TsStream::Graphics(graphics);
        let mut row = stream_summary(&stream);
        row.description = "kept".to_owned();
        assert_eq!(super::full_description(&stream, &row), "kept");
    }

    #[test]
    fn build_sorted_streams_takes_graphics_detail_from_the_resolved_streams() {
        // The clip info (and the quick scan) carry no PGS detail; the
        // resolved presented stream holds the full pass's re-merged caption
        // tallies — the row's description comes from there.
        let mut clip = BTreeMap::new();
        let mut graphics = TsGraphicsStream::default();
        graphics.base.pid = Pid::new(0x1200);
        graphics.base.stream_type = TsStreamType::PresentationGraphics;
        graphics.base.set_language_code("deu");
        clip.insert(0x1200, TsStream::Graphics(graphics));

        let mut resolved = bare_playlist();
        let mut presented = TsGraphicsStream {
            captions: 837,
            width: 1920,
            height: 1080,
            ..TsGraphicsStream::default()
        };
        presented.base.pid = Pid::new(0x1200);
        presented.base.stream_type = TsStreamType::PresentationGraphics;
        resolved.streams = BTreeMap::from([(0x1200_u16, TsStream::Graphics(presented))]);

        let rows = build_sorted_streams(&clip, None, &resolved, 0);
        assert_eq!(rows.first().unwrap().description, "1920x1080 / 837 Captions");

        // An unresolved playlist keeps the quick detail: an empty description.
        let rows = build_sorted_streams(&clip, None, &bare_playlist(), 0);
        assert_eq!(rows.first().unwrap().description, "");
    }

    #[test]
    fn build_sorted_streams_orders_clones_and_merges() {
        // A clip with a 1080p AVC video (PID 0x1011) and an English AC3 audio (0x1100).
        let mut clip = BTreeMap::new();
        let mut video = TsVideoStream::default();
        video.base.pid = Pid::new(0x1011);
        video.base.stream_type = TsStreamType::AvcVideo;
        video.set_video_format(TsVideoFormat::Videoformat1080p);
        clip.insert(0x1011, TsStream::Video(video));
        let mut audio = TsAudioStream::default();
        audio.base.pid = Pid::new(0x1100);
        audio.base.stream_type = TsStreamType::Ac3Audio;
        audio.base.set_language_code("eng");
        clip.insert(0x1100, TsStream::Audio(audio));

        // No scan, no angles → one row per stream, ordered by PID. An
        // unresolved playlist leaves the measured rates at zero.
        let unresolved = bare_playlist();
        let rows = build_sorted_streams(&clip, None, &unresolved, 0);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows.first().unwrap().pid, Pid::new(0x1011));
        assert_eq!(rows.first().unwrap().stream_type.name(), "AVC_VIDEO");
        assert_eq!(rows.first().unwrap().bitrate, 0);
        assert_eq!(rows.get(1).unwrap().pid, Pid::new(0x1100));
        assert_eq!(rows.get(1).unwrap().language_name, "English");

        // Two extra angles → the video PID appears three times (base + 2 clones),
        // audio once → four rows, still PID-ordered with the clones grouped first.
        // The clones carry their 1-based angle index; main rows stay 0.
        let rows = build_sorted_streams(&clip, None, &unresolved, 2);
        assert_eq!(rows.len(), 4);
        assert!(rows.iter().take(3).all(|r| r.pid == Pid::new(0x1011)));
        assert_eq!(rows.get(3).unwrap().pid, Pid::new(0x1100));
        let angles: Vec<usize> = rows.iter().map(|r| r.angle_index).collect();
        assert_eq!(angles, [0, 1, 2, 0]);

        // A resolved playlist supplies each row's measured rates: the main map
        // for the main rows, each angle's own map for its clone.
        let mut resolved = bare_playlist();
        resolved.streams = clip.clone();
        let main_video = resolved.streams.get_mut(&0x1011).expect("the video is presented");
        main_video.base_mut().bit_rate = 26_030_000;
        main_video.base_mut().active_bit_rate = 26_031_000;
        resolved.streams.get_mut(&0x1100).expect("the audio is presented").base_mut().bit_rate =
            640_000;
        let mut angle = clip.clone();
        let angle_video = angle.get_mut(&0x1011).expect("the angle video is presented");
        angle_video.base_mut().bit_rate = 26_120_000;
        angle_video.base_mut().active_bit_rate = 26_121_000;
        resolved.angle_streams = vec![angle];
        let rows = build_sorted_streams(&clip, None, &resolved, 1);
        assert_eq!(rows.len(), 3);
        assert_eq!(rows.first().unwrap().bitrate, 26_030_000);
        assert_eq!(rows.first().unwrap().active_bitrate, 26_031_000);
        assert_eq!(rows.get(1).unwrap().bitrate, 26_120_000);
        assert_eq!(rows.get(1).unwrap().active_bitrate, 26_121_000);
        assert_eq!(rows.get(2).unwrap().bitrate, 640_000);
        assert_eq!(rows.get(2).unwrap().active_bitrate, 0);

        // More angle clones than resolved angle maps → the surplus clone keeps
        // zero rates rather than borrowing another angle's.
        let rows = build_sorted_streams(&clip, None, &resolved, 2);
        assert_eq!(rows.len(), 4);
        assert_eq!(rows.get(1).unwrap().bitrate, 26_120_000);
        assert_eq!(rows.get(2).unwrap().bitrate, 0);

        // A scanned AVC stream supplies the encoding profile (the merge ran).
        let mut scanned = BTreeMap::new();
        let mut scanned_video = TsVideoStream::default();
        scanned_video.base.pid = Pid::new(0x1011);
        scanned_video.base.stream_type = TsStreamType::AvcVideo;
        scanned_video.encoding_profile = Some("High Profile 4.1".to_owned());
        scanned.insert(0x1011, TsStream::Video(scanned_video));
        let rows = build_sorted_streams(&clip, Some(&scanned), &unresolved, 0);
        assert!(rows.first().unwrap().description.contains("High Profile 4.1"));

        // A scanned stream whose PID is absent from the clip is ignored — neither
        // merged nor presented; the clip's own streams stay the presented set.
        let mut orphan = BTreeMap::new();
        let mut orphan_audio = TsAudioStream::default();
        orphan_audio.base.pid = Pid::new(0x9999);
        orphan_audio.base.stream_type = TsStreamType::Ac3Audio;
        orphan.insert(0x9999, TsStream::Audio(orphan_audio));
        assert_eq!(build_sorted_streams(&clip, Some(&orphan), &unresolved, 0).len(), 2);
    }

    #[test]
    fn build_sorted_streams_presents_the_resolved_dependent_view() {
        // A clip with only the base video; the resolved playlist also presents
        // the interleaved MVC dependent view with a measured rate.
        let mut clip = BTreeMap::new();
        let mut video = TsVideoStream::default();
        video.base.pid = Pid::new(0x1011);
        video.base.stream_type = TsStreamType::AvcVideo;
        clip.insert(0x1011, TsStream::Video(video));

        let mut resolved = bare_playlist();
        resolved.streams = clip.clone();
        let mut mvc = TsVideoStream::default();
        mvc.base.pid = Pid::new(MVC_PID);
        mvc.base.stream_type = TsStreamType::MvcVideo;
        mvc.base.bit_rate = 7_579_000;
        resolved.streams.insert(MVC_PID, TsStream::Video(mvc));

        let rows = build_sorted_streams(&clip, None, &resolved, 0);
        assert_eq!(rows.len(), 2);
        let row = rows.get(1).unwrap();
        assert_eq!(row.pid, Pid::new(MVC_PID));
        assert_eq!(row.stream_type.name(), "MVC_VIDEO");
        assert_eq!(
            (row.codec_short_name.as_str(), row.codec_name.as_str()),
            ("MVC", "MPEG-4 MVC Video")
        );
        assert_eq!(row.description, "");
        assert_eq!(row.bitrate, 7_579_000);
        assert!(row.ssif_only);
        assert!(!row.is_hidden, "the dependent view is never marked hidden");
        // The base video row is an (undeclared) clip stream: hidden, not
        // SSIF-only.
        assert!(rows.first().unwrap().is_hidden);
        assert!(!rows.first().unwrap().ssif_only);

        // A clip that declares the MVC PID itself yields a plain clip-stream
        // row — no SSIF presentation, and the hidden check applies as usual.
        let mut declared = clip.clone();
        let mut own = TsVideoStream::default();
        own.base.pid = Pid::new(MVC_PID);
        own.base.stream_type = TsStreamType::MvcVideo;
        declared.insert(MVC_PID, TsStream::Video(own));
        let rows = build_sorted_streams(&declared, None, &resolved, 0);
        assert_eq!(rows.len(), 2);
        assert!(!rows.get(1).unwrap().ssif_only);
        assert!(rows.get(1).unwrap().is_hidden);
    }

    // ── orchestration: a full disc with every flag set ──────────────────────

    #[test]
    fn open_scans_a_full_disc() {
        let clip = clpi(&[
            (0x1011, 0x1B, [0x63, 0x30, 0, 0]),       // AVC 1080p / 25 fps
            (0x1100, 0x81, [0x61, b'e', b'n', b'g']), // AC3 audio
            (0x1200, 0x90, [b'e', b'n', b'g', 0]),    // PG graphics
            (0x1A00, 0x92, [0, b'f', b'r', b'a']),    // subtitle text
        ]);
        let play = mpls("00000", 2_700_000, 4_500_000, &[(1, 0, 2_700_000)]);
        let index = b"INDX0300\x00\x00".to_vec();
        let xml = title_xml("Movie");
        let m2ts = vec![0_u8; 1000];
        let ssif = vec![0_u8; 500];

        // The trailing three ones: the bdjo, the mnv, and FilmIndex.xml.
        let expected_size: u64 =
            [index.len(), play.len(), clip.len(), m2ts.len(), xml.len(), 1, 1, 1]
                .iter()
                .map(|&n| u64::try_from(n).unwrap())
                .sum();

        let disc = TempDisc::build(
            &["BDSVM"],
            &[
                ("BDMV/index.bdmv", index),
                ("BDMV/PLAYLIST/00000.mpls", play),
                ("BDMV/CLIPINF/00000.clpi", clip),
                ("BDMV/STREAM/00000.m2ts", m2ts),
                ("BDMV/STREAM/SSIF/00000.ssif", ssif), // excluded from Size, used for ifilesize
                ("BDMV/META/DL/bdmt_eng.xml", xml),
                ("BDMV/BDJO/00000.bdjo", vec![b'x']),
                ("SNP/clip.mnv", vec![b'x']),
                ("FilmIndex.xml", vec![b'x']),
            ],
        );
        let bd = disc.open().expect("scan full disc");

        assert!(bd.volume_label.starts_with("bdinfo-rs-disc-"));
        assert_eq!(bd.disc_title.as_deref(), Some("Movie"));
        assert_eq!(bd.size, expected_size); // the 500-byte .ssif is excluded
        assert!(bd.is_uhd);
        assert!(bd.is_3d);
        assert!(bd.is_bd_plus);
        assert!(bd.is_bd_java);
        assert!(bd.is_dbox);
        assert!(bd.is_psp);
        assert!(bd.is_50hz);
        // Every extras label, in the fixed presentation order.
        assert_eq!(
            bd.extra_features(),
            [
                "Ultra HD",
                "BD-Java",
                "50Hz Content",
                "Blu-ray 3D",
                "D-BOX Motion Code",
                "PSP Digital Copy"
            ]
        );
        // The 40 s playlist passes the default filter.
        assert_eq!(bd.presentation_order(&PlaylistFilter::default()), [0]);

        assert_eq!(bd.playlists.len(), 1);
        let pl = bd.playlists.first().unwrap();
        assert_eq!(pl.name, "00000.MPLS");
        assert_eq!(pl.total_length.to_bits(), 40.0_f64.to_bits());
        assert_eq!(pl.file_size, 1000);
        assert_eq!(pl.interleaved_file_size, 500);
        // The single clip carries the same on-disk sizes (its `*.m2ts` + `*.ssif`).
        assert_eq!(pl.clips.len(), 1);
        let clip0 = pl.clips.first().unwrap();
        assert_eq!(clip0.file_size, 1000);
        assert_eq!(clip0.interleaved_file_size, 500);
        assert_eq!(pl.chapter_count, 1);
        assert_eq!(pl.stream_count, 4);
        // The scan-free open leaves the presented streams unfilled by codec detail
        // but still built from the clip-info entries (one per kind).
        assert_eq!(pl.streams.len(), 4);

        // The packet scan reads the (synthetic, codec-less) `*.m2ts`: the streams are
        // still the four clip-info entries (no codec detail to merge), in PID order.
        let scanned = disc.open_scanned().expect("packet-scan the disc");
        let pl = scanned.playlists.first().unwrap();
        assert_eq!(pl.stream_count, 4);
        let pids: Vec<u16> = pl.streams.iter().map(|s| s.pid.get()).collect();
        assert_eq!(pids, vec![0x1011, 0x1100, 0x1200, 0x1A00]);
        assert_eq!(pl.streams.first().unwrap().stream_type.name(), "AVC_VIDEO");

        // One chapter row per mark; the synthetic (codec-less) stream yields
        // no frames, so the row keeps its times with zero rates.
        assert_eq!(pl.chapters.len(), 1);
        let row = pl.chapters.first().unwrap();
        assert_eq!(row.time_in.to_bits(), 0.0_f64.to_bits());
        assert_eq!(row.length.to_bits(), 40.0_f64.to_bits());
        assert_eq!(row.avg_rate.to_bits(), 0.0_f64.to_bits());
    }

    // ── orchestration: present-but-empty dirs / absent stream file (false sides) ──

    #[test]
    fn open_scans_a_disc_with_empty_dirs_and_missing_stream() {
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]); // 1080p / 24 fps
        let play = mpls("00000", 0, 4_500_000, &[]); // 100 s, no chapters
        let disc = TempDisc::build(
            &["BDMV/BDJO", "BDMV/STREAM/SSIF"], // present but empty
            &[
                ("BDMV/PLAYLIST/00000.mpls", play),
                ("BDMV/CLIPINF/00000.clpi", clip),
                ("BDMV/META/note.txt", vec![b'x']), // META present, no bdmt_eng.xml
                ("SNP/note.txt", vec![b'x']),       // SNP present, no *.mnv
                ("readme.txt", vec![b'x']),         // a root file that is not FilmIndex.xml
            ],
        );
        let bd = disc.open().expect("scan sparse disc");

        assert!(!bd.is_uhd); // no index.bdmv
        assert!(!bd.is_3d); // SSIF empty
        assert!(!bd.is_bd_plus); // no BDSVM/SLYVM/ANYVM
        assert!(!bd.is_bd_java); // BDJO empty
        assert!(!bd.is_dbox); // no FilmIndex.xml in the root
        assert!(!bd.is_psp); // SNP has no *.mnv
        assert!(bd.extra_features().is_empty()); // no flag set, no label
        assert!(!bd.is_50hz); // 24 fps
        assert_eq!(bd.disc_title, None); // META has no bdmt_eng.xml

        let pl = bd.playlists.first().unwrap();
        assert_eq!(pl.total_length.to_bits(), 100.0_f64.to_bits());
        assert_eq!(pl.file_size, 0); // no *.m2ts on disc
        assert_eq!(pl.interleaved_file_size, 0);
        // The clip mirrors the absence: no on-disk file, no interleaved file.
        let clip0 = pl.clips.first().unwrap();
        assert_eq!(clip0.file_size, 0);
        assert_eq!(clip0.interleaved_file_size, 0);
        assert_eq!(pl.chapter_count, 0);
        assert_eq!(pl.stream_count, 1);
    }

    // ── orchestration: the truly-minimal disc (None branches) ───────────────

    #[test]
    fn open_scans_a_minimal_disc() {
        let disc = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[("BDMV/MovieObject.bdmv", vec![b'x'])], // a non-index file in BDMV
        );
        let bd = disc.open().expect("scan minimal disc");
        assert_eq!(bd.size, 1);
        assert!(!bd.is_uhd && !bd.is_3d && !bd.is_bd_plus && !bd.is_bd_java && !bd.is_psp);
        assert_eq!(bd.disc_title, None);
        assert!(bd.playlists.is_empty());
    }

    #[test]
    fn open_handles_a_playlist_with_no_clips() {
        // A zero-item playlist resolves no reference clip → no presented streams.
        let disc =
            TempDisc::build(&["BDMV/CLIPINF"], &[("BDMV/PLAYLIST/00000.mpls", empty_mpls())]);
        let bd = disc.open().expect("scan clip-less playlist");
        let pl = bd.playlists.first().unwrap();
        assert_eq!(pl.stream_count, 0);
        assert!(pl.streams.is_empty());
        assert_eq!(pl.total_length.to_bits(), 0.0_f64.to_bits());
        assert!(!bd.is_50hz);
    }

    #[test]
    fn open_marks_undeclared_streams_hidden() {
        // The clip carries video + two audio streams; the playlist declares
        // only the first audio PID — the video and the second audio are
        // presented but hidden by this playlist.
        let clip = clpi(&[
            (0x1011, 0x1B, [0x62, 0x30, 0, 0]),
            (0x1100, 0x81, [0x61, b'e', b'n', b'g']),
            (0x1101, 0x81, [0x61, b'f', b'r', b'a']),
        ]);
        let play = mpls_declared("00000", 0, 4_500_000, &[0x1100], &[]);
        let disc = TempDisc::build(
            &[],
            &[("BDMV/PLAYLIST/00000.mpls", play), ("BDMV/CLIPINF/00000.clpi", clip)],
        );
        let bd = disc.open().expect("scan disc with a declared stream");
        let pl = bd.playlists.first().unwrap();
        let hidden: Vec<(u16, bool)> =
            pl.streams.iter().map(|s| (s.pid.get(), s.is_hidden)).collect();
        assert_eq!(hidden, vec![(0x1011, true), (0x1100, false), (0x1101, true)]);
        assert!(pl.has_hidden_streams());
    }

    #[test]
    fn open_detects_a_looping_playlist() {
        // The same clip replayed from the same in-time → a loop; two different
        // clips (or different in-times) → no loop.
        let clip = clpi(&[(0x1100, 0x81, [0x61, b'e', b'n', b'g'])]);
        let looping = mpls_items(&["00000", "00000"], 0, 4_500_000, &[], &[], &[]);
        let chained = mpls_items(&["00000", "00001"], 0, 4_500_000, &[], &[], &[]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", looping),
                ("BDMV/PLAYLIST/00001.mpls", chained),
                ("BDMV/CLIPINF/00000.clpi", clip.clone()),
                ("BDMV/CLIPINF/00001.clpi", clip),
            ],
        );
        let bd = disc.open().expect("scan looping disc");
        assert_eq!(bd.playlists.len(), 2);
        assert!(bd.playlists.first().unwrap().has_loops);
        assert!(!bd.playlists.get(1).unwrap().has_loops);
        // The loop also doubles the playlist length (both items count).
        assert_eq!(bd.playlists.first().unwrap().total_length.to_bits(), 200.0_f64.to_bits());
        // The default presentation order drops the looping playlist, keeping
        // only the chained one; the everything filter keeps both in one group
        // (they share 00000.M2TS), name-ordered on the length tie.
        assert_eq!(bd.presentation_order(&PlaylistFilter::default()), [1]);
        assert_eq!(bd.presentation_order(&PlaylistFilter::everything()), [0, 1]);
    }

    #[test]
    fn open_leaves_fully_declared_streams_visible() {
        // The playlist declares every clip stream — nothing is hidden.
        let clip = clpi(&[(0x1100, 0x81, [0x61, b'e', b'n', b'g'])]);
        let play = mpls_declared("00000", 0, 4_500_000, &[0x1100], &[]);
        let disc = TempDisc::build(
            &[],
            &[("BDMV/PLAYLIST/00000.mpls", play), ("BDMV/CLIPINF/00000.clpi", clip)],
        );
        let bd = disc.open().expect("scan disc with all streams declared");
        let pl = bd.playlists.first().unwrap();
        assert!(pl.streams.iter().all(|s| !s.is_hidden));
        assert!(!pl.has_hidden_streams());
    }

    #[test]
    fn open_with_packet_scan_and_no_stream_directory() {
        // A packet scan requested on a disc with no STREAM/ dir → the per-stream-file
        // scan short-circuits; the streams are still built from the clip info.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let play = mpls("00000", 0, 4_500_000, &[]);
        let disc = TempDisc::build(
            &[],
            &[("BDMV/PLAYLIST/00000.mpls", play), ("BDMV/CLIPINF/00000.clpi", clip)],
        );
        let bd = disc.open_scanned().expect("packet-scan without a STREAM dir");
        let pl = bd.playlists.first().unwrap();
        assert_eq!(pl.stream_count, 1);
        assert_eq!(pl.file_size, 0);
    }

    #[test]
    fn open_counts_only_angle_zero_clips() {
        // A multi-angle playlist: the main clip resolves; the angle clips
        // contribute only to `file_size` and are skipped for the reference clip
        // + `total_length`.
        let clip =
            clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0]), (0x1100, 0x81, [0x61, b'e', b'n', b'g'])]);
        let play = mpls_angles("00000", 2_700_000, 4_500_000, &["00010", "00021"], &[]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", play),
                ("BDMV/CLIPINF/00000.clpi", clip),
                ("BDMV/STREAM/00000.m2ts", vec![0; 100]),
            ],
        );
        let bd = disc.open().expect("scan multi-angle disc");
        let pl = bd.playlists.first().unwrap();
        assert_eq!(pl.total_length.to_bits(), 40.0_f64.to_bits()); // main clip only
        assert_eq!(pl.file_size, 100); // only the present main *.m2ts
        // Presented streams = video × (1 + angle_count) + audio = 1×3 + 1.
        assert_eq!(pl.stream_count, 4);
    }

    // ── measurement model: totals, tallies, and the angle timeline ──────────

    /// A [`ClipSummary`] with the given angle/start/length/packet count and no
    /// per-stream tallies.
    fn clip_summary(angle_index: i32, time_in: f64, length: f64, packets: u64) -> ClipSummary {
        ClipSummary {
            name: "00000.M2TS".to_owned(),
            display_name: "00000.M2TS".to_owned(),
            file_size: 0,
            interleaved_file_size: 0,
            angle_index,
            relative_time_in: time_in,
            length,
            payload_bytes: 0,
            packet_count: packets,
            packet_seconds: 0.0,
            file_seconds: 0.0,
            streams: Vec::new(),
        }
    }

    /// A [`PlaylistSummary`] carrying only the fields the totals math reads.
    fn playlist_summary(
        total_length: f64,
        angle_count: usize,
        clips: Vec<ClipSummary>,
    ) -> PlaylistSummary {
        PlaylistSummary {
            name: "00000.MPLS".to_owned(),
            total_length,
            file_size: 0,
            interleaved_file_size: 0,
            chapter_count: 0,
            stream_count: 0,
            angle_count,
            has_loops: false,
            streams: Vec::new(),
            clips,
            chapters: Vec::new(),
        }
    }

    #[test]
    fn chapter_summaries_walk_the_first_video_pid_diagnostics() {
        use crate::bdrom::m2ts::TsStreamDiagnostics;

        // An audio stream below the video PID proves the diagnostics PID is the
        // first *video* stream, not merely the first stream.
        let mut audio = TsAudioStream::default();
        audio.base.stream_type = TsStreamType::Ac3Audio;
        let mut video = TsVideoStream::default();
        video.base.stream_type = TsStreamType::AvcVideo;
        let mut playlist = TsPlaylistFile {
            file_type: "MPLS0200".to_owned(),
            name: "00000.MPLS".to_owned(),
            mvc_base_view_r: false,
            chapters: vec![0.0],
            playlist_streams: BTreeMap::new(),
            streams: BTreeMap::from([
                (0x1010, TsStream::Audio(audio)),
                (0x1011, TsStream::Video(video)),
            ]),
            angle_streams: Vec::new(),
            stream_clips: vec![
                TsStreamClip { name: "00000.M2TS".to_owned(), ..TsStreamClip::default() },
                // No measured file for this clip → it is skipped whole.
                TsStreamClip { name: "00001.M2TS".to_owned(), ..TsStreamClip::default() },
            ],
            angle_count: 0,
        };
        let mut file = TsStreamFile::new("00000.m2ts");
        file.stream_diagnostics.insert(
            0x1011,
            vec![
                TsStreamDiagnostics {
                    bytes: 1000,
                    packets: 1,
                    marker: 1.0,
                    interval: 1.0,
                    tag: Some("I".to_owned()),
                },
                TsStreamDiagnostics {
                    bytes: 1000,
                    packets: 1,
                    marker: 2.0,
                    interval: 1.0,
                    tag: None,
                },
            ],
        );
        let measured = BTreeMap::from([("00000.M2TS".to_owned(), file)]);

        let rows = build_chapter_summaries(&playlist, &measured, 4.0);
        assert_eq!(rows.len(), 1);
        let row = rows.first().unwrap();
        assert_eq!(row.length.to_bits(), 4.0_f64.to_bits());
        assert_eq!(row.avg_rate.to_bits(), 4000.0_f64.to_bits()); // 2000 B × 8 / 4 s
        assert_eq!(row.avg_frame_size.to_bits(), 2000.0_f64.to_bits()); // one tagged frame

        // Without a presented video stream there is no diagnostics PID: the
        // rows keep their times but measure nothing.
        playlist.streams.remove(&0x1011);
        let rows = build_chapter_summaries(&playlist, &measured, 4.0);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows.first().unwrap().avg_rate.to_bits(), 0.0_f64.to_bits());
        assert_eq!(rows.first().unwrap().length.to_bits(), 4.0_f64.to_bits());
    }

    #[test]
    fn clip_packet_size_and_bit_rate_derive_from_the_tallies() {
        let mut clip = clip_summary(0, 0.0, 10.0, 6);
        clip.packet_seconds = 4.0;
        assert_eq!(clip.packet_size(), 1152); // 6 packets × 192
        assert_eq!(clip.packet_bit_rate(), 2304); // 1152 × 8 / 4.0

        // Nothing demuxed → zero rate, not a division by zero.
        clip.packet_seconds = 0.0;
        assert_eq!(clip.packet_bit_rate(), 0);

        // The rate rounds half-to-even: 100 packets × 192 × 8 / 7 s = 21 942.857…
        clip.packet_count = 100;
        clip.packet_seconds = 7.0;
        assert_eq!(clip.packet_bit_rate(), 21_943);
    }

    #[test]
    fn rate_over_guards_the_zero_duration() {
        assert_eq!(rate_over(1152, 4.0), 2304);
        assert_eq!(rate_over(1152, 0.0), 0);
        assert_eq!(rate_over(1152, -1.0), 0);
    }

    #[test]
    fn playlist_totals_split_main_and_angle_clips() {
        // Main clips: 10 packets at t=0 (40 s) and 20 packets at t=40 (60 s);
        // angle 1 replaces the t=0 slot with 30 packets; angle 2 has no clips.
        let playlist = playlist_summary(
            100.0,
            2,
            vec![
                clip_summary(0, 0.0, 40.0, 10),
                clip_summary(1, 0.0, 40.0, 30),
                clip_summary(0, 40.0, 60.0, 20),
            ],
        );
        assert_eq!(playlist.total_packet_size(), 30 * 192); // main clips only
        assert_eq!(playlist.total_angle_packet_size(), 60 * 192); // every clip
        assert_eq!(playlist.total_angle_length().to_bits(), 140.0_f64.to_bits());
        // 30 × 192 × 8 / 100 s = 460.8 → 461 (half-to-even rounding).
        assert_eq!(playlist.total_bit_rate(), 461);
        // 60 × 192 × 8 / 140 s = 658.28… → 658.
        assert_eq!(playlist.total_angle_bit_rate(), 658);

        let angles = playlist.angle_totals();
        assert_eq!(angles.len(), 2);
        // Angle 1: its own clip (30 packets, 40 s); its timeline replaces the
        // t=0 main clip, keeping the t=40 one (30 + 20 packets).
        let one = angles.first().unwrap();
        assert_eq!(one.length.to_bits(), 40.0_f64.to_bits());
        assert_eq!(one.packet_size, 30 * 192);
        assert_eq!(one.timeline_packet_size, 50 * 192);
        // Angle 2: no clips of its own — the timeline is the main clips.
        let two = angles.get(1).unwrap();
        assert_eq!(two.length.to_bits(), 0.0_f64.to_bits());
        assert_eq!(two.packet_size, 0);
        assert_eq!(two.timeline_packet_size, 30 * 192);

        // No angles → no totals.
        assert!(playlist_summary(100.0, 0, Vec::new()).angle_totals().is_empty());

        // The per-angle rates: angle 1's own clips over its own length
        // (30 × 192 × 8 / 40 s = 1152), its timeline over the playlist length
        // (50 × 192 × 8 / 100 s = 768); the clip-less angle 2 rates zero.
        assert_eq!(one.bit_rate(), 1152);
        assert_eq!(one.timeline_bit_rate(100.0), 768);
        assert_eq!(two.bit_rate(), 0);
        assert_eq!(two.timeline_bit_rate(0.0), 0);
    }

    proptest! {
        /// The totals hold their set relations for arbitrary clip lists: the
        /// all-angles size counts every clip, the main size only angle 0, and
        /// each angle's own size never exceeds its timeline's.
        #[test]
        fn playlist_totals_invariants(
            clips in proptest::collection::vec(
                (0_i32..3, 0_u8..4, 1.0_f64..100.0, 0_u64..1000), 0..8,
            ),
        ) {
            let clips: Vec<ClipSummary> = clips
                .into_iter()
                .map(|(angle, slot, length, packets)| {
                    clip_summary(angle, f64::from(slot) * 50.0, length, packets)
                })
                .collect();
            let playlist = playlist_summary(100.0, 2, clips);
            let total = playlist.total_packet_size();
            let total_angle = playlist.total_angle_packet_size();
            prop_assert!(total <= total_angle);
            let angles = playlist.angle_totals();
            prop_assert_eq!(angles.len(), 2);
            for angle in &angles {
                prop_assert!(angle.packet_size <= angle.timeline_packet_size);
                prop_assert!(angle.timeline_packet_size <= total_angle);
            }
        }
    }

    /// Builds a parsed playlist whose clip list is `clips` and whose angle
    /// count is `angle_count`, with empty stream maps.
    fn playlist_with_clips(angle_count: i32, clips: Vec<TsStreamClip>) -> TsPlaylistFile {
        let mut playlist = bare_playlist();
        playlist.angle_count = angle_count;
        playlist.stream_clips = clips;
        playlist
    }

    #[test]
    fn clear_measurements_zeroes_the_clip_tallies() {
        let playlist = playlist_with_clips(
            0,
            vec![TsStreamClip {
                name: "00000.M2TS".to_owned(),
                payload_bytes: 9,
                packet_count: 8,
                packet_seconds: 7.0,
                ..TsStreamClip::default()
            }],
        );
        let mut playlists = vec![playlist];
        clear_measurements(&mut playlists);
        let clip = playlists.first().unwrap().stream_clips.first().unwrap();
        assert_eq!(clip.payload_bytes, 0);
        assert_eq!(clip.packet_count, 0);
        assert_eq!(clip.packet_seconds.to_bits(), 0.0_f64.to_bits());
    }

    #[test]
    fn resolve_playlist_streams_presents_reset_copies_and_angle_maps() {
        // The reference clip declares a video and an audio stream; the playlist
        // has two extra angles.
        let mut clip_streams = BTreeMap::new();
        let mut video = TsVideoStream::default();
        video.base.pid = Pid::new(0x1011);
        video.base.stream_type = TsStreamType::AvcVideo;
        clip_streams.insert(0x1011, TsStream::Video(video));
        let mut audio = TsAudioStream::default();
        audio.base.pid = Pid::new(0x1100);
        audio.base.stream_type = TsStreamType::Ac3Audio;
        audio.base.set_language_code("eng");
        clip_streams.insert(0x1100, TsStream::Audio(audio));

        // The quick-scanned file supplies codec detail to merge.
        let mut file = TsStreamFile::new("00000.m2ts");
        let mut scanned_video = TsVideoStream::default();
        scanned_video.base.pid = Pid::new(0x1011);
        scanned_video.base.stream_type = TsStreamType::AvcVideo;
        scanned_video.base.is_vbr = true;
        scanned_video.base.payload_bytes = 999; // demux counter, must not leak
        scanned_video.encoding_profile = Some("High Profile 4.1".to_owned());
        file.streams.insert(0x1011, TsStream::Video(scanned_video));

        let metas = [ClipMeta {
            clip_streams: &clip_streams,
            scanned: Some(&file),
            has_50hz_video: false,
            relative_length: 1.0,
            length: 10.0,
            stream_file_present: true,
        }];
        let mut playlist = playlist_with_clips(2, Vec::new());
        resolve_playlist_streams(&mut playlist, &metas);

        // The presented streams: reset copies with the merged detail.
        assert_eq!(playlist.streams.len(), 2);
        let video = playlist.streams.get(&0x1011).unwrap();
        assert!(video.base().is_vbr);
        assert_eq!(video.base().payload_bytes, 0);
        let v = as_video(video).expect("video stays video");
        assert_eq!(v.encoding_profile.as_deref(), Some("High Profile 4.1"));
        assert_eq!(
            playlist.streams.get(&0x1100).unwrap().base().language_name.as_deref(),
            Some("English")
        );

        // Two angle maps, video-only, with the angle index stamped.
        assert_eq!(playlist.angle_streams.len(), 2);
        for (index, angle) in playlist.angle_streams.iter().enumerate() {
            assert_eq!(angle.len(), 1);
            let clone = angle.get(&0x1011).unwrap();
            assert_eq!(clone.base().angle_index, i32::try_from(index).unwrap().wrapping_add(1));
            assert!(clone.base().is_vbr);
        }

        // No reference clip → the maps stay empty.
        let mut unresolved = playlist_with_clips(1, Vec::new());
        resolve_playlist_streams(&mut unresolved, &[]);
        assert!(unresolved.streams.is_empty());
        assert!(unresolved.angle_streams.is_empty());
    }

    #[test]
    fn resolve_playlist_streams_presents_the_interleaved_dependent_view() {
        let mut clip_streams = BTreeMap::new();
        let mut video = TsVideoStream::default();
        video.base.pid = Pid::new(0x1011);
        video.base.stream_type = TsStreamType::AvcVideo;
        clip_streams.insert(0x1011, TsStream::Video(video));

        // The scanned file carries the MVC dependent view the clip info omits.
        let mvc = |pid: u16| {
            let mut stream = TsVideoStream::default();
            stream.base.pid = Pid::new(pid);
            stream.base.stream_type = TsStreamType::MvcVideo;
            TsStream::Video(stream)
        };
        let interleaved =
            || TsInterleavedFile::new(Box::new(MemBdFile::new("00000.ssif", Vec::new(), false)));
        let mut file = TsStreamFile::new("00000.m2ts");
        file.interleaved_file = Some(interleaved());
        file.streams.insert(MVC_PID, mvc(MVC_PID));

        let mut playlist = playlist_with_clips(0, Vec::new());
        let metas = [ClipMeta {
            clip_streams: &clip_streams,
            scanned: Some(&file),
            has_50hz_video: false,
            relative_length: 1.0,
            length: 10.0,
            stream_file_present: true,
        }];
        resolve_playlist_streams(&mut playlist, &metas);
        assert!(playlist.streams.contains_key(&MVC_PID), "dependent view presented");
        assert_eq!(playlist.streams.len(), 2);

        // Without the interleaved source the dependent view stays absent.
        let mut plain = TsStreamFile::new("00000.m2ts");
        plain.streams.insert(MVC_PID, mvc(MVC_PID));
        let mut playlist = playlist_with_clips(0, Vec::new());
        let metas = [ClipMeta {
            clip_streams: &clip_streams,
            scanned: Some(&plain),
            has_50hz_video: false,
            relative_length: 1.0,
            length: 10.0,
            stream_file_present: true,
        }];
        resolve_playlist_streams(&mut playlist, &metas);
        assert!(!playlist.streams.contains_key(&MVC_PID));

        // A clip-info-declared stream on the MVC PID is not overwritten.
        let mut declared = clip_streams.clone();
        let mut own = TsAudioStream::default();
        own.base.pid = Pid::new(MVC_PID);
        own.base.stream_type = TsStreamType::Ac3Audio;
        declared.insert(MVC_PID, TsStream::Audio(own));
        let mut file = TsStreamFile::new("00000.m2ts");
        file.interleaved_file = Some(interleaved());
        file.streams.insert(MVC_PID, mvc(MVC_PID));
        let metas = [ClipMeta {
            clip_streams: &declared,
            scanned: Some(&file),
            has_50hz_video: false,
            relative_length: 1.0,
            length: 10.0,
            stream_file_present: true,
        }];
        let mut playlist = playlist_with_clips(0, Vec::new());
        resolve_playlist_streams(&mut playlist, &metas);
        assert_eq!(playlist.streams.get(&MVC_PID).unwrap().stream_type(), TsStreamType::Ac3Audio);
    }

    // ── orchestration: the end-to-end measurement scan ──────────────────────

    /// A PES elementary payload opening with an AVC sequence parameter set
    /// (High Profile 4.1), padded to 100 bytes — enough for the AVC scanner to
    /// initialise the stream (and mark it VBR) during the quick pass.
    fn sps_payload() -> Vec<u8> {
        let mut data = vec![0x00, 0x00, 0x01, 0x67, 100, 0x00, 41];
        data.resize(100, 0xAA);
        data
    }

    #[test]
    fn open_scanned_measures_clips_streams_and_totals() {
        let clip =
            clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0]), (0x1100, 0x81, [0x61, b'e', b'n', b'g'])]);
        let play = mpls("00000", 0, 4_500_000, &[]); // 100 s
        let mut m2ts = packet(0, true, &pat_payload(0x0100));
        // The PMT also announces a graphics stream the clip info does not
        // declare: the demux registers it, but the playlist never presents it,
        // so it stays out of the per-clip tallies.
        m2ts.extend(packet(
            0x0100,
            true,
            &pmt_payload(&[(0x1B, 0x1011), (0x81, 0x1100), (0x90, 0x1200)]),
        ));
        let audio_data = [0xBB_u8; 100];
        m2ts.extend(packet(0x1100, true, &pes_pts(0xC0, 90_000, &audio_data)));
        m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, 90_000, 90_000, &sps_payload())));
        m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, 180_000, 180_000, &sps_payload())));
        m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, 270_000, 270_000, &sps_payload())));
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", play),
                ("BDMV/CLIPINF/00000.clpi", clip),
                ("BDMV/STREAM/00000.m2ts", m2ts),
            ],
        );
        let bd = disc.open_scanned().expect("measured scan");
        let pl = bd.playlists.first().unwrap();

        // The video row carries the measured VBR and active rates: 200 payload
        // bytes were window-flushed over 4.0 clip seconds (VBR) and 2.0 stream
        // seconds (active); the junk AC3 never decoded a nominal rate.
        let video = pl.streams.first().unwrap();
        assert_eq!(video.bitrate, 400);
        assert_eq!(video.active_bitrate, 800);
        assert!(video.description.contains("High Profile 4.1"));
        assert_eq!(pl.streams.get(1).unwrap().bitrate, 0);

        // The per-clip measurements: every packet the demux attributed (PAT +
        // PMT + 1 audio + 3 video), the flushed payload, and the demuxed
        // whole-file seconds.
        assert_eq!(pl.clips.len(), 1);
        let clip = pl.clips.first().unwrap();
        assert_eq!(clip.name, "00000.M2TS");
        assert_eq!(clip.display_name, "00000.M2TS");
        assert_eq!(clip.angle_index, 0);
        assert_eq!(clip.relative_time_in.to_bits(), 0.0_f64.to_bits());
        assert_eq!(clip.length.to_bits(), 100.0_f64.to_bits());
        assert_eq!(clip.file_seconds.to_bits(), 1.0_f64.to_bits());
        assert_eq!(clip.payload_bytes, 300);
        assert_eq!(clip.packet_count, 6);
        assert_eq!(clip.packet_seconds.to_bits(), 4.0_f64.to_bits());
        assert_eq!(clip.packet_size(), 1152);
        assert_eq!(clip.packet_bit_rate(), 2304);

        // The whole-file per-stream tallies, PID-ordered.
        assert_eq!(clip.streams.len(), 2);
        let video_tally = clip.streams.first().unwrap();
        assert_eq!(video_tally.pid, Pid::new(0x1011));
        assert_eq!((video_tally.payload_bytes, video_tally.packet_count), (200, 3));
        let audio_tally = clip.streams.get(1).unwrap();
        assert_eq!(audio_tally.pid, Pid::new(0x1100));
        assert_eq!((audio_tally.payload_bytes, audio_tally.packet_count), (100, 1));

        // The playlist totals derive from the packet tallies.
        assert_eq!(pl.angle_count, 0);
        assert_eq!(pl.total_packet_size(), 1152);
        assert_eq!(pl.total_angle_packet_size(), 1152);
        assert_eq!(pl.total_bit_rate(), 92); // 1152 × 8 / 100 s
        assert!(pl.angle_totals().is_empty());
    }

    #[test]
    fn open_codecs_mode_reads_codec_detail_but_not_bitrate() {
        // The same scannable disc as the full-scan test: the video PID carries an
        // SPS (so the quick pass can parse the encoding profile), and a full scan
        // measures a non-zero rate. `Codecs` mode must run only the quick pass —
        // codec detail present, every measurement still zero.
        let clip =
            clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0]), (0x1100, 0x81, [0x61, b'e', b'n', b'g'])]);
        let play = mpls("00000", 0, 4_500_000, &[]); // 100 s
        let mut m2ts = packet(0, true, &pat_payload(0x0100));
        m2ts.extend(packet(0x0100, true, &pmt_payload(&[(0x1B, 0x1011), (0x81, 0x1100)])));
        m2ts.extend(packet(0x1100, true, &pes_pts(0xC0, 90_000, &[0xBB_u8; 100])));
        m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, 90_000, 90_000, &sps_payload())));
        m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, 180_000, 180_000, &sps_payload())));
        m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, 270_000, 270_000, &sps_payload())));
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", play),
                ("BDMV/CLIPINF/00000.clpi", clip),
                ("BDMV/STREAM/00000.m2ts", m2ts),
            ],
        );

        // Full scan (the baseline): the quick pass gives the profile, the full
        // pass gives the measured rate + clip tallies.
        let full = disc.open_scanned().expect("full scan");
        let full_pl = full.playlists.first().unwrap();
        let full_video = full_pl.streams.first().unwrap();
        assert!(full_video.description.contains("High Profile 4.1"));
        assert_eq!(full_video.bitrate, 400);
        assert_eq!(full_pl.total_packet_size(), 1152);

        // Metadata mode reads NO packets, so the profile — which only the packet
        // scan parses from the SPS — is absent (the description keeps its plain
        // clip-info form). This is what makes `scans_packets()` matter.
        let meta = disc.open().expect("metadata scan");
        let meta_video = meta.playlists.first().unwrap().streams.first().unwrap();
        assert!(
            !meta_video.description.contains("High Profile 4.1"),
            "metadata mode runs no packet scan, so no scanned codec detail"
        );
        assert_eq!(meta_video.bitrate, 0);

        // Codecs mode: identical codec detail (the quick pass ran), but no full
        // pass — the bitrate and every clip/playlist tally stay zero.
        let codecs = disc.open_codecs().expect("codec-only scan");
        let pl = codecs.playlists.first().unwrap();
        let video = pl.streams.first().unwrap();
        assert!(
            video.description.contains("High Profile 4.1"),
            "the quick pass fills the encoding profile"
        );
        assert_eq!(video.bitrate, 0, "no full pass ⇒ no measured bitrate");
        assert_eq!(video.active_bitrate, 0);
        assert_eq!(pl.total_packet_size(), 0, "no clip payload measured");
        assert_eq!(pl.total_bit_rate(), 0);
        let clip = pl.clips.first().unwrap();
        assert_eq!(clip.packet_count, 0);
        assert_eq!(clip.payload_bytes, 0);
    }

    #[test]
    fn clip_summaries_skip_a_registration_order_entry_without_a_stream() {
        // The two registration fields are public: a caller can desync them, so
        // an order entry whose stream is gone is skipped, not trusted.
        let mut audio = TsAudioStream::default();
        audio.base.pid = Pid::new(0x1100);
        audio.base.stream_type = TsStreamType::Ac3Audio;
        audio.base.payload_bytes = 64;
        audio.base.packet_count = 2;
        let mut file = TsStreamFile::new("00000.m2ts");
        file.stream_order = vec![0x1011, 0x1100];
        file.streams = BTreeMap::from([(0x1100, TsStream::Audio(audio))]);
        let playlist = TsPlaylistFile {
            file_type: "MPLS0300".to_owned(),
            name: "00000.MPLS".to_owned(),
            mvc_base_view_r: false,
            chapters: Vec::new(),
            playlist_streams: BTreeMap::new(),
            streams: BTreeMap::from([(0x1100, TsStream::Audio(TsAudioStream::default()))]),
            angle_streams: Vec::new(),
            stream_clips: vec![TsStreamClip {
                name: "00000.M2TS".to_owned(),
                ..TsStreamClip::default()
            }],
            angle_count: 0,
        };
        let measured = BTreeMap::from([("00000.M2TS".to_owned(), file)]);
        let stream_files = BTreeMap::from([("00000.M2TS".to_owned(), 4096_u64)]);
        let interleaved_files = BTreeMap::from([("00000.SSIF".to_owned(), 8192_u64)]);
        let clips = build_clip_summaries(&playlist, &stream_files, &interleaved_files, &measured);
        let clip = clips.first().unwrap();
        // The on-disk sizes come straight from the two size maps, keyed by the
        // clip's `*.m2ts` name and its `<stem>.SSIF`.
        assert_eq!(clip.file_size, 4096);
        assert_eq!(clip.interleaved_file_size, 8192);
        let tallies = &clip.streams;
        assert_eq!(tallies.len(), 1);
        assert_eq!(tallies.first().unwrap().pid, Pid::new(0x1100));
        assert_eq!(tallies.first().unwrap().codec_short_name, "AC3");
        assert_eq!(tallies.first().unwrap().stream_type, TsStreamType::Ac3Audio);
    }

    #[test]
    fn open_scanned_reads_the_interleaved_source_and_presents_the_dependent_view() {
        // The plain m2ts is a stub; the interleaved .ssif holds the real
        // packets, including the MVC dependent view the clip info omits.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let play = mpls("00000", 0, 4_500_000, &[]);
        let mut ssif = packet(0, true, &pat_payload(0x0100));
        ssif.extend(packet(0x0100, true, &pmt_payload(&[(0x1B, 0x1011), (0x20, 0x1012)])));
        ssif.extend(packet(0x1011, true, &pes_dts(0xE0, 90_000, 90_000, &sps_payload())));
        ssif.extend(packet(0x1012, true, &pes_pts(0xE1, 90_000, &[0xCC; 50])));
        ssif.extend(packet(0x1011, true, &pes_dts(0xE0, 180_000, 180_000, &sps_payload())));
        ssif.extend(packet(0x1011, true, &pes_dts(0xE0, 270_000, 270_000, &sps_payload())));
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", play),
                ("BDMV/CLIPINF/00000.clpi", clip),
                ("BDMV/STREAM/00000.m2ts", vec![0_u8; 192]),
                ("BDMV/STREAM/SSIF/00000.ssif", ssif),
            ],
        );
        let bd = disc.open_scanned().expect("interleaved scan");
        let pl = bd.playlists.first().unwrap();

        // The dependent view the clip info omits is presented as an SSIF-only
        // row with its demuxed rate — never hidden, and excluded from the
        // presented .
        assert_eq!(pl.streams.len(), 2);
        assert_eq!(pl.stream_count, 1);
        let mvc_row = pl.streams.iter().find(|s| s.pid == Pid::new(0x1012)).unwrap();
        assert_eq!(mvc_row.stream_type.name(), "MVC_VIDEO");
        assert_eq!(mvc_row.codec_name, "MPEG-4 MVC Video");
        assert_eq!(mvc_row.description, "");
        assert!(mvc_row.ssif_only && !mvc_row.is_hidden);
        assert!(mvc_row.bitrate > 0, "the dependent view carries its measured rate");
        let clip = pl.clips.first().unwrap();
        assert_eq!(clip.name, "00000.M2TS");
        assert_eq!(clip.display_name, "00000.SSIF");
        assert!(clip.streams.iter().any(|tally| tally.pid == Pid::new(0x1012)));
        // The base view was demuxed from the interleaved source.
        let base = clip.streams.iter().find(|t| t.pid == Pid::new(0x1011)).unwrap();
        assert_eq!((base.payload_bytes, base.packet_count), (200, 3));
    }

    // ── orchestration: error paths ──────────────────────────────────────────

    #[test]
    fn open_rejects_a_folder_without_bdmv() {
        let disc = TempDisc::build(&["random"], &[]);
        // `BdError` is not `PartialEq` (its `Io` wraps `io::Error`); the
        // error paths assert on the failure's `Display` instead.
        assert_eq!(disc.open().unwrap_err().to_string(), "unable to locate BD structure");
    }

    #[test]
    fn open_rejects_bdmv_missing_clipinf_or_playlist() {
        // PLAYLIST present, CLIPINF absent.
        let disc = TempDisc::build(&["BDMV/PLAYLIST"], &[]);
        assert_eq!(disc.open().unwrap_err().to_string(), "unable to locate BD structure");
    }

    // ── the disc-root self/ancestor walk ────────────────────────────────────

    /// Opens the disc with the scan rooted at `rel` under the fixture root —
    /// exercising [`walked_disc_root`] over the real filesystem backend.
    fn open_at(disc: &TempDisc, rel: &str) -> Result<BdRom, BdError> {
        BdRom::open(&FsDir::new(disc.root.join(rel)), ScanMode::Metadata)
    }

    #[test]
    fn open_accepts_the_bdmv_directory_itself() {
        let disc = TempDisc::build(&["BDMV/PLAYLIST", "BDMV/CLIPINF"], &[]);
        let bd = open_at(&disc, "BDMV").expect("scan from the BDMV directory");
        // The walk resolved the real disc root, so the volume label is its name.
        assert!(bd.volume_label.starts_with("bdinfo-rs-disc-"));
    }

    #[test]
    fn open_accepts_a_directory_inside_bdmv() {
        let disc = TempDisc::build(&["BDMV/PLAYLIST", "BDMV/CLIPINF"], &[]);
        let bd = open_at(&disc, "BDMV/PLAYLIST").expect("scan from inside BDMV");
        assert!(bd.volume_label.starts_with("bdinfo-rs-disc-"));
    }

    #[test]
    fn open_scans_a_disc_root_itself_named_bdmv() {
        // The input is named BDMV but is NOT a scannable BDMV (no CLIPINF/
        // PLAYLIST children) — it is a disc root that happens to carry the name.
        // The validated walk skips it and the child lookup scans it as the root.
        let disc = TempDisc::build(&["BDMV/BDMV/PLAYLIST", "BDMV/BDMV/CLIPINF"], &[]);
        let bd = open_at(&disc, "BDMV").expect("scan a disc root named BDMV");
        assert_eq!(bd.volume_label, "BDMV");
    }

    #[test]
    fn a_stray_bdmv_ancestor_does_not_break_the_scan() {
        // A valid disc nested under a directory named BDMV: the stray ancestor
        // holds no CLIPINF/PLAYLIST, so the walk passes it by and the input is
        // scanned as the disc root (an unvalidated walk would commit to the
        // stray and abort).
        let disc = TempDisc::build(&["BDMV/disc/BDMV/PLAYLIST", "BDMV/disc/BDMV/CLIPINF"], &[]);
        let bd = open_at(&disc, "BDMV/disc").expect("scan under a stray BDMV ancestor");
        assert_eq!(bd.volume_label, "disc");
    }

    #[test]
    fn a_stray_bdmv_ancestor_with_only_clipinf_does_not_win() {
        let disc = TempDisc::build(
            &["BDMV/CLIPINF", "BDMV/disc/BDMV/PLAYLIST", "BDMV/disc/BDMV/CLIPINF"],
            &[],
        );
        let bd = open_at(&disc, "BDMV/disc").expect("scan under a CLIPINF-only stray BDMV");
        assert_eq!(bd.volume_label, "disc");
    }

    #[test]
    fn a_stray_bdmv_ancestor_with_only_playlist_does_not_win() {
        let disc = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/disc/BDMV/PLAYLIST", "BDMV/disc/BDMV/CLIPINF"],
            &[],
        );
        let bd = open_at(&disc, "BDMV/disc").expect("scan under a PLAYLIST-only stray BDMV");
        assert_eq!(bd.volume_label, "disc");
    }

    /// A minimal [`BdDir`] fake for the walk's pathological arms: a fixed name,
    /// a parent that is `None` or a clone of itself (an endless cycle), and a
    /// child listing that is empty or fails.
    #[derive(Clone)]
    struct WalkDir {
        name: &'static str,
        cyclic: bool,
        fail_listing: bool,
    }

    impl BdDir for WalkDir {
        fn name(&self) -> &str {
            self.name
        }

        fn full_name(&self) -> &str {
            self.name
        }

        fn parent(&self) -> Option<Box<dyn BdDir>> {
            if self.cyclic {
                let cycle: Box<dyn BdDir> = Box::new(self.clone());
                Some(cycle)
            } else {
                None
            }
        }

        fn get_files(&self) -> io::Result<Vec<Box<dyn BdFile>>> {
            Ok(Vec::new())
        }

        fn get_files_pattern(&self, _pattern: &str) -> io::Result<Vec<Box<dyn BdFile>>> {
            Ok(Vec::new())
        }

        fn get_files_pattern_option(
            &self,
            _pattern: &str,
            _option: SearchOption,
        ) -> io::Result<Vec<Box<dyn BdFile>>> {
            Ok(Vec::new())
        }

        fn get_directories(&self) -> io::Result<Vec<Box<dyn BdDir>>> {
            if self.fail_listing { Err(io::Error::other("listing failed")) } else { Ok(Vec::new()) }
        }
    }

    #[test]
    fn walked_disc_root_survives_a_cyclic_parent_chain() {
        // A BDMV-named dir whose parent chain cycles forever: the bounded walk
        // gives up instead of spinning, and the scan then fails cleanly on the
        // (empty) child lookup.
        let dir = WalkDir { name: "BDMV", cyclic: true, fail_listing: false };
        assert!(walked_disc_root(&dir).is_none());
        assert_eq!(
            BdRom::open(&dir, ScanMode::Metadata).unwrap_err().to_string(),
            "unable to locate BD structure"
        );
    }

    #[test]
    fn walk_dir_fake_satisfies_the_full_seam() {
        // Exercise the fake's remaining trait surface so coverage sees it.
        let dir = WalkDir { name: "BDMV", cyclic: false, fail_listing: false };
        assert_eq!(dir.full_name(), "BDMV");
        assert!(dir.get_files().expect("files").is_empty());
        assert!(dir.get_files_pattern("*").expect("pattern files").is_empty());
        assert!(
            dir.get_files_pattern_option("*", SearchOption::TopDirectoryOnly)
                .expect("optioned files")
                .is_empty()
        );
    }

    #[test]
    fn walked_disc_root_treats_an_unreadable_candidate_as_not_scannable() {
        // The scannability probe is speculative: a BDMV-named input whose child
        // listing errors is skipped (the error is not propagated), and with no
        // parent the walk yields nothing.
        let dir = WalkDir { name: "BDMV", cyclic: false, fail_listing: true };
        assert!(walked_disc_root(&dir).is_none());
    }

    #[test]
    fn open_reports_a_playlist_referencing_a_missing_clip_file() {
        let play = mpls("00000", 0, 4_500_000, &[]);
        let disc = TempDisc::build(
            &["BDMV/CLIPINF"], // CLIPINF present but empty
            &[("BDMV/PLAYLIST/00000.mpls", play)],
        );
        assert_eq!(
            disc.open().unwrap_err().to_string(),
            "referenced missing clip file: 00000.CLPI"
        );
    }

    #[test]
    fn open_propagates_a_malformed_clip_file() {
        let disc = TempDisc::build(
            &["BDMV/PLAYLIST"],
            &[("BDMV/CLIPINF/00000.clpi", b"XXXX0100junk".to_vec())],
        );
        assert_eq!(disc.open().unwrap_err().to_string(), "unknown file type: XXXX0100");
    }

    #[test]
    fn open_propagates_a_malformed_playlist() {
        let disc = TempDisc::build(
            &["BDMV/CLIPINF"],
            &[("BDMV/PLAYLIST/00000.mpls", b"XXXXjunk".to_vec())],
        );
        assert_eq!(disc.open().unwrap_err().to_string(), "unknown file type: XXXXjunk");
    }

    #[test]
    fn read_file_surfaces_io_errors() {
        // Build a handle, delete the file, then read it: open_read fails → Io.
        let disc = TempDisc::build(&[], &[("gone.bin", vec![1, 2, 3])]);
        let file = FsFile::from_full_name(disc.root.join("gone.bin")).expect("handle");
        std::fs::remove_file(disc.root.join("gone.bin")).expect("remove");
        assert!(read_file(&file).is_err()); // io error → Err (always BdError::Io)
    }

    // ── in-memory mock BD tree with injectable io failures ───────────────────
    //
    // Real temp folders can't make a *valid* directory's enumeration or a present
    // file's read fail at a chosen point, so the io-error `?` arms inside `open`
    // and its helpers are exercised with this mock: every IO operation ticks a
    // shared counter and the (configurable) Nth one returns an error.

    /// A shared "fail the Nth io operation" trip-wire.
    #[derive(Clone)]
    struct Trip {
        count: Arc<AtomicUsize>,
        fail_at: usize,
    }

    impl Trip {
        fn new(fail_at: usize) -> Self {
            Self { count: Arc::new(AtomicUsize::new(0)), fail_at }
        }

        fn tick(&self) -> io::Result<()> {
            if self.count.fetch_add(1, Ordering::Relaxed) == self.fail_at {
                Err(io::Error::other("injected io failure"))
            } else {
                Ok(())
            }
        }

        fn used(&self) -> usize {
            self.count.load(Ordering::Relaxed)
        }
    }

    #[derive(Clone)]
    struct MockFile {
        name: String,
        extension: String,
        bytes: Vec<u8>,
        trip: Trip,
        /// When set, `open_read` succeeds but the returned reader errors — to
        /// exercise `read_file`'s `read_to_end` (not `open_read`) failure arm.
        fail_read: bool,
    }

    impl BdFile for MockFile {
        fn name(&self) -> &str {
            &self.name
        }

        fn full_name(&self) -> &str {
            &self.name
        }

        fn extension(&self) -> &str {
            &self.extension
        }

        fn length(&self) -> u64 {
            u64::try_from(self.bytes.len()).unwrap()
        }

        fn is_dir(&self) -> bool {
            false
        }

        fn open_read(&self) -> io::Result<Box<dyn ReadSeek>> {
            self.trip.tick()?;
            if self.fail_read {
                Ok(Box::new(FailingReader))
            } else {
                Ok(Box::new(Cursor::new(self.bytes.clone())))
            }
        }

        fn open_text(&self) -> io::Result<Box<dyn BufRead>> {
            // `open` reads metadata via `open_read`; `open_text` exists only to
            // satisfy the trait, so it never participates in the failure injection.
            Ok(Box::new(BufReader::new(Cursor::new(self.bytes.clone()))))
        }
    }

    /// A reader that opens fine but errors on the first read.
    struct FailingReader;

    impl Read for FailingReader {
        fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
            Err(io::Error::other("read failed"))
        }
    }

    impl Seek for FailingReader {
        fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
            Ok(0)
        }
    }

    /// Recursively collects files named `pattern` (case-insensitive) under `dir`.
    fn collect_matching(dir: &MockDir, pattern: &str, out: &mut Vec<Box<dyn BdFile>>) {
        for file in &dir.files {
            if file.name.eq_ignore_ascii_case(pattern) {
                out.push(Box::new(file.clone()));
            }
        }
        for sub in &dir.dirs {
            collect_matching(sub, pattern, out);
        }
    }

    #[derive(Clone)]
    struct MockDir {
        name: String,
        dirs: Vec<Self>,
        files: Vec<MockFile>,
        trip: Trip,
    }

    impl BdDir for MockDir {
        fn name(&self) -> &str {
            &self.name
        }

        fn full_name(&self) -> &str {
            &self.name
        }

        fn parent(&self) -> Option<Box<dyn BdDir>> {
            None
        }

        fn get_files(&self) -> io::Result<Vec<Box<dyn BdFile>>> {
            self.trip.tick()?;
            Ok(self.files.iter().cloned().map(|f| -> Box<dyn BdFile> { Box::new(f) }).collect())
        }

        fn get_files_pattern(&self, _pattern: &str) -> io::Result<Vec<Box<dyn BdFile>>> {
            self.get_files()
        }

        fn get_files_pattern_option(
            &self,
            pattern: &str,
            _option: SearchOption,
        ) -> io::Result<Vec<Box<dyn BdFile>>> {
            self.trip.tick()?;
            let mut out: Vec<Box<dyn BdFile>> = Vec::new();
            collect_matching(self, pattern, &mut out);
            Ok(out)
        }

        fn get_directories(&self) -> io::Result<Vec<Box<dyn BdDir>>> {
            self.trip.tick()?;
            Ok(self.dirs.iter().cloned().map(|d| -> Box<dyn BdDir> { Box::new(d) }).collect())
        }
    }

    /// Builds a complete, valid mock disc (two playlists, all flag dirs) whose io
    /// operations all share `trip`.
    fn mock_disc(trip: &Trip) -> MockDir {
        let file = |name: &str, bytes: Vec<u8>| {
            let extension =
                name.rsplit_once('.').map_or_else(String::new, |(_, ext)| format!(".{ext}"));
            MockFile {
                name: name.to_owned(),
                extension,
                bytes,
                trip: trip.clone(),
                fail_read: false,
            }
        };
        let dir = |name: &str, dirs: Vec<MockDir>, files: Vec<MockFile>| MockDir {
            name: name.to_owned(),
            dirs,
            files,
            trip: trip.clone(),
        };

        let clip0 =
            clpi(&[(0x1011, 0x1B, [0x63, 0x30, 0, 0]), (0x1100, 0x81, [0x61, b'e', b'n', b'g'])]);
        let clip1 = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        dir(
            "disc",
            vec![
                dir(
                    "BDMV",
                    vec![
                        dir(
                            "CLIPINF",
                            vec![],
                            vec![file("00000.clpi", clip0), file("00001.clpi", clip1)],
                        ),
                        dir(
                            "PLAYLIST",
                            vec![],
                            vec![
                                file(
                                    "00000.mpls",
                                    mpls("00000", 2_700_000, 4_500_000, &[(1, 0, 2_700_000)]),
                                ),
                                file("00001.mpls", mpls("00001", 0, 4_500_000, &[])),
                            ],
                        ),
                        dir(
                            "STREAM",
                            vec![dir("SSIF", vec![], vec![file("00000.ssif", vec![0; 10])])],
                            vec![file("00000.m2ts", vec![0; 100]), file("00001.m2ts", vec![0; 50])],
                        ),
                        dir(
                            "META",
                            vec![dir(
                                "DL",
                                vec![],
                                // a non-matching sibling so the title search's
                                // name filter exercises both outcomes
                                vec![
                                    file("thumb.jpg", vec![0xFF]),
                                    file("bdmt_eng.xml", title_xml("Movie")),
                                ],
                            )],
                            vec![],
                        ),
                        dir("BDJO", vec![], vec![file("00000.bdjo", vec![b'x'])]),
                    ],
                    vec![file("index.bdmv", b"INDX0300".to_vec())],
                ),
                dir("SNP", vec![], vec![file("clip.mnv", vec![b'x'])]),
                dir("BDSVM", vec![], vec![]),
            ],
            vec![],
        )
    }

    #[test]
    fn open_propagates_io_errors_at_every_step() {
        // A clean scan establishes the IO-operation count. The packet scan is on, so
        // the count also covers the per-stream-file open in `scan_stream_files`.
        let probe = Trip::new(usize::MAX);
        let bd = BdRom::open(&mock_disc(&probe), ScanMode::Full).expect("mock disc scans clean");
        assert_eq!(bd.playlists.len(), 2); // exercises the playlist sort comparator
        assert!(bd.is_uhd && bd.is_3d && bd.is_bd_plus && bd.is_bd_java && bd.is_psp);
        let total = probe.used();
        assert!(total > 12, "expected many io ops, got {total}");

        // Failing each successive IO op must surface as an error (never a panic),
        // walking every `?` propagation arm in `open` and its helpers.
        for fail_at in 0..total {
            let trip = Trip::new(fail_at);
            // Each injected io failure surfaces as an error (never a panic); the io
            // path only ever yields `BdError::Io`.
            assert!(
                BdRom::open(&mock_disc(&trip), ScanMode::Full).is_err(),
                "io failure at op {fail_at}"
            );
        }
    }

    #[test]
    fn scan_stream_files_propagates_a_reader_error() {
        // A STREAM dir with one `*.m2ts` whose reader fails after a successful open:
        // the packet scan's read error propagates out of `scan_stream_files`.
        let trip = Trip::new(usize::MAX);
        let m2ts = MockFile {
            name: "00000.m2ts".to_owned(),
            extension: ".m2ts".to_owned(),
            bytes: vec![0_u8; 200],
            trip: trip.clone(),
            fail_read: true,
        };
        let stream_dir =
            MockDir { name: "STREAM".to_owned(), dirs: Vec::new(), files: vec![m2ts], trip };
        // A non-empty playlist list so the scan proceeds past its empty-input guard.
        let mut playlists =
            vec![TsPlaylistFile::scan("00000.mpls", &mpls("00000", 0, 4_500_000, &[])).unwrap()];
        // Strict mode propagates the read failure…
        let mut noop = |_: ScanProgress<'_>| {};
        let mut progress =
            Progress { callback: &mut noop, done: 0, total: 200, cancel: &AtomicBool::new(false) };
        let strict = scan_stream_files(
            Some(&stream_dir),
            None,
            &mut playlists,
            None,
            &mut progress,
            &mut Sink { errors: None },
            false,
        );
        assert!(strict.is_err());
        // …resilient mode records it and skips the file; the failed file still
        // consumes its progress budget (the snap to the file boundary).
        let mut errors = Vec::new();
        let mut noop = |_: ScanProgress<'_>| {};
        let mut progress =
            Progress { callback: &mut noop, done: 0, total: 200, cancel: &AtomicBool::new(false) };
        let resilient = scan_stream_files(
            Some(&stream_dir),
            None,
            &mut playlists,
            None,
            &mut progress,
            &mut Sink { errors: Some(&mut errors) },
            false,
        )
        .expect("resilient scan continues");
        assert_eq!(progress.done, 200, "the failed file's bytes are snapped past");
        assert!(resilient.is_empty());
        assert_eq!(errors.len(), 1);
        let recorded = errors.first().expect("one recorded error");
        assert_eq!(recorded.stage, ScanStage::StreamFile);
        assert_eq!(recorded.file, "00000.m2ts");
    }

    // ── scan progress + selection ───────────────────────────────────────────

    #[test]
    fn scan_total_budgets_selected_sources_once_preferring_the_ssif() {
        let stream_files = BTreeMap::from([
            ("00000.M2TS".to_owned(), 1000_u64),
            ("00001.M2TS".to_owned(), 500_u64),
        ]);
        let interleaved_files = BTreeMap::from([("00000.SSIF".to_owned(), 4000_u64)]);
        // No selection: every file, its .ssif source preferred, once — the
        // reported budget is the full pass only.
        assert_eq!(scan_total(&stream_files, &interleaved_files, None), 4000 + 500);
        // A selection narrows the budget to the named files.
        let only_one = BTreeSet::from(["00001.M2TS".to_owned()]);
        assert_eq!(scan_total(&stream_files, &interleaved_files, Some(&only_one)), 500);
        // An empty selection budgets nothing.
        assert_eq!(scan_total(&stream_files, &interleaved_files, Some(&BTreeSet::new())), 0);
        // Without interleaved sources the file's own size counts.
        assert_eq!(scan_total(&stream_files, &BTreeMap::new(), None), 1500);
    }

    #[test]
    fn progress_advances_clamped_and_snaps_at_file_boundaries() {
        let mut events: Vec<(String, u64, u64)> = Vec::new();
        {
            let mut callback =
                |p: ScanProgress<'_>| events.push((p.file.to_owned(), p.done, p.total));
            let mut progress = Progress {
                callback: &mut callback,
                done: 0,
                total: 100,
                cancel: &AtomicBool::new(false),
            };
            progress.advance("A.M2TS", 30);
            // An over-read clamps at the total instead of overshooting.
            progress.advance("A.M2TS", 90);
            // A snap target below the current count never moves it backwards…
            progress.finish_file("A.M2TS", 50);
        }
        assert_eq!(
            events,
            [
                ("A.M2TS".to_owned(), 30, 100),
                ("A.M2TS".to_owned(), 100, 100),
                ("A.M2TS".to_owned(), 100, 100),
            ]
        );

        // …and a snap past a short read pulls the count up to the boundary.
        events.clear();
        {
            let mut callback =
                |p: ScanProgress<'_>| events.push((p.file.to_owned(), p.done, p.total));
            let mut progress = Progress {
                callback: &mut callback,
                done: 0,
                total: 100,
                cancel: &AtomicBool::new(false),
            };
            progress.advance("B.M2TS", 10);
            progress.finish_file("B.M2TS", 60);
        }
        assert_eq!(events, [("B.M2TS".to_owned(), 10, 100), ("B.M2TS".to_owned(), 60, 100)]);
    }

    /// A cancel flag that never trips — the default scan extras of every test
    /// that is not about cancellation.
    fn never_cancel() -> AtomicBool {
        AtomicBool::new(false)
    }

    #[test]
    fn open_with_reports_progress_and_narrows_the_scan_to_selected_files() {
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 2_700_000, 4_500_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", clpi(&[(0x1011, 0x1B, [0x63, 0x30, 0, 0])])),
                ("BDMV/STREAM/00000.m2ts", vec![0_u8; 1000]),
                ("BDMV/PLAYLIST/00001.mpls", mpls("00001", 2_700_000, 4_500_000, &[])),
                ("BDMV/CLIPINF/00001.clpi", clpi(&[(0x1011, 0x1B, [0x63, 0x30, 0, 0])])),
                ("BDMV/STREAM/00001.m2ts", vec![0_u8; 500]),
            ],
        );
        let root = FsDir::new(disc.root.clone());

        // Full scan: both files — the count runs 0→total over the full pass
        // (the quick codec-init pass is neither budgeted nor reported).
        let mut events: Vec<(String, u64, u64)> = Vec::new();
        let mut collect = |p: ScanProgress<'_>| events.push((p.file.to_owned(), p.done, p.total));
        let bd = BdRom::open_with(&root, ScanMode::Full, None, &mut collect, &never_cancel())
            .expect("scan with progress");
        assert_eq!(bd.playlists.len(), 2);
        assert!(!events.is_empty());
        assert!(events.iter().all(|(_, _, total)| *total == 1000 + 500));
        assert!(events.windows(2).all(|pair| {
            pair.first().is_none_or(|(_, a, _)| pair.get(1).is_none_or(|(_, b, _)| a <= b))
        }));
        assert_eq!(events.last().map(|(_, done, _)| *done), Some(1500));
        assert!(events.iter().any(|(file, _, _)| file == "00000.M2TS"));
        assert!(events.iter().any(|(file, _, _)| file == "00001.M2TS"));

        // A selection narrows the scan: only the named file is read (and
        // budgeted), the other playlist still summarises from metadata.
        let selected = BTreeSet::from(["00000.M2TS".to_owned()]);
        let mut events: Vec<(String, u64, u64)> = Vec::new();
        let mut collect = |p: ScanProgress<'_>| events.push((p.file.to_owned(), p.done, p.total));
        let bd =
            BdRom::open_with(&root, ScanMode::Full, Some(&selected), &mut collect, &never_cancel())
                .expect("scan the selection");
        assert_eq!(bd.playlists.len(), 2);
        assert!(events.iter().all(|(file, _, total)| file == "00000.M2TS" && *total == 1000));
        assert_eq!(events.last().map(|(_, done, _)| *done), Some(1000));

        // The resilient variant takes the same extras and records nothing on
        // healthy media.
        let mut last_total = 0;
        let mut observe = |p: ScanProgress<'_>| last_total = p.total;
        let report = BdRom::open_resilient_with(
            &root,
            ScanMode::Full,
            Some(&selected),
            &mut observe,
            &never_cancel(),
        )
        .expect("resilient scan with progress");
        assert!(report.errors.is_empty());
        assert_eq!(last_total, 1000);
        assert_eq!(report.bdrom, bd);

        // Without the packet scan the callback never fires.
        let mut fired = false;
        let mut observe = |_: ScanProgress<'_>| fired = true;
        drop(
            BdRom::open_with(&root, ScanMode::Metadata, None, &mut observe, &never_cancel())
                .expect("metadata-only scan"),
        );
        assert!(!fired);
    }

    // ── cooperative cancellation ─────────────────────────────────────────────

    /// The two-playlist / two-stream-file on-disk fixture the cancellation
    /// tests scan (the same shape the progress test uses).
    fn cancel_fixture() -> TempDisc {
        TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 2_700_000, 4_500_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", clpi(&[(0x1011, 0x1B, [0x63, 0x30, 0, 0])])),
                ("BDMV/STREAM/00000.m2ts", vec![0_u8; 1000]),
                ("BDMV/PLAYLIST/00001.mpls", mpls("00001", 2_700_000, 4_500_000, &[])),
                ("BDMV/CLIPINF/00001.clpi", clpi(&[(0x1011, 0x1B, [0x63, 0x30, 0, 0])])),
                ("BDMV/STREAM/00001.m2ts", vec![0_u8; 500]),
            ],
        )
    }

    #[test]
    fn a_cancel_flag_tripped_by_the_progress_callback_aborts_the_scan() {
        let disc = cancel_fixture();
        let root = FsDir::new(disc.root.clone());
        // Baseline: the uncancelled full scan's complete event trail.
        let mut baseline: Vec<u64> = Vec::new();
        let mut collect = |p: ScanProgress<'_>| baseline.push(p.done);
        drop(
            BdRom::open_with(&root, ScanMode::Full, None, &mut collect, &never_cancel())
                .expect("the uncancelled scan"),
        );
        // Cancelling on the FIRST event: the scan aborts with `ScanCancelled`
        // and stops emitting promptly — the full pass's event trail and the
        // file-boundary snaps never happen, proving an early exit rather than
        // a scan run to completion.
        let cancel = AtomicBool::new(false);
        let mut events: Vec<u64> = Vec::new();
        let mut trip = |p: ScanProgress<'_>| {
            events.push(p.done);
            cancel.store(true, Ordering::Relaxed);
        };
        let err = BdRom::open_with(&root, ScanMode::Full, None, &mut trip, &cancel)
            .expect_err("the cancelled scan errors");
        assert_eq!(err.to_string(), "scan cancelled");
        assert!(events.len() < baseline.len(), "the cancelled scan must stop early");
        assert!(events.len() <= 3, "the event trail stops at the in-flight chunk");

        // The resilient scan aborts identically: cancellation is the caller's
        // abort, not disc damage to collect, so no partial report escapes.
        let cancel = AtomicBool::new(false);
        let mut trip = |_: ScanProgress<'_>| cancel.store(true, Ordering::Relaxed);
        let err = BdRom::open_resilient_with(&root, ScanMode::Full, None, &mut trip, &cancel)
            .expect_err("the cancelled resilient scan errors");
        assert_eq!(err.to_string(), "scan cancelled");
    }

    #[test]
    fn a_preset_cancel_flag_aborts_the_packet_scan_before_any_progress() {
        let disc = cancel_fixture();
        let root = FsDir::new(disc.root.clone());
        let cancel = AtomicBool::new(true);
        // Every packet-scanning mode aborts on the quick pass's first chunk
        // read, before the full pass ever fires the callback.
        for mode in [ScanMode::Codecs, ScanMode::Full] {
            let mut fired = false;
            let mut observe = |_: ScanProgress<'_>| fired = true;
            let err = BdRom::open_with(&root, mode, None, &mut observe, &cancel)
                .expect_err("the pre-cancelled scan errors");
            assert_eq!(err.to_string(), "scan cancelled");
            assert!(!fired, "no progress escapes a pre-cancelled scan");
        }
        let mut resilient_fired = false;
        let mut observe = |_: ScanProgress<'_>| resilient_fired = true;
        let err = BdRom::open_resilient_with(&root, ScanMode::Full, None, &mut observe, &cancel)
            .expect_err("the pre-cancelled resilient scan errors");
        assert_eq!(err.to_string(), "scan cancelled");
        assert!(!resilient_fired, "no progress escapes the resilient abort either");
        // Metadata reads no packets, so the flag is never observed — the
        // bounded structural scan completes as if no flag existed.
        let mut metadata_fired = false;
        let mut observe = |_: ScanProgress<'_>| metadata_fired = true;
        let bd = BdRom::open_with(&root, ScanMode::Metadata, None, &mut observe, &cancel)
            .expect("the metadata scan never polls the flag");
        assert!(!metadata_fired, "a metadata scan reads no packets");
        assert_eq!(bd.playlists.len(), 2);
    }

    #[test]
    fn a_cancelled_resilient_scan_records_no_per_file_errors() {
        // Cancellation mid-pass aborts the RESILIENT `scan_stream_files` with
        // nothing recorded — a cancel never misreports the in-flight (or any
        // later) file as damaged.
        let trip = Trip::new(usize::MAX);
        let file = |name: &str| MockFile {
            name: name.to_owned(),
            extension: ".m2ts".to_owned(),
            bytes: vec![0_u8; 200],
            trip: trip.clone(),
            fail_read: false,
        };
        let stream_dir = MockDir {
            name: "STREAM".to_owned(),
            dirs: Vec::new(),
            files: vec![file("00000.m2ts"), file("00001.m2ts")],
            trip,
        };
        let mut playlists =
            vec![TsPlaylistFile::scan("00000.mpls", &mpls("00000", 0, 4_500_000, &[])).unwrap()];
        let cancel = AtomicBool::new(false);
        let mut arm = |_: ScanProgress<'_>| cancel.store(true, Ordering::Relaxed);
        let mut progress = Progress { callback: &mut arm, done: 0, total: 400, cancel: &cancel };
        let mut errors = Vec::new();
        let result = scan_stream_files(
            Some(&stream_dir),
            None,
            &mut playlists,
            None,
            &mut progress,
            &mut Sink { errors: Some(&mut errors) },
            false,
        );
        let message = result.err().map(|err| err.to_string());
        assert_eq!(message.as_deref(), Some("scan cancelled"));
        assert!(errors.is_empty(), "cancellation is never a per-file failure");
    }

    // ── the resilient (collect-and-continue) scan ────────────────────────────

    #[test]
    fn open_resilient_equals_open_on_a_healthy_disc_with_no_errors() {
        // Resilience is additive: on healthy media the resilient scan returns the
        // exact same BdRom as the strict scan, with an empty error list.
        let clip = clpi(&[(0x1011, 0x1B, [0x63, 0x30, 0, 0])]);
        let play = mpls("00000", 2_700_000, 4_500_000, &[(1, 0, 2_700_000)]);
        let disc = TempDisc::build(
            &[],
            &[("BDMV/PLAYLIST/00000.mpls", play), ("BDMV/CLIPINF/00000.clpi", clip)],
        );
        let strict = disc.open().expect("strict scan");
        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("resilient scan");
        assert!(report.errors.is_empty());
        assert_eq!(report.bdrom, strict);
    }

    #[test]
    fn open_resilient_keeps_other_playlists_on_a_corrupt_clip_file() {
        // Playlist 00001 references the corrupt 00001.clpi; playlist 00000 is
        // healthy. The strict scan aborts everything; the resilient scan emits
        // 00000.MPLS and records both the clip-info parse failure and the playlist
        // that lost its clip.
        let good_clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
                ("BDMV/PLAYLIST/00001.mpls", mpls("00001", 0, 9_000_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", good_clip),
                ("BDMV/CLIPINF/00001.clpi", b"XXXX0100junk".to_vec()),
            ],
        );
        assert!(disc.open().is_err(), "the strict scan aborts on the corrupt clip");

        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("resilient scan continues");
        let names: Vec<&str> = report.bdrom.playlists.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["00000.MPLS"]); // the readable rest is emitted
        assert_eq!(report.errors.len(), 2);
        let clip_err = report.errors.first().expect("clip error");
        assert_eq!(clip_err.stage, ScanStage::ClipInfo);
        assert_eq!(clip_err.file, "00001.clpi");
        assert_eq!(clip_err.reason.to_string(), "unknown file type: XXXX0100");
        let playlist_err = report.errors.get(1).expect("playlist error");
        assert_eq!(playlist_err.stage, ScanStage::Playlist);
        assert_eq!(playlist_err.file, "00001.MPLS");
        assert_eq!(playlist_err.reason.to_string(), "referenced missing clip file: 00001.CLPI");
    }

    #[test]
    fn open_resilient_keeps_other_playlists_on_a_corrupt_playlist() {
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
                ("BDMV/PLAYLIST/00001.mpls", b"XXXXjunk".to_vec()),
                ("BDMV/CLIPINF/00000.clpi", clip),
            ],
        );
        assert!(disc.open().is_err(), "the strict scan aborts on the corrupt playlist");

        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("resilient scan continues");
        let names: Vec<&str> = report.bdrom.playlists.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["00000.MPLS"]);
        assert_eq!(report.errors.len(), 1);
        let err = report.errors.first().expect("playlist error");
        assert_eq!((err.stage, err.file.as_str()), (ScanStage::Playlist, "00001.mpls"));
        assert_eq!(err.reason.to_string(), "unknown file type: XXXXjunk");
    }

    #[test]
    fn open_resilient_defaults_the_flags_on_failed_metadata_reads() {
        // index.bdmv and bdmt_eng.xml open fine but fail to read: the resilient
        // scan records both and falls back to is_uhd=false / disc_title=None.
        let trip = Trip::new(usize::MAX);
        let broken = |name: &str| MockFile {
            name: name.to_owned(),
            extension: name.rsplit_once('.').map_or_else(String::new, |(_, e)| format!(".{e}")),
            bytes: vec![0],
            trip: trip.clone(),
            fail_read: true,
        };
        let dir = |name: &str, dirs: Vec<MockDir>, files: Vec<MockFile>| MockDir {
            name: name.to_owned(),
            dirs,
            files,
            trip: trip.clone(),
        };
        let root = dir(
            "disc",
            vec![dir(
                "BDMV",
                vec![
                    dir("CLIPINF", vec![], vec![]),
                    dir("PLAYLIST", vec![], vec![]),
                    dir("META", vec![], vec![broken("bdmt_eng.xml")]),
                ],
                vec![broken("index.bdmv")],
            )],
            vec![],
        );
        let report =
            BdRom::open_resilient(&root, ScanMode::Metadata).expect("resilient scan continues");
        assert!(!report.bdrom.is_uhd);
        assert_eq!(report.bdrom.disc_title, None);
        assert_eq!(report.errors.len(), 2);
        let uhd = report.errors.first().expect("index error");
        assert_eq!((uhd.stage, uhd.file.as_str()), (ScanStage::Discovery, "index.bdmv"));
        let title = report.errors.get(1).expect("title error");
        assert_eq!((title.stage, title.file.as_str()), (ScanStage::Discovery, "META"));

        // The strict scan aborts on the first of the same failures.
        assert!(BdRom::open(&root, ScanMode::Metadata).is_err());
    }

    #[test]
    fn open_resilient_records_an_io_failure_at_every_step() {
        // The resilient counterpart of `open_propagates_io_errors_at_every_step`:
        // failing each successive IO op either aborts (the fatal structure-locating
        // block) or completes with that failure recorded — never panics, never
        // silently swallows.
        let probe = Trip::new(usize::MAX);
        let clean =
            BdRom::open_resilient(&mock_disc(&probe), ScanMode::Full).expect("mock disc scans");
        assert!(clean.errors.is_empty());
        let total = probe.used();

        let mut absorbed = 0_usize;
        for fail_at in 0..total {
            let trip = Trip::new(fail_at);
            // An `Err` is the fatal BDMV/CLIPINF/PLAYLIST block; everything else
            // must complete with the failure recorded.
            if let Ok(report) = BdRom::open_resilient(&mock_disc(&trip), ScanMode::Full) {
                assert!(
                    !report.errors.is_empty(),
                    "io failure at op {fail_at} was swallowed without a record"
                );
                absorbed = absorbed.saturating_add(1);
            }
        }
        // Most ops are isolated (only the directory-locating block is fatal).
        assert!(absorbed > total.saturating_div(2), "absorbed {absorbed} of {total}");
    }

    #[test]
    fn read_file_surfaces_a_read_error_after_a_successful_open() {
        let unreadable = MockFile {
            name: "unreadable.bin".to_owned(),
            extension: ".bin".to_owned(),
            bytes: vec![1],
            trip: Trip::new(usize::MAX),
            fail_read: true,
        };
        assert!(read_file(&unreadable).is_err()); // open_read ok, read_to_end fails
        // Exercise the failing reader's seek.
        let mut reader = unreadable.open_read().expect("open");
        assert_eq!(reader.seek(SeekFrom::Start(0)).expect("seek"), 0);
    }

    #[test]
    fn mock_trait_surface_is_exercised() {
        // The mock's trait methods `open` never calls (`full_name`, `parent`,
        // `get_files_pattern`, `is_dir`, `open_text`) are touched here so the mock
        // itself stays fully covered.
        let trip = Trip::new(usize::MAX);
        let root = mock_disc(&trip);
        assert_eq!(root.full_name(), "disc");
        assert!(root.parent().is_none());
        assert_eq!(root.get_files_pattern("*").expect("pattern").len(), root.files.len());
        let file = root.get_directories().expect("dirs");
        assert!(!file.is_empty());
        let mock_file = MockFile {
            name: "x".to_owned(),
            extension: String::new(),
            bytes: vec![1],
            trip,
            fail_read: false,
        };
        assert_eq!(mock_file.full_name(), "x");
        assert!(!mock_file.is_dir());
        let mut text = String::new();
        mock_file.open_text().expect("open_text").read_to_string(&mut text).expect("read");
        assert_eq!(text, "\u{1}");
    }

    // ── FMTS clips ───────────────────────────────────────────────────────────

    #[test]
    fn clip_stem_strips_either_stream_extension() {
        assert_eq!(clip_stem("00000.M2TS"), "00000");
        assert_eq!(clip_stem("00000.FMTS"), "00000");
        assert_eq!(clip_stem("noext"), "noext");
    }

    #[test]
    fn open_scanned_resolves_an_fmts_clip_stream_file() {
        // A play item whose codec id is `FMTS` resolves a `*.FMTS` stream file
        // (not `*.M2TS`) while still pairing with its `*.CLPI` by stem, so an
        // FMTS disc scans instead of degrading to a missing-file warning.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let play = mpls_items_codec(*b"FMTS", &["00000"], 0, 4_500_000, &[], &[], &[]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", play),
                ("BDMV/CLIPINF/00000.clpi", clip),
                ("BDMV/STREAM/00000.fmts", vec![0; 200]),
            ],
        );
        let bd = disc.open_scanned().expect("fmts disc scans");
        let playlist = bd.playlists.first().expect("one playlist");
        let clip = playlist.clips.first().expect("one clip");
        assert_eq!(clip.name, "00000.FMTS"); // the clip resolved its `.fmts` file
        // The `.fmts` file was discovered as a stream file and folded into the size.
        assert_eq!(playlist.file_size, 200);
    }

    // ── BDMV/BACKUP recovery ─────────────────────────────────────────────────

    #[test]
    fn open_resilient_recovers_a_playlist_from_backup() {
        // The primary playlist is corrupt but `BDMV/BACKUP/PLAYLIST` carries an
        // intact copy: the resilient scan recovers the playlist and still notes
        // the bad primary. Strict open never reads BACKUP, so it aborts.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", b"XXXXjunk".to_vec()),
                ("BDMV/BACKUP/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", clip),
            ],
        );
        assert!(disc.open().is_err(), "strict open ignores BACKUP");

        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("recovers");
        let names: Vec<&str> = report.bdrom.playlists.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["00000.MPLS"]); // recovered from BACKUP
        assert_eq!(report.errors.len(), 1);
        let err = report.errors.first().expect("primary note");
        assert_eq!((err.stage, err.file.as_str()), (ScanStage::Playlist, "00000.mpls"));
        assert_eq!(err.reason.to_string(), "unknown file type: XXXXjunk");
    }

    #[test]
    fn open_resilient_recovers_a_clip_from_backup() {
        // The primary clip-info is corrupt but `BDMV/BACKUP/CLIPINF` is intact:
        // the clip recovers, so its playlist scans (no missing-clip failure) and
        // only the bad primary is noted.
        let good_clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", b"XXXX0100junk".to_vec()),
                ("BDMV/BACKUP/CLIPINF/00000.clpi", good_clip),
            ],
        );
        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("recovers");
        let names: Vec<&str> = report.bdrom.playlists.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["00000.MPLS"]); // the clip recovered → playlist scans
        assert_eq!(report.errors.len(), 1);
        let err = report.errors.first().expect("clip note");
        assert_eq!((err.stage, err.file.as_str()), (ScanStage::ClipInfo, "00000.clpi"));
        assert_eq!(err.reason.to_string(), "unknown file type: XXXX0100");
    }

    #[test]
    fn open_resilient_recovers_the_index_from_backup() {
        // The primary `index.bdmv` is present but unreadable; the BACKUP copy
        // says UHD. The resilient scan recovers the UHD flag and notes the bad
        // primary. (A real on-disk file can't fail to read, so this uses the
        // io-injecting mock.)
        let trip = Trip::new(usize::MAX);
        let mk = |name: &str, bytes: Vec<u8>, fail_read: bool| MockFile {
            name: name.to_owned(),
            extension: name.rsplit_once('.').map_or_else(String::new, |(_, e)| format!(".{e}")),
            bytes,
            trip: trip.clone(),
            fail_read,
        };
        let dir = |name: &str, dirs: Vec<MockDir>, files: Vec<MockFile>| MockDir {
            name: name.to_owned(),
            dirs,
            files,
            trip: trip.clone(),
        };
        let root = dir(
            "disc",
            vec![dir(
                "BDMV",
                vec![
                    dir("CLIPINF", vec![], vec![]),
                    dir("PLAYLIST", vec![], vec![]),
                    dir("BACKUP", vec![], vec![mk("index.bdmv", b"INDX0300".to_vec(), false)]),
                ],
                vec![mk("index.bdmv", vec![0], true)], // primary unreadable
            )],
            vec![],
        );
        let report = BdRom::open_resilient(&root, ScanMode::Metadata).expect("scans");
        assert!(report.bdrom.is_uhd, "UHD flag recovered from BACKUP");
        assert_eq!(report.errors.len(), 1);
        let err = report.errors.first().expect("index note");
        assert_eq!((err.stage, err.file.as_str()), (ScanStage::Discovery, "index.bdmv"));
    }

    #[test]
    fn open_resilient_does_not_recover_from_a_corrupt_backup() {
        // Both copies are corrupt: nothing recovers, and only the primary's
        // failure is recorded (the backup's is not double-counted).
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", b"XXXXjunk".to_vec()),
                ("BDMV/BACKUP/PLAYLIST/00000.mpls", b"YYYYjunk".to_vec()),
                ("BDMV/CLIPINF/00000.clpi", clip),
            ],
        );
        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("scans");
        assert!(report.bdrom.playlists.is_empty());
        assert_eq!(report.errors.len(), 1);
        assert_eq!(
            report.errors.first().expect("primary note").reason.to_string(),
            "unknown file type: XXXXjunk"
        );
    }

    #[test]
    fn open_resilient_does_not_recover_when_backup_lacks_the_file() {
        // The BACKUP directory exists but holds a different file, so the corrupt
        // primary cannot be recovered.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let disc = TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", b"XXXXjunk".to_vec()),
                ("BDMV/BACKUP/PLAYLIST/00001.mpls", mpls("00001", 0, 4_500_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", clip),
            ],
        );
        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("scans");
        assert!(report.bdrom.playlists.is_empty());
        assert_eq!(report.errors.len(), 1);
    }

    #[test]
    fn backup_subdir_files_lists_present_and_empties_absent_directories() {
        let ok = Trip::new(usize::MAX);
        let mk = |name: &str| MockFile {
            name: name.to_owned(),
            extension: ".mpls".to_owned(),
            bytes: vec![1],
            trip: ok.clone(),
            fail_read: false,
        };
        let playlist = MockDir {
            name: "PLAYLIST".to_owned(),
            dirs: Vec::new(),
            files: vec![mk("00000.mpls")],
            trip: ok.clone(),
        };
        let backup = MockDir {
            name: "BACKUP".to_owned(),
            dirs: vec![playlist],
            files: Vec::new(),
            trip: ok,
        };
        // A present subdirectory is listed keyed by upper-cased name…
        let pool = backup_subdir_files(&backup, BdmvDir::Playlist).expect("present");
        assert!(pool.contains_key("00000.MPLS"));
        // …an absent one yields an empty pool.
        assert!(backup_subdir_files(&backup, BdmvDir::ClipInf).expect("absent").is_empty());
    }

    #[test]
    fn collect_backups_lists_all_pools_and_propagates_every_listing_failure() {
        // A `BDMV` whose `BACKUP` (index.bdmv + PLAYLIST + CLIPINF) shares a trip
        // across its own listing ops, while `BDMV` itself never fails — so every
        // BACKUP-side listing failure can be injected one at a time, and none is
        // silently swallowed.
        let build = |bt: &Trip| {
            let mk = |name: &str| MockFile {
                name: name.to_owned(),
                extension: name.rsplit_once('.').map_or_else(String::new, |(_, e)| format!(".{e}")),
                bytes: vec![1],
                trip: bt.clone(),
                fail_read: false,
            };
            let sub = |name: &str, file: &str| MockDir {
                name: name.to_owned(),
                dirs: Vec::new(),
                files: vec![mk(file)],
                trip: bt.clone(),
            };
            let backup = MockDir {
                name: "BACKUP".to_owned(),
                dirs: vec![sub("PLAYLIST", "00000.mpls"), sub("CLIPINF", "00000.clpi")],
                files: vec![mk("index.bdmv")],
                trip: bt.clone(),
            };
            MockDir {
                name: "BDMV".to_owned(),
                dirs: vec![backup],
                files: Vec::new(),
                trip: Trip::new(usize::MAX), // locating BACKUP never fails
            }
        };
        // A clean probe collects all three pools and counts the BACKUP-side ops.
        let probe = Trip::new(usize::MAX);
        let (index, playlist, clipinf) = collect_backups(&build(&probe)).expect("clean probe");
        assert!(index.contains_key("INDEX.BDMV"));
        assert!(playlist.contains_key("00000.MPLS"));
        assert!(clipinf.contains_key("00000.CLPI"));
        let total = probe.used();
        assert!(total >= 5, "expected several BACKUP listing ops, got {total}");
        // Failing each successive BACKUP listing op surfaces as Err (none swallowed).
        for fail_at in 0..total {
            let bt = Trip::new(fail_at);
            assert!(collect_backups(&build(&bt)).is_err(), "listing failure at op {fail_at}");
        }
    }

    // ── index.bdmv sanity warning ────────────────────────────────────────────

    #[test]
    fn an_untagged_index_warns_in_resilient_and_is_tolerated_in_strict() {
        // A present `index.bdmv` lacking the `INDX` tag stays non-UHD (the
        // tolerance is kept), but the resilient scan surfaces it as a warning;
        // strict open tolerates it silently.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let make = |index: &[u8]| {
            TempDisc::build(
                &[],
                &[
                    ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
                    ("BDMV/CLIPINF/00000.clpi", clip.clone()),
                    ("BDMV/index.bdmv", index.to_vec()),
                ],
            )
        };

        // A long (>= 8 byte) garbage index: warned, version magic reported.
        let disc = make(b"XXXXjunk");
        let report = BdRom::open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("scans");
        assert!(!report.bdrom.is_uhd);
        assert_eq!(report.errors.len(), 1);
        let err = report.errors.first().expect("index warning");
        assert_eq!((err.stage, err.file.as_str()), (ScanStage::Discovery, "index.bdmv"));
        assert_eq!(err.reason.to_string(), "unknown file type: XXXXjunk");
        // Strict open tolerates the same index silently — non-UHD, no error.
        assert!(!disc.open().expect("strict tolerates an untagged index").is_uhd);

        // A short (< 8 byte) garbage index: still warned, magic empty.
        let short = make(b"XX");
        let report = BdRom::open_resilient(&FsDir::new(short.root.clone()), ScanMode::Metadata)
            .expect("scans");
        assert!(!report.bdrom.is_uhd);
        assert_eq!(
            report.errors.first().expect("short index warning").reason.to_string(),
            "unknown file type: "
        );
    }
}