bdinfo-rs-core 4.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
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
//! 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/AACS/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::fmt;
use std::io::{self, Read};
use std::sync::atomic::{AtomicBool, Ordering};

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::measured::{self, MeasuredSnapshot};
use super::mpls::TsPlaylistFile;
use super::order::{self, PlaylistFilter};
use super::shortfall::{self, ShortStreamFile};
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, TsVideoStream};
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>,
}

/// The most extra camera angles [`PlaylistSummary::angle_totals`] builds totals
/// for — the most a playlist can declare.
///
/// A playlist item's angle table opens with a one-byte angle count and
/// [`super::mpls`] takes the *extra* angles as that byte less one, so the widest
/// table a `*.mpls` can express (255) is 254 extras and no parsed playlist can
/// carry more. [`PlaylistSummary::angle_count`] is a plain `usize` field,
/// though, so a caller that assembles a summary rather than scanning one can set
/// it to anything, and every angle costs an [`AngleTotals`] slot plus a walk of
/// the clip list: 100,000,000 angles asked for a 3 GiB allocation (measured
/// 2026-08-03, one playlist, one clip). Bounding the loop holds every caller to
/// what the format itself can say.
const MAX_EXTRA_ANGLES: usize = 254;

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)
    }

    /// The playlist's *estimated* (on-disk, unmeasured) size in bytes.
    ///
    /// The interleaved `*.ssif` total when the playlist has one, else the
    /// `*.m2ts` total, else `None` — neither file is present, or none has a
    /// size.
    ///
    /// The interleaved total wins because an `*.ssif` already contains its
    /// playlist's `*.m2ts` bytes; adding the two would double-count. How an
    /// absent size renders is the caller's choice (the classic table prints
    /// `-`).
    #[must_use]
    pub const fn estimated_bytes(&self) -> Option<u64> {
        if self.interleaved_file_size > 0 {
            Some(self.interleaved_file_size)
        } else if self.file_size > 0 {
            Some(self.file_size)
        } else {
            None
        }
    }

    /// 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.
    ///
    /// At most 254 entries, whatever [`angle_count`](Self::angle_count) says:
    /// 254 extra angles is the widest angle table a playlist can declare, so a
    /// larger count is bounded here rather than allocated for.
    #[must_use]
    pub fn angle_totals(&self) -> Vec<AngleTotals> {
        let mut totals = Vec::new();
        for angle in 1..=self.angle_count.min(MAX_EXTRA_ANGLES) {
            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
    }
}

/// The footnote a playlist listing prints when any listed playlist reports
/// [`PlaylistSummary::has_hidden_streams`].
///
/// The classic `BDInfo` wording, explaining the `*` those playlists are marked
/// with.
///
/// A surface with no room for a footnote need not show it, but one that does
/// must show this text: the mark and its explanation are one contract.
pub const HIDDEN_STREAMS_NOTE: &str =
    "(*) Some playlists on this disc have hidden tracks. These tracks are marked with an asterisk.";

/// `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,
    /// Whether the measurement pass demuxed this clip's stream file.
    ///
    /// The one thing that separates "measured as empty" from "never looked
    /// at", both of which leave every measured field below at zero: a
    /// [`ScanMode::Metadata`] or [`ScanMode::Codecs`] open, a file a
    /// `scan_files` selection left out, a file that failed to open, and a file
    /// whose partial demux was dropped ([`ScanOptions::keep_partial`] off) all
    /// come back `false`, while a 0-byte or header-destroyed file that opens,
    /// reads to a clean end of file and registers no stream at all comes back
    /// `true` with nothing measured — which is what lets
    /// [`BdRom::short_stream_files`] name it.
    pub measured: bool,
    /// 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 — its demuxed packet count at
    /// [`measured::packet_size`]'s 192 bytes a source packet, the same
    /// conversion the live snapshots of a running scan apply.
    #[must_use]
    pub const fn packet_size(&self) -> u64 {
        measured::packet_size(self.packet_count)
    }

    /// 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)
    }

    /// The clip's *estimated* (on-disk, unmeasured) size in bytes.
    ///
    /// The interleaved `*.ssif` size when the clip has one, else the `*.m2ts`
    /// size, else `None` (the file is absent) — the per-clip form of
    /// [`PlaylistSummary::estimated_bytes`], with the same preference and the
    /// same reason for it.
    #[must_use]
    pub const fn estimated_bytes(&self) -> Option<u64> {
        if self.interleaved_file_size > 0 {
            Some(self.interleaved_file_size)
        } else if self.file_size > 0 {
            Some(self.file_size)
        } else {
            None
        }
    }
}

/// Test constructors for [`PlaylistSummary`] and [`ClipSummary`].
///
/// Both are wide plain-data structs — 11 and 13 public fields — while a test
/// usually cares about two or three. Each function takes those few and zeroes
/// the rest, so a test spells only its own intent and a field added to either
/// struct changes one body here instead of every construction site.
///
/// Other crates reach these through the off-by-default `test-fixtures` feature;
/// inside this crate `cfg(test)` alone brings them in.
#[cfg(any(test, feature = "test-fixtures"))]
pub mod fixtures {
    use super::{ClipSummary, PlaylistSummary};

    /// A clip named `name` — its display name too — `length` seconds long,
    /// with no sizes and nothing measured.
    #[must_use]
    pub fn clip(name: &str, length: f64) -> ClipSummary {
        ClipSummary {
            name: name.to_owned(),
            display_name: name.to_owned(),
            file_size: 0,
            interleaved_file_size: 0,
            angle_index: 0,
            relative_time_in: 0.0,
            length,
            measured: false,
            payload_bytes: 0,
            packet_count: 0,
            packet_seconds: 0.0,
            file_seconds: 0.0,
            streams: Vec::new(),
        }
    }

    /// One [`clip`] per name in `names`, each `length` seconds long — the clip
    /// sequence of a playlist that plays those files.
    #[must_use]
    pub fn clips(names: &[&str], length: f64) -> Vec<ClipSummary> {
        names.iter().map(|name| clip(name, length)).collect()
    }

    /// A single-angle, non-looping playlist named `name`, `total_length`
    /// seconds long, presenting `clips` and no streams, chapters or sizes.
    #[must_use]
    pub fn playlist(name: &str, total_length: f64, clips: Vec<ClipSummary>) -> PlaylistSummary {
        PlaylistSummary {
            name: name.to_owned(),
            total_length,
            file_size: 0,
            interleaved_file_size: 0,
            chapter_count: 0,
            stream_count: 0,
            angle_count: 0,
            has_loops: false,
            streams: Vec::new(),
            clips,
            chapters: Vec::new(),
        }
    }
}

/// 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,
}

/// 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 eight flags are independent disc properties (3D/50Hz/UHD/AACS/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,
    /// AACS-encrypted stream content — the disc root carries the
    /// `AACS/Unit_Key_RO.inf` key file AND the sampled stream heads show the
    /// AACS encryption fingerprint (see [`detect_aacs_encryption`]). State
    /// only: the report never mentions it, and the measured scan still runs if
    /// a caller asks — whether to scan ciphertext is the caller's policy.
    pub is_aacs_encrypted: 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 the [`ScanObservers`] an open carries, 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 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. Which pass is the reported one follows the
    /// [`ScanMode`]: under [`Full`](ScanMode::Full) it is the whole-file
    /// measurement pass, and the quick codec-init pass ahead of it is neither
    /// budgeted nor reported; under [`Codecs`](ScanMode::Codecs), which has no
    /// measurement pass, the quick pass itself reports. The quick pass reads
    /// only as far into each file as its codec detail needs, so under `Codecs`
    /// the count advances by the bytes actually read and then snaps up to the
    /// file's budgeted source size as that file finishes — the same
    /// per-file-boundary snap a short or failed full-pass read gets. Either
    /// way a completed scan ends at `total`.
    pub total: u64,
}

/// Everything one scan reports to and takes its orders from: where the
/// progress goes, what watches the measured tallies build up, and the flag
/// that stops it.
///
/// The bundle every open takes ([`BdRom::open`], [`BdRom::open_resilient`],
/// [`crate::scan::open_folder`], [`crate::scan::open_iso`]) in place of a
/// widening argument list. Its contents are set only through
/// [`none`](Self::none) or [`new`](Self::new) and the builder methods —
/// `ScanObservers::none()` for a caller that watches nothing,
/// `ScanObservers::new(&mut progress, &cancel)` then
/// `.with_measured(&mut watch)` for one that wants the live tallies too — so a
/// scan facility added later is another builder method rather than a break at
/// every call site.
pub struct ScanObservers<'a> {
    /// Where each [`ScanProgress`] observation goes; `None` discards them.
    progress: Option<&'a mut dyn FnMut(ScanProgress<'_>)>,
    /// The measured-tally observer, when the caller installed one.
    measured: Option<&'a mut dyn FnMut(MeasuredSnapshot)>,
    /// The cooperative cancel flag the packet scan polls; `None` is a scan
    /// that cannot be cancelled.
    cancel: Option<&'a AtomicBool>,
}

impl<'a> ScanObservers<'a> {
    /// The observers of a scan nobody watches: progress is discarded, no
    /// measured tallies are snapshotted, and the scan runs to completion —
    /// nothing can set a flag it does not carry, so [`BdError::ScanCancelled`]
    /// is unreachable through this bundle.
    ///
    /// No [`MeasuredSnapshot`] is built at all (the observer's absence is what
    /// makes an unobserved scan cost nothing there); the progress reports are
    /// still made, into a callback that discards them.
    #[must_use]
    pub const fn none() -> Self {
        Self { progress: None, measured: None, cancel: None }
    }

    /// The observers of a scan that reports to `progress` and stops when
    /// `cancel` is set, watching no measured tallies.
    #[must_use]
    pub fn new(progress: &'a mut dyn FnMut(ScanProgress<'_>), cancel: &'a AtomicBool) -> Self {
        Self { progress: Some(progress), measured: None, cancel: Some(cancel) }
    }

    /// The same observers with `measured` watching the tallies build up: it is
    /// handed an owned [`MeasuredSnapshot`] after each read chunk the
    /// measurement pass demuxes and as each of its stream files finishes — the
    /// file-boundary snapshot is the one whose per-stream rates include the
    /// demux's end-of-file flush, so it can settle rates the last chunk's
    /// snapshot reported slightly differently, while every byte tally only
    /// grows. The chunk cadence is a byte cadence (one snapshot per demux read
    /// chunk), deliberately untimed: a consumer wanting a wall-clock rate —
    /// classic `BDInfo` samples its live grids at 1 Hz — throttles these
    /// itself.
    ///
    /// Only the measurement pass ([`ScanMode::Full`]) reports here. The bounded
    /// codec pass ahead of it reads an unpredictable sliver of each file and
    /// has its tallies discarded before the measurement starts, so reporting it
    /// would hand a display numbers that then vanish; a [`ScanMode::Codecs`]
    /// open, which is that pass and nothing else, is silent for the same
    /// reason.
    #[must_use]
    pub fn with_measured(mut self, measured: &'a mut dyn FnMut(MeasuredSnapshot)) -> Self {
        self.measured = Some(measured);
        self
    }
}

// A closure has no `Debug`, so the observers print what a reader can act on:
// which observers are installed, and whether the scan has been told to stop.
// A bundle carrying no cancel flag prints `cancelled: false` — it is a scan
// nothing can stop, which is what that reads as.
impl fmt::Debug for ScanObservers<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScanObservers")
            .field("progress", &self.progress.is_some())
            .field("measured", &self.measured.is_some())
            .field("cancelled", &self.cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)))
            .finish_non_exhaustive()
    }
}

/// The live bookkeeping of one demux pass: the running byte count over that
/// pass's total, reported through the caller's callback before and after
/// every demux read and at every file boundary, plus the caller's
/// cooperative cancel flag the demux polls per read chunk and the measured
/// observer its chunk and file boundaries snapshot to. Each pass builds its
/// own; `run_measurement_scan` decides which of them the caller observes.
struct Progress<'a> {
    /// The observer of this pass: the caller's callback for the reported
    /// pass, a no-op for an unreported one and for the plain `open`s.
    callback: &'a mut dyn FnMut(ScanProgress<'_>),
    /// The caller's measured observer, installed on the measurement pass
    /// alone — `None` leaves every snapshot unbuilt, which is what makes an
    /// unobserved scan cost nothing.
    measured: Option<&'a mut dyn FnMut(MeasuredSnapshot)>,
    /// Bytes demuxed so far, kept within `0..=total`.
    done: u64,
    /// Total bytes this pass will read over the selected files (zero for an
    /// unreported pass, whose count no one sees).
    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.heartbeat(file);
    }

    /// Reports the current count against `file` without advancing it — the
    /// pre-read heartbeat, and the single emission point the two counter
    /// updates end in. [`CountingReader`] fires it before every physical
    /// read, so a consumer watching for staleness knows a read is in flight
    /// (and in which file) rather than seeing plain silence: on damaged media
    /// one blocking read can stall for minutes, and the heartbeat is the last
    /// event before that gap opens.
    fn heartbeat(&mut self, file: &str) {
        (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.heartbeat(file);
    }

    /// Hands the measured observer an owned snapshot of what `playlists` hold
    /// after demuxing `file`, and does nothing at all when no observer is
    /// installed — the snapshot is built inside the check, so an unobserved
    /// scan never walks the playlists for one.
    fn emit_measured(&mut self, file: &str, playlists: &[TsPlaylistFile]) {
        if let Some(observer) = self.measured.as_deref_mut() {
            observer(measured::snapshot(file, playlists));
        }
    }
}

/// 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> {
        self.progress.heartbeat(&self.name);
        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 demux pass will read: per selected stream
/// file, its interleaved `*.ssif` source when one exists, else the file
/// itself, each counted once. The same budget serves either reported pass —
/// the full pass reads every one of those bytes, so its display runs 0→100%
/// at a steady pace, while the quick pass (the reported one in
/// [`ScanMode::Codecs`]) reads only each file's head and reaches 100% in
/// per-file jumps as [`Progress::finish_file`] snaps the count to each
/// finished file's share.
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,
    /// Whether the clip's interleaved 3D `*.ssif` exists on the disc.
    interleaved_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)
    }
}

/// Behavior switches for one disc open, orthogonal to how deep [`ScanMode`]
/// reads.
///
/// `#[non_exhaustive]`, so literal construction is crate-internal: start from
/// [`default`](Self::default) and reassign the fields to change on a `mut`
/// binding.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScanOptions {
    /// Whether a resilient scan keeps what the packet scan measured of a
    /// stream file whose read failed partway (`true` by default).
    ///
    /// A kept partial file holds everything the demux accumulated up to the
    /// failing read — registered streams, codec detail, per-stream tallies,
    /// per-frame diagnostics, demuxed seconds — and fills the same summary and
    /// report cells a completed file would, so chapter rows and stream
    /// diagnostics cover the span before the failure and stay zero after it.
    /// The failure is recorded as a [`ScanError`] either way; `false` also
    /// discards the partial state, leaving the affected rows all zero while
    /// the in-place playlist tallies the demux already flushed still count
    /// (partial sizes and bitrates next to empty chapter rows). A strict
    /// ([`BdRom::open`]) scan aborts on the first error regardless, and a
    /// stream file that fails to open has no demux state to keep.
    pub keep_partial: bool,
    /// Whether a [`ScanMode::Full`] scan skips the bounded quick codec pass
    /// and runs the measurement pass alone (`false` by default).
    ///
    /// For a caller whose earlier [`ScanMode::Codecs`] open already read the
    /// codec detail, the quick pass only re-reads the same file heads — on
    /// damaged media each such read can stall for minutes. Skipped, the scan
    /// resolves each playlist's presented streams from the clip info alone
    /// and back-fills the scanned codec detail from the measurement pass as
    /// it demuxes, so the disc summaries come out as a two-pass scan's would
    /// — with one divergence: a stream file the measurement pass failed on
    /// and dropped ([`keep_partial`](Self::keep_partial) off) has no quick
    /// detail to fall back to, so its streams keep clip-info detail only.
    /// Ignored by [`ScanMode::Codecs`], whose whole scan *is* the quick pass.
    pub skip_quick_pass: bool,
    /// A prior open's AACS-encryption verdict to reuse as
    /// [`BdRom::is_aacs_encrypted`], skipping this open's stream head probe;
    /// `None` (the default) probes.
    ///
    /// The probe opens and samples the heads of the two largest `*.m2ts`
    /// files, so a caller opening the same disc repeatedly (a listing open
    /// followed by a measured one) re-pays it on every open — on damaged
    /// media each probe read can stall for minutes. The reused verdict must
    /// come from a probe of the same disc: it is recorded verbatim, not
    /// verified.
    pub aacs_encrypted: Option<bool>,
}

impl Default for ScanOptions {
    /// Partial stream scans are kept, the quick pass runs, and the AACS
    /// probe decides the encryption verdict; see
    /// [`keep_partial`](Self::keep_partial),
    /// [`skip_quick_pass`](Self::skip_quick_pass) and
    /// [`aacs_encrypted`](Self::aacs_encrypted).
    fn default() -> Self {
        Self { keep_partial: true, skip_quick_pass: false, aacs_encrypted: None }
    }
}

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.
    ///
    /// `options` — the [`ScanOptions`] behavior switches.
    /// [`keep_partial`](ScanOptions::keep_partial) matters only to
    /// [`open_resilient`](Self::open_resilient); this strict open aborts on the
    /// first failure regardless.
    ///
    /// `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.
    ///
    /// `observers` — where the scan reports and what stops it
    /// ([`ScanObservers`]); [`ScanObservers::none`] for a caller watching
    /// nothing. Its progress callback is called before each stream file's
    /// source is opened (so a blocking open on damaged media is already
    /// attributed to the file being opened), before and after every demux read
    /// of the reported pass, and at every file boundary with the running
    /// [`ScanProgress`], whose [`total`](ScanProgress::total) documents which
    /// pass each mode reports; it never fires without the packet scan. Its
    /// cancel flag is cooperative: 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
    /// - [`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.
    /// - [`BdError::ScanCancelled`] when the observers' cancel flag was set mid-scan.
    pub fn open(
        root: &dyn BdDir,
        mode: ScanMode,
        options: ScanOptions,
        scan_files: Option<&BTreeSet<String>>,
        observers: ScanObservers<'_>,
    ) -> Result<Self, BdError> {
        Self::open_impl(root, mode, options, scan_files, observers, &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`] — except a stream
    /// file whose packet scan failed partway, which keeps its partial demux state
    /// by default ([`ScanOptions::keep_partial`], which takes effect here and
    /// nowhere else). On healthy media the result is identical to
    /// [`open`](Self::open) with an empty error list.
    ///
    /// `root`, `mode`, `scan_files` and `observers` are [`open`](Self::open)'s,
    /// passed through unchanged.
    ///
    /// # 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) — plus
    /// [`BdError::ScanCancelled`] when the observers' cancel flag was set
    /// mid-scan, since resilience collects disc damage, not the caller's abort:
    /// a cancelled scan returns that error, never a partial [`ScanReport`] and
    /// never a recorded per-file failure.
    pub fn open_resilient(
        root: &dyn BdDir,
        mode: ScanMode,
        options: ScanOptions,
        scan_files: Option<&BTreeSet<String>>,
        observers: ScanObservers<'_>,
    ) -> Result<ScanReport, BdError> {
        let mut errors = Vec::new();
        let bdrom = Self::open_impl(
            root,
            mode,
            options,
            scan_files,
            observers,
            &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,
        options: ScanOptions,
        scan_files: Option<&BTreeSet<String>>,
        observers: ScanObservers<'_>,
        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)?;
        // Deliberately outside the sink: the verdict is disc state, not disc
        // damage — a failed probe is a "not encrypted" verdict, never an error.
        // A caller-supplied verdict (`ScanOptions::aacs_encrypted`) replaces
        // the probe wholesale, sparing its head reads of the two largest
        // stream files.
        let is_aacs_encrypted = options
            .aacs_encrypted
            .unwrap_or_else(|| detect_aacs_encryption(root, stream.as_deref()));
        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(),
                options,
                observers,
                sink,
            )?
        } else {
            (BTreeMap::new(), BTreeMap::new())
        };
        let detail = scanned_detail(mode, options, &scanned, &measured);

        // --- 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,
                detail,
                &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_aacs_encrypted,
            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()
    }

    /// The stream files this scan measured materially less of than the disc
    /// declares — a truncated or unreadably short `*.m2ts`, whose reads end in
    /// a clean end of file and which is therefore recorded nowhere else (see
    /// [`shortfall::short_stream_files`] for the thresholds and the shortfall
    /// each entry carries).
    ///
    /// Derived from the per-clip summaries on every call, over whatever this
    /// [`BdRom`] holds, and read through [`ClipSummary::measured`]: empty after
    /// an open that measured nothing
    /// ([`ScanMode::Metadata`]/[`ScanMode::Codecs`]), and silent about the
    /// files a `scan_files` selection left out. A 0-byte or header-destroyed
    /// file that registers no stream at all IS named — it was measured, and
    /// what it measured is nothing.
    ///
    /// A stream file whose read FAILED partway is named here too when its
    /// partial state was kept ([`ScanOptions::keep_partial`]) — its measured
    /// span is genuinely short. That file is also a [`ScanError`] of the
    /// resilient scan, and this type carries no error list, so a surface
    /// showing both pairs them by file name. With the partial state dropped the
    /// file is silent here and the [`ScanError`] is its only record.
    #[must_use]
    pub fn short_stream_files(&self) -> Vec<ShortStreamFile> {
        shortfall::short_stream_files(&self.playlists)
    }
}

/// 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: `BDMV/BACKUP/index.bdmv` answers whenever the primary cannot — both
/// when the primary *read* fails and when it succeeds but yields an index
/// lacking the `INDX` magic (libbluray likewise retries the backup on a parse
/// failure, `indx_get`). Either way the primary's defect is recorded once as a
/// `ScanReport` warning, so the `WARNING` block surfaces the bad primary even
/// when the backup supplied the verdict.
///
/// An untagged index that the backup cannot replace stays *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) {
        return Ok(index::is_uhd(&bytes));
    }
    sink.record(
        ScanStage::Discovery,
        "index.bdmv",
        BdError::UnknownFileType(index::read_index_version(&bytes).unwrap_or_default()),
    );
    // The untagged bytes may themselves have come from the backup (an unreadable
    // primary recovered above); re-reading it then reaches the same untagged
    // verdict, costing one extra small read on an already doubly-damaged disc.
    // The backup needs no tag check of its own: an untagged one cannot carry the
    // UHD magic, so its verdict is the same tolerated non-UHD as no backup.
    match recover_backup(backup_index, "index.bdmv", |_, bytes| Ok(bytes.to_vec())) {
        Some(Ok(backup)) => Ok(index::is_uhd(&backup)),
        _ => Ok(false),
    }
}

/// 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)
}

/// One BDAV source packet in bytes: a 4-byte `TP_extra_header` followed by a
/// 188-byte TS packet whose first byte is the `0x47` sync (see [`super::m2ts`]).
const SOURCE_PACKET_BYTES: usize = 192;

/// One AACS Aligned Unit in bytes — 32 source packets of
/// [`SOURCE_PACKET_BYTES`]. AACS encrypts each Aligned Unit of a stream file
/// separately, leaving only its first 16 bytes cleartext (AACS Blu-ray Disc
/// Prerecorded Book 0.953 §3.10), so packet 0's sync byte survives encryption
/// and the other 31 syncs vanish into ciphertext.
const ALIGNED_UNIT_BYTES: usize = 6144;

/// How many stream files [`stream_content_encrypted`] samples. Two, the
/// largest first: every sampled unit must agree for an "encrypted" verdict,
/// and the largest files are the feature streams — never the sub-Aligned-Unit
/// menu stubs whose short read would fail the probe open.
const SAMPLED_STREAM_FILES: usize = 2;

/// How many leading Aligned Units [`file_head_encrypted`] checks per sampled
/// stream file.
const SAMPLED_UNITS_PER_FILE: usize = 2;

/// The most `0x47` bytes tolerated at the 31 ciphertext sync positions of an
/// Aligned Unit that still counts as encrypted. Ciphertext is uniform, so each
/// position matches with chance 1/256 (~0.12 expected per unit); three keeps
/// the false-"clear" chance negligible while staying far under the 31/31 a
/// clear unit shows.
const MAX_STRAY_SYNCS: usize = 3;

/// Whether the disc's stream content is AACS-encrypted (`is_aacs_encrypted`):
/// the disc root carries `AACS/Unit_Key_RO.inf` — mandatory on every encrypted
/// disc (AACS Blu-ray Disc Prerecorded Book 0.953 §3.9.3), but routinely left
/// behind by decrypting rippers, so its existence alone proves nothing — AND
/// the sampled stream heads show the encryption fingerprint
/// ([`stream_content_encrypted`]).
///
/// Fail-open by design: every failure — IO error, missing directory, short or
/// damaged stream — resolves to `false`. A false "not encrypted" costs a
/// caller one pointless scan of ciphertext; a false "encrypted" would brand a
/// readable disc unreadable. Damage therefore stays with the damaged-disc
/// machinery (the resilient sink), which this probe never touches.
fn detect_aacs_encryption(root: &dyn BdDir, stream: Option<&dyn BdDir>) -> bool {
    has_aacs_key_file(root) && stream.is_some_and(stream_content_encrypted)
}

/// Whether the disc root has an `AACS` directory holding `Unit_Key_RO.inf`,
/// both matched ASCII case-insensitively like the rest of the discovery. The
/// file's contents are never read — existence is the whole hint. Enumeration
/// failures read as "absent" (the probe's fail-open rule).
fn has_aacs_key_file(root: &dyn BdDir) -> bool {
    let Ok(dirs) = root.get_directories() else {
        return false;
    };
    dirs.iter().filter(|dir| dir.name().eq_ignore_ascii_case("AACS")).any(|dir| {
        dir.get_files().is_ok_and(|files| {
            files.iter().any(|file| file.name().eq_ignore_ascii_case("Unit_Key_RO.inf"))
        })
    })
}

/// Whether the sampled stream content confirms encryption: the
/// [`SAMPLED_STREAM_FILES`] largest `*.m2ts` files (ties broken by name, so
/// the verdict never depends on directory enumeration order) must **all** pass
/// [`file_head_encrypted`]. No stream files, an enumeration failure, or any
/// non-fingerprint sample resolves to `false` (fail-open).
fn stream_content_encrypted(stream: &dyn BdDir) -> bool {
    let Ok(mut files) = vfs::find_files(stream, BdFileKind::Stream) else {
        return false;
    };
    if files.is_empty() {
        return false;
    }
    files.sort_by(|a, b| b.length().cmp(&a.length()).then_with(|| a.name().cmp(b.name())));
    files.truncate(SAMPLED_STREAM_FILES);
    files.iter().all(|file| file_head_encrypted(&**file))
}

/// Whether `file`'s first [`SAMPLED_UNITS_PER_FILE`] Aligned Units all show
/// the encryption fingerprint. A failed open, a short read (a file under
/// 2 × [`ALIGNED_UNIT_BYTES`]), or any non-fingerprint unit reads `false`.
fn file_head_encrypted(file: &dyn BdFile) -> bool {
    let Ok(mut reader) = file.open_read() else {
        return false;
    };
    let mut unit = [0_u8; ALIGNED_UNIT_BYTES];
    for _ in 0..SAMPLED_UNITS_PER_FILE {
        if reader.read_exact(&mut unit).is_err() || !unit_shows_encryption(&unit) {
            return false;
        }
    }
    true
}

/// Whether one Aligned Unit shows the AACS encryption fingerprint: packet 0's
/// `0x47` sync byte intact (it sits inside the unit's 16 cleartext bytes) and
/// at most [`MAX_STRAY_SYNCS`] of the 31 encrypted packets' sync positions
/// matching by ciphertext chance. A clear unit shows all 32 (the container
/// guarantees them); anything else — damage, garbage, a partial wipe — is not
/// this fingerprint and reads `false`.
fn unit_shows_encryption(unit: &[u8; ALIGNED_UNIT_BYTES]) -> bool {
    let mut syncs =
        unit.chunks_exact(SOURCE_PACKET_BYTES).map(|packet| packet.get(4) == Some(&0x47));
    let first = syncs.next() == Some(true);
    let strays = syncs.filter(|&hit| hit).count();
    first && strays <= MAX_STRAY_SYNCS
}

/// 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 summaries' scanned-detail source, following the pass that read it: the
/// quick map, or — when [`ScanOptions::skip_quick_pass`] left it empty on a
/// measuring open — the measurement map, whose files carry the same detail
/// read to end of file instead of to codec initialisation.
const fn scanned_detail<'a>(
    mode: ScanMode,
    options: ScanOptions,
    scanned: &'a ScannedFiles,
    measured: &'a ScannedFiles,
) -> &'a ScannedFiles {
    if options.skip_quick_pass && mode.measures_bitrate() { measured } else { scanned }
}

/// 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.
///
/// `keep_partial` ([`ScanOptions::keep_partial`]) reaches both passes: a file
/// whose head is damaged fails the quick pass at the same spot as the full
/// one, and its partial quick state (whatever codec detail initialised before
/// the failure) is retained or dropped by the same switch.
///
/// # 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, observers, 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,
    options: ScanOptions,
    observers: ScanObservers<'_>,
    sink: &mut Sink<'_>,
) -> Result<(ScannedFiles, ScannedFiles), BdError> {
    // The caller observes the last pass this scan runs, against one budget:
    // every selected file's source once (`scan_total`). With a full pass to
    // come the quick pass stays silent — it reads an unpredictable sliver of
    // each file, so reporting it would spend part of the bar on a distance
    // the budget cannot predict, and restart the count afterwards; the full
    // pass then owns a steady 0→100%. Without one (`Codecs`) the quick pass
    // IS the scan the caller waits on, so it reports instead: its reads
    // advance the count and the per-file boundary snaps carry it over the
    // tails it never reads, up to 100% at the last file. Cancellation reaches
    // both passes either way: each carries the caller's flag in its
    // `Progress`.
    //
    // The measured observer belongs to the measurement pass alone (see
    // `ScanObservers::with_measured`): the quick pass is built without one, so
    // its file boundaries have nothing to snapshot to.
    //
    // The two passes below carry a callback and a flag, not options: keeping
    // the `None`s out of `Progress` keeps the per-chunk cancel poll and the
    // per-read report free of a branch that an unobserved scan would take on
    // every packet. A bundle carrying no flag scans under one that is never
    // set, and one carrying no callback reports into `discarded` — declared
    // ahead of the bundle it stands in for, so it outlives the `Progress`
    // that borrows it.
    static NEVER_CANCELLED: AtomicBool = AtomicBool::new(false);
    let mut discarded = |_: ScanProgress<'_>| {};
    let ScanObservers { progress, measured, cancel } = observers;
    let callback: &mut dyn FnMut(ScanProgress<'_>) = match progress {
        Some(callback) => callback,
        None => &mut discarded,
    };
    // `Progress` holds both observers under one lifetime, so the installed one
    // is reborrowed down to `callback`'s rather than pulling it back up to the
    // bundle's (which `discarded`, a local, cannot reach).
    #[expect(
        clippy::option_if_let_else,
        reason = "the `map_or`/`map` rewrite infers the closure's return at the bundle's lifetime, so the reborrow does not shorten and `discarded`, a local, cannot meet it"
    )]
    let measured: Option<&mut dyn FnMut(MeasuredSnapshot)> = match measured {
        Some(measured) => Some(&mut *measured),
        None => None,
    };
    let cancel = cancel.unwrap_or(&NEVER_CANCELLED);
    let total = scan_total(stream_files, interleaved_files, scan_files);
    // `skip_quick_pass` only ever skips a pass that would be followed by the
    // measurement pass — in `Codecs` mode the quick pass is the whole scan,
    // so the option is ignored there rather than turning the mode into
    // `Metadata`.
    let skip_quick = options.skip_quick_pass && measure;
    let quick = if skip_quick {
        BTreeMap::new()
    } else {
        let mut silent = |_: ScanProgress<'_>| {};
        let quick_progress = &mut if measure {
            Progress { callback: &mut silent, measured: None, done: 0, total: 0, cancel }
        } else {
            Progress { callback: &mut *callback, measured: None, done: 0, total, cancel }
        };
        scan_stream_files(
            stream,
            ssif,
            parsed,
            scan_files,
            quick_progress,
            sink,
            options.keep_partial,
            false,
            false,
        )?
    };
    // With the quick pass skipped, `quick` is empty and the resolution falls
    // back to the clip-info streams alone — the measurement pass then
    // back-fills the scanned detail it would have merged here (see
    // `TsStreamFile::backfill_detail`).
    for playlist in parsed.iter_mut() {
        if let Ok(metas) =
            collect_clip_metas(playlist, clip_files, stream_files, interleaved_files, &quick)
        {
            resolve_playlist_streams(playlist, &metas, skip_quick);
        }
    }
    // 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, measured, done: 0, total, cancel };
    let full = scan_stream_files(
        stream,
        ssif,
        parsed,
        scan_files,
        progress,
        sink,
        options.keep_partial,
        true,
        skip_quick,
    )?;
    // 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, interleaved_files, &full)
            && let Some(reference) = select_reference(&metas)
        {
            if skip_quick {
                remove_mvc_placeholder(playlist, reference);
            }
            if let Some(file) = reference.scanned {
                remerge_graphics_detail(playlist, &file.streams);
            }
        }
    }
    Ok((quick, full))
}

/// Removes the placeholder dependent-view stream a
/// [`ScanOptions::skip_quick_pass`] resolution synthesized
/// ([`resolve_playlist_streams`]) when the measurement pass registered no MVC
/// stream in the reference clip's demuxed file — the interleaved `*.ssif`
/// exists but carries no dependent view, so presenting the placeholder would
/// invent a stream row. An MVC PID the clip info itself declares is not a
/// placeholder and stays, as does the placeholder of a reference file the
/// pass failed on and dropped — with no demux verdict to consult, the
/// interleaved file's existence remains the best evidence.
fn remove_mvc_placeholder(playlist: &mut TsPlaylistFile, reference: &ClipMeta<'_>) {
    if let Some(file) = reference.scanned
        && !file.streams.contains_key(&MVC_PID)
        && !reference.clip_streams.contains_key(&MVC_PID)
    {
        playlist.streams.remove(&MVC_PID);
        for angle in &mut playlist.angle_streams {
            angle.remove(&MVC_PID);
        }
    }
}

/// 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>,
    interleaved_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),
            interleaved_file_present: interleaved_files.contains_key(&format!("{stem}.SSIF")),
        });
    }
    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.
///
/// With `synthesize_mvc` (a [`ScanOptions::skip_quick_pass`] scan, whose
/// `metas` carry no scanned files) a reference clip with an interleaved
/// `*.ssif` gets a placeholder dependent-view stream instead, so the
/// measurement pass has an entry to accumulate the MVC windows into from its
/// first packet; [`remove_mvc_placeholder`] removes the placeholder if that
/// pass finds no such stream.
fn resolve_playlist_streams(
    playlist: &mut TsPlaylistFile,
    metas: &[ClipMeta<'_>],
    synthesize_mvc: bool,
) {
    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 synthesize_mvc && reference.interleaved_file_present && !streams.contains_key(&MVC_PID) {
        let mut mvc = TsStream::Video(TsVideoStream::default());
        mvc.base_mut().pid = Pid::new(MVC_PID);
        mvc.base_mut().stream_type = TsStreamType::MvcVideo;
        streams.insert(MVC_PID, mvc);
    }
    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());
        }
        merge_matching(&mut streams, &file.streams, |_| true);
    }

    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>) {
    merge_matching(&mut playlist.streams, scanned, |stream| {
        matches!(stream, TsStream::Graphics(_))
    });
}

/// 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,
            // Presence in the full-pass map IS "the measurement pass demuxed
            // this file": a file that never ran, failed to open, or had its
            // partial state dropped is not in it, and one that opened and read
            // to a clean end of file is — however little it carried.
            measured: file.is_some(),
            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, interleaved_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 {
        merge_matching(&mut streams, scanned, |_| true);
    }
    // Graphics detail only exists after the full pass, which
    // [`remerge_graphics_detail`] merged into the resolved presented streams —
    // so the rows take it from there rather than from the quick merge above.
    merge_matching(&mut streams, &playlist.streams, |stream| {
        matches!(stream, TsStream::Graphics(_))
    });
    // 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);
        rows.push(stream_row(stream, 0, is_hidden, ssif_only, playlist.streams.get(pid)));
        if stream.base().is_video_stream() {
            for index in 0..angle_count {
                rows.push(stream_row(
                    stream,
                    index.saturating_add(1),
                    is_hidden,
                    ssif_only,
                    playlist.angle_streams.get(index).and_then(|angle| angle.get(pid)),
                ));
            }
        }
    }
    rows
}

/// One report row for the presented `stream`: its [`stream_summary`] fields,
/// the presentation flags (`angle_index` `0` for the main row, `1..` for an
/// angle clone), the measured bitrates copied from the playlist's resolved
/// `measured` stream when the playlist is resolved, and the full description
/// composed last — it reads the rates this row just took.
///
/// The one home for what a report row carries: a main row and an angle row of
/// the same stream differ only in the two arguments.
fn stream_row(
    stream: &TsStream,
    angle_index: usize,
    is_hidden: bool,
    ssif_only: bool,
    measured: Option<&TsStream>,
) -> StreamSummary {
    let mut row = stream_summary(stream);
    row.is_hidden = is_hidden;
    row.ssif_only = ssif_only;
    row.angle_index = angle_index;
    if let Some(measured) = measured {
        row.bitrate = measured.base().bit_rate;
        row.active_bitrate = measured.base().active_bit_rate;
    }
    row.full_description = full_description(stream, &row);
    row
}

/// 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 codec detail of a demuxed clip's `streams` into
/// `playlist`'s presented-stream maps, main and angle alike (a PID a map does
/// not carry is skipped) — the [`ScanOptions::skip_quick_pass`] stand-in for
/// the quick-scanned detail [`resolve_playlist_streams`] merges ahead of a
/// two-pass scan. The demux calls this after every parsed chunk of such a
/// measurement pass ([`TsStreamFile::backfill_detail`]), because two of its
/// own reads during the pass come from these maps and start empty without
/// the quick merge: `is_vbr`, which gates the per-window variable-bitrate
/// recomputation, and a `TrueHD` stream's embedded core, whose nominal rate
/// discounts the active rate. Repetition is what keeps the final values
/// right: the chunk that initialises a codec back-fills it before the next
/// window recomputes, and the end-of-file flush recomputes every rate after
/// the last chunk's merge.
pub(crate) fn backfill_playlist_detail(
    playlist: &mut TsPlaylistFile,
    streams: &BTreeMap<u16, TsStream>,
) {
    merge_matching(&mut playlist.streams, streams, |_| true);
    for angle in &mut playlist.angle_streams {
        merge_matching(angle, streams, |_| true);
    }
}

/// Merges every `src` stream `keep` selects into the `dst` stream of the same
/// PID (a PID `dst` does not carry is skipped) — the walk both scan passes and
/// the summary pass share.
///
/// `keep` reads the source stream; because [`merge_stream`] is a no-op on a
/// type mismatch, filtering by stream kind selects the same pairs whichever
/// side it reads.
fn merge_matching(
    dst: &mut BTreeMap<u16, TsStream>,
    src: &BTreeMap<u16, TsStream>,
    keep: fn(&TsStream) -> bool,
) {
    for (pid, stream) in src {
        if !keep(stream) {
            continue;
        }
        if let Some(dst) = dst.get_mut(pid) {
            merge_stream(dst, stream);
        }
    }
}

/// 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 description = stream.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: stream.codec_short_name().to_owned(),
        codec_name: stream.codec_name().to_owned(),
        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 —
/// unless that file will not open, which in resilient mode falls back to the
/// plain `*.m2ts` (see [`scan_one_stream_file`]).
/// `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 a file that failed
/// mid-demux keeps its partial state in the returned map when `keep_partial`
/// is set — otherwise (and always on a failed open) the file is skipped, its
/// playlists falling 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 — and which therefore
/// reports neither the boundary of the file it stopped in nor a snapshot of
/// it.
///
/// Every other completed file boundary reports twice: the progress snap, then
/// the [`MeasuredSnapshot`] of the playlists that play the file, when the
/// caller installed an observer for them. Each file also reports one
/// heartbeat under its own name *before* its source is opened, so an open
/// that blocks on damaged media is already attributed to the file being
/// opened rather than to the previously finished one.
///
/// `backfill_detail` marks each scanned file's demux to merge its scanned
/// codec detail into the playlists as it goes (see
/// [`TsStreamFile::backfill_detail`]) — the
/// [`ScanOptions::skip_quick_pass`] measurement pass, which has no
/// quick-merged detail to build on.
#[expect(
    clippy::too_many_arguments,
    reason = "the scan orchestration threads the per-open context (dirs, maps, selection, progress, sink) one level down"
)]
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<'_>,
    keep_partial: bool,
    is_full_scan: bool,
    backfill_detail: 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);
        // Polled here as well as per read chunk, so a cancel now aborts
        // before this file's open (not one blocking read later) and so the
        // heartbeat below never reports on a pass that is already cancelled —
        // a pre-cancelled scan emits no progress at all.
        if progress.cancel.load(Ordering::Relaxed) {
            return Err(BdError::ScanCancelled);
        }
        // Attribute the window between the previous file's boundary and this
        // file's first counted read — which contains the source open, itself
        // able to block for minutes on damaged media — to this file, before
        // the open. A heartbeat reports the count without advancing it.
        progress.heartbeat(&name);
        let scan = scan_one_stream_file(
            &*file,
            interleaved,
            playlists,
            is_full_scan,
            backfill_detail,
            progress,
            sink,
        );
        // 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);
        // The file's tallies are final and its playlists are no longer
        // borrowed by the demux, so this snapshot — unlike the per-chunk ones
        // the demux emitted while reading — includes the demux's end-of-file
        // flush in its per-stream rates; it fires once per stream file, after
        // the boundary progress event it belongs to. A file that failed
        // partway is snapshotted too — the demux wrote its windows into the
        // playlists as it read them, and dropping the partial file does not
        // take them back.
        progress.emit_measured(&name, playlists);
        // This one absorb call is the whole keep/drop policy: strict mode
        // propagates the failure (partial state and all), resilient mode
        // records it and yields the fallback — the partial file itself under
        // `keep_partial`, nothing otherwise. A failed open carries no demux
        // state, so its fallback is always empty.
        let (fallback, demuxed) = match scan {
            Ok(StreamScan::Complete(stream_file)) => (None, Ok(Some(stream_file))),
            Ok(StreamScan::Partial(stream_file, reason)) => {
                (keep_partial.then_some(stream_file), Err(reason))
            }
            Err(reason) => (None, Err(reason)),
        };
        if let Some(stream_file) =
            sink.absorb(ScanStage::StreamFile, file.name(), fallback, demuxed)?
        {
            scanned.insert(name, stream_file);
        }
    }
    Ok(scanned)
}

/// One stream file's demux outcome, distinguishing a run to EOF from a
/// mid-demux failure whose measured-so-far state is still worth handing back.
enum StreamScan {
    /// The demux read the whole pass's bytes; the file carries its complete
    /// scan outputs.
    Complete(TsStreamFile),
    /// The demux failed partway; the file carries everything accumulated up
    /// to the failing read — registered streams, codec detail, per-stream
    /// tallies, per-frame diagnostics, demuxed seconds — alongside the error.
    /// The caller decides whether to keep or drop the partial state
    /// ([`ScanOptions::keep_partial`]).
    Partial(TsStreamFile, BdError),
}

/// 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`].
///
/// A demux failure returns [`StreamScan::Partial`] rather than `Err`; plain
/// `Err` is reserved for the two no-demux-state cases — the source would not
/// open, or the caller cancelled ([`BdError::ScanCancelled`], whose partial
/// state is deliberately never offered: cancellation is an abort, not damage).
///
/// An interleaved source that will not open is recovered from rather than
/// failed on, in resilient mode: the clip is scanned from its plain `*.m2ts`
/// instead and the `*.ssif` failure recorded through `sink` — see
/// `DIFFERENCES.md`.
fn scan_one_stream_file(
    file: &dyn BdFile,
    interleaved: Option<Box<dyn BdFile>>,
    playlists: &mut [TsPlaylistFile],
    is_full_scan: bool,
    backfill_detail: bool,
    progress: &mut Progress<'_>,
    sink: &mut Sink<'_>,
) -> Result<StreamScan, BdError> {
    let mut stream_file = TsStreamFile::new(file.name());
    stream_file.backfill_detail = backfill_detail;
    // The `*.ssif` handle's name as the disc spells it, read before the handle
    // is wrapped (which upper-cases it), so the failure below is recorded in
    // the same casing as every other name this scan records.
    let interleaved_name = interleaved.as_ref().map_or_else(String::new, |s| s.name().to_owned());
    stream_file.interleaved_file = interleaved.map(TsInterleavedFile::new);
    // The interleaved 3D `*.ssif` is the demux source in preference to the plain
    // `*.m2ts` whenever the clip has one: its base/dependent extents are just more
    // source packets, and without reading it the dependent-view (MVC) streams
    // never register. The selected reader is wrapped so each read advances the
    // progress.
    let inner = match stream_file.interleaved_file.take() {
        Some(interleaved) => match interleaved.open_read() {
            Ok(reader) => {
                stream_file.interleaved_file = Some(interleaved);
                reader
            }
            // The `*.ssif` is the superset source, not the only one: the base
            // view is also in the plain `*.m2ts`, so a clip whose interleaved
            // file will not open is measured in 2D rather than lost — only the
            // dependent view is unreachable. `interleaved_file` stays taken,
            // so the clip reports the source it was read from. Strict mode has
            // no such policy: `absorb` propagates the failure there, exactly as
            // an unopenable `*.m2ts` does.
            Err(reason) => {
                sink.absorb(
                    ScanStage::StreamFile,
                    &interleaved_name,
                    (),
                    Err(BdError::Io(reason)),
                )?;
                file.open_read()?
            }
        },
        None => file.open_read()?,
    };
    // The shared reference and the measured observer are moved out before the
    // reader mutably borrows the progress, so the demux can poll the flag and
    // report chunk-boundary snapshots alongside the counting reads; the
    // observer is restored below for the file-boundary snapshot.
    let cancel = progress.cancel;
    let mut measured = progress.measured.take();
    let mut reader =
        CountingReader { inner, name: file.name().to_ascii_uppercase(), progress: &mut *progress };
    let scan = stream_file.scan_cancellable(
        &mut reader,
        playlists,
        is_full_scan,
        cancel,
        measured.as_deref_mut(),
    );
    progress.measured = measured;
    // The scan's public outputs — complete or partial — are now captured; free
    // the demux scratch (its per-PID PES buffers) before the file is handed
    // back, so a multi-clip disc holds only the in-flight clip's buffers, not
    // every scanned clip's at once. Pure reclaim — see
    // `TsStreamFile::release_scratch`.
    stream_file.release_scratch();
    match scan {
        Ok(()) => Ok(StreamScan::Complete(stream_file)),
        Err(BdError::ScanCancelled) => Err(BdError::ScanCancelled),
        Err(reason) => Ok(StreamScan::Partial(stream_file, reason)),
    }
}

/// 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)))
}

/// The most bytes [`read_file`] buffers for one metadata file.
///
/// The largest `*.mpls`/`*.clpi` an authored disc carries is well under a
/// megabyte, so this never bites real media. It exists because a file's
/// *declared* size is attacker-controlled and need not be backed by stored
/// bytes at all: a UDF File Entry can claim an arbitrary `InformationLength`
/// over not-recorded extents, which `vfs::udf` serves as zeros without reading
/// the image. Without a cap a few-hundred-KB `.iso` can drive an unbounded
/// allocation. `vfs::udf`'s own `max_dir_bytes` bounds the directory side of
/// exactly this hazard, and matches this value.
const MAX_METADATA_BYTES: u64 = 64 << 20;

/// Reads a VFS file fully into a byte vector, mapping IO errors to [`BdError::Io`].
///
/// Capped at [`MAX_METADATA_BYTES`]; see [`read_file_capped`].
fn read_file(file: &dyn BdFile) -> Result<Vec<u8>, BdError> {
    read_file_capped(file, MAX_METADATA_BYTES)
}

/// Reads a VFS file fully into a byte vector, refusing to buffer more than
/// `cap` bytes.
///
/// The cap is a parameter only so the boundary cases can be tested against a
/// handful of bytes instead of materializing [`MAX_METADATA_BYTES`]; production
/// always goes through [`read_file`].
///
/// Reads one byte past `cap`, because that overshoot is what separates a file
/// sitting exactly on the cap from one running past it — [`std::io::Take::limit`]
/// reaching zero means the latter. Truncating instead would hand a silently
/// clipped buffer to a parser, which would then report a misleading
/// [`BdError::UnexpectedEof`].
fn read_file_capped(file: &dyn BdFile, cap: u64) -> Result<Vec<u8>, BdError> {
    let mut reader = file.open_read()?.take(cap.saturating_add(1));
    let mut bytes = Vec::new();
    reader.read_to_end(&mut bytes)?;
    if reader.limit() == 0 {
        return Err(BdError::MetadataTooLarge { file: file.name().to_owned(), limit: cap });
    }
    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::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

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

    use super::{
        ALIGNED_UNIT_BYTES, BdError, BdRom, ClipMeta, ClipSummary, CountingReader,
        MAX_METADATA_BYTES, MVC_PID, MeasuredSnapshot, PlaylistFilter, PlaylistSummary, Progress,
        SOURCE_PACKET_BYTES, ScanMode, ScanObservers, ScanOptions, ScanProgress, ScanReport,
        ScanStage, Sink, TsPlaylistFile, TsStreamFile, backfill_playlist_detail,
        backup_subdir_files, build_chapter_summaries, build_clip_summaries, build_sorted_streams,
        clear_measurements, clip_has_50hz_video, clip_stem, collect_backups, directory_size,
        fixtures, has_aacs_key_file, merge_stream, rate_over, read_disc_title, read_file,
        read_file_capped, remove_mvc_placeholder, resolve_playlist_streams, scan_stream_files,
        scan_total, select_reference, stream_content_encrypted, stream_summary,
        unit_shows_encryption, walked_disc_root,
    };
    use crate::bdrom::clpi::TsStreamClip;
    use crate::bdrom::clpi::clips::build_clpi;
    use crate::bdrom::interleaved::{MemBdFile, TsInterleavedFile};
    use crate::bdrom::m2ts::packets::{packet, pat_payload, pes_dts, pes_pts, pmt_payload};
    use crate::bdrom::mpls::playlists::{build_item_codec, build_mpls, chapter_entry, pl_stream};
    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, extension_of_name};

    /// [`BdRom::open`] over the whole disc, with no observers and the default
    /// options — the shape most tests here want, spelled once.
    fn open(root: &dyn BdDir, mode: ScanMode) -> Result<BdRom, BdError> {
        BdRom::open(root, mode, ScanOptions::default(), None, ScanObservers::none())
    }

    /// [`open`]'s resilient twin.
    fn open_resilient(root: &dyn BdDir, mode: ScanMode) -> Result<ScanReport, BdError> {
        BdRom::open_resilient(root, mode, ScanOptions::default(), None, ScanObservers::none())
    }

    // ── synthetic metadata builders (minimal valid `*.clpi` / `*.mpls`) ──────
    //
    // Convenience wrappers only: the on-disc byte layouts live once, in the
    // parsers' own `clpi::clips` and `mpls::playlists` builders.

    /// 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> {
        build_clpi(*b"HDMV0300", entries)
    }

    /// 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` with `angle_names` extra camera angles and 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> {
        // Each declared PID becomes one AC3 5.1 / 48 kHz English entry, so the
        // counts array names audio alone.
        let mut stream_bytes = Vec::new();
        for &pid in declared_audio {
            stream_bytes.extend(pl_stream(1, pid, 0x81, [0x61, b'e', b'n', b'g']));
        }
        let counts = [0, u8::try_from(declared_audio.len()).unwrap(), 0, 0, 0, 0, 0];
        // An empty angle list is a single-angle item, not a multi-angle one with
        // no extra angles — the two differ in the item's multiangle flag.
        let angles = (!angle_names.is_empty()).then_some(angle_names);
        let items: Vec<Vec<u8>> = item_names
            .iter()
            .map(|name| build_item_codec(name, codec, in_t, out_t, angles, counts, &stream_bytes))
            .collect();
        let marks: Vec<Vec<u8>> = chapters
            .iter()
            .map(|&(chapter_type, file_index, tick)| chapter_entry(chapter_type, file_index, tick))
            .collect();
        build_mpls(0, &items, &marks)
    }

    /// A valid `*.mpls` with zero play items — its `stream_clips` are empty, so
    /// the reference-clip selection finds nothing.
    fn empty_mpls() -> Vec<u8> {
        build_mpls(0, &[], &[])
    }

    /// `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()));
            // The name repeats across runs — the operating system reuses process
            // ids — and a run killed before `Drop` leaves its directory behind, so
            // clear any leftover first. `create_dir_all` would adopt it silently,
            // and a disc built to lack a directory would then be handed the files
            // of whichever test held this name last.
            let _ = std::fs::remove_dir_all(&root).is_ok();
            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> {
            open(&FsDir::new(self.root.clone()), ScanMode::Metadata)
        }

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

        fn open_codecs(&self) -> Result<BdRom, BdError> {
            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,
            interleaved_file_present: false,
        }
    }

    #[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);
        // Detail a whole-map merge WOULD copy, so the graphics filter has teeth.
        scanned_video.encoding_profile = Some("High Profile 4.1".to_owned());
        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 = as_video(playlist.streams.get(&0x1011).unwrap()).unwrap();
        assert!(video.encoding_profile.is_none(), "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_aacs_encrypted); // no AACS/Unit_Key_RO.inf
        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.is_aacs_encrypted); // no AACS/Unit_Key_RO.inf
        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);
    }

    // ── AACS encryption detection ───────────────────────────────────────────

    /// One Aligned Unit: `0x47` at the sync positions `present` selects
    /// (packet 0 first), `0xAA` everywhere else.
    fn unit_with_syncs(present: &[bool; 32]) -> [u8; ALIGNED_UNIT_BYTES] {
        let mut unit = [0xAA_u8; ALIGNED_UNIT_BYTES];
        for (packet, &sync) in unit.chunks_exact_mut(SOURCE_PACKET_BYTES).zip(present) {
            if sync && let Some(byte) = packet.get_mut(4) {
                *byte = 0x47;
            }
        }
        unit
    }

    /// One Aligned Unit with the exact encryption fingerprint: packet 0's sync
    /// intact, the other 31 sync positions ciphertext (no chance matches).
    fn encrypted_unit() -> [u8; ALIGNED_UNIT_BYTES] {
        let mut present = [false; 32];
        present[0] = true;
        unit_with_syncs(&present)
    }

    /// The first two Aligned Units of an AACS-encrypted stream file.
    fn encrypted_stream() -> Vec<u8> {
        [encrypted_unit().as_slice(), encrypted_unit().as_slice()].concat()
    }

    /// Two clear Aligned Units: all 32 sync bytes in place in each.
    fn clear_stream() -> Vec<u8> {
        let unit = unit_with_syncs(&[true; 32]);
        [unit.as_slice(), unit.as_slice()].concat()
    }

    #[test]
    fn the_unit_fingerprint_needs_the_first_sync_and_tolerates_only_stray_ones() {
        let mut present = [false; 32];
        present[0] = true;
        // The exact fingerprint, and up to MAX_STRAY_SYNCS chance matches.
        assert!(unit_shows_encryption(&unit_with_syncs(&present)));
        present[7] = true;
        present[15] = true;
        present[31] = true;
        assert!(unit_shows_encryption(&unit_with_syncs(&present)));
        // One stray past the tolerance is no longer the fingerprint.
        present[20] = true;
        assert!(!unit_shows_encryption(&unit_with_syncs(&present)));
        // Without packet 0's sync nothing reads encrypted, however few strays.
        present[0] = false;
        assert!(!unit_shows_encryption(&unit_with_syncs(&present)));
        assert!(!unit_shows_encryption(&unit_with_syncs(&[false; 32])));
        // A clear unit shows all 32 syncs — the container guarantee.
        assert!(!unit_shows_encryption(&unit_with_syncs(&[true; 32])));
    }

    #[test]
    fn an_encrypted_disc_sets_the_aacs_flag_without_a_scan_error() {
        let disc = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[
                ("AACS/Unit_Key_RO.inf", Vec::new()),
                ("BDMV/STREAM/00000.m2ts", encrypted_stream()),
                ("BDMV/STREAM/00001.m2ts", encrypted_stream()),
            ],
        );
        assert!(disc.open().expect("scan encrypted disc").is_aacs_encrypted);
        // State only: the resilient sink records nothing for the verdict.
        let report = open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata)
            .expect("resilient scan");
        assert!(report.bdrom.is_aacs_encrypted);
        assert!(report.errors.is_empty());
    }

    #[test]
    fn the_aacs_marker_matches_case_insensitively_and_one_stream_file_suffices() {
        let disc = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[("aacs/UNIT_KEY_RO.INF", Vec::new()), ("BDMV/STREAM/00000.m2ts", encrypted_stream())],
        );
        assert!(disc.open().expect("scan encrypted disc").is_aacs_encrypted);
    }

    #[test]
    fn a_decrypted_rip_keeping_the_aacs_folder_is_not_encrypted() {
        // The feature's safety proof: the key file plus clear streams is a
        // decrypted rip, and it must scan exactly like any clear disc.
        let disc = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[
                ("AACS/Unit_Key_RO.inf", Vec::new()),
                ("BDMV/STREAM/00000.m2ts", clear_stream()),
                ("BDMV/STREAM/00001.m2ts", clear_stream()),
            ],
        );
        assert!(!disc.open().expect("scan decrypted rip").is_aacs_encrypted);
    }

    #[test]
    fn encrypted_looking_streams_without_the_key_file_stay_unflagged() {
        // No AACS directory at all…
        let bare = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[("BDMV/STREAM/00000.m2ts", encrypted_stream())],
        );
        assert!(!bare.open().expect("scan").is_aacs_encrypted);
        // …and an AACS directory without Unit_Key_RO.inf.
        let keyless = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[("AACS/Content000.cer", vec![b'x']), ("BDMV/STREAM/00000.m2ts", encrypted_stream())],
        );
        assert!(!keyless.open().expect("scan").is_aacs_encrypted);
    }

    #[test]
    fn a_keyed_disc_without_confirmable_stream_content_is_not_encrypted() {
        // No STREAM directory…
        let streamless = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[("AACS/Unit_Key_RO.inf", Vec::new())],
        );
        assert!(!streamless.open().expect("scan").is_aacs_encrypted);
        // …an empty STREAM directory (the all-of-nothing guard)…
        let empty = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF", "BDMV/STREAM"],
            &[("AACS/Unit_Key_RO.inf", Vec::new())],
        );
        assert!(!empty.open().expect("scan").is_aacs_encrypted);
        // …and a stream file too short for two Aligned Units.
        let short = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[
                ("AACS/Unit_Key_RO.inf", Vec::new()),
                ("BDMV/STREAM/00000.m2ts", encrypted_unit().to_vec()),
            ],
        );
        assert!(!short.open().expect("scan").is_aacs_encrypted);
    }

    #[test]
    fn any_clear_sample_resolves_to_not_encrypted() {
        // One encrypted and one clear stream file: mixed content is damage or
        // a partial rip, never the fingerprint.
        let mixed = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[
                ("AACS/Unit_Key_RO.inf", Vec::new()),
                ("BDMV/STREAM/00000.m2ts", encrypted_stream()),
                ("BDMV/STREAM/00001.m2ts", clear_stream()),
            ],
        );
        assert!(!mixed.open().expect("scan").is_aacs_encrypted);
        // A file whose second Aligned Unit is clear: every sampled unit must
        // agree, not just the first.
        let clear_tail = [encrypted_unit(), unit_with_syncs(&[true; 32])].concat();
        let tailed = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[("AACS/Unit_Key_RO.inf", Vec::new()), ("BDMV/STREAM/00000.m2ts", clear_tail)],
        );
        assert!(!tailed.open().expect("scan").is_aacs_encrypted);
    }

    #[test]
    fn the_probe_samples_the_two_largest_stream_files() {
        // Two feature-sized encrypted files plus a tiny menu stub: the stub is
        // never sampled, so its short read cannot fail the verdict open.
        let disc = TempDisc::build(
            &["BDMV/PLAYLIST", "BDMV/CLIPINF"],
            &[
                ("AACS/Unit_Key_RO.inf", Vec::new()),
                ("BDMV/STREAM/00000.m2ts", encrypted_stream()),
                ("BDMV/STREAM/00001.m2ts", encrypted_stream()),
                ("BDMV/STREAM/00002.m2ts", vec![0_u8; 100]),
            ],
        );
        assert!(disc.open().expect("scan").is_aacs_encrypted);
    }

    #[test]
    fn equal_sized_samples_are_chosen_by_name_not_listing_order() {
        let trip = Trip::new(usize::MAX);
        let mk = |name: &str, bytes: Vec<u8>| MockFile {
            name: name.to_owned(),
            extension: ".m2ts".to_owned(),
            bytes,
            trip: trip.clone(),
            fail_read_at: None,
            reads: None,
        };
        let four_units = [encrypted_stream(), encrypted_stream()].concat();
        // Listed out of name order: the sample must be the largest file plus —
        // by the name tie-break, not listing position — the *clear* 00001, so
        // the verdict is `false`; sampling by listing order would take the two
        // encrypted files and read `true`.
        let stream = MockDir {
            name: "STREAM".to_owned(),
            dirs: Vec::new(),
            files: vec![
                mk("00000.m2ts", four_units.clone()),
                mk("00002.m2ts", encrypted_stream()),
                mk("00001.m2ts", clear_stream()),
            ],
            trip: trip.clone(),
        };
        assert!(!stream_content_encrypted(&stream));
        // Largest-first, deterministically: with the sizes distinct and listed
        // smallest-first, the two largest (encrypted) files win over the short
        // stub whose sampling would fail the verdict open.
        let sized = MockDir {
            name: "STREAM".to_owned(),
            dirs: Vec::new(),
            files: vec![
                mk("00002.m2ts", vec![0_u8; 100]),
                mk("00001.m2ts", encrypted_stream()),
                mk("00000.m2ts", four_units),
            ],
            trip: trip.clone(),
        };
        assert!(stream_content_encrypted(&sized));
    }

    #[test]
    fn every_probe_io_failure_reads_as_not_encrypted() {
        let ok = Trip::new(usize::MAX);
        let key = |trip: &Trip| MockFile {
            name: "Unit_Key_RO.inf".to_owned(),
            extension: ".inf".to_owned(),
            bytes: Vec::new(),
            trip: trip.clone(),
            fail_read_at: None,
            reads: None,
        };
        let aacs = |trip: &Trip| MockDir {
            name: "AACS".to_owned(),
            dirs: Vec::new(),
            files: vec![key(&ok)],
            trip: trip.clone(),
        };
        // The root listing fails → no marker.
        let root = MockDir {
            name: "disc".to_owned(),
            dirs: vec![aacs(&ok)],
            files: Vec::new(),
            trip: Trip::new(0),
        };
        assert!(!has_aacs_key_file(&root));
        // The AACS directory's file listing fails → no marker.
        let root = MockDir {
            name: "disc".to_owned(),
            dirs: vec![aacs(&Trip::new(0))],
            files: Vec::new(),
            trip: ok.clone(),
        };
        assert!(!has_aacs_key_file(&root));
        // The STREAM listing fails → no confirmation.
        let stream = MockDir {
            name: "STREAM".to_owned(),
            dirs: Vec::new(),
            files: Vec::new(),
            trip: Trip::new(0),
        };
        assert!(!stream_content_encrypted(&stream));
        // A stream file that cannot open → not encrypted.
        let unopenable = MockDir {
            name: "STREAM".to_owned(),
            dirs: Vec::new(),
            files: vec![MockFile {
                name: "00000.m2ts".to_owned(),
                extension: ".m2ts".to_owned(),
                bytes: encrypted_stream(),
                trip: Trip::new(0),
                fail_read_at: None,
                reads: None,
            }],
            trip: ok.clone(),
        };
        assert!(!stream_content_encrypted(&unopenable));
        // A stream file whose reader fails mid-unit → not encrypted.
        let unreadable = MockDir {
            name: "STREAM".to_owned(),
            dirs: Vec::new(),
            files: vec![MockFile {
                name: "00000.m2ts".to_owned(),
                extension: ".m2ts".to_owned(),
                bytes: encrypted_stream(),
                trip: ok.clone(),
                fail_read_at: Some(0),
                reads: None,
            }],
            trip: ok,
        };
        assert!(!stream_content_encrypted(&unreadable));
    }

    // ── 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 {
            angle_index,
            relative_time_in: time_in,
            packet_count: packets,
            ..fixtures::clip("00000.M2TS", length)
        }
    }

    /// A [`PlaylistSummary`] carrying only the fields the totals math reads.
    fn playlist_summary(
        total_length: f64,
        angle_count: usize,
        clips: Vec<ClipSummary>,
    ) -> PlaylistSummary {
        PlaylistSummary { angle_count, ..fixtures::playlist("00000.MPLS", total_length, clips) }
    }

    #[test]
    fn estimated_bytes_prefer_the_interleaved_size_then_the_m2ts_size() {
        // Both sizes known: the interleaved total wins (it already contains the
        // m2ts bytes). Only the m2ts: that. Neither: absent.
        let sizes = |interleaved, m2ts| {
            let clip = ClipSummary {
                file_size: m2ts,
                interleaved_file_size: interleaved,
                ..clip_summary(0, 0.0, 0.0, 0)
            };
            let playlist = PlaylistSummary {
                file_size: m2ts,
                interleaved_file_size: interleaved,
                ..playlist_summary(0.0, 0, Vec::new())
            };
            (playlist.estimated_bytes(), clip.estimated_bytes())
        };
        assert_eq!(sizes(2000, 500), (Some(2000), Some(2000)));
        assert_eq!(sizes(0, 500), (Some(500), Some(500)));
        assert_eq!(sizes(0, 0), (None, None));
    }

    #[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());
    }

    #[test]
    fn angle_totals_stop_at_the_widest_angle_table_a_playlist_can_declare() {
        // 254 extra angles is a one-byte angle count of 255, so a summary a scan
        // produced is never clamped; a larger count reaches here only from a
        // hand-assembled summary, where it would otherwise buy one entry (and
        // one walk of the clip list) per angle asked for.
        let clips = vec![clip_summary(0, 0.0, 40.0, 10), clip_summary(1, 0.0, 40.0, 30)];
        assert_eq!(playlist_summary(100.0, 253, clips.clone()).angle_totals().len(), 253);
        assert_eq!(playlist_summary(100.0, 254, clips.clone()).angle_totals().len(), 254);
        assert_eq!(playlist_summary(100.0, 255, clips.clone()).angle_totals().len(), 254);
        assert_eq!(playlist_summary(100.0, usize::MAX, clips).angle_totals().len(), 254);
    }

    proptest! {
        /// The totals hold their set relations for arbitrary clip lists and any
        /// angle count: the all-angles size counts every clip, the main size
        /// only angle 0, each angle's own size never exceeds its timeline's,
        /// and the row count never passes the format's 254.
        #[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,
            ),
            angle_count in proptest::prop_oneof![0_usize..300, proptest::strategy::Just(usize::MAX)],
        ) {
            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, angle_count, 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(), angle_count.min(254));
            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,
            interleaved_file_present: false,
        }];
        let mut playlist = playlist_with_clips(2, Vec::new());
        resolve_playlist_streams(&mut playlist, &metas, false);

        // 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, &[], false);
        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,
            interleaved_file_present: false,
        }];
        resolve_playlist_streams(&mut playlist, &metas, false);
        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,
            interleaved_file_present: false,
        }];
        resolve_playlist_streams(&mut playlist, &metas, false);
        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,
            interleaved_file_present: false,
        }];
        let mut playlist = playlist_with_clips(0, Vec::new());
        resolve_playlist_streams(&mut playlist, &metas, false);
        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 a_stream_file_that_ends_before_its_declared_span_is_reported_short() {
        // The stream file holds three video frames — four demuxed seconds — and
        // its reads end in a clean end of file, so a play item declaring 100 s
        // of it fails nothing and records nothing: the measured span is the
        // only evidence that most of the file is missing.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let mut m2ts = packet(0, true, &pat_payload(0x0100));
        m2ts.extend(packet(0x0100, true, &pmt_payload(&[(0x1B, 0x1011)])));
        for ticks in [90_000_u64, 180_000, 270_000] {
            m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, ticks, ticks, &sps_payload())));
        }
        let build = |out_t: u32| {
            TempDisc::build(
                &[],
                &[
                    ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, out_t, &[])),
                    ("BDMV/CLIPINF/00000.clpi", clip.clone()),
                    ("BDMV/STREAM/00000.m2ts", m2ts.clone()),
                ],
            )
        };

        let short = build(4_500_000); // 100 s declared over a 4 s file
        let scanned = short.open_scanned().expect("measured scan");
        let reported = scanned.short_stream_files();
        assert_eq!(reported.len(), 1);
        let file = reported.first().unwrap();
        assert_eq!(file.file(), "00000.M2TS");
        assert_eq!(file.declared_seconds().to_bits(), 100.0_f64.to_bits());
        assert_eq!(file.measured_seconds().to_bits(), 4.0_f64.to_bits());
        assert_eq!(file.missing_seconds().to_bits(), 96.0_f64.to_bits());

        // The same bytes under a play item declaring the four seconds they
        // carry: the check reports the disagreement between the two spans, not
        // the fixture's size.
        let whole = build(180_000).open_scanned().expect("measured scan");
        assert!(whole.short_stream_files().is_empty());

        // Neither unmeasured mode demuxes a span to compare, so the short disc
        // is silent in both.
        assert!(short.open().expect("metadata scan").short_stream_files().is_empty());
        assert!(short.open_codecs().expect("codec scan").short_stream_files().is_empty());

        // So is a full scan that left this file out of its selection: an
        // unscanned file measures nothing, which is not evidence of a short
        // one. The progress sink is called once here, before the scan, so that
        // the count below proves the scan itself demuxed nothing.
        let mut reported = 0_usize;
        let unselected = {
            let mut progress = |_: ScanProgress<'_>| reported = reported.saturating_add(1);
            progress(ScanProgress { file: "00000.M2TS", done: 0, total: 0 });
            BdRom::open(
                &FsDir::new(short.root.clone()),
                ScanMode::Full,
                ScanOptions::default(),
                Some(&BTreeSet::new()),
                ScanObservers::new(&mut progress, &AtomicBool::new(false)),
            )
            .expect("selective scan")
        };
        assert_eq!(reported, 1, "an empty selection reads no stream file");
        assert!(unselected.short_stream_files().is_empty());
    }

    #[test]
    fn a_stream_file_that_demuxes_to_nothing_at_all_is_reported_short() {
        // Total destruction leaves every number a never-scanned file leaves:
        // no per-stream tally, no demuxed second, no error (both files open and
        // read to a clean end of file). `ClipSummary::measured` is the only
        // thing that tells the two apart, so this is the case that would go
        // silent if the check read the tally list instead.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        // A 0-byte stub, as a rip that died before writing a byte leaves, and a
        // non-empty file whose header is gone — no PAT, no PMT, so no stream
        // ever registers.
        for stub in [Vec::new(), vec![0xFF; 4096]] {
            let bytes = stub.len();
            let disc = TempDisc::build(
                &[],
                &[
                    ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])), // 100 s
                    ("BDMV/CLIPINF/00000.clpi", clip.clone()),
                    ("BDMV/STREAM/00000.m2ts", stub),
                ],
            );
            let scanned = disc.open_scanned().expect("measured scan");
            let summary = scanned
                .playlists
                .first()
                .and_then(|pl| pl.clips.first())
                .expect("the destroyed file's clip row");
            assert!(summary.measured, "{bytes} bytes: the file was demuxed");
            assert!(summary.streams.is_empty(), "{bytes} bytes: nothing registered");
            let reported = scanned.short_stream_files();
            assert_eq!(reported.len(), 1, "{bytes} bytes: {reported:?}");
            assert_eq!(
                reported.first().expect("the short file").notice(),
                "00000.M2TS is shorter than declared: \
                 measured 0.0 s of 100.0 s (100.0 s missing)"
            );
        }
    }

    #[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: the quick-pass-skipping scan ─────────────────────────

    /// Opens `root` at `mode` twice — with the default two-pass options and
    /// with [`ScanOptions::skip_quick_pass`] — returning `(two_pass,
    /// skipped)` for the equality assertions the skipping scan is held to.
    fn scan_both_ways(root: &dyn BdDir, mode: ScanMode) -> (BdRom, BdRom) {
        let two_pass = BdRom::open(
            root,
            mode,
            ScanOptions::default(),
            None,
            ScanObservers::new(&mut |_| {}, &never_cancel()),
        )
        .expect("the two-pass scan opens");
        let options = ScanOptions { skip_quick_pass: true, ..ScanOptions::default() };
        let skipped = BdRom::open(
            root,
            mode,
            options,
            None,
            ScanObservers::new(&mut |_| {}, &never_cancel()),
        )
        .expect("the quick-pass-skipping scan opens");
        (two_pass, skipped)
    }

    /// The interleaved 3D `*.ssif` bytes of
    /// [`open_scanned_reads_the_interleaved_source_and_presents_the_dependent_view`],
    /// with the dependent view (PMT entry and packet) included or not.
    fn interleaved_ssif(with_mvc: bool) -> Vec<u8> {
        let mut ssif = packet(0, true, &pat_payload(0x0100));
        let mut streams = vec![(0x1B, 0x1011)];
        if with_mvc {
            streams.push((0x20, 0x1012));
        }
        ssif.extend(packet(0x0100, true, &pmt_payload(&streams)));
        ssif.extend(packet(0x1011, true, &pes_dts(0xE0, 90_000, 90_000, &sps_payload())));
        if with_mvc {
            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())));
        ssif
    }

    /// The one-clip interleaved disc around `ssif` those equality tests scan.
    fn interleaved_disc(ssif: Vec<u8>) -> TempDisc {
        TempDisc::build(
            &[],
            &[
                ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])])),
                ("BDMV/STREAM/00000.m2ts", vec![0_u8; 192]),
                ("BDMV/STREAM/SSIF/00000.ssif", ssif),
            ],
        )
    }

    /// The same one-clip 3D disc as a mock tree, so either source can be made
    /// unopenable: the base view alone in `00000.m2ts` (opening under `m2ts`),
    /// base plus dependent view in `00000.ssif` (opening under `ssif`). Every
    /// other file is intact.
    fn interleaved_mock_disc(ssif: &Trip, m2ts: &Trip) -> MockDir {
        let trip = Trip::new(usize::MAX);
        let file = |name: &str, bytes: Vec<u8>, trip: &Trip| MockFile {
            name: name.to_owned(),
            extension: extension_of_name(name),
            bytes,
            trip: trip.clone(),
            fail_read_at: None,
            reads: None,
        };
        let dir = |name: &str, dirs: Vec<MockDir>, files: Vec<MockFile>| MockDir {
            name: name.to_owned(),
            dirs,
            files,
            trip: trip.clone(),
        };
        dir(
            "disc",
            vec![dir(
                "BDMV",
                vec![
                    dir(
                        "CLIPINF",
                        vec![],
                        vec![file(
                            "00000.clpi",
                            clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]),
                            &trip,
                        )],
                    ),
                    dir(
                        "PLAYLIST",
                        vec![],
                        vec![file("00000.mpls", mpls("00000", 0, 4_500_000, &[]), &trip)],
                    ),
                    dir(
                        "STREAM",
                        vec![dir(
                            "SSIF",
                            vec![],
                            vec![file("00000.ssif", interleaved_ssif(true), ssif)],
                        )],
                        vec![file("00000.m2ts", interleaved_ssif(false), m2ts)],
                    ),
                ],
                vec![],
            )],
            vec![],
        )
    }

    #[test]
    fn an_unopenable_interleaved_source_falls_back_to_the_base_view() {
        // Control: with the `.ssif` openable this really is a 3D scan, so the
        // 2D result below is the failed open's doing, not the fixture's.
        let intact = Trip::new(usize::MAX);
        let healthy = open_resilient(&interleaved_mock_disc(&intact, &intact), ScanMode::Full)
            .expect("healthy 3D scan");
        assert!(healthy.errors.is_empty());
        let control = healthy.bdrom.playlists.first().unwrap();
        assert!(control.streams.iter().any(|s| s.pid == Pid::new(0x1012)), "the dependent view");
        assert_eq!(control.clips.first().unwrap().display_name, "00000.SSIF");

        let report =
            open_resilient(&interleaved_mock_disc(&Trip::always(), &intact), ScanMode::Full)
                .expect("the resilient scan degrades to the base view");
        // Both measurement passes open the source, so both record the failure
        // — the per-attempt shape every unopenable file already has.
        // The file that failed is the file named — the `.ssif`, not the
        // `.m2ts` the clip is keyed by.
        let recorded: Vec<(ScanStage, &str)> =
            report.errors.iter().map(|e| (e.stage, e.file.as_str())).collect();
        assert_eq!(recorded, vec![(ScanStage::StreamFile, "00000.ssif"); 2]);

        // The clip is measured from its `*.m2ts` — base view present with its
        // rate, dependent view absent, and named by the source it was read
        // from.
        let pl = report.bdrom.playlists.first().unwrap();
        let base = pl.streams.iter().find(|s| s.pid == Pid::new(0x1011)).expect("the base view");
        assert!(base.bitrate > 0, "the base view carries its measured rate");
        assert!(pl.streams.iter().all(|s| s.pid != Pid::new(0x1012)), "no dependent-view row");
        let clip = pl.clips.first().unwrap();
        assert_eq!(clip.display_name, "00000.M2TS");
        assert!(clip.streams.iter().any(|t| t.pid == Pid::new(0x1011)));
        assert!(clip.file_seconds > 0.0, "the base view was demuxed");
    }

    #[test]
    fn a_strict_scan_still_fails_on_an_unopenable_interleaved_source() {
        // The fallback is the resilient scan's keep-what-you-can policy; strict
        // mode is the fail-fast path and has no policy to apply.
        let failed =
            open(&interleaved_mock_disc(&Trip::always(), &Trip::new(usize::MAX)), ScanMode::Full)
                .expect_err("strict mode propagates the failed interleaved open");
        assert_eq!(failed.to_string(), "io error: injected io failure");
    }

    #[test]
    fn a_clip_with_neither_source_openable_keeps_the_scan_going() {
        // The fallback is an attempt, not a guarantee: with the `*.m2ts`
        // unopenable too there is nothing left to read, so the clip is dropped
        // and both failures are recorded — one per source, per pass.
        let dead = Trip::always();
        let report = open_resilient(&interleaved_mock_disc(&dead, &dead), ScanMode::Full)
            .expect("the resilient scan continues past a clip it cannot read");
        let recorded: Vec<(ScanStage, &str)> =
            report.errors.iter().map(|e| (e.stage, e.file.as_str())).collect();
        assert_eq!(
            recorded,
            vec![
                (ScanStage::StreamFile, "00000.ssif"),
                (ScanStage::StreamFile, "00000.m2ts"),
                (ScanStage::StreamFile, "00000.ssif"),
                (ScanStage::StreamFile, "00000.m2ts"),
            ]
        );
        // The playlist still reports, on clip-info detail alone.
        let pl = report.bdrom.playlists.first().unwrap();
        let base = pl.streams.iter().find(|s| s.pid == Pid::new(0x1011)).expect("the base view");
        assert_eq!(base.bitrate, 0, "nothing was measured");
        assert!(pl.clips.first().unwrap().streams.is_empty());
    }

    #[test]
    fn a_full_scan_without_the_quick_pass_presents_the_two_pass_result() {
        // The hardest resolution case: the dependent view exists only in the
        // demuxed `*.ssif`, so the skipping scan has to synthesize its
        // presented entry before the measurement pass (or its windows would
        // never accumulate) and keep it afterwards.
        let disc = interleaved_disc(interleaved_ssif(true));
        let root = FsDir::new(disc.root.clone());
        let (two_pass, skipped) = scan_both_ways(&root, ScanMode::Full);
        assert_eq!(skipped, two_pass);
        // Not vacuous: the dependent view really is presented, with its
        // measured rate.
        let pl = skipped.playlists.first().unwrap();
        let mvc = pl.streams.iter().find(|s| s.pid == Pid::new(0x1012)).unwrap();
        assert!(mvc.ssif_only, "the dependent view is the SSIF-only row");
        assert!(mvc.bitrate > 0, "the dependent view carries its measured rate");

        // `Codecs` ignores the switch — the quick pass IS that mode's scan —
        // so the skipping open still carries the quick-scanned detail.
        let (codecs, codecs_skipped) = scan_both_ways(&root, ScanMode::Codecs);
        assert_eq!(codecs_skipped, codecs);
        let codec_pl = codecs.playlists.first().unwrap();
        assert!(codec_pl.streams.iter().any(|s| s.pid == Pid::new(0x1012)));
    }

    #[test]
    fn a_skipping_scan_withdraws_a_dependent_view_the_measurement_finds_absent() {
        // The interleaved source exists but its PMT declares no dependent
        // view: the placeholder the skipping resolution synthesized must not
        // survive into the presented rows — the two-pass scan presents none.
        let disc = interleaved_disc(interleaved_ssif(false));
        let root = FsDir::new(disc.root.clone());
        let (two_pass, skipped) = scan_both_ways(&root, ScanMode::Full);
        assert_eq!(skipped, two_pass);
        let pl = skipped.playlists.first().unwrap();
        assert!(pl.streams.iter().all(|s| s.pid != Pid::new(0x1012)), "no phantom row");
    }

    #[test]
    fn a_skipping_scan_measures_shared_clips_like_the_two_pass_scan() {
        // Three playlists over three clips, one clip shared: the per-chunk
        // detail back-fill has to reach every playlist a file plays in.
        let disc = shared_clip_disc();
        let (two_pass, skipped) = scan_both_ways(&disc, ScanMode::Full);
        assert_eq!(skipped, two_pass);
        // Not vacuous: the measurement really resolved rates to compare.
        assert!(
            two_pass.playlists.iter().all(|p| p.streams.iter().any(|s| s.bitrate > 0)),
            "every playlist carries a measured rate"
        );
    }

    #[test]
    fn a_skipping_resilient_scan_keeps_partials_like_the_two_pass_scan() {
        use crate::bdrom::m2ts::DATA_SIZE;
        // The reader dies at the read-chunk boundary, so the kept partial
        // file carries the head frames — the skipping scan must present the
        // same partial rows the two-pass scan does.
        let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47, 48]);
        let scan = |options: ScanOptions| {
            let disc = tripping_disc(m2ts.clone(), Some(DATA_SIZE));
            BdRom::open_resilient(
                &disc,
                ScanMode::Full,
                options,
                None,
                ScanObservers::new(&mut |_| {}, &never_cancel()),
            )
            .expect("the resilient scan continues")
        };
        let two_pass = scan(ScanOptions::default());
        let skipped = scan(ScanOptions { skip_quick_pass: true, ..ScanOptions::default() });
        assert_eq!(skipped.bdrom, two_pass.bdrom);
        assert_eq!(two_pass.errors.len(), 1, "the mid-file failure is recorded");
        assert_eq!(skipped.errors.len(), 1, "the skipping scan records it too");
        // Not vacuous: the kept partial really measured the head frames.
        let pl = skipped.bdrom.playlists.first().unwrap();
        assert!(pl.streams.iter().any(|s| s.bitrate > 0), "the partial carries a rate");
    }

    /// A one-clip mock disc whose stream file logs every read's requested
    /// size into `reads`; `aacs` adds the `AACS/Unit_Key_RO.inf` key file the
    /// encryption probe looks for (the stream bytes carry no fingerprint, so
    /// a probe that runs resolves to unencrypted).
    fn logged_disc(m2ts: Vec<u8>, reads: &Arc<Mutex<Vec<usize>>>, aacs: bool) -> MockDir {
        let trip = Trip::new(usize::MAX);
        let file = |name: &str, bytes: Vec<u8>, reads: Option<Arc<Mutex<Vec<usize>>>>| MockFile {
            name: name.to_owned(),
            extension: extension_of_name(name),
            bytes,
            trip: trip.clone(),
            fail_read_at: None,
            reads,
        };
        let dir = |name: &str, dirs: Vec<MockDir>, files: Vec<MockFile>| MockDir {
            name: name.to_owned(),
            dirs,
            files,
            trip: trip.clone(),
        };
        let mut top = vec![dir(
            "BDMV",
            vec![
                dir(
                    "CLIPINF",
                    vec![],
                    vec![file("00000.clpi", clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]), None)],
                ),
                dir(
                    "PLAYLIST",
                    vec![],
                    vec![file("00000.mpls", mpls("00000", 0, 4_500_000, &[]), None)],
                ),
                dir("STREAM", vec![], vec![file("00000.m2ts", m2ts, Some(Arc::clone(reads)))]),
            ],
            vec![],
        )];
        if aacs {
            top.push(dir("AACS", vec![], vec![file("Unit_Key_RO.inf", b"key".to_vec(), None)]));
        }
        dir("disc", top, vec![])
    }

    #[test]
    fn a_skipping_full_scan_issues_no_quick_sized_reads() {
        use crate::bdrom::m2ts::{DATA_SIZE, QUICK_DATA_SIZE};
        let log = Arc::new(Mutex::new(Vec::new()));
        let disc = logged_disc(video_m2ts(&[1, 2, 3]), &log, false);
        let scan = |options: ScanOptions| {
            log.lock().unwrap().clear();
            drop(
                BdRom::open(
                    &disc,
                    ScanMode::Full,
                    options,
                    None,
                    ScanObservers::new(&mut |_| {}, &never_cancel()),
                )
                .expect("the mock disc scans"),
            );
            log.lock().unwrap().clone()
        };
        // The two passes are told apart by their read-chunk sizes alone.
        let two_pass = scan(ScanOptions::default());
        assert!(two_pass.contains(&QUICK_DATA_SIZE), "the quick pass requests its own chunk size");
        assert!(two_pass.contains(&DATA_SIZE), "the measurement pass requests full chunks");
        let skipped = scan(ScanOptions { skip_quick_pass: true, ..ScanOptions::default() });
        assert_eq!(skipped.first(), Some(&DATA_SIZE), "the scan opens on a full chunk");
        assert!(
            skipped.iter().all(|&size| size > QUICK_DATA_SIZE),
            "no quick-pass read remains: {skipped:?}"
        );
    }

    #[test]
    fn a_supplied_aacs_verdict_replaces_the_stream_head_probe() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let disc = logged_disc(video_m2ts(&[1]), &log, true);
        let progressed = AtomicBool::new(false);
        let open = |mode: ScanMode, options: ScanOptions| {
            log.lock().unwrap().clear();
            let mut observe = |_: ScanProgress<'_>| progressed.store(true, Ordering::Relaxed);
            BdRom::open(
                &disc,
                mode,
                options,
                None,
                ScanObservers::new(&mut observe, &never_cancel()),
            )
            .expect("the mock disc opens")
        };
        // Probing (the default): the key file is present, so the probe reads
        // the stream head — a `Metadata` open's only stream read — and the
        // fingerprint-free bytes resolve to unencrypted.
        let probed = open(ScanMode::Metadata, ScanOptions::default());
        assert!(!probed.is_aacs_encrypted);
        assert!(!log.lock().unwrap().is_empty(), "the probe reads the stream head");
        // A supplied verdict is recorded verbatim with no read at all —
        // `true` could not have come from probing this unencrypted disc.
        let told =
            |verdict| ScanOptions { aacs_encrypted: Some(verdict), ..ScanOptions::default() };
        assert!(open(ScanMode::Metadata, told(true)).is_aacs_encrypted);
        assert!(log.lock().unwrap().is_empty(), "no probe read with a supplied verdict");
        assert!(!open(ScanMode::Metadata, told(false)).is_aacs_encrypted);
        assert!(log.lock().unwrap().is_empty(), "no probe read either way");
        assert!(!progressed.load(Ordering::Relaxed), "a Metadata open reports no progress");
        // A `Codecs` open with a reused verdict — the shape of a listing's
        // second open — keeps its packet scan: the quick pass reads (and
        // reports progress); only the probe stays silent.
        let coded = open(ScanMode::Codecs, told(false));
        assert!(!coded.is_aacs_encrypted);
        assert!(!log.lock().unwrap().is_empty(), "the quick pass still reads packets");
        assert!(progressed.load(Ordering::Relaxed), "the quick pass reports progress");
    }

    #[test]
    fn a_logged_reader_seeks_through_to_its_source() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut reader =
            LoggedReads { inner: Box::new(Cursor::new(vec![1, 2, 3, 4])), log: Arc::clone(&log) };
        assert_eq!(reader.seek(SeekFrom::Start(2)).unwrap(), 2);
        let mut buf = [0_u8; 2];
        assert_eq!(reader.read(&mut buf).unwrap(), 2);
        assert_eq!(buf, [3, 4]);
        assert_eq!(*log.lock().unwrap(), [2], "the seek is silent; the read is logged");
    }

    #[test]
    fn the_pre_open_heartbeat_names_the_file_being_opened() {
        // Two clips, the second failing its first read: the window between
        // the first file's boundary and the second file's first read — the
        // window a blocking open on damaged media stalls in — must already be
        // reported under the second file's name. Two count-preserving events
        // name it there: the pre-open heartbeat and the first read's.
        let clip = || clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let disc = tripping_disc_of(
            &[
                MockClip { stem: "00011", clip: clip(), m2ts: video_m2ts(&[1, 2]), serve: None },
                MockClip { stem: "00022", clip: clip(), m2ts: video_m2ts(&[1]), serve: Some(0) },
            ],
            &[("00000", &["00011"]), ("00001", &["00022"])],
        );
        let mut events: Vec<(String, u64)> = Vec::new();
        let mut collect = |p: ScanProgress<'_>| events.push((p.file.to_owned(), p.done));
        drop(
            BdRom::open_resilient(
                &disc,
                ScanMode::Full,
                ScanOptions::default(),
                None,
                ScanObservers::new(&mut collect, &never_cancel()),
            )
            .expect("the resilient scan continues over the failed read"),
        );
        let first_boundary = u64::try_from(video_m2ts(&[1, 2]).len()).unwrap();
        let attributed = events
            .iter()
            .filter(|(file, done)| file == "00022.M2TS" && *done == first_boundary)
            .count();
        assert!(
            attributed >= 2,
            "pre-open and pre-read heartbeats both name the second file: {events:?}"
        );
        // The boundary snap still closes the failed file out.
        assert_eq!(events.last().map(|(file, _)| file.as_str()), Some("00022.M2TS"));
    }

    #[test]
    fn remove_mvc_placeholder_withdraws_only_an_unconfirmed_synthetic_entry() {
        let mvc = || {
            let mut stream = TsVideoStream::default();
            stream.base.pid = Pid::new(MVC_PID);
            stream.base.stream_type = TsStreamType::MvcVideo;
            TsStream::Video(stream)
        };
        let placeholder_playlist = || {
            let mut playlist = playlist_with_clips(1, Vec::new());
            playlist.streams = BTreeMap::from([(MVC_PID, mvc())]);
            playlist.angle_streams = vec![BTreeMap::from([(MVC_PID, mvc())])];
            playlist
        };
        let empty = BTreeMap::new();
        let meta = |clip_streams, scanned| ClipMeta {
            clip_streams,
            scanned,
            has_50hz_video: false,
            relative_length: 1.0,
            length: 10.0,
            stream_file_present: true,
            interleaved_file_present: true,
        };

        // The measurement registered no MVC stream: the placeholder goes,
        // from the main map and every angle map.
        let unconfirmed = TsStreamFile::new("00000.m2ts");
        let mut playlist = placeholder_playlist();
        remove_mvc_placeholder(&mut playlist, &meta(&empty, Some(&unconfirmed)));
        assert!(playlist.streams.is_empty());
        assert!(playlist.angle_streams.iter().all(BTreeMap::is_empty));

        // The measurement registered the dependent view: the entry stays.
        let mut confirmed = TsStreamFile::new("00000.m2ts");
        confirmed.streams.insert(MVC_PID, mvc());
        let mut playlist = placeholder_playlist();
        remove_mvc_placeholder(&mut playlist, &meta(&empty, Some(&confirmed)));
        assert!(playlist.streams.contains_key(&MVC_PID));

        // No measured file to consult (a dropped partial): the entry stays —
        // the interleaved file's existence remains the best evidence.
        let mut playlist = placeholder_playlist();
        remove_mvc_placeholder(&mut playlist, &meta(&empty, None));
        assert!(playlist.streams.contains_key(&MVC_PID));

        // A clip-info-declared MVC PID is not a placeholder and stays even
        // when the measured file carries none.
        let declared = BTreeMap::from([(MVC_PID, mvc())]);
        let mut playlist = placeholder_playlist();
        remove_mvc_placeholder(&mut playlist, &meta(&declared, Some(&unconfirmed)));
        assert!(playlist.streams.contains_key(&MVC_PID));
    }

    #[test]
    fn resolve_synthesizes_the_dependent_view_only_for_an_interleaved_clip() {
        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 meta = |interleaved: bool| ClipMeta {
            clip_streams: &clip_streams,
            scanned: None,
            has_50hz_video: false,
            relative_length: 1.0,
            length: 10.0,
            stream_file_present: true,
            interleaved_file_present: interleaved,
        };

        // Interleaved + synthesize: the placeholder appears, typed as the
        // dependent view, and is cloned per angle like any video stream.
        let mut playlist = playlist_with_clips(1, Vec::new());
        resolve_playlist_streams(&mut playlist, &[meta(true)], true);
        let placeholder = playlist.streams.get(&MVC_PID).expect("the placeholder is presented");
        assert_eq!(placeholder.stream_type(), TsStreamType::MvcVideo);
        assert_eq!(placeholder.pid(), Pid::new(MVC_PID));
        assert!(playlist.angle_streams.first().is_some_and(|a| a.contains_key(&MVC_PID)));

        // No interleaved file, or no synthesize switch: no placeholder.
        let mut playlist = playlist_with_clips(0, Vec::new());
        resolve_playlist_streams(&mut playlist, &[meta(false)], true);
        assert!(!playlist.streams.contains_key(&MVC_PID));
        let mut playlist = playlist_with_clips(0, Vec::new());
        resolve_playlist_streams(&mut playlist, &[meta(true)], false);
        assert!(!playlist.streams.contains_key(&MVC_PID));
    }

    #[test]
    fn backfill_playlist_detail_merges_matching_pids_into_every_map() {
        // The playlist presents a clip-info video copy (no scanned detail) on
        // the main map and an angle map; the demuxed clip has learned the
        // codec detail and also carries a PID the playlist does not present.
        let clip_video = || {
            let mut stream = TsVideoStream::default();
            stream.base.pid = Pid::new(0x1011);
            stream.base.stream_type = TsStreamType::AvcVideo;
            TsStream::Video(stream)
        };
        let mut playlist = playlist_with_clips(1, Vec::new());
        playlist.streams = BTreeMap::from([(0x1011, clip_video())]);
        playlist.angle_streams = vec![BTreeMap::from([(0x1011, clip_video())])];

        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.encoding_profile = Some("High Profile 4.1".to_owned());
        let mut unpresented = TsVideoStream::default();
        unpresented.base.pid = Pid::new(0x1012);
        unpresented.base.stream_type = TsStreamType::MvcVideo;
        let streams = BTreeMap::from([
            (0x1011, TsStream::Video(scanned_video)),
            (0x1012, TsStream::Video(unpresented)),
        ]);

        backfill_playlist_detail(&mut playlist, &streams);
        let main = playlist.streams.get(&0x1011).unwrap();
        assert!(main.base().is_vbr, "the demux-read switch is back-filled");
        assert_eq!(
            as_video(main).and_then(|v| v.encoding_profile.as_deref()),
            Some("High Profile 4.1")
        );
        let angle = playlist.angle_streams.first().and_then(|a| a.get(&0x1011)).unwrap();
        assert!(angle.base().is_vbr, "angle copies are back-filled too");
        // A PID the playlist does not present is merged nowhere — the
        // back-fill only enriches, it never adds a presented stream.
        assert!(!playlist.streams.contains_key(&0x1012));
    }

    // ── 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> {
        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_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!(
            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,
        /// Whether *every* operation fails, `fail_at` notwithstanding — an
        /// object that never opens, which a scan opening it once per
        /// measurement pass needs (a one-shot trip would let the second pass
        /// through).
        always: bool,
    }

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

        fn always() -> Self {
            Self { count: Arc::new(AtomicUsize::new(0)), fail_at: usize::MAX, always: true }
        }

        fn tick(&self) -> io::Result<()> {
            if self.count.fetch_add(1, Ordering::Relaxed) == self.fail_at || self.always {
                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 once
        /// this many bytes have been served — `Some(0)` fails the first read
        /// (exercising `read_file`'s `read_to_end`, not `open_read`, failure
        /// arm), a larger count models a file whose tail is unreadable.
        fail_read_at: Option<usize>,
        /// When set, every read served through `open_read` appends its
        /// requested size here, shared across the file's clones — the
        /// instrument that tells the passes (and the AACS probe) apart by
        /// their distinct read sizes, and proves a skipped pass by silence.
        reads: Option<Arc<Mutex<Vec<usize>>>>,
    }

    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()?;
            let inner = self.fail_read_at.map_or_else(
                || -> Box<dyn ReadSeek> { Box::new(Cursor::new(self.bytes.clone())) },
                |serve| {
                    Box::new(ServeThenFail {
                        bytes: Cursor::new(self.bytes.clone()),
                        remaining: serve,
                    })
                },
            );
            Ok(match &self.reads {
                Some(log) => Box::new(LoggedReads { inner, log: Arc::clone(log) }),
                None => inner,
            })
        }

        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 appends each read's requested size to its shared log
    /// before serving it — the recording half of [`MockFile::reads`].
    struct LoggedReads {
        inner: Box<dyn ReadSeek>,
        log: Arc<Mutex<Vec<usize>>>,
    }

    impl Read for LoggedReads {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            self.log.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(buf.len());
            self.inner.read(buf)
        }
    }

    impl Seek for LoggedReads {
        fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
            self.inner.seek(pos)
        }
    }

    /// A reader that serves at most `remaining` bytes of `bytes` and then
    /// errors — a file whose tail sectors are unreadable. A source shorter
    /// than `remaining` just hits EOF first (no error).
    struct ServeThenFail {
        bytes: Cursor<Vec<u8>>,
        remaining: usize,
    }

    impl Read for ServeThenFail {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            if self.remaining == 0 {
                return Err(io::Error::other("read failed"));
            }
            // `min` keeps the split inside the buffer, and an in-memory cursor
            // read is an infallible copy — `unwrap_or` spells its `Result`
            // away without adding an uncoverable error arm.
            let cap = self.remaining.min(buf.len());
            let (dst, _) = buf.split_at_mut(cap);
            let served = self.bytes.read(dst).unwrap_or(0);
            self.remaining = self.remaining.saturating_sub(served);
            Ok(served)
        }
    }

    impl Seek for ServeThenFail {
        fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
            self.bytes.seek(pos)
        }
    }

    /// 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
        }

        // Both convenience methods are provided by `BdDir`; these overrides
        // exist so this fake ticks its failure countdown once per call and
        // lists every file whatever the pattern — the provided bodies would
        // route through `get_files_pattern_option`, tick there instead, and
        // filter by `collect_matching`'s exact-name rule.
        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>| MockFile {
            name: name.to_owned(),
            extension: extension_of_name(name),
            bytes,
            trip: trip.clone(),
            fail_read_at: None,
            reads: None,
        };
        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 directory_size_keeps_an_uppercase_ssif_out_of_the_disc_size() {
        // `extension_of_name` returns the suffix verbatim, case included, so the
        // interleaved split is what has to fold case: a disc naming its file
        // `00000.SSIF` must reach the same two totals as the lowercase spelling.
        let trip = Trip::new(usize::MAX);
        let file = |name: &str, len: usize| MockFile {
            name: name.to_owned(),
            extension: extension_of_name(name),
            bytes: vec![0; len],
            trip: trip.clone(),
            fail_read_at: None,
            reads: None,
        };
        let dir = MockDir {
            name: "SSIF".to_owned(),
            dirs: Vec::new(),
            files: vec![file("00000.SSIF", 10), file("00001.ssif", 20), file("00000.m2ts", 5)],
            trip,
        };
        assert_eq!(directory_size(&dir).expect("mock listing is infallible"), (5, 30));
    }

    #[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 = 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. The one
        // exception is the AACS probe (fail-open by design): a failure it
        // absorbs must leave the scan identical to the clean one.
        let mut fail_open = 0_usize;
        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`.
            if let Ok(scanned) = open(&mock_disc(&trip), ScanMode::Full) {
                assert_eq!(scanned, bd, "io failure at op {fail_at} altered the scan");
                fail_open = fail_open.saturating_add(1);
            }
        }
        // Exactly the probe's root listing: with no `AACS` directory the probe
        // short-circuits after one op, so exactly one failure is absorbed — more
        // would mean the probe kept sampling without its key-file hint.
        assert_eq!(fail_open, 1);
    }

    #[test]
    fn scan_stream_files_keeps_or_drops_a_partial_file_per_mode_and_switch() {
        // A STREAM dir with one `*.m2ts` whose reader fails after a successful
        // open — a read error before any packet demuxes. The three outcomes of
        // the keep/drop seam, over the same damage:
        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_at: Some(0),
            reads: None,
        };
        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()];
        let run = |playlists: &mut Vec<TsPlaylistFile>, sink: &mut Sink<'_>, keep_partial: bool| {
            let mut noop = |_: ScanProgress<'_>| {};
            let mut progress = Progress {
                callback: &mut noop,
                measured: None,
                done: 0,
                total: 200,
                cancel: &AtomicBool::new(false),
            };
            let scanned = scan_stream_files(
                Some(&stream_dir),
                None,
                playlists,
                None,
                &mut progress,
                sink,
                keep_partial,
                false,
                false,
            );
            // The failed file still consumes its progress budget (the snap to
            // the file boundary) whether or not its partial state is kept.
            assert_eq!(progress.done, 200, "the failed file's bytes are snapped past");
            scanned
        };
        // Strict mode propagates the read failure, partial state and all —
        // `keep_partial` changes nothing there.
        let strict = run(&mut playlists, &mut Sink { errors: None }, true);
        assert!(strict.is_err());
        // Resilient mode records the failure either way; the switch decides
        // whether the partial file (here empty — the read failed before any
        // packet) still lands in the returned map.
        let mut errors = Vec::new();
        let kept = run(&mut playlists, &mut Sink { errors: Some(&mut errors) }, true)
            .expect("resilient scan continues");
        let partial = kept.get("00000.M2TS").expect("the partial file is kept");
        assert!(partial.streams.is_empty(), "no packet demuxed before the failing read");
        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");
        // `keep_partial: false` drops the file wholesale — the pre-retention
        // resilient outcome.
        let mut errors = Vec::new();
        let dropped = run(&mut playlists, &mut Sink { errors: Some(&mut errors) }, false)
            .expect("resilient scan continues");
        assert!(dropped.is_empty());
        assert_eq!(errors.len(), 1);
    }

    // ── partial retention: the disc-level keep/drop seam ─────────────────────

    /// A demuxable `*.m2ts` longer than one read chunk
    /// ([`DATA_SIZE`](crate::bdrom::m2ts::DATA_SIZE)): PAT, a PMT declaring
    /// `streams`, AVC video frames (PID 0x1011) timestamped at `head_seconds`
    /// inside the first chunk, null-PID padding across the chunk boundary,
    /// then frames at `tail_seconds`. A reader that dies at the boundary hands
    /// the demux every head frame and none of the tail (a mid-chunk death
    /// voids the whole in-flight chunk — `fill_buffer` propagates before
    /// demuxing it).
    fn two_chunk_m2ts(
        streams: &[(u8, u16)],
        head_seconds: &[u64],
        tail_seconds: &[u64],
    ) -> Vec<u8> {
        use crate::bdrom::m2ts::DATA_SIZE;
        let frame = |s: u64| {
            let ticks = s.wrapping_mul(90_000);
            packet(0x1011, true, &pes_dts(0xE0, ticks, ticks, &sps_payload()))
        };
        let mut m2ts = packet(0, true, &pat_payload(0x0100));
        m2ts.extend(packet(0x0100, true, &pmt_payload(streams)));
        for &s in head_seconds {
            m2ts.extend(frame(s));
        }
        while m2ts.len() <= DATA_SIZE {
            m2ts.extend(packet(0x1FFF, false, &[0_u8; 184]));
        }
        for &s in tail_seconds {
            m2ts.extend(frame(s));
        }
        m2ts
    }

    /// One clip of a [`tripping_disc_of`] tree: `stem` names the `{stem}.clpi`
    /// / `{stem}.m2ts` pair carrying `clip` and `m2ts` bytes, and the stream
    /// file's reader fails once `serve` bytes have been read (`None` =
    /// healthy).
    struct MockClip {
        stem: &'static str,
        clip: Vec<u8>,
        m2ts: Vec<u8>,
        serve: Option<usize>,
    }

    /// A mock disc over `clips` carrying one `*.mpls` per `playlists` entry:
    /// entry `(stem, items)` becomes `{stem}.mpls`, playing each named clip
    /// stem as its own 100 s play item, with chapter marks at 0 s and 45 s of
    /// the first item. Every metadata file is intact — a clip's own `serve` is
    /// the only damage on the disc.
    fn tripping_disc_of(clips: &[MockClip], playlists: &[(&str, &[&str])]) -> MockDir {
        let trip = Trip::new(usize::MAX);
        let file = |name: &str, bytes: Vec<u8>, fail_read_at: Option<usize>| MockFile {
            name: name.to_owned(),
            extension: extension_of_name(name),
            bytes,
            trip: trip.clone(),
            fail_read_at,
            reads: None,
        };
        let dir = |name: &str, dirs: Vec<MockDir>, files: Vec<MockFile>| MockDir {
            name: name.to_owned(),
            dirs,
            files,
            trip: trip.clone(),
        };
        let clip_info: Vec<MockFile> = clips
            .iter()
            .map(|clip| file(&format!("{}.clpi", clip.stem), clip.clip.clone(), None))
            .collect();
        let streams: Vec<MockFile> = clips
            .iter()
            .map(|clip| file(&format!("{}.m2ts", clip.stem), clip.m2ts.clone(), clip.serve))
            .collect();
        let playlist_files: Vec<MockFile> = playlists
            .iter()
            .map(|&(stem, items)| {
                file(
                    &format!("{stem}.mpls"),
                    mpls_items(items, 0, 4_500_000, &[], &[], &[(1, 0, 0), (1, 0, 2_025_000)]),
                    None,
                )
            })
            .collect();
        dir(
            "disc",
            vec![dir(
                "BDMV",
                vec![
                    dir("CLIPINF", vec![], clip_info),
                    dir("PLAYLIST", vec![], playlist_files),
                    dir("STREAM", vec![], streams),
                ],
                vec![],
            )],
            vec![],
        )
    }

    /// A minimal one-playlist mock disc around `m2ts`: one 100 s play item
    /// (`00000.M2TS`, clip info `clip`) with chapter marks at 0 s and 45 s.
    /// The stream file's reader fails once `serve` bytes have been read
    /// (`None` = healthy); every other file is intact.
    fn tripping_disc_with(clip: Vec<u8>, m2ts: Vec<u8>, serve: Option<usize>) -> MockDir {
        tripping_disc_of(&[MockClip { stem: "00000", clip, m2ts, serve }], &[("00000", &["00000"])])
    }

    /// [`tripping_disc_with`] over a video-only clip (AVC on PID 0x1011).
    fn tripping_disc(m2ts: Vec<u8>, serve: Option<usize>) -> MockDir {
        tripping_disc_with(clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]), m2ts, serve)
    }

    #[test]
    fn open_resilient_keeps_a_mid_file_partial_scan_by_default() {
        use crate::bdrom::m2ts::DATA_SIZE;
        let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47, 48]);

        // Healthy control: the same tree scans clean and both chapters carry
        // measured rates — so the damaged scan's zero second row below is the
        // trip's doing, not the fixture's.
        let healthy = open_resilient(&tripping_disc(m2ts.clone(), None), ScanMode::Full)
            .expect("healthy scan");
        assert!(healthy.errors.is_empty());
        let control = healthy.bdrom.playlists.first().unwrap();
        assert!(control.chapters.first().unwrap().avg_rate > 0.0);
        assert!(control.chapters.get(1).unwrap().avg_rate > 0.0);

        // Tripped at the chunk boundary: the head frames demuxed, the rest died.
        let report = open_resilient(&tripping_disc(m2ts, Some(DATA_SIZE)), ScanMode::Full)
            .expect("resilient scan continues");
        // The full pass trips; the quick pass stops inside the served first
        // chunk once the lone video stream's codec detail initialises, so it
        // never reaches the failing read.
        assert_eq!(report.errors.len(), 1);
        let recorded = report.errors.first().unwrap();
        assert_eq!((recorded.stage, recorded.file.as_str()), (ScanStage::StreamFile, "00000.m2ts"));

        let pl = report.bdrom.playlists.first().unwrap();
        // The kept partial file fills the chapter rows up to the death point:
        // the first chapter carries its measured rate, the post-death chapter
        // is a zero row with its mark's own time and length.
        assert_eq!(pl.chapters.len(), 2);
        let first = pl.chapters.first().unwrap();
        assert_eq!(first.time_in.to_bits(), 0.0_f64.to_bits());
        assert_eq!(first.length.to_bits(), 45.0_f64.to_bits());
        assert!(first.avg_rate > 0.0);
        let second = pl.chapters.get(1).unwrap();
        assert_eq!(second.time_in.to_bits(), 45.0_f64.to_bits());
        assert_eq!(second.length.to_bits(), 55.0_f64.to_bits());
        assert_eq!(second.avg_rate.to_bits(), 0.0_f64.to_bits());
        // The stream-diagnostics material survives too: the clip row carries
        // the partial demuxed seconds and per-stream tallies.
        let clip = pl.clips.first().unwrap();
        assert!(clip.file_seconds > 0.0);
        let tally = clip.streams.first().expect("the partial file's video tally");
        assert!(tally.payload_bytes > 0);
        // The quick pass's codec detail is intact on the presented stream.
        assert!(pl.streams.first().unwrap().description.contains("High Profile 4.1"));
    }

    #[test]
    fn keep_partial_off_drops_the_partial_scan_wholesale() {
        use crate::bdrom::m2ts::DATA_SIZE;
        let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47, 48]);
        let kept = open_resilient(&tripping_disc(m2ts.clone(), Some(DATA_SIZE)), ScanMode::Full)
            .expect("resilient scan continues");
        let off = BdRom::open_resilient(
            &tripping_disc(m2ts, Some(DATA_SIZE)),
            ScanMode::Full,
            ScanOptions { keep_partial: false, ..ScanOptions::default() },
            None,
            ScanObservers::new(&mut |_| {}, &AtomicBool::new(false)),
        )
        .expect("resilient scan continues");

        // Same failure recorded either way; the switch only decides retention.
        assert_eq!(off.errors.len(), kept.errors.len());
        let pl = off.bdrom.playlists.first().unwrap();
        let kept_pl = kept.bdrom.playlists.first().unwrap();
        // The dropped file leaves the chapter rows and diagnostics all zero…
        assert_eq!(pl.chapters.len(), 2);
        assert_eq!(pl.chapters.first().unwrap().avg_rate.to_bits(), 0.0_f64.to_bits());
        let clip = pl.clips.first().unwrap();
        assert!(!clip.measured, "a dropped file is not in the full-pass map");
        assert!(clip.streams.is_empty());
        assert_eq!(clip.file_seconds.to_bits(), 0.0_f64.to_bits());
        // …while the in-place playlist tallies the demux flushed before dying
        // still count, exactly as they do with retention on: dropping the file
        // preserves the partial-size-next-to-zero-chapters inconsistency by
        // design (the switch's OFF contract), it does not undo the demux.
        let kept_clip = kept_pl.clips.first().unwrap();
        assert!(clip.packet_count > 0);
        assert_eq!(clip.packet_count, kept_clip.packet_count);
        assert_eq!(clip.payload_bytes, kept_clip.payload_bytes);
        // The rendered report's byte pin — see `DAMAGED_OFF_REPORT`.
        assert_eq!(
            crate::report::text::render(&off.bdrom, &off.errors),
            DAMAGED_OFF_REPORT.replace('\n', "\r\n").replace("<TAB>", "\t")
        );
    }

    #[test]
    fn a_file_that_died_partway_is_reported_short_only_while_its_partial_scan_is_kept() {
        use crate::bdrom::m2ts::DATA_SIZE;
        let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47, 48]);
        // A read failure leaves the same measured shortfall a truncated file
        // does, so the file is reported short as well as recorded — the two
        // lists deliberately overlap, and the caller pairs them by name.
        let kept = open_resilient(&tripping_disc(m2ts.clone(), Some(DATA_SIZE)), ScanMode::Full)
            .expect("resilient scan continues");
        let short = kept.bdrom.short_stream_files();
        assert_eq!(short.len(), 1);
        assert_eq!(short.first().unwrap().file(), "00000.M2TS");
        assert_eq!(kept.errors.len(), 1);
        assert_eq!(
            kept.errors.first().unwrap().file.to_ascii_uppercase(),
            short.first().unwrap().file()
        );

        // Retention off drops the dead file from the full-pass map, so its clip
        // comes back unmeasured — the same marker a file the scan never opened
        // carries — and the recorded failure alone names it.
        let off = BdRom::open_resilient(
            &tripping_disc(m2ts, Some(DATA_SIZE)),
            ScanMode::Full,
            ScanOptions { keep_partial: false, ..ScanOptions::default() },
            None,
            ScanObservers::new(&mut |_| {}, &AtomicBool::new(false)),
        )
        .expect("resilient scan continues");
        assert_eq!(off.errors.len(), 1);
        let dropped = off
            .bdrom
            .playlists
            .first()
            .and_then(|pl| pl.clips.first())
            .expect("the dropped file's clip row");
        assert!(!dropped.measured);
        assert!(off.bdrom.short_stream_files().is_empty());
    }

    /// The whole expected report of the `keep_partial: false` scan of the
    /// tripped [`tripping_disc`] fixture, spelled with `\n` endings and a
    /// `<TAB>` token (the assert respells them `\r\n` and `\t`).
    ///
    /// Byte-pinned because the OFF switch's contract is exactly the
    /// pre-retention damaged-scan output — including its inconsistency: the
    /// in-place partial tallies still show as the 960-byte Movie Size and the
    /// FILES bitrate while every chapter row and the stream diagnostics stay
    /// empty. Retention must change nothing when switched off.
    const DAMAGED_OFF_REPORT: &str = r"Disc Label:     disc
Disc Size:      263,040 bytes
Protection:     AACS
BDInfo:         0.8.0.1

Notes:          

BDINFO HOME:
  Cinema Squid (old)
    http://www.cinemasquid.com/blu-ray/tools/bdinfo
  UniqProject GitHub (new)
    https://github.com/UniqProject/BDInfo

INCLUDES FORUMS REPORT FOR:
  AVS Forum Blu-ray Audio and Video Specifications Thread
    http://www.avsforum.com/avs-vb/showthread.php?t=1155731

WARNING: File errors were encountered during scan:

00000.m2ts<TAB>io error: read failed

********************
PLAYLIST: 00000.MPLS
********************

<--- BEGIN FORUMS PASTE --->
[code]
                                                                                                                      Total        Video                                                                           
Title                                                           Codec   Length    Movie Size        Disc Size         Bitrate      Bitrate      Main Audio Track                          Secondary Audio Track    
-----                                                           ------  -------   --------------    ----------------  -----------  -----------  ------------------                        ---------------------    
00000.MPLS                                                      AVC     00:01:40  960               263,040           0.00 Mbps    0.00 Mbps                                                                       
[/code]

[code]
DISC INFO:
Disc Label:     disc
Disc Size:      263,040 bytes
Protection:     AACS
BDInfo:         0.8.0.1b

PLAYLIST REPORT:

Name:           00000.MPLS
Length:         00:01:40.000 (h:m:s.ms)
Size:           960 bytes
Total Bitrate:  0.00 Mbps

(*) Indicates included stream hidden by this playlist.

VIDEO:

Codec                   Bitrate             Description     
---------------         -------------       -----------     
* MPEG-4 AVC Video      0 kbps              1080p / 24 fps / 16:9 / High Profile 4.1

FILES:

Name            Time In         Length          Size            Total Bitrate   
--------------- -------------   -------------   -------------   -------------   
00000.M2TS      0:00:00.000     0:01:40.000     960                  2 kbps     

CHAPTERS:

Number          Time In         Length          Avg Video Rate  Max 1-Sec Rate  Max 1-Sec Time  Max 5-Sec Rate  Max 5-Sec Time  Max 10Sec Rate  Max 10Sec Time  Avg Frame Size  Max Frame Size  Max Frame Time  
------          -------------   -------------   --------------  --------------  --------------  --------------  --------------  --------------  --------------  --------------  --------------  --------------  
1               0:00:00.000     0:00:45.000          0 kbps          0 kbps     00:00:00.000         0 kbps     00:00:00.000         0 kbps     00:00:00.000          0 bytes         0 bytes   00:00:00.000    
2               0:00:45.000     0:00:55.000          0 kbps          0 kbps     00:00:00.000         0 kbps     00:00:00.000         0 kbps     00:00:00.000          0 bytes         0 bytes   00:00:00.000    

STREAM DIAGNOSTICS:

File            PID             Type            Codec           Language                Seconds                     Bitrate                  Bytes        Packets       
----------      -------------   -----           ----------      -------------           --------------          ---------------         --------------  -----------     

[/code]
<---- END FORUMS PASTE ---->

QUICK SUMMARY:

Disc Label:     disc
Disc Size:      263,040 bytes
Protection:     AACS
Playlist:       00000.MPLS
Size:           960 bytes
Length:         00:01:40.000
Total Bitrate:  0.00 Mbps
* Video:        MPEG-4 AVC Video / 0 kbps / 1080p / 24 fps / 16:9 / High Profile 4.1

";

    #[test]
    fn a_quick_pass_partial_keeps_its_initialised_codec_detail() {
        use crate::bdrom::m2ts::DATA_SIZE;
        // The PMT declares video AND audio, but no audio PES ever arrives, so
        // the quick pass — unlike the video-only fixtures above, where it
        // stops inside the first chunk — keeps reading for the audio codec
        // detail and trips at the boundary exactly like the full pass: one
        // recorded failure per pass. Its partial file already parsed the
        // video SPS, and that detail reaches the presented stream only
        // because the partial quick file is kept.
        let clip =
            clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0]), (0x1100, 0x81, [0x61, b'e', b'n', b'g'])]);
        let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011), (0x81, 0x1100)], &[1, 2, 3], &[46, 47, 48]);
        let report = open_resilient(
            &tripping_disc_with(clip.clone(), m2ts.clone(), Some(DATA_SIZE)),
            ScanMode::Full,
        )
        .expect("resilient scan continues");
        assert_eq!(report.errors.len(), 2);
        let pl = report.bdrom.playlists.first().unwrap();
        assert!(pl.streams.first().unwrap().description.contains("High Profile 4.1"));
        assert!(pl.chapters.first().unwrap().avg_rate > 0.0);

        // Switched off, the same damage loses the quick pass's codec detail
        // with everything else: the presented video keeps only its clip-info
        // description.
        let off = BdRom::open_resilient(
            &tripping_disc_with(clip, m2ts, Some(DATA_SIZE)),
            ScanMode::Full,
            ScanOptions { keep_partial: false, ..ScanOptions::default() },
            None,
            ScanObservers::new(&mut |_| {}, &AtomicBool::new(false)),
        )
        .expect("resilient scan continues");
        assert_eq!(off.errors.len(), 2);
        let off_pl = off.bdrom.playlists.first().unwrap();
        assert!(!off_pl.streams.first().unwrap().description.contains("High Profile 4.1"));
    }

    #[test]
    fn open_resilient_records_one_warning_per_pass_on_head_damage() {
        // A reader that dies on its first byte: the quick pass and the full
        // pass each open the file and each trip, so ONE failure is recorded
        // per pass — two `WARNING` lines for the same file, deliberately
        // undeduplicated.
        let report = open_resilient(&tripping_disc(vec![0_u8; 400], Some(0)), ScanMode::Full)
            .expect("resilient scan continues");
        assert_eq!(report.errors.len(), 2);
        for recorded in &report.errors {
            assert_eq!(
                (recorded.stage, recorded.file.as_str()),
                (ScanStage::StreamFile, "00000.m2ts")
            );
        }
        // Nothing was demuxed, so every measurement is zero — but the open
        // succeeded and the structure is fully listed.
        let pl = report.bdrom.playlists.first().unwrap();
        assert_eq!(pl.chapters.len(), 2);
        assert_eq!(pl.chapters.first().unwrap().avg_rate.to_bits(), 0.0_f64.to_bits());
        assert!(pl.clips.first().unwrap().streams.is_empty());
    }

    #[test]
    fn open_strict_aborts_wholesale_on_a_stream_read_error() {
        // The strict open propagates the first read failure — no partial
        // state, no report — whatever `keep_partial` would have said.
        assert!(open(&tripping_disc(vec![0_u8; 400], Some(0)), ScanMode::Full).is_err());
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(24))]
        /// Tripping the stream reader at an arbitrary byte offset never
        /// panics or hangs the resilient scan, and the chapter table keeps
        /// its shape: one row per mark, each with its mark's own time and
        /// length, rates finite and non-negative. (24 cases — each scans a
        /// two-chunk fixture just past `DATA_SIZE` twice; the range runs
        /// beyond the fixture so some cases never trip, and the
        /// deterministic boundary offsets 0 and `DATA_SIZE` are pinned by
        /// the tests above.)
        #[test]
        fn a_tripped_reader_yields_a_total_scan_with_one_chapter_row_per_mark(
            serve in 0_usize..crate::bdrom::m2ts::DATA_SIZE.saturating_add(10_000),
        ) {
            let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47]);
            let report =
                open_resilient(&tripping_disc(m2ts, Some(serve)), ScanMode::Full)
                    .expect("the resilient scan is total");
            let pl = report.bdrom.playlists.first().unwrap();
            prop_assert_eq!(pl.chapters.len(), 2);
            let first = pl.chapters.first().unwrap();
            prop_assert_eq!(first.time_in.to_bits(), 0.0_f64.to_bits());
            prop_assert_eq!(first.length.to_bits(), 45.0_f64.to_bits());
            let second = pl.chapters.get(1).unwrap();
            prop_assert_eq!(second.time_in.to_bits(), 45.0_f64.to_bits());
            prop_assert_eq!(second.length.to_bits(), 55.0_f64.to_bits());
            for row in &pl.chapters {
                prop_assert!(row.avg_rate.is_finite() && row.avg_rate >= 0.0);
                prop_assert!(row.max_1sec_rate.is_finite() && row.max_1sec_rate >= 0.0);
            }
        }
    }

    // ── subset selection over damaged media ─────────────────────────────────

    #[test]
    fn a_narrowed_selection_leaves_the_defective_playlists_rows_unchanged() {
        use crate::bdrom::m2ts::DATA_SIZE;
        // Three playlists over DISTINCT clips — no clip is shared, so nothing
        // the demux writes in place reaches another playlist — and the first
        // clip's reader dies at the read-chunk boundary.
        let video = || clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let m2ts = || two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47, 48]);
        let disc = tripping_disc_of(
            &[
                MockClip { stem: "00000", clip: video(), m2ts: m2ts(), serve: Some(DATA_SIZE) },
                MockClip { stem: "00001", clip: video(), m2ts: m2ts(), serve: None },
                MockClip { stem: "00002", clip: video(), m2ts: m2ts(), serve: None },
            ],
            &[("00000", &["00000"]), ("00001", &["00001"]), ("00002", &["00002"])],
        );
        let scan = |selection: Option<&BTreeSet<String>>| {
            BdRom::open_resilient(
                &disc,
                ScanMode::Full,
                ScanOptions::default(),
                selection,
                ScanObservers::new(&mut |_| {}, &never_cancel()),
            )
            .expect("resilient scan continues")
        };
        let selection = |names: &[&str]| -> BTreeSet<String> {
            names.iter().map(|name| (*name).to_owned()).collect()
        };
        let playlist = |report: &ScanReport, name: &str| -> PlaylistSummary {
            report
                .bdrom
                .playlists
                .iter()
                .find(|summary| summary.name == name)
                .expect("every playlist is summarised")
                .clone()
        };
        // The same damaged disc opened three ways: no selection at all, a
        // selection naming every clip, and a true subset that keeps the
        // defective playlist and one other while deselecting the third.
        let whole = scan(None);
        let every = scan(Some(&selection(&["00000.M2TS", "00001.M2TS", "00002.M2TS"])));
        let subset = scan(Some(&selection(&["00000.M2TS", "00001.M2TS"])));

        // The defective playlist is measured-then-damaged, not merely absent:
        // chapter 1 carries the head frames' rate, chapter 2 is the zero row
        // the death at the boundary leaves behind.
        let defective = playlist(&whole, "00000.MPLS");
        assert!(defective.chapters.first().unwrap().avg_rate > 0.0);
        assert_eq!(defective.chapters.get(1).unwrap().avg_rate.to_bits(), 0.0_f64.to_bits());
        assert!(defective.clips.first().unwrap().payload_bytes > 0);

        // The three-way assertion: a selected playlist's own rows are a pure
        // function of its own clips, so narrowing the selection changes
        // nothing about them — chapter rows, FILES rows, presented streams,
        // and the playlist totals are identical across all three opens…
        assert_eq!(playlist(&every, "00000.MPLS"), defective);
        assert_eq!(playlist(&subset, "00000.MPLS"), defective);
        // …and so is the failure the damage records.
        for report in [&whole, &every, &subset] {
            assert_eq!(report.errors.len(), 1);
            let recorded = report.errors.first().unwrap();
            assert_eq!(
                (recorded.stage, recorded.file.as_str()),
                (ScanStage::StreamFile, "00000.m2ts")
            );
        }

        // What the narrowing DOES change, so the assertion above is over a
        // genuinely narrowed scan rather than a selection the scan ignored:
        // the deselected third playlist is never read and keeps only its
        // metadata, while the second selected one measures exactly as it does
        // in the two full opens.
        let third = playlist(&whole, "00002.MPLS");
        assert!(third.chapters.first().unwrap().avg_rate > 0.0);
        assert_eq!(playlist(&every, "00002.MPLS"), third);
        let deselected = playlist(&subset, "00002.MPLS");
        assert_eq!(deselected.chapters.first().unwrap().avg_rate.to_bits(), 0.0_f64.to_bits());
        assert!(deselected.clips.first().unwrap().streams.is_empty());
        assert_eq!(playlist(&subset, "00001.MPLS"), playlist(&whole, "00001.MPLS"));
    }

    #[test]
    fn an_earlier_clip_without_diagnostics_shifts_the_chapter_rows_past_the_boundary() {
        // A two-clip playlist (100 s per clip, 200 s total; chapter marks at
        // 0 s and 45 s of the first clip) where one clip's reader dies on its
        // first byte — that clip contributes no diagnostics at all — and the
        // other carries frames at 1/2/3 s. Each diagnostics entry closes at
        // the NEXT frame's timestamp, so the surviving clip contributes two
        // 100-byte entries, at clip seconds 2 and 3. Which of the two clips is
        // damaged decides the chapter table's shape.
        let video = || clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let frames = || two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[]);
        let rows = |first: Option<usize>, second: Option<usize>| {
            let disc = tripping_disc_of(
                &[
                    MockClip { stem: "00000", clip: video(), m2ts: frames(), serve: first },
                    MockClip { stem: "00001", clip: video(), m2ts: frames(), serve: second },
                ],
                &[("00000", &["00000", "00001"])],
            );
            open_resilient(&disc, ScanMode::Full)
                .expect("resilient scan continues")
                .bdrom
                .playlists
                .first()
                .unwrap()
                .chapters
                .clone()
        };

        // The EARLIER clip missing: the walk steps over it without advancing
        // the playlist position, so the surviving clip's first entry — at
        // playlist second 102, far past the 45 s mark — is what closes
        // chapter 1, and its second entry closes chapter 2. Both rows measure
        // an entry; the accounting is shifted across the boundary, not lost.
        let shifted = rows(Some(0), None);
        assert_eq!(shifted.len(), 2);
        let first = shifted.first().unwrap();
        assert!(first.avg_rate > 0.0);
        assert_eq!(first.max_frame_size.to_bits(), 100.0_f64.to_bits());
        assert_eq!(first.max_frame_time.to_bits(), 102.0_f64.to_bits());
        let second = shifted.get(1).unwrap();
        assert!(second.avg_rate > 0.0);
        assert_eq!(second.max_frame_time.to_bits(), 103.0_f64.to_bits());

        // The mirror image — the LATER clip missing — is the collapse the
        // partial-retention tests pin instead: both entries land in chapter 1,
        // inside its own span, and chapter 2 is a zero row.
        let collapsed = rows(None, Some(0));
        let first = collapsed.first().unwrap();
        assert!(
            first.avg_rate > shifted.first().unwrap().avg_rate,
            "chapter 1 absorbs both entries here, only the shifted one there"
        );
        assert_eq!(first.max_frame_time.to_bits(), 2.0_f64.to_bits());
        let second = collapsed.get(1).unwrap();
        assert_eq!(second.avg_rate.to_bits(), 0.0_f64.to_bits());
        assert_eq!(second.max_frame_size.to_bits(), 0.0_f64.to_bits());
    }

    // ── the cross-surface damaged-disc golden ───────────────────────────────

    /// The first unreadable byte of `00011.M2TS` in the damaged-disc pin.
    ///
    /// 5 MiB is the browser build's read-chunk size
    /// ([`m2ts::DATA_SIZE`](crate::bdrom::m2ts::DATA_SIZE) under
    /// `target_arch = "wasm32"`) and exactly 20 native chunks of its 256 KiB, so
    /// it is a chunk boundary on BOTH builds: each keeps the bytes below it and
    /// loses every byte above, whatever its chunk size. Any other offset splits
    /// the two — the browser voids its whole 5 MiB chunk while the native scan
    /// keeps another 256 KiB chunk of it — and the two sides would then render
    /// different numbers from the same damage for a reason that is not a defect.
    /// The offset also sits inside `00011.M2TS`'s second chunk (the clip is
    /// 6,297,600 bytes), which is what makes the failure a truncation rather
    /// than a voided file: the codec pass finishes well below it and only the
    /// measured pass dies, so the file is named ONCE in the `WARNING:` block.
    const DAMAGED_FAULT_AT: usize = 5_242_880;

    /// The committed damaged-disc golden — the report both surfaces pin.
    ///
    /// Beside the healthy goldens, one crate over, so the browser harness
    /// (`crates/bdinfo-rs-wasm/web/test/faults.node.mjs`) reads the very same
    /// committed file this test does. The golden directory's `*.txt -text`
    /// entry in `.gitattributes` keeps its CRLF bytes through a checkout.
    fn damaged_disc_golden() -> String {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../bdinfo-rs/tests/fixtures/golden/damaged-multiplaylist.txt");
        std::fs::read_to_string(path).expect("read the damaged-disc golden")
    }

    /// The report with every `WARNING:` line's reason replaced by `<reason>`.
    ///
    /// The block renders `{file}⇥{reason}`, and the reason is each surface's
    /// own error text — [`BdError`]'s `io error: {0}` for a native read, the
    /// value the browser's `FileReaderSync` threw for a web one — so it is the
    /// one field two surfaces cannot be expected to share for the same fault.
    /// The file list beside it is what they must agree on. Tabs appear nowhere
    /// else in the report, which is what makes the per-line rule safe over the
    /// whole text.
    fn normalize_warning_reasons(report: &str) -> String {
        report
            .split("\r\n")
            .map(|line| {
                line.split_once('\t')
                    .map_or_else(|| line.to_owned(), |(file, _)| format!("{file}\t<reason>"))
            })
            .collect::<Vec<String>>()
            .join("\r\n")
    }

    /// The committed fixture disc `name` as a mock tree whose stream files can
    /// fail: `faults` names a file (case-insensitively) and the byte count its
    /// reader serves before erroring, as [`MockFile::fail_read_at`].
    ///
    /// The bytes are the real fixture's, read from disk; only the reader is
    /// synthetic, so no damaged copy of a disc is committed.
    fn fixture_tree(name: &str, faults: &[(&str, usize)]) -> MockDir {
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../bdinfo-rs/tests/fixtures")
            .join(name);
        load_fixture_dir(&root, name, faults)
    }

    /// One directory of a [`fixture_tree`], recursing into its subdirectories.
    ///
    /// Entries are sorted by name: `read_dir` order is filesystem-defined, and
    /// listing order reaches the report (the disc's playlist and clip order).
    fn load_fixture_dir(path: &std::path::Path, name: &str, faults: &[(&str, usize)]) -> MockDir {
        let trip = Trip::new(usize::MAX);
        let mut entries: Vec<PathBuf> = std::fs::read_dir(path)
            .expect("list the fixture directory")
            .map(|entry| entry.expect("read the directory entry").path())
            .collect();
        entries.sort();
        let mut dirs = Vec::new();
        let mut files = Vec::new();
        for entry in entries {
            let entry_name = entry
                .file_name()
                .expect("a fixture entry has a name")
                .to_string_lossy()
                .into_owned();
            if entry.is_dir() {
                dirs.push(load_fixture_dir(&entry, &entry_name, faults));
            } else {
                files.push(MockFile {
                    extension: extension_of_name(&entry_name),
                    bytes: std::fs::read(&entry).expect("read the fixture file"),
                    trip: trip.clone(),
                    fail_read_at: faults
                        .iter()
                        .find(|(file, _)| file.eq_ignore_ascii_case(&entry_name))
                        .map(|&(_, serve)| serve),
                    reads: None,
                    name: entry_name,
                });
            }
        }
        MockDir { name: name.to_owned(), dirs, files, trip }
    }

    #[test]
    fn the_damaged_disc_report_matches_the_golden_the_browser_pins_too() {
        // The core half of the cross-surface pin. The browser half scans the
        // SAME committed disc, damaged at the SAME byte of the same stream
        // file, and compares the SAME committed golden — so a change that moves
        // damaged-disc output on either side reddens that side's own gate,
        // whichever gate the diff selected. (The browser harness runs only in
        // the wasm gate, which a core-only diff never selects.)
        //
        // Characterization, not judgement: the golden is what current master
        // renders, including anything a later ruling may decide is wrong.
        let disc = fixture_tree("MultiPlaylist", &[("00011.m2ts", DAMAGED_FAULT_AT)]);
        let report = open_resilient(&disc, ScanMode::Full).expect("resilient scan continues");
        let rendered = crate::report::text::render(&report.bdrom, &report.errors);

        // The damage is one truncation, so exactly one failure is recorded —
        // the shape the golden's single WARNING line carries.
        assert_eq!(report.errors.len(), 1);
        let recorded = report.errors.first().expect("the recorded failure");
        assert_eq!((recorded.stage, recorded.file.as_str()), (ScanStage::StreamFile, "00011.m2ts"));

        assert_eq!(normalize_warning_reasons(&rendered), damaged_disc_golden());
    }

    // ── 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,
                measured: None,
                done: 0,
                total: 100,
                cancel: &AtomicBool::new(false),
            };
            progress.advance("A.M2TS", 30);
            // A heartbeat reports without moving the count.
            progress.heartbeat("A.M2TS");
            // 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(), 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,
                measured: None,
                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)]);
    }

    #[test]
    fn a_counting_reader_heartbeats_before_every_read_and_advances_after() {
        // Two reads through the counting seam: one serving bytes, one at EOF.
        // Each is bracketed by a heartbeat (same count) and an advance, so a
        // consumer's last event before a blocking read names the file being
        // read — the signal a stalled read leaves behind.
        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,
                measured: None,
                done: 0,
                total: 5,
                cancel: &AtomicBool::new(false),
            };
            let mut reader = CountingReader {
                inner: Box::new(Cursor::new(vec![0_u8; 5])),
                name: "A.M2TS".to_owned(),
                progress: &mut progress,
            };
            let mut sink = [0_u8; 8];
            assert_eq!(reader.read(&mut sink).expect("serving read"), 5);
            assert_eq!(reader.read(&mut sink).expect("EOF read"), 0);
        }
        assert_eq!(
            events,
            [
                ("A.M2TS".to_owned(), 0, 5),
                ("A.M2TS".to_owned(), 5, 5),
                ("A.M2TS".to_owned(), 5, 5),
                ("A.M2TS".to_owned(), 5, 5),
            ]
        );
    }

    /// 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 an_observed_open_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
        // (a `Full` open's 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(
            &root,
            ScanMode::Full,
            ScanOptions::default(),
            None,
            ScanObservers::new(&mut collect, &never_cancel()),
        )
        .expect("scan with progress");
        assert_eq!(bd.playlists.len(), 2);
        assert!(!events.is_empty());
        // The pre-read heartbeat precedes the first byte: the pass's first
        // event reports a zero count, naming the file about to be read.
        assert_eq!(events.first().map(|(_, done, _)| *done), Some(0));
        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(
            &root,
            ScanMode::Full,
            ScanOptions::default(),
            Some(&selected),
            ScanObservers::new(&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(
            &root,
            ScanMode::Full,
            ScanOptions::default(),
            Some(&selected),
            ScanObservers::new(&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(
                &root,
                ScanMode::Metadata,
                ScanOptions::default(),
                None,
                ScanObservers::new(&mut observe, &never_cancel()),
            )
            .expect("metadata-only scan"),
        );
        assert!(!fired);
    }

    #[test]
    fn a_codecs_open_reports_the_quick_pass_a_full_open_leaves_silent() {
        use crate::bdrom::m2ts::DATA_SIZE;
        // One stream file just past a full-pass chunk whose codec detail is
        // complete in its first packets: the quick pass exits early inside
        // that first chunk while the full pass reads to EOF, so which pass a
        // trail came from is visible in where its count stops climbing.
        let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47, 48]);
        let size = u64::try_from(m2ts.len()).expect("the fixture is far under u64::MAX");
        let chunk = u64::try_from(DATA_SIZE).expect("the read chunk is far under u64::MAX");
        let disc = tripping_disc(m2ts, None);
        let trail = |mode| {
            let mut events: Vec<(String, u64, u64)> = Vec::new();
            let mut collect =
                |p: ScanProgress<'_>| events.push((p.file.to_owned(), p.done, p.total));
            drop(
                BdRom::open(
                    &disc,
                    mode,
                    ScanOptions::default(),
                    None,
                    ScanObservers::new(&mut collect, &never_cancel()),
                )
                .expect("the healthy mock disc scans"),
            );
            events
        };
        let climbs = |events: &[(String, u64, u64)]| {
            events.windows(2).all(|pair| {
                pair.first().is_none_or(|(_, a, _)| pair.get(1).is_none_or(|(_, b, _)| a <= b))
            })
        };

        // `Codecs`: the quick pass reports, against the same whole-source
        // budget the full pass would have used.
        let codecs = trail(ScanMode::Codecs);
        assert!(codecs.iter().all(|(file, _, total)| file == "00000.M2TS" && *total == size));
        assert_eq!(codecs.first().map(|(_, done, _)| *done), Some(0));
        assert!(climbs(&codecs), "the count never goes backwards");
        // The pass stops reading long before EOF — its last read event is
        // still inside the first full-pass chunk…
        let last_read = codecs.iter().rev().nth(1).map(|(_, done, _)| *done);
        assert!(last_read.is_some_and(|done| done < chunk), "the quick pass exits early");
        // …and the file-boundary snap is what carries the display to 100%.
        assert_eq!(codecs.last().map(|(_, done, _)| *done), Some(size));

        // `Full`: the quick pass ahead of the measurement pass stays silent.
        // Its first read would be a 16 KiB quick chunk followed by its own
        // snap to 100%; the trail instead opens on the measurement pass's
        // pre-open and pre-read heartbeats (both count 0), then a full-pass
        // chunk, and climbs to 100% once, so nothing of the quick pass
        // reaches the caller.
        let full = trail(ScanMode::Full);
        assert!(full.iter().all(|(file, _, total)| file == "00000.M2TS" && *total == size));
        assert_eq!(full.first().map(|(_, done, _)| *done), Some(0));
        assert_eq!(full.get(1).map(|(_, done, _)| *done), Some(0));
        assert_eq!(full.get(2).map(|(_, done, _)| *done), Some(chunk));
        assert!(climbs(&full), "the count never restarts");
        assert_eq!(full.last().map(|(_, done, _)| *done), Some(size));
    }

    // ── the measured-snapshot observer ───────────────────────────────────────

    /// A small demuxable video-only `*.m2ts`: PAT, a PMT declaring AVC on PID
    /// `0x1011`, then one video frame per entry of `seconds` (its
    /// presentation time). Every frame closes the previous frame's window, so
    /// the demux attributes packets to the clip as it reads.
    fn video_m2ts(seconds: &[u64]) -> Vec<u8> {
        let mut m2ts = packet(0, true, &pat_payload(0x0100));
        m2ts.extend(packet(0x0100, true, &pmt_payload(&[(0x1B, 0x1011)])));
        for &second in seconds {
            let ticks = second.wrapping_mul(90_000);
            m2ts.extend(packet(0x1011, true, &pes_dts(0xE0, ticks, ticks, &sps_payload())));
        }
        m2ts
    }

    /// A three-playlist mock disc over three clips of different lengths, one
    /// of them shared: `00000.MPLS` plays `00011`, `00001.MPLS` plays `00022`,
    /// and `00002.MPLS` plays `00033` then `00011`. The stream directory holds
    /// them in `00011`, `00022`, `00033` order, which is the order the scan
    /// reads them in, so the shared clip is measured first and the playlist
    /// that also plays `00033` only completes at the last file.
    fn shared_clip_disc() -> MockDir {
        let clip = || clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        tripping_disc_of(
            &[
                MockClip { stem: "00011", clip: clip(), m2ts: video_m2ts(&[1, 2, 3]), serve: None },
                MockClip { stem: "00022", clip: clip(), m2ts: video_m2ts(&[1, 2]), serve: None },
                MockClip { stem: "00033", clip: clip(), m2ts: video_m2ts(&[1]), serve: None },
            ],
            &[("00000", &["00011"]), ("00001", &["00022"]), ("00002", &["00033", "00011"])],
        )
    }

    /// Every measured snapshot a `mode` open of `disc` hands out, alongside the
    /// disc it scanned.
    fn observed_scan(disc: &MockDir, mode: ScanMode) -> (BdRom, Vec<MeasuredSnapshot>) {
        let mut snapshots: Vec<MeasuredSnapshot> = Vec::new();
        let bd = {
            let mut watch = |snapshot: MeasuredSnapshot| snapshots.push(snapshot);
            let mut collect = |_: ScanProgress<'_>| {};
            BdRom::open(
                disc,
                mode,
                ScanOptions::default(),
                None,
                ScanObservers::new(&mut collect, &never_cancel()).with_measured(&mut watch),
            )
            .expect("the healthy mock disc scans")
        };
        (bd, snapshots)
    }

    #[test]
    fn a_measured_observer_sees_each_files_chunks_and_then_its_boundary() {
        let (_, snapshots) = observed_scan(&shared_clip_disc(), ScanMode::Full);
        // Per stream file, in read order: one snapshot per parsed chunk (each
        // of these files fits one read chunk) and then the file-boundary
        // snapshot. Both passes read all three files, so a quick pass that
        // reported would double this list.
        let files: Vec<&str> = snapshots.iter().map(|s| s.file.as_str()).collect();
        assert_eq!(
            files,
            ["00011.M2TS", "00011.M2TS", "00022.M2TS", "00022.M2TS", "00033.M2TS", "00033.M2TS"]
        );
        // Each covers exactly the playlists that sequence its file.
        let covered: Vec<Vec<&str>> = snapshots
            .iter()
            .map(|s| s.playlists.iter().map(|p| p.name.as_str()).collect())
            .collect();
        let per_file = [vec!["00000.MPLS", "00002.MPLS"], vec!["00001.MPLS"], vec!["00002.MPLS"]];
        let expected: Vec<Vec<&str>> =
            per_file.iter().flat_map(|playlists| [playlists.clone(), playlists.clone()]).collect();
        assert_eq!(covered, expected);
    }

    #[test]
    fn measured_snapshots_climb_and_end_on_the_finished_scans_numbers() {
        let (bd, snapshots) = observed_scan(&shared_clip_disc(), ScanMode::Full);
        // Nothing a playlist reports ever shrinks: the pass only adds to the
        // tallies, so a display patching cells from these never regresses one.
        let mut seen: BTreeMap<&str, u64> = BTreeMap::new();
        for playlist in snapshots.iter().flat_map(|s| &s.playlists) {
            let previous = seen.insert(&playlist.name, playlist.measured_bytes).unwrap_or(0);
            assert!(
                playlist.measured_bytes >= previous,
                "{} fell from {previous} to {}",
                playlist.name,
                playlist.measured_bytes
            );
        }
        // The last file's snapshot is the whole scan's answer for the playlist
        // it completes: bytes, per-clip rows and per-stream rates all land on
        // the summary the scan returns.
        let last = snapshots.last().expect("the pass snapshots its last file");
        let live = last.playlists.first().expect("the last file completes 00002.MPLS");
        let summary =
            bd.playlists.iter().find(|p| p.name == live.name).expect("the playlist is summarised");
        assert!(live.measured_bytes > 0, "the fixture demuxes packets");
        assert_eq!(live.measured_bytes, summary.total_angle_packet_size());
        let rows: Vec<(&str, i32, u64)> = summary
            .clips
            .iter()
            .map(|clip| (clip.name.as_str(), clip.angle_index, clip.packet_size()))
            .collect();
        assert_eq!(
            live.clips
                .iter()
                .map(|clip| (clip.name.as_str(), clip.angle_index, clip.measured_bytes))
                .collect::<Vec<_>>(),
            rows
        );
        let rates: Vec<(Pid, usize, i64, i64)> = summary
            .streams
            .iter()
            .map(|stream| (stream.pid, stream.angle_index, stream.bitrate, stream.active_bitrate))
            .collect();
        assert!(rates.iter().any(|&(_, _, bitrate, _)| bitrate > 0), "the video row is measured");
        assert_eq!(
            live.streams
                .iter()
                .map(|stream| {
                    (stream.pid, stream.angle_index, stream.bitrate, stream.active_bitrate)
                })
                .collect::<Vec<_>>(),
            rates
        );
    }

    #[test]
    fn a_scan_only_snapshots_when_it_measures_and_scans_the_same_either_way() {
        let disc = shared_clip_disc();
        // The bounded codec pass is not a measurement pass: it has no observer
        // to report to, and the tallies it leaves are discarded anyway.
        let (codecs, none) = observed_scan(&disc, ScanMode::Codecs);
        assert!(none.is_empty(), "the quick pass reports no measured tallies");
        assert!(codecs.playlists.iter().all(|p| p.total_angle_packet_size() == 0));
        // Installing an observer changes nothing about what the scan produces.
        let (observed, snapshots) = observed_scan(&disc, ScanMode::Full);
        assert_eq!(snapshots.len(), 6);
        let plain = open(&disc, ScanMode::Full).expect("the healthy mock disc scans");
        assert_eq!(observed, plain);
    }

    #[test]
    fn scan_observers_carry_both_callbacks_and_print_what_they_watch() {
        let disc = shared_clip_disc();
        let cancel = AtomicBool::new(false);
        let events = AtomicUsize::new(0);
        let snapshots = AtomicUsize::new(0);
        let mut collect = |_: ScanProgress<'_>| {
            events.fetch_add(1, Ordering::Relaxed);
        };
        let mut watch = |_: MeasuredSnapshot| {
            snapshots.fetch_add(1, Ordering::Relaxed);
        };
        // A bundle prints what a reader can act on, its two callbacks being
        // closures with nothing to print.
        assert_eq!(
            format!("{:?}", ScanObservers::new(&mut collect, &cancel)),
            "ScanObservers { progress: true, measured: false, cancelled: false, .. }"
        );
        // The watch-nothing bundle: no observers, and no flag to read, which
        // prints as the scan nothing can stop.
        assert_eq!(
            format!("{:?}", ScanObservers::none()),
            "ScanObservers { progress: false, measured: false, cancelled: false, .. }"
        );
        // Both callbacks reach the scan through the bundle.
        drop(
            BdRom::open(
                &disc,
                ScanMode::Full,
                ScanOptions::default(),
                None,
                ScanObservers::new(&mut collect, &cancel).with_measured(&mut watch),
            )
            .expect("the healthy mock disc scans"),
        );
        assert!(events.load(Ordering::Relaxed) > 0, "the progress callback fired");
        assert_eq!(
            snapshots.load(Ordering::Relaxed),
            6,
            "one snapshot per parsed chunk and one per stream file"
        );
        // A flag already set prints as the scan it would stop.
        cancel.store(true, Ordering::Relaxed);
        assert_eq!(
            format!("{:?}", ScanObservers::new(&mut collect, &cancel).with_measured(&mut watch)),
            "ScanObservers { progress: true, measured: true, cancelled: true, .. }"
        );
    }

    #[test]
    fn a_cancelled_measurement_pass_keeps_only_the_chunks_it_parsed() {
        let disc = shared_clip_disc();
        let cancel = AtomicBool::new(false);
        let snapshots = AtomicUsize::new(0);
        let mut watch = |_: MeasuredSnapshot| {
            snapshots.fetch_add(1, Ordering::Relaxed);
        };
        // Control: the same observer over the same disc with nothing armed,
        // so what the cancelled run below loses is most of the pass, not a
        // fixture that never reported.
        let mut quiet = |_: ScanProgress<'_>| {};
        drop(
            BdRom::open(
                &disc,
                ScanMode::Full,
                ScanOptions::default(),
                None,
                ScanObservers::new(&mut quiet, &cancel).with_measured(&mut watch),
            )
            .expect("the healthy mock disc scans"),
        );
        assert_eq!(snapshots.swap(0, Ordering::Relaxed), 6);
        // Armed by the measurement pass's first counted read (the first event
        // whose count advanced — the pre-open and pre-read heartbeats report
        // count 0 and must not arm, or the flag's pre-read poll would abort
        // before any chunk is parsed). The armed chunk is already parsed, so
        // the observer keeps its snapshot; the cancelled file's boundary
        // snapshot never fires, and neither does any later file's.
        let mut arm = |p: ScanProgress<'_>| {
            if p.done > 0 {
                cancel.store(true, Ordering::Relaxed);
            }
        };
        let err = BdRom::open(
            &disc,
            ScanMode::Full,
            ScanOptions::default(),
            None,
            ScanObservers::new(&mut arm, &cancel).with_measured(&mut watch),
        )
        .expect_err("the armed flag aborts the scan");
        assert_eq!(err.to_string(), "scan cancelled");
        assert_eq!(snapshots.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn a_file_spanning_chunks_snapshots_inside_the_file_and_at_its_boundary() {
        // A stream just past one read chunk: the demux parses two chunks, so
        // the observer sees the tallies move INSIDE the file — the cadence a
        // display needs on a real disc, where one file is hours of reading —
        // and then the file boundary settles them on the summary's numbers.
        let m2ts = two_chunk_m2ts(&[(0x1B, 0x1011)], &[1, 2, 3], &[46, 47, 48]);
        let (bd, snapshots) = observed_scan(&tripping_disc(m2ts, None), ScanMode::Full);
        assert_eq!(snapshots.len(), 3, "two chunk snapshots, then the boundary one");
        assert!(snapshots.iter().all(|s| s.file == "00000.M2TS"));
        let tallies: Vec<u64> = snapshots
            .iter()
            .map(|s| s.playlists.first().expect("the playlist plays the clip").measured_bytes)
            .collect();
        let [first, second, boundary]: [u64; 3] =
            tallies.try_into().expect("two chunk snapshots and the boundary one");
        // The second chunk's snapshot strictly exceeds the first — the
        // intra-file movement this cadence exists for; the boundary snapshot
        // adds no bytes here (this stream's last window was already flushed by
        // the tail frames), it settles the rates.
        assert!(first > 0, "the first chunk's snapshot already tallies");
        assert!(first < second, "the tallies climb between the chunks");
        assert!(second <= boundary, "the boundary snapshot never regresses");
        // The boundary snapshot's total is the finished scan's answer.
        let summary = bd.playlists.first().expect("the playlist is summarised");
        assert_eq!(boundary, summary.total_angle_packet_size());
    }

    // ── 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(
                &root,
                ScanMode::Full,
                ScanOptions::default(),
                None,
                ScanObservers::new(&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(
            &root,
            ScanMode::Full,
            ScanOptions::default(),
            None,
            ScanObservers::new(&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");
        // The in-flight chunk still completes (the flag is polled per chunk),
        // emitting at most a heartbeat + advance pair for its serving read
        // and another for its EOF read; nothing follows.
        assert!(events.len() <= 4, "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(
            &root,
            ScanMode::Full,
            ScanOptions::default(),
            None,
            ScanObservers::new(&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(
                &root,
                mode,
                ScanOptions::default(),
                None,
                ScanObservers::new(&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(
            &root,
            ScanMode::Full,
            ScanOptions::default(),
            None,
            ScanObservers::new(&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(
            &root,
            ScanMode::Metadata,
            ScanOptions::default(),
            None,
            ScanObservers::new(&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_at: None,
            reads: None,
        };
        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, measured: None, 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) },
            true,
            false,
            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 = 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 = 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 = 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_at: Some(0),
            reads: None,
        };
        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 = 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!(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 = 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;
        let mut fail_open = 0_usize;
        for fail_at in 0..total {
            let trip = Trip::new(fail_at);
            // An `Err` is the fatal BDMV/CLIPINF/PLAYLIST block; a completed scan
            // must either record the failure or — only in the fail-open AACS
            // probe — absorb it with the scan left identical to the clean one.
            if let Ok(report) = open_resilient(&mock_disc(&trip), ScanMode::Full) {
                if report.errors.is_empty() {
                    assert_eq!(
                        report.bdrom, clean.bdrom,
                        "io failure at op {fail_at} was swallowed and altered the scan"
                    );
                    fail_open = fail_open.saturating_add(1);
                } else {
                    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}");
        // Exactly the AACS probe's root listing (no `AACS` directory here, so
        // the probe short-circuits after one op).
        assert_eq!(fail_open, 1);
    }

    #[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_at: Some(0),
            reads: None,
        };
        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);
    }

    /// A reader that never reaches EOF — the in-process analogue of a `.iso`
    /// file entry whose not-recorded extents serve unlimited zeros without the
    /// image storing them.
    struct EndlessReader;

    impl Read for EndlessReader {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            buf.fill(0);
            Ok(buf.len())
        }
    }

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

    /// A file that claims `len` bytes and yields them forever.
    struct EndlessFile {
        name: String,
        extension: String,
        len: u64,
    }

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

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

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

        fn length(&self) -> u64 {
            self.len
        }

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

        fn open_read(&self) -> io::Result<Box<dyn ReadSeek>> {
            Ok(Box::new(EndlessReader))
        }

        fn open_text(&self) -> io::Result<Box<dyn BufRead>> {
            Ok(Box::new(BufReader::new(EndlessReader)))
        }
    }

    #[test]
    fn read_file_capped_accepts_a_file_sitting_exactly_on_the_cap() {
        let file = MockFile {
            name: "00000.MPLS".to_owned(),
            extension: ".mpls".to_owned(),
            bytes: vec![7; 8],
            trip: Trip::new(usize::MAX),
            fail_read_at: None,
            reads: None,
        };
        // Exactly `cap` bytes is legal — only the byte *past* the cap is not.
        assert_eq!(read_file_capped(&file, 8).expect("at the cap"), vec![7; 8]);
    }

    #[test]
    fn read_file_capped_rejects_a_file_one_byte_over_the_cap() {
        let file = MockFile {
            name: "00000.MPLS".to_owned(),
            extension: ".mpls".to_owned(),
            bytes: vec![7; 9],
            trip: Trip::new(usize::MAX),
            fail_read_at: None,
            reads: None,
        };
        let err = read_file_capped(&file, 8).expect_err("one byte over the cap");
        assert!(matches!(
            err,
            BdError::MetadataTooLarge { ref file, limit: 8 } if file == "00000.MPLS"
        ));
    }

    #[test]
    fn read_file_caps_an_endless_reader_instead_of_buffering_it_forever() {
        // A hostile `.iso` can declare any InformationLength over not-recorded
        // extents, which the UDF reader serves as zeros without the image
        // holding a byte of them; before the cap this read_to_end grew until
        // the allocator gave up. The declared length is deliberately absurd to
        // pin that the guard is the read cap, not a trusted size field.
        let file = EndlessFile {
            name: "00000.MPLS".to_owned(),
            extension: ".mpls".to_owned(),
            len: u64::MAX,
        };
        let err = read_file(&file).expect_err("an endless file is refused");
        assert!(matches!(
            err,
            BdError::MetadataTooLarge { limit, .. } if limit == MAX_METADATA_BYTES
        ));
        // The mock's remaining trait surface, so the mock itself stays covered.
        assert_eq!(file.name(), "00000.MPLS");
        assert_eq!(file.full_name(), "00000.MPLS");
        assert_eq!(file.extension(), ".mpls");
        assert_eq!(file.length(), u64::MAX);
        assert!(!file.is_dir());
        let mut one = [0xAA_u8; 1];
        file.open_text().expect("open_text").read_exact(&mut one).expect("read");
        assert_eq!(one, [0]);
        assert_eq!(file.open_read().expect("open_read").seek(SeekFrom::End(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_at: None,
            reads: None,
        };
        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 =
            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 =
            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_at: fail_read.then_some(0),
            reads: None,
        };
        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 = 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 =
            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 =
            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_at: None,
            reads: None,
        };
        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_at: None,
                reads: None,
            };
            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 =
            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 =
            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: "
        );
    }

    #[test]
    fn an_untagged_index_falls_back_to_the_backup_copy() {
        // The primary `index.bdmv` reads fine but is garbage. A tagged BACKUP
        // copy supplies the verdict (UHD here); an untagged or absent one leaves
        // the tolerated non-UHD. Every case warns about the primary exactly once.
        let clip = clpi(&[(0x1011, 0x1B, [0x62, 0x30, 0, 0])]);
        let make = |backup: Option<&[u8]>| {
            let mut files = vec![
                ("BDMV/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
                ("BDMV/CLIPINF/00000.clpi", clip.clone()),
                ("BDMV/index.bdmv", b"XXXXjunk".to_vec()),
                // A BACKUP directory is present in every case, so the missing
                // -counterpart case differs from the others only in its index.
                ("BDMV/BACKUP/PLAYLIST/00000.mpls", mpls("00000", 0, 4_500_000, &[])),
            ];
            if let Some(bytes) = backup {
                files.push(("BDMV/BACKUP/index.bdmv", bytes.to_vec()));
            }
            TempDisc::build(&[], &files)
        };
        let scan = |disc: &TempDisc| {
            open_resilient(&FsDir::new(disc.root.clone()), ScanMode::Metadata).expect("scans")
        };

        // A tagged BACKUP copy recovers the UHD verdict…
        let recovered = make(Some(b"INDX0300"));
        let report = scan(&recovered);
        assert!(report.bdrom.is_uhd, "UHD flag recovered from an intact BACKUP index");
        assert_eq!(report.errors.len(), 1, "the untagged primary warns exactly once");
        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");
        // …and a tagged non-UHD BACKUP copy answers non-UHD from the tag, not
        // from the fallback.
        assert!(!scan(&make(Some(b"INDX0200"))).bdrom.is_uhd);
        // Strict open builds no recovery pool, so it stays at the tolerated
        // non-UHD with no warning.
        assert!(!recovered.open().expect("strict tolerates an untagged index").is_uhd);

        // An untagged BACKUP copy recovers nothing, and is not warned about.
        let report = scan(&make(Some(b"YYYYjunk")));
        assert!(!report.bdrom.is_uhd);
        assert_eq!(report.errors.len(), 1);

        // Neither does a BACKUP directory holding no `index.bdmv`.
        let report = scan(&make(None));
        assert!(!report.bdrom.is_uhd);
        assert_eq!(report.errors.len(), 1);
    }

    #[test]
    fn an_unreadable_primary_index_recovered_as_garbage_stays_non_uhd() {
        // Both copies are damaged in different ways: the primary cannot be read
        // and the BACKUP copy is untagged. The recovered garbage is tolerated as
        // non-UHD, and only the primary's read failure is recorded.
        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_at: fail_read.then_some(0),
            reads: None,
        };
        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"XXXXjunk".to_vec(), false)]),
                ],
                vec![mk("index.bdmv", vec![0], true)], // primary unreadable
            )],
            vec![],
        );
        let report = open_resilient(&root, ScanMode::Metadata).expect("scans");
        assert!(!report.bdrom.is_uhd);
        assert_eq!(report.errors.len(), 2, "the unreadable primary, then its untagged stand-in");
        for err in &report.errors {
            assert_eq!((err.stage, err.file.as_str()), (ScanStage::Discovery, "index.bdmv"));
        }
    }
}