broadcast-hls 0.5.0

HLS (M3U8) playlist syntax (RFC 8216 / RFC 8216bis) — Media/Master Playlist parse + serialize, no_std.
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
#![doc = include_str!("../README.md")]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]
// Runnable examples, embedded so they render on docs.rs and stay in sync with
// the actual `examples/*.rs` files (shown, not compiled).
#![doc = "\n## Runnable examples\n"]
#![doc = "Run with `cargo run -p broadcast-hls --example <name>`.\n"]
#![doc = "\n### `build_playlist`\n\n```rust,ignore"]
#![doc = include_str!("../examples/build_playlist.rs")]
#![doc = "```\n\n### `parse_playlist`\n\n```rust,ignore"]
#![doc = include_str!("../examples/parse_playlist.rs")]
#![doc = "```"]

extern crate alloc;

mod error;

pub use error::{Error, Result};

use alloc::collections::BTreeMap;
use alloc::collections::BTreeSet;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use broadcast_common::hex::hex_encode;

/// A CENC protection scheme (`schm.scheme_type`) — ISO/IEC 23001-7 §4.
///
/// Re-exported from [`broadcast_common::cenc`], which holds the single
/// definition. CENC is *Common* Encryption — a container-independent scheme
/// identity — so it sits below both this crate and `transmux` (which owns the
/// ISOBMFF `schm`/`tenc`/`senc` boxes carrying it), rather than being defined
/// twice and converted at the boundary (issues #564, #878).
pub use broadcast_common::CencScheme;

// ---------------------------------------------------------------------------
// CENC/CBCS DRM signalling — ISO/IEC 23001-7 `cbcs` over CMAF-HLS (issue #564).
// ---------------------------------------------------------------------------

/// `KEYFORMAT` for the generic CENC identification (mirrors DASH's
/// `ContentProtection@schemeIdUri` for the "common" scheme —
/// ISO/IEC 23001-7 / `urn:mpeg:dash:mp4protection:2011`).
pub const CENC_KEYFORMAT: &str = "urn:mpeg:dash:mp4protection:2011";

/// `KEYFORMATVERSIONS` for [`CENC_KEYFORMAT`] (there is only version `"1"`).
pub const CENC_KEYFORMATVERSIONS: &str = "1";

/// Build the `#EXT-X-KEY` tag line for a CMAF track protected with either
/// Common Encryption scheme (RFC 8216bis §4.4.4.4): `cbcs` (AES-128 pattern
/// CBC) renders `METHOD=SAMPLE-AES`, `cenc` (AES-128 full-block CTR) renders
/// `METHOD=SAMPLE-AES-CTR`. In both cases `KEYFORMAT`/`KEYFORMATVERSIONS`
/// per [`CENC_KEYFORMAT`]/[`CENC_KEYFORMATVERSIONS`], plus the `KEYID`
/// attribute Apple's HLS CMAF/fMP4 authoring guidance uses to identify the
/// CENC key ID. Per §4.4.4.4, encryption with SAMPLE-AES-CTR is defined only
/// for fMP4 Media Segments and the `IV` attribute MUST NOT be present, so no
/// `IV` is ever emitted here.
///
/// `key_uri` is caller-supplied (a key-server URL, `skd://`, or `data:`
/// URI — no DRM logic lives here) and `kid` is the track's Track Encryption
/// Box default KID (`tenc.default_kid`, ISO/IEC 14496-12 §8.12.1 — the
/// `transmux` crate's `cenc::TrackEncryptionBox::default_kid` /
/// `media::TrackEncryption::tenc::default_kid`).
///
/// `Err` if `key_uri` cannot be represented as a quoted-string (`"`, CR or
/// LF — RFC 8216 §4.2; issue #1140 / audit r05-W10: a key-server URL
/// assembled from request data previously went straight into the tag
/// unvalidated, an attribute-list-injection vector).
pub fn cenc_ext_x_key(scheme: CencScheme, kid: &[u8; 16], key_uri: &str) -> Result<Option<String>> {
    // Audit BH-W1 (issue #1111): `cenc` used to return `None` on the claim
    // that "CTR is not a valid HLS METHOD". RFC 8216bis §4.4.4.4 defines
    // exactly that method — SAMPLE-AES-CTR — for `cenc`-protected fMP4.
    let method = match scheme {
        CencScheme::Cbcs => "SAMPLE-AES",
        CencScheme::Cenc => "SAMPLE-AES-CTR",
        // Other CencScheme values (the enum is #[non_exhaustive]) have no
        // defined HLS METHOD.
        _ => return Ok(None),
    };
    let mut s = format!("#EXT-X-KEY:METHOD={method}");
    let attrs = [
        (String::from("URI"), AttrValue::quoted(key_uri)?),
        (
            String::from("KEYFORMAT"),
            AttrValue::quoted(CENC_KEYFORMAT)?,
        ),
        (
            String::from("KEYFORMATVERSIONS"),
            AttrValue::quoted(CENC_KEYFORMATVERSIONS)?,
        ),
        (
            String::from("KEYID"),
            AttrValue::bare(format!("0x{}", hex_encode(kid)))?,
        ),
    ];
    render_attribute_list(&mut s, &attrs);
    Ok(Some(s))
}

/// A byte sub-range into a resource.
///
/// Shared by three tags that all use the same underlying notation:
/// - `#EXT-X-BYTERANGE:<n>[@<o>]` (RFC 8216bis §4.4.4.2) — [`MediaSegment::byte_range`].
/// - `#EXT-X-PART`'s `BYTERANGE="<n>[@<o>]"` attribute (RFC 8216bis
///   §4.4.4.9, "same format as the EXT-X-BYTERANGE tag") — [`PartSpec::byte_range`].
/// - `#EXT-X-MAP`'s `BYTERANGE="<n>@<o>"` attribute (RFC 8216bis §4.4.4.5) —
///   [`MapTag::byte_range`]. Unlike the other two, the spec says the offset
///   `o` is **REQUIRED** here (there is no "previous sub-range" to continue
///   from for an Initialization Section).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ByteRange {
    /// `n` — length of the sub-range in bytes.
    pub length: u64,
    /// `o` — byte offset of the sub-range from the start of the resource.
    /// `None` means "immediately following the previous Media/Partial
    /// Segment's sub-range of the same resource" (only meaningful for
    /// `EXT-X-BYTERANGE`/`EXT-X-PART`'s `BYTERANGE`; `EXT-X-MAP`'s
    /// `BYTERANGE` always carries `Some`).
    pub offset: Option<u64>,
}

impl ByteRange {
    /// Render the `<n>[@<o>]` wire notation (used inside a quoted attribute
    /// value for `PART`/`MAP`, or as the whole `#EXT-X-BYTERANGE` tag value).
    fn render(&self) -> String {
        match self.offset {
            Some(o) => format!("{}@{o}", self.length),
            None => format!("{}", self.length),
        }
    }

    /// Parse the `<n>[@<o>]` wire notation.
    fn parse(s: &str, line_no: usize, line: &str) -> Result<Self> {
        let mut split = s.splitn(2, '@');
        let n = split.next().unwrap_or("");
        let length = parse_decimal_int::<u64>(n, line_no, line, "BYTERANGE length")?;
        let offset = match split.next() {
            Some(o) => Some(parse_decimal_int::<u64>(
                o,
                line_no,
                line,
                "BYTERANGE offset",
            )?),
            None => None,
        };
        if let Some(o) = offset.filter(|&o| o.checked_add(length).is_none()) {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: format!("BYTERANGE offset ({o}) + length ({length}) overflows u64"),
            });
        }
        Ok(ByteRange { length, offset })
    }
}

/// The Media Initialization Section reference of `#EXT-X-MAP` (RFC 8216bis
/// §4.4.4.5) — see [`MediaSegment::map`] for carry-forward/dedup semantics.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MapTag {
    /// `URI` — the resource containing the Media Initialization Section
    /// (REQUIRED).
    pub uri: String,
    /// `BYTERANGE` — a sub-range of `uri` containing just the
    /// Initialization Section. `None` means the entire resource. The
    /// offset is always present when this is `Some` (spec requires it here,
    /// unlike [`MediaSegment::byte_range`]/[`PartSpec::byte_range`]).
    pub byte_range: Option<ByteRange>,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// `TYPE` attribute of `#EXT-X-PRELOAD-HINT` (RFC 8216bis §4.4.5.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum PreloadHintType {
    /// `PART` — the hinted resource is a Partial Segment.
    #[default]
    Part,
    /// `MAP` — the hinted resource is a Media Initialization Section.
    Map,
}

impl PreloadHintType {
    /// The spec token (`"PART"` / `"MAP"`).
    pub fn name(&self) -> &'static str {
        match self {
            PreloadHintType::Part => "PART",
            PreloadHintType::Map => "MAP",
        }
    }
}

broadcast_common::impl_spec_display!(PreloadHintType);

/// `#EXT-X-RENDITION-REPORT` (RFC 8216bis §4.4.5.4) — a pointer to the
/// current state of an associated Rendition's own Media Playlist, so an
/// LL-HLS client following one Rendition can discover how far another has
/// progressed without polling it.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RenditionReport {
    /// `URI` of the Rendition's Media Playlist, relative to the playlist
    /// carrying this tag (REQUIRED).
    pub uri: String,
    /// `LAST-MSN` — Media Sequence Number of the last segment (or partial
    /// segment, if any) currently in that Rendition (REQUIRED).
    pub last_msn: u64,
    /// `LAST-PART` — Part Index of the last partial segment at `last_msn`,
    /// if that Rendition has partial segments.
    pub last_part: Option<u64>,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// `#EXT-X-SKIP` (RFC 8216bis §4.4.5.2) — present on a Playlist Delta Update
/// response in place of the segments/tags before the Skip Boundary.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SkipInfo {
    /// `SKIPPED-SEGMENTS` — count of Media Segments elided (REQUIRED).
    pub skipped_segments: u64,
    /// `RECENTLY-REMOVED-DATERANGES` — `EXT-X-DATERANGE` `ID`s removed from
    /// the playlist recently (tab-delimited on the wire). Empty when the
    /// attribute is absent.
    pub recently_removed_daterange_ids: Vec<String>,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// A single partial segment ("part") of a [`MediaSegment`] — RFC 8216bis
/// §4.4.4.9 (`#EXT-X-PART`).
///
/// A part is an independently addressable CMAF chunk (a `moof`+`mdat` fragment)
/// covering a sub-duration of its parent segment; a client can fetch and play it
/// before the parent segment is complete. Parts are emitted as `#EXT-X-PART`
/// lines immediately before the parent segment's `#EXTINF`.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct PartSpec {
    /// The part URI (e.g. `"seg0.1.m4s"`).
    pub uri: String,
    /// The part duration in seconds (e.g. `0.334`).
    pub duration: DecimalSeconds,
    /// If `true`, render `,INDEPENDENT=YES` — the part begins with an
    /// independently decodable frame (a sync sample). RFC 8216bis §4.4.4.9.
    pub independent: bool,
    /// `BYTERANGE` attribute (RFC 8216bis §4.4.4.9) — the part is a
    /// sub-range of the resource named by [`Self::uri`], same `<n>[@<o>]`
    /// format as [`MediaSegment::byte_range`]. `None` when the part is the
    /// entire resource.
    pub byte_range: Option<ByteRange>,
    /// `GAP` attribute (RFC 8216bis §4.4.4.9) — `true` if this partial
    /// segment is not actually available (a hole in the part list).
    pub gap: bool,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// An in-progress (open) LL-HLS segment: its parts are known and being served,
/// but the segment is not yet complete, so it carries no `#EXTINF`/URI
/// (RFC 8216bis §4.4.4.9 — an open segment is represented by its trailing
/// `#EXT-X-PART` lines only, until it closes).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct OpenSegment {
    /// The parts of the in-progress segment, in order.
    pub parts: Vec<PartSpec>,
    /// The Media Initialization Section in effect for this segment (RFC
    /// 8216bis §4.4.4.5) — `#EXT-X-MAP` applies "until the next `EXT-X-MAP`
    /// tag or the end of the Playlist", so this carries forward from the
    /// last `#EXT-X-MAP` seen, whether or not any segment has *closed* yet.
    /// `None` if no `#EXT-X-MAP` has appeared at all (rare in practice — a
    /// live LL-HLS playlist's very first segment normally needs one).
    pub map: Option<MapTag>,
    /// Verbatim segment-scoped tag lines (the [`MediaSegment::pre_tags`]
    /// counterpart for the open segment): segment-defining tags that appear
    /// after the last closed segment but before the pending one — e.g. a
    /// `#EXT-X-KEY` for the next key period, or a `#EXT-X-PROGRAM-DATE-TIME`
    /// for the in-progress segment (audit BH-W5, issue #1111). Rendered
    /// after the open segment's map/parts, in order.
    pub pre_tags: Vec<String>,
    /// `#EXT-X-PROGRAM-DATE-TIME` (RFC 8216bis §4.4.4.6) applying to this
    /// open (in-progress) segment, if any.
    pub program_date_time: Option<ProgramDateTime>,
}

impl OpenSegment {
    /// Build an open segment from its in-progress parts, with no map (see
    /// [`Self::with_map`] to attach one).
    pub fn new(parts: Vec<PartSpec>) -> Self {
        Self {
            parts,
            map: None,
            pre_tags: Vec::new(),
            program_date_time: None,
        }
    }

    /// Attach the Media Initialization Section in effect for this segment.
    pub fn with_map(mut self, map: MapTag) -> Self {
        self.map = Some(map);
        self
    }
}

// ---------------------------------------------------------------------------
// Media or Multivariant Playlist Tags — RFC 8216bis §4.4.2. Valid in either
// a `MediaPlaylist` or a `MasterPlaylist` (issue #872).
// ---------------------------------------------------------------------------

/// `#EXT-X-START` (RFC 8216bis §4.4.2.2) — a preferred playback start point.
/// Valid in either a [`MediaPlaylist`] or a [`MasterPlaylist`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct StartPoint {
    /// `TIME-OFFSET` — signed seconds from the start of the Playlist
    /// (positive) or from the end of the last Media Segment (negative).
    /// REQUIRED.
    pub time_offset: SignedDecimalSeconds,
    /// `PRECISE` — if `true`, a client should not render samples before
    /// `time_offset` within the segment it lands in. Absence on the wire
    /// means `false` (RFC 8216bis §4.4.2.2).
    pub precise: bool,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// A single `#EXT-X-DEFINE` variable declaration (RFC 8216bis §4.4.2.3).
/// Unlike every other §4.4.2 tag, `EXT-X-DEFINE` MAY appear more than once
/// per Playlist, so it is carried as a `Vec` on both [`MediaPlaylist`] and
/// [`MasterPlaylist`] rather than a single field.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Define {
    /// `NAME`/`VALUE` form — declares a Variable with a literal value.
    Name {
        /// The Variable Name (`[a-zA-Z0-9_-]` per spec).
        name: String,
        /// The Variable Value (MAY be empty).
        value: String,
        /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
        /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
        extra_attrs: Vec<(String, AttrValue)>,
    },
    /// `IMPORT` form — imports a Variable of the same name from the parent
    /// Multivariant Playlist. The spec says this **MUST NOT** occur in a
    /// [`MasterPlaylist`] (Multivariant Playlist) — only in a
    /// [`MediaPlaylist`] loaded from one — but that is a cross-file
    /// constraint this single-playlist parser cannot check, so it is not
    /// enforced here (see the module docs on this crate's general
    /// MUST-constraint leniency).
    Import {
        /// The imported Variable Name.
        name: String,
        /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
        /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
        extra_attrs: Vec<(String, AttrValue)>,
    },
    /// `QUERYPARAM` form — imports a Variable from the query parameter of
    /// the same name in the Playlist's own URI.
    QueryParam {
        /// The Variable Name / query parameter name.
        name: String,
        /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
        /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
        extra_attrs: Vec<(String, AttrValue)>,
    },
}

// ---------------------------------------------------------------------------
// Media Playlist Tags — RFC 8216bis §4.4.3.5.
// ---------------------------------------------------------------------------

/// `#EXT-X-PLAYLIST-TYPE` (RFC 8216bis §4.4.3.5) mutability declaration —
/// [`MediaPlaylist`]-only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlaylistType {
    /// `EVENT` — segments can only be appended, never removed.
    Event,
    /// `VOD` (Video On Demand) — the Playlist can never change.
    Vod,
}

impl PlaylistType {
    /// The spec token (`"EVENT"` / `"VOD"`).
    pub fn name(&self) -> &'static str {
        match self {
            PlaylistType::Event => "EVENT",
            PlaylistType::Vod => "VOD",
        }
    }
}

broadcast_common::impl_spec_display!(PlaylistType);

// ---------------------------------------------------------------------------
// Multivariant Playlist Tags — RFC 8216bis §4.4.6.4 / §4.4.6.5 / §4.4.6.6.
// All three are [`MasterPlaylist`]-only.
// ---------------------------------------------------------------------------

/// `FORMAT` attribute of `#EXT-X-SESSION-DATA` (RFC 8216bis §4.4.6.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum SessionDataFormat {
    /// `JSON` — the default when the attribute (or the whole `URI`
    /// attribute it qualifies) is absent.
    #[default]
    Json,
    /// `RAW` — the URI names a binary file.
    Raw,
}

impl SessionDataFormat {
    /// The spec token (`"JSON"` / `"RAW"`).
    pub fn name(&self) -> &'static str {
        match self {
            SessionDataFormat::Json => "JSON",
            SessionDataFormat::Raw => "RAW",
        }
    }
}

broadcast_common::impl_spec_display!(SessionDataFormat);

/// The mutually-exclusive `VALUE`/`URI` content of `#EXT-X-SESSION-DATA`
/// (RFC 8216bis §4.4.6.4: "Each ... tag MUST contain either a VALUE or URI
/// attribute, but not both").
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SessionDataContent {
    /// `VALUE` — a literal data string.
    Value(String),
    /// `URI` (+ `FORMAT`) — a reference to an external resource.
    Uri {
        /// The `URI` attribute.
        uri: String,
        /// The `FORMAT` attribute — only meaningful here (ignored by the
        /// spec when `URI` is absent, i.e. for [`SessionDataContent::Value`]).
        format: SessionDataFormat,
    },
}

/// `#EXT-X-SESSION-DATA` (RFC 8216bis §4.4.6.4) — arbitrary session data
/// carried in a [`MasterPlaylist`] (Multivariant Playlist only). A Playlist
/// MAY carry multiple entries, including repeats of the same `DATA-ID`
/// distinguished by `LANGUAGE`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SessionData {
    /// `DATA-ID` — identifies this data value (REQUIRED).
    pub data_id: String,
    /// The mutually-exclusive `VALUE`/`URI` payload.
    pub content: SessionDataContent,
    /// `LANGUAGE` — an RFC 5646 language tag, typically qualifying a
    /// [`SessionDataContent::Value`].
    pub language: Option<String>,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// `METHOD` attribute shared by `#EXT-X-KEY`/`#EXT-X-SESSION-KEY`
/// (RFC 8216bis §4.4.4.4 / §4.4.6.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EncryptionMethod {
    /// `NONE` — not encrypted. The spec disallows this value on
    /// `EXT-X-SESSION-KEY` specifically (not enforced at parse time here).
    None,
    /// `AES-128` — whole-segment AES-128-CBC.
    Aes128,
    /// `SAMPLE-AES` — per-sample AES (`cbcs` scheme for fMP4).
    SampleAes,
    /// `SAMPLE-AES-CTR` — per-sample AES-CTR (`cenc` scheme for fMP4).
    SampleAesCtr,
    /// `AES-256-GCM` — whole-segment AES-256-GCM.
    Aes256Gcm,
}

impl EncryptionMethod {
    /// The spec token.
    pub fn name(&self) -> &'static str {
        match self {
            EncryptionMethod::None => "NONE",
            EncryptionMethod::Aes128 => "AES-128",
            EncryptionMethod::SampleAes => "SAMPLE-AES",
            EncryptionMethod::SampleAesCtr => "SAMPLE-AES-CTR",
            EncryptionMethod::Aes256Gcm => "AES-256-GCM",
        }
    }
}

broadcast_common::impl_spec_display!(EncryptionMethod);

/// `#EXT-X-SESSION-KEY` (RFC 8216bis §4.4.6.5) — preloadable decryption key
/// info for a [`MasterPlaylist`] (Multivariant Playlist only), carrying the
/// same attributes as `#EXT-X-KEY` (§4.4.4.4) except that the spec requires
/// `METHOD` not be `NONE` (enforced at parse time).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SessionKey {
    /// `METHOD` (REQUIRED).
    pub method: EncryptionMethod,
    /// `URI` — REQUIRED unless `method` is [`EncryptionMethod::None`].
    pub uri: Option<String>,
    /// `IV` — 128-bit Initialization Vector.
    pub iv: Option<[u8; 16]>,
    /// `KEYFORMAT` — absence on the wire implies `"identity"`.
    pub keyformat: Option<String>,
    /// `KEYFORMATVERSIONS` — absence on the wire implies `"1"`.
    pub keyformatversions: Option<String>,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// `#EXT-X-CONTENT-STEERING` (RFC 8216bis §4.4.6.6) — a pointer to a Content
/// Steering Manifest. [`MasterPlaylist`]-only; at most one per Playlist.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContentSteering {
    /// `SERVER-URI` — the Steering Manifest URI (REQUIRED).
    pub server_uri: String,
    /// `PATHWAY-ID` — the Pathway to apply before the first Steering
    /// Manifest has been obtained.
    pub pathway_id: Option<String>,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// `#EXT-X-PROGRAM-DATE-TIME` value (RFC 8216bis §4.4.4.6) — an absolute
/// date/time associated with the first sample of a Media Segment. Stored as a
/// millisecond-precision UTC [`jiff::Timestamp`] (the wire form is canonicalised
/// to `YYYY-MM-DDThh:mm:ss.SSSZ` on render; sub-millisecond precision and any
/// offset are normalised away on parse, so a round trip compares equal as a
/// typed value even when the textual form changes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ProgramDateTime(jiff::Timestamp);

impl ProgramDateTime {
    /// Parse an ISO 8601 / RFC 3339 date-time (`2010-02-19T14:54:23.031+08:00`,
    /// `2024-01-01T00:00:00.000Z`, or a zone-less value, which the spec says
    /// the client SHOULD treat as UTC). Sub-millisecond precision is truncated to
    /// milliseconds; offsets are converted to UTC. Returns an error if the value
    /// is not a recognisable date/time.
    pub fn parse(s: &str) -> crate::Result<Self> {
        let trimmed = s.trim();
        let ts = if let Ok(ts) = trimmed.parse::<jiff::Timestamp>() {
            ts
        } else if let Ok(dt) = trimmed.parse::<jiff::civil::DateTime>() {
            dt.to_zoned(jiff::tz::TimeZone::UTC)
                .map_err(|_| crate::Error::HlsParse {
                    line_no: 0,
                    line: trimmed.to_string(),
                    reason: "EXT-X-PROGRAM-DATE-TIME value is not a valid date/time".to_string(),
                })?
                .timestamp()
        } else {
            return Err(crate::Error::HlsParse {
                line_no: 0,
                line: trimmed.to_string(),
                reason: "EXT-X-PROGRAM-DATE-TIME value is not a valid ISO 8601 date/time"
                    .to_string(),
            });
        };
        let ms = ts.as_millisecond();
        let ts = jiff::Timestamp::from_millisecond(ms).map_err(|_| crate::Error::HlsParse {
            line_no: 0,
            line: trimmed.to_string(),
            reason: "EXT-X-PROGRAM-DATE-TIME value is out of range".to_string(),
        })?;
        Ok(Self(ts))
    }

    /// Wrap a timestamp, truncating it to millisecond precision (the wire
    /// precision, §4.4.4.6).
    pub fn from_timestamp(ts: jiff::Timestamp) -> Self {
        // `as_millisecond` of a valid timestamp is always representable.
        Self(jiff::Timestamp::from_millisecond(ts.as_millisecond()).unwrap_or(ts))
    }

    /// The underlying millisecond-precision UTC timestamp.
    pub fn timestamp(&self) -> jiff::Timestamp {
        self.0
    }

    /// Render in canonical form `YYYY-MM-DDThh:mm:ss.SSSZ`.
    pub fn render(&self) -> alloc::string::String {
        self.0.strftime("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()
    }
}

impl core::str::FromStr for ProgramDateTime {
    type Err = crate::Error;
    fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl core::fmt::Display for ProgramDateTime {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.render())
    }
}

/// A single media segment in a media playlist.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct MediaSegment {
    /// The segment URI (e.g. `"seg0.m4s"`).
    pub uri: String,
    /// The segment duration in seconds (e.g. `9.009`).
    pub duration: DecimalSeconds,
    /// If `true`, emit `#EXT-X-DISCONTINUITY` immediately before this
    /// segment's `#EXTINF` line — RFC 8216 §4.3.4.3.
    pub discontinuous: bool,
    /// Low-Latency HLS partial segments of this segment (RFC 8216bis §4.4.4.9).
    /// Rendered as `#EXT-X-PART` lines *before* this segment's `#EXTINF`, but
    /// only when the playlist is low-latency (see [`MediaPlaylist::low_latency`]).
    /// Empty for a non-low-latency playlist or a segment whose parts have already
    /// been coalesced into the full `#EXTINF`.
    pub parts: Vec<PartSpec>,
    /// `#EXT-X-BYTERANGE` (RFC 8216bis §4.4.4.2) — this segment is a
    /// sub-range of the resource named by [`Self::uri`]. Rendered
    /// immediately after this segment's `#EXTINF` line, before the URI.
    /// `None` (the default) means the segment is the entire resource.
    pub byte_range: Option<ByteRange>,
    /// `#EXT-X-MAP` (RFC 8216bis §4.4.4.5) applying to this segment. Per
    /// spec a map applies to every segment following it until the next
    /// `#EXT-X-MAP`; `to_m3u8` renders the tag only when it differs from the
    /// previous segment's map (dedup), and [`MediaPlaylist::parse`] carries
    /// the value forward onto every segment it applies to — so this field
    /// is `Some` on every segment covered by a given `#EXT-X-MAP`, not just
    /// the one it was written before.
    pub map: Option<MapTag>,
    /// `#EXT-X-GAP` (RFC 8216bis §4.4.4.7) — `true` if this segment's URI
    /// does not contain media data and should not be loaded by clients.
    /// Applies to exactly the one segment it is rendered against (no
    /// carry-forward, unlike [`Self::map`]/[`Self::bitrate`]).
    pub gap: bool,
    /// `#EXT-X-BITRATE` (RFC 8216bis §4.4.4.8) in kilobits per second —
    /// carried forward (same rule as [`Self::map`]) onto every segment
    /// following the tag until the next `#EXT-X-BITRATE` or the end of the
    /// Playlist. `to_m3u8` re-emits the tag only when it changes from the
    /// previous segment (same dedup rule as `#EXT-X-MAP`). The spec says the
    /// tag does not apply to a segment carrying its own `#EXT-X-BYTERANGE`;
    /// this crate does not enforce that producer-side constraint (documented
    /// modeling gap, see the module docs).
    pub bitrate: Option<u64>,
    /// The `#EXTINF` title: the text after the duration's comma
    /// (RFC 8216bis §4.4.4.1 — "a comma-separated title string, the
    /// title of the Media Segment ... optional"; the spec notes it
    /// "applies to the entire segment, but ... is normally not displayed").
    /// `None` when the tag carried no title (the overwhelmingly common
    /// case), which renders as the bare `#EXTINF:<dur>,` — audit BH-W11
    /// (#1111): the title used to be discarded outright, so it
    /// survived no round trip.
    pub title: Option<String>,
    /// Verbatim tag lines that appeared immediately before this segment's
    /// defining line(s) and *define this segment* — `#EXT-X-KEY`,
    /// `#EXT-X-PROGRAM-DATE-TIME`, `#EXT-X-DATERANGE`, `#EXT-X-CUE-*`, or
    /// any other tag this crate does not model with a typed field
    /// (RFC 8216bis §4.4.1: such tags apply until the next occurrence or the
    /// end of the Playlist, so position is load-bearing). `to_m3u8` re-emits
    /// them here, in order, immediately before the segment — so a key
    /// rotation or a per-segment PDT survives parse → render (audit BH-W5,
    /// issue #1111; previously all such lines were hoisted into one
    /// playlist-level `extra_tags` block before every segment, which applied
    /// the last key to the whole playlist and collapsed the PDT timeline).
    /// `MediaPlaylist::parse` populates this only for tags it recognizes as
    /// segment-scoped; unrecognized *playlist-level* tags
    /// (`#EXT-X-MEDIA`, `#EXT-X-DEFINE`, …) still go to
    /// [`MediaPlaylist::extra_tags`].
    pub pre_tags: Vec<String>,
    /// `#EXT-X-PROGRAM-DATE-TIME` (RFC 8216bis §4.4.4.6) associated with
    /// this segment, if any.
    pub program_date_time: Option<ProgramDateTime>,
}

/// A media playlist (`#EXTM3U` / `#EXTINF` / ...).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct MediaPlaylist {
    /// `#EXT-X-VERSION` — an explicit *floor*, not the rendered value. `0`
    /// (this type's `Default`) means "no explicit floor": [`Self::to_m3u8`]
    /// renders exactly [`Self::computed_version`], or no tag at all when
    /// nothing triggers one. A nonzero value is raised — never lowered — to
    /// the computed minimum. See the module's "Protocol version derivation"
    /// docs (issue #871).
    pub version: u8,
    /// `#EXT-X-TARGETDURATION` — must be >= the max rounded segment duration.
    pub target_duration: u32,
    /// `#EXT-X-MEDIA-SEQUENCE`
    pub media_sequence: u64,
    /// `#EXT-X-DISCONTINUITY-SEQUENCE` (RFC 8216 §4.3.3.3) — the count of
    /// discontinuities that have already rolled off the front of a live
    /// sliding-window playlist and are no longer represented by any in-window
    /// `#EXT-X-DISCONTINUITY` tag. Emitted as
    /// `#EXT-X-DISCONTINUITY-SEQUENCE:<n>` when `n > 0`; omitted when `0`
    /// (which is the implicit default per the spec).
    pub discontinuity_sequence: u64,
    /// If `true`, force emission of `#EXT-X-DISCONTINUITY-SEQUENCE:<n>`
    /// even when `discontinuity_sequence == 0` (Apple authoring 8.17).
    /// Set `true` on parse whenever the tag is present, so a parsed
    /// `#EXT-X-DISCONTINUITY-SEQUENCE:0` round-trips byte-stably.
    pub always_emit_discontinuity_sequence: bool,
    /// Ordered list of segments.
    pub segments: Vec<MediaSegment>,
    /// The in-progress (open) segment, if any — rendered as trailing
    /// `#EXT-X-PART` lines with no `#EXTINF` (LL-HLS live edge).
    pub open_segment: Option<OpenSegment>,
    /// If `true`, append `#EXT-X-ENDLIST`.
    pub endlist: bool,
    /// Extra tag lines emitted verbatim before segment entries
    /// (e.g. `#EXT-X-DATERANGE:...`).
    pub extra_tags: Vec<String>,
    /// Low-Latency HLS configuration (RFC 8216bis). When `Some`, `to_m3u8`
    /// renders the LL-HLS directives — `#EXT-X-SERVER-CONTROL`,
    /// `#EXT-X-PART-INF`, each segment's `#EXT-X-PART` lines, and (if set) the
    /// `#EXT-X-PRELOAD-HINT`. When `None` (the default), none of these appear —
    /// LL-HLS is strictly opt-in and a plain playlist is unchanged.
    pub low_latency: Option<LowLatencyConfig>,
    /// If `true`, emit `#EXT-X-I-FRAMES-ONLY` (RFC 8216 §4.3.3.6) in the
    /// header block, declaring that every segment in this playlist carries a
    /// single I-frame (a trick-play / thumbnail rendition).  When `true` the
    /// rendered version is at least 4 (RFC 8216 §4.3.3.6 requirement).
    pub iframes_only: bool,
    /// `#EXT-X-RENDITION-REPORT` entries (RFC 8216bis §4.4.5.4) — one per
    /// associated Rendition, pointing an LL-HLS client at that Rendition's
    /// current playlist state. Rendered after the segment list (and any
    /// preload hint), in order.
    pub rendition_reports: Vec<RenditionReport>,
    /// `#EXT-X-SKIP` (RFC 8216bis §4.4.5.2) — present on a Playlist Delta
    /// Update response, replacing the segments/tags before the Skip
    /// Boundary. `None` (the default) means this is a full playlist, not a
    /// delta update.
    pub skip: Option<SkipInfo>,
    /// `#EXT-X-INDEPENDENT-SEGMENTS` (RFC 8216bis §4.4.2.1) — every Media
    /// Segment in this Playlist can be decoded without information from any
    /// other segment.
    pub independent_segments: bool,
    /// `#EXT-X-START` (RFC 8216bis §4.4.2.2) — a preferred playback start
    /// point.
    pub start: Option<StartPoint>,
    /// `#EXT-X-DEFINE` entries (RFC 8216bis §4.4.2.3) — variable
    /// declarations/imports, in the order they appeared on the wire.
    pub defines: Vec<Define>,
    /// `#EXT-X-PLAYLIST-TYPE` (RFC 8216bis §4.4.3.5) — mutability
    /// declaration. `None` means the tag was absent (no additional
    /// restriction beyond Section 6.2.1's defaults).
    pub playlist_type: Option<PlaylistType>,
}

/// Low-Latency HLS playlist configuration — RFC 8216bis.
///
/// Presence of this config on a [`MediaPlaylist`] switches on the LL-HLS
/// directives (`#EXT-X-SERVER-CONTROL`, `#EXT-X-PART-INF`, `#EXT-X-PART`,
/// `#EXT-X-PRELOAD-HINT`); see the module docs for each tag's spec section.
#[derive(Debug, Clone, PartialEq)]
pub struct LowLatencyConfig {
    /// Part-target duration in seconds — the `PART-TARGET` of `#EXT-X-PART-INF`
    /// (RFC 8216bis §4.4.3.7). Typically 0.2–0.5 s. `None` means no
    /// `#EXT-X-PART-INF` tag is present or rendered — the shape of a playlist
    /// that carries `#EXT-X-SERVER-CONTROL` (e.g. `HOLD-BACK` or
    /// `CAN-SKIP-UNTIL`) without Partial Segments, which RFC 8216bis §4.4.3.8
    /// allows (audit BH-W3, issue #1111: this used to be a non-optional
    /// `DecimalSeconds` that re-rendered a bogus `PART-TARGET=0`).
    pub part_target: Option<DecimalSeconds>,
    /// `PART-HOLD-BACK` in seconds — the `#EXT-X-SERVER-CONTROL` attribute
    /// (RFC 8216bis §4.4.3.8). MUST be at least `3 × part_target`; the
    /// renderer raises it to that floor if a smaller value is supplied.
    /// REQUIRED if the Playlist contains `#EXT-X-PART-INF` (§4.4.3.8), so
    /// `to_m3u8` renders it exactly when this is `Some` — as with
    /// [`Self::part_target`], `None` emits nothing (audit BH-W3).
    pub part_hold_back: Option<DecimalSeconds>,
    /// URI of the next, not-yet-available part or map — rendered as
    /// `#EXT-X-PRELOAD-HINT:TYPE=<...>,URI="<uri>"` (RFC 8216bis §4.4.5.3). When
    /// `None`, no preload hint is emitted (e.g. an ended playlist).
    pub preload_hint_part: Option<String>,
    /// `TYPE` of [`Self::preload_hint_part`]'s hinted resource (RFC 8216bis
    /// §4.4.5.3): `PART` (a Partial Segment) or `MAP` (a Media
    /// Initialization Section). Only meaningful when `preload_hint_part` is
    /// `Some`; defaults to [`PreloadHintType::Part`] (the overwhelmingly
    /// common case).
    pub preload_hint_type: PreloadHintType,
    /// `BYTERANGE-START` of the `#EXT-X-PRELOAD-HINT` tag (RFC 8216bis
    /// §4.4.5.3) — byte offset of the hinted resource. `None` implies 0.
    pub preload_hint_byte_range_start: Option<u64>,
    /// `BYTERANGE-LENGTH` of the `#EXT-X-PRELOAD-HINT` tag (RFC 8216bis
    /// §4.4.5.3) — length in bytes. `None` means "to the end of the
    /// resource".
    pub preload_hint_byte_range_length: Option<u64>,
    /// `CAN-SKIP-UNTIL` attribute of `#EXT-X-SERVER-CONTROL` (RFC 8216bis
    /// §4.4.3.8) — the Skip Boundary in seconds, advertising support for
    /// Playlist Delta Updates (`#EXT-X-SKIP`). `None` omits the attribute.
    pub can_skip_until: Option<DecimalSeconds>,
    /// `CAN-BLOCK-RELOAD` attribute of `#EXT-X-SERVER-CONTROL` (RFC 8216bis
    /// §4.4.3.8) — whether the server supports Blocking Playlist Reload
    /// (RFC 8216bis §6.2.5.2). `to_m3u8` renders the actual value
    /// (`YES`/`NO`) rather than assuming `YES`; `MediaPlaylist::parse`
    /// derives it from the attribute's real wire value, defaulting to
    /// `false` (per RFC 8216bis) when the attribute — or the whole
    /// `#EXT-X-SERVER-CONTROL` tag — is absent. A client MUST NOT infer
    /// blocking-reload support merely from [`MediaPlaylist::low_latency`]
    /// being `Some`; it must check this field (issue #717 slice 1 gap).
    pub can_block_reload: bool,
    /// Unmodeled attributes from `#EXT-X-SERVER-CONTROL` (`#EXT-X-SERVER-CONTROL`
    /// is §4.4.3.8), retained so `REQ-` prefixed names can fire RFC 8216bis §8
    /// row 12. Sorted by name on parse (deterministic). The three per-tag
    /// lists below are the *only* copy of each tag's unmodeled attributes
    /// (audit BH-W8, issue #1111): this struct used to also carry a
    /// playlist-wide `extra_attrs` union that the renderer ignored, so a
    /// hand-built config could put a `REQ-` attribute in the union only and
    /// have it (a) never rendered and (b) missed by the §8 row-12 version
    /// scan, under-declaring `EXT-X-VERSION`.
    pub sc_extra_attrs: Vec<(String, AttrValue)>,
    /// Unmodeled attributes from `#EXT-X-PART-INF` only.
    pub pi_extra_attrs: Vec<(String, AttrValue)>,
    /// Unmodeled attributes from `#EXT-X-PRELOAD-HINT` only.
    pub ph_extra_attrs: Vec<(String, AttrValue)>,
    /// `HOLD-BACK` attribute of `#EXT-X-SERVER-CONTROL` (RFC 8216bis
    /// §4.4.3.8) — the server-recommended minimum distance from the live
    /// edge for clients NOT playing in Low-Latency Mode. `None` means the
    /// attribute is absent (the spec default: three times the Target
    /// Duration). When `Some`, the value MUST be at least three times the
    /// Target Duration per the spec. Only meaningful when
    /// [`LowLatencyConfig`] is present; for a non-LL-HLS playlist with a
    /// custom hold-back, set this on a playlist that also carries the
    /// `#EXT-X-PART-INF` and `#EXT-X-SERVER-CONTROL` tags.
    pub hold_back: Option<DecimalSeconds>,
    /// `CAN-SKIP-DATERANGES` attribute of `#EXT-X-SERVER-CONTROL`
    /// (RFC 8216bis §4.4.3.8) — enumerated-string `YES` if the server can
    /// produce Playlist Delta Updates (§6.2.5.1) that skip older
    /// `#EXT-X-DATERANGE` tags in addition to Media Segments. REQUIRES the
    /// presence of [`Self::can_skip_until`]; the renderer suppresses this
    /// attribute when that field is `None` regardless of this value.
    pub can_skip_dateranges: bool,
}

impl LowLatencyConfig {
    /// The `PART-HOLD-BACK` value actually rendered: at least
    /// `3 × part_target` per RFC 8216bis §4.4.3.8, even if
    /// [`Self::part_hold_back`] is smaller. When [`Self::part_target`] is
    /// `None` there is no floor to compute, so [`Self::part_hold_back`] is
    /// returned as given: a playlist without Partial Segments may still carry
    /// the attribute so its `#EXT-X-SERVER-CONTROL` equals the other Media
    /// Playlists' (RFC 8216bis §6.2.4).
    pub fn effective_part_hold_back(&self) -> Option<DecimalSeconds> {
        let Some(part_target) = self.part_target else {
            return self.part_hold_back;
        };
        let floor = 3.0 * part_target.get();
        // `floor` and `self.part_hold_back.get()` are both finite and
        // non-negative, so their max is too.
        Some(DecimalSeconds::new_unchecked(
            self.part_hold_back
                .map_or(floor, |phb| phb.get().max(floor)),
        ))
    }
}

impl Default for LowLatencyConfig {
    /// Defaults `can_block_reload` to `true` — this crate's own LL-HLS
    /// origin (and every in-repo test/fixture that builds a
    /// [`LowLatencyConfig`] from scratch via `..Default::default()`) always
    /// supports blocking reload, matching `to_m3u8()`'s historical
    /// `CAN-BLOCK-RELOAD=YES` output. This default is never consulted for a
    /// *parsed* playlist: [`MediaPlaylist::parse`] always derives
    /// `can_block_reload` from the wire attribute (RFC 8216bis default:
    /// `false`/absent-means-NO), independent of this `Default` impl.
    fn default() -> Self {
        Self {
            part_target: None,
            part_hold_back: None,
            preload_hint_part: None,
            preload_hint_type: PreloadHintType::default(),
            preload_hint_byte_range_start: None,
            preload_hint_byte_range_length: None,
            can_skip_until: None,
            can_block_reload: true,
            sc_extra_attrs: Vec::new(),
            pi_extra_attrs: Vec::new(),
            ph_extra_attrs: Vec::new(),
            hold_back: None,
            can_skip_dateranges: false,
        }
    }
}

// ---------------------------------------------------------------------------
// Protocol Version Compatibility — RFC 8216bis §8 (issue #871).
//
// Source of truth: `docs/version-compatibility.md`, a twice-verified
// transcription of §8 from draft-pantos-hls-rfc8216bis-22. One named
// constant per row of that table, cited by row number. `#EXT-X-VERSION` is
// always `max()` over the minimums the playlist's actual content triggers —
// never a value picked ahead of time and baked in (the bug this issue
// fixes: a low-latency origin unconditionally declaring 9 when nothing it
// emits requires more than 6, forcing every client on 6/7/8 to refuse a
// stream it could have played).
// ---------------------------------------------------------------------------

/// §8 row 2 (Media Playlist): the `IV` attribute of `EXT-X-KEY`.
const VERSION_KEY_IV: u8 = 2;
/// §8 row 3 (Media Playlist): a floating-point `EXTINF` duration.
const VERSION_FLOAT_EXTINF: u8 = 3;
/// §8 row 4 (Media Playlist): `EXT-X-BYTERANGE`, or `EXT-X-I-FRAMES-ONLY`.
const VERSION_BYTERANGE_OR_IFRAMES_ONLY: u8 = 4;
/// §8 row 5 (Media Playlist): `EXT-X-KEY` with `METHOD=SAMPLE-AES`, or its
/// `KEYFORMAT`/`KEYFORMATVERSIONS` attributes, or `EXT-X-MAP` **together
/// with** `EXT-X-I-FRAMES-ONLY`. (`EXT-X-MAP` alone, without
/// `EXT-X-I-FRAMES-ONLY`, needs [`VERSION_MAP_WITHOUT_IFRAMES_ONLY`] = 6
/// instead — the row-6 note in `docs/version-compatibility.md`.)
const VERSION_SAMPLE_AES_OR_KEYFORMAT_OR_MAP_WITH_IFRAMES_ONLY: u8 = 5;
/// §8 row 6 (Media Playlist): `EXT-X-MAP` in a playlist that does *not* also
/// carry `EXT-X-I-FRAMES-ONLY`.
const VERSION_MAP_WITHOUT_IFRAMES_ONLY: u8 = 6;
/// §8 row 7 (Multivariant Playlist): a `"SERVICE"` value for the
/// `INSTREAM-ID` attribute of `EXT-X-MEDIA`.
const VERSION_MEDIA_SERVICE_INSTREAM_ID: u8 = 7;
/// §8 row 8 (any Playlist): variable substitution.
const VERSION_VARIABLE_SUBSTITUTION: u8 = 8;
/// §8 row 9 (any Playlist): `EXT-X-SKIP`.
const VERSION_SKIP: u8 = 9;
/// §8 row 10 (any Playlist): an `EXT-X-SKIP` that replaces
/// `EXT-X-DATERANGE` tags in a Playlist Delta Update — its
/// `RECENTLY-REMOVED-DATERANGES` attribute is non-empty.
const VERSION_SKIP_REPLACES_DATERANGE: u8 = 10;
/// §8 row 11 (any Playlist): `EXT-X-DEFINE` with a `QUERYPARAM` attribute.
const VERSION_DEFINE_QUERYPARAM: u8 = 11;
/// §8 row 12 (any Playlist): an attribute whose name starts with `"REQ-"`.
const VERSION_REQ_ATTRIBUTE: u8 = 12;
/// §8 row 13 (Multivariant Playlist): `EXT-X-MEDIA` with an `INSTREAM-ID`
/// attribute for a non-`CLOSED-CAPTIONS` `TYPE`.
const VERSION_MEDIA_INSTREAM_ID_NON_CC: u8 = 13;

/// RFC 8216bis §4.2.2's variable-substitution marker (`{$name}`, inside a
/// quoted-string attribute value or a URI) — §8 row 8's trigger. This is
/// *not* part of the version-compatibility transcription (that section
/// states only the rule, not the substitution grammar, which lives in a
/// different part of the spec) — it is a textual heuristic over the opaque
/// strings this crate already carries (`extra_tags`, segment/variant URIs),
/// not a modeled `EXT-X-DEFINE` parser.
const VARIABLE_SUBSTITUTION_MARKER: &str = "{$";

/// Fold `n` into the running maximum `v` — §8's rule is that the highest
/// version required by any single triggered feature governs the whole
/// Playlist.
fn bump_version(v: &mut Option<u8>, n: u8) {
    *v = Some(match *v {
        Some(m) => m.max(n),
        None => n,
    });
}

/// `true` if this duration **renders** as a floating-point `EXTINF` value
/// (§8 row 3).
///
/// Deliberately defined as "does [`format_extinf`] emit a decimal point",
/// not as a numeric property of `duration`, because §8 row 3 constrains what
/// the *playlist contains* — "A Media Playlist MUST indicate an
/// EXT-X-VERSION of 3 or higher if it contains: Floating-point EXTINF
/// duration values" — not what the in-memory type happens to be. Deriving
/// the predicate from the renderer makes the two impossible to diverge.
///
/// They previously did, in both directions, and both were spec violations:
///
/// - a whole `4.0` rendered as `#EXTINF:4.000,` — a floating-point value —
///   while this predicate (integer-millisecond) called it integral, so no
///   `EXT-X-VERSION` was emitted at all and a v1/v2 client was told the
///   playlist was compatible with it before meeting a float it cannot parse;
/// - a sub-millisecond `4.0004` rendered at full precision as
///   `#EXTINF:4.0004,` (correctly, since issue #872) while the same
///   millisecond-granular rounding still called it integral.
///
/// Note the modeling boundary this implies: a playlist *parsed* from text
/// that literally said `4.000` reports no row-3 requirement here, because
/// [`MediaPlaylist`] stores the numeric duration, not its original lexical
/// form — and this crate would re-render it as `4`. The claim is about the
/// playlist this crate emits, which is the one a client will actually read.
fn is_fractional_duration(duration: DecimalSeconds) -> bool {
    format_extinf(duration).contains('.')
}

/// `true` if `s` carries a variable-substitution reference (§8 row 8).
fn contains_variable_substitution(s: &str) -> bool {
    s.contains(VARIABLE_SUBSTITUTION_MARKER)
}

/// Scan a set of opaque, verbatim tag lines (a playlist's `extra_tags`) for
/// the §8 triggers that are attributes of tags this crate does not model as
/// struct fields: `EXT-X-KEY`'s `IV`/`METHOD`/`KEYFORMAT*` attributes (rows
/// 2 and 5), `EXT-X-MEDIA`'s `INSTREAM-ID` (rows 7 and 13 —
/// Multivariant-Playlist-only; harmless to scan on a Media Playlist's
/// `extra_tags` since that tag never legitimately appears there), and any
/// attribute name starting `REQ-` (row 12). Returns the max triggered
/// version, or `None`.
///
/// **Row 11 is handled here only for the raw-line path.** `EXT-X-DEFINE`
/// gained a typed representation in issue #872, so a *parsed* playlist's
/// `EXT-X-DEFINE` tags land in `defines` and never reach `extra_tags`;
/// relying on this scan alone would make row 11 silently stop firing for
/// every parsed or programmatically-built playlist. Both `computed_version`
/// impls therefore check the typed field, and the arm below is retained
/// purely for a caller who hand-pushes a verbatim tag line. `bump_version`
/// is a max, so the two paths cannot double-count or disagree.
///
///
/// **Row 12 now fires on typed tags too.** Unknown attributes on modeled tags
/// are retained since issue #884 (`extra_attrs` on every attribute-list-bearing
/// struct); the typed check in `any_typed_req_attr` and
/// `any_media_typed_req_attr` scans those fields so `REQ-` attributes reach
/// the version derivation whether they appear on a modeled or an unmodeled
/// tag.
fn scan_tag_lines_for_version(tags: &[String]) -> Option<u8> {
    let mut v: Option<u8> = None;
    for tag in tags {
        if let Some(rest) = tag.strip_prefix("#EXT-X-KEY:") {
            let (attrs, _quoted) = parse_attribute_list(rest);
            if attrs.contains_key("IV") {
                bump_version(&mut v, VERSION_KEY_IV);
            }
            if attrs.get("METHOD").map(String::as_str) == Some("SAMPLE-AES")
                || attrs.contains_key("KEYFORMAT")
                || attrs.contains_key("KEYFORMATVERSIONS")
            {
                bump_version(
                    &mut v,
                    VERSION_SAMPLE_AES_OR_KEYFORMAT_OR_MAP_WITH_IFRAMES_ONLY,
                );
            }
        } else if let Some(rest) = tag.strip_prefix("#EXT-X-DEFINE:") {
            // Row 11 via the *raw-line* path only. Since issue #872 a parsed
            // `EXT-X-DEFINE` lands in the typed `defines` field and never
            // reaches here, so this arm no longer covers the common case —
            // both `computed_version` impls check `defines` directly. It is
            // kept because a caller may still hand-push a verbatim tag line
            // into `extra_tags`, and `bump_version` is a max, so the two
            // paths cannot double-count or disagree.
            if parse_attribute_list(rest).0.contains_key("QUERYPARAM") {
                bump_version(&mut v, VERSION_DEFINE_QUERYPARAM);
            }
        } else if let Some(rest) = tag.strip_prefix("#EXT-X-MEDIA:") {
            let (attrs, _quoted) = parse_attribute_list(rest);
            if let Some(instream_id) = attrs.get("INSTREAM-ID") {
                if instream_id.starts_with("SERVICE") {
                    bump_version(&mut v, VERSION_MEDIA_SERVICE_INSTREAM_ID);
                }
                let is_closed_captions =
                    attrs.get("TYPE").map(String::as_str) == Some("CLOSED-CAPTIONS");
                if !is_closed_captions {
                    bump_version(&mut v, VERSION_MEDIA_INSTREAM_ID_NON_CC);
                }
            }
        }
        // Row 12 applies to ANY attribute-bearing tag, not just the three
        // handled above — scan every tag's attribute keys uniformly.
        if let Some(colon) = tag.find(':')
            && parse_attribute_list(&tag[colon + 1..])
                .0
                .keys()
                .any(|k| k.starts_with("REQ-"))
        {
            bump_version(&mut v, VERSION_REQ_ATTRIBUTE);
        }
    }
    v
}

/// Check whether any extra_attrs on any typed struct carry a `REQ-` prefix
/// (RFC 8216bis §8 row 12). `start` is Option<StartPoint>, `defines` is
/// `&[Define]`, `sd` is `&[SessionData]`, `sk` is `&[SessionKey]`,
/// `cs` is `Option<&ContentSteering>`, `variants` is `&[Variant]`,
/// `iframes` is `&[IFrameVariant]`.
///
/// AttributeName contains only uppercase letters per §4.2, so the `REQ-`
/// prefix match is case-sensitive.
#[allow(clippy::too_many_arguments)]
fn any_typed_req_attr(
    start: Option<&StartPoint>,
    defines: &[Define],
    sd: &[SessionData],
    sk: &[SessionKey],
    cs: Option<&ContentSteering>,
    media: &[MediaRendition],
    variants: &[Variant],
    iframes: &[IFrameVariant],
) -> bool {
    let extra_attr_is_req = |attrs: &[(String, AttrValue)]| -> bool {
        attrs.iter().any(|(k, _)| k.starts_with("REQ-"))
    };
    if start.is_some_and(|s| extra_attr_is_req(&s.extra_attrs)) {
        return true;
    }
    if defines.iter().any(|d| {
        let attrs = match d {
            Define::Name { extra_attrs, .. } => extra_attrs,
            Define::Import { extra_attrs, .. } => extra_attrs,
            Define::QueryParam { extra_attrs, .. } => extra_attrs,
        };
        extra_attr_is_req(attrs)
    }) {
        return true;
    }
    if sd.iter().any(|s| extra_attr_is_req(&s.extra_attrs)) {
        return true;
    }
    if sk.iter().any(|s| extra_attr_is_req(&s.extra_attrs)) {
        return true;
    }
    if cs.is_some_and(|c| extra_attr_is_req(&c.extra_attrs)) {
        return true;
    }
    if media.iter().any(|m| extra_attr_is_req(&m.extra_attrs)) {
        return true;
    }
    if variants.iter().any(|v| extra_attr_is_req(&v.extra_attrs)) {
        return true;
    }
    if iframes.iter().any(|i| extra_attr_is_req(&i.extra_attrs)) {
        return true;
    }
    false
}

/// Check whether any extra_attrs on media-playlist-specific typed structs
/// carry a `REQ-` prefix: `MapTag` (in segments/open), `PartSpec`,
/// `RenditionReport`, `SkipInfo`, `LowLatencyConfig`.
fn any_media_typed_req_attr(
    segments: &[MediaSegment],
    open_segment: Option<&OpenSegment>,
    rendition_reports: &[RenditionReport],
    skip: Option<&SkipInfo>,
    low_latency: Option<&LowLatencyConfig>,
) -> bool {
    let extra_attr_is_req = |attrs: &[(String, AttrValue)]| -> bool {
        attrs.iter().any(|(k, _)| k.starts_with("REQ-"))
    };
    if segments.iter().any(|s| {
        s.map
            .as_ref()
            .is_some_and(|m| extra_attr_is_req(&m.extra_attrs))
            || s.parts.iter().any(|p| extra_attr_is_req(&p.extra_attrs))
    }) {
        return true;
    }
    if let Some(open) = open_segment
        && (open
            .map
            .as_ref()
            .is_some_and(|m| extra_attr_is_req(&m.extra_attrs))
            || open.parts.iter().any(|p| extra_attr_is_req(&p.extra_attrs)))
    {
        return true;
    }
    if rendition_reports
        .iter()
        .any(|r| extra_attr_is_req(&r.extra_attrs))
    {
        return true;
    }
    if skip.is_some_and(|s| extra_attr_is_req(&s.extra_attrs)) {
        return true;
    }
    if low_latency.is_some_and(|ll| {
        extra_attr_is_req(&ll.sc_extra_attrs)
            || extra_attr_is_req(&ll.pi_extra_attrs)
            || extra_attr_is_req(&ll.ph_extra_attrs)
    }) {
        return true;
    }
    false
}

/// Shared floor/clamp logic behind `MediaPlaylist`'s and `MasterPlaylist`'s
/// private `effective_version` methods: `explicit` (the public `version`
/// field) acts as a floor over `computed` (the derived minimum), raised —
/// never lowered — to it. `0` means "no explicit floor".
fn effective_version(explicit: u8, computed: Option<u8>) -> Option<u8> {
    match (explicit, computed) {
        (0, None) => None,
        (0, Some(m)) => Some(m),
        (e, None) => Some(e),
        (e, Some(m)) => Some(e.max(m)),
    }
}

impl MediaPlaylist {
    /// Compute the minimum `#EXT-X-VERSION` this playlist's actual content
    /// requires, per RFC 8216bis §8 (`docs/version-compatibility.md`).
    /// `None` means the playlist is fully compatible with version 1, which
    /// per §8's opening rule need not carry the tag at all.
    ///
    /// This is `max()` over every triggered rule — see the `VERSION_*`
    /// constants above for the rule → row mapping. [`Self::to_m3u8`] uses
    /// this (via the private `effective_version`) rather than blindly
    /// trusting [`Self::version`]; see that field's docs for how an
    /// explicit value interacts with this computed minimum.
    pub fn computed_version(&self) -> Option<u8> {
        let mut v: Option<u8> = None;

        // Rows 5/6: EXT-X-MAP, present either as a structured
        // MediaSegment/OpenSegment map, or (a caller that hasn't adopted
        // that field, e.g. a raw #EXT-X-MAP: line) in `extra_tags`.
        let has_map = self.segments.iter().any(|s| s.map.is_some())
            // The open segment's map renders only with low-latency on, so it
            // only counts then (audit BH-O3, #1111).
            || (self.low_latency.is_some()
                && self.open_segment.as_ref().is_some_and(|o| o.map.is_some()))
            || self.extra_tags.iter().any(|t| t.starts_with("#EXT-X-MAP:"));
        if has_map {
            bump_version(
                &mut v,
                if self.iframes_only {
                    VERSION_SAMPLE_AES_OR_KEYFORMAT_OR_MAP_WITH_IFRAMES_ONLY
                } else {
                    VERSION_MAP_WITHOUT_IFRAMES_ONLY
                },
            );
        }

        // Row 4: EXT-X-BYTERANGE, or EXT-X-I-FRAMES-ONLY.
        if self.iframes_only || self.segments.iter().any(|s| s.byte_range.is_some()) {
            bump_version(&mut v, VERSION_BYTERANGE_OR_IFRAMES_ONLY);
        }

        // Row 3: floating-point EXTINF duration.
        if self
            .segments
            .iter()
            .any(|s| is_fractional_duration(s.duration))
        {
            bump_version(&mut v, VERSION_FLOAT_EXTINF);
        }

        // Rows 9/10: EXT-X-SKIP, optionally replacing EXT-X-DATERANGE.
        if let Some(skip) = &self.skip {
            bump_version(&mut v, VERSION_SKIP);
            if !skip.recently_removed_daterange_ids.is_empty() {
                bump_version(&mut v, VERSION_SKIP_REPLACES_DATERANGE);
            }
        }

        // Row 11: EXT-X-DEFINE with a QUERYPARAM attribute. Read from the
        // typed `defines` (issue #872) — before that, `EXT-X-DEFINE` was
        // unmodeled and this row could only be reached by string-scanning
        // `extra_tags`, which now never sees the tag at all.
        if self
            .defines
            .iter()
            .any(|d| matches!(d, Define::QueryParam { .. }))
        {
            bump_version(&mut v, VERSION_DEFINE_QUERYPARAM);
        }

        // Row 8: variable substitution, wherever this crate carries a URI
        // or tag verbatim. Every string field that can legitimately hold a
        // `{$var}` reference is scanned — a URI or attribute value the
        // caller supplied, whether it reached us as a modeled field or as
        // an opaque `extra_tags` line.
        if self
            .extra_tags
            .iter()
            .any(|t| contains_variable_substitution(t))
            || self
                .segments
                .iter()
                .any(|s| contains_variable_substitution(&s.uri))
            || self.media_playlist_typed_strings_use_substitution()
        {
            bump_version(&mut v, VERSION_VARIABLE_SUBSTITUTION);
        }

        // Rows 2/5/7/12/13: EXT-X-KEY's IV/METHOD/KEYFORMAT*, EXT-X-MEDIA's
        // INSTREAM-ID, and any REQ- attribute on *unmodeled* tags — none of
        // these tags has a modeled struct field in this crate, so `extra_tags`
        // remains the substrate for the first three. Row 12 on modeled tags
        // is now checked below via the typed extra_attrs scan (issue #884).
        // (Row 11 moved to the typed check above.)
        // Since audit BH-W5 (issue #1111) segment-defining tags live on
        // `MediaSegment::pre_tags`/`OpenSegment::pre_tags` instead of the
        // playlist-level block, so the scan must cover those too — an
        // `EXT-X-KEY` with `IV=` before segment 2 still triggers row 2.
        {
            let mut opaque_tags: Vec<&String> = self.extra_tags.iter().collect();
            opaque_tags.extend(self.segments.iter().flat_map(|s| &s.pre_tags));
            if let Some(open) = &self.open_segment {
                opaque_tags.extend(open.pre_tags.iter());
            }
            let owned: Vec<String> = opaque_tags.into_iter().cloned().collect();
            if let Some(m) = scan_tag_lines_for_version(&owned) {
                bump_version(&mut v, m);
            }
        }

        // Row 12: REQ- attribute on any typed struct — modeled tags that
        // carry extra_attrs fields since issue #884.
        if any_media_typed_req_attr(
            &self.segments,
            // Open-segment parts/map render only with low-latency on.
            self.open_segment
                .as_ref()
                .filter(|_| self.low_latency.is_some()),
            &self.rendition_reports,
            self.skip.as_ref(),
            self.low_latency.as_ref(),
        ) || any_typed_req_attr(
            self.start.as_ref(),
            &self.defines,
            &[],
            &[],
            None,
            &[],
            &[],
            &[],
        ) {
            bump_version(&mut v, VERSION_REQ_ATTRIBUTE);
        }

        v
    }

    /// Row 8 helper: does any *typed* string field of this Media Playlist
    /// carry a `{$var}` reference?
    ///
    /// Segment URIs are checked by the caller; this covers the rest of the
    /// places a URI or attribute value lives once it is modeled rather than
    /// left in `extra_tags` — `EXT-X-MAP`/`EXT-X-PART` URIs (typed since
    /// before #872) and the `EXT-X-DEFINE` values / preload-hint /
    /// rendition-report URIs. Missing one of these would under-declare the
    /// version for a playlist that genuinely uses substitution.
    fn media_playlist_typed_strings_use_substitution(&self) -> bool {
        let seg_strings = self.segments.iter().flat_map(|s| {
            s.map
                .iter()
                .map(|m| &m.uri)
                .chain(s.parts.iter().map(|p| &p.uri))
        });
        let open_strings = self.open_segment.iter().flat_map(|o| {
            o.map
                .iter()
                .map(|m| &m.uri)
                .chain(o.parts.iter().map(|p| &p.uri))
        });
        let define_values = self.defines.iter().filter_map(|d| match d {
            Define::Name { value, .. } => Some(value),
            _ => None,
        });
        let report_uris = self.rendition_reports.iter().map(|r| &r.uri);
        let preload = self
            .low_latency
            .iter()
            .filter_map(|ll| ll.preload_hint_part.as_ref());

        seg_strings
            .chain(open_strings)
            .chain(define_values)
            .chain(report_uris)
            .chain(preload)
            .any(|s| contains_variable_substitution(s))
    }

    /// The `#EXT-X-VERSION` value actually rendered by [`Self::to_m3u8`]:
    /// [`Self::computed_version`], raised — never lowered — to
    /// [`Self::version`] when that field carries a nonzero explicit floor.
    /// See [`Self::version`]'s docs for the full rule.
    fn effective_version(&self) -> Option<u8> {
        effective_version(self.version, self.computed_version())
    }
}

/// The `KEYFORMAT` an `#EXT-X-KEY` with no `KEYFORMAT` attribute implies
/// (RFC 8216 §4.3.2.4).
pub const KEYFORMAT_IDENTITY: &str = "identity";

/// An `#EXT-X-KEY` tag (RFC 8216 §4.3.2.4): the same attribute set as
/// [`SessionKey`], with `METHOD=NONE` allowed.
pub type MediaKey = SessionKey;

const EXT_X_KEY_PREFIX: &str = "#EXT-X-KEY:";

fn key_format_of(key: &MediaKey) -> &str {
    key.keyformat.as_deref().unwrap_or(KEYFORMAT_IDENTITY)
}

#[derive(Default)]
struct KeyState {
    identity: Option<MediaKey>,
    others: BTreeMap<String, MediaKey>,
}

impl KeyState {
    fn apply_tags(&mut self, tags: &[String]) -> Result<()> {
        for tag in tags {
            let Some(rest) = tag.strip_prefix(EXT_X_KEY_PREFIX) else {
                continue;
            };
            let key = parse_media_key(rest, 0, tag)?;
            if key.method != EncryptionMethod::None && key.uri.is_none() {
                return Err(Error::KeyWithoutUri { method: key.method });
            }
            if key.method == EncryptionMethod::None {
                self.identity = None;
                self.others.clear();
            } else if key_format_of(&key) == KEYFORMAT_IDENTITY {
                self.identity = Some(key);
            } else {
                self.others.insert(key_format_of(&key).to_string(), key);
            }
        }
        Ok(())
    }

    fn effective(&self) -> Result<Option<MediaKey>> {
        if let Some(key) = &self.identity {
            return Ok(Some(key.clone()));
        }
        match self.others.keys().next() {
            Some(keyformat) => Err(Error::UnsupportedKeyFormat {
                keyformat: keyformat.clone(),
            }),
            None => Ok(None),
        }
    }
}

impl MediaPlaylist {
    /// The `#EXT-X-KEY` in effect for each closed segment (RFC 8216
    /// §4.3.2.4): a tag applies to the segment it precedes and every later
    /// segment until the next `#EXT-X-KEY` with the same `KEYFORMAT` or a
    /// `METHOD` of `NONE` (RFC 8216bis §4.4.4.4), which ends every key
    /// format. Only the `identity` `KEYFORMAT` (absent means identity)
    /// participates; `METHOD=NONE` yields `None`.
    ///
    /// # Errors
    /// [`Error::KeyWithoutUri`] for a non-`NONE` key with no `URI`;
    /// [`Error::UnsupportedKeyFormat`] for a segment to which only
    /// non-identity key formats apply; [`Error::HlsParse`] for a malformed
    /// `#EXT-X-KEY`.
    pub fn segment_keys(&self) -> Result<Vec<Option<MediaKey>>> {
        self.segment_key_results()?.into_iter().collect()
    }

    /// Like [`Self::segment_keys`], but a segment to which only
    /// non-identity key formats apply yields its own
    /// [`Error::UnsupportedKeyFormat`] entry instead of failing the whole
    /// playlist, so the clear segments after a `METHOD=NONE` stay usable.
    ///
    /// # Errors
    /// [`Error::KeyWithoutUri`] or [`Error::HlsParse`] for a malformed
    /// `#EXT-X-KEY`, which no segment can be resolved around.
    pub fn segment_key_results(&self) -> Result<Vec<Result<Option<MediaKey>>>> {
        let mut state = KeyState::default();
        let mut keys = Vec::with_capacity(self.segments.len());
        for seg in &self.segments {
            state.apply_tags(&seg.pre_tags)?;
            keys.push(state.effective());
        }
        Ok(keys)
    }

    /// The key in effect for the open (in-progress) segment, if any, under
    /// the same rules as [`Self::segment_keys`].
    ///
    /// # Errors
    /// As [`Self::segment_keys`].
    pub fn open_segment_key(&self) -> Result<Option<MediaKey>> {
        let mut state = KeyState::default();
        for seg in &self.segments {
            state.apply_tags(&seg.pre_tags)?;
        }
        if let Some(open) = &self.open_segment {
            state.apply_tags(&open.pre_tags)?;
        }
        state.effective()
    }
}

impl MediaPlaylist {
    /// Render this media playlist as an RFC 8216 `#EXTM3U` string.
    ///
    /// Emits `#EXT-X-DISCONTINUITY-SEQUENCE:<n>` after the media-sequence
    /// header when `discontinuity_sequence > 0` (RFC 8216 §4.3.3.3), and
    /// `#EXT-X-DISCONTINUITY` immediately before the `#EXTINF` of every
    /// segment whose [`MediaSegment::discontinuous`] flag is `true`
    /// (RFC 8216 §4.3.4.3).
    ///
    /// When [`Self::iframes_only`] is `true`, emits `#EXT-X-I-FRAMES-ONLY`
    /// (RFC 8216 §4.3.3.6) in the header block; the version this (and every
    /// other triggering feature) requires is derived by
    /// [`Self::computed_version`] (see the module's "Protocol version
    /// derivation" docs, issue #871) — omitted entirely when nothing in the
    /// playlist triggers a version requirement.
    ///
    /// # Errors
    ///
    /// A field this crate renders inside an RFC 8216 §4.2 quoted-string or
    /// as a URI (a segment/part/map URI, a `#EXT-X-DEFINE` `NAME`/`VALUE`,
    /// a `KEYFORMAT`/`SERVER-URI`, …) that contains `"`, CR or LF is
    /// rejected before any of it reaches the output (audit BH-W7, issue
    /// #1111) — those three characters are forbidden in a quoted-string and
    /// would let a value inject a tag line into the playlist. This renderer
    /// is the guard: it rejects such a value before a single byte of output
    /// is produced, whether the playlist came from `parse` (whose fields are
    /// already wire-valid) or was assembled by hand through the public
    /// fields.
    pub fn to_m3u8(&self) -> Result<String> {
        self.validate_for_render()?;
        let mut s = String::new();
        s.push_str("#EXTM3U\n");
        if let Some(version) = self.effective_version() {
            s.push_str(&format!("#EXT-X-VERSION:{version}\n"));
        }
        if self.iframes_only {
            s.push_str("#EXT-X-I-FRAMES-ONLY\n");
        }
        // §4.4.2 tags (valid in either playlist type) — RFC 8216bis
        // §4.4.2.1/.2/.3 (issue #872).
        if self.independent_segments {
            s.push_str("#EXT-X-INDEPENDENT-SEGMENTS\n");
        }
        for def in &self.defines {
            push_define_line(&mut s, def)?;
        }
        if let Some(start) = &self.start {
            push_start_line(&mut s, start);
        }
        s.push_str(&format!("#EXT-X-TARGETDURATION:{}\n", self.target_duration));
        s.push_str(&format!("#EXT-X-MEDIA-SEQUENCE:{}\n", self.media_sequence));
        if self.discontinuity_sequence > 0 || self.always_emit_discontinuity_sequence {
            s.push_str(&format!(
                "#EXT-X-DISCONTINUITY-SEQUENCE:{}\n",
                self.discontinuity_sequence
            ));
        }
        // §4.4.3.5 (issue #872).
        if let Some(pt) = self.playlist_type {
            s.push_str(&format!("#EXT-X-PLAYLIST-TYPE:{}\n", pt.name()));
        }

        // Low-Latency HLS header directives (RFC 8216bis §4.4.3.7/§4.4.3.8),
        // opt-in via `low_latency`.
        if let Some(ll) = &self.low_latency {
            // #EXT-X-SERVER-CONTROL — CAN-BLOCK-RELOAD (the actual value,
            // not always YES) + PART-HOLD-BACK (>= 3x part-target, enforced
            // by effective_part_hold_back) + optional HOLD-BACK +
            // optional CAN-SKIP-UNTIL + optional CAN-SKIP-DATERANGES
            // (RFC 8216bis §4.4.3.8). PART-HOLD-BACK is REQUIRED only if the
            // Playlist contains #EXT-X-PART-INF, so it renders only when
            // present (audit BH-W3, issue #1111): a SERVER-CONTROL-only
            // playlist must not fabricate PART-HOLD-BACK=0.
            s.push_str(&format!(
                "#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD={}",
                if ll.can_block_reload { "YES" } else { "NO" },
            ));
            if let Some(phb) = ll.effective_part_hold_back() {
                s.push_str(&format!(",PART-HOLD-BACK={}", format_secs(phb)));
            }
            if let Some(hb) = ll.hold_back {
                s.push_str(&format!(",HOLD-BACK={}", format_secs(hb)));
            }
            if let Some(csu) = ll.can_skip_until {
                s.push_str(&format!(",CAN-SKIP-UNTIL={}", format_secs(csu)));
                if ll.can_skip_dateranges {
                    s.push_str(",CAN-SKIP-DATERANGES=YES");
                }
            }
            render_attribute_list(&mut s, &ll.sc_extra_attrs);
            s.push('\n');
            // #EXT-X-PART-INF — the part-target duration, rendered only when
            // a part target exists (audit BH-W3: previously always emitted,
            // rendering a bogus PART-TARGET=0 for a no-parts playlist).
            if let Some(part_target) = ll.part_target {
                s.push_str(&format!(
                    "#EXT-X-PART-INF:PART-TARGET={}",
                    format_secs(part_target),
                ));
                render_attribute_list(&mut s, &ll.pi_extra_attrs);
                s.push('\n');
            }
        }

        // #EXT-X-SKIP (RFC 8216bis §4.4.5.2) — a Playlist Delta Update marker
        // standing in for the segments/tags before the Skip Boundary.
        if let Some(skip) = &self.skip {
            s.push_str(&format!(
                "#EXT-X-SKIP:SKIPPED-SEGMENTS={}",
                skip.skipped_segments
            ));
            if !skip.recently_removed_daterange_ids.is_empty() {
                s.push_str(&format!(
                    ",RECENTLY-REMOVED-DATERANGES=\"{}\"",
                    skip.recently_removed_daterange_ids.join("\t")
                ));
            }
            render_attribute_list(&mut s, &skip.extra_attrs);
            s.push('\n');
        }

        for tag in &self.extra_tags {
            s.push_str(tag);
            s.push('\n');
        }

        for (i, seg) in self.segments.iter().enumerate() {
            // Segment-scoped unmodeled tags (EXT-X-KEY rotation, PDT,
            // DATERANGE, CUE-*) in their original position (audit BH-W5).
            for tag in &seg.pre_tags {
                s.push_str(tag);
                s.push('\n');
            }
            if seg.discontinuous {
                s.push_str("#EXT-X-DISCONTINUITY\n");
            }
            // #EXT-X-MAP (RFC 8216bis §4.4.4.5) — emitted only when it
            // changes from the previous segment's map, since the tag
            // applies "until the next EXT-X-MAP or the end of the Playlist".
            let prev_map = if i == 0 {
                None
            } else {
                self.segments[i - 1].map.as_ref()
            };
            if seg.map.as_ref() != prev_map
                && let Some(map) = &seg.map
            {
                push_map_line(&mut s, map)?;
            }
            // #EXT-X-BITRATE (RFC 8216bis §4.4.4.8, issue #872) — same
            // carry-forward + dedup-render rule as #EXT-X-MAP above.
            let prev_bitrate = if i == 0 {
                None
            } else {
                self.segments[i - 1].bitrate
            };
            if seg.bitrate != prev_bitrate
                && let Some(kbps) = seg.bitrate
            {
                s.push_str(&format!("#EXT-X-BITRATE:{kbps}\n"));
            }
            // #EXT-X-PROGRAM-DATE-TIME (§4.4.4.6) applies to this segment and
            // MUST precede its first #EXT-X-PART (§4.4.4.9); it follows
            // DISCONTINUITY/MAP/BITRATE, the conventional order.
            if let Some(pdt) = &seg.program_date_time {
                s.push_str(&format!("#EXT-X-PROGRAM-DATE-TIME:{pdt}\n"));
            }
            // LL-HLS partial segments precede the parent's #EXTINF
            // (RFC 8216bis §4.4.4.9), rendered only for a low-latency playlist.
            if self.low_latency.is_some() {
                for part in &seg.parts {
                    push_part_line(&mut s, part)?;
                }
            }
            // #EXT-X-GAP (RFC 8216bis §4.4.4.7, issue #872) — applies to
            // exactly this segment; rendered immediately before its #EXTINF.
            if seg.gap {
                s.push_str("#EXT-X-GAP\n");
            }
            // Format with exactly 3 decimal places per RFC 8216 examples.
            match &seg.title {
                Some(title) => {
                    validate_quoted_string(title, "EXTINF title")?;
                    s.push_str(&format!(
                        "#EXTINF:{},{title}\n",
                        format_extinf(seg.duration)
                    ));
                }
                None => {
                    s.push_str(&format!("#EXTINF:{},\n", format_extinf(seg.duration)));
                }
            }
            // #EXT-X-BYTERANGE (RFC 8216bis §4.4.4.2) — after EXTINF, before
            // the URI it applies to.
            if let Some(br) = &seg.byte_range {
                s.push_str(&format!("#EXT-X-BYTERANGE:{}\n", br.render()));
            }
            s.push_str(&seg.uri);
            s.push('\n');
        }

        // The in-progress (open) segment at the live edge — its parts are
        // known but it has not yet closed, so it carries no #EXTINF/URI
        // (RFC 8216bis §4.4.4.9). Its parts are rendered only for a
        // low-latency playlist (same opt-in gating as the closed segments'
        // parts above), but its segment-scoped pre-tags are always rendered
        // (audit BH-W5, issue #1111): the parse side only accumulates them
        // into an open segment when lines remain after the last URI, and
        // dropping them there would be the round-trip loss BH-W5 fixes.
        if let Some(open) = &self.open_segment {
            if self.low_latency.is_some() {
                // Same dedup-vs-previous rule as the closed segments' loop
                // above: `#EXT-X-MAP` applies until a new one is seen, so
                // only emit it here if it differs from the last *closed*
                // segment's map (or there were no closed segments at all).
                let prev_map = self.segments.last().and_then(|s| s.map.as_ref());
                if open.map.as_ref() != prev_map
                    && let Some(map) = &open.map
                {
                    push_map_line(&mut s, map)?;
                }
                // PDT precedes the open segment's first #EXT-X-PART (§4.4.4.9).
                if let Some(pdt) = &open.program_date_time {
                    s.push_str(&format!("#EXT-X-PROGRAM-DATE-TIME:{pdt}\n"));
                }
                for part in &open.parts {
                    push_part_line(&mut s, part)?;
                }
            } else if let Some(pdt) = &open.program_date_time {
                s.push_str(&format!("#EXT-X-PROGRAM-DATE-TIME:{pdt}\n"));
            }
            for tag in &open.pre_tags {
                s.push_str(tag);
                s.push('\n');
            }
        }

        // LL-HLS preload hint for the next not-yet-available part or map
        // (RFC 8216bis §4.4.5.3) — after the segment list, before ENDLIST.
        if let Some(ll) = &self.low_latency
            && let Some(uri) = &ll.preload_hint_part
        {
            s.push_str(&format!(
                "#EXT-X-PRELOAD-HINT:TYPE={},URI=\"{uri}\"",
                ll.preload_hint_type.name(),
            ));
            if let Some(start) = ll.preload_hint_byte_range_start {
                s.push_str(&format!(",BYTERANGE-START={start}"));
            }
            if let Some(len) = ll.preload_hint_byte_range_length {
                s.push_str(&format!(",BYTERANGE-LENGTH={len}"));
            }
            render_attribute_list(&mut s, &ll.ph_extra_attrs);
            s.push('\n');
        }

        // #EXT-X-RENDITION-REPORT entries (RFC 8216bis §4.4.5.4).
        for rr in &self.rendition_reports {
            s.push_str(&format!(
                "#EXT-X-RENDITION-REPORT:URI=\"{}\",LAST-MSN={}",
                rr.uri, rr.last_msn
            ));
            if let Some(lp) = rr.last_part {
                s.push_str(&format!(",LAST-PART={lp}"));
            }
            render_attribute_list(&mut s, &rr.extra_attrs);
            s.push('\n');
        }

        if self.endlist {
            s.push_str("#EXT-X-ENDLIST\n");
        }

        Ok(s)
    }

    /// Reject any field that would be rendered inside an RFC 8216 §4.2
    /// quoted-string or as a URI but contains `"`, CR or LF (audit BH-W7,
    /// issue #1111) — a tag/attribute-list injection vector for a playlist
    /// assembled from external data. Covers every field [`Self::to_m3u8`]
    /// emits; the per-tag renderers re-check the same values, so a caller
    /// that bypasses this method still cannot emit a malformed line.
    fn validate_for_render(&self) -> Result<()> {
        // Opaque verbatim lines: not a quoted-string, but a newline would
        // still split the line into two.
        validate_tag_body("playlist-level extra tag", &self.extra_tags)?;
        for seg in &self.segments {
            validate_uri(&seg.uri, "segment URI")?;
            if let Some(title) = &seg.title {
                validate_quoted_string(title, "EXTINF title")?;
            }
            validate_tag_body("segment pre-tag", &seg.pre_tags)?;
            for part in &seg.parts {
                validate_uri(&part.uri, "EXT-X-PART URI")?;
            }
            if let Some(map) = &seg.map {
                validate_uri(&map.uri, "EXT-X-MAP URI")?;
            }
        }
        if let Some(open) = &self.open_segment {
            validate_tag_body("open-segment pre-tag", &open.pre_tags)?;
            for part in &open.parts {
                validate_uri(&part.uri, "EXT-X-PART URI")?;
            }
            if let Some(map) = &open.map {
                validate_uri(&map.uri, "EXT-X-MAP URI")?;
            }
        }
        if let Some(ll) = &self.low_latency
            && let Some(uri) = &ll.preload_hint_part
        {
            validate_uri(uri, "EXT-X-PRELOAD-HINT URI")?;
        }
        for report in &self.rendition_reports {
            validate_uri(&report.uri, "EXT-X-RENDITION-REPORT URI")?;
        }
        if let Some(skip) = &self.skip {
            // RFC 8216bis §4.4.5.2: the ids are one quoted-string, tab (0x9)
            // delimited — so a tab inside an id would split it into two ids.
            for id in &skip.recently_removed_daterange_ids {
                validate_quoted_string(id, "EXT-X-SKIP RECENTLY-REMOVED-DATERANGES id")?;
                if id.contains('\t') {
                    return Err(Error::InvalidQuotedString {
                        what: "EXT-X-SKIP RECENTLY-REMOVED-DATERANGES id".to_string(),
                        bad_char: '\t',
                        value: id.clone(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Parse an RFC 8216bis `#EXTM3U` Media Playlist — the symmetric inverse
    /// of [`Self::to_m3u8`]. See the module docs for the recognized-tag list
    /// and the documented modeling gaps.
    ///
    /// Unrecognized `#EXT-...` tags are preserved verbatim into
    /// [`Self::extra_tags`] rather than erroring (forward-compat); a
    /// non-`#EXT` comment line (RFC 8216 §4.1) is silently ignored. A known
    /// tag with a missing required attribute or an unparsable value returns
    /// [`crate::Error::HlsParse`].
    pub fn parse(input: &str) -> Result<Self> {
        // `0` (not `1`): distinguishes "no #EXT-X-VERSION line was present
        // on the wire at all" from "the wire explicitly said version 1",
        // so a fully-untagged input round-trips back to no tag rather than
        // gaining one (see `effective_version`/issue #871).
        let mut version: u8 = 0;
        let mut target_duration: Option<u32> = None;
        let mut media_sequence: u64 = 0;
        let mut discontinuity_sequence: u64 = 0;
        let mut saw_discontinuity_sequence = false;
        let mut iframes_only = false;
        let mut endlist = false;
        let mut pending_title: Option<String> = None;
        let mut extra_tags: Vec<String> = Vec::new();
        let mut segments: Vec<MediaSegment> = Vec::new();
        let mut rendition_reports: Vec<RenditionReport> = Vec::new();
        let mut skip: Option<SkipInfo> = None;
        let mut saw_extm3u = false;
        // §4.4.2/§4.4.3.5 accumulators (issue #872).
        let mut independent_segments = false;
        let mut start: Option<StartPoint> = None;
        let mut defines: Vec<Define> = Vec::new();
        let mut playlist_type: Option<PlaylistType> = None;

        // Low-Latency HLS accumulators.
        let mut part_target: Option<DecimalSeconds> = None;
        let mut part_hold_back: Option<DecimalSeconds> = None;
        let mut can_skip_until: Option<DecimalSeconds> = None;
        let mut can_skip_dateranges = false;
        let mut hold_back: Option<DecimalSeconds> = None;
        // RFC 8216bis §4.4.3.8: absent CAN-BLOCK-RELOAD (or an absent
        // #EXT-X-SERVER-CONTROL tag entirely) means the server does NOT
        // support Blocking Playlist Reload — default false, not the
        // `LowLatencyConfig::default()` convenience value of true.
        let mut can_block_reload = false;
        let mut preload_hint_part: Option<String> = None;
        let mut preload_hint_type = PreloadHintType::Part;
        let mut preload_hint_byte_range_start: Option<u64> = None;
        let mut preload_hint_byte_range_length: Option<u64> = None;
        let mut saw_ll_tag = false;
        let mut sc_extra_attrs: Vec<(String, AttrValue)> = Vec::new();
        let mut pi_extra_attrs: Vec<(String, AttrValue)> = Vec::new();
        let mut ph_extra_attrs: Vec<(String, AttrValue)> = Vec::new();

        // Per-segment pending state, reset each time a bare URI line closes
        // a segment.
        let mut current_map: Option<MapTag> = None;
        let mut pending_discontinuous = false;
        let mut pending_byte_range: Option<ByteRange> = None;
        let mut pending_parts: Vec<PartSpec> = Vec::new();
        let mut pending_duration: Option<DecimalSeconds> = None;
        // §4.4.4.7/§4.4.4.8 per-segment state (issue #872): GAP applies only
        // to the next segment; BITRATE carries forward like MAP.
        let mut pending_gap = false;
        let mut current_bitrate: Option<u64> = None;
        // Segment-scoped unmodeled tags accumulated for the next segment
        // (audit BH-W5, issue #1111).
        let mut pending_pre_tags: Vec<String> = Vec::new();
        // Typed `#EXT-X-PROGRAM-DATE-TIME` for the next segment (issue #1423).
        let mut pending_program_date_time: Option<ProgramDateTime> = None;

        for (idx, raw_line) in input.lines().enumerate() {
            let line_no = idx + 1;
            let mut line = raw_line.trim_end_matches('\r');
            if line_no == 1 {
                line = line.strip_prefix('\u{feff}').unwrap_or(line);
            }
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            if line == "#EXTM3U" {
                saw_extm3u = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-VERSION:") {
                version = parse_decimal_int(rest, line_no, line, "EXT-X-VERSION")?;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-TARGETDURATION:") {
                target_duration = Some(parse_decimal_int(
                    rest,
                    line_no,
                    line,
                    "EXT-X-TARGETDURATION",
                )?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-MEDIA-SEQUENCE:") {
                media_sequence = parse_decimal_int(rest, line_no, line, "EXT-X-MEDIA-SEQUENCE")?;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-DISCONTINUITY-SEQUENCE:") {
                discontinuity_sequence =
                    parse_decimal_int(rest, line_no, line, "EXT-X-DISCONTINUITY-SEQUENCE")?;
                saw_discontinuity_sequence = true;
            } else if line == "#EXT-X-I-FRAMES-ONLY" {
                iframes_only = true;
            } else if line == "#EXT-X-INDEPENDENT-SEGMENTS" {
                independent_segments = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-START:") {
                start = Some(parse_start(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-DEFINE:") {
                defines.push(parse_define(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-PLAYLIST-TYPE:") {
                playlist_type = Some(match rest.trim() {
                    "EVENT" => PlaylistType::Event,
                    "VOD" => PlaylistType::Vod,
                    other => {
                        return Err(Error::HlsParse {
                            line_no,
                            line: line.to_string(),
                            reason: format!(
                                "EXT-X-PLAYLIST-TYPE value {other:?} is neither EVENT nor VOD"
                            ),
                        });
                    }
                });
            } else if line == "#EXT-X-ENDLIST" {
                endlist = true;
            } else if line == "#EXT-X-DISCONTINUITY" {
                pending_discontinuous = true;
            } else if line == "#EXT-X-GAP" {
                pending_gap = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-BITRATE:") {
                current_bitrate = Some(parse_decimal_int(rest, line_no, line, "EXT-X-BITRATE")?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-BYTERANGE:") {
                pending_byte_range = Some(ByteRange::parse(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-MAP:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                let uri = require_attr(&attrs, "URI", line_no, line, "EXT-X-MAP")?;
                let byte_range = match attrs.get("BYTERANGE") {
                    Some(v) => Some(ByteRange::parse(v, line_no, line)?),
                    None => None,
                };
                let extra_attrs = filter_extra_attrs(&attrs, &["URI", "BYTERANGE"], &quoted)?;
                current_map = Some(MapTag {
                    uri,
                    byte_range,
                    extra_attrs,
                });
            } else if let Some(rest) = line.strip_prefix("#EXTINF:") {
                let (dur_str, title) = match rest.split_once(',') {
                    Some((dur, title)) => (dur, title),
                    None => (rest, ""),
                };
                pending_duration = Some(parse_decimal_seconds(
                    dur_str,
                    line_no,
                    line,
                    "EXTINF duration",
                )?);
                // Audit BH-W11 (issue #1111): the title after the comma
                // (RFC 8216bis §4.4.4.1) is part of the tag, so keep it —
                // it used to be split off and thrown away.
                pending_title = (!title.is_empty()).then(|| title.to_string());
            } else if let Some(rest) = line.strip_prefix("#EXT-X-PART-INF:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                if let Some(v) = attrs.get("PART-TARGET") {
                    part_target = Some(parse_decimal_seconds(v, line_no, line, "PART-TARGET")?);
                }
                pi_extra_attrs.extend(filter_extra_attrs(&attrs, &["PART-TARGET"], &quoted)?);
                saw_ll_tag = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-SERVER-CONTROL:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                if let Some(v) = attrs.get("PART-HOLD-BACK") {
                    part_hold_back =
                        Some(parse_decimal_seconds(v, line_no, line, "PART-HOLD-BACK")?);
                }
                if let Some(v) = attrs.get("CAN-SKIP-UNTIL") {
                    can_skip_until =
                        Some(parse_decimal_seconds(v, line_no, line, "CAN-SKIP-UNTIL")?);
                }
                can_skip_dateranges =
                    attrs.get("CAN-SKIP-DATERANGES").map(String::as_str) == Some("YES");
                can_block_reload = attrs.get("CAN-BLOCK-RELOAD").map(String::as_str) == Some("YES");
                if let Some(v) = attrs.get("HOLD-BACK") {
                    hold_back = Some(parse_decimal_seconds(v, line_no, line, "HOLD-BACK")?);
                }
                sc_extra_attrs.extend(filter_extra_attrs(
                    &attrs,
                    &[
                        "PART-HOLD-BACK",
                        "CAN-SKIP-UNTIL",
                        "CAN-BLOCK-RELOAD",
                        "HOLD-BACK",
                        "CAN-SKIP-DATERANGES",
                    ],
                    &quoted,
                )?);
                saw_ll_tag = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-PART:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                let uri = require_attr(&attrs, "URI", line_no, line, "EXT-X-PART")?;
                let duration_str = attrs.get("DURATION").ok_or_else(|| Error::HlsParse {
                    line_no,
                    line: line.to_string(),
                    reason: "EXT-X-PART missing required DURATION attribute".to_string(),
                })?;
                let duration =
                    parse_decimal_seconds(duration_str, line_no, line, "EXT-X-PART DURATION")?;
                let independent = attrs.get("INDEPENDENT").map(String::as_str) == Some("YES");
                let gap = attrs.get("GAP").map(String::as_str) == Some("YES");
                let byte_range = match attrs.get("BYTERANGE") {
                    Some(v) => Some(ByteRange::parse(v, line_no, line)?),
                    None => None,
                };
                let extra_attrs = filter_extra_attrs(
                    &attrs,
                    &["URI", "DURATION", "INDEPENDENT", "GAP", "BYTERANGE"],
                    &quoted,
                )?;
                pending_parts.push(PartSpec {
                    uri,
                    duration,
                    independent,
                    byte_range,
                    gap,
                    extra_attrs,
                });
                saw_ll_tag = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-PRELOAD-HINT:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                preload_hint_type = match attrs.get("TYPE").map(String::as_str) {
                    Some("MAP") => PreloadHintType::Map,
                    _ => PreloadHintType::Part,
                };
                preload_hint_part = Some(require_attr(
                    &attrs,
                    "URI",
                    line_no,
                    line,
                    "EXT-X-PRELOAD-HINT",
                )?);
                if let Some(v) = attrs.get("BYTERANGE-START") {
                    preload_hint_byte_range_start =
                        Some(parse_decimal_int(v, line_no, line, "BYTERANGE-START")?);
                }
                if let Some(v) = attrs.get("BYTERANGE-LENGTH") {
                    preload_hint_byte_range_length =
                        Some(parse_decimal_int(v, line_no, line, "BYTERANGE-LENGTH")?);
                }
                ph_extra_attrs.extend(filter_extra_attrs(
                    &attrs,
                    &["TYPE", "URI", "BYTERANGE-START", "BYTERANGE-LENGTH"],
                    &quoted,
                )?);
                saw_ll_tag = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-RENDITION-REPORT:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                let uri = require_attr(&attrs, "URI", line_no, line, "EXT-X-RENDITION-REPORT")?;
                // Audit BH-W2 (issue #1111): LAST-MSN is REQUIRED
                // (RFC 8216bis §4.4.5.3); defaulting it to 0 fabricated a
                // report that sends clients to a long-gone segment.
                let last_msn_str =
                    require_attr(&attrs, "LAST-MSN", line_no, line, "EXT-X-RENDITION-REPORT")?;
                let last_msn = parse_decimal_int(&last_msn_str, line_no, line, "LAST-MSN")?;
                let last_part = match attrs.get("LAST-PART") {
                    Some(v) => Some(parse_decimal_int(v, line_no, line, "LAST-PART")?),
                    None => None,
                };
                let extra_attrs =
                    filter_extra_attrs(&attrs, &["URI", "LAST-MSN", "LAST-PART"], &quoted)?;
                rendition_reports.push(RenditionReport {
                    uri,
                    last_msn,
                    last_part,
                    extra_attrs,
                });
            } else if let Some(rest) = line.strip_prefix("#EXT-X-SKIP:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                let skipped_segments_str =
                    require_attr(&attrs, "SKIPPED-SEGMENTS", line_no, line, "EXT-X-SKIP")?;
                let skipped_segments =
                    parse_decimal_int(&skipped_segments_str, line_no, line, "SKIPPED-SEGMENTS")?;
                let recently_removed_daterange_ids = attrs
                    .get("RECENTLY-REMOVED-DATERANGES")
                    .map(|v| {
                        v.split('\t')
                            .filter(|s| !s.is_empty())
                            .map(ToString::to_string)
                            .collect()
                    })
                    .unwrap_or_default();
                let extra_attrs = filter_extra_attrs(
                    &attrs,
                    &["SKIPPED-SEGMENTS", "RECENTLY-REMOVED-DATERANGES"],
                    &quoted,
                )?;
                skip = Some(SkipInfo {
                    skipped_segments,
                    recently_removed_daterange_ids,
                    extra_attrs,
                });
            } else if let Some(rest) = line.strip_prefix("#EXT-X-PROGRAM-DATE-TIME:") {
                let pdt =
                    ProgramDateTime::parse(rest.trim()).map_err(|_| crate::Error::HlsParse {
                        line_no,
                        line: line.to_string(),
                        reason: "EXT-X-PROGRAM-DATE-TIME value is not a valid ISO 8601 date/time"
                            .to_string(),
                    })?;
                pending_program_date_time = Some(pdt);
            } else if let Some(rest) = line.strip_prefix("#EXT") {
                let _ = rest;
                // A well-formed but unrecognized tag: preserve verbatim
                // (forward-compat) rather than error or drop. A
                // segment-defining tag (`EXT-X-KEY`/`EXT-X-PROGRAM-DATE-TIME`/
                // `EXT-X-DATERANGE`/`EXT-X-CUE-*`) is attached to the
                // *following* segment so it re-renders in place; everything
                // else is playlist-level and goes in the header block
                // (audit BH-W5, issue #1111).
                if is_segment_defining_tag(line) {
                    pending_pre_tags.push(line.to_string());
                } else {
                    extra_tags.push(line.to_string());
                }
            } else if line.starts_with('#') {
                // RFC 8216 §4.1: a non-"#EXT" '#' line is a comment — ignore.
            } else {
                // A bare (non-'#') line is always a Media Segment URI; parts
                // have no URI line of their own (their URI is an attribute).
                let duration = pending_duration.take().ok_or_else(|| Error::HlsParse {
                    line_no,
                    line: line.to_string(),
                    reason: "media segment URI with no preceding #EXTINF".to_string(),
                })?;
                segments.push(MediaSegment {
                    uri: line.to_string(),
                    duration,
                    discontinuous: core::mem::take(&mut pending_discontinuous),
                    parts: core::mem::take(&mut pending_parts),
                    byte_range: pending_byte_range.take(),
                    map: current_map.clone(),
                    gap: core::mem::take(&mut pending_gap),
                    bitrate: current_bitrate,
                    title: pending_title.take(),
                    pre_tags: core::mem::take(&mut pending_pre_tags),
                    program_date_time: pending_program_date_time.take(),
                });
            }
        }

        if !saw_extm3u {
            return Err(Error::HlsParse {
                line_no: 1,
                line: String::new(),
                reason: "missing #EXTM3U header".to_string(),
            });
        }
        let target_duration = target_duration.ok_or_else(|| Error::HlsParse {
            line_no: 0,
            line: String::new(),
            reason: "missing required #EXT-X-TARGETDURATION".to_string(),
        })?;

        // Any parts accumulated but never closed by a following #EXTINF/URI
        // are the in-progress (open) segment at the live edge
        // (RFC 8216bis §4.4.4.9).
        let open_segment = if pending_parts.is_empty()
            && pending_pre_tags.is_empty()
            && pending_program_date_time.is_none()
        {
            None
        } else {
            let open = OpenSegment::new(core::mem::take(&mut pending_parts));
            let open = match &current_map {
                Some(map) => open.with_map(map.clone()),
                None => open,
            };
            Some(OpenSegment {
                pre_tags: core::mem::take(&mut pending_pre_tags),
                program_date_time: pending_program_date_time.take(),
                ..open
            })
        };

        if let (Some(start), Some(len)) = (
            preload_hint_byte_range_start,
            preload_hint_byte_range_length,
        ) && start.checked_add(len).is_none()
        {
            return Err(Error::HlsParse {
                line_no: 0,
                line: String::new(),
                reason: format!(
                    "PRELOAD-HINT BYTERANGE-START ({start}) + BYTERANGE-LENGTH ({len}) overflows u64"
                ),
            });
        }

        let low_latency = if saw_ll_tag {
            Some(LowLatencyConfig {
                part_target,
                part_hold_back,
                preload_hint_part,
                preload_hint_type,
                preload_hint_byte_range_start,
                preload_hint_byte_range_length,
                can_skip_until,
                can_block_reload,
                sc_extra_attrs,
                pi_extra_attrs,
                ph_extra_attrs,
                hold_back,
                can_skip_dateranges,
            })
        } else {
            None
        };

        Ok(MediaPlaylist {
            version,
            target_duration,
            media_sequence,
            discontinuity_sequence,
            always_emit_discontinuity_sequence: saw_discontinuity_sequence,
            segments,
            open_segment,
            endlist,
            extra_tags,
            low_latency,
            iframes_only,
            rendition_reports,
            skip,
            independent_segments,
            start,
            defines,
            playlist_type,
        })
    }
}

/// Render one `#EXT-X-PART:DURATION=<sec>,URI="<uri>"[,BYTERANGE="<n>[@<o>]"]
/// [,INDEPENDENT=YES][,GAP=YES]` line (RFC 8216bis §4.4.4.9) into `s`, shared
/// by both a closed segment's parts and an open (in-progress) segment's parts
/// so the two can never drift in format.
fn push_part_line(s: &mut String, part: &PartSpec) -> Result<()> {
    validate_uri(&part.uri, "EXT-X-PART URI")?;
    s.push_str(&format!(
        "#EXT-X-PART:DURATION={},URI=\"{}\"",
        format_secs(part.duration),
        part.uri,
    ));
    if let Some(br) = &part.byte_range {
        s.push_str(&format!(",BYTERANGE=\"{}\"", br.render()));
    }
    if part.independent {
        s.push_str(",INDEPENDENT=YES");
    }
    if part.gap {
        s.push_str(",GAP=YES");
    }
    render_attribute_list(s, &part.extra_attrs);
    s.push('\n');
    Ok(())
}

/// Render one `#EXT-X-MAP:URI="<uri>"[,BYTERANGE="<n>@<o>"]` line
/// (RFC 8216bis §4.4.4.5).
fn push_map_line(s: &mut String, map: &MapTag) -> Result<()> {
    validate_uri(&map.uri, "EXT-X-MAP URI")?;
    s.push_str(&format!("#EXT-X-MAP:URI=\"{}\"", map.uri));
    if let Some(br) = &map.byte_range {
        s.push_str(&format!(",BYTERANGE=\"{}\"", br.render()));
    }
    render_attribute_list(s, &map.extra_attrs);
    s.push('\n');
    Ok(())
}

/// Render one `#EXT-X-DEFINE:...` line (RFC 8216bis §4.4.2.3, issue #872).
fn push_define_line(s: &mut String, def: &Define) -> Result<()> {
    match def {
        Define::Name {
            name,
            value,
            extra_attrs,
        } => {
            validate_quoted_string(name, "EXT-X-DEFINE NAME")?;
            validate_quoted_string(value, "EXT-X-DEFINE VALUE")?;
            s.push_str(&format!("#EXT-X-DEFINE:NAME=\"{name}\",VALUE=\"{value}\""));
            render_attribute_list(s, extra_attrs);
            s.push('\n');
        }
        Define::Import { name, extra_attrs } => {
            validate_quoted_string(name, "EXT-X-DEFINE IMPORT")?;
            s.push_str(&format!("#EXT-X-DEFINE:IMPORT=\"{name}\""));
            render_attribute_list(s, extra_attrs);
            s.push('\n');
        }
        Define::QueryParam { name, extra_attrs } => {
            validate_quoted_string(name, "EXT-X-DEFINE QUERYPARAM")?;
            s.push_str(&format!("#EXT-X-DEFINE:QUERYPARAM=\"{name}\""));
            render_attribute_list(s, extra_attrs);
            s.push('\n');
        }
    }
    Ok(())
}

/// Parse an `#EXT-X-DEFINE:<attribute-list>` value (RFC 8216bis §4.4.2.3):
/// exactly one of `NAME` (+ required `VALUE`), `IMPORT`, `QUERYPARAM`.
fn parse_define(rest: &str, line_no: usize, line: &str) -> Result<Define> {
    let (attrs, quoted) = parse_attribute_list_strict(rest)?;
    let present = [
        attrs.contains_key("NAME"),
        attrs.contains_key("IMPORT"),
        attrs.contains_key("QUERYPARAM"),
    ]
    .iter()
    .filter(|&&b| b)
    .count();
    if present != 1 {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-DEFINE must contain exactly one of NAME, IMPORT, QUERYPARAM".to_string(),
        });
    }
    if let Some(name) = attrs.get("NAME") {
        let value = require_attr(&attrs, "VALUE", line_no, line, "EXT-X-DEFINE")?;
        let extra_attrs = filter_extra_attrs(&attrs, &["NAME", "VALUE"], &quoted)?;
        Ok(Define::Name {
            name: name.clone(),
            value,
            extra_attrs,
        })
    } else if let Some(name) = attrs.get("IMPORT") {
        let extra_attrs = filter_extra_attrs(&attrs, &["IMPORT"], &quoted)?;
        Ok(Define::Import {
            name: name.clone(),
            extra_attrs,
        })
    } else {
        let name = attrs
            .get("QUERYPARAM")
            .expect("exactly one of the three checked above")
            .clone();
        let extra_attrs = filter_extra_attrs(&attrs, &["QUERYPARAM"], &quoted)?;
        Ok(Define::QueryParam { name, extra_attrs })
    }
}

/// The wire representation of one attribute-list value (RFC 8216 §4.2):
/// whether it was written as a **quoted-string** or a **bare** token
/// (enumerated-string / decimal-integer / decimal-floating-point).
///
/// `extra_attrs` (every attribute this crate does not model as a typed
/// struct field) stores one of these per entry instead of a plain `String`,
/// recorded from the actual on-wire token at parse time, so quoting
/// round-trips losslessly — including for an attribute this crate has never
/// heard of (issue #1045 / audit BH-C1). A plain `String` alone cannot
/// represent this: `parse_attribute_list` must strip the surrounding `"` either
/// way to recover a quoted value's content, so by the time the value
/// reaches `extra_attrs` the two forms are indistinguishable unless
/// recorded explicitly.
///
/// Opaque by construction (issue #1045 T12, coordinator review): a value
/// that cannot be represented in its requested kind (a quoted-string
/// containing `"`/CR/LF, or a bare value containing a character that would
/// require quoting) is rejected by [`Self::quoted`]/[`Self::bare`] rather
/// than silently mangled (e.g. percent-encoded) or emitted raw — cf. #1129
/// ("never silently wrap/mangle an over-range value"). This keeps
/// rendering (`to_m3u8`) infallible without ever letting an invalid value
/// exist in the first place; parsing constructs through the same checks
/// (a value read off the wire can never fail them — see the module docs on
/// `parse_attribute_list`/`filter_extra_attrs`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttrValue {
    value: String,
    quoted: bool,
}

impl AttrValue {
    /// Build a quoted-string attribute value (RFC 8216 §4.2). Rejects a
    /// value containing `"`, CR or LF — a quoted-string must never contain
    /// any of them.
    pub fn quoted(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        if value.contains('"') || value.contains('\r') || value.contains('\n') {
            return Err(Error::InvalidAttrValue {
                value,
                kind: "a quoted-string",
            });
        }
        Ok(Self {
            value,
            quoted: true,
        })
    }

    /// Build a bare enumerated-string/decimal attribute value. Rejects a
    /// value containing `,`, `"`, CR, LF or whitespace, any of which would
    /// require quoting.
    pub fn bare(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        if value.contains(',')
            || value.contains('"')
            || value.contains('\r')
            || value.contains('\n')
            || value.contains(char::is_whitespace)
        {
            return Err(Error::InvalidAttrValue {
                value,
                kind: "a bare value",
            });
        }
        Ok(Self {
            value,
            quoted: false,
        })
    }

    /// The value's content, with wire quoting (if any) already stripped.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.value
    }

    /// Whether this value renders quoted (`"<content>"`) or bare.
    #[must_use]
    pub fn is_quoted(&self) -> bool {
        self.quoted
    }

    /// Build an [`AttrValue`] for a **programmatically constructed**
    /// attribute (e.g. assembling a fresh [`Variant`] rather than parsing
    /// one), choosing [`Self::quoted`] or [`Self::bare`] from a static
    /// table of known RFC 8216bis quoted-string attribute names
    /// (§4.4.6.2 / §4.4.6.2.1 — spec text at
    /// `specs/ietf_draft_pantos_hls_rfc8216bis.txt` lines 2637-2980) for a
    /// recognized name, falling back to sniffing the value's content for
    /// one this crate doesn't recognize (a non-`,`/`"`/whitespace/
    /// non-empty value is left unquoted). Prefer calling
    /// [`Self::quoted`]/[`Self::bare`] directly when the correct kind is
    /// already known — this is a convenience for the common case, not the
    /// source of truth (parsing always records the true wire form). Fails
    /// exactly when the chosen constructor would (the value contains a
    /// character forbidden for that kind).
    pub fn for_attr(name: &str, value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        match known_attr_value_kind(name) {
            Some(AttrValueKind::Quoted) => Self::quoted(value),
            Some(AttrValueKind::QuotedUnless(bare)) => {
                if value == bare {
                    Self::bare(value)
                } else {
                    Self::quoted(value)
                }
            }
            None => {
                if value.is_empty()
                    || value.contains(',')
                    || value.contains('"')
                    || value.contains(char::is_whitespace)
                {
                    Self::quoted(value)
                } else {
                    Self::bare(value)
                }
            }
        }
    }
}

/// `serde` support for [`AttrValue`] (issue #1140: `timed-metadata`'s
/// `DateRange::extra_attrs` needs to derive `Serialize`/`Deserialize`
/// through it). A blind field-derive would let an untrusted JSON payload
/// deserialize an `AttrValue` whose content was never checked by
/// [`AttrValue::quoted`]/[`AttrValue::bare`] — exactly the injection this
/// type exists to prevent — so `Deserialize` is hand-written to go through
/// those constructors instead.
#[cfg(feature = "serde")]
impl serde::Serialize for AttrValue {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> core::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut s = serializer.serialize_struct("AttrValue", 2)?;
        s.serialize_field("value", &self.value)?;
        s.serialize_field("quoted", &self.quoted)?;
        s.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for AttrValue {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> core::result::Result<Self, D::Error> {
        #[derive(serde::Deserialize)]
        struct Raw {
            value: String,
            quoted: bool,
        }
        let raw = Raw::deserialize(deserializer)?;
        if raw.quoted {
            AttrValue::quoted(raw.value)
        } else {
            AttrValue::bare(raw.value)
        }
        .map_err(serde::de::Error::custom)
    }
}

/// The RFC 8216bis §4.4.6.2 / §4.4.6.2.1 attribute-value *kind* for an
/// attribute name this crate does not model as a typed struct field —
/// used only by [`AttrValue::for_attr`]'s programmatic-construction
/// convenience (issue #1045 / audit BH-C1); parsing never consults this,
/// since it records the true wire form directly.
enum AttrValueKind {
    /// Always a quoted-string.
    Quoted,
    /// A quoted-string, *unless* the value is exactly this bare enumerated
    /// token (case-sensitive) — e.g. `CLOSED-CAPTIONS=NONE`.
    QuotedUnless(&'static str),
}

/// Known quoted-string attributes not modeled as typed fields on
/// [`Variant`]/[`IFrameVariant`] (`#EXT-X-STREAM-INF` / `#EXT-X-I-FRAME-
/// STREAM-INF`). Extend this list if a future unmodeled attribute is added
/// elsewhere; an attribute absent from it falls back to content-sniffing in
/// [`AttrValue::for_attr`].
fn known_attr_value_kind(name: &str) -> Option<AttrValueKind> {
    match name {
        "AUDIO"
        | "VIDEO"
        | "SUBTITLES"
        | "PATHWAY-ID"
        | "STABLE-VARIANT-ID"
        | "STABLE-RENDITION-ID"
        | "SUPPLEMENTAL-CODECS"
        | "REQ-VIDEO-LAYOUT"
        | "ALLOWED-CPC" => Some(AttrValueKind::Quoted),
        "CLOSED-CAPTIONS" => Some(AttrValueKind::QuotedUnless("NONE")),
        _ => None,
    }
}

/// Append `,NAME=VALUE` (or `,NAME="VALUE"`) for each attribute in an HLS
/// `<attribute-list>` (RFC 8216bis §4.2), in the given order, with no
/// leading tag prefix and no trailing newline.
///
/// This is the single attribute-list renderer for the workspace (issue
/// #1140 T12): `ssai-runtime` and `timed-metadata` each used to hand-format
/// `,NAME="VALUE"` themselves with no validation of the interpolated
/// content — an injection vector when that content comes from outside the
/// crate (a third-party ad-decision service, a caller-assembled
/// `DATERANGE`). Both now build a `Vec<(String, AttrValue)>` and call this
/// function instead.
///
/// Quoting is exactly what [`AttrValue`] records — no guessing at render
/// time, and infallible: an [`AttrValue`] can only ever hold content valid
/// for its kind (RFC 8216 §4.2's forbidden `"`/CR/LF in a quoted-string,
/// or `,`/`"`/CR/LF/whitespace in a bare value, are rejected at
/// construction — [`AttrValue::quoted`]/[`AttrValue::bare`], issue #1045
/// T12) — so there is nothing left to validate or sanitize here. A caller
/// assembling attributes from external data MUST go through those
/// constructors (or [`AttrValue::for_attr`]) first; this function itself
/// cannot fail.
pub fn render_attribute_list(s: &mut String, attrs: &[(String, AttrValue)]) {
    for (name, value) in attrs {
        s.push(',');
        s.push_str(name);
        s.push('=');
        if value.is_quoted() {
            s.push('"');
            s.push_str(value.as_str());
            s.push('"');
        } else {
            s.push_str(value.as_str());
        }
    }
}

/// RFC 8216 §4.2: a quoted-string is "a string ... enclosed in double
/// quotes"; it MUST NOT contain `"`, CR or LF. Every model field this crate
/// renders as a quoted-string attribute value or as a URI goes through the
/// constructors below, so a `\n` smuggled into a segment URI (e.g.
/// `"seg.m4s\n#EXT-X-ENDLIST"`) can never inject a tag line and an
/// embedded `"` can never break out of the attribute list (audit BH-W7,
/// issue #1111).
const QUOTED_STRING_FORBIDDEN: &[char] = &['"', '\r', '\n'];

/// Reject a value that cannot be rendered as an RFC 8216 §4.2
/// quoted-string (see [`QUOTED_STRING_FORBIDDEN`]).
fn validate_quoted_string(value: &str, what: &str) -> Result<()> {
    if let Some(bad) = value.chars().find(|c| QUOTED_STRING_FORBIDDEN.contains(c)) {
        return Err(Error::InvalidQuotedString {
            what: what.to_string(),
            bad_char: bad,
            value: value.to_string(),
        });
    }
    Ok(())
}

/// A tag line this crate re-emits verbatim (an opaque `extra_tags`/
/// `pre_tags` entry) is not a quoted-string, but it is one line: a CR or LF
/// inside it would split it into two lines and inject a tag (audit BH-W7,
/// issue #1111).
fn validate_tag_body(what: &str, tags: &[String]) -> Result<()> {
    for tag in tags {
        if let Some(bad) = tag.chars().find(|c| *c == '\r' || *c == '\n') {
            return Err(Error::InvalidQuotedString {
                what: what.to_string(),
                bad_char: bad,
                value: tag.clone(),
            });
        }
    }
    Ok(())
}

/// RFC 8216 §4.1: a URI line is the whole line, so a CR or LF inside one is
/// a tag/line injection; §4.2 forbids `"` in a quoted-string URI.
fn validate_uri(value: &str, what: &str) -> Result<()> {
    if let Some(bad) = value.chars().find(|c| QUOTED_STRING_FORBIDDEN.contains(c)) {
        return Err(Error::InvalidUri {
            what: what.to_string(),
            bad_char: bad,
            value: value.to_string(),
        });
    }
    Ok(())
}

/// Render the `#EXT-X-START:...` line (RFC 8216bis §4.4.2.2, issue #872).
fn push_start_line(s: &mut String, start: &StartPoint) {
    s.push_str(&format!(
        "#EXT-X-START:TIME-OFFSET={}",
        format_signed_secs(start.time_offset)
    ));
    if start.precise {
        s.push_str(",PRECISE=YES");
    }
    render_attribute_list(s, &start.extra_attrs);
    s.push('\n');
}

/// Parse the `#EXT-X-START:<attribute-list>` value.
fn parse_start(rest: &str, line_no: usize, line: &str) -> Result<StartPoint> {
    let (attrs, quoted) = parse_attribute_list_strict(rest)?;
    let time_offset_str = require_attr(&attrs, "TIME-OFFSET", line_no, line, "EXT-X-START")?;
    let time_offset = parse_signed_decimal_seconds(&time_offset_str, line_no, line, "TIME-OFFSET")?;
    let precise = attrs.get("PRECISE").map(String::as_str) == Some("YES");
    let extra_attrs = filter_extra_attrs(&attrs, &["TIME-OFFSET", "PRECISE"], &quoted)?;
    Ok(StartPoint {
        time_offset,
        precise,
        extra_attrs,
    })
}

/// Render one `#EXT-X-SESSION-DATA:...` line (RFC 8216bis §4.4.6.4, issue #872).
fn push_session_data_line(s: &mut String, sd: &SessionData) -> Result<()> {
    validate_quoted_string(&sd.data_id, "EXT-X-SESSION-DATA DATA-ID")?;
    s.push_str(&format!("#EXT-X-SESSION-DATA:DATA-ID=\"{}\"", sd.data_id));
    match &sd.content {
        SessionDataContent::Value(v) => {
            validate_quoted_string(v, "EXT-X-SESSION-DATA VALUE")?;
            s.push_str(&format!(",VALUE=\"{v}\""));
        }
        SessionDataContent::Uri { uri, format } => {
            validate_uri(uri, "EXT-X-SESSION-DATA URI")?;
            s.push_str(&format!(",URI=\"{uri}\""));
            if *format == SessionDataFormat::Raw {
                s.push_str(",FORMAT=RAW");
            }
        }
    }
    if let Some(lang) = &sd.language {
        validate_quoted_string(lang, "EXT-X-SESSION-DATA LANGUAGE")?;
        s.push_str(&format!(",LANGUAGE=\"{lang}\""));
    }
    render_attribute_list(s, &sd.extra_attrs);
    s.push('\n');
    Ok(())
}

/// Parse an `#EXT-X-SESSION-DATA:<attribute-list>` value.
fn parse_session_data(rest: &str, line_no: usize, line: &str) -> Result<SessionData> {
    let (attrs, quoted) = parse_attribute_list_strict(rest)?;
    let data_id = require_attr(&attrs, "DATA-ID", line_no, line, "EXT-X-SESSION-DATA")?;
    let value = attrs.get("VALUE");
    let uri = attrs.get("URI");
    let content = match (value, uri) {
        (Some(v), None) => SessionDataContent::Value(v.clone()),
        (None, Some(u)) => {
            let format = match attrs.get("FORMAT").map(String::as_str) {
                Some("RAW") => SessionDataFormat::Raw,
                _ => SessionDataFormat::Json,
            };
            SessionDataContent::Uri {
                uri: u.clone(),
                format,
            }
        }
        (Some(_), Some(_)) => {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: "EXT-X-SESSION-DATA must not contain both VALUE and URI".to_string(),
            });
        }
        (None, None) => {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: "EXT-X-SESSION-DATA must contain either VALUE or URI".to_string(),
            });
        }
    };
    let language = attrs.get("LANGUAGE").cloned();
    let known: &[&str] = match &content {
        SessionDataContent::Value(_) => &["DATA-ID", "VALUE", "LANGUAGE"],
        SessionDataContent::Uri { .. } => &["DATA-ID", "URI", "FORMAT", "LANGUAGE"],
    };
    let extra_attrs = filter_extra_attrs(&attrs, known, &quoted)?;
    Ok(SessionData {
        data_id,
        content,
        language,
        extra_attrs,
    })
}

/// Render one `#EXT-X-SESSION-KEY:...` line (RFC 8216bis §4.4.6.5, issue #872).
fn push_session_key_line(s: &mut String, sk: &SessionKey) -> Result<()> {
    s.push_str(&format!("#EXT-X-SESSION-KEY:METHOD={}", sk.method.name()));
    if let Some(uri) = &sk.uri {
        validate_uri(uri, "EXT-X-SESSION-KEY URI")?;
        s.push_str(&format!(",URI=\"{uri}\""));
    }
    if let Some(iv) = &sk.iv {
        s.push_str(&format!(",IV=0x{}", hex_encode(iv)));
    }
    if let Some(kf) = &sk.keyformat {
        validate_quoted_string(kf, "EXT-X-SESSION-KEY KEYFORMAT")?;
        s.push_str(&format!(",KEYFORMAT=\"{kf}\""));
    }
    if let Some(kfv) = &sk.keyformatversions {
        validate_quoted_string(kfv, "EXT-X-SESSION-KEY KEYFORMATVERSIONS")?;
        s.push_str(&format!(",KEYFORMATVERSIONS=\"{kfv}\""));
    }
    render_attribute_list(s, &sk.extra_attrs);
    s.push('\n');
    Ok(())
}

/// Parse an `#EXT-X-SESSION-KEY:<attribute-list>` value (same attribute set
/// as `#EXT-X-KEY`, RFC 8216bis §4.4.4.4, except METHOD MUST NOT be NONE).
fn parse_session_key(rest: &str, line_no: usize, line: &str) -> Result<SessionKey> {
    parse_key_attributes(rest, line_no, line, "EXT-X-SESSION-KEY", false)
}

/// Parse an `#EXT-X-KEY:<attribute-list>` value (RFC 8216 §4.3.2.4).
fn parse_media_key(rest: &str, line_no: usize, line: &str) -> Result<SessionKey> {
    parse_key_attributes(rest, line_no, line, "EXT-X-KEY", true)
}

fn parse_key_attributes(
    rest: &str,
    line_no: usize,
    line: &str,
    tag: &str,
    allow_none: bool,
) -> Result<SessionKey> {
    let (attrs, quoted) = parse_attribute_list_strict(rest)?;
    let method_str = require_attr(&attrs, "METHOD", line_no, line, tag)?;
    let method = match method_str.as_str() {
        "NONE" if allow_none => EncryptionMethod::None,
        "NONE" => {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: "EXT-X-SESSION-KEY METHOD MUST NOT be NONE (RFC 8216bis §4.4.6.5)"
                    .to_string(),
            });
        }
        "AES-128" => EncryptionMethod::Aes128,
        "SAMPLE-AES" => EncryptionMethod::SampleAes,
        "SAMPLE-AES-CTR" => EncryptionMethod::SampleAesCtr,
        "AES-256-GCM" => EncryptionMethod::Aes256Gcm,
        other => {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: format!("{tag} METHOD value {other:?} is not recognized"),
            });
        }
    };
    if method == EncryptionMethod::None && attrs.len() > 1 {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: format!(
                "{tag} METHOD=NONE MUST NOT carry other attributes (RFC 8216bis §4.4.4.4)"
            ),
        });
    }
    let uri = attrs.get("URI").cloned();
    let iv = match attrs.get("IV") {
        Some(v) => Some(parse_iv(v)?),
        None => None,
    };
    let keyformat = attrs.get("KEYFORMAT").cloned();
    let keyformatversions = attrs.get("KEYFORMATVERSIONS").cloned();
    let extra_attrs = filter_extra_attrs(
        &attrs,
        &["METHOD", "URI", "IV", "KEYFORMAT", "KEYFORMATVERSIONS"],
        &quoted,
    )?;
    Ok(SessionKey {
        method,
        uri,
        iv,
        keyformat,
        keyformatversions,
        extra_attrs,
    })
}

/// Parse a `0x`-prefixed hexadecimal-sequence attribute value into
/// exactly 16 bytes — the 128-bit IV of `#EXT-X-KEY`/`#EXT-X-SESSION-KEY`
/// (RFC 8216bis §4.4.4.4). Only the *encoder* half of hex lives in
/// `broadcast_common::hex` (see that module's doc comment); each consumer's
/// decode error type differs, so the decoder is local to this crate.
const IV_HEX_DIGITS: usize = 32;

fn parse_iv(s: &str) -> Result<[u8; 16]> {
    let hex = s
        .strip_prefix("0x")
        .or_else(|| s.strip_prefix("0X"))
        .filter(|h| h.len() == IV_HEX_DIGITS && h.bytes().all(|b| b.is_ascii_hexdigit()))
        .ok_or_else(|| Error::InvalidIv {
            value: s.to_string(),
        })?;
    let mut out = [0u8; 16];
    for i in 0..16 {
        // Safe: length and hex-digit-ness were just validated above.
        out[i] = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).expect("validated hex digits");
    }
    Ok(out)
}

/// Format a possibly-negative seconds value (RFC 8216bis §4.2
/// signed-decimal-floating-point — `#EXT-X-START`'s `TIME-OFFSET`), reusing
/// [`format_secs`] for the magnitude. Infallible: [`SignedDecimalSeconds`]
/// is always finite (issue #1140 T12/BH-W4), so there is no non-finite
/// case left to guard against.
fn format_signed_secs(v: SignedDecimalSeconds) -> String {
    let v = v.get();
    if v < 0.0 {
        // Safe: `-v` of a finite negative value is finite and non-negative.
        format!("-{}", format_secs(DecimalSeconds::new_unchecked(-v)))
    } else {
        format_secs(DecimalSeconds::new_unchecked(v))
    }
}

/// Format a non-negative seconds value as an HLS decimal-floating-point
/// (RFC 8216bis §4.2), **losslessly**.
///
/// Prefers the historical compact millisecond form (`0.334`, `1.5`, `6` —
/// trailing zeros trimmed) whenever that form re-parses to bit-identical
/// `v`, so output for the overwhelmingly common ms-granular case is
/// unchanged. When it would not (a real LL-HLS playlist's `2.00004`, a real
/// segment's `9.9766`), falls back to `core`'s `Display for f64`, which
/// emits the shortest decimal string that round-trips exactly — never
/// scientific notation, so the result is always valid §4.2 syntax.
///
/// The millisecond-rounding this replaced silently corrupted any duration
/// finer than 1 ms: `2.00004` rendered as `2`. Caught by round-tripping the
/// real Apple `fixtures/hls/real/` playlists (issue #872), which no
/// hand-made 3-decimal fixture could have surfaced.
fn format_secs(v: DecimalSeconds) -> String {
    // Infallible (issue #1140 T12/BH-W4): `DecimalSeconds` is always finite
    // and non-negative, so there is no NaN/inf/negative case left to guard
    // against here — the validation lives entirely at construction.
    let v = v.get();
    let millis = (v * 1000.0 + 0.5) as u64;
    let whole = millis / 1000;
    let frac = millis % 1000;
    let compact = if frac == 0 {
        format!("{whole}")
    } else {
        let mut f = format!("{frac:03}");
        while f.ends_with('0') {
            f.pop();
        }
        format!("{whole}.{f}")
    };
    if compact.parse::<f64>() == Ok(v) {
        return compact;
    }
    format!("{v}")
}

/// Format an `#EXTINF` duration losslessly (RFC 8216bis §4.4.4.1).
///
/// Three tiers, in order:
///
/// 1. **An exactly-whole number of seconds renders as an integer** (`4.0` ->
///    `4`), so the playlist contains no floating-point duration value and is
///    honestly compatible with protocol version 1 (§8 row 3 — see
///    [`is_fractional_duration`], which is defined in terms of this
///    function). Rendering `4.000` here instead declared a float while
///    emitting no `EXT-X-VERSION`, locking a v1/v2 client into a value it
///    cannot parse.
///
///    §4.4.4.1 makes this a MUST, not merely an option: `duration` "is a
///    decimal-floating-point **or decimal-integer** number", and "if the
///    compatibility version number is less than 3, durations MUST be
///    integers". Emitting no `EXT-X-VERSION` tag means version 1, so an
///    integral render is the only conforming output. (§4.4.4.1 also SHOULDs
///    that durations be floating-point for accuracy — but that is authoring
///    advice subordinate to the MUST, and it is satisfied the moment a
///    caller supplies a genuinely fractional duration, which every real
///    keyframe-cutting segmenter does.)
/// 2. Otherwise the historical fixed 3-decimal rendering (`9.009` — the form
///    every RFC 8216 example and every existing consumer of this crate
///    expects) whenever it re-parses to bit-identical `v`.
/// 3. Otherwise the shortest exactly-round-tripping decimal, same rule as
///    [`format_secs`]. A hardcoded `{:.3}` alone loses real-world precision —
///    Apple's BipBop playlists carry `#EXTINF:9.9766`, which would render
///    back as `9.977` (issue #882).
fn format_extinf(v: DecimalSeconds) -> String {
    // Infallible, same reasoning as `format_secs` (issue #1140 T12/BH-W4).
    let v = v.get();
    if let Some(whole) = whole_seconds(v) {
        return format!("{whole}");
    }
    let three = format!("{v:.3}");
    if three.parse::<f64>() == Ok(v) {
        return three;
    }
    format!("{v}")
}

/// `Some(n)` if `v` is exactly the whole number of seconds `n`, else `None`.
///
/// Uses an integer cast rather than `f64::fract()`, which is `std`-only and
/// unavailable to this `no_std`+`alloc` crate (same constraint that shaped
/// [`format_secs`]). The round-trip comparison is what makes it exact: a
/// value with any fractional part, however small, fails `(v as u64) as f64
/// == v` and is rejected.
fn whole_seconds(v: f64) -> Option<u64> {
    if !v.is_finite() || !(0.0..WHOLE_SECONDS_CAST_LIMIT).contains(&v) {
        return None;
    }
    let whole = v as u64;
    (whole as f64 == v).then_some(whole)
}

/// Upper bound for the `f64 -> u64` cast in [`whole_seconds`]. Beyond 2^53 an
/// `f64` cannot represent consecutive integers anyway, so a duration that
/// large is not a meaningful segment length; falling through to the decimal
/// path is the safe answer.
const WHOLE_SECONDS_CAST_LIMIT: f64 = 9_007_199_254_740_992.0; // 2^53

/// Parse an RFC 8216bis §4.2 `decimal-floating-point` value into `f64` with
/// the strict lexical grammar (audit BH-W4, issue #1111). `f64::from_str`
/// alone accepts `nan`, `inf`, `infinity`, a leading `+`, and exponent
/// notation — none of which §4.2 allows — so `#EXTINF:nan,` previously
/// parsed `Ok` into a NaN duration that a downstream range check
/// (`x < lo || x > hi`) silently treated as in-range. `signed` is true only
/// where the spec allows a signed-decimal (TIME-OFFSET, §4.4.2.2).
fn parse_decimal_float(
    s: &str,
    line_no: usize,
    line: &str,
    what: &str,
    signed: bool,
) -> Result<f64> {
    let t = s.trim();
    if !is_valid_decimal_token(t, signed) {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: format!("{what} value {s:?} is not a valid decimal number"),
        });
    }
    // The grammar above accepts only finite values (non-negative unless
    // `signed`).
    t.parse::<f64>().map_err(|_| Error::HlsParse {
        line_no,
        line: line.to_string(),
        reason: format!("{what} value {s:?} is not a valid number"),
    })
}

/// Parse an RFC 8216bis §4.2 `decimal-integer` into `T` with the strict
/// lexical grammar (audit BH-W4, issue #1111). The integer `from_str` impls
/// reject `nan`/`inf`/exponent notation on their own, but they *accept* a
/// leading `+` (e.g. `BANDWIDTH=+7`), which §4.2's decimal-integer grammar
/// does not allow. `parse_decimal_float` covers the float attributes; every
/// integer attribute parse goes through here.
fn parse_decimal_int<T: core::str::FromStr>(
    s: &str,
    line_no: usize,
    line: &str,
    what: &str,
) -> Result<T> {
    let t = s.trim();
    if !is_valid_decimal_token(t, false) {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: format!("{what} value {s:?} is not a valid decimal integer"),
        });
    }
    t.parse::<T>().map_err(|_| Error::HlsParse {
        line_no,
        line: line.to_string(),
        reason: format!("{what} value {s:?} is not a valid number"),
    })
}

/// Validate an RFC 8216bis §4.2 `decimal-floating-point` (or
/// `decimal-integer`) token's *lexical form* before handing it to
/// `f64::from_str`: `-`? (if `signed`) `[0-9]+` (`.` `[0-9]+`)? — nothing
/// else. `f64::from_str` alone is far more permissive than the spec (it
/// also accepts `nan`, `inf`, `infinity`, a leading `+`, and exponent
/// notation, none of which §4.2 allows) and would otherwise let
/// `#EXTINF:nan,` (audit BH-W4) parse successfully into a NaN duration
/// that a downstream range check (`x < lo || x > hi`) silently treats as
/// in-range, or that panics `Duration::from_secs_f64` later. Only
/// `TIME-OFFSET` accepts a sign, per §4.4.2.2.
fn is_valid_decimal_token(s: &str, signed: bool) -> bool {
    let s = s.strip_prefix('-').filter(|_| signed).unwrap_or(s);
    let (int_part, frac_part) = match s.split_once('.') {
        Some((i, f)) => (i, Some(f)),
        None => (s, None),
    };
    if int_part.is_empty() || !int_part.bytes().all(|b| b.is_ascii_digit()) {
        return false;
    }
    match frac_part {
        Some(f) => !f.is_empty() && f.bytes().all(|b| b.is_ascii_digit()),
        None => true,
    }
}

/// A validated RFC 8216bis §4.2 `decimal-floating-point` seconds value:
/// always finite and non-negative. The field type for every unsigned
/// duration attribute this crate models (`EXTINF`, `PART-TARGET`,
/// `PART-HOLD-BACK`, `CAN-SKIP-UNTIL`, `HOLD-BACK`, `EXT-X-PART`
/// `DURATION`) — issue #1140 T12/BH-W4: previously a directly-constructed
/// `f64` field could hold NaN/infinite/negative, and the (necessarily
/// infallible) `to_m3u8` renderer clamped it to `"0"` rather than ever
/// emitting invalid syntax. With the value validated at construction, no
/// invalid value can exist for the renderer to have to defend against.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DecimalSeconds(f64);

impl DecimalSeconds {
    /// `0.0` — always valid; the natural default.
    pub const ZERO: Self = Self(0.0);

    /// Validate `value`: finite and non-negative, or
    /// [`Error::InvalidDecimalSeconds`].
    pub fn new(value: f64) -> Result<Self> {
        if value.is_finite() && value >= 0.0 {
            Ok(Self(value))
        } else {
            Err(Error::InvalidDecimalSeconds(value))
        }
    }

    /// The validated seconds value.
    #[must_use]
    pub fn get(self) -> f64 {
        self.0
    }

    /// Construct without re-validating — only for a value already known
    /// valid (this module's own strict-grammar parse, or a literal/`ZERO`).
    fn new_unchecked(value: f64) -> Self {
        debug_assert!(value.is_finite() && value >= 0.0, "{value} must be valid");
        Self(value)
    }
}

impl Default for DecimalSeconds {
    fn default() -> Self {
        Self::ZERO
    }
}

impl core::fmt::Display for DecimalSeconds {
    /// Delegates to `f64`'s own `Display` (not `format_secs`, which is
    /// this crate's specific §4.2 wire-syntax renderer) — for a caller
    /// that just wants to print the value.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.0, f)
    }
}

/// As [`DecimalSeconds`], but signed — the one field RFC 8216bis allows to
/// be negative (`TIME-OFFSET`, §4.4.2.2: negative means "from the end of
/// the last Media Segment").
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SignedDecimalSeconds(f64);

impl SignedDecimalSeconds {
    /// `0.0` — always valid.
    pub const ZERO: Self = Self(0.0);

    /// Validate `value`: finite, or [`Error::InvalidSignedDecimalSeconds`].
    pub fn new(value: f64) -> Result<Self> {
        if value.is_finite() {
            Ok(Self(value))
        } else {
            Err(Error::InvalidSignedDecimalSeconds(value))
        }
    }

    /// The validated seconds value.
    #[must_use]
    pub fn get(self) -> f64 {
        self.0
    }

    /// Construct without re-validating — only for a value already known
    /// valid.
    fn new_unchecked(value: f64) -> Self {
        debug_assert!(value.is_finite(), "{value} must be finite");
        Self(value)
    }
}

impl core::fmt::Display for SignedDecimalSeconds {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.0, f)
    }
}

/// Parse an RFC 8216bis §4.2 decimal-floating-point seconds value
/// (`EXTINF`, `PART`/`PART-INF`/`SERVER-CONTROL` durations — all
/// non-negative) with the strict lexical grammar [`is_valid_decimal_token`]
/// checks, rather than `f64::from_str`'s much wider grammar (issue #1140 /
/// audit BH-W4).
fn parse_decimal_seconds(
    s: &str,
    line_no: usize,
    line: &str,
    what: &str,
) -> Result<DecimalSeconds> {
    // The grammar in `parse_decimal_float` accepts only finite,
    // non-negative values.
    parse_decimal_float(s, line_no, line, what, false).map(DecimalSeconds::new_unchecked)
}

/// As [`parse_decimal_seconds`], but also accepts a leading `-` — used only
/// for `#EXT-X-START`'s `TIME-OFFSET` (RFC 8216bis §4.4.2.2, which allows a
/// negative offset from the end of the playlist).
fn parse_signed_decimal_seconds(
    s: &str,
    line_no: usize,
    line: &str,
    what: &str,
) -> Result<SignedDecimalSeconds> {
    // The grammar in `parse_decimal_float` accepts only finite values.
    parse_decimal_float(s, line_no, line, what, true).map(SignedDecimalSeconds::new_unchecked)
}

/// Split an HLS `<attribute-list>` (RFC 8216bis §4.2: comma-separated
/// `AttributeName=AttributeValue` pairs, where a quoted-string value may
/// itself contain commas) into a name → value map, plus the set of names
/// whose value was written as a quoted-string on the wire.
///
/// This is the single attribute-list tokenizer for the workspace (issue
/// #1140 T12): `ssai-runtime` and `timed-metadata` each carried their own
/// copy of this exact honour-quoted-commas algorithm (audit r14-SSAI-O1);
/// both now call this function instead. Quoted values are returned with
/// their surrounding `"` stripped; unquoted (enumerated-string / decimal)
/// values are returned as-is — named/typed attribute extraction (every
/// `require_attr`/`.get(...)` call site) reads only the value map (issue
/// #1045 / audit BH-C1 — `filter_extra_attrs` uses the quoted-name set to
/// build a lossless [`AttrValue`] per unmodeled attribute).
pub fn parse_attribute_list(s: &str) -> (BTreeMap<String, String>, BTreeSet<String>) {
    scan_attribute_list(s, false).unwrap_or_default()
}

/// Strict [`parse_attribute_list`]: an unterminated quoted-string is
/// [`Error::UnterminatedQuotedString`] and a repeated `AttributeName` is
/// [`Error::DuplicateAttribute`] (RFC 8216bis §4.2: "A given AttributeName
/// MUST NOT appear more than once in a given AttributeList"). Every typed
/// playlist parser in this crate uses this form.
pub fn parse_attribute_list_strict(
    s: &str,
) -> Result<(BTreeMap<String, String>, BTreeSet<String>)> {
    scan_attribute_list(s, true)
}

fn scan_attribute_list(
    s: &str,
    strict: bool,
) -> Result<(BTreeMap<String, String>, BTreeSet<String>)> {
    let mut map = BTreeMap::new();
    let mut quoted_keys = BTreeSet::new();
    let bytes = s.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    while i < len {
        while i < len && (bytes[i] == b',' || bytes[i].is_ascii_whitespace()) {
            i += 1;
        }
        if i >= len {
            break;
        }
        let key_start = i;
        while i < len && bytes[i] != b'=' {
            i += 1;
        }
        if i >= len {
            break;
        }
        let key = &s[key_start..i];
        i += 1;
        let quoted = i < len && bytes[i] == b'"';
        let value = if quoted {
            i += 1;
            let value_start = i;
            while i < len && bytes[i] != b'"' {
                i += 1;
            }
            let value = &s[value_start..i];
            if i < len {
                i += 1;
            } else if strict {
                return Err(Error::UnterminatedQuotedString {
                    list: s.to_string(),
                });
            }
            value
        } else {
            let value_start = i;
            while i < len && bytes[i] != b',' {
                i += 1;
            }
            &s[value_start..i]
        };
        if strict && map.contains_key(key) {
            return Err(Error::DuplicateAttribute {
                name: key.to_string(),
            });
        }
        map.insert(key.to_string(), value.to_string());
        if quoted {
            quoted_keys.insert(key.to_string());
        }
    }
    Ok((map, quoted_keys))
}

/// From an already-parsed attribute map, collect every attribute whose name
/// is not in `known` into a `Vec<(name, AttrValue)>`, sorted by name for
/// deterministic serialization. `quoted` (from [`parse_attribute_list`]) decides
/// [`AttrValue::quoted`] vs. [`AttrValue::bare`] per entry — the recorded
/// wire form, not a guess (issue #1045 / audit BH-C1).
///
/// Fallible because [`AttrValue::quoted`]/[`AttrValue::bare`] validate their
/// content (issue #1045 T12); in practice this can only fail for a
/// malformed *bare* token whose text happens to contain `"` or whitespace
/// (a bare token's own scan stops at the next `,`, so it can hold those; a
/// quoted token's content can never contain an unescaped `"`, and neither
/// form can span a CR/LF since input is split into lines first).
fn filter_extra_attrs(
    attrs: &BTreeMap<String, String>,
    known: &[&str],
    quoted: &BTreeSet<String>,
) -> Result<Vec<(String, AttrValue)>> {
    attrs
        .iter()
        .filter(|(k, _)| !known.contains(&k.as_str()))
        .map(|(k, v)| {
            let value = if quoted.contains(k) {
                AttrValue::quoted(v.clone())?
            } else {
                AttrValue::bare(v.clone())?
            };
            Ok((k.clone(), value))
        })
        .collect()
}

/// Segment-scoped, *segment-defining* tags this crate does not model with a
/// typed field (RFC 8216bis §4.4.4.4 `EXT-X-KEY`, §4.4.4.3
/// `EXT-X-PROGRAM-DATE-TIME`, §4.4.5.1 `EXT-X-DATERANGE`, and the
/// `EXT-X-CUE-*` ad-marker family — a de-facto `EXT-X-CUE-OUT`/`EXT-X-CUE-IN`
/// convention the spec text does not define, matched by prefix here):
/// per §4.4.1 each applies until the next occurrence or the end of the
/// Playlist, so its position relative to segments is load-bearing.
/// `MediaPlaylist::parse` attaches such lines to the following segment's
/// [`MediaSegment::pre_tags`] instead of hoisting them into the
/// playlist-level `extra_tags` block (audit BH-W5, issue #1111).
fn is_segment_defining_tag(line: &str) -> bool {
    const SEGMENT_SCOPED: &[&str] = &["#EXT-X-KEY:", "#EXT-X-DATERANGE:", "#EXT-X-CUE-"];
    SEGMENT_SCOPED.iter().any(|prefix| line.starts_with(prefix))
}

/// Fetch a required attribute from an already-parsed attribute map, or
/// return a contextual [`crate::Error::HlsParse`] naming the missing
/// attribute and the owning tag.
fn require_attr(
    attrs: &BTreeMap<String, String>,
    key: &str,
    line_no: usize,
    line: &str,
    tag: &str,
) -> Result<String> {
    attrs.get(key).cloned().ok_or_else(|| Error::HlsParse {
        line_no,
        line: line.to_string(),
        reason: format!("{tag} missing required {key} attribute"),
    })
}

/// `VIDEO-RANGE` attribute of `#EXT-X-STREAM-INF` (RFC 8216bis §4.4.6.2,
/// spec text at `specs/ietf_draft_pantos_hls_rfc8216bis.txt` lines 2786-2815):
/// an enumerated bare token describing the dynamic range of the variant's video.
///
/// `SDR` for CICP transfer characteristics 1, 6, 13, 14, 15; `HLG` for 18;
/// `PQ` for 16. Any other code point (including 2 "unspecified" and the
/// reserved values) has no mapping and the attribute is omitted (absence
/// implies SDR).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum VideoRange {
    /// Standard dynamic range (`VIDEO-RANGE=SDR`).
    Sdr,
    /// Hybrid Log-Gamma (`VIDEO-RANGE=HLG`).
    Hlg,
    /// Perceptual Quantizer (`VIDEO-RANGE=PQ`).
    Pq,
}

impl VideoRange {
    /// The spec token (`"SDR"` / `"HLG"` / `"PQ"`), rendered bare and
    /// unquoted on the wire.
    pub fn name(&self) -> &'static str {
        match self {
            VideoRange::Sdr => "SDR",
            VideoRange::Hlg => "HLG",
            VideoRange::Pq => "PQ",
        }
    }

    /// Map a CICP transfer-characteristics code point (the value returned by
    /// `transmux`'s `TransferCharacteristics::code()`) to a [`VideoRange`],
    /// per RFC 8216bis §4.4.6.2. Returns `None` for any code point with no
    /// defined mapping (including 2 "unspecified" and reserved values), so
    /// the caller omits the attribute rather than inventing a value.
    pub fn from_transfer_characteristics(code: u8) -> Option<Self> {
        // Named CICP transfer-characteristics code points (H.264 Table E-4 /
        // H.265 Table E.4), per RFC 8216bis §4.4.6.2.
        const TRANSFER_BT709: u8 = 1;
        const TRANSFER_BT601: u8 = 6;
        const TRANSFER_IEC_61966_2_1: u8 = 13;
        const TRANSFER_BT2020_10BIT: u8 = 14;
        const TRANSFER_BT2020_12BIT: u8 = 15;
        const TRANSFER_SMPTE_ST_2084: u8 = 16;
        const TRANSFER_ARIB_STD_B67: u8 = 18;
        match code {
            TRANSFER_BT709
            | TRANSFER_BT601
            | TRANSFER_IEC_61966_2_1
            | TRANSFER_BT2020_10BIT
            | TRANSFER_BT2020_12BIT => Some(Self::Sdr),
            TRANSFER_SMPTE_ST_2084 => Some(Self::Pq),
            TRANSFER_ARIB_STD_B67 => Some(Self::Hlg),
            _ => None,
        }
    }

    /// Build the `("VIDEO-RANGE", AttrValue::bare(...))` extra attribute
    /// for a [`Variant`]/[`IFrameVariant`] `extra_attrs` list (or any
    /// attribute list assembled for `#EXT-X-STREAM-INF`), per RFC 8216bis
    /// §4.4.6.2. The value is the bare enumerated token
    /// (`"SDR"`/`"HLG"`/`"PQ"`).
    pub fn attr(self) -> (String, AttrValue) {
        (
            String::from("VIDEO-RANGE"),
            AttrValue::bare(self.name()).expect("VIDEO-RANGE token is a valid bare value"),
        )
    }
}

broadcast_common::impl_spec_display!(VideoRange);

/// `FRAME-RATE` for an `#EXT-X-STREAM-INF` — Apple HLS authoring
/// specification item 9.15 (MUST for every variant that includes video) and
/// RFC 8216bis §4.4.6.2 (`decimal-floating-point`).
///
/// Stored as an exact integer number of millihertz (1/1000 Hz), so the wire
/// form `FRAME-RATE=<int>.<3 digits>` (e.g. `25.000`, `29.970`,
/// `59.940`) is rendered and parsed without any floating-point rounding.
/// Construct with [`FrameRate::from_millihertz`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameRate(u32);

impl FrameRate {
    /// Build a [`FrameRate`] from an exact millihertz value.
    #[must_use]
    pub fn from_millihertz(millihertz: u32) -> Self {
        Self(millihertz)
    }

    /// The frame rate in millihertz (1/1000 Hz).
    #[must_use]
    pub fn millihertz(self) -> u32 {
        self.0
    }
}

impl core::fmt::Display for FrameRate {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let whole = self.0 / 1000;
        let frac = self.0 % 1000;
        write!(f, "{whole}.{frac:03}")
    }
}

impl core::str::FromStr for FrameRate {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self> {
        parse_frame_rate(s, 0, s)
    }
}

/// Media type of an `#EXT-X-MEDIA` rendition (RFC 8216bis §4.4.6.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum MediaType {
    /// Audio rendition.
    #[default]
    Audio,
    /// Video rendition.
    Video,
    /// Subtitle rendition.
    Subtitles,
    /// Closed-caption rendition (carried in-band; no URI).
    ClosedCaptions,
}

impl MediaType {
    /// The spec token (`"AUDIO"` / `"VIDEO"` / `"SUBTITLES"` /
    /// `"CLOSED-CAPTIONS"`).
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            MediaType::Audio => "AUDIO",
            MediaType::Video => "VIDEO",
            MediaType::Subtitles => "SUBTITLES",
            MediaType::ClosedCaptions => "CLOSED-CAPTIONS",
        }
    }
}

broadcast_common::impl_spec_display!(MediaType);

/// Typed `INSTREAM-ID` value for an `#EXT-X-MEDIA` rendition
/// (RFC 8216bis §4.4.6.1).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum InstreamId {
    /// A Line 21 Data Services channel (`"CC1"`..`"CC4"`).
    Cc(u8),
    /// A Digital Television Closed Captioning service block
    /// (`"SERVICE1"`..`"SERVICE63"`).
    Service(u8),
    /// Any other in-band rendition identifier (non-closed-caption types).
    Other(String),
}

const INSTREAM_CC_PREFIX: &str = "CC";
const INSTREAM_SERVICE_PREFIX: &str = "SERVICE";
const INSTREAM_CC_RANGE: core::ops::RangeInclusive<u8> = 1..=4;
const INSTREAM_SERVICE_RANGE: core::ops::RangeInclusive<u8> = 1..=63;

impl InstreamId {
    /// Render the wire form.
    #[must_use]
    pub fn render(&self) -> String {
        match self {
            InstreamId::Cc(n) => format!("{INSTREAM_CC_PREFIX}{n}"),
            InstreamId::Service(n) => format!("{INSTREAM_SERVICE_PREFIX}{n}"),
            InstreamId::Other(s) => s.clone(),
        }
    }

    /// Parse a closed-caption `INSTREAM-ID` value, rejecting `CC5+` and
    /// `SERVICE0`/`SERVICE64+`.
    pub fn parse_closed_captions(value: &str) -> Result<Self> {
        let invalid = || Error::InvalidInstreamId {
            value: value.to_string(),
        };
        let canonical_decimal = |digits: &str| -> Option<u8> {
            let well_formed = !digits.is_empty()
                && digits.bytes().all(|b| b.is_ascii_digit())
                && !digits.starts_with('0');
            well_formed.then(|| digits.parse().ok()).flatten()
        };
        if let Some(rest) = value.strip_prefix(INSTREAM_CC_PREFIX) {
            return canonical_decimal(rest)
                .filter(|n| INSTREAM_CC_RANGE.contains(n))
                .map(InstreamId::Cc)
                .ok_or_else(invalid);
        }
        if let Some(rest) = value.strip_prefix(INSTREAM_SERVICE_PREFIX) {
            return canonical_decimal(rest)
                .filter(|n| INSTREAM_SERVICE_RANGE.contains(n))
                .map(InstreamId::Service)
                .ok_or_else(invalid);
        }
        Err(invalid())
    }
}

/// Typed reference to a closed-caption group on a `Variant`
/// (RFC 8216bis §4.4.6.2).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClosedCaptionsRef {
    /// A quoted `GROUP-ID` value referencing an `#EXT-X-MEDIA` group.
    Group(String),
    /// The enumerated, unquoted token `NONE`.
    None,
}

/// A single `#EXT-X-MEDIA` rendition entry in a multivariant playlist
/// (RFC 8216bis §4.4.6.1).
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct MediaRendition {
    /// `TYPE` attribute (REQUIRED).
    pub media_type: MediaType,
    /// `URI` attribute (optional; MUST NOT be present for closed captions).
    pub uri: Option<String>,
    /// `GROUP-ID` attribute (REQUIRED, non-empty).
    pub group_id: String,
    /// `LANGUAGE` attribute.
    pub language: Option<String>,
    /// `ASSOC-LANGUAGE` attribute.
    pub assoc_language: Option<String>,
    /// `NAME` attribute (REQUIRED, non-empty).
    pub name: String,
    /// `STABLE-RENDITION-ID` attribute.
    pub stable_rendition_id: Option<String>,
    /// `DEFAULT` attribute (absence implies NO).
    pub default: bool,
    /// `AUTOSELECT` attribute (absence implies NO).
    pub autoselect: bool,
    /// `FORCED` attribute (absence implies NO; only for subtitles).
    pub forced: bool,
    /// `INSTREAM-ID` attribute.
    pub instream_id: Option<InstreamId>,
    /// `BIT-DEPTH` attribute (audio only).
    pub bit_depth: Option<u32>,
    /// `SAMPLE-RATE` attribute (audio only).
    pub sample_rate: Option<u32>,
    /// `CHARACTERISTICS` attribute, split into individual MCTs.
    pub characteristics: Vec<String>,
    /// `CHANNELS` attribute (audio only).
    pub channels: Option<String>,
    /// Unmodeled attributes, retained for forward-compat / `REQ-` scanning.
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// A variant stream entry in a master playlist.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Variant {
    /// `BANDWIDTH` in bits per second.
    pub bandwidth: u32,
    /// `AVERAGE-BANDWIDTH` in bits per second (RFC 8216bis §4.4.6.2), or
    /// `None` when the `#EXT-X-STREAM-INF` carried no `AVERAGE-BANDWIDTH`
    /// attribute. Apple's HLS authoring specification item 9.14 requires an
    /// authored multivariant playlist to carry it; this crate models the
    /// attribute (parse and render) and leaves that obligation to the
    /// producer.
    pub average_bandwidth: Option<u32>,
    /// `FRAME-RATE` as an exact millihertz value (Apple HLS authoring
    /// specification item 9.15 — MUST for every variant that includes
    /// video), or `None` when the `#EXT-X-STREAM-INF` carried no
    /// `FRAME-RATE` attribute. This crate models the attribute (parse and
    /// render) and leaves the obligation to the producer; it is emitted
    /// only when the stream's H.264 SPS carries VUI `timing_info`
    /// (HEVC and codecs without VUI timing omit it, never inventing a
    /// value).
    pub frame_rate: Option<FrameRate>,
    /// `CODECS` — the quoted-string value of the `CODECS` attribute (e.g.
    /// `"avc1.64001e,mp4a.40.2"`), or `None` when the `#EXT-X-STREAM-INF`
    /// carried no `CODECS` attribute at all (audit BH-W6, issue #1111: it
    /// used to default to `""`, so the renderer emitted the invalid
    /// `CODECS=""` — a malformed codec list a strict client rejects).
    pub codecs: Option<String>,
    /// `RESOLUTION` as `(width, height)`, if present.
    pub resolution: Option<(u32, u32)>,
    /// URI of the media playlist for this variant.
    pub uri: String,
    /// `AUDIO` attribute: GROUP-ID of the audio rendition group, if any.
    pub audio: Option<String>,
    /// `VIDEO` attribute: GROUP-ID of the video rendition group, if any.
    pub video: Option<String>,
    /// `SUBTITLES` attribute: GROUP-ID of the subtitle rendition group, if any.
    pub subtitles: Option<String>,
    /// `CLOSED-CAPTIONS` attribute: a group reference or `NONE`.
    pub closed_captions: Option<ClosedCaptionsRef>,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// An I-frame-only rendition entry for a master playlist — RFC 8216 §4.3.4.2
/// (`#EXT-X-I-FRAME-STREAM-INF`).
///
/// Unlike [`Variant`] / `#EXT-X-STREAM-INF`, the URI is an *attribute* on the
/// tag line itself (not on a following line).  Rendered as:
/// ```text
/// #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=<n>[,CODECS="<c>"][,RESOLUTION=<w>x<h>],URI="<uri>"
/// ```
#[derive(Debug, Clone, PartialEq, Default)]
pub struct IFrameVariant {
    /// `BANDWIDTH` in bits per second (required).
    pub bandwidth: u32,
    /// `AVERAGE-BANDWIDTH` in bits per second (RFC 8216bis §4.4.6.2), or
    /// `None` when the `#EXT-X-I-FRAME-STREAM-INF` carried no
    /// `AVERAGE-BANDWIDTH` attribute.
    pub average_bandwidth: Option<u32>,
    /// `CODECS` RFC 6381 string (e.g. `"hvc1.1.6.L93.B0"`).  `None` to omit.
    pub codecs: Option<String>,
    /// `RESOLUTION` as `(width, height)`.  `None` to omit.
    pub resolution: Option<(u32, u32)>,
    /// URI of the I-frame-only media playlist.
    pub uri: String,
    /// Unmodeled attributes, retained so `REQ-` prefixed names can fire
    /// RFC 8216bis §8 row 12. Sorted by name on parse (deterministic).
    pub extra_attrs: Vec<(String, AttrValue)>,
}

/// A master playlist (`#EXTM3U` / `#EXT-X-STREAM-INF` / ...).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct MasterPlaylist {
    /// `#EXT-X-VERSION` — an explicit *floor*, not the rendered value. `0`
    /// means "no explicit floor": [`Self::to_m3u8`] renders exactly
    /// [`Self::computed_version`], or no tag at all when nothing triggers
    /// one. A nonzero value is raised — never lowered — to the computed
    /// minimum. See the module's "Protocol version derivation" docs
    /// (issue #871).
    pub version: u8,
    /// Ordered list of `#EXT-X-MEDIA` renditions (RFC 8216bis §4.4.6.1),
    /// rendered before the variant streams.
    pub media: Vec<MediaRendition>,
    /// Ordered list of variant streams.
    pub variants: Vec<Variant>,
    /// Ordered list of I-frame-only renditions (RFC 8216 §4.3.4.2).
    ///
    /// Each entry is rendered as an `#EXT-X-I-FRAME-STREAM-INF` line with the
    /// URI as an attribute (not a following line).  An empty `Vec` (the
    /// default) produces no such lines.
    pub iframe_variants: Vec<IFrameVariant>,
    /// Extra tag lines emitted **verbatim, first** — immediately after
    /// `#EXT-X-VERSION` and before `#EXT-X-INDEPENDENT-SEGMENTS`/`DEFINE`/
    /// `START`, the `SESSION-*`/`CONTENT-STEERING` tags, and the
    /// variant/I-frame-variant entries (audit BH-W10, issue #1111: this doc
    /// previously claimed they were emitted *after* the entries, the inverse
    /// of what [`Self::to_m3u8`] does).
    ///
    /// The Multivariant-Playlist counterpart of
    /// [`MediaPlaylist::extra_tags`]. [`Self::parse`] preserves any
    /// unrecognized `#EXT-...` tag here (forward-compat) instead of dropping
    /// it; [`Self::computed_version`] scans these lines for the §8 rows this
    /// crate does not model as typed struct fields (rows 7/12/13 —
    /// `docs/version-compatibility.md`). Rows 8 and 11 were also scanned
    /// here until issue #872 gave `EXT-X-DEFINE` a typed representation; they
    /// now read [`Self::defines`] instead.
    pub extra_tags: Vec<String>,
    /// `#EXT-X-INDEPENDENT-SEGMENTS` (RFC 8216bis §4.4.2.1, issue #872).
    pub independent_segments: bool,
    /// `#EXT-X-START` (RFC 8216bis §4.4.2.2, issue #872).
    pub start: Option<StartPoint>,
    /// `#EXT-X-DEFINE` entries (RFC 8216bis §4.4.2.3, issue #872), in wire
    /// order. Feeds §8 row 11 via [`Self::computed_version`].
    pub defines: Vec<Define>,
    /// `#EXT-X-SESSION-DATA` entries (RFC 8216bis §4.4.6.4, issue #872), in
    /// wire order.
    pub session_data: Vec<SessionData>,
    /// `#EXT-X-SESSION-KEY` entries (RFC 8216bis §4.4.6.5, issue #872), in
    /// wire order.
    pub session_keys: Vec<SessionKey>,
    /// `#EXT-X-CONTENT-STEERING` (RFC 8216bis §4.4.6.6, issue #872) — at most
    /// one per Playlist.
    pub content_steering: Option<ContentSteering>,
}

/// A parsed but not-yet-closed `#EXT-X-STREAM-INF` — `(bandwidth,
/// average_bandwidth, frame_rate, codecs, resolution, extra attributes)` —
/// awaiting the URI line that turns it into a [`Variant`]. `codecs` is `None`
/// when the tag carried no `CODECS` attribute (audit BH-W6, issue #1111);
/// `average_bandwidth` is `None` when it carried no `AVERAGE-BANDWIDTH`;
/// `frame_rate` is `None` when it carried no `FRAME-RATE`.
type PendingStreamInf = (
    u32,
    Option<u32>,
    Option<FrameRate>,
    Option<String>,
    Option<(u32, u32)>,
    Vec<(String, AttrValue)>,
);

impl MasterPlaylist {
    /// Render this master playlist as an RFC 8216 `#EXTM3U` string.
    ///
    /// After the regular `#EXT-X-STREAM-INF` variant lines, emits one
    /// `#EXT-X-I-FRAME-STREAM-INF` line per entry in
    /// [`Self::iframe_variants`] (RFC 8216 §4.3.4.2).  The URI is rendered
    /// as an attribute on the tag line itself — *not* on a following line.
    /// # Errors
    ///
    /// A field this crate renders inside an RFC 8216 §4.2 quoted-string
    /// or as a URI — a variant/I-frame-variant URI, a `CODECS`, a
    /// `#EXT-X-CONTENT-STEERING` `SERVER-URI`/`PATHWAY-ID`, a
    /// `#EXT-X-SESSION-DATA` `DATA-ID`/`VALUE`/`URI`/`LANGUAGE`, a
    /// `#EXT-X-SESSION-KEY` `URI`/`KEYFORMAT`/`KEYFORMATVERSIONS`, a
    /// `#EXT-X-DEFINE` `NAME`/`VALUE` — that contains `"`, CR or LF is
    /// rejected before any of it reaches the output (audit BH-W7, issue
    /// #1111): those three are forbidden in a quoted-string, and a
    /// newline would let a value inject a tag line into the playlist.
    pub fn to_m3u8(&self) -> Result<String> {
        self.validate_for_render()?;
        let mut s = String::new();
        s.push_str("#EXTM3U\n");
        if let Some(version) = self.effective_version() {
            s.push_str(&format!("#EXT-X-VERSION:{version}\n"));
        }

        for tag in &self.extra_tags {
            s.push_str(tag);
            s.push('\n');
        }

        // #EXT-X-MEDIA renditions (RFC 8216bis §4.4.6.1), before variants.
        for m in &self.media {
            s.push_str("#EXT-X-MEDIA:TYPE=");
            s.push_str(m.media_type.name());
            if let Some(uri) = &m.uri {
                validate_uri(uri, "EXT-X-MEDIA URI")?;
                s.push_str(&format!(",URI=\"{uri}\""));
            }
            s.push_str(&format!(",GROUP-ID=\"{}\"", m.group_id));
            if let Some(l) = &m.language {
                validate_quoted_string(l, "EXT-X-MEDIA LANGUAGE")?;
                s.push_str(&format!(",LANGUAGE=\"{l}\""));
            }
            if let Some(l) = &m.assoc_language {
                validate_quoted_string(l, "EXT-X-MEDIA ASSOC-LANGUAGE")?;
                s.push_str(&format!(",ASSOC-LANGUAGE=\"{l}\""));
            }
            validate_quoted_string(&m.name, "EXT-X-MEDIA NAME")?;
            s.push_str(&format!(",NAME=\"{}\"", m.name));
            if let Some(sri) = &m.stable_rendition_id {
                validate_quoted_string(sri, "EXT-X-MEDIA STABLE-RENDITION-ID")?;
                s.push_str(&format!(",STABLE-RENDITION-ID=\"{sri}\""));
            }
            s.push_str(&format!(
                ",DEFAULT={}",
                if m.default { "YES" } else { "NO" }
            ));
            if m.autoselect || !m.default {
                s.push_str(&format!(
                    ",AUTOSELECT={}",
                    if m.autoselect { "YES" } else { "NO" }
                ));
            }
            if m.forced {
                s.push_str(",FORCED=YES");
            } else if m.media_type == MediaType::Subtitles {
                // Preserve explicit NO for subtitles to mirror fixtures? Keep NO always for losslessness.
                s.push_str(",FORCED=NO");
            }
            if let Some(ii) = &m.instream_id {
                let v = ii.render();
                validate_quoted_string(&v, "EXT-X-MEDIA INSTREAM-ID")?;
                s.push_str(&format!(",INSTREAM-ID=\"{v}\""));
            }
            if let Some(bd) = m.bit_depth {
                s.push_str(&format!(",BIT-DEPTH={bd}"));
            }
            if let Some(sr) = m.sample_rate {
                s.push_str(&format!(",SAMPLE-RATE={sr}"));
            }
            if !m.characteristics.is_empty() {
                let joined = m.characteristics.join(",");
                validate_quoted_string(&joined, "EXT-X-MEDIA CHARACTERISTICS")?;
                s.push_str(&format!(",CHARACTERISTICS=\"{joined}\""));
            }
            if let Some(ch) = &m.channels {
                validate_quoted_string(ch, "EXT-X-MEDIA CHANNELS")?;
                s.push_str(&format!(",CHANNELS=\"{ch}\""));
            }
            render_attribute_list(&mut s, &m.extra_attrs);
            s.push('\n');
        }

        // §4.4.2 tags (issue #872).
        if self.independent_segments {
            s.push_str("#EXT-X-INDEPENDENT-SEGMENTS\n");
        }
        for def in &self.defines {
            push_define_line(&mut s, def)?;
        }
        if let Some(start) = &self.start {
            push_start_line(&mut s, start);
        }
        // §4.4.6.4/.5/.6 Multivariant Playlist tags (issue #872).
        for sk in &self.session_keys {
            push_session_key_line(&mut s, sk)?;
        }
        for sd in &self.session_data {
            push_session_data_line(&mut s, sd)?;
        }
        if let Some(cs) = &self.content_steering {
            validate_uri(&cs.server_uri, "EXT-X-CONTENT-STEERING SERVER-URI")?;
            s.push_str(&format!(
                "#EXT-X-CONTENT-STEERING:SERVER-URI=\"{}\"",
                cs.server_uri
            ));
            if let Some(pid) = &cs.pathway_id {
                validate_quoted_string(pid, "EXT-X-CONTENT-STEERING PATHWAY-ID")?;
                s.push_str(&format!(",PATHWAY-ID=\"{pid}\""));
            }
            render_attribute_list(&mut s, &cs.extra_attrs);
            s.push('\n');
        }

        for var in &self.variants {
            s.push_str(&format!("#EXT-X-STREAM-INF:BANDWIDTH={}", var.bandwidth));
            // RFC 8216bis §4.4.6.2: AVERAGE-BANDWIDTH renders immediately
            // after BANDWIDTH; an absent value renders nothing.
            if let Some(avg) = var.average_bandwidth {
                s.push_str(&format!(",AVERAGE-BANDWIDTH={avg}"));
            }
            // Audit BH-W6 (issue #1111): CODECS is optional on the tag line,
            // so an absent attribute renders nothing rather than the invalid
            // empty `CODECS=""`.
            if let Some(codecs) = &var.codecs {
                validate_quoted_string(codecs, "EXT-X-STREAM-INF CODECS")?;
                s.push_str(&format!(",CODECS=\"{codecs}\""));
            }
            if let Some((w, h)) = var.resolution {
                s.push_str(&format!(",RESOLUTION={w}x{h}"));
            }
            // Apple HLS authoring specification item 9.15 / RFC 8216bis
            // §4.4.6.2: FRAME-RATE renders after RESOLUTION as an exact
            // 3-decimal millihertz value.
            if let Some(frame_rate) = var.frame_rate {
                s.push_str(&format!(",FRAME-RATE={frame_rate}"));
            }
            if let Some(g) = &var.audio {
                validate_quoted_string(g, "EXT-X-STREAM-INF AUDIO")?;
                s.push_str(&format!(",AUDIO=\"{g}\""));
            }
            if let Some(g) = &var.video {
                validate_quoted_string(g, "EXT-X-STREAM-INF VIDEO")?;
                s.push_str(&format!(",VIDEO=\"{g}\""));
            }
            if let Some(g) = &var.subtitles {
                validate_quoted_string(g, "EXT-X-STREAM-INF SUBTITLES")?;
                s.push_str(&format!(",SUBTITLES=\"{g}\""));
            }
            match &var.closed_captions {
                Some(ClosedCaptionsRef::Group(g)) => {
                    validate_quoted_string(g, "EXT-X-STREAM-INF CLOSED-CAPTIONS")?;
                    s.push_str(&format!(",CLOSED-CAPTIONS=\"{g}\""));
                }
                Some(ClosedCaptionsRef::None) => {
                    s.push_str(",CLOSED-CAPTIONS=NONE");
                }
                None => {}
            }
            render_attribute_list(&mut s, &var.extra_attrs);
            s.push('\n');
            validate_uri(&var.uri, "variant URI")?;
            s.push_str(&var.uri);
            s.push('\n');
        }

        // I-frame-only renditions — RFC 8216 §4.3.4.2.
        // URI is an attribute on the tag line, not a following URI line.
        for iv in &self.iframe_variants {
            s.push_str(&format!(
                "#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH={}",
                iv.bandwidth
            ));
            // RFC 8216bis §4.4.6.2: AVERAGE-BANDWIDTH renders immediately
            // after BANDWIDTH; an absent value renders nothing.
            if let Some(avg) = iv.average_bandwidth {
                s.push_str(&format!(",AVERAGE-BANDWIDTH={avg}"));
            }
            if let Some(c) = &iv.codecs {
                s.push_str(&format!(",CODECS=\"{c}\""));
            }
            if let Some((w, h)) = iv.resolution {
                s.push_str(&format!(",RESOLUTION={w}x{h}"));
            }
            validate_uri(&iv.uri, "I-frame-variant URI")?;
            if let Some(codecs) = &iv.codecs {
                validate_quoted_string(codecs, "EXT-X-I-FRAME-STREAM-INF CODECS")?;
            }
            render_attribute_list(&mut s, &iv.extra_attrs);
            s.push_str(&format!(",URI=\"{}\"\n", iv.uri));
        }

        Ok(s)
    }

    /// Reject any field that would be rendered inside an RFC 8216 §4.2
    /// quoted-string or as a URI but contains `"`, CR or LF (audit BH-W7,
    /// issue #1111) — a tag/attribute-list injection vector for a playlist
    /// assembled from external data. Covers every field [`Self::to_m3u8`]
    /// emits; the per-tag renderers re-check the same values, so a caller
    /// that bypasses this method still cannot emit a malformed line.
    fn validate_for_render(&self) -> Result<()> {
        validate_tag_body("playlist-level extra tag", &self.extra_tags)?;
        for def in &self.defines {
            push_define_line(&mut String::new(), def)?;
        }
        if let Some(cs) = &self.content_steering {
            validate_uri(&cs.server_uri, "EXT-X-CONTENT-STEERING SERVER-URI")?;
            if let Some(pid) = &cs.pathway_id {
                validate_quoted_string(pid, "EXT-X-CONTENT-STEERING PATHWAY-ID")?;
            }
        }
        for var in &self.variants {
            validate_uri(&var.uri, "variant URI")?;
            if let Some(codecs) = &var.codecs {
                validate_quoted_string(codecs, "EXT-X-STREAM-INF CODECS")?;
            }
        }
        for iv in &self.iframe_variants {
            validate_uri(&iv.uri, "I-frame-variant URI")?;
            if let Some(codecs) = &iv.codecs {
                validate_quoted_string(codecs, "EXT-X-I-FRAME-STREAM-INF CODECS")?;
            }
        }
        check_rendition_groups(&self.media)?;
        // EXT-X-MEDIA rendition validation (RFC 8216bis §4.4.6.1).
        for m in &self.media {
            if m.group_id.is_empty() {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: "EXT-X-MEDIA GROUP-ID must be non-empty".to_string(),
                });
            }
            validate_quoted_string(&m.group_id, "EXT-X-MEDIA GROUP-ID")?;
            if m.name.is_empty() {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: "EXT-X-MEDIA NAME must be non-empty".to_string(),
                });
            }
            validate_quoted_string(&m.name, "EXT-X-MEDIA NAME")?;
            if m.media_type == MediaType::ClosedCaptions {
                if m.uri.is_some() {
                    return Err(Error::HlsParse {
                        line_no: 0,
                        line: String::new(),
                        reason: "EXT-X-MEDIA URI MUST NOT be present when TYPE is CLOSED-CAPTIONS"
                            .to_string(),
                    });
                }
                if m.instream_id.is_none() {
                    return Err(Error::HlsParse {
                        line_no: 0,
                        line: String::new(),
                        reason: "EXT-X-MEDIA INSTREAM-ID REQUIRED when TYPE is CLOSED-CAPTIONS"
                            .to_string(),
                    });
                }
            } else {
                // URI allowed; instream_id optional
            }
            if m.forced && m.media_type != MediaType::Subtitles {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: "EXT-X-MEDIA FORCED MUST NOT be present unless TYPE is SUBTITLES"
                        .to_string(),
                });
            }
            if m.bit_depth.is_some() && m.media_type != MediaType::Audio {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: "EXT-X-MEDIA BIT-DEPTH MUST NOT be present unless TYPE is AUDIO"
                        .to_string(),
                });
            }
            if m.sample_rate.is_some() && m.media_type != MediaType::Audio {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: "EXT-X-MEDIA SAMPLE-RATE MUST NOT be present unless TYPE is AUDIO"
                        .to_string(),
                });
            }
            if m.channels.is_some() && m.media_type != MediaType::Audio {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: "EXT-X-MEDIA CHANNELS MUST NOT be present unless TYPE is AUDIO"
                        .to_string(),
                });
            }
            if let Some(uri) = &m.uri {
                validate_uri(uri, "EXT-X-MEDIA URI")?;
            }
            if let Some(sri) = &m.stable_rendition_id {
                validate_quoted_string(sri, "EXT-X-MEDIA STABLE-RENDITION-ID")?;
            }
            if let Some(ii) = &m.instream_id {
                let v = ii.render();
                validate_quoted_string(&v, "EXT-X-MEDIA INSTREAM-ID")?;
                let closed_captions = m.media_type == MediaType::ClosedCaptions;
                let cc_form = !matches!(ii, InstreamId::Other(_));
                if closed_captions != cc_form {
                    return Err(Error::InstreamIdTypeMismatch {
                        media_type: m.media_type,
                        value: v,
                    });
                }
                if closed_captions {
                    InstreamId::parse_closed_captions(&v)?;
                }
            }
            if let Some(ch) = &m.channels {
                validate_quoted_string(ch, "EXT-X-MEDIA CHANNELS")?;
            }
        }
        // Group cross-check + NONE consistency.
        let none_used = self
            .variants
            .iter()
            .any(|v| matches!(v.closed_captions, Some(ClosedCaptionsRef::None)));
        if none_used {
            for v in &self.variants {
                if !matches!(v.closed_captions, Some(ClosedCaptionsRef::None)) {
                    return Err(Error::HlsParse {
                        line_no: 0,
                        line: String::new(),
                        reason:
                            "EXT-X-STREAM-INF CLOSED-CAPTIONS=NONE must be used on all variants"
                                .to_string(),
                    });
                }
            }
        }
        let group_exists = |gid: &str, mt: MediaType| -> bool {
            self.media
                .iter()
                .any(|m| m.group_id == gid && m.media_type == mt)
        };
        for v in &self.variants {
            if let Some(g) = &v.audio
                && !group_exists(g, MediaType::Audio)
            {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: format!("EXT-X-STREAM-INF AUDIO group {g:?} not found"),
                });
            }
            if let Some(g) = &v.video
                && !group_exists(g, MediaType::Video)
            {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: format!("EXT-X-STREAM-INF VIDEO group {g:?} not found"),
                });
            }
            if let Some(g) = &v.subtitles
                && !group_exists(g, MediaType::Subtitles)
            {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: format!("EXT-X-STREAM-INF SUBTITLES group {g:?} not found"),
                });
            }
            if let Some(ClosedCaptionsRef::Group(g)) = &v.closed_captions
                && !group_exists(g, MediaType::ClosedCaptions)
            {
                return Err(Error::HlsParse {
                    line_no: 0,
                    line: String::new(),
                    reason: format!("EXT-X-STREAM-INF CLOSED-CAPTIONS group {g:?} not found"),
                });
            }
        }
        for sk in &self.session_keys {
            push_session_key_line(&mut String::new(), sk)?;
        }
        for sd in &self.session_data {
            push_session_data_line(&mut String::new(), sd)?;
        }
        Ok(())
    }

    /// Parse an RFC 8216 `#EXTM3U` Multivariant (Master) Playlist — the
    /// symmetric inverse of [`Self::to_m3u8`].
    ///
    /// Recognizes `#EXT-X-VERSION`, `#EXT-X-STREAM-INF` + its following URI
    /// line, and `#EXT-X-I-FRAME-STREAM-INF`. `#EXT-X-MEDIA` (alternate
    /// audio/subtitle renditions), `#EXT-X-DEFINE`, and any other
    /// unrecognized `#EXT-...` tag are not modeled with typed fields, but
    /// are preserved verbatim into [`Self::extra_tags`] (forward-compat),
    /// mirroring [`MediaPlaylist::parse`]. A malformed
    /// `#EXT-X-STREAM-INF`/`#EXT-X-I-FRAME-STREAM-INF` (missing required
    /// attribute, unparsable value) or a variant URI with no preceding
    /// `#EXT-X-STREAM-INF` returns [`crate::Error::HlsParse`].
    pub fn parse(input: &str) -> Result<Self> {
        // `0` (not `1`): see the identical comment in `MediaPlaylist::parse`.
        let mut version: u8 = 0;
        let mut variants: Vec<Variant> = Vec::new();
        let mut iframe_variants: Vec<IFrameVariant> = Vec::new();
        let mut media: Vec<MediaRendition> = Vec::new();
        let mut extra_tags: Vec<String> = Vec::new();
        let mut saw_extm3u = false;
        let mut pending_stream_inf: Option<PendingStreamInf> = None;
        // §4.4.2/§4.4.6.4/.5/.6 accumulators (issue #872).
        let mut independent_segments = false;
        let mut start: Option<StartPoint> = None;
        let mut defines: Vec<Define> = Vec::new();
        let mut session_data: Vec<SessionData> = Vec::new();
        let mut session_keys: Vec<SessionKey> = Vec::new();
        let mut content_steering: Option<ContentSteering> = None;

        for (idx, raw_line) in input.lines().enumerate() {
            let line_no = idx + 1;
            let mut line = raw_line.trim_end_matches('\r');
            if line_no == 1 {
                line = line.strip_prefix('\u{feff}').unwrap_or(line);
            }
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            if line == "#EXTM3U" {
                saw_extm3u = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-VERSION:") {
                version = parse_decimal_int(rest, line_no, line, "EXT-X-VERSION")?;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-STREAM-INF:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                let bandwidth_str =
                    require_attr(&attrs, "BANDWIDTH", line_no, line, "EXT-X-STREAM-INF")?;
                let bandwidth = parse_decimal_int(&bandwidth_str, line_no, line, "BANDWIDTH")?;
                // RFC 8216bis §4.4.6.2: AVERAGE-BANDWIDTH is a
                // decimal-integer, optional on parse (Apple item 9.14 asks
                // the producer to emit it).
                let average_bandwidth = match attrs.get("AVERAGE-BANDWIDTH") {
                    Some(v) => Some(parse_decimal_int(v, line_no, line, "AVERAGE-BANDWIDTH")?),
                    None => None,
                };
                // RFC 8216bis §4.4.6.2: FRAME-RATE is a decimal-floating-point
                // value, rounded to millihertz (3 decimals) on parse.
                let frame_rate = match attrs.get("FRAME-RATE") {
                    Some(v) => Some(parse_frame_rate(v, line_no, line)?),
                    None => None,
                };
                // Audit BH-W6 (issue #1111): `CODECS` is optional on the tag
                // line, so an absent attribute stays `None` (rendering
                // nothing) instead of becoming an empty, invalid `CODECS=""`.
                let codecs = attrs.get("CODECS").cloned();
                let resolution = match attrs.get("RESOLUTION") {
                    Some(v) => Some(parse_resolution(v, line_no, line)?),
                    None => None,
                };
                let extra_attrs = filter_extra_attrs(
                    &attrs,
                    &[
                        "BANDWIDTH",
                        "AVERAGE-BANDWIDTH",
                        "CODECS",
                        "RESOLUTION",
                        "FRAME-RATE",
                    ],
                    &quoted,
                )?;
                // Audit BH-W9 (issue #1111): `#EXT-X-STREAM-INF` MUST be
                // followed by the URI line of the Variant it describes
                // (RFC 8216bis §4.4.6.2). A second STREAM-INF before that
                // line means the first Variant's URI is missing — the
                // playlist is malformed, and silently overwriting *loses*
                // a variant (which no downstream validator can recover,
                // since the information is gone by the time it sees the
                // parsed struct).
                if pending_stream_inf.is_some() {
                    return Err(Error::HlsParse {
                        line_no,
                        line: line.to_string(),
                        reason: "second #EXT-X-STREAM-INF before the first Variant's URI \
                                 line (RFC 8216bis §4.4.6.2)"
                            .to_string(),
                    });
                }
                pending_stream_inf = Some((
                    bandwidth,
                    average_bandwidth,
                    frame_rate,
                    codecs,
                    resolution,
                    extra_attrs,
                ));
            } else if let Some(rest) = line.strip_prefix("#EXT-X-I-FRAME-STREAM-INF:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                let bandwidth_str = require_attr(
                    &attrs,
                    "BANDWIDTH",
                    line_no,
                    line,
                    "EXT-X-I-FRAME-STREAM-INF",
                )?;
                let bandwidth = parse_decimal_int(&bandwidth_str, line_no, line, "BANDWIDTH")?;
                let average_bandwidth = match attrs.get("AVERAGE-BANDWIDTH") {
                    Some(v) => Some(parse_decimal_int(v, line_no, line, "AVERAGE-BANDWIDTH")?),
                    None => None,
                };
                let codecs = attrs.get("CODECS").cloned();
                let resolution = match attrs.get("RESOLUTION") {
                    Some(v) => Some(parse_resolution(v, line_no, line)?),
                    None => None,
                };
                let uri = require_attr(&attrs, "URI", line_no, line, "EXT-X-I-FRAME-STREAM-INF")?;
                let extra_attrs = filter_extra_attrs(
                    &attrs,
                    &[
                        "BANDWIDTH",
                        "AVERAGE-BANDWIDTH",
                        "CODECS",
                        "RESOLUTION",
                        "URI",
                    ],
                    &quoted,
                )?;
                iframe_variants.push(IFrameVariant {
                    bandwidth,
                    average_bandwidth,
                    codecs,
                    resolution,
                    uri,
                    extra_attrs,
                });
            } else if line == "#EXT-X-INDEPENDENT-SEGMENTS" {
                independent_segments = true;
            } else if let Some(rest) = line.strip_prefix("#EXT-X-START:") {
                start = Some(parse_start(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-DEFINE:") {
                defines.push(parse_define(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-SESSION-DATA:") {
                session_data.push(parse_session_data(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-SESSION-KEY:") {
                session_keys.push(parse_session_key(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT-X-CONTENT-STEERING:") {
                let (attrs, quoted) = parse_attribute_list_strict(rest)?;
                let server_uri = require_attr(
                    &attrs,
                    "SERVER-URI",
                    line_no,
                    line,
                    "EXT-X-CONTENT-STEERING",
                )?;
                let pathway_id = attrs.get("PATHWAY-ID").cloned();
                let extra_attrs =
                    filter_extra_attrs(&attrs, &["SERVER-URI", "PATHWAY-ID"], &quoted)?;
                content_steering = Some(ContentSteering {
                    server_uri,
                    pathway_id,
                    extra_attrs,
                });
            } else if let Some(rest) = line.strip_prefix("#EXT-X-MEDIA:") {
                media.push(parse_media_rendition(rest, line_no, line)?);
            } else if let Some(rest) = line.strip_prefix("#EXT") {
                let _ = rest;
                // A well-formed but still-unmodeled tag (e.g. #EXT-X-MEDIA):
                // preserve verbatim (forward-compat, and the substrate
                // `computed_version` scans for §8 rows 7/12/13), mirroring
                // `MediaPlaylist::parse`. NOTE: this arm must stay LAST of
                // the `#EXT` arms — every typed arm above is a more specific
                // prefix and would otherwise be shadowed by it.
                extra_tags.push(line.to_string());
            } else if line.starts_with('#') {
                // RFC 8216 §4.1: a non-"#EXT" '#' line is a comment — ignore.
            } else {
                let (bandwidth, average_bandwidth, frame_rate, codecs, resolution, extra_attrs) =
                    pending_stream_inf.take().ok_or_else(|| Error::HlsParse {
                        line_no,
                        line: line.to_string(),
                        reason: "variant URI with no preceding #EXT-X-STREAM-INF".to_string(),
                    })?;
                // Pull the typed rendition-group references out of the
                // unmodeled attribute bag (issue #1428).
                let mut audio = None;
                let mut video = None;
                let mut subtitles = None;
                let mut closed_captions = None;
                let mut extra_attrs_filtered = Vec::new();
                for (k, v) in extra_attrs {
                    match k.as_str() {
                        "AUDIO" => audio = Some(v.as_str().to_string()),
                        "VIDEO" => video = Some(v.as_str().to_string()),
                        "SUBTITLES" => subtitles = Some(v.as_str().to_string()),
                        "CLOSED-CAPTIONS" => {
                            if v.as_str() == "NONE" {
                                closed_captions = Some(ClosedCaptionsRef::None);
                            } else {
                                closed_captions =
                                    Some(ClosedCaptionsRef::Group(v.as_str().to_string()));
                            }
                        }
                        _ => extra_attrs_filtered.push((k, v)),
                    }
                }
                variants.push(Variant {
                    bandwidth,
                    average_bandwidth,
                    frame_rate,
                    codecs,
                    resolution,
                    uri: line.to_string(),
                    audio,
                    video,
                    subtitles,
                    closed_captions,
                    extra_attrs: extra_attrs_filtered,
                });
            }
        }

        if !saw_extm3u {
            return Err(Error::HlsParse {
                line_no: 1,
                line: String::new(),
                reason: "missing #EXTM3U header".to_string(),
            });
        }
        // Audit BH-W9 (issue #1111): a trailing `#EXT-X-STREAM-INF` with no
        // URI line is a truncated playlist, not a variant silently dropped.
        if pending_stream_inf.is_some() {
            return Err(Error::HlsParse {
                line_no: 0,
                line: String::new(),
                reason: "#EXT-X-STREAM-INF with no following Variant URI line (RFC 8216bis \
                         §4.4.6.2)"
                    .to_string(),
            });
        }

        check_rendition_groups(&media)?;

        Ok(MasterPlaylist {
            version,
            media,
            variants,
            iframe_variants,
            extra_tags,
            independent_segments,
            start,
            defines,
            session_data,
            session_keys,
            content_steering,
        })
    }

    /// Compute the minimum `#EXT-X-VERSION` this Multivariant Playlist's
    /// actual content requires, per RFC 8216bis §8
    /// (`docs/version-compatibility.md`). `None` means fully compatible
    /// with version 1 (no tag required). See
    /// [`MediaPlaylist::computed_version`] for the Media-Playlist-only rows
    /// (2–6, 9–10) that do not apply to a Multivariant Playlist.
    pub fn computed_version(&self) -> Option<u8> {
        // Rows 7/13 (SERVICE INSTREAM-ID, non-CC INSTREAM-ID) — all
        // attributes of `EXT-X-MEDIA` or of tags this crate still does not
        // model, so `extra_tags` remains the substrate. Row 12 on *unmodeled*
        // tags is handled here; row 12 on modeled tags is checked below.
        let mut v = scan_tag_lines_for_version(&self.extra_tags);

        // Typed EXT-X-MEDIA renditions (issue #1428): drive the same §8
        // version floor the verbatim scanner did when these lines sat in
        // `extra_tags`.
        for m in &self.media {
            if let Some(InstreamId::Service(_)) = m.instream_id {
                bump_version(&mut v, VERSION_MEDIA_SERVICE_INSTREAM_ID);
            }
            if m.instream_id.is_some() && m.media_type != MediaType::ClosedCaptions {
                bump_version(&mut v, VERSION_MEDIA_INSTREAM_ID_NON_CC);
            }
        }

        // Row 11: EXT-X-DEFINE with a QUERYPARAM attribute — typed since
        // issue #872 (see `MediaPlaylist::computed_version` for why the
        // string scan can no longer see this tag).
        if self
            .defines
            .iter()
            .any(|d| matches!(d, Define::QueryParam { .. }))
        {
            bump_version(&mut v, VERSION_DEFINE_QUERYPARAM);
        }

        // Row 8: variable substitution across every string this playlist
        // carries — opaque tag lines, variant/I-frame-variant URIs, and the
        // typed #872 fields (EXT-X-DEFINE values, EXT-X-SESSION-DATA
        // VALUE/URI, EXT-X-SESSION-KEY URI, EXT-X-CONTENT-STEERING URIs).
        if self
            .extra_tags
            .iter()
            .any(|t| contains_variable_substitution(t))
            || self.media.iter().any(|m| {
                m.uri
                    .as_ref()
                    .is_some_and(|u| contains_variable_substitution(u))
                    || contains_variable_substitution(&m.group_id)
                    || contains_variable_substitution(&m.name)
                    || m.language
                        .as_ref()
                        .is_some_and(|x| contains_variable_substitution(x))
                    || m.assoc_language
                        .as_ref()
                        .is_some_and(|x| contains_variable_substitution(x))
                    || m.stable_rendition_id
                        .as_ref()
                        .is_some_and(|x| contains_variable_substitution(x))
                    || m.channels
                        .as_ref()
                        .is_some_and(|x| contains_variable_substitution(x))
                    || m.characteristics
                        .iter()
                        .any(|x| contains_variable_substitution(x))
            })
            || self
                .variants
                .iter()
                .any(|var| contains_variable_substitution(&var.uri))
            || self
                .iframe_variants
                .iter()
                .any(|iv| contains_variable_substitution(&iv.uri))
            || self.master_playlist_typed_strings_use_substitution()
        {
            bump_version(&mut v, VERSION_VARIABLE_SUBSTITUTION);
        }

        // Row 12: REQ- attribute on any typed struct — modeled tags that
        // carry extra_attrs fields since issue #884.
        if any_typed_req_attr(
            self.start.as_ref(),
            &self.defines,
            &self.session_data,
            &self.session_keys,
            self.content_steering.as_ref(),
            &self.media,
            &self.variants,
            &self.iframe_variants,
        ) {
            bump_version(&mut v, VERSION_REQ_ATTRIBUTE);
        }

        v
    }

    /// Row 8 helper — the Multivariant-Playlist counterpart of
    /// [`MediaPlaylist::media_playlist_typed_strings_use_substitution`],
    /// covering the string-bearing tags issue #872 gave typed
    /// representations (before which they sat in `extra_tags` and were
    /// covered by the opaque scan).
    fn master_playlist_typed_strings_use_substitution(&self) -> bool {
        let define_values = self.defines.iter().filter_map(|d| match d {
            Define::Name { value, .. } => Some(value),
            _ => None,
        });
        let session_data_strings = self.session_data.iter().map(|sd| match &sd.content {
            SessionDataContent::Value(v) => v,
            SessionDataContent::Uri { uri, .. } => uri,
        });
        let session_key_uris = self.session_keys.iter().filter_map(|k| k.uri.as_ref());
        let steering_uris = self.content_steering.iter().map(|cs| &cs.server_uri);

        define_values
            .chain(session_data_strings)
            .chain(session_key_uris)
            .chain(steering_uris)
            .any(|s| contains_variable_substitution(s))
    }

    /// The `#EXT-X-VERSION` value actually rendered by [`Self::to_m3u8`] —
    /// see [`MediaPlaylist::effective_version`] for the shared rule.
    fn effective_version(&self) -> Option<u8> {
        effective_version(self.version, self.computed_version())
    }
}

/// Parse a `FRAME-RATE=<decimal-floating-point>` attribute value into an exact
/// millihertz [`FrameRate`], rounding half-up to three decimal places without
/// any floating-point arithmetic; any number of fraction digits is accepted
/// (RFC 8216bis §4.2 `decimal-floating-point` has no digit limit).
fn parse_frame_rate(v: &str, line_no: usize, line: &str) -> Result<FrameRate> {
    let t = v.trim();
    if !is_valid_decimal_token(t, false) {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: format!("FRAME-RATE value {v:?} is not a valid decimal number"),
        });
    }
    let (int_part, frac_part) = match t.split_once('.') {
        Some((i, f)) => (i, Some(f)),
        None => (t, None),
    };
    let out_of_range = || Error::HlsParse {
        line_no,
        line: line.to_string(),
        reason: format!("FRAME-RATE value {v:?} is out of range"),
    };
    let int_value: u32 = int_part.parse().map_err(|_| out_of_range())?;
    let mut digits = frac_part.unwrap_or("").bytes().map(|b| u32::from(b - b'0'));
    let mut next = || digits.next().unwrap_or(0);
    let milli = next() * 100 + next() * 10 + next();
    let round_up = u32::from(next() >= 5);
    let total = int_value
        .checked_mul(1000)
        .and_then(|i| i.checked_add(milli + round_up))
        .ok_or_else(out_of_range)?;
    Ok(FrameRate::from_millihertz(total))
}

/// Parse a `RESOLUTION=<w>x<h>` attribute value.
fn parse_resolution(v: &str, line_no: usize, line: &str) -> Result<(u32, u32)> {
    let mut split = v.splitn(2, 'x');
    let w = split.next().unwrap_or("");
    let h = split.next().ok_or_else(|| Error::HlsParse {
        line_no,
        line: line.to_string(),
        reason: format!("RESOLUTION value {v:?} is not of the form <width>x<height>"),
    })?;
    let width = parse_decimal_int(w, line_no, line, "RESOLUTION width")?;
    let height = parse_decimal_int(h, line_no, line, "RESOLUTION height")?;
    Ok((width, height))
}

fn parse_yes_no(attrs: &BTreeMap<String, String>, attribute: &'static str) -> Result<Option<bool>> {
    match attrs.get(attribute).map(String::as_str) {
        None => Ok(None),
        Some("YES") => Ok(Some(true)),
        Some("NO") => Ok(Some(false)),
        Some(other) => Err(Error::InvalidYesNo {
            attribute,
            value: other.to_string(),
        }),
    }
}

fn check_rendition_groups(media: &[MediaRendition]) -> Result<()> {
    let mut seen: BTreeSet<(&str, &str, &str)> = BTreeSet::new();
    let mut defaults: BTreeSet<(&str, &str)> = BTreeSet::new();
    for m in media {
        let group = (m.media_type.name(), m.group_id.as_str());
        if !seen.insert((m.media_type.name(), m.group_id.as_str(), m.name.as_str())) {
            return Err(Error::DuplicateNameInGroup {
                media_type: m.media_type,
                group_id: m.group_id.clone(),
                name: m.name.clone(),
            });
        }
        if m.default && !defaults.insert(group) {
            return Err(Error::DuplicateDefaultInGroup {
                media_type: m.media_type,
                group_id: m.group_id.clone(),
            });
        }
    }
    Ok(())
}

fn parse_media_rendition(rest: &str, line_no: usize, line: &str) -> Result<MediaRendition> {
    let (attrs, quoted) = parse_attribute_list_strict(rest)?;

    // TYPE (REQUIRED)
    let type_str = require_attr(&attrs, "TYPE", line_no, line, "EXT-X-MEDIA")?;
    let media_type = match type_str.as_str() {
        "AUDIO" => MediaType::Audio,
        "VIDEO" => MediaType::Video,
        "SUBTITLES" => MediaType::Subtitles,
        "CLOSED-CAPTIONS" => MediaType::ClosedCaptions,
        _ => {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: format!("EXT-X-MEDIA invalid TYPE {type_str:?}"),
            });
        }
    };

    let group_id = require_attr(&attrs, "GROUP-ID", line_no, line, "EXT-X-MEDIA")?;
    if group_id.is_empty() {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-MEDIA GROUP-ID must be non-empty".to_string(),
        });
    }
    validate_quoted_string(&group_id, "EXT-X-MEDIA GROUP-ID")?;

    let name = require_attr(&attrs, "NAME", line_no, line, "EXT-X-MEDIA")?;
    if name.is_empty() {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-MEDIA NAME must be non-empty".to_string(),
        });
    }
    validate_quoted_string(&name, "EXT-X-MEDIA NAME")?;

    // URI
    let uri = attrs.get("URI").cloned();
    if media_type == MediaType::ClosedCaptions && uri.is_some() {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-MEDIA URI MUST NOT be present when TYPE is CLOSED-CAPTIONS".to_string(),
        });
    }
    if let Some(u) = &uri {
        validate_uri(u, "EXT-X-MEDIA URI")?;
    }

    let language = attrs.get("LANGUAGE").cloned();
    let assoc_language = attrs.get("ASSOC-LANGUAGE").cloned();
    if let Some(l) = &language {
        validate_quoted_string(l, "EXT-X-MEDIA LANGUAGE")?;
    }
    if let Some(l) = &assoc_language {
        validate_quoted_string(l, "EXT-X-MEDIA ASSOC-LANGUAGE")?;
    }

    let stable_rendition_id = attrs.get("STABLE-RENDITION-ID").cloned();
    if let Some(s) = &stable_rendition_id {
        validate_quoted_string(s, "EXT-X-MEDIA STABLE-RENDITION-ID")?;
    }

    // DEFAULT / AUTOSELECT
    let default = parse_yes_no(&attrs, "DEFAULT")?.unwrap_or(false);
    let autoselect_attr = parse_yes_no(&attrs, "AUTOSELECT")?;
    let autoselect = autoselect_attr.unwrap_or(false);
    if default && autoselect_attr == Some(false) {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-MEDIA AUTOSELECT MUST be YES when DEFAULT is YES".to_string(),
        });
    }

    // FORCED
    let forced = parse_yes_no(&attrs, "FORCED")?.unwrap_or(false);
    if forced && media_type != MediaType::Subtitles {
        // FORCED MUST NOT be present unless TYPE is SUBTITLES; treat YES as violation
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-MEDIA FORCED MUST NOT be present unless TYPE is SUBTITLES".to_string(),
        });
    }
    // Also reject FORCED present for non-subtitles even if NO? Spec: MUST NOT be present.
    if attrs.contains_key("FORCED") && media_type != MediaType::Subtitles {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-MEDIA FORCED MUST NOT be present unless TYPE is SUBTITLES".to_string(),
        });
    }

    // INSTREAM-ID
    let instream_id = if let Some(v) = attrs.get("INSTREAM-ID") {
        validate_quoted_string(v, "EXT-X-MEDIA INSTREAM-ID")?;
        if media_type == MediaType::ClosedCaptions {
            Some(InstreamId::parse_closed_captions(v)?)
        } else {
            Some(InstreamId::Other(v.clone()))
        }
    } else {
        None
    };
    if media_type == MediaType::ClosedCaptions && instream_id.is_none() {
        return Err(Error::HlsParse {
            line_no,
            line: line.to_string(),
            reason: "EXT-X-MEDIA INSTREAM-ID REQUIRED when TYPE is CLOSED-CAPTIONS".to_string(),
        });
    }

    // BIT-DEPTH / SAMPLE-RATE / CHANNELS only for AUDIO
    let bit_depth = if let Some(v) = attrs.get("BIT-DEPTH") {
        if media_type != MediaType::Audio {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: "EXT-X-MEDIA BIT-DEPTH MUST NOT be present unless TYPE is AUDIO"
                    .to_string(),
            });
        }
        Some(parse_decimal_int(v, line_no, line, "BIT-DEPTH")?)
    } else {
        None
    };
    let sample_rate = if let Some(v) = attrs.get("SAMPLE-RATE") {
        if media_type != MediaType::Audio {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: "EXT-X-MEDIA SAMPLE-RATE MUST NOT be present unless TYPE is AUDIO"
                    .to_string(),
            });
        }
        Some(parse_decimal_int(v, line_no, line, "SAMPLE-RATE")?)
    } else {
        None
    };
    let channels = if let Some(v) = attrs.get("CHANNELS") {
        if media_type != MediaType::Audio {
            return Err(Error::HlsParse {
                line_no,
                line: line.to_string(),
                reason: "EXT-X-MEDIA CHANNELS MUST NOT be present unless TYPE is AUDIO".to_string(),
            });
        }
        validate_quoted_string(v, "EXT-X-MEDIA CHANNELS")?;
        Some(v.clone())
    } else {
        None
    };

    // CHARACTERISTICS
    let characteristics = attrs
        .get("CHARACTERISTICS")
        .map(|v| {
            validate_quoted_string(v, "EXT-X-MEDIA CHARACTERISTICS")?;
            Ok(v.split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>())
        })
        .transpose()?
        .unwrap_or_default();

    // extra_attrs
    const KNOWN: &[&str] = &[
        "TYPE",
        "URI",
        "GROUP-ID",
        "LANGUAGE",
        "ASSOC-LANGUAGE",
        "NAME",
        "STABLE-RENDITION-ID",
        "DEFAULT",
        "AUTOSELECT",
        "FORCED",
        "INSTREAM-ID",
        "BIT-DEPTH",
        "SAMPLE-RATE",
        "CHARACTERISTICS",
        "CHANNELS",
    ];
    let extra_attrs = filter_extra_attrs(&attrs, KNOWN, &quoted)?;

    // INSTREAM-ID version row 13 for non-CC is handled in version derivation.

    Ok(MediaRendition {
        media_type,
        uri,
        group_id,
        language,
        assoc_language,
        name,
        stable_rendition_id,
        default,
        autoselect,
        forced,
        instream_id,
        bit_depth,
        sample_rate,
        characteristics,
        channels,
        extra_attrs,
    })
}

/// Auto-detect init-segment changes across a sequence of segments and mark the
/// first segment that follows an init change as discontinuous (RFC 8216 §4.3.4.3).
///
/// `entries` is an ordered list of `(init_bytes, segment)` pairs — one per
/// media segment in playlist order. For each segment after the first, if its
/// init bytes differ from the preceding segment's, `segment.discontinuous` is
/// set to `true`. The first segment is never marked (no preceding context).
///
/// This is the building block for playlist assemblers that splice content from
/// multiple sources with different `EXT-X-MAP` init segments: detect changes
/// once, then pass the updated `MediaSegment` list to [`MediaPlaylist`].
///
/// # Example
/// ```
/// use broadcast_hls::{mark_init_discontinuities, DecimalSeconds, MediaSegment};
/// let init_a = b"moov_a" as &[u8];
/// let init_b = b"moov_b" as &[u8];
/// let five_secs = DecimalSeconds::new(5.0).unwrap();
/// let mut seg0 = MediaSegment { uri: "s0.m4s".into(), duration: five_secs, discontinuous: false, parts: vec![], ..Default::default() };
/// let mut seg1 = MediaSegment { uri: "s1.m4s".into(), duration: five_secs, discontinuous: false, parts: vec![], ..Default::default() };
/// let mut seg2 = MediaSegment { uri: "s2.m4s".into(), duration: five_secs, discontinuous: false, parts: vec![], ..Default::default() };
/// let mut entries: Vec<(&[u8], &mut MediaSegment)> = vec![
///     (init_a, &mut seg0),
///     (init_b, &mut seg1),
///     (init_b, &mut seg2),
/// ];
/// mark_init_discontinuities(&mut entries);
/// assert!(!entries[0].1.discontinuous);
/// assert!(entries[1].1.discontinuous);   // init changed: a → b
/// assert!(!entries[2].1.discontinuous);  // same init
/// ```
pub fn mark_init_discontinuities(entries: &mut [(&[u8], &mut MediaSegment)]) {
    if entries.len() < 2 {
        return;
    }
    // Walk the slice as a sliding window: [prev | cur..].
    // `split_at_mut` gives two non-overlapping sub-slices so we can hold an
    // immutable read of `prev.0` while mutating `cur.1.discontinuous`.
    for i in 1..entries.len() {
        let (head, tail) = entries.split_at_mut(i);
        let prev_init: &[u8] = head[i - 1].0;
        let cur = &mut tail[0];
        if cur.0 != prev_init {
            cur.1.discontinuous = true;
        }
    }
}

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

    fn seg(uri: &str, duration: f64) -> MediaSegment {
        MediaSegment {
            uri: uri.into(),
            duration: DecimalSeconds::new(duration).unwrap(),
            discontinuous: false,
            parts: vec![],
            ..Default::default()
        }
    }

    fn seg_disc(uri: &str, duration: f64) -> MediaSegment {
        MediaSegment {
            uri: uri.into(),
            duration: DecimalSeconds::new(duration).unwrap(),
            discontinuous: true,
            parts: vec![],
            ..Default::default()
        }
    }

    fn playlist(segments: Vec<MediaSegment>) -> MediaPlaylist {
        MediaPlaylist {
            version: 3,
            target_duration: 10,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments,
            endlist: true,
            extra_tags: vec![],
            low_latency: None,
            iframes_only: false,
            open_segment: None,
            ..Default::default()
        }
    }

    #[test]
    fn media_playlist_basic() {
        let pl = MediaPlaylist {
            version: 3,
            target_duration: 10,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![
                seg("seg0.m4s", 9.009),
                seg("seg1.m4s", 9.009),
                seg("seg2.m4s", 3.003),
            ],
            endlist: true,
            extra_tags: vec![],
            low_latency: None,
            iframes_only: false,
            open_segment: None,
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(out.starts_with("#EXTM3U\n"));
        assert!(out.contains("#EXT-X-TARGETDURATION:10\n"));
        assert!(out.contains("#EXT-X-MEDIA-SEQUENCE:0\n"));
        assert_eq!(out.matches("#EXTINF:").count(), 3);
        assert!(out.ends_with("#EXT-X-ENDLIST\n"));
        // No discontinuity sequence when 0.
        assert!(!out.contains("#EXT-X-DISCONTINUITY-SEQUENCE"));
    }

    #[test]
    fn media_playlist_no_endlist() {
        let pl = MediaPlaylist {
            version: 7,
            target_duration: 6,
            media_sequence: 42,
            discontinuity_sequence: 0,
            segments: vec![seg("seg.m4s", 6.000)],
            endlist: false,
            extra_tags: vec![],
            low_latency: None,
            iframes_only: false,
            open_segment: None,
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(out.starts_with("#EXTM3U\n"));
        assert!(out.contains("#EXT-X-VERSION:7\n"));
        assert!(!out.contains("#EXT-X-ENDLIST"));
    }

    #[test]
    fn master_playlist_basic() {
        let pl = MasterPlaylist {
            version: 6,
            media: vec![],
            variants: vec![
                Variant {
                    bandwidth: 300_000,
                    average_bandwidth: None,
                    frame_rate: None,
                    codecs: Some("avc1.64001e,mp4a.40.2".into()),
                    resolution: Some((640, 360)),
                    uri: "v300/index.m3u8".into(),
                    ..Default::default()
                },
                Variant {
                    bandwidth: 800_000,
                    average_bandwidth: None,
                    frame_rate: None,
                    codecs: Some("avc1.640028,mp4a.40.2".into()),
                    resolution: Some((1280, 720)),
                    uri: "v800/index.m3u8".into(),
                    ..Default::default()
                },
            ],
            iframe_variants: vec![],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(out.starts_with("#EXTM3U\n"));
        assert_eq!(out.matches("#EXT-X-STREAM-INF:").count(), 2);
        assert!(out.contains("v300/index.m3u8"));
        assert!(out.contains("v800/index.m3u8"));
        assert!(out.contains("RESOLUTION=640x360"));
        assert!(out.contains("RESOLUTION=1280x720"));
    }

    #[test]
    fn master_playlist_no_resolution() {
        let pl = MasterPlaylist {
            version: 6,
            media: vec![],
            variants: vec![Variant {
                bandwidth: 1_000_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.640028".into()),
                resolution: None,
                uri: "v1k/index.m3u8".into(),
                audio: None,
                video: None,
                subtitles: None,
                closed_captions: None,
                extra_attrs: Vec::new(),
            }],
            iframe_variants: vec![],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(!out.contains("RESOLUTION"));
        assert!(out.contains("#EXT-X-STREAM-INF:BANDWIDTH=1000000,CODECS=\"avc1.640028\""));
    }

    /// RFC 8216bis §4.4.6.2: `AVERAGE-BANDWIDTH` renders immediately after
    /// `BANDWIDTH`, and a `Variant` built with the attribute round-trips
    /// (render -> parse) with the same value.
    #[test]
    fn master_playlist_renders_average_bandwidth_after_bandwidth() {
        let pl = MasterPlaylist {
            media: vec![],
            variants: vec![Variant {
                bandwidth: 2_523_597,
                average_bandwidth: Some(2_190_673),
                frame_rate: None,
                codecs: Some("avc1.640020,mp4a.40.2".into()),
                uri: "v540/index.m3u8".into(),
                ..Default::default()
            }],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(
            out.contains(
                "#EXT-X-STREAM-INF:BANDWIDTH=2523597,AVERAGE-BANDWIDTH=2190673,\
                 CODECS=\"avc1.640020,mp4a.40.2\""
            ),
            "out: {out}"
        );
        let reparsed = MasterPlaylist::parse(&out).unwrap();
        assert_eq!(reparsed.variants, pl.variants, "render -> parse must equal");
        assert_eq!(reparsed.variants[0].average_bandwidth, Some(2_190_673));
    }

    /// A `Variant` with no `AVERAGE-BANDWIDTH` renders no attribute and
    /// round-trips as `None` (the attribute is optional on parse).
    #[test]
    fn master_playlist_omits_absent_average_bandwidth_and_round_trips_none() {
        let pl = MasterPlaylist {
            media: vec![],
            variants: vec![Variant {
                bandwidth: 800_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.640028,mp4a.40.2".into()),
                uri: "v800/index.m3u8".into(),
                ..Default::default()
            }],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(!out.contains("AVERAGE-BANDWIDTH"), "out: {out}");
        let reparsed = MasterPlaylist::parse(&out).unwrap();
        assert_eq!(reparsed.variants, pl.variants, "render -> parse must equal");
        assert_eq!(reparsed.variants[0].average_bandwidth, None);
    }

    /// A non-decimal `AVERAGE-BANDWIDTH` is a structured parse error, like
    /// `BANDWIDTH` (RFC 8216bis §4.2 `decimal-integer`).
    #[test]
    fn average_bandwidth_must_be_a_decimal_integer() {
        let text =
            "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1000,AVERAGE-BANDWIDTH=12x\nv/index.m3u8\n";
        let err = MasterPlaylist::parse(text).unwrap_err();
        match err {
            Error::HlsParse { reason, .. } => {
                assert!(reason.contains("AVERAGE-BANDWIDTH"), "reason: {reason}");
            }
            other => panic!("expected HlsParse, got {other:?}"),
        }
    }

    /// RFC 8216bis §4.4.6.2: `AVERAGE-BANDWIDTH` on
    /// `#EXT-X-I-FRAME-STREAM-INF` renders immediately after `BANDWIDTH` and
    /// round-trips (render -> parse) with the same value.
    #[test]
    fn iframe_variant_renders_average_bandwidth_after_bandwidth() {
        let pl = MasterPlaylist {
            iframe_variants: vec![IFrameVariant {
                bandwidth: 200_000,
                average_bandwidth: Some(150_000),
                codecs: Some("hvc1.1.6.L93.B0".into()),
                resolution: Some((320, 240)),
                uri: "iframe.m3u8".into(),
                extra_attrs: Vec::new(),
            }],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(
            out.contains("#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=200000,AVERAGE-BANDWIDTH=150000,"),
            "out: {out}"
        );
        let reparsed = MasterPlaylist::parse(&out).unwrap();
        assert_eq!(reparsed.iframe_variants, pl.iframe_variants);
        assert_eq!(reparsed.iframe_variants[0].average_bandwidth, Some(150_000));
    }

    /// An I-frame variant with no `AVERAGE-BANDWIDTH` renders no attribute
    /// and round-trips as `None`.
    #[test]
    fn iframe_variant_omits_absent_average_bandwidth_and_round_trips_none() {
        let pl = MasterPlaylist {
            iframe_variants: vec![IFrameVariant {
                bandwidth: 200_000,
                average_bandwidth: None,
                codecs: Some("hvc1.1.6.L93.B0".into()),
                resolution: Some((320, 240)),
                uri: "iframe.m3u8".into(),
                extra_attrs: Vec::new(),
            }],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(!out.contains("AVERAGE-BANDWIDTH"), "out: {out}");
        let reparsed = MasterPlaylist::parse(&out).unwrap();
        assert_eq!(reparsed.iframe_variants, pl.iframe_variants);
        assert_eq!(reparsed.iframe_variants[0].average_bandwidth, None);
    }

    /// A parsed I-frame `#EXT-X-I-FRAME-STREAM-INF` line carrying
    /// `AVERAGE-BANDWIDTH` exposes it on the typed field and NOT in
    /// `extra_attrs`.
    #[test]
    fn iframe_variant_average_bandwidth_not_retained_in_extra_attrs() {
        let text = "#EXTM3U\n#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=1000,AVERAGE-BANDWIDTH=1200,URI=\"i.m3u8\"\n";
        let pl = MasterPlaylist::parse(text).unwrap();
        assert_eq!(pl.iframe_variants[0].average_bandwidth, Some(1200));
        assert!(
            pl.iframe_variants[0].extra_attrs.is_empty(),
            "extra_attrs: {:?}",
            pl.iframe_variants[0].extra_attrs
        );
        assert!(
            !pl.iframe_variants[0]
                .extra_attrs
                .iter()
                .any(|(k, _)| k == "AVERAGE-BANDWIDTH")
        );
    }

    /// A non-decimal `AVERAGE-BANDWIDTH` on an I-frame variant is a
    /// structured parse error, like `BANDWIDTH`.
    #[test]
    fn iframe_average_bandwidth_must_be_a_decimal_integer() {
        let text = "#EXTM3U\n#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=1000,AVERAGE-BANDWIDTH=12x,URI=\"i.m3u8\"\n";
        let err = MasterPlaylist::parse(text).unwrap_err();
        match err {
            Error::HlsParse { reason, .. } => {
                assert!(reason.contains("AVERAGE-BANDWIDTH"), "reason: {reason}");
            }
            other => panic!("expected HlsParse, got {other:?}"),
        }
    }

    /// RFC 8216bis §4.4.6.2 / Apple 9.15: `FRAME-RATE` renders after
    /// `RESOLUTION` as an exact 3-decimal millihertz value and round-trips.
    #[test]
    fn master_playlist_renders_frame_rate_after_resolution() {
        let pl = MasterPlaylist {
            media: vec![],
            variants: vec![Variant {
                bandwidth: 1_000_000,
                average_bandwidth: None,
                codecs: Some("avc1.640028".into()),
                resolution: Some((1280, 720)),
                frame_rate: Some(FrameRate::from_millihertz(29_970)),
                uri: "v/index.m3u8".into(),
                ..Default::default()
            }],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(
            out.contains("RESOLUTION=1280x720,FRAME-RATE=29.970"),
            "out: {out}"
        );
        let reparsed = MasterPlaylist::parse(&out).unwrap();
        assert_eq!(reparsed.variants, pl.variants);
        assert_eq!(
            reparsed.variants[0].frame_rate,
            Some(FrameRate::from_millihertz(29_970))
        );
    }

    /// A `Variant` with no `FRAME-RATE` renders no attribute and round-trips
    /// as `None`.
    #[test]
    fn master_playlist_omits_absent_frame_rate_and_round_trips_none() {
        let pl = MasterPlaylist {
            media: vec![],
            variants: vec![Variant {
                bandwidth: 800_000,
                average_bandwidth: None,
                codecs: Some("avc1.640028".into()),
                resolution: None,
                frame_rate: None,
                uri: "v/index.m3u8".into(),
                ..Default::default()
            }],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(!out.contains("FRAME-RATE"), "out: {out}");
        let reparsed = MasterPlaylist::parse(&out).unwrap();
        assert_eq!(reparsed.variants[0].frame_rate, None);
    }

    /// Parse `FRAME-RATE` decimal-floating-point values, rounding half-up to
    /// three decimals into millihertz.
    #[test]
    fn frame_rate_parses_various_forms() {
        for (text, expected) in [
            ("30", 30_000u32),
            ("29.97", 29_970u32),
            ("29.9704", 29_970u32),
        ] {
            let src = format!(
                "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1000,FRAME-RATE={text}\nv/index.m3u8\n"
            );
            let parsed = MasterPlaylist::parse(&src).unwrap();
            assert_eq!(
                parsed.variants[0].frame_rate,
                Some(FrameRate::from_millihertz(expected)),
                "text={text}"
            );
        }
    }

    /// `FRAME-RATE` parse rejects empty / negative / exponent / non-numeric
    /// values with a structured `HlsParse` error naming the attribute.
    #[test]
    fn frame_rate_rejects_invalid_values() {
        for value in ["", "-1", "1e3", "abc", "1.2.3"] {
            let src = format!(
                "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1000,FRAME-RATE={value}\nv/index.m3u8\n"
            );
            let err = MasterPlaylist::parse(&src).unwrap_err();
            match err {
                Error::HlsParse { reason, .. } => {
                    assert!(
                        reason.contains("FRAME-RATE"),
                        "value={value:?} reason={reason}"
                    );
                }
                other => panic!("value={value:?} expected HlsParse, got {other:?}"),
            }
        }
    }

    /// The 3-decimal `#EXTINF` form (`9.009` — what every RFC 8216 example
    /// and every existing consumer expects) is kept for genuinely fractional
    /// durations.
    #[test]
    fn extinf_three_decimals() {
        let pl = playlist(vec![seg("s.m4s", 9.009)]);
        let out = pl.to_m3u8().unwrap();
        assert!(out.contains("#EXTINF:9.009,\n"), "{out}");
    }

    /// RFC 8216bis §8 row 3: "A Media Playlist MUST indicate an
    /// EXT-X-VERSION of 3 or higher if it contains: Floating-point EXTINF
    /// duration values." The requirement is about what the playlist
    /// **contains**, so a whole number of seconds must render as an integer
    /// — otherwise `to_m3u8` emitted `#EXTINF:9.000,` (a floating-point
    /// value) while `computed_version` reported `None`, telling a v1/v2
    /// client the playlist was compatible with it and then handing it a
    /// float it cannot parse.
    ///
    /// MUTATION VERIFIED: restoring the old `format!("{v:.3}")`-first body
    /// of `format_extinf` makes the `#EXTINF:9,` assertion below fail
    /// (`9.000` is rendered instead). Recompiled and re-run to confirm,
    /// then reverted.
    #[test]
    fn integral_extinf_renders_as_an_integer_and_needs_no_version() {
        // `version: 0` — no explicit floor, so the rendered tag (or its
        // absence) is exactly what the derivation asks for.
        let pl = MediaPlaylist {
            version: 0,
            ..playlist(vec![seg("s.m4s", 9.0)])
        };
        let out = pl.to_m3u8().unwrap();
        assert!(out.contains("#EXTINF:9,\n"), "{out}");
        assert!(!out.contains("9.000"), "{out}");
        assert_eq!(
            pl.computed_version(),
            None,
            "a playlist with no floating-point EXTINF trips no §8 row: {out}"
        );
        assert!(!out.contains("#EXT-X-VERSION"), "{out}");
        // ...and it still re-parses to the identical f64.
        let reparsed = MediaPlaylist::parse(&out).expect("round-trip parse");
        assert_eq!(
            reparsed.segments[0].duration,
            DecimalSeconds::new(9.0).unwrap()
        );
    }

    /// The renderer and the §8 row-3 predicate must never disagree about
    /// whether a duration is floating-point — the divergence that caused the
    /// bug above. Pins the exact four values from the report, plus the
    /// sub-millisecond case that diverged in the *other* direction (the
    /// old integer-millisecond predicate called `4.0004` integral while
    /// issue #882's precision fallback rendered it as `4.0004`).
    #[test]
    fn extinf_rendering_and_version_derivation_never_diverge() {
        for (duration, expected_text, expected_version) in [
            (4.0_f64, "#EXTINF:4,", None),
            (4.004, "#EXTINF:4.004,", Some(3)),
            (9.9766, "#EXTINF:9.9766,", Some(3)), // issue #882 regression guard
            (4.0004, "#EXTINF:4.0004,", Some(3)), // sub-ms: predicate used to say None
        ] {
            let pl = playlist(vec![seg("s.m4s", duration)]);
            let out = pl.to_m3u8().unwrap();
            assert!(out.contains(expected_text), "{duration}: {out}");
            assert_eq!(pl.computed_version(), expected_version, "{duration}: {out}");
            // The invariant, stated directly: a rendered decimal point and a
            // row-3 requirement are the same thing.
            assert_eq!(
                out.contains(expected_text) && expected_text.contains('.'),
                expected_version == Some(3),
                "{duration}: rendered text and §8 row 3 must agree: {out}"
            );
            // Bit-exact round-trip of the duration itself.
            let reparsed = MediaPlaylist::parse(&out).expect("round-trip parse");
            assert_eq!(reparsed.segments[0].duration.get(), duration, "{out}");
        }
    }

    /// Regression (issue #872): durations finer than 1 ms must survive
    /// rendering. `to_m3u8` used a hardcoded `{:.3}` for `#EXTINF` and
    /// integer-millisecond math for every other seconds value, so real
    /// content silently lost precision — Apple's BipBop playlists carry
    /// `#EXTINF:9.9766` (rendered back as `9.977`) and RFC 8216bis §9.11's
    /// LL-HLS example carries `DURATION=2.00004` (rendered back as `2`).
    /// Found by round-tripping the real `fixtures/hls/real/` playlists; no
    /// hand-made 3-decimal fixture could have surfaced it.
    #[test]
    fn sub_millisecond_durations_survive_rendering() {
        // #EXTINF — the value that actually failed against real Apple data.
        let pl = playlist(vec![seg("main.ts", 9.9766)]);
        let out = pl.to_m3u8().unwrap();
        assert!(
            out.contains("#EXTINF:9.9766,\n"),
            "EXTINF must not be truncated to 3 decimals:\n{out}"
        );
        assert_eq!(
            MediaPlaylist::parse(&out).unwrap().segments[0].duration,
            DecimalSeconds::new(9.9766).unwrap(),
            "duration must survive a round trip bit-exactly"
        );

        // The ms-granular common case keeps its historical compact form.
        assert_eq!(format_secs(DecimalSeconds::new(0.334).unwrap()), "0.334");
        assert_eq!(format_secs(DecimalSeconds::new(1.5).unwrap()), "1.5");
        assert_eq!(format_secs(DecimalSeconds::new(6.0).unwrap()), "6");
        // ...and the sub-ms case is now lossless rather than rounded to it.
        assert_eq!(
            format_secs(DecimalSeconds::new(2.00004).unwrap()),
            "2.00004"
        );
        assert_eq!(
            format_secs(DecimalSeconds::new(4.00008).unwrap()),
            "4.00008"
        );
        assert_eq!(
            format_signed_secs(SignedDecimalSeconds::new(-10.5).unwrap()),
            "-10.5"
        );
        assert_eq!(
            format_signed_secs(SignedDecimalSeconds::new(-2.00004).unwrap()),
            "-2.00004"
        );
    }

    /// Audit BH-W4 (issue #1140): `f64::from_str` is far more permissive
    /// than RFC 8216bis §4.2's decimal-floating-point grammar — it also
    /// accepts `nan`/`inf`/`infinity`, a leading `+`, and exponent
    /// notation. `#EXTINF:nan,` previously parsed `Ok` into a NaN duration.
    #[test]
    fn extinf_and_ll_hls_durations_reject_non_conformant_decimal_tokens() {
        for bad in ["nan", "inf", "-inf", "infinity", "1e10", "+3", "-5", ""] {
            let pl = format!("#EXTM3U\n#EXTINF:{bad},\nmain.ts\n");
            assert!(
                MediaPlaylist::parse(&pl).is_err(),
                "EXTINF:{bad} must be rejected"
            );
        }
        // TIME-OFFSET is the one signed field; it still rejects nan/inf/exponent.
        for bad in ["nan", "inf", "1e5"] {
            let pl = format!("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-START:TIME-OFFSET={bad}\n");
            assert!(
                MediaPlaylist::parse(&pl).is_err(),
                "TIME-OFFSET={bad} must be rejected"
            );
        }
        // A conformant negative TIME-OFFSET is still accepted.
        let pl = "#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-START:TIME-OFFSET=-12.5\n";
        assert_eq!(
            MediaPlaylist::parse(pl).unwrap().start.unwrap().time_offset,
            SignedDecimalSeconds::new(-12.5).unwrap()
        );
    }

    /// Coordinator follow-up to BH-W4/T12 (issue #1140): a NaN/inf/negative
    /// value must never *exist* as a `DecimalSeconds` in the first place —
    /// no silent renderer-side clamp, exactly the same discipline as
    /// `AttrValue`. `DecimalSeconds::new` rejects it at construction, so a
    /// bad value can never reach `format_secs`/`format_extinf` at all.
    #[test]
    fn decimal_seconds_rejects_non_finite_and_negative() {
        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0] {
            assert!(
                DecimalSeconds::new(bad).is_err(),
                "DecimalSeconds::new({bad}) must be rejected"
            );
        }
        // A finite, non-negative value round-trips through get() unchanged.
        assert_eq!(DecimalSeconds::new(6.0).unwrap().get(), 6.0);
    }

    /// As above, for the signed field (`TIME-OFFSET`): only NaN/inf are
    /// rejected, since a negative value is legitimate there.
    #[test]
    fn signed_decimal_seconds_rejects_non_finite_but_allows_negative() {
        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            assert!(
                SignedDecimalSeconds::new(bad).is_err(),
                "SignedDecimalSeconds::new({bad}) must be rejected"
            );
        }
        assert_eq!(SignedDecimalSeconds::new(-6.0).unwrap().get(), -6.0);
    }

    /// A whole real-shaped LL-HLS playlist built from RFC 8216bis §9.11's
    /// actual sub-millisecond part/segment durations must round-trip. The
    /// spec's own §9.11 fixture can't cover this (it is unparsable — its
    /// `...` elision line, see `tests/it/hls_fixture_corpus.rs`), so the values
    /// are exercised here instead.
    #[test]
    fn round_trip_rfc_9_11_sub_millisecond_part_durations() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            segments: vec![MediaSegment {
                uri: "fileSequence271.mp4".into(),
                duration: DecimalSeconds::new(4.00008).unwrap(),
                parts: vec![
                    PartSpec {
                        uri: "filePart271.0.mp4".into(),
                        duration: DecimalSeconds::new(2.00004).unwrap(),
                        independent: true,
                        ..Default::default()
                    },
                    PartSpec {
                        uri: "filePart271.1.mp4".into(),
                        duration: DecimalSeconds::new(0.50001).unwrap(),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            low_latency: Some(LowLatencyConfig {
                part_target: Some(DecimalSeconds::new(2.00002).unwrap()),
                part_hold_back: Some(DecimalSeconds::new(6.00006).unwrap()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let text = pl.to_m3u8().unwrap();
        assert!(text.contains("#EXTINF:4.00008,"), "{text}");
        assert!(text.contains("DURATION=2.00004"), "{text}");
        assert!(text.contains("DURATION=0.50001"), "{text}");
        assert!(text.contains("PART-TARGET=2.00002"), "{text}");
        assert_eq!(
            MediaPlaylist::parse(&text).expect("must parse"),
            pl,
            "sub-ms LL-HLS durations must round-trip:\n{text}"
        );
    }

    // --- discontinuity tag tests ---

    #[test]
    fn discontinuity_tag_emitted_before_extinf() {
        // seg1 is discontinuous; the tag must appear before its #EXTINF.
        let pl = playlist(vec![
            seg("s0.m4s", 5.0),
            seg_disc("s1.m4s", 5.0),
            seg("s2.m4s", 5.0),
        ]);
        let out = pl.to_m3u8().unwrap();
        assert_eq!(out.matches("#EXT-X-DISCONTINUITY\n").count(), 1);
        // The tag must immediately precede the #EXTINF for s1.
        let disc_pos = out.find("#EXT-X-DISCONTINUITY\n").unwrap();
        let extinf_pos = out.find("#EXTINF:5.000,\n#s1.m4s\n").unwrap_or_else(|| {
            // Find the position of "s1.m4s" in the output and trace back to its #EXTINF.
            let s1_pos = out.find("s1.m4s\n").unwrap();
            // The #EXTINF line starts 11 chars before "5.000,\n" — find it preceding s1.
            out[..s1_pos].rfind("#EXTINF:").unwrap()
        });
        assert!(
            disc_pos < extinf_pos,
            "#EXT-X-DISCONTINUITY must appear before #EXTINF of s1"
        );
        // The discontinuity tag must be the line immediately before #EXTINF:
        let tag_end = disc_pos + "#EXT-X-DISCONTINUITY\n".len();
        assert!(
            out[tag_end..].starts_with("#EXTINF:"),
            "#EXT-X-DISCONTINUITY must be immediately before #EXTINF, got: {:?}",
            &out[tag_end..tag_end + 20]
        );
    }

    #[test]
    fn no_discontinuity_tag_when_all_continuous() {
        let pl = playlist(vec![
            seg("s0.m4s", 5.0),
            seg("s1.m4s", 5.0),
            seg("s2.m4s", 5.0),
        ]);
        let out = pl.to_m3u8().unwrap();
        assert!(
            !out.contains("#EXT-X-DISCONTINUITY\n"),
            "no tag when all segments are continuous"
        );
    }

    #[test]
    fn discontinuity_sequence_emitted_when_nonzero() {
        let pl = MediaPlaylist {
            version: 3,
            target_duration: 6,
            media_sequence: 5,
            discontinuity_sequence: 2,
            segments: vec![seg("s5.m4s", 6.0)],
            endlist: false,
            extra_tags: vec![],
            low_latency: None,
            iframes_only: false,
            open_segment: None,
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(
            out.contains("#EXT-X-DISCONTINUITY-SEQUENCE:2\n"),
            "header must be present when n>0"
        );
    }

    #[test]
    fn discontinuity_sequence_absent_when_zero() {
        let pl = playlist(vec![seg("s0.m4s", 6.0)]);
        let out = pl.to_m3u8().unwrap();
        assert!(
            !out.contains("#EXT-X-DISCONTINUITY-SEQUENCE"),
            "header must be absent when n==0"
        );
    }

    // --- LL-HLS render tests (issue #702: OpenSegment) ---

    fn ll_config() -> LowLatencyConfig {
        LowLatencyConfig {
            part_target: Some(DecimalSeconds::new(0.5).unwrap()),
            part_hold_back: Some(DecimalSeconds::new(1.5).unwrap()),
            preload_hint_part: None,
            ..Default::default()
        }
    }

    #[test]
    fn server_control_without_part_target_keeps_part_hold_back() {
        let pl = MediaPlaylist {
            target_duration: 4,
            low_latency: Some(LowLatencyConfig {
                part_target: None,
                part_hold_back: Some(DecimalSeconds::new(1.5).unwrap()),
                hold_back: Some(DecimalSeconds::new(12.0).unwrap()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(out.contains("PART-HOLD-BACK=1.5"), "{out}");
        assert!(!out.contains("#EXT-X-PART-INF"), "{out}");
    }

    #[test]
    fn ll_hls_renders_server_control_part_inf_and_parts() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![MediaSegment {
                uri: "seg-1-4.m4s".into(),
                duration: DecimalSeconds::new(4.0).unwrap(),
                discontinuous: false,
                parts: vec![PartSpec {
                    uri: "part-1-1.m4s".into(),
                    duration: DecimalSeconds::new(0.5).unwrap(),
                    independent: true,
                    ..Default::default()
                }],
                ..Default::default()
            }],
            endlist: false,
            extra_tags: vec![],
            low_latency: Some(ll_config()),
            iframes_only: false,
            open_segment: None,
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(out.contains("#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES"));
        assert!(out.contains("#EXT-X-PART-INF:PART-TARGET="));
        assert!(out.contains("#EXT-X-PART:DURATION=0.5,URI=\"part-1-1.m4s\""));
    }

    #[test]
    fn open_segment_renders_parts_without_extinf() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![MediaSegment {
                uri: "seg-1-4.m4s".into(),
                duration: DecimalSeconds::new(4.0).unwrap(),
                discontinuous: false,
                parts: vec![],
                ..Default::default()
            }],
            endlist: false,
            extra_tags: vec![],
            low_latency: Some(ll_config()),
            iframes_only: false,
            open_segment: Some(OpenSegment::new(vec![PartSpec {
                uri: "part-1-5.0.m4s".into(),
                duration: DecimalSeconds::new(0.5).unwrap(),
                independent: true,
                ..Default::default()
            }])),
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        // The open part is rendered as an #EXT-X-PART line.
        assert!(
            out.contains("#EXT-X-PART:DURATION=0.5,URI=\"part-1-5.0.m4s\",INDEPENDENT=YES"),
            "open segment's part must render:\n{out}"
        );
        // The closed segment is still rendered with its #EXTINF (a whole
        // 4.0 s renders as the integer `4` — see
        // `integral_extinf_renders_as_an_integer_and_needs_no_version`).
        assert!(out.contains("#EXTINF:4,\n"), "{out}");
        assert!(out.contains("seg-1-4.m4s"));
        // The open part's URI never appears on an #EXTINF/plain-URI line — only
        // inside its #EXT-X-PART line (there is no #EXTINF for an open segment).
        assert!(
            !out.contains("#EXTINF:0.500,\npart-1-5.0.m4s"),
            "open segment must not be rendered as a closed #EXTINF segment:\n{out}"
        );
        // Exact count: only 1 closed segment, so exactly 1 #EXTINF occurrence.
        assert_eq!(
            out.matches("#EXTINF:").count(),
            1,
            "only closed segments should have #EXTINF lines; open segment must not:\n{out}"
        );
        let lines: Vec<&str> = out.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if *line == "part-1-5.0.m4s" {
                panic!("open part URI must not appear on its own URI line: {out}");
            }
            if line.starts_with("#EXTINF") && i + 1 < lines.len() {
                assert_ne!(
                    lines[i + 1],
                    "part-1-5.0.m4s",
                    "open part URI must not follow an #EXTINF line:\n{out}"
                );
            }
        }
    }

    /// Audit BH-O3 (#1111): the open segment's EXT-X-MAP is rendered only
    /// with low-latency on, so it must not raise the computed version
    /// (EXT-X-MAP needs >= 6) when LL is off.
    #[test]
    fn open_segment_map_does_not_count_toward_version_without_low_latency() {
        let mut open = OpenSegment::new(vec![PartSpec {
            uri: "part-1-5.0.m4s".into(),
            duration: DecimalSeconds::new(0.5).unwrap(),
            independent: true,
            ..Default::default()
        }]);
        open.map = Some(MapTag {
            uri: "init.mp4".into(),
            byte_range: None,
            extra_attrs: Vec::new(),
        });
        let mut pl = MediaPlaylist {
            target_duration: 4,
            segments: vec![seg("seg-1-4.m4s", 4.0)],
            open_segment: Some(open),
            ..Default::default()
        };
        assert_eq!(
            pl.computed_version(),
            None,
            "map not rendered, no version row"
        );
        pl.low_latency = Some(ll_config());
        assert!(pl.computed_version() >= Some(6));
    }

    #[test]
    fn open_segment_not_rendered_without_low_latency() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![seg("seg-1-4.m4s", 4.0)],
            endlist: false,
            extra_tags: vec![],
            low_latency: None,
            iframes_only: false,
            open_segment: Some(OpenSegment::new(vec![PartSpec {
                uri: "part-1-5.0.m4s".into(),
                duration: DecimalSeconds::new(0.5).unwrap(),
                independent: true,
                ..Default::default()
            }])),
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(
            !out.contains("part-1-5.0.m4s"),
            "open segment parts must not render without low_latency:\n{out}"
        );
        assert!(!out.contains("#EXT-X-PART:"));
    }

    #[test]
    fn preload_hint_rendered_from_low_latency() {
        let mut ll = ll_config();
        ll.preload_hint_part = Some("part-1-5.1.m4s".into());
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![seg("seg-1-4.m4s", 4.0)],
            endlist: false,
            extra_tags: vec![],
            low_latency: Some(ll),
            iframes_only: false,
            open_segment: None,
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(out.contains("#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"part-1-5.1.m4s\""));
    }

    #[test]
    fn open_segment_parts_precede_preload_hint() {
        let mut ll = ll_config();
        ll.preload_hint_part = Some("part-1-5.1.m4s".into());
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![MediaSegment {
                uri: "seg-1-4.m4s".into(),
                duration: DecimalSeconds::new(4.0).unwrap(),
                discontinuous: false,
                parts: vec![],
                ..Default::default()
            }],
            endlist: false,
            extra_tags: vec![],
            low_latency: Some(ll),
            iframes_only: false,
            open_segment: Some(OpenSegment::new(vec![PartSpec {
                uri: "part-1-5.0.m4s".into(),
                duration: DecimalSeconds::new(0.5).unwrap(),
                independent: true,
                ..Default::default()
            }])),
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        // Both the open-segment part and preload-hint must be present.
        assert!(
            out.contains("#EXT-X-PART:DURATION=0.5,URI=\"part-1-5.0.m4s\",INDEPENDENT=YES"),
            "open-segment part must be present:\n{out}"
        );
        assert!(
            out.contains("#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"part-1-5.1.m4s\""),
            "preload-hint must be present:\n{out}"
        );
        // The open-segment #EXT-X-PART line must appear BEFORE the #EXT-X-PRELOAD-HINT line.
        let part_pos = out
            .find("#EXT-X-PART:DURATION=0.5,URI=\"part-1-5.0.m4s\",INDEPENDENT=YES")
            .expect("open-segment part line not found");
        let preload_pos = out
            .find("#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"part-1-5.1.m4s\"")
            .expect("preload-hint line not found");
        assert!(
            part_pos < preload_pos,
            "open-segment #EXT-X-PART must precede #EXT-X-PRELOAD-HINT:\npart at {}, preload at {}\noutput:\n{out}",
            part_pos,
            preload_pos
        );
    }

    /// Issue #717 slice 5 follow-up fix: `#EXT-X-MAP` applies "until the
    /// next `EXT-X-MAP` tag or the end of the Playlist" (RFC 8216bis
    /// §4.4.4.5) — including to the *open* (never-yet-closed) segment, even
    /// when NO segment has closed yet (the very first segment of a
    /// freshly-tuned-into live stream). Before this fix, `OpenSegment`
    /// carried no `map` field at all, so a client parsing a playlist with
    /// only an open segment had no way to learn the init segment's URI
    /// until that segment's first *closed* appearance — needlessly
    /// delaying every part's playback until then.
    #[test]
    fn open_segment_inherits_map_when_no_segment_has_closed_yet() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:9\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-MEDIA-SEQUENCE:1\n\
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=1.5\n\
#EXT-X-PART-INF:PART-TARGET=0.5\n\
#EXT-X-MAP:URI=\"init-1.mp4\"\n\
#EXT-X-PART:DURATION=0.5,URI=\"part-1-1.0.m4s\",INDEPENDENT=YES\n\
#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"part-1-1.1.m4s\"\n";
        let pl = MediaPlaylist::parse(text).expect("must parse");
        assert!(pl.segments.is_empty(), "no segment has closed yet");
        let open = pl.open_segment.as_ref().expect("one open segment");
        assert_eq!(
            open.map,
            Some(MapTag {
                uri: "init-1.mp4".into(),
                byte_range: None,
                extra_attrs: Vec::new(),
            }),
            "the open segment must inherit the EXT-X-MAP that precedes it, \
             even though no segment has closed yet"
        );
    }

    /// Round trip the same no-closed-segments-yet shape through
    /// `to_m3u8`/`parse`, proving the renderer emits the `#EXT-X-MAP` line
    /// for a bare open segment (not just for closed ones).
    #[test]
    fn round_trip_open_segment_only_with_map() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 1,
            discontinuity_sequence: 0,
            segments: vec![],
            open_segment: Some(
                OpenSegment::new(vec![PartSpec {
                    uri: "part-1-1.0.m4s".into(),
                    duration: DecimalSeconds::new(0.5).unwrap(),
                    independent: true,
                    ..Default::default()
                }])
                .with_map(MapTag {
                    uri: "init-1.mp4".into(),
                    byte_range: None,
                    extra_attrs: Vec::new(),
                }),
            ),
            endlist: false,
            extra_tags: vec![],
            low_latency: Some(ll_config()),
            iframes_only: false,
            ..Default::default()
        };
        let text = pl.to_m3u8().unwrap();
        assert!(
            text.contains("#EXT-X-MAP:URI=\"init-1.mp4\""),
            "renderer must emit EXT-X-MAP for a bare open segment:\n{text}"
        );
        let parsed = MediaPlaylist::parse(&text).expect("parse must succeed");
        assert_eq!(parsed, pl, "round trip must be lossless:\n{text}");
    }

    // --- parsing (issue #717 slice 1): round-trip + real-world-sample tests ---

    fn ll_config_full() -> LowLatencyConfig {
        LowLatencyConfig {
            part_target: Some(DecimalSeconds::new(0.5).unwrap()),
            part_hold_back: Some(DecimalSeconds::new(1.5).unwrap()), // already at the 3x floor: idempotent through render.
            preload_hint_part: Some("part-9.2.m4s".into()),
            preload_hint_type: PreloadHintType::Part,
            preload_hint_byte_range_start: Some(0),
            preload_hint_byte_range_length: Some(1000),
            can_skip_until: Some(DecimalSeconds::new(24.0).unwrap()),
            can_block_reload: true,
            hold_back: None,
            can_skip_dateranges: false,
            ..Default::default()
        }
    }

    #[test]
    fn round_trip_live_ll_playlist_with_parts_preload_and_server_control() {
        let map = MapTag {
            uri: "init.mp4".into(),
            byte_range: Some(ByteRange {
                length: 800,
                offset: Some(0),
            }),
            extra_attrs: Vec::new(),
        };
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 100,
            discontinuity_sequence: 0,
            segments: vec![MediaSegment {
                uri: "seg-9.m4s".into(),
                duration: DecimalSeconds::new(4.0).unwrap(),
                discontinuous: false,
                parts: vec![
                    PartSpec {
                        uri: "part-9.0.m4s".into(),
                        duration: DecimalSeconds::new(0.5).unwrap(),
                        independent: true,
                        byte_range: None,
                        gap: false,
                        ..Default::default()
                    },
                    PartSpec {
                        uri: "part-9.1.m4s".into(),
                        duration: DecimalSeconds::new(0.5).unwrap(),
                        independent: false,
                        byte_range: Some(ByteRange {
                            length: 500,
                            offset: Some(1000),
                        }),
                        gap: false,
                        ..Default::default()
                    },
                ],
                byte_range: None,
                map: Some(map.clone()),
                ..Default::default()
            }],
            // `#EXT-X-MAP` applies "until the next EXT-X-MAP or the end of
            // the Playlist" (RFC 8216bis §4.4.4.5) — the open segment is
            // still governed by the same map as the preceding closed
            // segment (no new `#EXT-X-MAP` appears between them), so it
            // must carry it too for a lossless round trip.
            open_segment: Some(
                OpenSegment::new(vec![PartSpec {
                    uri: "part-10.0.m4s".into(),
                    duration: DecimalSeconds::new(0.5).unwrap(),
                    independent: true,
                    byte_range: None,
                    gap: true,
                    extra_attrs: Vec::new(),
                }])
                .with_map(map.clone()),
            ),
            endlist: false,
            extra_tags: vec![],
            low_latency: Some(ll_config_full()),
            iframes_only: false,
            rendition_reports: vec![RenditionReport {
                uri: "../audio/playlist.m3u8".into(),
                last_msn: 100,
                last_part: Some(1),
                extra_attrs: Vec::new(),
            }],
            skip: None,
            ..Default::default()
        };
        let text = pl.to_m3u8().unwrap();
        let parsed = MediaPlaylist::parse(&text).expect("parse must succeed");
        assert_eq!(parsed, pl, "round trip must be lossless:\n{text}");
    }

    #[test]
    fn round_trip_vod_playlist_with_byteranges_map_and_endlist() {
        let map = MapTag {
            uri: "init.mp4".into(),
            byte_range: None,
            extra_attrs: Vec::new(),
        };
        let pl = MediaPlaylist {
            version: 6,
            target_duration: 10,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![
                MediaSegment {
                    uri: "media.ts".into(),
                    duration: DecimalSeconds::new(10.0).unwrap(),
                    discontinuous: false,
                    parts: vec![],
                    byte_range: Some(ByteRange {
                        length: 500_000,
                        offset: Some(0),
                    }),
                    map: Some(map.clone()),
                    ..Default::default()
                },
                MediaSegment {
                    uri: "media.ts".into(),
                    duration: DecimalSeconds::new(10.0).unwrap(),
                    discontinuous: false,
                    parts: vec![],
                    // No offset: continues immediately after the previous
                    // sub-range of the same resource (RFC 8216bis §4.4.4.2).
                    byte_range: Some(ByteRange {
                        length: 500_000,
                        offset: None,
                    }),
                    // Same map as the previous segment — to_m3u8 must dedup
                    // (emit the tag only once) and parse must carry it forward.
                    map: Some(map.clone()),
                    pre_tags: vec![
                        "#EXT-X-DATERANGE:ID=\"ad-1\",START-DATE=\"2024-01-01T00:00:00.000Z\",DURATION=15.0"
                            .into(),
                    ],
                    ..Default::default()
                },
            ],
            open_segment: None,
            endlist: true,
            low_latency: None,
            iframes_only: false,
            rendition_reports: vec![],
            skip: None,
            ..Default::default()
        };
        let text = pl.to_m3u8().unwrap();
        // The map is only emitted once (dedup), not once per segment.
        assert_eq!(
            text.matches("#EXT-X-MAP:").count(),
            1,
            "identical map on consecutive segments must render once:\n{text}"
        );
        let parsed = MediaPlaylist::parse(&text).expect("parse must succeed");
        assert_eq!(parsed, pl, "round trip must be lossless:\n{text}");
    }

    /// Round-trips the remaining new §4.4.2/§4.4.3.5/§4.4.4.7/§4.4.4.8 tags
    /// that live on [`MediaPlaylist`] (issue #872): INDEPENDENT-SEGMENTS,
    /// START, DEFINE (IMPORT form — only valid in a Media Playlist),
    /// PLAYLIST-TYPE, GAP, and BITRATE (carry-forward + dedup, like MAP).
    #[test]
    fn round_trip_media_playlist_with_new_872_tags() {
        let pl = MediaPlaylist {
            version: 6,
            target_duration: 10,
            media_sequence: 0,
            discontinuity_sequence: 0,
            independent_segments: true,
            start: Some(StartPoint {
                time_offset: SignedDecimalSeconds::new(5.5).unwrap(),
                precise: false,
                extra_attrs: Vec::new(),
            }),
            defines: vec![Define::Import {
                name: "base".into(),
                extra_attrs: Vec::new(),
            }],
            playlist_type: Some(PlaylistType::Vod),
            segments: vec![
                MediaSegment {
                    uri: "seg0.ts".into(),
                    duration: DecimalSeconds::new(10.0).unwrap(),
                    bitrate: Some(2000),
                    ..Default::default()
                },
                MediaSegment {
                    uri: "seg1.ts".into(),
                    duration: DecimalSeconds::new(10.0).unwrap(),
                    gap: true,
                    bitrate: Some(2000),
                    ..Default::default()
                },
                MediaSegment {
                    uri: "seg2.ts".into(),
                    duration: DecimalSeconds::new(10.0).unwrap(),
                    bitrate: Some(1800),
                    ..Default::default()
                },
            ],
            endlist: true,
            ..Default::default()
        };
        let text = pl.to_m3u8().unwrap();
        assert!(text.contains("#EXT-X-INDEPENDENT-SEGMENTS\n"));
        assert!(text.contains("#EXT-X-DEFINE:IMPORT=\"base\"\n"));
        assert!(text.contains("#EXT-X-START:TIME-OFFSET=5.5\n"));
        assert!(
            !text.contains("PRECISE"),
            "PRECISE=NO must be omitted:\n{text}"
        );
        assert!(text.contains("#EXT-X-PLAYLIST-TYPE:VOD\n"));
        assert!(text.contains("#EXT-X-GAP\n"));
        // BITRATE carries forward + dedups: 2000 (seg0), unchanged for seg1
        // (no re-emit), then 1800 for seg2 — exactly 2 EXT-X-BITRATE lines.
        assert_eq!(
            text.matches("#EXT-X-BITRATE:").count(),
            2,
            "unchanged bitrate must not re-emit:\n{text}"
        );
        assert!(text.contains("#EXT-X-BITRATE:2000\n"));
        assert!(text.contains("#EXT-X-BITRATE:1800\n"));
        let parsed = MediaPlaylist::parse(&text).expect("parse must succeed");
        assert_eq!(parsed, pl, "round trip must be lossless:\n{text}");
    }

    /// `#EXT-X-PLAYLIST-TYPE` with an unrecognized value must error rather
    /// than silently default (issue #872): unlike some other attributes,
    /// there is no spec-sanctioned fallback for a garbage mutability token.
    #[test]
    fn parse_rejects_unrecognized_playlist_type() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:3\n\
#EXT-X-TARGETDURATION:6\n\
#EXT-X-PLAYLIST-TYPE:LIVE\n\
#EXTINF:6.000,\n\
s0.m4s\n";
        let err = MediaPlaylist::parse(text).expect_err("unrecognized PLAYLIST-TYPE must error");
        assert!(matches!(err, Error::HlsParse { .. }));
    }

    /// `#EXT-X-DEFINE` with zero or more than one of NAME/IMPORT/QUERYPARAM
    /// must error (RFC 8216bis §4.4.2.3, issue #872).
    #[test]
    fn parse_rejects_define_with_wrong_attribute_count() {
        let none = "#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-DEFINE:VALUE=\"x\"\n\
#EXT-X-TARGETDURATION:6\n#EXTINF:6.000,\ns0.m4s\n";
        let err = MediaPlaylist::parse(none).expect_err("DEFINE with none of the three must error");
        assert!(matches!(err, Error::HlsParse { .. }));

        let both = "#EXTM3U\n#EXT-X-VERSION:3\n\
#EXT-X-DEFINE:NAME=\"a\",VALUE=\"1\",IMPORT=\"b\"\n\
#EXT-X-TARGETDURATION:6\n#EXTINF:6.000,\ns0.m4s\n";
        let err = MediaPlaylist::parse(both).expect_err("DEFINE with two of the three must error");
        assert!(matches!(err, Error::HlsParse { .. }));
    }

    /// `#EXT-X-SESSION-DATA` requires exactly one of VALUE/URI (issue #872).
    #[test]
    fn parse_rejects_session_data_with_wrong_content_count() {
        let neither = "#EXTM3U\n#EXT-X-SESSION-DATA:DATA-ID=\"x\"\n";
        let err = MasterPlaylist::parse(neither)
            .expect_err("SESSION-DATA with neither VALUE nor URI must error");
        assert!(matches!(err, Error::HlsParse { .. }));

        let both = "#EXTM3U\n#EXT-X-SESSION-DATA:DATA-ID=\"x\",VALUE=\"v\",URI=\"u\"\n";
        let err = MasterPlaylist::parse(both)
            .expect_err("SESSION-DATA with both VALUE and URI must error");
        assert!(matches!(err, Error::HlsParse { .. }));
    }

    /// `#EXT-X-SESSION-KEY`'s `IV` must be exactly 32 hex digits (issue #872).
    #[test]
    fn parse_rejects_malformed_session_key_iv() {
        let text = "#EXTM3U\n\
#EXT-X-SESSION-KEY:METHOD=AES-128,URI=\"k\",IV=0xnotahexvalue\n";
        let err = MasterPlaylist::parse(text).expect_err("malformed IV must error");
        assert!(matches!(err, Error::InvalidIv { value } if value == "0xnotahexvalue"));
    }

    #[test]
    fn round_trip_multivariant_playlist() {
        let pl = MasterPlaylist {
            version: 7,
            media: vec![],
            variants: vec![
                Variant {
                    bandwidth: 300_000,
                    average_bandwidth: None,
                    frame_rate: None,
                    codecs: Some("avc1.64001e,mp4a.40.2".into()),
                    resolution: Some((640, 360)),
                    uri: "v300/index.m3u8".into(),
                    ..Default::default()
                },
                Variant {
                    bandwidth: 800_000,
                    average_bandwidth: None,
                    frame_rate: None,
                    codecs: Some("avc1.640028,mp4a.40.2".into()),
                    resolution: Some((1280, 720)),
                    uri: "v800/index.m3u8".into(),
                    ..Default::default()
                },
            ],
            iframe_variants: vec![IFrameVariant {
                bandwidth: 50_000,
                average_bandwidth: None,
                codecs: Some("avc1.64001e".into()),
                resolution: Some((640, 360)),
                uri: "v300/iframe.m3u8".into(),
                extra_attrs: Vec::new(),
            }],
            ..Default::default()
        };
        let text = pl.to_m3u8().unwrap();
        let parsed = MasterPlaylist::parse(&text).expect("parse must succeed");
        assert_eq!(parsed, pl, "round trip must be lossless:\n{text}");
    }

    /// Round-trips all 6 new §4.4.2/§4.4.6 Multivariant Playlist tags
    /// together (issue #872): INDEPENDENT-SEGMENTS, START, DEFINE (NAME/
    /// VALUE + QUERYPARAM forms), SESSION-DATA (VALUE + URI/FORMAT forms),
    /// SESSION-KEY, CONTENT-STEERING.
    #[test]
    fn round_trip_multivariant_playlist_with_new_872_tags() {
        // version 11 is not arbitrary: the QUERYPARAM `EXT-X-DEFINE` below
        // triggers §8 row 11, so `computed_version()` derives 11 and
        // `to_m3u8` renders it. Setting the floor to anything lower would
        // still render 11 (issue #880's floor semantics: raised, never
        // lowered), which would then re-parse to 11 and break the identity
        // round trip below — so the floor must match the derived minimum.
        let pl = MasterPlaylist {
            version: 11,
            independent_segments: true,
            start: Some(StartPoint {
                time_offset: SignedDecimalSeconds::new(-10.5).unwrap(),
                precise: true,
                extra_attrs: Vec::new(),
            }),
            defines: vec![
                Define::Name {
                    name: "base".into(),
                    value: "https://cdn.example.com/video12".into(),
                    extra_attrs: Vec::new(),
                },
                Define::QueryParam {
                    name: "token".into(),
                    extra_attrs: Vec::new(),
                },
            ],
            session_data: vec![
                SessionData {
                    data_id: "com.example.lyrics".into(),
                    content: SessionDataContent::Uri {
                        uri: "lyrics.json".into(),
                        format: SessionDataFormat::Json,
                    },
                    language: None,
                    extra_attrs: Vec::new(),
                },
                SessionData {
                    data_id: "com.example.title".into(),
                    content: SessionDataContent::Value("This is an example".into()),
                    language: Some("en".into()),
                    extra_attrs: Vec::new(),
                },
            ],
            session_keys: vec![
                SessionKey {
                    method: EncryptionMethod::Aes128,
                    uri: Some("https://priv.example.com/key.php?r=52".into()),
                    iv: None,
                    keyformat: Some("identity".into()),
                    keyformatversions: Some("1".into()),
                    extra_attrs: Vec::new(),
                },
                SessionKey {
                    method: EncryptionMethod::SampleAesCtr,
                    uri: Some("skd://key2".into()),
                    iv: Some([
                        0x9c, 0x7d, 0xb8, 0x77, 0x85, 0x70, 0xd0, 0x5c, 0x3a, 0x5e, 0x3d, 0x2c,
                        0x8a, 0xe5, 0x5e, 0x46,
                    ]),
                    keyformat: None,
                    keyformatversions: None,
                    extra_attrs: Vec::new(),
                },
            ],
            content_steering: Some(ContentSteering {
                server_uri: "/steering?video=00012".into(),
                pathway_id: Some("CDN-A".into()),
                extra_attrs: Vec::new(),
            }),
            media: vec![],
            variants: vec![Variant {
                bandwidth: 1_280_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.64001e,mp4a.40.2".into()),
                resolution: Some((640, 360)),
                uri: "low/index.m3u8".into(),
                audio: None,
                video: None,
                subtitles: None,
                closed_captions: None,
                extra_attrs: Vec::new(),
            }],
            iframe_variants: vec![],
            extra_tags: vec![],
        };
        assert_eq!(
            pl.computed_version(),
            Some(11),
            "EXT-X-DEFINE with QUERYPARAM must derive §8 row 11 from the \
             typed `defines` field (issue #872 + #880 integration)"
        );
        let text = pl.to_m3u8().unwrap();
        assert!(text.contains("#EXT-X-INDEPENDENT-SEGMENTS\n"));
        assert!(text.contains("#EXT-X-START:TIME-OFFSET=-10.5,PRECISE=YES\n"));
        assert!(
            text.contains(
                "#EXT-X-DEFINE:NAME=\"base\",VALUE=\"https://cdn.example.com/video12\"\n"
            )
        );
        assert!(text.contains("#EXT-X-DEFINE:QUERYPARAM=\"token\"\n"));
        assert!(
            text.contains(
                "#EXT-X-SESSION-DATA:DATA-ID=\"com.example.lyrics\",URI=\"lyrics.json\"\n"
            )
        );
        assert!(text.contains(
            "#EXT-X-SESSION-KEY:METHOD=SAMPLE-AES-CTR,URI=\"skd://key2\",IV=0x9c7db8778570d05c3a5e3d2c8ae55e46\n"
        ));
        assert!(text.contains(
            "#EXT-X-CONTENT-STEERING:SERVER-URI=\"/steering?video=00012\",PATHWAY-ID=\"CDN-A\"\n"
        ));
        let parsed = MasterPlaylist::parse(&text).expect("parse must succeed");
        assert_eq!(parsed, pl, "round trip must be lossless:\n{text}");
    }

    /// Real-world sample: RFC 8216bis §9.11 "Low-Latency Playlist" appendix
    /// example, verbatim for the segment/part/discontinuity/preload-hint/
    /// rendition-report lines (only the elided `...` header lines were filled
    /// in with plausible values, since the spec elides them for brevity).
    #[test]
    fn real_world_sample_ll_playlist_from_rfc8216bis_appendix() {
        let text = "\
#EXTM3U
#EXT-X-VERSION:9
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:266
#EXT-X-PART-INF:PART-TARGET=2.00002
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=6.00006
#EXTINF:4.00008,
fileSequence268.mp4
#EXTINF:4.00008,
fileSequence269.mp4
#EXTINF:4.00008,
fileSequence270.mp4
#EXT-X-PART:DURATION=2.00004,INDEPENDENT=YES,URI=\"filePart271.0.mp4\"
#EXT-X-PART:DURATION=2.00004,URI=\"filePart271.1.mp4\"
#EXTINF:4.00008,
fileSequence271.mp4
#EXT-X-PART:DURATION=2.00004,INDEPENDENT=YES,URI=\"filePart272.0.mp4\"
#EXT-X-PART:DURATION=0.50001,URI=\"filePart272.1.mp4\"
#EXTINF:2.50005,
fileSequence272.mp4
#EXT-X-DISCONTINUITY
#EXT-X-PART:DURATION=2.00004,INDEPENDENT=YES,URI=\"midRoll273.0.mp4\"
#EXT-X-PART:DURATION=2.00004,URI=\"midRoll273.1.mp4\"
#EXTINF:4.00008,
midRoll273.mp4
#EXT-X-PART:DURATION=2.00004,INDEPENDENT=YES,URI=\"midRoll274.0.mp4\"
#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"midRoll274.1.mp4\"
#EXT-X-RENDITION-REPORT:URI=\"/1M/LL-HLS.m3u8\",LAST-MSN=274,LAST-PART=1
";
        let pl = MediaPlaylist::parse(text).expect("real-world LL sample must parse");
        assert_eq!(pl.version, 9);
        assert_eq!(pl.target_duration, 4);
        assert_eq!(pl.media_sequence, 266);
        // 5 closed segments: 268, 269, 270, 271, 272 + the discontinuous
        // midRoll273 = 6; midRoll274 has parts but never closes with an
        // EXTINF/URI, so it becomes the open (in-progress) segment.
        assert_eq!(pl.segments.len(), 6, "{:?}", pl.segments);
        assert_eq!(pl.segments[4].uri, "fileSequence272.mp4");
        assert_eq!(pl.segments[4].parts.len(), 2);
        assert!(pl.segments[4].parts[0].independent);
        assert!(!pl.segments[4].parts[1].independent);
        assert_eq!(pl.segments[5].uri, "midRoll273.mp4");
        assert!(
            pl.segments[5].discontinuous,
            "midRoll273 follows #EXT-X-DISCONTINUITY"
        );
        let open = pl.open_segment.as_ref().expect("midRoll274 is open");
        assert_eq!(open.parts.len(), 1);
        assert_eq!(open.parts[0].uri, "midRoll274.0.mp4");
        let ll = pl.low_latency.as_ref().expect("LL config must be present");
        assert_eq!(ll.preload_hint_part.as_deref(), Some("midRoll274.1.mp4"));
        assert!(
            ll.can_block_reload,
            "CAN-BLOCK-RELOAD=YES in the fixture must parse to true"
        );
        assert_eq!(pl.rendition_reports.len(), 1);
        assert_eq!(pl.rendition_reports[0].uri, "/1M/LL-HLS.m3u8");
        assert_eq!(pl.rendition_reports[0].last_msn, 274);
        assert_eq!(pl.rendition_reports[0].last_part, Some(1));
    }

    /// Real-world-shaped sample: a Playlist Delta Update (`#EXT-X-SKIP`),
    /// hand-written per RFC 8216bis §4.4.5.2's confirmed attribute grammar
    /// (no full numeric example is given in the spec appendix for this tag).
    #[test]
    fn real_world_sample_delta_update_with_skip() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:9\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-MEDIA-SEQUENCE:1000\n\
#EXT-X-PART-INF:PART-TARGET=0.5\n\
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,CAN-SKIP-UNTIL=24.0,PART-HOLD-BACK=1.5\n\
#EXT-X-SKIP:SKIPPED-SEGMENTS=996,RECENTLY-REMOVED-DATERANGES=\"ad-1\tad-2\"\n\
#EXTINF:4.00000,\n\
fileSequence1996.mp4\n\
#EXTINF:4.00000,\n\
fileSequence1997.mp4\n";
        let pl = MediaPlaylist::parse(text).expect("delta update sample must parse");
        assert_eq!(pl.media_sequence, 1000);
        assert_eq!(pl.segments.len(), 2);
        assert_eq!(pl.segments[0].uri, "fileSequence1996.mp4");
        let skip = pl.skip.as_ref().expect("EXT-X-SKIP must be captured");
        assert_eq!(skip.skipped_segments, 996);
        assert_eq!(skip.recently_removed_daterange_ids, vec!["ad-1", "ad-2"]);
        let ll = pl.low_latency.as_ref().expect("LL config must be present");
        assert_eq!(ll.can_skip_until, Some(DecimalSeconds::new(24.0).unwrap()));
        assert!(!pl.endlist);
    }

    /// Audit T12: a RECENTLY-REMOVED-DATERANGES id with `"`, CR, LF or the
    /// tab separator must be rejected, not injected into the tag line.
    #[test]
    fn skip_recently_removed_ids_reject_injection() {
        let text = "#EXTM3U\n#EXT-X-VERSION:10\n#EXT-X-TARGETDURATION:4\n#EXT-X-MEDIA-SEQUENCE:0\n\
#EXT-X-SKIP:SKIPPED-SEGMENTS=3,RECENTLY-REMOVED-DATERANGES=\"ad-1\\tad-2\"\n\
#EXTINF:4,\na.mp4\n"
            .replace("\\t", "\t");
        let good = MediaPlaylist::parse(&text).unwrap();
        // multi-id list round-trips byte-exact
        assert_eq!(good.to_m3u8().unwrap(), text);
        for bad in ["a\"b", "a\rb", "a\nb", "a\tb"] {
            let mut pl = good.clone();
            pl.skip.as_mut().unwrap().recently_removed_daterange_ids = vec![bad.to_string()];
            assert!(
                matches!(pl.to_m3u8(), Err(Error::InvalidQuotedString { .. })),
                "{bad:?}"
            );
        }
    }

    /// Issue #717 slice 1 fix: an origin that advertises LL-HLS tags but
    /// explicitly declines blocking reload (`CAN-BLOCK-RELOAD=NO`) must
    /// parse to `can_block_reload == false` — a client inferring support
    /// from `low_latency.is_some()` alone would get this wrong.
    #[test]
    fn real_world_sample_can_block_reload_no_is_parsed_not_inferred() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:9\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-MEDIA-SEQUENCE:0\n\
#EXT-X-PART-INF:PART-TARGET=0.5\n\
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=NO,PART-HOLD-BACK=1.5\n\
#EXTINF:4.00000,\n\
seg0.mp4\n";
        let pl = MediaPlaylist::parse(text).expect("must parse");
        let ll = pl
            .low_latency
            .as_ref()
            .expect("LL config must be present (PART-INF seen)");
        assert!(
            !ll.can_block_reload,
            "CAN-BLOCK-RELOAD=NO must not be inferred as true just because low_latency is Some"
        );
    }

    /// RFC 8216bis §4.4.3.8: an absent `CAN-BLOCK-RELOAD` attribute (or an
    /// entirely absent `#EXT-X-SERVER-CONTROL` tag) means the server does
    /// NOT support blocking reload — default `false`, distinct from
    /// [`LowLatencyConfig::default()`]'s convenience value of `true`.
    #[test]
    fn parse_defaults_can_block_reload_false_when_attribute_absent() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:9\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-MEDIA-SEQUENCE:0\n\
#EXT-X-PART-INF:PART-TARGET=0.5\n\
#EXTINF:4.00000,\n\
seg0.mp4\n";
        let pl = MediaPlaylist::parse(text).expect("must parse");
        let ll = pl
            .low_latency
            .as_ref()
            .expect("LL config must be present (PART-INF seen)");
        assert!(
            !ll.can_block_reload,
            "absent CAN-BLOCK-RELOAD/SERVER-CONTROL must default to false, not true"
        );
    }

    /// Round trip a `CAN-BLOCK-RELOAD=NO` config through `to_m3u8`/`parse`
    /// to prove the renderer emits the actual value (not a hardcoded YES).
    #[test]
    fn round_trip_can_block_reload_no() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: vec![MediaSegment {
                uri: "seg0.mp4".into(),
                duration: DecimalSeconds::new(4.0).unwrap(),
                ..Default::default()
            }],
            low_latency: Some(LowLatencyConfig {
                part_target: Some(DecimalSeconds::new(0.5).unwrap()),
                part_hold_back: Some(DecimalSeconds::new(1.5).unwrap()),
                can_block_reload: false,
                ..Default::default()
            }),
            ..Default::default()
        };
        let text = pl.to_m3u8().unwrap();
        assert!(
            text.contains("CAN-BLOCK-RELOAD=NO"),
            "renderer must emit the actual value:\n{text}"
        );
        let parsed = MediaPlaylist::parse(&text).expect("parse must succeed");
        assert_eq!(parsed, pl, "round trip must be lossless:\n{text}");
    }

    #[test]
    fn parse_ignores_unrecognized_tag_by_preserving_it_into_extra_tags() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:3\n\
#EXT-X-TARGETDURATION:6\n\
#EXT-X-MEDIA-SEQUENCE:0\n\
#EXT-X-PROGRAM-DATE-TIME:2024-01-01T00:00:00.000Z\n\
#EXTINF:6.000,\n\
s0.m4s\n\
#EXT-X-ENDLIST\n";
        let pl = MediaPlaylist::parse(text).expect("unrecognized tag must not error");
        // Audit BH-W5: `#EXT-X-PROGRAM-DATE-TIME` is segment-defining, so it
        // is preserved verbatim on the *following* segment's `pre_tags`
        // rather than the playlist-level block.
        assert!(
            pl.segments
                .first()
                .is_some_and(|s| s.program_date_time.is_some()),
            "EXT-X-PROGRAM-DATE-TIME must be preserved as a typed field, not dropped: {:?}",
            pl.segments.first().map(|s| s.program_date_time)
        );
    }

    #[test]
    fn parse_rejects_missing_targetduration() {
        let text = "#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:0\n#EXTINF:6.000,\ns0.m4s\n";
        let err = MediaPlaylist::parse(text).expect_err("missing TARGETDURATION must error");
        assert!(matches!(err, Error::HlsParse { .. }));
    }

    #[test]
    fn parse_rejects_malformed_part_missing_duration() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:9\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-PART-INF:PART-TARGET=0.5\n\
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=1.5\n\
#EXT-X-PART:URI=\"part.m4s\"\n\
#EXTINF:4.000,\n\
seg.m4s\n";
        let err = MediaPlaylist::parse(text).expect_err("EXT-X-PART without DURATION must error");
        let Error::HlsParse { reason, .. } = err else {
            panic!("expected Error::HlsParse, got {err:?}")
        };
        assert!(reason.contains("DURATION"), "{reason}");
    }

    #[test]
    fn parse_rejects_variant_uri_with_no_preceding_stream_inf() {
        let text = "#EXTM3U\n#EXT-X-VERSION:6\nv300/index.m3u8\n";
        let err = MasterPlaylist::parse(text).expect_err("orphan variant URI must error");
        assert!(matches!(err, Error::HlsParse { .. }));
    }

    #[test]
    fn parse_master_playlist_models_ext_x_media() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:7\n\
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aac\",NAME=\"English\",DEFAULT=YES,AUTOSELECT=YES,URI=\"eng.m3u8\"\n\
#EXT-X-STREAM-INF:BANDWIDTH=300000,CODECS=\"avc1.64001e,mp4a.40.2\",AUDIO=\"aac\"\n\
v300/index.m3u8\n";
        let pl = MasterPlaylist::parse(text).expect("EXT-X-MEDIA must parse");
        assert_eq!(pl.variants.len(), 1);
        assert_eq!(pl.media.len(), 1);
        assert_eq!(pl.media[0].name, "English");
    }

    // -----------------------------------------------------------------------
    // Protocol version derivation (RFC 8216bis §8, issue #871) — table-driven
    // per docs/version-compatibility.md, plus the five named regression
    // cases from that issue.
    // -----------------------------------------------------------------------

    /// A minimal, otherwise-untriggering Media Playlist: integer-second
    /// duration, no map/byte-range/iframes-only/skip/extra_tags. Every
    /// table-driven test starts here and flips exactly one trigger.
    fn base_media_playlist() -> MediaPlaylist {
        MediaPlaylist {
            version: 0,
            target_duration: 6,
            media_sequence: 0,
            segments: vec![seg("s0.m4s", 6.0)],
            endlist: true,
            ..Default::default()
        }
    }

    /// Extract the `#EXT-X-VERSION:<n>` value from rendered text, or `None`
    /// if no such line is present.
    fn rendered_version(m3u8: &str) -> Option<u8> {
        m3u8.lines()
            .find_map(|l| l.strip_prefix("#EXT-X-VERSION:"))
            .map(|v| v.parse::<u8>().expect("version must be a valid u8"))
    }

    #[test]
    fn version_row1_no_trigger_omits_the_tag() {
        let out = base_media_playlist().to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), None, "no trigger:\n{out}");
    }

    #[test]
    fn version_row2_key_iv_triggers_v2() {
        let mut pl = base_media_playlist();
        pl.extra_tags = vec![
            "#EXT-X-KEY:METHOD=AES-128,URI=\"https://k\",IV=0x00000000000000000000000000000001"
                .into(),
        ];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(2), "{out}");
    }

    #[test]
    fn version_row3_float_extinf_triggers_v3() {
        let mut pl = base_media_playlist();
        pl.segments = vec![seg("s0.m4s", 6.5)];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(3), "{out}");
    }

    #[test]
    fn version_row4_byterange_triggers_v4() {
        let mut pl = base_media_playlist();
        pl.segments[0].byte_range = Some(ByteRange {
            length: 1000,
            offset: Some(0),
        });
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(4), "{out}");
    }

    #[test]
    fn version_row4_iframes_only_triggers_v4() {
        let mut pl = base_media_playlist();
        pl.iframes_only = true;
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(4), "{out}");
    }

    #[test]
    fn version_row5_sample_aes_triggers_v5() {
        let mut pl = base_media_playlist();
        pl.extra_tags = vec!["#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"https://k\",KEYID=0x01".into()];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(5), "{out}");
    }

    #[test]
    fn version_row5_keyformat_triggers_v5() {
        let mut pl = base_media_playlist();
        pl.extra_tags = vec![
            "#EXT-X-KEY:METHOD=AES-128,URI=\"https://k\",KEYFORMAT=\"com.example\",\
             KEYFORMATVERSIONS=\"1\""
                .into(),
        ];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(5), "{out}");
    }

    #[test]
    fn version_row5_map_with_iframes_only_triggers_v5_not_v6() {
        let mut pl = base_media_playlist();
        pl.iframes_only = true;
        pl.segments[0].map = Some(MapTag {
            uri: "init.mp4".into(),
            byte_range: None,
            extra_attrs: Vec::new(),
        });
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(5), "{out}");
    }

    #[test]
    fn version_row6_map_without_iframes_only_triggers_v6() {
        let mut pl = base_media_playlist();
        pl.segments[0].map = Some(MapTag {
            uri: "init.mp4".into(),
            byte_range: None,
            extra_attrs: Vec::new(),
        });
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(6), "{out}");
    }

    #[test]
    fn version_row7_media_service_instream_id_triggers_v7_multivariant_only() {
        let mut pl = MasterPlaylist {
            version: 0,
            media: vec![],
            variants: vec![Variant {
                bandwidth: 300_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.64001e".into()),
                resolution: None,
                uri: "v300/index.m3u8".into(),
                audio: None,
                video: None,
                subtitles: None,
                closed_captions: None,
                extra_attrs: Vec::new(),
            }],
            iframe_variants: vec![],
            extra_tags: vec![],
            ..Default::default()
        };
        pl.extra_tags = vec![
            "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS,GROUP-ID=\"cc\",NAME=\"CC1\",\
             INSTREAM-ID=\"SERVICE1\""
                .into(),
        ];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(7), "{out}");
    }

    #[test]
    fn version_row8_variable_substitution_triggers_v8() {
        let mut pl = base_media_playlist();
        pl.segments = vec![seg("seg-{$id}.m4s", 6.0)];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(8), "{out}");
    }

    #[test]
    fn version_row8_variable_substitution_triggers_v8_multivariant() {
        let pl = MasterPlaylist {
            version: 0,
            media: vec![],
            variants: vec![Variant {
                bandwidth: 300_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.64001e".into()),
                resolution: None,
                uri: "{$base}/index.m3u8".into(),
                audio: None,
                video: None,
                subtitles: None,
                closed_captions: None,
                extra_attrs: Vec::new(),
            }],
            iframe_variants: vec![],
            extra_tags: vec![],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(8), "{out}");
    }

    #[test]
    fn version_row9_skip_triggers_v9() {
        let mut pl = base_media_playlist();
        pl.skip = Some(SkipInfo {
            skipped_segments: 5,
            recently_removed_daterange_ids: vec![],
            ..Default::default()
        });
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(9), "{out}");
    }

    #[test]
    fn version_row10_skip_replacing_daterange_triggers_v10() {
        let mut pl = base_media_playlist();
        pl.skip = Some(SkipInfo {
            skipped_segments: 5,
            recently_removed_daterange_ids: vec!["ad-1".into()],
            ..Default::default()
        });
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(10), "{out}");
    }

    #[test]
    fn version_row11_define_queryparam_triggers_v11() {
        let mut pl = base_media_playlist();
        pl.extra_tags = vec!["#EXT-X-DEFINE:QUERYPARAM=\"auth\"".into()];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(11), "{out}");
    }

    #[test]
    fn version_row11_define_queryparam_triggers_v11_multivariant() {
        let pl = MasterPlaylist {
            version: 0,
            media: vec![],
            variants: vec![Variant {
                bandwidth: 300_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.64001e".into()),
                resolution: None,
                uri: "v300/index.m3u8".into(),
                ..Default::default()
            }],
            iframe_variants: vec![],
            extra_tags: vec!["#EXT-X-DEFINE:QUERYPARAM=\"auth\"".into()],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(11), "{out}");
    }

    #[test]
    fn version_row12_req_attribute_triggers_v12() {
        let mut pl = base_media_playlist();
        pl.extra_tags = vec!["#EXT-X-FUTURE-FEATURE:REQ-CODEC=\"av01\"".into()];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(12), "{out}");
    }

    /// Audit BH-W8 (issue #1111): the §8 row-12 `REQ-` scan must see the
    /// per-tag `SC`/`PI`/`PH` attribute lists, not a separate playlist-wide
    /// union that the renderer never read. A config built directly with a
    /// `REQ-` attribute in `sc_extra_attrs` used to render that attribute
    /// while leaving `EXT-X-VERSION` at 11 — an under-declaration the §8
    /// rule forbids (and the before/after difference is exactly this test:
    /// with the duplicate field present the scan missed it).
    #[test]
    fn version_row12_req_attribute_in_per_tag_lists_triggers_v12() {
        let mut pl = base_media_playlist();
        pl.low_latency = Some(LowLatencyConfig {
            sc_extra_attrs: vec![(
                "REQ-LATENCY".to_string(),
                AttrValue::bare("ultra-low").unwrap(),
            )],
            ..Default::default()
        });
        let out = pl.to_m3u8().unwrap();
        assert!(out.contains("REQ-LATENCY=ultra-low"), "{out}");
        assert_eq!(rendered_version(&out), Some(12), "{out}");

        // Same for PART-INF and PRELOAD-HINT.
        for (list, name) in [("pi", "REQ-VIDEO"), ("ph", "REQ-INFO")] {
            let mut pl = base_media_playlist();
            let attr = vec![(name.to_string(), AttrValue::bare("1").unwrap())];
            let mut ll = LowLatencyConfig::default();
            match list {
                "pi" => ll.pi_extra_attrs = attr,
                _ => ll.ph_extra_attrs = attr,
            }
            pl.low_latency = Some(ll);
            let out = pl.to_m3u8().unwrap();
            assert_eq!(rendered_version(&out), Some(12), "{list}: {out}");
        }
    }

    #[test]
    fn version_row12_req_attribute_triggers_v12_multivariant() {
        let pl = MasterPlaylist {
            version: 0,
            media: vec![],
            variants: vec![Variant {
                bandwidth: 300_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.64001e".into()),
                resolution: None,
                uri: "v300/index.m3u8".into(),
                ..Default::default()
            }],
            iframe_variants: vec![],
            extra_tags: vec!["#EXT-X-FUTURE-FEATURE:REQ-CODEC=\"av01\"".into()],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(12), "{out}");
    }

    #[test]
    fn version_row13_media_instream_id_non_cc_triggers_v13_multivariant_only() {
        let pl = MasterPlaylist {
            version: 0,
            media: vec![],
            variants: vec![Variant {
                bandwidth: 300_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.64001e".into()),
                resolution: None,
                uri: "v300/index.m3u8".into(),
                ..Default::default()
            }],
            iframe_variants: vec![],
            extra_tags: vec![
                "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aud\",NAME=\"Eng\",INSTREAM-ID=\"CC1\"".into(),
            ],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(13), "{out}");
    }

    #[test]
    fn version_multivariant_no_trigger_omits_the_tag() {
        let pl = MasterPlaylist {
            version: 0,
            media: vec![],
            variants: vec![Variant {
                bandwidth: 300_000,
                average_bandwidth: None,
                frame_rate: None,
                codecs: Some("avc1.64001e".into()),
                resolution: None,
                uri: "v300/index.m3u8".into(),
                ..Default::default()
            }],
            iframe_variants: vec![],
            extra_tags: vec![],
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), None, "{out}");
    }

    // --- The five named regression cases from issue #871 ---

    /// Case 1: the specific regression this issue exists for. Shaped like
    /// `hls-runtime`'s actual LL-HLS media playlist (fMP4 segments, an
    /// `EXT-X-MAP` conveyed via `extra_tags` exactly as that origin emits
    /// it, `low_latency` config, no `EXT-X-I-FRAMES-ONLY`, no `EXT-X-SKIP`)
    /// — must render **6**, never the old hardcoded **9**.
    #[test]
    fn named_case_1_fmp4_low_latency_renders_6_not_9() {
        let pl = MediaPlaylist {
            version: 0, // hls-runtime no longer supplies an explicit floor.
            target_duration: 4,
            media_sequence: 100,
            segments: vec![MediaSegment {
                uri: "seg-1-100.m4s".into(),
                duration: DecimalSeconds::new(4.0).unwrap(),
                ..Default::default()
            }],
            open_segment: Some(OpenSegment::new(vec![PartSpec {
                uri: "part-1-101.0.m4s".into(),
                duration: DecimalSeconds::new(0.5).unwrap(),
                independent: true,
                ..Default::default()
            }])),
            extra_tags: vec!["#EXT-X-MAP:URI=\"init-1.mp4\"".into()],
            low_latency: Some(LowLatencyConfig {
                part_target: Some(DecimalSeconds::new(0.5).unwrap()),
                part_hold_back: Some(DecimalSeconds::new(1.5).unwrap()),
                ..Default::default()
            }),
            iframes_only: false,
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert_eq!(
            rendered_version(&out),
            Some(6),
            "fMP4 + low-latency must render 6, not the old hardcoded 9:\n{out}"
        );
        assert!(!out.contains("#EXT-X-VERSION:9"), "{out}");
    }

    /// Case 2: a classic MPEG-TS playlist (no fMP4/LL features at all) whose
    /// segment durations are genuine floating-point values renders **3**.
    #[test]
    fn named_case_2_classic_mpegts_float_extinf_renders_3() {
        let pl = MediaPlaylist {
            version: 0,
            target_duration: 10,
            media_sequence: 0,
            segments: vec![
                seg("seg0.ts", 9.009),
                seg("seg1.ts", 9.009),
                seg("seg2.ts", 3.003),
            ],
            endlist: true,
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(3), "{out}");
    }

    /// Case 3: adding `EXT-X-SKIP` to an otherwise-untriggering playlist
    /// raises the rendered version to **9** automatically.
    #[test]
    fn named_case_3_adding_skip_raises_version_to_9() {
        let mut pl = base_media_playlist();
        assert_eq!(
            rendered_version(&pl.to_m3u8().unwrap()),
            None,
            "sanity: no trigger before adding EXT-X-SKIP"
        );
        pl.skip = Some(SkipInfo {
            skipped_segments: 3,
            recently_removed_daterange_ids: vec![],
            ..Default::default()
        });
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(9), "{out}");
    }

    /// Case 4: a playlist triggering nothing renders NO `EXT-X-VERSION` tag
    /// at all (RFC 8216bis §8's opening rule).
    #[test]
    fn named_case_4_no_trigger_renders_no_version_tag() {
        let out = base_media_playlist().to_m3u8().unwrap();
        assert!(!out.contains("#EXT-X-VERSION"), "{out}");
    }

    /// Case 5: `SAMPLE-AES` (the CBCS CENC key tag this crate's own
    /// `cenc_ext_x_key` produces) renders **5**.
    #[test]
    fn named_case_5_sample_aes_renders_5() {
        let tag = cenc_ext_x_key(CencScheme::Cbcs, &[0xab; 16], "https://k.example/key")
            .expect("valid key_uri")
            .expect("cbcs must emit an EXT-X-KEY tag");
        let mut pl = base_media_playlist();
        pl.extra_tags = vec![tag];
        let out = pl.to_m3u8().unwrap();
        assert_eq!(rendered_version(&out), Some(5), "{out}");
    }

    // --- F1 + F4: HOLD-BACK and CAN-SKIP-DATERANGES attribute coverage ---

    /// RFC 8216bis §4.4.3.8: `CAN-SKIP-DATERANGES=YES` with `CAN-SKIP-UNTIL`
    /// must survive parse -> serialize -> re-parse losslessly.
    #[test]
    fn parse_and_round_trip_can_skip_dateranges_yes() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:9\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-PART-INF:PART-TARGET=0.5\n\
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=1.5,CAN-SKIP-UNTIL=24.0,CAN-SKIP-DATERANGES=YES\n\
#EXTINF:4.000,\n\
seg0.m4s\n";
        let pl = MediaPlaylist::parse(text).expect("parse must succeed");
        let ll = pl.low_latency.as_ref().expect("must have low_latency");
        assert!(
            ll.can_skip_dateranges,
            "CAN-SKIP-DATERANGES=YES must parse to true"
        );
        let round = pl.to_m3u8().unwrap();
        assert!(
            round.contains("CAN-SKIP-DATERANGES=YES"),
            "render must emit CAN-SKIP-DATERANGES=YES:\n{round}"
        );
        let reparse = MediaPlaylist::parse(&round).expect("reparse must succeed");
        let re_ll = reparse
            .low_latency
            .as_ref()
            .expect("must have low_latency on reparse");
        assert!(
            re_ll.can_skip_dateranges,
            "CAN-SKIP-DATERANGES=YES must survive round trip"
        );
    }

    /// RFC 8216bis §4.4.3.8: `CAN-SKIP-DATERANGES` suppressed when
    /// `CAN-SKIP-UNTIL` is absent (REQUIRES relationship).
    #[test]
    fn can_skip_dateranges_not_rendered_without_can_skip_until() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            segments: vec![],
            low_latency: Some(LowLatencyConfig {
                part_target: Some(DecimalSeconds::new(0.5).unwrap()),
                part_hold_back: Some(DecimalSeconds::new(1.5).unwrap()),
                can_skip_until: None,
                can_skip_dateranges: true,
                can_block_reload: true,
                ..Default::default()
            }),
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(
            !out.contains("CAN-SKIP-DATERANGES"),
            "CAN-SKIP-DATERANGES must NOT render without CAN-SKIP-UNTIL:\n{out}"
        );
    }

    /// RFC 8216bis §4.4.3.8: `HOLD-BACK` attribute survives parse ->
    /// serialize -> re-parse losslessly.
    #[test]
    fn parse_and_round_trip_hold_back() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:9\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-PART-INF:PART-TARGET=0.5\n\
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=1.5,HOLD-BACK=12.0\n\
#EXTINF:4.000,\n\
seg0.m4s\n";
        let pl = MediaPlaylist::parse(text).expect("parse must succeed");
        let ll = pl.low_latency.as_ref().expect("must have low_latency");
        assert_eq!(
            ll.hold_back,
            Some(DecimalSeconds::new(12.0).unwrap()),
            "HOLD-BACK=12.0 must parse"
        );
        let round = pl.to_m3u8().unwrap();
        // format_secs renders 12.0 as "12" (no trailing zero).
        assert!(
            round.contains("HOLD-BACK=12"),
            "render must emit HOLD-BACK=12:\n{round}"
        );
        let reparse = MediaPlaylist::parse(&round).expect("reparse must succeed");
        let re_ll = reparse
            .low_latency
            .as_ref()
            .expect("must have low_latency on reparse");
        assert_eq!(
            re_ll.hold_back,
            Some(DecimalSeconds::new(12.0).unwrap()),
            "HOLD-BACK must survive round trip"
        );
    }

    /// `HOLD-BACK` omitted when `None` (spec default: 3× Target Duration).
    #[test]
    fn hold_back_omitted_when_none() {
        let pl = MediaPlaylist {
            version: 9,
            target_duration: 4,
            media_sequence: 0,
            segments: vec![MediaSegment {
                uri: "seg0.m4s".into(),
                duration: DecimalSeconds::new(4.0).unwrap(),
                ..Default::default()
            }],
            low_latency: Some(LowLatencyConfig {
                part_target: Some(DecimalSeconds::new(0.5).unwrap()),
                part_hold_back: Some(DecimalSeconds::new(1.5).unwrap()),
                hold_back: None,
                can_block_reload: true,
                ..Default::default()
            }),
            ..Default::default()
        };
        let out = pl.to_m3u8().unwrap();
        assert!(
            !out.contains(",HOLD-BACK="),
            "HOLD-BACK must be absent when None:\n{out}"
        );
    }

    // --- F3: EXT-X-SESSION-KEY METHOD=NONE rejection ---

    /// RFC 8216bis §4.4.6.5: `EXT-X-SESSION-KEY` MUST NOT have a METHOD of
    /// NONE. Parsing a playlist with `METHOD=NONE` must error.
    #[test]
    fn session_key_method_none_is_rejected() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:6\n\
#EXT-X-STREAM-INF:BANDWIDTH=5000000\n\
v300/index.m3u8\n\
#EXT-X-SESSION-KEY:METHOD=NONE,URI=\"https://k.example/key\"\n";
        let err = MasterPlaylist::parse(text)
            .expect_err("EXT-X-SESSION-KEY with METHOD=NONE must be rejected");
        let Error::HlsParse { reason, .. } = err else {
            panic!("expected Error::HlsParse, got {err:?}")
        };
        assert!(reason.contains("NONE"), "error must mention NONE: {reason}");
    }

    /// `EXT-X-SESSION-KEY` with a real method (AES-128) is accepted and
    /// round-trips.
    #[test]
    fn session_key_real_method_is_accepted_and_round_trips() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:6\n\
#EXT-X-STREAM-INF:BANDWIDTH=5000000\n\
v300/index.m3u8\n\
#EXT-X-SESSION-KEY:METHOD=AES-128,URI=\"https://k.example/key\"\n";
        let pl = MasterPlaylist::parse(text).expect("legitimate session key must parse");
        assert_eq!(pl.session_keys.len(), 1);
        assert_eq!(pl.session_keys[0].method, EncryptionMethod::Aes128);
        let round = pl.to_m3u8().unwrap();
        let reparse = MasterPlaylist::parse(&round).expect("reparse must succeed");
        assert_eq!(reparse.session_keys.len(), 1);
        assert_eq!(reparse.session_keys[0].method, EncryptionMethod::Aes128);
    }

    /// Interaction test (rebase #893 + #894): EXT-X-SERVER-CONTROL with
    /// typed attributes (HOLD-BACK, CAN-SKIP-DATERANGES) plus a REQ-
    /// attribute must round-trip all three and compute version 12
    /// (RFC 8216bis §8 row 12 + §4.4.3.8). The REQ- attribute must
    /// survive in `sc_extra_attrs`/`extra_attrs` and not be swallowed
    /// by the typed field parser.
    #[test]
    fn server_control_typed_and_req_attrs_round_trip_and_version_12() {
        let text = "#EXTM3U\n\
#EXT-X-VERSION:12\n\
#EXT-X-TARGETDURATION:4\n\
#EXT-X-PART-INF:PART-TARGET=0.5,REQ-VIDEO=720p\n\
#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=1.5,HOLD-BACK=12.0,CAN-SKIP-UNTIL=24.0,CAN-SKIP-DATERANGES=YES,REQ-LATENCY=ultra-low\n\
#EXTINF:4,\n\
seg0.m4s\n";
        let pl = MediaPlaylist::parse(text).expect("parse must succeed");
        let ll = pl.low_latency.as_ref().expect("must have low_latency");

        // Typed attributes survive.
        assert_eq!(ll.hold_back, Some(DecimalSeconds::new(12.0).unwrap()));
        assert!(ll.can_skip_dateranges);

        // REQ-VIDEO from PART-INF → pi_extra_attrs.
        assert!(
            ll.pi_extra_attrs
                .iter()
                .any(|(k, v)| k == "REQ-VIDEO" && v.as_str() == "720p"),
            "REQ-VIDEO must survive in pi_extra_attrs"
        );

        // REQ-LATENCY from SERVER-CONTROL → sc_extra_attrs.
        assert!(
            ll.sc_extra_attrs
                .iter()
                .any(|(k, v)| k == "REQ-LATENCY" && v.as_str() == "ultra-low"),
            "REQ-LATENCY must survive in sc_extra_attrs"
        );

        // Each tag's own list keeps its own unmodeled attributes.
        assert!(ll.pi_extra_attrs.iter().any(|(k, _)| k == "REQ-VIDEO"));
        assert!(ll.sc_extra_attrs.iter().any(|(k, _)| k == "REQ-LATENCY"));

        // Version must be 12.
        let round = pl.to_m3u8().unwrap();
        assert!(
            round.contains("#EXT-X-VERSION:12"),
            "must emit version 12:\n{round}"
        );

        // Round-trip lossless.
        let reparse = MediaPlaylist::parse(&round).expect("reparse must succeed");
        let re_ll = reparse
            .low_latency
            .as_ref()
            .expect("must have low_latency on reparse");
        assert_eq!(re_ll.hold_back, Some(DecimalSeconds::new(12.0).unwrap()));
        assert!(re_ll.can_skip_dateranges);
        assert!(re_ll.sc_extra_attrs.iter().any(|(k, _)| k == "REQ-LATENCY"));
        assert!(re_ll.pi_extra_attrs.iter().any(|(k, _)| k == "REQ-VIDEO"));
    }

    // --- #958 overflow-rejection tests ---

    #[test]
    fn byterange_offset_plus_length_overflow_rejected() {
        let input = "#EXTM3U\n\
                      #EXT-X-TARGETDURATION:10\n\
                      #EXTINF:10,\n\
                      #EXT-X-BYTERANGE:1@18446744073709551615\n\
                      seg0.ts\n";
        let err = MediaPlaylist::parse(input).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("overflows"), "expected overflow error: {msg}");
    }

    #[test]
    fn byterange_exact_max_accepted() {
        let input = "#EXTM3U\n\
                      #EXT-X-TARGETDURATION:10\n\
                      #EXTINF:10,\n\
                      #EXT-X-BYTERANGE:1@18446744073709551614\n\
                      seg0.ts\n";
        let pl = MediaPlaylist::parse(input).expect("u64::MAX exactly must parse");
        assert_eq!(pl.segments[0].byte_range.as_ref().unwrap().length, 1);
        assert_eq!(
            pl.segments[0].byte_range.as_ref().unwrap().offset,
            Some(u64::MAX - 1)
        );
    }

    #[test]
    fn byterange_no_offset_max_length_accepted() {
        let input = "#EXTM3U\n\
                      #EXT-X-TARGETDURATION:10\n\
                      #EXTINF:10,\n\
                      #EXT-X-BYTERANGE:18446744073709551615\n\
                      seg0.ts\n";
        let pl = MediaPlaylist::parse(input).expect("no offset means no overflow check");
        assert_eq!(pl.segments[0].byte_range.as_ref().unwrap().length, u64::MAX);
        assert!(pl.segments[0].byte_range.as_ref().unwrap().offset.is_none());
    }

    #[test]
    fn map_byterange_overflow_rejected() {
        let input = "#EXTM3U\n\
                      #EXT-X-TARGETDURATION:10\n\
                      #EXT-X-MAP:URI=\"init.mp4\",BYTERANGE=\"1@18446744073709551615\"\n\
                      #EXTINF:10,\n\
                      seg0.ts\n";
        let err = MediaPlaylist::parse(input).unwrap_err();
        assert!(
            err.to_string().contains("overflows"),
            "MAP BYTERANGE overflow: {err}"
        );
    }

    #[test]
    fn part_byterange_overflow_rejected() {
        let input = "#EXTM3U\n\
                      #EXT-X-TARGETDURATION:10\n\
                      #EXT-X-PART-INF:PART-TARGET=1.0\n\
                      #EXT-X-PART:URI=\"p0.m4s\",DURATION=1.0,BYTERANGE=\"1@18446744073709551615\"\n\
                      #EXTINF:10,\n\
                      seg0.ts\n";
        let err = MediaPlaylist::parse(input).unwrap_err();
        assert!(
            err.to_string().contains("overflows"),
            "PART BYTERANGE overflow: {err}"
        );
    }

    #[test]
    fn preload_hint_byterange_overflow_rejected() {
        let input = "#EXTM3U\n\
                      #EXT-X-TARGETDURATION:10\n\
                      #EXT-X-PART-INF:PART-TARGET=1.0\n\
                      #EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"next.m4s\",\
                      BYTERANGE-START=18446744073709551615,BYTERANGE-LENGTH=1\n\
                      #EXTINF:10,\n\
                      seg0.ts\n";
        let err = MediaPlaylist::parse(input).unwrap_err();
        assert!(
            err.to_string().contains("overflows"),
            "PRELOAD-HINT overflow: {err}"
        );
    }
}