oxideav-sub-image 0.0.7

Pure-Rust bitmap-subtitle decoders: PGS (.sup Blu-ray), DVB subtitles, VobSub (.idx/.sub)
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
//! PGS / HDMV / Blu-ray `.sup` parser, container, and decoder.
//!
//! A PGS stream is a sequence of display-sets. Each display-set is made
//! of segments, all prefixed by the same on-disk header:
//!
//! ```text
//! "PG" magic (2)
//! PTS (4 BE, 90 kHz units)
//! DTS (4 BE, 90 kHz units)
//! segment type (1): 0x14 PDS, 0x15 ODS, 0x16 PCS, 0x17 WDS, 0x80 END
//! segment size (2 BE)
//! segment body (segment-size bytes)
//! ```
//!
//! A display-set is: one PCS, optional WDS/PDS, one or more ODS,
//! followed by an END segment. The display-set defines a palette + one
//! or more picture objects + the positions at which to compose them on
//! the video canvas.
//!
//! ## Decoder contract
//!
//! The decoder output is one [`oxideav_core::Frame::Video`] per
//! display-set ending with an END segment. The frame's dimensions are
//! the video canvas declared in PCS. The pixel format is
//! [`oxideav_core::PixelFormat::Rgba`]. Transparent background wherever
//! no object is composed; objects are YCbCr→RGB-converted and
//! alpha-composited at the PCS positions.
//!
//! ## Scope / limitations
//!
//! * Decode and encode supported. The encoder crops the input frame to
//!   the tight bounding box of its non-transparent pixels and emits a
//!   single composition object covering that sub-rectangle at the
//!   bbox's `(x, y)`. Colour is quantised into a ≤ 255-entry palette
//!   (index 0 reserved for transparent). When the cropped region has
//!   more than 255 distinct RGBA colours the palette is built from a
//!   3/3/2/2 (R/G/B/A) bucketed reduction, nearest-matching any
//!   surplus colours. Fully-transparent input frames emit an erase
//!   display-set (PCS carrying zero composition objects + empty WDS).
//! * Objects referenced by a composition but not yet seen via ODS are
//!   skipped silently — PGS allows carrying only palette/WDS updates.
//! * ODS fragmentation is handled (an object carries `last_in_sequence`
//!   bits); a PDS version update is treated as a replace.
//! * Cropped compositions (PCS.object_cropped_flag) fall back to
//!   compositing the full object — crop rectangles are parsed but not
//!   applied.

use std::collections::{HashMap, VecDeque};
use std::io::{Read, SeekFrom};

use oxideav_core::{
    CodecId, CodecParameters, CodecResolver, Error, Frame, MediaType, Packet, PixelFormat, Result,
    StreamInfo, TimeBase, VideoFrame, VideoPlane,
};
use oxideav_core::{ContainerRegistry, Demuxer, ProbeData, ProbeScore, ReadSeek};
use oxideav_core::{Decoder, Encoder};

use crate::PGS_CODEC_ID;

// --- segment-type identifiers --------------------------------------------

pub const SEG_PDS: u8 = 0x14;
pub const SEG_ODS: u8 = 0x15;
pub const SEG_PCS: u8 = 0x16;
pub const SEG_WDS: u8 = 0x17;
pub const SEG_END: u8 = 0x80;

/// One parsed display-set segment, carrying only the bytes we need.
#[derive(Clone, Debug)]
pub struct RawSegment {
    pub pts_90k: u32,
    pub dts_90k: u32,
    pub seg_type: u8,
    pub body: Vec<u8>,
}

/// Parse the next raw segment starting at `buf[pos]`. Returns the parsed
/// segment and the new cursor position. `Error::NeedMore` is returned if
/// fewer than 13 bytes remain or the body is truncated — callers reading
/// a complete file typically treat that as EOF.
pub fn read_segment(buf: &[u8], pos: usize) -> Result<(RawSegment, usize)> {
    if pos + 13 > buf.len() {
        return Err(Error::NeedMore);
    }
    if &buf[pos..pos + 2] != b"PG" {
        return Err(Error::invalid("PGS: segment missing 'PG' magic"));
    }
    let pts_90k = u32::from_be_bytes([buf[pos + 2], buf[pos + 3], buf[pos + 4], buf[pos + 5]]);
    let dts_90k = u32::from_be_bytes([buf[pos + 6], buf[pos + 7], buf[pos + 8], buf[pos + 9]]);
    let seg_type = buf[pos + 10];
    let size = u16::from_be_bytes([buf[pos + 11], buf[pos + 12]]) as usize;
    let end = pos + 13 + size;
    if end > buf.len() {
        return Err(Error::NeedMore);
    }
    Ok((
        RawSegment {
            pts_90k,
            dts_90k,
            seg_type,
            body: buf[pos + 13..end].to_vec(),
        },
        end,
    ))
}

// --- PCS ---------------------------------------------------------------

#[derive(Clone, Debug)]
pub struct PresentationComposition {
    pub width: u16,
    pub height: u16,
    pub composition_number: u16,
    pub objects: Vec<CompositionObject>,
}

#[derive(Clone, Debug)]
pub struct CompositionObject {
    pub object_id: u16,
    pub window_id: u8,
    pub cropped: bool,
    pub forced: bool,
    pub x: u16,
    pub y: u16,
}

fn parse_pcs(body: &[u8]) -> Result<PresentationComposition> {
    if body.len() < 11 {
        return Err(Error::invalid("PGS PCS: body too short"));
    }
    let width = u16::from_be_bytes([body[0], body[1]]);
    let height = u16::from_be_bytes([body[2], body[3]]);
    // body[4] = frame-rate (ignored)
    let composition_number = u16::from_be_bytes([body[5], body[6]]);
    // body[7] = composition state (ignored for now)
    // body[8] = palette_update_flag (ignored)
    // body[9] = palette_id (ignored — stored on the PDS itself)
    let n_objects = body[10] as usize;
    let mut cur = 11;
    let mut objects = Vec::with_capacity(n_objects);
    for _ in 0..n_objects {
        if cur + 8 > body.len() {
            return Err(Error::invalid("PGS PCS: object entry truncated"));
        }
        let object_id = u16::from_be_bytes([body[cur], body[cur + 1]]);
        let window_id = body[cur + 2];
        let flags = body[cur + 3];
        let cropped = (flags & 0x80) != 0;
        let forced = (flags & 0x40) != 0;
        let x = u16::from_be_bytes([body[cur + 4], body[cur + 5]]);
        let y = u16::from_be_bytes([body[cur + 6], body[cur + 7]]);
        cur += 8;
        if cropped {
            if cur + 8 > body.len() {
                return Err(Error::invalid("PGS PCS: cropped object missing crop rect"));
            }
            cur += 8;
        }
        objects.push(CompositionObject {
            object_id,
            window_id,
            cropped,
            forced,
            x,
            y,
        });
    }
    Ok(PresentationComposition {
        width,
        height,
        composition_number,
        objects,
    })
}

// --- PDS ---------------------------------------------------------------

#[derive(Clone, Debug)]
pub struct Palette {
    /// 256 entries, defaulting to transparent black. Each entry holds
    /// pre-resolved RGBA bytes.
    pub entries: [[u8; 4]; 256],
}

impl Default for Palette {
    fn default() -> Self {
        Self {
            entries: [[0u8; 4]; 256],
        }
    }
}

fn ycbcr_to_rgba(y: u8, cr: u8, cb: u8, a: u8) -> [u8; 4] {
    // BT.601 — PGS uses 8-bit limited-range YCbCr.
    let y = y as i32;
    let cb = cb as i32 - 128;
    let cr = cr as i32 - 128;
    let r = y + ((91881 * cr) >> 16);
    let g = y - ((22554 * cb + 46802 * cr) >> 16);
    let b = y + ((116130 * cb) >> 16);
    [
        r.clamp(0, 255) as u8,
        g.clamp(0, 255) as u8,
        b.clamp(0, 255) as u8,
        a,
    ]
}

fn parse_pds_into(body: &[u8], palette: &mut Palette) -> Result<()> {
    if body.len() < 2 {
        return Err(Error::invalid("PGS PDS: too short"));
    }
    // body[0] = palette_id, body[1] = palette_version. We fold all
    // palettes into one shared table — real streams rarely use more
    // than the id-0 palette per display-set.
    let mut cur = 2;
    while cur + 5 <= body.len() {
        let idx = body[cur] as usize;
        let y = body[cur + 1];
        let cr = body[cur + 2];
        let cb = body[cur + 3];
        let a = body[cur + 4];
        palette.entries[idx] = ycbcr_to_rgba(y, cr, cb, a);
        cur += 5;
    }
    Ok(())
}

// --- ODS ---------------------------------------------------------------

#[derive(Clone, Debug)]
pub struct Object {
    pub width: u16,
    pub height: u16,
    /// Indexed-colour pixels (palette ids), row-major.
    pub pixels: Vec<u8>,
}

/// Assemble an ODS (handling the `last_in_sequence` fragmentation bits)
/// into a completed object.
fn parse_ods_into(
    body: &[u8],
    fragments: &mut HashMap<u16, Vec<u8>>,
    objects: &mut HashMap<u16, Object>,
) -> Result<()> {
    if body.len() < 4 {
        return Err(Error::invalid("PGS ODS: header too short"));
    }
    let object_id = u16::from_be_bytes([body[0], body[1]]);
    // body[2] = object_version
    let seq_flag = body[3];
    let first = (seq_flag & 0x80) != 0;
    let last = (seq_flag & 0x40) != 0;

    // First fragment carries: object_data_length (3 BE) + width (2) + height (2) + rle-data.
    // Middle/last fragments carry just rle-data.
    let entry = fragments.entry(object_id).or_default();
    if first {
        entry.clear();
    }
    entry.extend_from_slice(&body[4..]);

    if !last {
        return Ok(());
    }
    // Complete — decode. Pull out width/height + RLE stream.
    let full = fragments.remove(&object_id).unwrap_or_default();
    if full.len() < 7 {
        return Err(Error::invalid(
            "PGS ODS: assembled object data shorter than header",
        ));
    }
    // full[0..3] = object_data_length (u24 BE, informational)
    let width = u16::from_be_bytes([full[3], full[4]]);
    let height = u16::from_be_bytes([full[5], full[6]]);
    if width == 0 || height == 0 {
        return Err(Error::invalid("PGS ODS: zero width/height"));
    }
    let rle = &full[7..];
    let pixels = decode_rle(rle, width as usize, height as usize)?;
    objects.insert(
        object_id,
        Object {
            width,
            height,
            pixels,
        },
    );
    Ok(())
}

/// Decode a PGS run-length encoded bitmap into a width×height indexed
/// buffer. The PGS RLE uses these runs:
///
/// * `CCCCCCCC` (C ≠ 0) — single pixel of colour C.
/// * `00 00`    — end-of-line marker.
/// * `00 LLLLLLLL` (L < 0x40, L > 0) — L pixels of colour 0.
/// * `00 01LLLLLL LLLLLLLL` — (L, 6+8 bits) pixels of colour 0.
/// * `00 10LLLLLL CCCCCCCC` — L pixels of colour C (L < 0x40, L > 0).
/// * `00 11LLLLLL LLLLLLLL CCCCCCCC` — L pixels (14 bits) of colour C.
pub fn decode_rle(rle: &[u8], width: usize, height: usize) -> Result<Vec<u8>> {
    let mut out = vec![0u8; width * height];
    let mut i = 0;
    let mut row = 0usize;
    let mut col = 0usize;
    while i < rle.len() {
        let b0 = rle[i];
        i += 1;
        let (run_len, colour, line_end) = if b0 != 0 {
            (1usize, b0, false)
        } else {
            if i >= rle.len() {
                return Err(Error::invalid("PGS RLE: truncated after 0x00"));
            }
            let b1 = rle[i];
            i += 1;
            if b1 == 0 {
                // end-of-line
                (0usize, 0u8, true)
            } else {
                let hi = b1 & 0xC0;
                let len_lo = (b1 & 0x3F) as usize;
                let (length, colour) = match hi {
                    0x00 => (len_lo, 0u8),
                    0x40 => {
                        if i >= rle.len() {
                            return Err(Error::invalid("PGS RLE: truncated 14-bit length"));
                        }
                        let b2 = rle[i] as usize;
                        i += 1;
                        ((len_lo << 8) | b2, 0u8)
                    }
                    0x80 => {
                        if i >= rle.len() {
                            return Err(Error::invalid("PGS RLE: truncated colour"));
                        }
                        let c = rle[i];
                        i += 1;
                        (len_lo, c)
                    }
                    _ => {
                        if i + 1 >= rle.len() {
                            return Err(Error::invalid("PGS RLE: truncated 14-bit+colour run"));
                        }
                        let b2 = rle[i] as usize;
                        let c = rle[i + 1];
                        i += 2;
                        (((len_lo << 8) | b2), c)
                    }
                };
                (length, colour, false)
            }
        };
        if line_end {
            row += 1;
            col = 0;
            if row > height {
                return Err(Error::invalid("PGS RLE: too many lines"));
            }
            continue;
        }
        if row >= height {
            return Err(Error::invalid("PGS RLE: pixel past end of bitmap"));
        }
        // Clamp runs that would stray past the declared row — malformed
        // streams exist in the wild. Matching a row-exact end is not
        // strictly required: the RLE end-of-line marker is what moves
        // us to the next row.
        let end = col.saturating_add(run_len).min(width);
        let base = row * width + col;
        for px in &mut out[base..base + (end - col)] {
            *px = colour;
        }
        col = end;
    }
    Ok(out)
}

// --- Display-set accumulator + renderer --------------------------------

/// Internal state as we walk segments looking for an END.
#[derive(Default)]
struct DisplaySet {
    pcs: Option<PresentationComposition>,
    // Accepted last-known PTS in 90 kHz units.
    pts_90k: u32,
    palette: Palette,
    object_fragments: HashMap<u16, Vec<u8>>,
    objects: HashMap<u16, Object>,
    /// Last-known canvas size (carried over between display-sets when
    /// a PCS-less reset arrives).
    last_canvas: Option<(u16, u16)>,
}

impl DisplaySet {
    fn push(&mut self, seg: &RawSegment) -> Result<()> {
        self.pts_90k = seg.pts_90k;
        match seg.seg_type {
            SEG_PCS => {
                let pcs = parse_pcs(&seg.body)?;
                self.last_canvas = Some((pcs.width, pcs.height));
                self.pcs = Some(pcs);
            }
            // We don't clip to the declared windows — only validate that a
            // body is present at all.
            SEG_WDS if seg.body.is_empty() => {
                return Err(Error::invalid("PGS WDS: empty body"));
            }
            SEG_PDS => {
                parse_pds_into(&seg.body, &mut self.palette)?;
            }
            SEG_ODS => {
                parse_ods_into(&seg.body, &mut self.object_fragments, &mut self.objects)?;
            }
            SEG_END => {}
            _ => {
                // Unknown / reserved segment type — ignored, on the
                // principle that future PGS extensions should not break
                // playback of the parts of the stream we do understand.
            }
        }
        Ok(())
    }

    /// Render the assembled set into an RGBA frame. Returns `Ok(None)`
    /// when the display-set is an "erase" (PCS with zero composition
    /// objects or no PCS at all) — in that case the caller emits a
    /// fully-transparent canvas so the pipeline can clear whatever was
    /// displayed before.
    fn render(&self) -> Result<Option<Vec<u8>>> {
        let Some(pcs) = &self.pcs else {
            return Ok(None);
        };
        let width = pcs.width as usize;
        let height = pcs.height as usize;
        if width == 0 || height == 0 {
            return Err(Error::invalid("PGS PCS: zero-sized canvas"));
        }
        let mut canvas = vec![0u8; width * height * 4];
        for co in &pcs.objects {
            let Some(obj) = self.objects.get(&co.object_id) else {
                continue;
            };
            let ox = co.x as usize;
            let oy = co.y as usize;
            let ow = obj.width as usize;
            let oh = obj.height as usize;
            // Composition objects can overlap; when the topmost palette
            // entry is partially transparent the source blends *over*
            // whatever earlier object already painted, rather than
            // overwriting it (Porter–Duff source-over). Build the object
            // as rows of palette indices and run the shared compositor.
            let rows: Vec<Vec<u8>> = (0..oh)
                .map(|row| obj.pixels[row * ow..row * ow + ow].to_vec())
                .collect();
            let palette = &self.palette;
            crate::composite::blit_indexed(&mut canvas, width, height, &rows, ox, oy, |idx| {
                palette.entries[idx as usize]
            });
        }
        Ok(Some(canvas))
    }
}

// --- Container (.sup) --------------------------------------------------

/// File-extension / container name registration.
pub fn register_container(reg: &mut ContainerRegistry) {
    reg.register_demuxer("pgs", open_pgs);
    reg.register_extension("sup", "pgs");
    reg.register_probe("pgs", probe_pgs);
}

fn probe_pgs(p: &ProbeData) -> ProbeScore {
    // A PGS file opens with the ASCII "PG" magic and reasonable PTS
    // fields. Combined with the .sup extension we give it a high score.
    if p.buf.len() >= 13 && &p.buf[..2] == b"PG" {
        100
    } else if p.ext == Some("sup") {
        25
    } else {
        0
    }
}

fn open_pgs(mut input: Box<dyn ReadSeek>, _codecs: &dyn CodecResolver) -> Result<Box<dyn Demuxer>> {
    let mut buf = Vec::new();
    input.seek(SeekFrom::Start(0))?;
    input.read_to_end(&mut buf)?;

    // Walk the file, gathering segments into display-sets, emitting one
    // packet per display-set with pts = its first segment's PTS.
    let time_base = TimeBase::new(1, 90_000);
    let mut packets: VecDeque<Packet> = VecDeque::new();
    let mut cur = 0usize;
    let mut ds_start_pts: Option<u32> = None;
    let mut ds_buf: Vec<u8> = Vec::new();
    let mut last_canvas: Option<(u16, u16)> = None;
    while cur < buf.len() {
        let (seg, next) = match read_segment(&buf, cur) {
            Ok(x) => x,
            Err(_) => break,
        };
        if ds_start_pts.is_none() {
            ds_start_pts = Some(seg.pts_90k);
        }
        ds_buf.extend_from_slice(&buf[cur..next]);
        // Snoop on PCS to capture the canvas size for stream metadata.
        if seg.seg_type == SEG_PCS {
            if let Ok(pcs) = parse_pcs(&seg.body) {
                last_canvas = Some((pcs.width, pcs.height));
            }
        }
        cur = next;
        if seg.seg_type == SEG_END {
            let pts = ds_start_pts.take().unwrap_or(0);
            let mut packet = Packet::new(0, time_base, std::mem::take(&mut ds_buf));
            packet.pts = Some(pts as i64);
            packet.dts = Some(pts as i64);
            packet.flags.keyframe = true;
            packets.push_back(packet);
        }
    }
    // Give successive packets a synthetic duration (end - start) and
    // leave the final one's duration unset — we don't know when its cue
    // disappears until another display-set arrives.
    for i in 0..packets.len().saturating_sub(1) {
        let (Some(a), Some(b)) = (packets[i].pts, packets[i + 1].pts) else {
            continue;
        };
        packets[i].duration = Some((b - a).max(0));
    }

    let (w, h) = last_canvas.unwrap_or((0, 0));
    let mut params = CodecParameters::video(CodecId::new(PGS_CODEC_ID));
    params.media_type = MediaType::Subtitle;
    params.width = Some(w as u32);
    params.height = Some(h as u32);
    params.pixel_format = Some(PixelFormat::Rgba);

    let total = packets.back().and_then(|p| p.pts).unwrap_or(0);
    let stream = StreamInfo {
        index: 0,
        time_base,
        duration: Some(total),
        start_time: Some(0),
        params,
    };
    Ok(Box::new(PgsDemuxer {
        streams: [stream],
        packets,
    }))
}

struct PgsDemuxer {
    streams: [StreamInfo; 1],
    packets: VecDeque<Packet>,
}

impl Demuxer for PgsDemuxer {
    fn format_name(&self) -> &str {
        "pgs"
    }

    fn streams(&self) -> &[StreamInfo] {
        &self.streams
    }

    fn next_packet(&mut self) -> Result<Packet> {
        self.packets.pop_front().ok_or(Error::Eof)
    }

    fn duration_micros(&self) -> Option<i64> {
        // PTS is in 90 kHz — µs = pts * (1_000_000 / 90_000) = pts * 100 / 9.
        let pts = self.streams[0].duration?;
        Some(pts * 100 / 9)
    }
}

// --- Decoder -----------------------------------------------------------

/// Build a PGS decoder.
pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
    Ok(Box::new(PgsDecoder {
        codec_id: CodecId::new(PGS_CODEC_ID),
        pending: VecDeque::new(),
        eof: false,
    }))
}

struct PgsDecoder {
    codec_id: CodecId,
    pending: VecDeque<Frame>,
    eof: bool,
}

impl Decoder for PgsDecoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn send_packet(&mut self, packet: &Packet) -> Result<()> {
        let mut ds = DisplaySet::default();
        let mut cur = 0;
        while cur < packet.data.len() {
            let (seg, next) = read_segment(&packet.data, cur)?;
            ds.push(&seg)?;
            cur = next;
        }
        let Some(pcs) = &ds.pcs else {
            // No PCS → nothing to render for this packet. The container
            // normally emits packets only when an END closes a set, so
            // getting here means a malformed or empty display-set.
            return Ok(());
        };
        let width = pcs.width as u32;
        let height = pcs.height as u32;
        let rendered = ds
            .render()?
            .unwrap_or_else(|| vec![0u8; (width as usize) * (height as usize) * 4]);
        let _ = (width, height);
        let frame = VideoFrame {
            pts: packet.pts,
            planes: vec![VideoPlane {
                stride: (pcs.width as usize) * 4,
                data: rendered,
            }],
        };
        self.pending.push_back(Frame::Video(frame));
        Ok(())
    }

    fn receive_frame(&mut self) -> Result<Frame> {
        if let Some(f) = self.pending.pop_front() {
            return Ok(f);
        }
        if self.eof {
            Err(Error::Eof)
        } else {
            Err(Error::NeedMore)
        }
    }

    fn flush(&mut self) -> Result<()> {
        self.eof = true;
        Ok(())
    }

    fn reset(&mut self) -> Result<()> {
        // PGS is stateless across packets — each display set comes with
        // its own PCS/PDS/ODS chain. Just drop the ready-frame queue and
        // clear the eof latch.
        self.pending.clear();
        self.eof = false;
        Ok(())
    }
}

// --- Encoder -----------------------------------------------------------

/// Build a PGS encoder. The encoder accepts [`Frame::Video`] frames with
/// [`PixelFormat::Rgba`] and emits one [`Packet`] per frame carrying a
/// complete PGS display-set (PCS + WDS + PDS + ODS + END).
///
/// All pixels are quantised into a 255-entry palette (index 0 is reserved
/// for fully-transparent background). When the input has ≤ 255 distinct
/// RGBA colours the quantisation is lossless; otherwise each channel is
/// reduced to a lower bit-depth (3-3-2-2 R-G-B-A) which loses precision
/// but stays within the PGS palette budget.
pub fn make_encoder(_params: &CodecParameters) -> Result<Box<dyn Encoder>> {
    let mut out_params = CodecParameters::video(CodecId::new(PGS_CODEC_ID));
    out_params.media_type = MediaType::Subtitle;
    out_params.pixel_format = Some(PixelFormat::Rgba);
    Ok(Box::new(PgsEncoder {
        codec_id: CodecId::new(PGS_CODEC_ID),
        params: out_params,
        pending: VecDeque::new(),
        composition_number: 0,
    }))
}

struct PgsEncoder {
    codec_id: CodecId,
    params: CodecParameters,
    pending: VecDeque<Packet>,
    composition_number: u16,
}

impl Encoder for PgsEncoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn output_params(&self) -> &CodecParameters {
        &self.params
    }

    fn send_frame(&mut self, frame: &Frame) -> Result<()> {
        let Frame::Video(v) = frame else {
            return Err(Error::unsupported(
                "PGS encoder only accepts Frame::Video input",
            ));
        };
        // Pixel format is now stream-level — RGBA is asserted at the
        // CodecParameters layer upstream. Derive (width, height) from
        // the first plane: RGBA stride is `width * 4`.
        if v.planes.is_empty() {
            return Err(Error::invalid("PGS encoder: frame has no plane"));
        }
        let plane = &v.planes[0];
        if plane.stride == 0 || plane.stride % 4 != 0 {
            return Err(Error::invalid(
                "PGS encoder: RGBA plane stride must be a positive multiple of 4",
            ));
        }
        let width = (plane.stride / 4) as u32;
        let height = if width == 0 {
            0
        } else {
            (plane.data.len() / plane.stride) as u32
        };
        if width == 0 || height == 0 {
            return Err(Error::invalid("PGS encoder: zero-sized frame"));
        }
        if self.params.width.is_none() {
            self.params.width = Some(width);
            self.params.height = Some(height);
        }

        let composition_number = self.composition_number;
        self.composition_number = self.composition_number.wrapping_add(1);
        let pts_90k = frame_pts_90k(v).unwrap_or(0);

        // Find the tight bounding box of non-transparent pixels. PGS
        // structurally allows an object smaller than the canvas placed at
        // an arbitrary (x, y); shrinking to the bbox lets a small visible
        // region (a single line of subtitle text near the bottom of a
        // 1920×1080 canvas, for example) be encoded as a small object
        // rather than reserving an RLE run for every transparent row of
        // the full frame.
        let bbox = tight_bbox(v, width as usize, height as usize);
        let bytes = match bbox {
            None => {
                // Fully transparent — emit an erase display-set (PCS with
                // zero objects + empty WDS). The decoder maps this to a
                // fully-transparent canvas, clearing whatever was shown
                // previously.
                encode_erase_display_set(width as u16, height as u16, composition_number, pts_90k)
            }
            Some((bx, by, bw, bh)) => {
                let (indices, palette_rgba) =
                    quantise_rgba_region(v, width as usize, bx, by, bw, bh)?;
                encode_display_set(
                    width as u16,
                    height as u16,
                    bx as u16,
                    by as u16,
                    bw as u16,
                    bh as u16,
                    composition_number,
                    pts_90k,
                    &palette_rgba,
                    &indices,
                )
            }
        };
        let mut packet = Packet::new(0, TimeBase::new(1, 90_000), bytes);
        packet.pts = Some(pts_90k as i64);
        packet.dts = Some(pts_90k as i64);
        packet.flags.keyframe = true;
        self.pending.push_back(packet);
        Ok(())
    }

    fn receive_packet(&mut self) -> Result<Packet> {
        self.pending.pop_front().ok_or(Error::NeedMore)
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }
}

fn frame_pts_90k(v: &VideoFrame) -> Option<u32> {
    // VideoFrame no longer carries a time_base. Treat the incoming pts as
    // microseconds (the canonical subtitle pts unit) and rescale to the
    // 90 kHz PGS clock.
    let pts = v.pts?;
    let scaled = TimeBase::new(1, 1_000_000).rescale(pts, TimeBase::new(1, 90_000));
    if scaled < 0 {
        Some(0)
    } else {
        Some(scaled as u32)
    }
}

/// Find the smallest rectangle covering every pixel with non-zero alpha.
///
/// Returns `None` if the frame is fully transparent (alpha == 0 everywhere),
/// otherwise `Some((x, y, width, height))` in pixel units. A zero-width
/// or zero-height frame also returns `None`.
fn tight_bbox(v: &VideoFrame, width: usize, height: usize) -> Option<(usize, usize, usize, usize)> {
    if width == 0 || height == 0 || v.planes.is_empty() {
        return None;
    }
    let plane = &v.planes[0];
    let needed = width * 4;
    if plane.stride < needed {
        return None;
    }
    let mut min_x = width;
    let mut max_x: isize = -1;
    let mut min_y = height;
    let mut max_y: isize = -1;
    for row in 0..height {
        let line = &plane.data[row * plane.stride..row * plane.stride + needed];
        let mut row_has = false;
        let mut row_min = width;
        let mut row_max: isize = -1;
        for col in 0..width {
            if line[col * 4 + 3] != 0 {
                if !row_has {
                    row_min = col;
                    row_has = true;
                }
                row_max = col as isize;
            }
        }
        if row_has {
            if (row as isize) < min_y as isize {
                min_y = row;
            }
            if (row as isize) > max_y {
                max_y = row as isize;
            }
            if row_min < min_x {
                min_x = row_min;
            }
            if row_max > max_x {
                max_x = row_max;
            }
        }
    }
    if max_x < 0 || max_y < 0 {
        return None;
    }
    let bw = (max_x as usize - min_x) + 1;
    let bh = (max_y as usize - min_y) + 1;
    Some((min_x, min_y, bw, bh))
}

/// Walk an RGBA frame's sub-rectangle and produce a paired indexed-colour
/// buffer and palette covering just that region. The caller supplies the
/// full frame width (for stride) plus the bbox `(x, y, width, height)`.
/// Index 0 is always fully-transparent black.
fn quantise_rgba_region(
    v: &VideoFrame,
    frame_width: usize,
    bx: usize,
    by: usize,
    bw: usize,
    bh: usize,
) -> Result<(Vec<u8>, Vec<[u8; 4]>)> {
    if v.planes.is_empty() {
        return Err(Error::invalid("PGS encoder: RGBA frame has no plane"));
    }
    let plane = &v.planes[0];
    let needed = frame_width * 4;
    if plane.stride < needed {
        return Err(Error::invalid("PGS encoder: RGBA stride too small"));
    }
    if bx + bw > frame_width || by * plane.stride + needed > plane.data.len() {
        return Err(Error::invalid("PGS encoder: bbox out of frame"));
    }
    let mut palette: Vec<[u8; 4]> = Vec::with_capacity(256);
    palette.push([0, 0, 0, 0]);
    let mut map: HashMap<[u8; 4], u8> = HashMap::new();
    map.insert([0, 0, 0, 0], 0);

    let mut indices = vec![0u8; bw * bh];
    let mut quantise_harder = false;
    'scan: for row in 0..bh {
        let src_row = by + row;
        let line = &plane.data[src_row * plane.stride..src_row * plane.stride + needed];
        for col in 0..bw {
            let src_col = bx + col;
            let px = &line[src_col * 4..src_col * 4 + 4];
            let key = if px[3] == 0 {
                [0, 0, 0, 0]
            } else {
                [px[0], px[1], px[2], px[3]]
            };
            if let Some(&idx) = map.get(&key) {
                indices[row * bw + col] = idx;
                continue;
            }
            if palette.len() >= 255 {
                quantise_harder = true;
                break 'scan;
            }
            let idx = palette.len() as u8;
            palette.push(key);
            map.insert(key, idx);
            indices[row * bw + col] = idx;
        }
    }

    if quantise_harder {
        return quantise_rgba_332_region(v, frame_width, bx, by, bw, bh);
    }
    Ok((indices, palette))
}

/// Fallback quantisation: bucket R/G/B to 3/3/2 bits and A to 2 bits over
/// a sub-rectangle of the frame. Yields up to 256 distinct indices;
/// index 0 is fully-transparent.
fn quantise_rgba_332_region(
    v: &VideoFrame,
    frame_width: usize,
    bx: usize,
    by: usize,
    bw: usize,
    bh: usize,
) -> Result<(Vec<u8>, Vec<[u8; 4]>)> {
    let plane = &v.planes[0];
    let needed = frame_width * 4;
    if plane.stride < needed {
        return Err(Error::invalid("PGS encoder: RGBA stride too small"));
    }
    if bx + bw > frame_width {
        return Err(Error::invalid("PGS encoder: bbox out of frame"));
    }
    let mut palette: Vec<[u8; 4]> = Vec::with_capacity(256);
    palette.push([0, 0, 0, 0]);
    let mut map: HashMap<[u8; 4], u8> = HashMap::new();
    map.insert([0, 0, 0, 0], 0);
    let mut indices = vec![0u8; bw * bh];
    for row in 0..bh {
        let src_row = by + row;
        let line = &plane.data[src_row * plane.stride..src_row * plane.stride + needed];
        for col in 0..bw {
            let src_col = bx + col;
            let px = &line[src_col * 4..src_col * 4 + 4];
            if px[3] == 0 {
                indices[row * bw + col] = 0;
                continue;
            }
            let r = px[0] & 0xE0;
            let g = px[1] & 0xE0;
            let b = px[2] & 0xC0;
            let a = match px[3] {
                0..=63 => 0x3F,
                64..=127 => 0x7F,
                128..=191 => 0xBF,
                _ => 0xFF,
            };
            let key = [r, g, b, a];
            if let Some(&idx) = map.get(&key) {
                indices[row * bw + col] = idx;
                continue;
            }
            let idx = palette.len() as u8;
            palette.push(key);
            map.insert(key, idx);
            indices[row * bw + col] = idx;
            if palette.len() == 256 {
                // No room for a further colour — subsequent novel pixels
                // snap to the nearest existing entry.
                for row2 in row..bh {
                    let src_row2 = by + row2;
                    let line2 =
                        &plane.data[src_row2 * plane.stride..src_row2 * plane.stride + needed];
                    let start_col = if row2 == row { col + 1 } else { 0 };
                    for col2 in start_col..bw {
                        let src_col2 = bx + col2;
                        let px2 = &line2[src_col2 * 4..src_col2 * 4 + 4];
                        let key2 = if px2[3] == 0 {
                            [0, 0, 0, 0]
                        } else {
                            let r = px2[0] & 0xE0;
                            let g = px2[1] & 0xE0;
                            let b = px2[2] & 0xC0;
                            let a = match px2[3] {
                                0..=63 => 0x3F,
                                64..=127 => 0x7F,
                                128..=191 => 0xBF,
                                _ => 0xFF,
                            };
                            [r, g, b, a]
                        };
                        indices[row2 * bw + col2] = *map
                            .get(&key2)
                            .unwrap_or(&nearest_palette_entry(&palette, key2));
                    }
                }
                return Ok((indices, palette));
            }
        }
    }
    Ok((indices, palette))
}

fn nearest_palette_entry(palette: &[[u8; 4]], key: [u8; 4]) -> u8 {
    let mut best = 0u8;
    let mut best_d = i32::MAX;
    for (i, entry) in palette.iter().enumerate() {
        let dr = entry[0] as i32 - key[0] as i32;
        let dg = entry[1] as i32 - key[1] as i32;
        let db = entry[2] as i32 - key[2] as i32;
        let da = entry[3] as i32 - key[3] as i32;
        let d = dr * dr + dg * dg + db * db + da * da;
        if d < best_d {
            best_d = d;
            best = i as u8;
        }
    }
    best
}

/// Encode an indexed bitmap + palette into a single PGS display-set
/// byte-string (PCS + WDS + PDS + ODS + END, each with the shared
/// "PG" segment header). The composition object sits at
/// `(obj_x, obj_y)` on a `canvas_w × canvas_h` canvas and itself
/// measures `obj_w × obj_h` pixels — `indices` must be `obj_w * obj_h`
/// bytes long.
#[allow(clippy::too_many_arguments)]
fn encode_display_set(
    canvas_w: u16,
    canvas_h: u16,
    obj_x: u16,
    obj_y: u16,
    obj_w: u16,
    obj_h: u16,
    composition_number: u16,
    pts_90k: u32,
    palette: &[[u8; 4]],
    indices: &[u8],
) -> Vec<u8> {
    let mut out = Vec::new();

    // PCS.
    let mut pcs = Vec::new();
    pcs.extend_from_slice(&canvas_w.to_be_bytes());
    pcs.extend_from_slice(&canvas_h.to_be_bytes());
    pcs.push(0x10); // frame rate (ignored by decoders but conventional)
    pcs.extend_from_slice(&composition_number.to_be_bytes());
    pcs.push(0x80); // composition state: epoch-start
    pcs.push(0); // palette update flag
    pcs.push(0); // palette id
    pcs.push(1); // one composition object
    pcs.extend_from_slice(&1u16.to_be_bytes()); // object id
    pcs.push(0); // window id
    pcs.push(0); // flags (not cropped, not forced)
    pcs.extend_from_slice(&obj_x.to_be_bytes()); // x
    pcs.extend_from_slice(&obj_y.to_be_bytes()); // y
    push_segment(&mut out, pts_90k, SEG_PCS, &pcs);

    // WDS — declare a single window matching the object's footprint.
    // Decoders use this to scope the area that will be redrawn between
    // display-sets; clamp to canvas if the object would overrun (a
    // 1-pixel-wide object at canvas_w-1 still fits).
    let win_w = obj_w.min(canvas_w.saturating_sub(obj_x));
    let win_h = obj_h.min(canvas_h.saturating_sub(obj_y));
    let mut wds = Vec::new();
    wds.push(1); // one window
    wds.push(0); // window id
    wds.extend_from_slice(&obj_x.to_be_bytes()); // x
    wds.extend_from_slice(&obj_y.to_be_bytes()); // y
    wds.extend_from_slice(&win_w.to_be_bytes());
    wds.extend_from_slice(&win_h.to_be_bytes());
    push_segment(&mut out, pts_90k, SEG_WDS, &wds);

    // PDS.
    let mut pds = Vec::new();
    pds.push(0); // palette id
    pds.push(0); // palette version
    for (idx, rgba) in palette.iter().enumerate() {
        if idx >= 256 {
            break;
        }
        if rgba[3] == 0 {
            // PGS does carry transparent entries, but the canonical form
            // for "unused" is alpha 0 with zeroed chroma — emit it.
            pds.push(idx as u8);
            pds.push(0);
            pds.push(0x80);
            pds.push(0x80);
            pds.push(0);
            continue;
        }
        let (y, cb, cr) = rgb_to_ycbcr_bt601(rgba[0], rgba[1], rgba[2]);
        pds.push(idx as u8);
        pds.push(y);
        pds.push(cr);
        pds.push(cb);
        pds.push(rgba[3]);
    }
    push_segment(&mut out, pts_90k, SEG_PDS, &pds);

    // ODS — single fragment (0xC0 = first + last sequence).
    let rle = encode_rle(indices, obj_w as usize, obj_h as usize);
    let mut ods = Vec::new();
    ods.extend_from_slice(&1u16.to_be_bytes()); // object id
    ods.push(0); // object version
    ods.push(0xC0); // first + last
    let obj_data_len = (rle.len() + 4) as u32; // width+height (4) + rle
    ods.push(((obj_data_len >> 16) & 0xFF) as u8);
    ods.push(((obj_data_len >> 8) & 0xFF) as u8);
    ods.push((obj_data_len & 0xFF) as u8);
    ods.extend_from_slice(&obj_w.to_be_bytes());
    ods.extend_from_slice(&obj_h.to_be_bytes());
    ods.extend_from_slice(&rle);
    push_segment(&mut out, pts_90k, SEG_ODS, &ods);

    // END.
    push_segment(&mut out, pts_90k, SEG_END, &[]);

    out
}

/// Encode an "erase" display-set — a PCS carrying zero composition
/// objects, an empty WDS, and the END marker. This is the canonical
/// representation of a fully-transparent frame (no objects to compose),
/// and tells the decoder/player to clear whatever subtitle was on
/// screen before.
fn encode_erase_display_set(
    canvas_w: u16,
    canvas_h: u16,
    composition_number: u16,
    pts_90k: u32,
) -> Vec<u8> {
    let mut out = Vec::new();

    let mut pcs = Vec::new();
    pcs.extend_from_slice(&canvas_w.to_be_bytes());
    pcs.extend_from_slice(&canvas_h.to_be_bytes());
    pcs.push(0x10); // frame rate
    pcs.extend_from_slice(&composition_number.to_be_bytes());
    pcs.push(0x80); // composition state: epoch-start (forces redraw)
    pcs.push(0); // palette update flag
    pcs.push(0); // palette id
    pcs.push(0); // zero composition objects
    push_segment(&mut out, pts_90k, SEG_PCS, &pcs);

    // WDS — zero windows. The body byte count is one (the window-count
    // field). An entirely empty body is rejected by `DisplaySet::push`,
    // so always emit the count.
    let wds = vec![0u8]; // zero windows
    push_segment(&mut out, pts_90k, SEG_WDS, &wds);

    // END.
    push_segment(&mut out, pts_90k, SEG_END, &[]);

    out
}

fn push_segment(out: &mut Vec<u8>, pts_90k: u32, seg_type: u8, body: &[u8]) {
    out.extend_from_slice(b"PG");
    out.extend_from_slice(&pts_90k.to_be_bytes());
    out.extend_from_slice(&0u32.to_be_bytes()); // DTS — not used
    out.push(seg_type);
    out.extend_from_slice(&(body.len() as u16).to_be_bytes());
    out.extend_from_slice(body);
}

fn rgb_to_ycbcr_bt601(r: u8, g: u8, b: u8) -> (u8, u8, u8) {
    let r = r as i32;
    let g = g as i32;
    let b = b as i32;
    let y = ((77 * r + 150 * g + 29 * b + 128) >> 8) as u8;
    let cb = (((-43 * r - 84 * g + 127 * b + 128) >> 8) + 128).clamp(0, 255) as u8;
    let cr = (((127 * r - 106 * g - 21 * b + 128) >> 8) + 128).clamp(0, 255) as u8;
    (y, cb, cr)
}

/// Encode a width×height indexed-colour buffer into PGS run-length form
/// (see [`decode_rle`] for the inverse description).
pub fn encode_rle(pixels: &[u8], width: usize, height: usize) -> Vec<u8> {
    debug_assert_eq!(pixels.len(), width * height);
    // Pre-size the output. A worst-case run-of-singletons emits one byte
    // per pixel plus a 2-byte end-of-line per row; a best-case long-run
    // input emits 3-4 bytes per row. Allocating once at the
    // singleton-worst-case bound avoids growth churn for typical
    // subtitle-text bitmaps without overcommitting on the long-run path,
    // which lands inside the initial capacity anyway.
    let mut out = Vec::with_capacity(pixels.len() + height * 2);
    for row in 0..height {
        let mut col = 0usize;
        while col < width {
            let colour = pixels[row * width + col];
            let mut run = 1usize;
            while col + run < width && pixels[row * width + col + run] == colour && run < 0x3FFF {
                run += 1;
            }
            emit_run(&mut out, run, colour);
            col += run;
        }
        // End-of-line marker: 00 00.
        out.push(0);
        out.push(0);
    }
    out
}

fn emit_run(out: &mut Vec<u8>, run: usize, colour: u8) {
    if colour == 0 {
        // Transparent background run.
        if run < 64 {
            out.push(0);
            out.push(run as u8); // 00LLLLLL — L > 0
        } else {
            out.push(0);
            out.push(0x40 | ((run >> 8) & 0x3F) as u8);
            out.push((run & 0xFF) as u8);
        }
        return;
    }
    if run == 1 {
        out.push(colour);
        return;
    }
    if run < 4 {
        // Short runs are cheaper as N back-to-back single pixels.
        for _ in 0..run {
            out.push(colour);
        }
        return;
    }
    if run < 64 {
        out.push(0);
        out.push(0x80 | (run as u8 & 0x3F));
        out.push(colour);
    } else {
        out.push(0);
        out.push(0xC0 | ((run >> 8) & 0x3F) as u8);
        out.push((run & 0xFF) as u8);
        out.push(colour);
    }
}

// --- Test helper -------------------------------------------------------

/// Build a minimal PGS display-set carrying one PCS, one PDS, one ODS,
/// and the terminating END. Used by this crate's tests. Public so that
/// external integration tests can exercise the decoder without pulling
/// in `oxideav-tests`.
#[doc(hidden)]
pub fn build_demo_display_set(
    canvas: (u16, u16),
    object: (u16, u16),
    position: (u16, u16),
    palette: &[(u8, [u8; 4])],
    pixels: &[u8],
) -> Vec<u8> {
    fn segment(out: &mut Vec<u8>, pts_90k: u32, seg_type: u8, body: &[u8]) {
        out.extend_from_slice(b"PG");
        out.extend_from_slice(&pts_90k.to_be_bytes());
        out.extend_from_slice(&0u32.to_be_bytes());
        out.push(seg_type);
        out.extend_from_slice(&(body.len() as u16).to_be_bytes());
        out.extend_from_slice(body);
    }

    let mut out = Vec::new();

    // PCS.
    let mut pcs = Vec::new();
    pcs.extend_from_slice(&canvas.0.to_be_bytes());
    pcs.extend_from_slice(&canvas.1.to_be_bytes());
    pcs.push(0); // frame rate
    pcs.extend_from_slice(&1u16.to_be_bytes()); // composition number
    pcs.push(0); // composition state (normal)
    pcs.push(0); // palette update flag
    pcs.push(0); // palette id
    pcs.push(1); // one composition object
    pcs.extend_from_slice(&1u16.to_be_bytes()); // object id
    pcs.push(0); // window id
    pcs.push(0); // flags
    pcs.extend_from_slice(&position.0.to_be_bytes());
    pcs.extend_from_slice(&position.1.to_be_bytes());
    segment(&mut out, 0, SEG_PCS, &pcs);

    // WDS (one window covering the full canvas).
    let mut wds = Vec::new();
    wds.push(1); // one window
    wds.push(0); // window id
    wds.extend_from_slice(&0u16.to_be_bytes()); // x
    wds.extend_from_slice(&0u16.to_be_bytes()); // y
    wds.extend_from_slice(&canvas.0.to_be_bytes());
    wds.extend_from_slice(&canvas.1.to_be_bytes());
    segment(&mut out, 0, SEG_WDS, &wds);

    // PDS.
    let mut pds = Vec::new();
    pds.push(0); // palette id
    pds.push(0); // palette version
    for (idx, rgba) in palette {
        // Convert to YCbCr.
        let r = rgba[0] as i32;
        let g = rgba[1] as i32;
        let b = rgba[2] as i32;
        let y = ((77 * r + 150 * g + 29 * b + 128) >> 8) as u8;
        let cb = (((-43 * r - 84 * g + 127 * b + 128) >> 8) + 128).clamp(0, 255) as u8;
        let cr = (((127 * r - 106 * g - 21 * b + 128) >> 8) + 128).clamp(0, 255) as u8;
        pds.push(*idx);
        pds.push(y);
        pds.push(cr);
        pds.push(cb);
        pds.push(rgba[3]);
    }
    segment(&mut out, 0, SEG_PDS, &pds);

    // ODS (first+last sequence). Single-pixel runs + end-of-line, shared
    // with the fragmented builder via `demo_rle`.
    let rle = demo_rle(object, pixels);
    let mut ods = Vec::new();
    ods.extend_from_slice(&1u16.to_be_bytes()); // object id
    ods.push(0); // object version
    ods.push(0xC0); // first + last sequence
    let obj_data_len = (rle.len() + 4) as u32; // width+height (4) + rle
    ods.push(((obj_data_len >> 16) & 0xFF) as u8);
    ods.push(((obj_data_len >> 8) & 0xFF) as u8);
    ods.push((obj_data_len & 0xFF) as u8);
    ods.extend_from_slice(&object.0.to_be_bytes());
    ods.extend_from_slice(&object.1.to_be_bytes());
    ods.extend_from_slice(&rle);
    segment(&mut out, 0, SEG_ODS, &ods);

    // END.
    segment(&mut out, 0, SEG_END, &[]);
    out
}

/// Encode `pixels` (one byte per palette index, row-major) into the
/// single-pixel-run + end-of-line RLE form `build_demo_display_set`
/// uses. Shared by the single- and multi-fragment demo builders so both
/// carry byte-identical object data.
fn demo_rle(object: (u16, u16), pixels: &[u8]) -> Vec<u8> {
    let w = object.0 as usize;
    let h = object.1 as usize;
    let mut rle = Vec::new();
    for row in 0..h {
        for c in 0..w {
            let p = pixels[row * w + c];
            if p == 0 {
                // short run-of-zero form: 00 01 (1 pixel of colour 0).
                rle.push(0);
                rle.push(1);
            } else {
                rle.push(p);
            }
        }
        rle.push(0);
        rle.push(0);
    }
    rle
}

/// Like [`build_demo_display_set`], but splits the single object's data
/// across `fragments` ODS segments using the PGS sequence flags
/// (first / continuation / last). A real PGS muxer fragments any object
/// whose data exceeds the per-segment size limit; `build_demo_display_set`
/// only ever emits a first+last (single-segment) object, so this builder
/// is what exercises the decoder's reassembly path.
///
/// The first fragment carries the object_data_length + width + height
/// header followed by the leading slice of RLE; continuation fragments
/// carry raw RLE only; the final fragment sets the `last_in_sequence`
/// flag. `fragments` is clamped to at least 1. The split points fall at
/// even byte boundaries of the *whole* `(header ++ rle)` payload, so a
/// boundary can land inside the 7-byte header, confirming the decoder
/// concatenates fragments before interpreting any field.
#[doc(hidden)]
pub fn build_demo_display_set_fragmented(
    canvas: (u16, u16),
    object: (u16, u16),
    position: (u16, u16),
    palette: &[(u8, [u8; 4])],
    pixels: &[u8],
    fragments: usize,
) -> Vec<u8> {
    fn segment(out: &mut Vec<u8>, pts_90k: u32, seg_type: u8, body: &[u8]) {
        out.extend_from_slice(b"PG");
        out.extend_from_slice(&pts_90k.to_be_bytes());
        out.extend_from_slice(&0u32.to_be_bytes());
        out.push(seg_type);
        out.extend_from_slice(&(body.len() as u16).to_be_bytes());
        out.extend_from_slice(body);
    }

    let fragments = fragments.max(1);

    // Reuse build_demo_display_set to emit the PCS / WDS / PDS prefix
    // verbatim, then splice our fragmented ODS chain in place of its
    // single ODS. Rather than re-derive the prefix, build the canonical
    // single-ODS set and copy everything up to (but not including) its
    // ODS segment, which is the only segment we replace.
    let canonical = build_demo_display_set(canvas, object, position, palette, pixels);
    let mut out = Vec::new();
    let mut cur = 0;
    while cur < canonical.len() {
        let (seg, next) = read_segment(&canonical, cur).expect("demo set is well-formed");
        if seg.seg_type == SEG_ODS || seg.seg_type == SEG_END {
            break;
        }
        out.extend_from_slice(&canonical[cur..next]);
        cur = next;
    }

    // Build the full object payload: object_data_length (u24) + width +
    // height + RLE — identical to the single-segment ODS body minus the
    // per-fragment object_id / version / sequence-flag prefix.
    let rle = demo_rle(object, pixels);
    let obj_data_len = (rle.len() + 4) as u32; // width + height (4) + rle
    let mut payload = Vec::new();
    payload.push(((obj_data_len >> 16) & 0xFF) as u8);
    payload.push(((obj_data_len >> 8) & 0xFF) as u8);
    payload.push((obj_data_len & 0xFF) as u8);
    payload.extend_from_slice(&object.0.to_be_bytes());
    payload.extend_from_slice(&object.1.to_be_bytes());
    payload.extend_from_slice(&rle);

    // Split `payload` into `fragments` near-equal chunks. Each ODS body
    // is: object_id (2) + version (1) + sequence_flag (1) + chunk.
    let chunk_len = payload.len().div_ceil(fragments).max(1);
    let mut offset = 0;
    let mut idx = 0;
    while offset < payload.len() || (idx == 0 && payload.is_empty()) {
        let end = (offset + chunk_len).min(payload.len());
        let chunk = &payload[offset..end];
        let is_first = idx == 0;
        let is_last = end >= payload.len();
        let mut flag = 0u8;
        if is_first {
            flag |= 0x80;
        }
        if is_last {
            flag |= 0x40;
        }
        let mut ods = Vec::new();
        ods.extend_from_slice(&1u16.to_be_bytes()); // object id
        ods.push(0); // object version
        ods.push(flag);
        ods.extend_from_slice(chunk);
        segment(&mut out, 0, SEG_ODS, &ods);
        offset = end;
        idx += 1;
        if is_last {
            break;
        }
    }

    // END.
    segment(&mut out, 0, SEG_END, &[]);
    out
}

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

    #[test]
    fn rle_round_trip_simple() {
        // A 4×1 bitmap: 1 1 0 0 — encoded as two one-pixel runs of colour
        // 1 plus a 2-pixel run of colour 0, then end-of-line.
        let rle: &[u8] = &[0x01, 0x01, 0x00, 0x02, 0x00, 0x00];
        let px = decode_rle(rle, 4, 1).unwrap();
        assert_eq!(px, vec![1, 1, 0, 0]);
    }

    // ---- RLE property sweep ---------------------------------------------
    //
    // The PGS RLE format documented in the module header has narrow rules
    // for short-vs-long runs and a separate "colour 0" branch with three
    // length encodings. The encoder picks the cheapest form per run; the
    // decoder must accept whichever the encoder emitted. These sweeps
    // verify `encode_rle ∘ decode_rle == identity` over a wide spread of
    // indexed bitmaps without external corpora.

    /// Deterministic LCG (same constants the composite tests use). Lets
    /// the sweeps run in plain Rust with no proptest dep.
    fn lcg(state: &mut u64) -> u32 {
        *state = state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (*state >> 32) as u32
    }

    #[test]
    fn rle_roundtrip_random_widths_and_palettes() {
        // Sweep random bitmaps of varying width / height / palette size.
        // For each, encode → decode → check equality.
        let mut st = 0x9e37_79b9_7f4a_7c15u64;
        let mut sampled = 0usize;
        for _ in 0..1_500 {
            let width = ((lcg(&mut st) % 31) + 1) as usize; // 1..=31
            let height = ((lcg(&mut st) % 17) + 1) as usize; // 1..=17
            let palette_size = ((lcg(&mut st) % 12) + 1) as u8; // 1..=12 distinct values incl. 0
            let mut pixels = vec![0u8; width * height];
            for px in &mut pixels {
                *px = (lcg(&mut st) as u8) % palette_size;
            }
            let rle = encode_rle(&pixels, width, height);
            let back = decode_rle(&rle, width, height).unwrap_or_else(|e| {
                panic!(
                    "decode failed on roundtrip w={width} h={height} palette={palette_size}: {e:?}"
                )
            });
            assert_eq!(
                back, pixels,
                "round-trip diverged at w={width} h={height} palette={palette_size}"
            );
            sampled += 1;
        }
        assert_eq!(sampled, 1_500);
    }

    #[test]
    fn rle_roundtrip_long_runs() {
        // Force long-run encoding paths (14-bit length form). A 600-wide
        // row of a single non-zero colour exercises the
        // `0xC0|hi LL CC` branch; the all-transparent row exercises the
        // `0x40|hi LL` branch.
        for colour in [0u8, 1u8, 42u8] {
            for width in [64usize, 100, 256, 600, 1024] {
                let height = 3usize;
                let pixels = vec![colour; width * height];
                let rle = encode_rle(&pixels, width, height);
                let back = decode_rle(&rle, width, height).unwrap();
                assert_eq!(
                    back, pixels,
                    "long-run roundtrip diverged at colour={colour} width={width}"
                );
            }
        }
    }

    #[test]
    fn rle_roundtrip_alternating_short_runs() {
        // Alternating colours mean every run is length 1 — the encoder
        // must emit a literal byte per pixel for colour != 0, and the
        // `0x00 0x01` 2-byte form for each colour-0 pixel.
        let width = 16usize;
        let height = 4usize;
        let mut pixels = vec![0u8; width * height];
        for (i, px) in pixels.iter_mut().enumerate() {
            *px = if i % 2 == 0 { 0 } else { 7 };
        }
        let rle = encode_rle(&pixels, width, height);
        let back = decode_rle(&rle, width, height).unwrap();
        assert_eq!(back, pixels);
    }

    #[test]
    fn rle_roundtrip_one_pixel_rows() {
        // A 1×N bitmap stresses the end-of-line marker between
        // single-pixel rows.
        for height in [1usize, 2, 5, 11] {
            for colour in [0u8, 1u8, 250u8] {
                let pixels = vec![colour; height];
                let rle = encode_rle(&pixels, 1, height);
                let back = decode_rle(&rle, 1, height).unwrap();
                assert_eq!(back, pixels, "1×{height} colour={colour}");
            }
        }
    }

    #[test]
    fn rle_roundtrip_mixed_run_lengths_in_one_row() {
        // A handcrafted row that hits every encoder branch in sequence:
        // 1 literal, 3-singletons, 5-colour-run, 70-colour-run, then
        // 80-zero-run, then 200-zero-run.
        let mut pixels: Vec<u8> = Vec::new();
        pixels.push(9); // 1 literal
        pixels.extend(std::iter::repeat(5).take(3)); // 3 of colour 5 → 3 literals
        pixels.extend(std::iter::repeat(6).take(5)); // 5 of colour 6 → short 3-byte run
        pixels.extend(std::iter::repeat(7).take(70)); // 70 of colour 7 → 14-bit run
        pixels.extend(std::iter::repeat(0).take(80)); // 80 of colour 0 → 14-bit zero run
        pixels.extend(std::iter::repeat(0).take(200)); // a second zero block
        let width = pixels.len();
        let height = 1usize;
        let rle = encode_rle(&pixels, width, height);
        let back = decode_rle(&rle, width, height).unwrap();
        assert_eq!(back, pixels);
    }

    #[test]
    fn rle_size_shrinks_for_long_uniform_runs() {
        // A long, uniform run must shrink in the encoder — that's the
        // whole point of the format. The 14-bit-length form caps a run
        // at 4 bytes including its 2-byte end-of-line, so a 1000-wide
        // single-colour row should land well below the singleton bound.
        let width = 1000usize;
        let pixels = vec![3u8; width];
        let rle = encode_rle(&pixels, width, 1);
        assert!(
            rle.len() < 10,
            "long-run encoding too verbose: {} bytes for 1000-wide flat row",
            rle.len()
        );
    }

    // ---- RLE negative-input sweep ---------------------------------------
    //
    // The decoder must not panic on malformed RLE — that input arrives
    // from PGS payloads off arbitrary disks / networks. These tests pass
    // pathological byte streams in and assert the result is either a
    // graceful `Error::invalid` or a clamped success (the documented
    // behaviour for runs that overshoot the row).

    #[test]
    fn rle_truncated_escape_returns_invalid_not_panic() {
        // Lone 0x00 with no follow-up byte → escape begun, stream ended.
        let err = decode_rle(&[0x00], 4, 1);
        assert!(err.is_err(), "truncated escape must error: {err:?}");
    }

    #[test]
    fn rle_truncated_14bit_length_returns_invalid_not_panic() {
        // 0x00 0x4X marks the 14-bit-length-only form, needs one more byte.
        let err = decode_rle(&[0x00, 0x40], 4, 1);
        assert!(err.is_err(), "truncated 14-bit length must error: {err:?}");
    }

    #[test]
    fn rle_truncated_short_colour_run_returns_invalid_not_panic() {
        // 0x00 0x8L marks the short-colour-run form, needs colour byte.
        let err = decode_rle(&[0x00, 0x82], 4, 1);
        assert!(
            err.is_err(),
            "truncated short colour run must error: {err:?}"
        );
    }

    #[test]
    fn rle_truncated_long_colour_run_returns_invalid_not_panic() {
        // 0x00 0xCX marks the 14-bit-colour-run form, needs LL CC bytes.
        let err = decode_rle(&[0x00, 0xC0], 4, 1);
        assert!(
            err.is_err(),
            "truncated 14-bit colour run must error: {err:?}"
        );
        let err = decode_rle(&[0x00, 0xC0, 0xFF], 4, 1);
        assert!(
            err.is_err(),
            "14-bit colour run missing colour byte must error: {err:?}"
        );
    }

    #[test]
    fn rle_overlong_run_clamps_to_row_without_panic() {
        // The documented decoder behaviour for an over-long run is to
        // clamp to the row end and continue. Build a 4-wide row with a
        // 14-bit run claiming 100 pixels of colour 5, then a normal
        // end-of-line. The 4 pixels of colour 5 must come out cleanly.
        let rle: &[u8] = &[0x00, 0xC0, 0x64, 0x05, 0x00, 0x00];
        let px = decode_rle(rle, 4, 1).unwrap();
        assert_eq!(px, vec![5, 5, 5, 5]);
    }

    #[test]
    fn rle_too_many_lines_returns_invalid_not_panic() {
        // 1-row bitmap fed three end-of-lines: the second EOL pushes
        // `row` past `height` and must error rather than scribble.
        let rle: &[u8] = &[0x00, 0x00, 0x00, 0x00];
        let err = decode_rle(rle, 1, 1);
        assert!(err.is_err(), "extra EOL must error: {err:?}");
    }

    #[test]
    fn rle_pixel_past_end_returns_invalid_not_panic() {
        // A single literal pixel after the final end-of-line means
        // `row >= height` and the decoder hits the post-EOL pixel branch.
        let rle: &[u8] = &[0x01, 0x00, 0x00, 0x02];
        let err = decode_rle(rle, 1, 1);
        assert!(err.is_err(), "pixel past EOL must error: {err:?}");
    }

    #[test]
    fn rle_random_garbage_never_panics() {
        // Feed pseudo-random byte streams to the decoder over a sweep
        // of widths and heights. The result may be Ok or Err but must
        // not panic / corrupt memory / take time disproportionate to
        // the input length.
        let mut st = 0xfeed_face_dead_beefu64;
        for _ in 0..400 {
            let len = (lcg(&mut st) % 128) as usize;
            let mut bytes = vec![0u8; len];
            for b in &mut bytes {
                *b = lcg(&mut st) as u8;
            }
            let width = ((lcg(&mut st) % 17) + 1) as usize;
            let height = ((lcg(&mut st) % 9) + 1) as usize;
            let _ = decode_rle(&bytes, width, height); // just must not panic
        }
    }

    #[test]
    fn rle_roundtrip_all_one_colour_no_zero() {
        // Every pixel is a single non-zero colour. The encoder must
        // produce a single 14-bit-colour-run plus end-of-line.
        let width = 200usize;
        let height = 2usize;
        let pixels = vec![42u8; width * height];
        let rle = encode_rle(&pixels, width, height);
        let back = decode_rle(&rle, width, height).unwrap();
        assert_eq!(back, pixels);
        // Two rows × (one 4-byte 14-bit-run + 2-byte EOL) = 12 bytes is
        // the optimal encoding; we accept up to 16 bytes to allow for
        // any small encoder rearrangement.
        assert!(
            rle.len() <= 16,
            "uniform-row encoding too verbose: {} bytes",
            rle.len()
        );
    }

    #[test]
    fn rle_roundtrip_all_transparent_no_colour() {
        // Every pixel is colour 0. Each row encodes as one transparent
        // run + EOL.
        let width = 300usize;
        let height = 4usize;
        let pixels = vec![0u8; width * height];
        let rle = encode_rle(&pixels, width, height);
        let back = decode_rle(&rle, width, height).unwrap();
        assert_eq!(back, pixels);
        // Per row: 3-byte 14-bit zero run + 2-byte EOL = 5 bytes. ×4 = 20.
        assert!(
            rle.len() <= 28,
            "transparent-row encoding too verbose: {} bytes",
            rle.len()
        );
    }

    #[test]
    fn decodes_tiny_display_set() {
        // 2×2 bitmap: red red / green blue.
        let pixels = [1u8, 1, 2, 3];
        let palette = [
            (0u8, [0u8, 0, 0, 0]), // index 0 → transparent
            (1u8, [255u8, 0, 0, 255]),
            (2u8, [0u8, 255, 0, 255]),
            (3u8, [0u8, 0, 255, 255]),
        ];
        let blob = build_demo_display_set((2, 2), (2, 2), (0, 0), &palette, &pixels);

        let mut dec = make_decoder(&CodecParameters::video(CodecId::new(PGS_CODEC_ID))).unwrap();
        let pkt = Packet::new(0, TimeBase::new(1, 90_000), blob).with_pts(0);
        dec.send_packet(&pkt).unwrap();
        let frame = dec.receive_frame().unwrap();
        let Frame::Video(v) = frame else {
            panic!("expected video frame");
        };
        assert_eq!(v.planes[0].stride, 2 * 4);
        let data = &v.planes[0].data;
        assert_eq!(data.len(), 2 * 2 * 4);
        // Row 0: red, red — the YCbCr round-trip is approximate, so
        // check R dominance + opaque alpha rather than exact bytes.
        let r0c0 = &data[0..4];
        let r0c1 = &data[4..8];
        assert!(
            r0c0[0] > 200 && r0c0[3] == 255,
            "not red-dominant: {:?}",
            r0c0
        );
        assert!(
            r0c1[0] > 200 && r0c1[3] == 255,
            "not red-dominant: {:?}",
            r0c1
        );
        // Row 1: green, blue — same dominance check.
        let g = &data[8..12];
        let b = &data[12..16];
        assert!(
            g[1] > g[0] && g[1] > g[2],
            "green pixel not dominant: {:?}",
            g
        );
        assert!(
            b[2] > b[0] && b[2] > b[1],
            "blue pixel not dominant: {:?}",
            b
        );
    }

    // ---- Fragmented-ODS reassembly --------------------------------------
    //
    // A real PGS muxer splits any object whose data overruns the
    // per-segment size limit across several ODS segments using the
    // first / continuation / last sequence-flag bits, and the decoder
    // must concatenate the fragments before interpreting the
    // object_data_length / width / height header or the RLE. The demo
    // encoder only ever emits a single first+last ODS, so without these
    // tests the `parse_ods_into` reassembly branch is unexercised.

    /// Decode a complete `.sup` display-set blob through the public
    /// decoder and return the single RGBA frame's pixel bytes.
    fn decode_one(blob: Vec<u8>) -> Vec<u8> {
        let mut dec = make_decoder(&CodecParameters::video(CodecId::new(PGS_CODEC_ID))).unwrap();
        let pkt = Packet::new(0, TimeBase::new(1, 90_000), blob).with_pts(0);
        dec.send_packet(&pkt).unwrap();
        let Frame::Video(v) = dec.receive_frame().unwrap() else {
            panic!("expected video frame");
        };
        v.planes[0].data.clone()
    }

    #[test]
    fn fragmented_ods_matches_single_segment() {
        // Same object, encoded as 1 ODS vs. 2..=7 ODS fragments, must
        // decode to byte-identical RGBA. The split points fall at even
        // boundaries of (header ++ rle), so several of these land inside
        // the 7-byte width/height header — proving the decoder defers
        // interpretation until the whole object is reassembled.
        let pixels = [1u8, 1, 2, 3, 0, 1, 2, 3, 3, 2, 1, 0]; // 4×3
        let palette = [
            (0u8, [0u8, 0, 0, 0]),
            (1u8, [255u8, 0, 0, 255]),
            (2u8, [0u8, 255, 0, 255]),
            (3u8, [0u8, 0, 255, 255]),
        ];
        let canvas = (4u16, 3u16);
        let object = (4u16, 3u16);

        let single = decode_one(build_demo_display_set(
            canvas,
            object,
            (0, 0),
            &palette,
            &pixels,
        ));

        for n in 2..=7usize {
            let multi = decode_one(build_demo_display_set_fragmented(
                canvas,
                object,
                (0, 0),
                &palette,
                &pixels,
                n,
            ));
            assert_eq!(
                multi, single,
                "fragmented ODS ({n} segments) decoded differently from single-segment"
            );
        }
    }

    #[test]
    fn fragmented_ods_split_inside_header() {
        // A tiny 1×1 object whose total payload (7-byte header + a couple
        // of RLE bytes) is split into more fragments than it has bytes:
        // every fragment is at most one byte, so the very first boundary
        // is inside the object_data_length field. Reassembly must still
        // produce the correct single opaque pixel.
        let pixels = [1u8];
        let palette = [(0u8, [0u8, 0, 0, 0]), (1u8, [10u8, 200, 30, 255])];
        let blob = build_demo_display_set_fragmented((1, 1), (1, 1), (0, 0), &palette, &pixels, 32);
        let data = decode_one(blob);
        assert_eq!(data.len(), 4);
        // Green-dominant, opaque.
        assert!(
            data[1] > data[0] && data[1] > data[2] && data[3] == 255,
            "expected opaque green-dominant pixel, got {:?}",
            data
        );
    }

    #[test]
    fn incomplete_object_without_last_fragment_is_dropped_not_rendered() {
        // A first-but-never-last ODS leaves the object incomplete. The
        // decoder must not render a partial object; it emits the
        // canvas-sized frame with that composition object absent
        // (fully transparent here, since it's the only object).
        let pixels = [1u8, 1, 1, 1]; // 2×2
        let palette = [(0u8, [0u8, 0, 0, 0]), (1u8, [200u8, 0, 0, 255])];
        // Build the canonical set, then drop the END-terminating `last`
        // flag from its ODS by re-emitting only a `first` fragment.
        let frag2 = build_demo_display_set_fragmented((2, 2), (2, 2), (0, 0), &palette, &pixels, 2);
        // Keep everything up to and including the FIRST ODS fragment, then
        // splice in an END — so the decoder sees a first-without-last.
        let mut truncated = Vec::new();
        let mut cur = 0;
        let mut seen_first_ods = false;
        while cur < frag2.len() {
            let (seg, next) = read_segment(&frag2, cur).unwrap();
            if seg.seg_type == SEG_END {
                break;
            }
            truncated.extend_from_slice(&frag2[cur..next]);
            cur = next;
            if seg.seg_type == SEG_ODS {
                seen_first_ods = true;
                break;
            }
        }
        assert!(seen_first_ods, "expected to capture the first ODS fragment");
        // Terminating END (13-byte header, empty body).
        truncated.extend_from_slice(b"PG");
        truncated.extend_from_slice(&0u32.to_be_bytes());
        truncated.extend_from_slice(&0u32.to_be_bytes());
        truncated.push(SEG_END);
        truncated.extend_from_slice(&0u16.to_be_bytes());

        let data = decode_one(truncated);
        assert_eq!(data.len(), 2 * 2 * 4);
        for chunk in data.chunks(4) {
            assert_eq!(
                chunk,
                &[0, 0, 0, 0],
                "incomplete object must not paint any pixel"
            );
        }
    }
}