cc-data 0.10.0

Closed-caption cc_data() carriage (CEA-608/708), per ETSI TS 101 154 Table B.9.
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
//! CEA-608 (line-21) caption decode — ANSI/CTA-608-E.
//!
//! Decodes the line-21 two-byte control / character codes that the
//! [`crate::CcData`] carriage demuxes (`cc_type` 0 = field 1, 1 = field 2) into a
//! caption screen. Implements the control-code state machine of
//! `private/specs-verified/captions/cc-data/decode/cea608-decode.md`:
//!
//! - pop-on (RCL/EOC), roll-up (RU2/RU3/RU4 + CR), paint-on (RDC) modes,
//! - Preamble Address Codes (row + indent + colour/italics/underline),
//! - mid-row colour/italics codes, tab offsets,
//! - the standard (Table 50), special (Table 49) and extended Western-European
//!   (Tables 5–10, automatic-backspace) character sets,
//! - the four data channels CC1–CC4, control-code doubling, and field-2 XDS
//!   detect-and-skip.
//!
//! Bytes carry odd parity in b7; this decoder strips parity (masks b7) to the
//! 7-bit value before classifying.

use crate::cc_data::{CcTriplet, CcType};
use alloc::string::String;
use alloc::vec::Vec;

/// Foreground colour of a line-21 caption cell (CTA-608-E Tables 51/53).
///
/// Returned by [`Cea608StyledChar::color`]; corresponds to the 3-bit colour
/// index in PAC / mid-row code tables.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Cea608Color {
    /// White (default).
    #[default]
    White,
    /// Green.
    Green,
    /// Blue.
    Blue,
    /// Cyan.
    Cyan,
    /// Red.
    Red,
    /// Yellow.
    Yellow,
    /// Magenta.
    Magenta,
}

impl Cea608Color {
    /// Label per the project's `name()` convention.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::White => "white",
            Self::Green => "green",
            Self::Blue => "blue",
            Self::Cyan => "cyan",
            Self::Red => "red",
            Self::Yellow => "yellow",
            Self::Magenta => "magenta",
        }
    }

    /// From the 3-bit colour index used in PAC and mid-row tables (Tables 51/53).
    #[must_use]
    pub(super) fn from_idx(idx: u8) -> Self {
        match idx & 0x07 {
            0 => Self::White,
            1 => Self::Green,
            2 => Self::Blue,
            3 => Self::Cyan,
            4 => Self::Red,
            5 => Self::Yellow,
            6 => Self::Magenta,
            _ => Self::White,
        }
    }
}
broadcast_common::impl_spec_display!(Cea608Color);

/// Number of caption rows on a line-21 screen (§3.2.2).
const SCREEN_ROWS: usize = 15;
/// Number of caption columns on a line-21 screen.
const SCREEN_COLS: usize = 32;

// ── Misc-control 2nd-byte values (Table 52, data-channel-1 column) ────────────
const MC_RCL: u8 = 0x20;
const MC_BS: u8 = 0x21;
const MC_DER: u8 = 0x24;
const MC_RU2: u8 = 0x25;
const MC_RU3: u8 = 0x26;
const MC_RU4: u8 = 0x27;
const MC_FON: u8 = 0x28;
const MC_RDC: u8 = 0x29;
const MC_TR: u8 = 0x2A;
const MC_RTD: u8 = 0x2B;
const MC_EDM: u8 = 0x2C;
const MC_CR: u8 = 0x2D;
const MC_ENM: u8 = 0x2E;
const MC_EOC: u8 = 0x2F;

// ── Tab offsets (Table 52): first byte 0x17/0x1F, 2nd byte 0x21–0x23 ──────────
const TAB_FIRST_C1: u8 = 0x17;
const TAB_FIRST_C2: u8 = 0x1F;
const TAB1: u8 = 0x21;
const TAB3: u8 = 0x23;

/// The caption mode (§6.1, §7).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Cea608Mode {
    /// No mode selected yet.
    #[default]
    None,
    /// Pop-on (RCL → load to back buffer → EOC flips).
    PopOn,
    /// Roll-up with the given number of rows (2/3/4).
    RollUp(u8),
    /// Paint-on (RDC → paint to displayed memory).
    PaintOn,
    /// Text mode (TR/RTD).
    Text,
}

impl Cea608Mode {
    /// Label per the project's `name()` convention.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::None => "none",
            Self::PopOn => "pop_on",
            Self::RollUp(_) => "roll_up",
            Self::PaintOn => "paint_on",
            Self::Text => "text",
        }
    }
}
broadcast_common::impl_spec_display!(Cea608Mode);

/// A line-21 caption data channel (Table 1, §4.1): the eight CC/Text logical
/// services keyed by field + data-channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Cea608Channel {
    /// CC1 — field 1, data channel 1 (primary).
    Cc1,
    /// CC2 — field 1, data channel 2.
    Cc2,
    /// CC3 — field 2, data channel 1 (secondary).
    Cc3,
    /// CC4 — field 2, data channel 2.
    Cc4,
}

impl Cea608Channel {
    /// The channel's number in `CC1`..`CC4`, 1 to 4.
    #[must_use]
    pub fn number(self) -> u8 {
        match self {
            Self::Cc1 => 1,
            Self::Cc2 => 2,
            Self::Cc3 => 3,
            Self::Cc4 => 4,
        }
    }

    /// Index 0–3 into the decoder's per-channel state.
    #[must_use]
    fn index(self) -> usize {
        match self {
            Self::Cc1 => 0,
            Self::Cc2 => 1,
            Self::Cc3 => 2,
            Self::Cc4 => 3,
        }
    }
    /// Label per the project's `name()` convention.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Cc1 => "cc1",
            Self::Cc2 => "cc2",
            Self::Cc3 => "cc3",
            Self::Cc4 => "cc4",
        }
    }
}
broadcast_common::impl_spec_display!(Cea608Channel);

/// A styled character cell on a 608 caption screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Cea608StyledChar {
    /// The glyph.
    pub ch: char,
    /// Underline attribute.
    pub underline: bool,
    /// Italics attribute.
    pub italics: bool,
    /// Foreground colour (CTA-608-E Tables 51/53).
    pub color: Cea608Color,
}

impl Default for Cea608StyledChar {
    fn default() -> Self {
        Cea608StyledChar {
            ch: ' ',
            underline: false,
            italics: false,
            color: Cea608Color::White,
        }
    }
}

/// One row of a 608 caption screen.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Cea608Row {
    /// The styled cells (sparse: only populated cells present, indexed by column).
    cells: Vec<(usize, Cea608StyledChar)>,
}

impl Cea608Row {
    fn set(&mut self, col: usize, c: Cea608StyledChar) {
        if let Some(slot) = self.cells.iter_mut().find(|(i, _)| *i == col) {
            slot.1 = c;
        } else {
            self.cells.push((col, c));
        }
    }
    fn clear_from(&mut self, col: usize) {
        self.cells.retain(|(i, _)| *i < col);
    }
    fn remove(&mut self, col: usize) {
        self.cells.retain(|(i, _)| *i != col);
    }
    /// The row's text (cells sorted by column, gaps filled with spaces).
    #[must_use]
    pub fn text(&self) -> String {
        let mut sorted = self.cells.clone();
        sorted.sort_by_key(|(i, _)| *i);
        let mut out = String::new();
        let mut last = None;
        for (i, c) in sorted {
            if let Some(prev) = last {
                for _ in (prev + 1)..i {
                    out.push(' ');
                }
            }
            out.push(c.ch);
            last = Some(i);
        }
        out
    }
    /// Styled cells in column order.
    #[must_use]
    pub fn styled_cells(&self) -> Vec<(usize, Cea608StyledChar)> {
        let mut sorted = self.cells.clone();
        sorted.sort_by_key(|(i, _)| *i);
        sorted
    }
}

/// A 608 caption screen — `SCREEN_ROWS` rows of styled cells.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Cea608Screen {
    rows: [Cea608Row; SCREEN_ROWS],
}

impl Cea608Screen {
    /// The screen text: non-empty rows joined with `\n`, trailing spaces trimmed.
    #[must_use]
    pub fn text(&self) -> String {
        let mut out = String::new();
        for row in &self.rows {
            let line = row.text();
            let trimmed = line.trim_end();
            if trimmed.is_empty() {
                continue;
            }
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(trimmed);
        }
        out
    }
    /// All rows (including empty ones).
    #[must_use]
    pub fn rows(&self) -> &[Cea608Row; SCREEN_ROWS] {
        &self.rows
    }
}

/// Current pen attribute set by a PAC / mid-row code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Pen {
    underline: bool,
    italics: bool,
    color: Cea608Color,
}

impl Default for Pen {
    fn default() -> Self {
        Pen {
            underline: false,
            italics: false,
            color: Cea608Color::White,
        }
    }
}

/// Per-channel caption state (displayed + non-displayed memory, mode, cursor).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ChannelState {
    displayed: Cea608Screen,
    nondisplayed: Cea608Screen,
    text: Cea608Screen,
    mode: Cea608Mode,
    rollup_rows: u8,
    cursor_row: usize,
    cursor_col: usize,
    pen: Pen,
}

impl ChannelState {
    /// The active memory for the current mode (pop-on writes to non-displayed;
    /// roll-up / paint-on write to displayed).
    fn active_mut(&mut self) -> &mut Cea608Screen {
        match self.mode {
            Cea608Mode::PopOn => &mut self.nondisplayed,
            Cea608Mode::Text => &mut self.text,
            _ => &mut self.displayed,
        }
    }
}

/// CEA-608 (line-21) caption decoder.
///
/// Feed it [`CcTriplet`]s (or raw byte pairs) of the 608 fields; read decoded
/// text per channel via [`channel_text`](Cea608Decoder::channel_text) /
/// [`screen`](Cea608Decoder::screen).
///
/// ```
/// use cc_data::decode::{Cea608Decoder, Cea608Channel};
/// let mut dec = Cea608Decoder::new();
/// // RCL, PAC row 15, "HI", EOC — a pop-on caption on CC1 (field 1).
/// dec.push_pair(false, 0x14, 0x20); // RCL (field 1 → CC1)
/// dec.push_pair(false, 0x14, 0x20); // doubled control — ignored
/// dec.push_pair(false, 0x14, 0x70); // PAC row 15 indent 0 (field 1)
/// dec.push_pair(false, b'H', b'I');
/// dec.push_pair(false, 0x14, 0x2F); // EOC → flip
/// assert_eq!(dec.channel_text(Cea608Channel::Cc1), "HI");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cea608Decoder {
    channels: [ChannelState; 4],
    /// The control pair last acted on, per field, for doubling suppression.
    last_control: [Option<(u8, u8)>; 2],
    /// The channel targeted by the last control code seen on each field.
    /// Standard (non-tagged) characters are routed here, per field, since
    /// CEA-608 encodes which channel a character belongs to only implicitly,
    /// via the most recent control code on that field.
    last_channel: [Cea608Channel; 2],
    xds_active: bool,
    /// Bit `Cea608Channel::index` set once a displayable character has been
    /// written to that channel outside text mode.
    caption_text_seen: u8,
}

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

impl Cea608Decoder {
    /// A new decoder.
    #[must_use]
    pub fn new() -> Self {
        Cea608Decoder {
            channels: Default::default(),
            last_control: [None, None],
            last_channel: [Cea608Channel::Cc1, Cea608Channel::Cc3],
            xds_active: false,
            caption_text_seen: 0,
        }
    }

    /// Feed the decoder the 608 (line-21) triplets of a [`crate::CcData`].
    pub fn push_triplets<'a, I>(&mut self, triplets: I)
    where
        I: IntoIterator<Item = &'a CcTriplet>,
    {
        for t in triplets {
            if !t.cc_valid {
                continue;
            }
            let field2 = match t.cc_type {
                CcType::Ntsc608Field1 => false,
                CcType::Ntsc608Field2 => true,
                _ => continue,
            };
            self.process_pair(field2, t.cc_data_1, t.cc_data_2);
        }
    }

    /// Feed one raw 608 byte pair. `field2 = false` ⇒ field 1 (`cc_type` 0);
    /// `field2 = true` ⇒ field 2 (`cc_type` 1). Bytes may carry parity in b7.
    pub fn push_pair(&mut self, field2: bool, b1: u8, b2: u8) {
        self.process_pair(field2, b1, b2);
    }

    fn process_pair(&mut self, field2: bool, raw1: u8, raw2: u8) {
        let b1 = raw1 & 0x7F;
        let b2 = raw2 & 0x7F;
        let field_idx = usize::from(field2);

        // Null filler (0x00 0x00): separates control pairs, so a control after it
        // is not a doubled copy (CTA-608-E Annex B.14; private/specs-verified/captions/cc-data/decode/cea608-decode.md).
        if b1 == 0x00 && b2 == 0x00 {
            self.last_control[field_idx] = None;
            return;
        }

        // XDS (field 2 only): a control pair with first byte 0x01–0x0F begins or
        // continues an XDS sub-packet; 0x0F + checksum ends it. Detect + skip the
        // whole span (we never decode XDS into captions).
        if field2 && (0x01..=0x0F).contains(&b1) {
            // 0x0F = End control (followed by a checksum byte); otherwise
            // Start/Continue. Either way this pair is XDS, not caption.
            self.xds_active = b1 != 0x0F;
            return;
        }

        // Control codes: first byte 0x10–0x1F. CTA-608 lets a caption control
        // code interrupt an open XDS sub-packet (XDS resumes afterwards with a
        // Continue code), so this check runs BEFORE the xds_active short-circuit
        // below — otherwise every caption code sent while XDS is open would be
        // swallowed along with the XDS payload.
        if (0x10..=0x1F).contains(&b1) {
            // Doubling: an identical control pair immediately repeated is one cmd.
            if self.last_control[field_idx] == Some((b1, b2)) {
                self.last_control[field_idx] = None; // consume the doubled copy
                return;
            }
            self.last_control[field_idx] = Some((b1, b2));
            self.xds_active = false;
            self.handle_control(field2, b1, b2);
            return;
        }
        // Any pair while an XDS sub-packet is open (field 2) is XDS payload
        // (informational chars 0x20–0x7F or null) until the End control closes it.
        if field2 && self.xds_active {
            return;
        }

        // First bytes 0x01–0x0F are reserved for XDS (field 2 only) and never
        // carry caption text on field 1 (CTA-608-E §8.6.1; private/specs-verified/captions/cc-data/decode/cea608-decode.md).
        if (0x01..=0x0F).contains(&b1) {
            self.last_control[field_idx] = None;
            return;
        }

        // Displayable characters: first byte 0x20–0x7F.
        self.last_control[field_idx] = None;
        self.xds_active = false;
        // Standard chars are not channel-tagged; route to the channel targeted
        // by the last control code seen on this field.
        let ch = self.last_channel[field_idx];
        if b1 >= 0x20 {
            self.put_char(ch, Self::standard_char(b1));
        }
        if b2 >= 0x20 {
            self.put_char(ch, Self::standard_char(b2));
        }
    }

    /// The control-code handler. `b1` 0x10–0x1F, `b2` 0x20–0x7F (7-bit).
    fn handle_control(&mut self, field2: bool, b1: u8, b2: u8) {
        // Determine data channel from the first byte. For field 1: 0x10–0x17 =
        // C1, 0x18–0x1F = C2. For field 2: same first-byte split selects C1/C2
        // for every category EXCEPT Miscellaneous Control Codes, which use a
        // shifted pair of their own on field 2 (CTA-608-E §8.4 a/b, cited in
        // `private/specs-verified/captions/cc-data/decode/cea608-decode.md`): field-1 `0x14`(C1)/`0x1C`(C2) become
        // field-2 `0x15`(C1/CC3)/`0x1D`(C2/CC4). That shift only applies to
        // misc-control's own 2nd-byte range (`0x20`-`0x2F`); `0x15`/`0x1D` with
        // a 2nd byte outside it (e.g. a PAC row byte, `0x40`-`0x7F`) is not
        // misc-control and folds the ordinary way (issue #1043 — the previous
        // fold recognised only field-1's `0x14`/`0x1C`, so field-2 misc-control
        // pairs never matched and were silently dropped).
        let field2_misc = field2 && (0x20..=0x2F).contains(&b2) && matches!(b1, 0x15 | 0x1D);
        let c2 = if field2_misc { b1 == 0x1D } else { b1 >= 0x18 };
        let base1 = if field2_misc {
            0x14
        } else if c2 {
            b1 - 0x08 // fold C2 onto C1 range
        } else {
            b1
        };
        let ch = self.channel_for(field2, c2);
        // Every control code updates the field's "current channel", so
        // subsequent untagged standard characters route to it (CC-W1).
        self.last_channel[usize::from(field2)] = ch;

        // Misc control: first byte 0x14 (C1) / 0x1C (C2), or the field-2
        // `field2_misc` fold above.
        if base1 == 0x14 && (0x20..=0x2F).contains(&b2) {
            self.misc_control(ch, b2);
            return;
        }
        // Tab offsets: first byte 0x17 (C1) / 0x1F (C2), 2nd 0x21–0x23.
        if (b1 == TAB_FIRST_C1 || b1 == TAB_FIRST_C2) && (TAB1..=TAB3).contains(&b2) {
            let n = (b2 - TAB1 + 1) as usize;
            let st = &mut self.channels[ch.index()];
            st.cursor_col = (st.cursor_col + n).min(SCREEN_COLS - 1);
            return;
        }
        // Mid-row codes: first byte 0x11 (C1) / 0x19 (C2), 2nd 0x20–0x2F.
        if base1 == 0x11 && (0x20..=0x2F).contains(&b2) {
            self.mid_row(ch, b2);
            return;
        }
        // Special characters: first byte 0x11/0x19, 2nd 0x30–0x3F.
        if base1 == 0x11 && (0x30..=0x3F).contains(&b2) {
            self.put_char(ch, Self::special_char(b2));
            return;
        }
        // Extended chars block 1: first byte 0x12/0x1A, 2nd 0x20–0x3F.
        if base1 == 0x12 && (0x20..=0x3F).contains(&b2) {
            self.put_extended(ch, Self::extended_char_block1(b2));
            return;
        }
        // Extended chars block 2: first byte 0x13/0x1B, 2nd 0x20–0x3F.
        if base1 == 0x13 && (0x20..=0x3F).contains(&b2) {
            self.put_extended(ch, Self::extended_char_block2(b2));
            return;
        }
        // PAC: 2nd byte 0x40–0x7F (any control first byte).
        if (0x40..=0x7F).contains(&b2) {
            self.pac(field2, ch, b1, b2);
        }
        // Background/foreground attr codes (0x10/0x18 2nd 0x20–0x2F) — ignored
        // for text extraction.
    }

    /// Miscellaneous control codes (RCL/RU2-4/RDC/CR/EDM/ENM/EOC/DER/BS …).
    fn misc_control(&mut self, ch: Cea608Channel, code: u8) {
        let st = &mut self.channels[ch.index()];
        match code {
            MC_RCL => {
                // RCL only selects pop-on style: it does NOT erase the
                // non-displayed memory (that is ENM's job). Real captions
                // re-issue RCL after loading text and before the EDM/EOC pair
                // that pops it on (libcaption `tos.scc`, pycaption
                // `example.scc`); clearing here discarded the whole caption.
                st.mode = Cea608Mode::PopOn;
                st.cursor_row = 0;
                st.cursor_col = 0;
            }
            MC_RU2 | MC_RU3 | MC_RU4 => {
                let rows = match code {
                    MC_RU2 => 2,
                    MC_RU3 => 3,
                    _ => 4,
                };
                st.mode = Cea608Mode::RollUp(rows);
                st.rollup_rows = rows;
                // base row defaults to bottom (row 15 → index 14)
                st.cursor_row = SCREEN_ROWS - 1;
                st.cursor_col = 0;
                st.pen = Pen::default();
            }
            MC_RDC => {
                st.mode = Cea608Mode::PaintOn;
            }
            MC_CR => {
                self.carriage_return(ch);
            }
            MC_EDM => {
                st.displayed = Cea608Screen::default();
            }
            MC_ENM => {
                st.nondisplayed = Cea608Screen::default();
            }
            MC_EOC => {
                // flip non-displayed ↔ displayed (pop-on)
                core::mem::swap(&mut st.displayed, &mut st.nondisplayed);
            }
            MC_BS if st.cursor_col > 0 => {
                st.cursor_col -= 1;
                let row = st.cursor_row.min(SCREEN_ROWS - 1);
                let col = st.cursor_col;
                st.active_mut().rows[row].remove(col);
            }
            MC_DER => {
                let row = st.cursor_row.min(SCREEN_ROWS - 1);
                let col = st.cursor_col;
                st.active_mut().rows[row].clear_from(col);
            }
            MC_TR => {
                st.mode = Cea608Mode::Text;
                st.text = Cea608Screen::default();
                st.cursor_row = 0;
                st.cursor_col = 0;
            }
            MC_RTD => {
                st.mode = Cea608Mode::Text;
            }
            MC_FON => {}
            _ => {}
        }
    }

    /// Carriage Return in roll-up: roll the window up one row, clear the base row.
    fn carriage_return(&mut self, ch: Cea608Channel) {
        let st = &mut self.channels[ch.index()];
        if let Cea608Mode::RollUp(rows) = st.mode {
            let base = st.cursor_row.min(SCREEN_ROWS - 1);
            let rows = rows as usize;
            let top = base.saturating_sub(rows - 1);
            for r in top..base {
                st.displayed.rows[r] = st.displayed.rows[r + 1].clone();
            }
            st.displayed.rows[base] = Cea608Row::default();
            st.cursor_col = 0;
        } else {
            // In other modes, CR is uncommon; just move cursor down.
            if st.cursor_row + 1 < SCREEN_ROWS {
                st.cursor_row += 1;
            }
            st.cursor_col = 0;
        }
    }

    /// Mid-row code (Table 51): sets colour/italics + underline from the cursor.
    fn mid_row(&mut self, ch: Cea608Channel, b2: u8) {
        let idx = (b2 - 0x20) as usize; // 0x20..0x2F → 0..15
        let underline = idx & 0x01 != 0;
        let color_idx = (idx >> 1) as u8;
        let (color, italics) = if color_idx <= 6 {
            (Cea608Color::from_idx(color_idx), false)
        } else {
            (Cea608Color::White, true) // 0x2E/0x2F = italics
        };
        let st = &mut self.channels[ch.index()];
        st.pen = Pen {
            underline,
            italics,
            color,
        };
        // mid-row occupies one cell (a space carrying the attribute)
        self.put_char(ch, ' ');
    }

    /// Preamble Address Code: set row + indent / colour + underline (Table 53).
    fn pac(&mut self, _field2: bool, ch: Cea608Channel, b1: u8, b2: u8) {
        // Fold the C2 first byte (0x18–0x1F) onto the C1 first byte (0x10–0x17).
        let f = if b1 >= 0x18 { b1 - 0x08 } else { b1 };
        // Row group from the first byte (Table 53 top block, C1 column).
        let row_pair = match f {
            0x11 => 1,  // rows 1–2
            0x12 => 3,  // rows 3–4
            0x15 => 5,  // rows 5–6
            0x16 => 7,  // rows 7–8
            0x17 => 9,  // rows 9–10
            0x10 => 11, // row 11
            0x13 => 12, // rows 12–13
            0x14 => 14, // rows 14–15
            _ => 1,
        };
        // Second byte high bit picks the row within the pair (0x40–0x5F = first
        // of pair, 0x60–0x7F = second).
        let second_of_pair = b2 >= 0x60;
        let row = if f == 0x10 {
            11 // row 11 has no pair partner
        } else if second_of_pair {
            row_pair + 1
        } else {
            row_pair
        };
        let row = row.clamp(1, SCREEN_ROWS); // 1-based
        let attr = b2 & 0x1F; // low 5 bits (drop the col-A/B high nibble)
        let underline = attr & 0x01 != 0;

        let (color, italics, indent) = if attr >= 0x10 {
            // Indent codes 0x10..0x1F → indent 0..28 in steps of 4, colour white.
            let indent = ((attr - 0x10) >> 1) as usize * 4;
            (Cea608Color::White, false, indent)
        } else {
            // Colour/italics codes 0x00..0x0F.
            let color_idx = attr >> 1;
            let (c, it) = if color_idx <= 6 {
                (Cea608Color::from_idx(color_idx), false)
            } else {
                (Cea608Color::White, true)
            };
            (c, it, 0)
        };

        let st = &mut self.channels[ch.index()];
        st.cursor_row = (row - 1).min(SCREEN_ROWS - 1);
        st.cursor_col = indent.min(SCREEN_COLS - 1);
        st.pen = Pen {
            underline,
            italics,
            color,
        };
    }

    /// Put a standard / special character at the cursor, advancing it.
    fn put_char(&mut self, ch: Cea608Channel, c: char) {
        let st = &mut self.channels[ch.index()];
        if st.mode != Cea608Mode::Text {
            self.caption_text_seen |= 1 << ch.index();
        }
        let row = st.cursor_row.min(SCREEN_ROWS - 1);
        let col = st.cursor_col;
        if col >= SCREEN_COLS {
            return;
        }
        let pen = st.pen;
        let styled = Cea608StyledChar {
            ch: c,
            underline: pen.underline,
            italics: pen.italics,
            color: pen.color,
        };
        st.active_mut().rows[row].set(col, styled);
        st.cursor_col = (col + 1).min(SCREEN_COLS);
    }

    /// Put an extended char: automatic backspace first (erase the fallback char
    /// the provider sent), then the glyph.
    fn put_extended(&mut self, ch: Cea608Channel, c: char) {
        {
            let st = &mut self.channels[ch.index()];
            if st.cursor_col > 0 {
                st.cursor_col -= 1;
                let row = st.cursor_row.min(SCREEN_ROWS - 1);
                let col = st.cursor_col;
                st.active_mut().rows[row].remove(col);
            }
        }
        self.put_char(ch, c);
    }

    /// Resolve the data channel for a control pair.
    fn channel_for(&self, field2: bool, c2: bool) -> Cea608Channel {
        match (field2, c2) {
            (false, false) => Cea608Channel::Cc1,
            (false, true) => Cea608Channel::Cc2,
            (true, false) => Cea608Channel::Cc3,
            (true, true) => Cea608Channel::Cc4,
        }
    }

    /// Whether caption text (a displayable character outside text mode) has
    /// been written to `channel` since this decoder was created. Control codes,
    /// XDS and null padding alone never set it.
    #[must_use]
    pub fn has_caption_text(&self, channel: Cea608Channel) -> bool {
        self.caption_text_seen & (1 << channel.index()) != 0
    }

    /// The displayed screen for a channel.
    #[must_use]
    pub fn screen(&self, channel: Cea608Channel) -> &Cea608Screen {
        &self.channels[channel.index()].displayed
    }

    /// The current mode for a channel.
    #[must_use]
    pub fn mode(&self, channel: Cea608Channel) -> Cea608Mode {
        self.channels[channel.index()].mode
    }

    /// The decoded displayed text for a channel.
    #[must_use]
    pub fn channel_text(&self, channel: Cea608Channel) -> String {
        self.channels[channel.index()].displayed.text()
    }

    // ── Character tables ──────────────────────────────────────────────────────

    /// Standard character set (Table 50): 7-bit `0x20`–`0x7F` → glyph.
    fn standard_char(b: u8) -> char {
        match b {
            0x2A => '\u{00E1}', // á
            0x5C => '\u{00E9}', // é
            0x5E => '\u{00ED}', // í
            0x5F => '\u{00F3}', // ó
            0x60 => '\u{00FA}', // ú
            0x7B => '\u{00E7}', // ç
            0x7C => '\u{00F7}', // ÷
            0x7D => '\u{00D1}', // Ñ
            0x7E => '\u{00F1}', // ñ
            0x7F => '\u{25A0}', // ■
            _ => char::from(b), // ASCII otherwise
        }
    }

    /// Special characters (Table 49): 2nd byte 0x30–0x3F.
    fn special_char(b2: u8) -> char {
        match b2 {
            0x30 => '\u{00AE}', // ®
            0x31 => '\u{00B0}', // °
            0x32 => '\u{00BD}', // ½
            0x33 => '\u{00BF}', // ¿
            0x34 => '\u{2122}', // ™
            0x35 => '\u{00A2}', // ¢
            0x36 => '\u{00A3}', // £
            0x37 => '\u{266A}', // ♪
            0x38 => '\u{00E0}', // à
            0x39 => ' ',        // transparent space
            0x3A => '\u{00E8}', // è
            0x3B => '\u{00E2}', // â
            0x3C => '\u{00EA}', // ê
            0x3D => '\u{00EE}', // î
            0x3E => '\u{00F4}', // ô
            0x3F => '\u{00FB}', // û
            _ => '?',
        }
    }

    /// Extended Western-European block 1 (first byte 0x12/0x1A; Tables 5–7).
    fn extended_char_block1(b2: u8) -> char {
        match b2 {
            // Spanish (Table 5)
            0x20 => '\u{00C1}', // Á
            0x21 => '\u{00C9}', // É
            0x22 => '\u{00D3}', // Ó
            0x23 => '\u{00DA}', // Ú
            0x24 => '\u{00DC}', // Ü
            0x25 => '\u{00FC}', // ü
            0x26 => '\u{2018}', // ‘
            0x27 => '\u{00A1}', // ¡
            // Misc (Table 6)
            0x28 => '*',
            0x29 => '\'',
            0x2A => '\u{2014}', // —
            0x2B => '\u{00A9}', // ©
            0x2C => '\u{2120}', // ℠
            0x2D => '\u{2022}', // •
            0x2E => '\u{201C}', // "
            0x2F => '\u{201D}', // "
            // French (Table 7)
            0x30 => '\u{00C0}', // À
            0x31 => '\u{00C2}', // Â
            0x32 => '\u{00C7}', // Ç
            0x33 => '\u{00C8}', // È
            0x34 => '\u{00CA}', // Ê
            0x35 => '\u{00CB}', // Ë
            0x36 => '\u{00EB}', // ë
            0x37 => '\u{00CE}', // Î
            0x38 => '\u{00CF}', // Ï
            0x39 => '\u{00EF}', // ï
            0x3A => '\u{00D4}', // Ô
            0x3B => '\u{00D9}', // Ù
            0x3C => '\u{00F9}', // ù
            0x3D => '\u{00DB}', // Û
            0x3E => '\u{00AB}', // «
            0x3F => '\u{00BB}', // »
            _ => '?',
        }
    }

    /// Extended Western-European block 2 (first byte 0x13/0x1B; Tables 8–10).
    fn extended_char_block2(b2: u8) -> char {
        match b2 {
            // Portuguese (Table 8)
            0x20 => '\u{00C3}', // Ã
            0x21 => '\u{00E3}', // ã
            0x22 => '\u{00CD}', // Í
            0x23 => '\u{00CC}', // Ì
            0x24 => '\u{00EC}', // ì
            0x25 => '\u{00D2}', // Ò
            0x26 => '\u{00F2}', // ò
            0x27 => '\u{00D5}', // Õ
            0x28 => '\u{00F5}', // õ
            0x29 => '{',
            0x2A => '}',
            0x2B => '\\',
            0x2C => '^',
            0x2D => '_',
            0x2E => '|',
            0x2F => '~',
            // German (Table 9)
            0x30 => '\u{00C4}', // Ä
            0x31 => '\u{00E4}', // ä
            0x32 => '\u{00D6}', // Ö
            0x33 => '\u{00F6}', // ö
            0x34 => '\u{00DF}', // ß
            0x35 => '\u{00A5}', // ¥
            0x36 => '\u{00A4}', // ¤
            0x37 => '|',
            // Danish (Table 10)
            0x38 => '\u{00C5}', // Å
            0x39 => '\u{00E5}', // å
            0x3A => '\u{00D8}', // Ø
            0x3B => '\u{00F8}', // ø
            0x3C => '\u{231C}', // ⌜
            0x3D => '\u{231D}', // ⌝
            0x3E => '\u{231E}', // ⌞
            0x3F => '\u{231F}', // ⌟
            _ => '?',
        }
    }
}

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

    /// Pop-on caption: RCL, PAC row 15 indent 0, "HI", EOC → on-screen "HI".
    #[test]
    fn pop_on_caption() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15 (col B), white indent0
        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC → flip to displayed
        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "HI");
        assert_eq!(dec.mode(Cea608Channel::Cc1), Cea608Mode::PopOn);
    }

    /// RCL selects pop-on without erasing non-displayed memory: text loaded,
    /// then RCL again, then EDM + EOC (the sequence real SCC files use) still
    /// pops the loaded text on. Regression for a decoder that cleared the
    /// non-displayed buffer on every RCL.
    #[test]
    fn rcl_does_not_erase_loaded_text() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15
        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL again
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2C)); // EDM
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC
        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "HI");
    }

    /// ENM, not RCL, is what erases non-displayed memory.
    #[test]
    fn enm_erases_loaded_text() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70));
        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2E)); // ENM
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC
        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "");
    }

    /// Control-code doubling: a repeated RCL pair acts once.
    #[test]
    fn control_doubling() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // RDC
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // doubled — ignored
        assert_eq!(dec.mode(Cea608Channel::Cc1), Cea608Mode::PaintOn);
        // a non-doubled second RDC after a non-control acts again
        dec.push_pair(false, set_odd_parity(b'X'), set_odd_parity(0x00));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2C)); // EDM
    }

    /// Roll-up across ≥2 rows: RU2, write line 1, CR, write line 2.
    #[test]
    fn roll_up_two_rows() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x25)); // RU2
        dec.push_pair(false, set_odd_parity(b'A'), set_odd_parity(b'B'));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2D)); // CR
        dec.push_pair(false, set_odd_parity(b'C'), set_odd_parity(b'D'));
        let text = dec.channel_text(Cea608Channel::Cc1);
        assert!(text.contains("AB"), "got {text:?}");
        assert!(text.contains("CD"), "got {text:?}");
        // AB rolled up above CD
        let ab = text.find("AB").unwrap();
        let cd = text.find("CD").unwrap();
        assert!(ab < cd, "AB should be above CD: {text:?}");
    }

    /// Mid-row colour change places a styled space and changes the pen colour.
    #[test]
    fn mid_row_colour() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15
        dec.push_pair(false, set_odd_parity(b'A'), set_odd_parity(0x00));
        dec.push_pair(false, set_odd_parity(0x11), set_odd_parity(0x22)); // mid-row Green
        dec.push_pair(false, set_odd_parity(b'B'), set_odd_parity(0x00));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC
        // Find the styled cells; "B" must be green.
        let screen = dec.screen(Cea608Channel::Cc1);
        let mut found_green_b = false;
        for row in screen.rows() {
            for (_, c) in row.styled_cells() {
                if c.ch == 'B' {
                    assert_eq!(c.color, Cea608Color::Green);
                    found_green_b = true;
                }
            }
        }
        assert!(found_green_b, "expected a green 'B'");
    }

    #[test]
    fn caption_text_is_tracked_per_channel() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x29));
        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
        assert!(dec.has_caption_text(Cea608Channel::Cc2));
        assert!(!dec.has_caption_text(Cea608Channel::Cc1));
        assert!(!dec.has_caption_text(Cea608Channel::Cc3));
        assert!(!dec.has_caption_text(Cea608Channel::Cc4));
    }

    #[test]
    fn control_codes_xds_and_text_mode_are_not_caption_text() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20));
        dec.push_pair(true, set_odd_parity(0x01), set_odd_parity(0x03));
        dec.push_pair(true, set_odd_parity(b'A'), set_odd_parity(b'B'));
        dec.push_pair(true, set_odd_parity(0x0F), set_odd_parity(0x2C));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2A));
        dec.push_pair(false, set_odd_parity(b'T'), set_odd_parity(b'X'));
        for ch in [
            Cea608Channel::Cc1,
            Cea608Channel::Cc2,
            Cea608Channel::Cc3,
            Cea608Channel::Cc4,
        ] {
            assert!(!dec.has_caption_text(ch), "{}", ch.name());
        }
    }

    /// Special character (musical note) via 0x11 0x37.
    #[test]
    fn special_char_music_note() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // RDC (paint-on → displayed)
        dec.push_pair(false, set_odd_parity(0x11), set_odd_parity(0x37)); // ♪ on CC1
        assert!(dec.channel_text(Cea608Channel::Cc1).contains('\u{266A}'));
    }

    /// Extended char with automatic backspace: provider sends 'u' then ü code.
    #[test]
    fn extended_char_backspace() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // RDC
        dec.push_pair(false, set_odd_parity(b'u'), set_odd_parity(0x00)); // fallback 'u'
        dec.push_pair(false, set_odd_parity(0x12), set_odd_parity(0x25)); // extended ü (block1 0x25)
        let t = dec.channel_text(Cea608Channel::Cc1);
        assert_eq!(t, "\u{00FC}"); // just ü, the 'u' was backspaced
    }

    /// Channel routing: a CC2 control (0x1C…) writes to CC2, not CC1.
    #[test]
    fn channel_cc2() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x29)); // RDC on data channel 2 → CC2
        assert_eq!(dec.mode(Cea608Channel::Cc2), Cea608Mode::PaintOn);
        assert_eq!(dec.mode(Cea608Channel::Cc1), Cea608Mode::None);
    }

    /// Field 2 → CC3. CTA-608-E §8.4(a): field-2 misc-control's own first
    /// byte is `0x15` (the `0x14`→`0x15` shift), not the field-1 `0x14` byte
    /// (issue #1043 — the previous version of this test used `0x14` on
    /// field 2, which happened to pass for the wrong reason: `0x14` is not a
    /// valid field-2 misc-control byte at all, so it exercised no real code
    /// path distinct from field 1's).
    #[test]
    fn field2_cc3() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x29)); // RDC field 2 ch1 (0x15) → CC3
        assert_eq!(dec.mode(Cea608Channel::Cc3), Cea608Mode::PaintOn);
    }

    /// Field 2, data channel 2 → CC4. CTA-608-E §8.4(b): the `0x1C`→`0x1D`
    /// shift (issue #1043).
    #[test]
    fn field2_cc4() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(true, set_odd_parity(0x1D), set_odd_parity(0x29)); // RDC field 2 ch2 (0x1D) → CC4
        assert_eq!(dec.mode(Cea608Channel::Cc4), Cea608Mode::PaintOn);
        assert_eq!(dec.mode(Cea608Channel::Cc3), Cea608Mode::None);
    }

    /// XDS on field 2 is detected and skipped (no caption output).
    #[test]
    fn xds_skipped() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(true, set_odd_parity(0x01), set_odd_parity(0x02)); // XDS start (Current class)
        dec.push_pair(true, set_odd_parity(0x20), set_odd_parity(0x21)); // XDS informational
        dec.push_pair(true, set_odd_parity(0x0F), set_odd_parity(0x40)); // XDS end + checksum
        assert_eq!(dec.channel_text(Cea608Channel::Cc3), "");
    }

    /// CC-W2 (#1107): a caption control code sent while an XDS sub-packet is
    /// open must interrupt it, not be swallowed. Pre-fix, the `xds_active`
    /// short-circuit ran before the control-code check, so every code between
    /// XDS Start and End (here, all of RCL/PAC/EOC) was silently dropped and
    /// "HI" was never displayed.
    #[test]
    fn control_code_interrupts_open_xds() {
        let mut dec = Cea608Decoder::new();
        dec.push_pair(true, set_odd_parity(0x01), set_odd_parity(0x02)); // XDS start (Current class)
        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x20)); // RCL on CC3 (field-2 misc)
        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x70)); // PAC row 15 white indent0
        dec.push_pair(true, set_odd_parity(b'H'), set_odd_parity(b'I'));
        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x2F)); // EOC → flip to displayed
        assert_eq!(dec.channel_text(Cea608Channel::Cc3), "HI");
    }

    /// CC-W1 (#1107): standard (untagged) characters must route to the
    /// channel targeted by the field's last control code, not a hardcoded
    /// CC1/CC3. Pre-fix, `default_channel` always returned CC1 for field 1,
    /// so CC2's characters were written into CC1's memory and interleaved
    /// with CC1's own text.
    #[test]
    fn standard_chars_follow_last_control_channel() {
        let mut dec = Cea608Decoder::new();
        // CC1: pop-on "AB".
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL (CC1, base1=0x14)
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15 (CC1)
        dec.push_pair(false, set_odd_parity(b'A'), set_odd_parity(b'B'));
        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC (CC1)
        // CC2: pop-on "CD" — b1 in 0x18..=0x1F selects data channel 2.
        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x20)); // RCL (CC2, base1=0x14 folded)
        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x70)); // PAC row 15 (CC2)
        dec.push_pair(false, set_odd_parity(b'C'), set_odd_parity(b'D'));
        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x2F)); // EOC (CC2)
        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "AB");
        assert_eq!(dec.channel_text(Cea608Channel::Cc2), "CD");
    }

    #[test]
    fn standard_char_accents() {
        assert_eq!(Cea608Decoder::standard_char(0x2A), '\u{00E1}'); // á
        assert_eq!(Cea608Decoder::standard_char(b'A'), 'A');
        assert_eq!(Cea608Decoder::standard_char(0x7F), '\u{25A0}'); // ■
    }

    #[test]
    fn no_panic_on_arbitrary_input() {
        let mut dec = Cea608Decoder::new();
        let mut x: u32 = 0xDEAD_BEEF;
        for _ in 0..8192 {
            x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
            let b1 = (x >> 8) as u8;
            let b2 = (x >> 16) as u8;
            let f2 = (x & 1) != 0;
            dec.push_pair(f2, b1, b2);
        }
        // Also via triplets, including invalid + truncated patterns.
        let triplets = [
            CcTriplet {
                cc_valid: true,
                cc_type: CcType::Ntsc608Field1,
                cc_data_1: 0x14,
                cc_data_2: 0x2D,
            },
            CcTriplet {
                cc_valid: false,
                cc_type: CcType::Ntsc608Field2,
                cc_data_1: 0xFF,
                cc_data_2: 0xFF,
            },
            CcTriplet {
                cc_valid: true,
                cc_type: CcType::Ntsc608Field2,
                cc_data_1: 0x01,
                cc_data_2: 0x00,
            },
        ];
        dec.push_triplets(&triplets);
    }

    fn pair(d: &mut Cea608Decoder, a: u8, b: u8) {
        d.push_pair(false, set_odd_parity(a), set_odd_parity(b));
    }

    #[test]
    fn text_restart_does_not_erase_the_caption_screen() {
        let mut d = Cea608Decoder::new();
        pair(&mut d, 0x14, 0x20);
        pair(&mut d, 0x14, 0x70);
        pair(&mut d, b'H', b'I');
        pair(&mut d, 0x14, 0x2F);
        assert_eq!(d.channel_text(Cea608Channel::Cc1), "HI");
        pair(&mut d, 0x14, 0x2A);
        pair(&mut d, b'T', b'X');
        assert_eq!(d.channel_text(Cea608Channel::Cc1), "HI");
    }

    #[test]
    fn a_control_pair_after_a_null_pair_is_not_a_doubled_control() {
        let mut d = Cea608Decoder::new();
        pair(&mut d, 0x14, 0x25);
        pair(&mut d, b'A', b'B');
        pair(&mut d, 0x14, 0x2D);
        pair(&mut d, b'C', b'D');
        assert_eq!(d.channel_text(Cea608Channel::Cc1), "AB\nCD");
        pair(&mut d, 0x14, 0x2D);
        d.push_pair(false, 0x80, 0x80);
        pair(&mut d, 0x14, 0x2D);
        assert_eq!(d.channel_text(Cea608Channel::Cc1), "");
    }

    #[test]
    fn a_field1_pair_with_first_byte_in_the_xds_range_prints_no_text() {
        let mut d = Cea608Decoder::new();
        pair(&mut d, 0x14, 0x29);
        pair(&mut d, 0x14, 0x70);
        pair(&mut d, 0x01, b'X');
        assert_eq!(d.channel_text(Cea608Channel::Cc1), "");
    }
}