Skip to main content

cc_data/decode/
cea608.rs

1//! CEA-608 (line-21) caption decode — ANSI/CTA-608-E.
2//!
3//! Decodes the line-21 two-byte control / character codes that the
4//! [`crate::CcData`] carriage demuxes (`cc_type` 0 = field 1, 1 = field 2) into a
5//! caption screen. Implements the control-code state machine of
6//! `private/specs-verified/captions/cc-data/decode/cea608-decode.md`:
7//!
8//! - pop-on (RCL/EOC), roll-up (RU2/RU3/RU4 + CR), paint-on (RDC) modes,
9//! - Preamble Address Codes (row + indent + colour/italics/underline),
10//! - mid-row colour/italics codes, tab offsets,
11//! - the standard (Table 50), special (Table 49) and extended Western-European
12//!   (Tables 5–10, automatic-backspace) character sets,
13//! - the four data channels CC1–CC4, control-code doubling, and field-2 XDS
14//!   detect-and-skip.
15//!
16//! Bytes carry odd parity in b7; this decoder strips parity (masks b7) to the
17//! 7-bit value before classifying.
18
19use crate::cc_data::{CcTriplet, CcType};
20use alloc::string::String;
21use alloc::vec::Vec;
22
23/// Foreground colour of a line-21 caption cell (CTA-608-E Tables 51/53).
24///
25/// Returned by [`Cea608StyledChar::color`]; corresponds to the 3-bit colour
26/// index in PAC / mid-row code tables.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize))]
29#[non_exhaustive]
30pub enum Cea608Color {
31    /// White (default).
32    #[default]
33    White,
34    /// Green.
35    Green,
36    /// Blue.
37    Blue,
38    /// Cyan.
39    Cyan,
40    /// Red.
41    Red,
42    /// Yellow.
43    Yellow,
44    /// Magenta.
45    Magenta,
46}
47
48impl Cea608Color {
49    /// Label per the project's `name()` convention.
50    #[must_use]
51    pub fn name(&self) -> &'static str {
52        match self {
53            Self::White => "white",
54            Self::Green => "green",
55            Self::Blue => "blue",
56            Self::Cyan => "cyan",
57            Self::Red => "red",
58            Self::Yellow => "yellow",
59            Self::Magenta => "magenta",
60        }
61    }
62
63    /// From the 3-bit colour index used in PAC and mid-row tables (Tables 51/53).
64    #[must_use]
65    pub(super) fn from_idx(idx: u8) -> Self {
66        match idx & 0x07 {
67            0 => Self::White,
68            1 => Self::Green,
69            2 => Self::Blue,
70            3 => Self::Cyan,
71            4 => Self::Red,
72            5 => Self::Yellow,
73            6 => Self::Magenta,
74            _ => Self::White,
75        }
76    }
77}
78broadcast_common::impl_spec_display!(Cea608Color);
79
80/// Number of caption rows on a line-21 screen (§3.2.2).
81const SCREEN_ROWS: usize = 15;
82/// Number of caption columns on a line-21 screen.
83const SCREEN_COLS: usize = 32;
84
85// ── Misc-control 2nd-byte values (Table 52, data-channel-1 column) ────────────
86const MC_RCL: u8 = 0x20;
87const MC_BS: u8 = 0x21;
88const MC_DER: u8 = 0x24;
89const MC_RU2: u8 = 0x25;
90const MC_RU3: u8 = 0x26;
91const MC_RU4: u8 = 0x27;
92const MC_FON: u8 = 0x28;
93const MC_RDC: u8 = 0x29;
94const MC_TR: u8 = 0x2A;
95const MC_RTD: u8 = 0x2B;
96const MC_EDM: u8 = 0x2C;
97const MC_CR: u8 = 0x2D;
98const MC_ENM: u8 = 0x2E;
99const MC_EOC: u8 = 0x2F;
100
101// ── Tab offsets (Table 52): first byte 0x17/0x1F, 2nd byte 0x21–0x23 ──────────
102const TAB_FIRST_C1: u8 = 0x17;
103const TAB_FIRST_C2: u8 = 0x1F;
104const TAB1: u8 = 0x21;
105const TAB3: u8 = 0x23;
106
107/// The caption mode (§6.1, §7).
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109#[cfg_attr(feature = "serde", derive(serde::Serialize))]
110#[non_exhaustive]
111pub enum Cea608Mode {
112    /// No mode selected yet.
113    #[default]
114    None,
115    /// Pop-on (RCL → load to back buffer → EOC flips).
116    PopOn,
117    /// Roll-up with the given number of rows (2/3/4).
118    RollUp(u8),
119    /// Paint-on (RDC → paint to displayed memory).
120    PaintOn,
121    /// Text mode (TR/RTD).
122    Text,
123}
124
125impl Cea608Mode {
126    /// Label per the project's `name()` convention.
127    #[must_use]
128    pub fn name(&self) -> &'static str {
129        match self {
130            Self::None => "none",
131            Self::PopOn => "pop_on",
132            Self::RollUp(_) => "roll_up",
133            Self::PaintOn => "paint_on",
134            Self::Text => "text",
135        }
136    }
137}
138broadcast_common::impl_spec_display!(Cea608Mode);
139
140/// A line-21 caption data channel (Table 1, §4.1): the eight CC/Text logical
141/// services keyed by field + data-channel.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
143#[cfg_attr(feature = "serde", derive(serde::Serialize))]
144#[non_exhaustive]
145pub enum Cea608Channel {
146    /// CC1 — field 1, data channel 1 (primary).
147    Cc1,
148    /// CC2 — field 1, data channel 2.
149    Cc2,
150    /// CC3 — field 2, data channel 1 (secondary).
151    Cc3,
152    /// CC4 — field 2, data channel 2.
153    Cc4,
154}
155
156impl Cea608Channel {
157    /// The channel's number in `CC1`..`CC4`, 1 to 4.
158    #[must_use]
159    pub fn number(self) -> u8 {
160        match self {
161            Self::Cc1 => 1,
162            Self::Cc2 => 2,
163            Self::Cc3 => 3,
164            Self::Cc4 => 4,
165        }
166    }
167
168    /// Index 0–3 into the decoder's per-channel state.
169    #[must_use]
170    fn index(self) -> usize {
171        match self {
172            Self::Cc1 => 0,
173            Self::Cc2 => 1,
174            Self::Cc3 => 2,
175            Self::Cc4 => 3,
176        }
177    }
178    /// Label per the project's `name()` convention.
179    #[must_use]
180    pub fn name(&self) -> &'static str {
181        match self {
182            Self::Cc1 => "cc1",
183            Self::Cc2 => "cc2",
184            Self::Cc3 => "cc3",
185            Self::Cc4 => "cc4",
186        }
187    }
188}
189broadcast_common::impl_spec_display!(Cea608Channel);
190
191/// A styled character cell on a 608 caption screen.
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193#[cfg_attr(feature = "serde", derive(serde::Serialize))]
194pub struct Cea608StyledChar {
195    /// The glyph.
196    pub ch: char,
197    /// Underline attribute.
198    pub underline: bool,
199    /// Italics attribute.
200    pub italics: bool,
201    /// Foreground colour (CTA-608-E Tables 51/53).
202    pub color: Cea608Color,
203}
204
205impl Default for Cea608StyledChar {
206    fn default() -> Self {
207        Cea608StyledChar {
208            ch: ' ',
209            underline: false,
210            italics: false,
211            color: Cea608Color::White,
212        }
213    }
214}
215
216/// One row of a 608 caption screen.
217#[derive(Debug, Clone, PartialEq, Eq, Default)]
218#[cfg_attr(feature = "serde", derive(serde::Serialize))]
219pub struct Cea608Row {
220    /// The styled cells (sparse: only populated cells present, indexed by column).
221    cells: Vec<(usize, Cea608StyledChar)>,
222}
223
224impl Cea608Row {
225    fn set(&mut self, col: usize, c: Cea608StyledChar) {
226        if let Some(slot) = self.cells.iter_mut().find(|(i, _)| *i == col) {
227            slot.1 = c;
228        } else {
229            self.cells.push((col, c));
230        }
231    }
232    fn clear_from(&mut self, col: usize) {
233        self.cells.retain(|(i, _)| *i < col);
234    }
235    fn remove(&mut self, col: usize) {
236        self.cells.retain(|(i, _)| *i != col);
237    }
238    /// The row's text (cells sorted by column, gaps filled with spaces).
239    #[must_use]
240    pub fn text(&self) -> String {
241        let mut sorted = self.cells.clone();
242        sorted.sort_by_key(|(i, _)| *i);
243        let mut out = String::new();
244        let mut last = None;
245        for (i, c) in sorted {
246            if let Some(prev) = last {
247                for _ in (prev + 1)..i {
248                    out.push(' ');
249                }
250            }
251            out.push(c.ch);
252            last = Some(i);
253        }
254        out
255    }
256    /// Styled cells in column order.
257    #[must_use]
258    pub fn styled_cells(&self) -> Vec<(usize, Cea608StyledChar)> {
259        let mut sorted = self.cells.clone();
260        sorted.sort_by_key(|(i, _)| *i);
261        sorted
262    }
263}
264
265/// A 608 caption screen — `SCREEN_ROWS` rows of styled cells.
266#[derive(Debug, Clone, PartialEq, Eq, Default)]
267#[cfg_attr(feature = "serde", derive(serde::Serialize))]
268pub struct Cea608Screen {
269    rows: [Cea608Row; SCREEN_ROWS],
270}
271
272impl Cea608Screen {
273    /// The screen text: non-empty rows joined with `\n`, trailing spaces trimmed.
274    #[must_use]
275    pub fn text(&self) -> String {
276        let mut out = String::new();
277        for row in &self.rows {
278            let line = row.text();
279            let trimmed = line.trim_end();
280            if trimmed.is_empty() {
281                continue;
282            }
283            if !out.is_empty() {
284                out.push('\n');
285            }
286            out.push_str(trimmed);
287        }
288        out
289    }
290    /// All rows (including empty ones).
291    #[must_use]
292    pub fn rows(&self) -> &[Cea608Row; SCREEN_ROWS] {
293        &self.rows
294    }
295}
296
297/// Current pen attribute set by a PAC / mid-row code.
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299struct Pen {
300    underline: bool,
301    italics: bool,
302    color: Cea608Color,
303}
304
305impl Default for Pen {
306    fn default() -> Self {
307        Pen {
308            underline: false,
309            italics: false,
310            color: Cea608Color::White,
311        }
312    }
313}
314
315/// Per-channel caption state (displayed + non-displayed memory, mode, cursor).
316#[derive(Debug, Clone, PartialEq, Eq, Default)]
317struct ChannelState {
318    displayed: Cea608Screen,
319    nondisplayed: Cea608Screen,
320    text: Cea608Screen,
321    mode: Cea608Mode,
322    rollup_rows: u8,
323    cursor_row: usize,
324    cursor_col: usize,
325    pen: Pen,
326}
327
328impl ChannelState {
329    /// The active memory for the current mode (pop-on writes to non-displayed;
330    /// roll-up / paint-on write to displayed).
331    fn active_mut(&mut self) -> &mut Cea608Screen {
332        match self.mode {
333            Cea608Mode::PopOn => &mut self.nondisplayed,
334            Cea608Mode::Text => &mut self.text,
335            _ => &mut self.displayed,
336        }
337    }
338}
339
340/// CEA-608 (line-21) caption decoder.
341///
342/// Feed it [`CcTriplet`]s (or raw byte pairs) of the 608 fields; read decoded
343/// text per channel via [`channel_text`](Cea608Decoder::channel_text) /
344/// [`screen`](Cea608Decoder::screen).
345///
346/// ```
347/// use cc_data::decode::{Cea608Decoder, Cea608Channel};
348/// let mut dec = Cea608Decoder::new();
349/// // RCL, PAC row 15, "HI", EOC — a pop-on caption on CC1 (field 1).
350/// dec.push_pair(false, 0x14, 0x20); // RCL (field 1 → CC1)
351/// dec.push_pair(false, 0x14, 0x20); // doubled control — ignored
352/// dec.push_pair(false, 0x14, 0x70); // PAC row 15 indent 0 (field 1)
353/// dec.push_pair(false, b'H', b'I');
354/// dec.push_pair(false, 0x14, 0x2F); // EOC → flip
355/// assert_eq!(dec.channel_text(Cea608Channel::Cc1), "HI");
356/// ```
357#[derive(Debug, Clone, PartialEq, Eq)]
358pub struct Cea608Decoder {
359    channels: [ChannelState; 4],
360    /// The control pair last acted on, per field, for doubling suppression.
361    last_control: [Option<(u8, u8)>; 2],
362    /// The channel targeted by the last control code seen on each field.
363    /// Standard (non-tagged) characters are routed here, per field, since
364    /// CEA-608 encodes which channel a character belongs to only implicitly,
365    /// via the most recent control code on that field.
366    last_channel: [Cea608Channel; 2],
367    xds_active: bool,
368    /// Bit `Cea608Channel::index` set once a displayable character has been
369    /// written to that channel outside text mode.
370    caption_text_seen: u8,
371}
372
373impl Default for Cea608Decoder {
374    fn default() -> Self {
375        Self::new()
376    }
377}
378
379impl Cea608Decoder {
380    /// A new decoder.
381    #[must_use]
382    pub fn new() -> Self {
383        Cea608Decoder {
384            channels: Default::default(),
385            last_control: [None, None],
386            last_channel: [Cea608Channel::Cc1, Cea608Channel::Cc3],
387            xds_active: false,
388            caption_text_seen: 0,
389        }
390    }
391
392    /// Feed the decoder the 608 (line-21) triplets of a [`crate::CcData`].
393    pub fn push_triplets<'a, I>(&mut self, triplets: I)
394    where
395        I: IntoIterator<Item = &'a CcTriplet>,
396    {
397        for t in triplets {
398            if !t.cc_valid {
399                continue;
400            }
401            let field2 = match t.cc_type {
402                CcType::Ntsc608Field1 => false,
403                CcType::Ntsc608Field2 => true,
404                _ => continue,
405            };
406            self.process_pair(field2, t.cc_data_1, t.cc_data_2);
407        }
408    }
409
410    /// Feed one raw 608 byte pair. `field2 = false` ⇒ field 1 (`cc_type` 0);
411    /// `field2 = true` ⇒ field 2 (`cc_type` 1). Bytes may carry parity in b7.
412    pub fn push_pair(&mut self, field2: bool, b1: u8, b2: u8) {
413        self.process_pair(field2, b1, b2);
414    }
415
416    fn process_pair(&mut self, field2: bool, raw1: u8, raw2: u8) {
417        let b1 = raw1 & 0x7F;
418        let b2 = raw2 & 0x7F;
419        let field_idx = usize::from(field2);
420
421        // Null filler (0x00 0x00): separates control pairs, so a control after it
422        // is not a doubled copy (CTA-608-E Annex B.14; private/specs-verified/captions/cc-data/decode/cea608-decode.md).
423        if b1 == 0x00 && b2 == 0x00 {
424            self.last_control[field_idx] = None;
425            return;
426        }
427
428        // XDS (field 2 only): a control pair with first byte 0x01–0x0F begins or
429        // continues an XDS sub-packet; 0x0F + checksum ends it. Detect + skip the
430        // whole span (we never decode XDS into captions).
431        if field2 && (0x01..=0x0F).contains(&b1) {
432            // 0x0F = End control (followed by a checksum byte); otherwise
433            // Start/Continue. Either way this pair is XDS, not caption.
434            self.xds_active = b1 != 0x0F;
435            return;
436        }
437
438        // Control codes: first byte 0x10–0x1F. CTA-608 lets a caption control
439        // code interrupt an open XDS sub-packet (XDS resumes afterwards with a
440        // Continue code), so this check runs BEFORE the xds_active short-circuit
441        // below — otherwise every caption code sent while XDS is open would be
442        // swallowed along with the XDS payload.
443        if (0x10..=0x1F).contains(&b1) {
444            // Doubling: an identical control pair immediately repeated is one cmd.
445            if self.last_control[field_idx] == Some((b1, b2)) {
446                self.last_control[field_idx] = None; // consume the doubled copy
447                return;
448            }
449            self.last_control[field_idx] = Some((b1, b2));
450            self.xds_active = false;
451            self.handle_control(field2, b1, b2);
452            return;
453        }
454        // Any pair while an XDS sub-packet is open (field 2) is XDS payload
455        // (informational chars 0x20–0x7F or null) until the End control closes it.
456        if field2 && self.xds_active {
457            return;
458        }
459
460        // First bytes 0x01–0x0F are reserved for XDS (field 2 only) and never
461        // carry caption text on field 1 (CTA-608-E §8.6.1; private/specs-verified/captions/cc-data/decode/cea608-decode.md).
462        if (0x01..=0x0F).contains(&b1) {
463            self.last_control[field_idx] = None;
464            return;
465        }
466
467        // Displayable characters: first byte 0x20–0x7F.
468        self.last_control[field_idx] = None;
469        self.xds_active = false;
470        // Standard chars are not channel-tagged; route to the channel targeted
471        // by the last control code seen on this field.
472        let ch = self.last_channel[field_idx];
473        if b1 >= 0x20 {
474            self.put_char(ch, Self::standard_char(b1));
475        }
476        if b2 >= 0x20 {
477            self.put_char(ch, Self::standard_char(b2));
478        }
479    }
480
481    /// The control-code handler. `b1` 0x10–0x1F, `b2` 0x20–0x7F (7-bit).
482    fn handle_control(&mut self, field2: bool, b1: u8, b2: u8) {
483        // Determine data channel from the first byte. For field 1: 0x10–0x17 =
484        // C1, 0x18–0x1F = C2. For field 2: same first-byte split selects C1/C2
485        // for every category EXCEPT Miscellaneous Control Codes, which use a
486        // shifted pair of their own on field 2 (CTA-608-E §8.4 a/b, cited in
487        // `private/specs-verified/captions/cc-data/decode/cea608-decode.md`): field-1 `0x14`(C1)/`0x1C`(C2) become
488        // field-2 `0x15`(C1/CC3)/`0x1D`(C2/CC4). That shift only applies to
489        // misc-control's own 2nd-byte range (`0x20`-`0x2F`); `0x15`/`0x1D` with
490        // a 2nd byte outside it (e.g. a PAC row byte, `0x40`-`0x7F`) is not
491        // misc-control and folds the ordinary way (issue #1043 — the previous
492        // fold recognised only field-1's `0x14`/`0x1C`, so field-2 misc-control
493        // pairs never matched and were silently dropped).
494        let field2_misc = field2 && (0x20..=0x2F).contains(&b2) && matches!(b1, 0x15 | 0x1D);
495        let c2 = if field2_misc { b1 == 0x1D } else { b1 >= 0x18 };
496        let base1 = if field2_misc {
497            0x14
498        } else if c2 {
499            b1 - 0x08 // fold C2 onto C1 range
500        } else {
501            b1
502        };
503        let ch = self.channel_for(field2, c2);
504        // Every control code updates the field's "current channel", so
505        // subsequent untagged standard characters route to it (CC-W1).
506        self.last_channel[usize::from(field2)] = ch;
507
508        // Misc control: first byte 0x14 (C1) / 0x1C (C2), or the field-2
509        // `field2_misc` fold above.
510        if base1 == 0x14 && (0x20..=0x2F).contains(&b2) {
511            self.misc_control(ch, b2);
512            return;
513        }
514        // Tab offsets: first byte 0x17 (C1) / 0x1F (C2), 2nd 0x21–0x23.
515        if (b1 == TAB_FIRST_C1 || b1 == TAB_FIRST_C2) && (TAB1..=TAB3).contains(&b2) {
516            let n = (b2 - TAB1 + 1) as usize;
517            let st = &mut self.channels[ch.index()];
518            st.cursor_col = (st.cursor_col + n).min(SCREEN_COLS - 1);
519            return;
520        }
521        // Mid-row codes: first byte 0x11 (C1) / 0x19 (C2), 2nd 0x20–0x2F.
522        if base1 == 0x11 && (0x20..=0x2F).contains(&b2) {
523            self.mid_row(ch, b2);
524            return;
525        }
526        // Special characters: first byte 0x11/0x19, 2nd 0x30–0x3F.
527        if base1 == 0x11 && (0x30..=0x3F).contains(&b2) {
528            self.put_char(ch, Self::special_char(b2));
529            return;
530        }
531        // Extended chars block 1: first byte 0x12/0x1A, 2nd 0x20–0x3F.
532        if base1 == 0x12 && (0x20..=0x3F).contains(&b2) {
533            self.put_extended(ch, Self::extended_char_block1(b2));
534            return;
535        }
536        // Extended chars block 2: first byte 0x13/0x1B, 2nd 0x20–0x3F.
537        if base1 == 0x13 && (0x20..=0x3F).contains(&b2) {
538            self.put_extended(ch, Self::extended_char_block2(b2));
539            return;
540        }
541        // PAC: 2nd byte 0x40–0x7F (any control first byte).
542        if (0x40..=0x7F).contains(&b2) {
543            self.pac(field2, ch, b1, b2);
544        }
545        // Background/foreground attr codes (0x10/0x18 2nd 0x20–0x2F) — ignored
546        // for text extraction.
547    }
548
549    /// Miscellaneous control codes (RCL/RU2-4/RDC/CR/EDM/ENM/EOC/DER/BS …).
550    fn misc_control(&mut self, ch: Cea608Channel, code: u8) {
551        let st = &mut self.channels[ch.index()];
552        match code {
553            MC_RCL => {
554                // RCL only selects pop-on style: it does NOT erase the
555                // non-displayed memory (that is ENM's job). Real captions
556                // re-issue RCL after loading text and before the EDM/EOC pair
557                // that pops it on (libcaption `tos.scc`, pycaption
558                // `example.scc`); clearing here discarded the whole caption.
559                st.mode = Cea608Mode::PopOn;
560                st.cursor_row = 0;
561                st.cursor_col = 0;
562            }
563            MC_RU2 | MC_RU3 | MC_RU4 => {
564                let rows = match code {
565                    MC_RU2 => 2,
566                    MC_RU3 => 3,
567                    _ => 4,
568                };
569                st.mode = Cea608Mode::RollUp(rows);
570                st.rollup_rows = rows;
571                // base row defaults to bottom (row 15 → index 14)
572                st.cursor_row = SCREEN_ROWS - 1;
573                st.cursor_col = 0;
574                st.pen = Pen::default();
575            }
576            MC_RDC => {
577                st.mode = Cea608Mode::PaintOn;
578            }
579            MC_CR => {
580                self.carriage_return(ch);
581            }
582            MC_EDM => {
583                st.displayed = Cea608Screen::default();
584            }
585            MC_ENM => {
586                st.nondisplayed = Cea608Screen::default();
587            }
588            MC_EOC => {
589                // flip non-displayed ↔ displayed (pop-on)
590                core::mem::swap(&mut st.displayed, &mut st.nondisplayed);
591            }
592            MC_BS if st.cursor_col > 0 => {
593                st.cursor_col -= 1;
594                let row = st.cursor_row.min(SCREEN_ROWS - 1);
595                let col = st.cursor_col;
596                st.active_mut().rows[row].remove(col);
597            }
598            MC_DER => {
599                let row = st.cursor_row.min(SCREEN_ROWS - 1);
600                let col = st.cursor_col;
601                st.active_mut().rows[row].clear_from(col);
602            }
603            MC_TR => {
604                st.mode = Cea608Mode::Text;
605                st.text = Cea608Screen::default();
606                st.cursor_row = 0;
607                st.cursor_col = 0;
608            }
609            MC_RTD => {
610                st.mode = Cea608Mode::Text;
611            }
612            MC_FON => {}
613            _ => {}
614        }
615    }
616
617    /// Carriage Return in roll-up: roll the window up one row, clear the base row.
618    fn carriage_return(&mut self, ch: Cea608Channel) {
619        let st = &mut self.channels[ch.index()];
620        if let Cea608Mode::RollUp(rows) = st.mode {
621            let base = st.cursor_row.min(SCREEN_ROWS - 1);
622            let rows = rows as usize;
623            let top = base.saturating_sub(rows - 1);
624            for r in top..base {
625                st.displayed.rows[r] = st.displayed.rows[r + 1].clone();
626            }
627            st.displayed.rows[base] = Cea608Row::default();
628            st.cursor_col = 0;
629        } else {
630            // In other modes, CR is uncommon; just move cursor down.
631            if st.cursor_row + 1 < SCREEN_ROWS {
632                st.cursor_row += 1;
633            }
634            st.cursor_col = 0;
635        }
636    }
637
638    /// Mid-row code (Table 51): sets colour/italics + underline from the cursor.
639    fn mid_row(&mut self, ch: Cea608Channel, b2: u8) {
640        let idx = (b2 - 0x20) as usize; // 0x20..0x2F → 0..15
641        let underline = idx & 0x01 != 0;
642        let color_idx = (idx >> 1) as u8;
643        let (color, italics) = if color_idx <= 6 {
644            (Cea608Color::from_idx(color_idx), false)
645        } else {
646            (Cea608Color::White, true) // 0x2E/0x2F = italics
647        };
648        let st = &mut self.channels[ch.index()];
649        st.pen = Pen {
650            underline,
651            italics,
652            color,
653        };
654        // mid-row occupies one cell (a space carrying the attribute)
655        self.put_char(ch, ' ');
656    }
657
658    /// Preamble Address Code: set row + indent / colour + underline (Table 53).
659    fn pac(&mut self, _field2: bool, ch: Cea608Channel, b1: u8, b2: u8) {
660        // Fold the C2 first byte (0x18–0x1F) onto the C1 first byte (0x10–0x17).
661        let f = if b1 >= 0x18 { b1 - 0x08 } else { b1 };
662        // Row group from the first byte (Table 53 top block, C1 column).
663        let row_pair = match f {
664            0x11 => 1,  // rows 1–2
665            0x12 => 3,  // rows 3–4
666            0x15 => 5,  // rows 5–6
667            0x16 => 7,  // rows 7–8
668            0x17 => 9,  // rows 9–10
669            0x10 => 11, // row 11
670            0x13 => 12, // rows 12–13
671            0x14 => 14, // rows 14–15
672            _ => 1,
673        };
674        // Second byte high bit picks the row within the pair (0x40–0x5F = first
675        // of pair, 0x60–0x7F = second).
676        let second_of_pair = b2 >= 0x60;
677        let row = if f == 0x10 {
678            11 // row 11 has no pair partner
679        } else if second_of_pair {
680            row_pair + 1
681        } else {
682            row_pair
683        };
684        let row = row.clamp(1, SCREEN_ROWS); // 1-based
685        let attr = b2 & 0x1F; // low 5 bits (drop the col-A/B high nibble)
686        let underline = attr & 0x01 != 0;
687
688        let (color, italics, indent) = if attr >= 0x10 {
689            // Indent codes 0x10..0x1F → indent 0..28 in steps of 4, colour white.
690            let indent = ((attr - 0x10) >> 1) as usize * 4;
691            (Cea608Color::White, false, indent)
692        } else {
693            // Colour/italics codes 0x00..0x0F.
694            let color_idx = attr >> 1;
695            let (c, it) = if color_idx <= 6 {
696                (Cea608Color::from_idx(color_idx), false)
697            } else {
698                (Cea608Color::White, true)
699            };
700            (c, it, 0)
701        };
702
703        let st = &mut self.channels[ch.index()];
704        st.cursor_row = (row - 1).min(SCREEN_ROWS - 1);
705        st.cursor_col = indent.min(SCREEN_COLS - 1);
706        st.pen = Pen {
707            underline,
708            italics,
709            color,
710        };
711    }
712
713    /// Put a standard / special character at the cursor, advancing it.
714    fn put_char(&mut self, ch: Cea608Channel, c: char) {
715        let st = &mut self.channels[ch.index()];
716        if st.mode != Cea608Mode::Text {
717            self.caption_text_seen |= 1 << ch.index();
718        }
719        let row = st.cursor_row.min(SCREEN_ROWS - 1);
720        let col = st.cursor_col;
721        if col >= SCREEN_COLS {
722            return;
723        }
724        let pen = st.pen;
725        let styled = Cea608StyledChar {
726            ch: c,
727            underline: pen.underline,
728            italics: pen.italics,
729            color: pen.color,
730        };
731        st.active_mut().rows[row].set(col, styled);
732        st.cursor_col = (col + 1).min(SCREEN_COLS);
733    }
734
735    /// Put an extended char: automatic backspace first (erase the fallback char
736    /// the provider sent), then the glyph.
737    fn put_extended(&mut self, ch: Cea608Channel, c: char) {
738        {
739            let st = &mut self.channels[ch.index()];
740            if st.cursor_col > 0 {
741                st.cursor_col -= 1;
742                let row = st.cursor_row.min(SCREEN_ROWS - 1);
743                let col = st.cursor_col;
744                st.active_mut().rows[row].remove(col);
745            }
746        }
747        self.put_char(ch, c);
748    }
749
750    /// Resolve the data channel for a control pair.
751    fn channel_for(&self, field2: bool, c2: bool) -> Cea608Channel {
752        match (field2, c2) {
753            (false, false) => Cea608Channel::Cc1,
754            (false, true) => Cea608Channel::Cc2,
755            (true, false) => Cea608Channel::Cc3,
756            (true, true) => Cea608Channel::Cc4,
757        }
758    }
759
760    /// Whether caption text (a displayable character outside text mode) has
761    /// been written to `channel` since this decoder was created. Control codes,
762    /// XDS and null padding alone never set it.
763    #[must_use]
764    pub fn has_caption_text(&self, channel: Cea608Channel) -> bool {
765        self.caption_text_seen & (1 << channel.index()) != 0
766    }
767
768    /// The displayed screen for a channel.
769    #[must_use]
770    pub fn screen(&self, channel: Cea608Channel) -> &Cea608Screen {
771        &self.channels[channel.index()].displayed
772    }
773
774    /// The current mode for a channel.
775    #[must_use]
776    pub fn mode(&self, channel: Cea608Channel) -> Cea608Mode {
777        self.channels[channel.index()].mode
778    }
779
780    /// The decoded displayed text for a channel.
781    #[must_use]
782    pub fn channel_text(&self, channel: Cea608Channel) -> String {
783        self.channels[channel.index()].displayed.text()
784    }
785
786    // ── Character tables ──────────────────────────────────────────────────────
787
788    /// Standard character set (Table 50): 7-bit `0x20`–`0x7F` → glyph.
789    fn standard_char(b: u8) -> char {
790        match b {
791            0x2A => '\u{00E1}', // á
792            0x5C => '\u{00E9}', // é
793            0x5E => '\u{00ED}', // í
794            0x5F => '\u{00F3}', // ó
795            0x60 => '\u{00FA}', // ú
796            0x7B => '\u{00E7}', // ç
797            0x7C => '\u{00F7}', // ÷
798            0x7D => '\u{00D1}', // Ñ
799            0x7E => '\u{00F1}', // ñ
800            0x7F => '\u{25A0}', // ■
801            _ => char::from(b), // ASCII otherwise
802        }
803    }
804
805    /// Special characters (Table 49): 2nd byte 0x30–0x3F.
806    fn special_char(b2: u8) -> char {
807        match b2 {
808            0x30 => '\u{00AE}', // ®
809            0x31 => '\u{00B0}', // °
810            0x32 => '\u{00BD}', // ½
811            0x33 => '\u{00BF}', // ¿
812            0x34 => '\u{2122}', // ™
813            0x35 => '\u{00A2}', // ¢
814            0x36 => '\u{00A3}', // £
815            0x37 => '\u{266A}', // ♪
816            0x38 => '\u{00E0}', // à
817            0x39 => ' ',        // transparent space
818            0x3A => '\u{00E8}', // è
819            0x3B => '\u{00E2}', // â
820            0x3C => '\u{00EA}', // ê
821            0x3D => '\u{00EE}', // î
822            0x3E => '\u{00F4}', // ô
823            0x3F => '\u{00FB}', // û
824            _ => '?',
825        }
826    }
827
828    /// Extended Western-European block 1 (first byte 0x12/0x1A; Tables 5–7).
829    fn extended_char_block1(b2: u8) -> char {
830        match b2 {
831            // Spanish (Table 5)
832            0x20 => '\u{00C1}', // Á
833            0x21 => '\u{00C9}', // É
834            0x22 => '\u{00D3}', // Ó
835            0x23 => '\u{00DA}', // Ú
836            0x24 => '\u{00DC}', // Ü
837            0x25 => '\u{00FC}', // ü
838            0x26 => '\u{2018}', // ‘
839            0x27 => '\u{00A1}', // ¡
840            // Misc (Table 6)
841            0x28 => '*',
842            0x29 => '\'',
843            0x2A => '\u{2014}', // —
844            0x2B => '\u{00A9}', // ©
845            0x2C => '\u{2120}', // ℠
846            0x2D => '\u{2022}', // •
847            0x2E => '\u{201C}', // "
848            0x2F => '\u{201D}', // "
849            // French (Table 7)
850            0x30 => '\u{00C0}', // À
851            0x31 => '\u{00C2}', // Â
852            0x32 => '\u{00C7}', // Ç
853            0x33 => '\u{00C8}', // È
854            0x34 => '\u{00CA}', // Ê
855            0x35 => '\u{00CB}', // Ë
856            0x36 => '\u{00EB}', // ë
857            0x37 => '\u{00CE}', // Î
858            0x38 => '\u{00CF}', // Ï
859            0x39 => '\u{00EF}', // ï
860            0x3A => '\u{00D4}', // Ô
861            0x3B => '\u{00D9}', // Ù
862            0x3C => '\u{00F9}', // ù
863            0x3D => '\u{00DB}', // Û
864            0x3E => '\u{00AB}', // «
865            0x3F => '\u{00BB}', // »
866            _ => '?',
867        }
868    }
869
870    /// Extended Western-European block 2 (first byte 0x13/0x1B; Tables 8–10).
871    fn extended_char_block2(b2: u8) -> char {
872        match b2 {
873            // Portuguese (Table 8)
874            0x20 => '\u{00C3}', // Ã
875            0x21 => '\u{00E3}', // ã
876            0x22 => '\u{00CD}', // Í
877            0x23 => '\u{00CC}', // Ì
878            0x24 => '\u{00EC}', // ì
879            0x25 => '\u{00D2}', // Ò
880            0x26 => '\u{00F2}', // ò
881            0x27 => '\u{00D5}', // Õ
882            0x28 => '\u{00F5}', // õ
883            0x29 => '{',
884            0x2A => '}',
885            0x2B => '\\',
886            0x2C => '^',
887            0x2D => '_',
888            0x2E => '|',
889            0x2F => '~',
890            // German (Table 9)
891            0x30 => '\u{00C4}', // Ä
892            0x31 => '\u{00E4}', // ä
893            0x32 => '\u{00D6}', // Ö
894            0x33 => '\u{00F6}', // ö
895            0x34 => '\u{00DF}', // ß
896            0x35 => '\u{00A5}', // ¥
897            0x36 => '\u{00A4}', // ¤
898            0x37 => '|',
899            // Danish (Table 10)
900            0x38 => '\u{00C5}', // Å
901            0x39 => '\u{00E5}', // å
902            0x3A => '\u{00D8}', // Ø
903            0x3B => '\u{00F8}', // ø
904            0x3C => '\u{231C}', // ⌜
905            0x3D => '\u{231D}', // ⌝
906            0x3E => '\u{231E}', // ⌞
907            0x3F => '\u{231F}', // ⌟
908            _ => '?',
909        }
910    }
911}
912
913#[cfg(test)]
914mod tests {
915    use super::*;
916    use broadcast_common::parity::set_odd_parity;
917
918    /// Pop-on caption: RCL, PAC row 15 indent 0, "HI", EOC → on-screen "HI".
919    #[test]
920    fn pop_on_caption() {
921        let mut dec = Cea608Decoder::new();
922        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
923        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15 (col B), white indent0
924        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
925        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC → flip to displayed
926        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "HI");
927        assert_eq!(dec.mode(Cea608Channel::Cc1), Cea608Mode::PopOn);
928    }
929
930    /// RCL selects pop-on without erasing non-displayed memory: text loaded,
931    /// then RCL again, then EDM + EOC (the sequence real SCC files use) still
932    /// pops the loaded text on. Regression for a decoder that cleared the
933    /// non-displayed buffer on every RCL.
934    #[test]
935    fn rcl_does_not_erase_loaded_text() {
936        let mut dec = Cea608Decoder::new();
937        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
938        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15
939        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
940        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL again
941        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2C)); // EDM
942        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC
943        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "HI");
944    }
945
946    /// ENM, not RCL, is what erases non-displayed memory.
947    #[test]
948    fn enm_erases_loaded_text() {
949        let mut dec = Cea608Decoder::new();
950        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
951        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70));
952        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
953        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2E)); // ENM
954        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC
955        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "");
956    }
957
958    /// Control-code doubling: a repeated RCL pair acts once.
959    #[test]
960    fn control_doubling() {
961        let mut dec = Cea608Decoder::new();
962        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // RDC
963        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // doubled — ignored
964        assert_eq!(dec.mode(Cea608Channel::Cc1), Cea608Mode::PaintOn);
965        // a non-doubled second RDC after a non-control acts again
966        dec.push_pair(false, set_odd_parity(b'X'), set_odd_parity(0x00));
967        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2C)); // EDM
968    }
969
970    /// Roll-up across ≥2 rows: RU2, write line 1, CR, write line 2.
971    #[test]
972    fn roll_up_two_rows() {
973        let mut dec = Cea608Decoder::new();
974        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x25)); // RU2
975        dec.push_pair(false, set_odd_parity(b'A'), set_odd_parity(b'B'));
976        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2D)); // CR
977        dec.push_pair(false, set_odd_parity(b'C'), set_odd_parity(b'D'));
978        let text = dec.channel_text(Cea608Channel::Cc1);
979        assert!(text.contains("AB"), "got {text:?}");
980        assert!(text.contains("CD"), "got {text:?}");
981        // AB rolled up above CD
982        let ab = text.find("AB").unwrap();
983        let cd = text.find("CD").unwrap();
984        assert!(ab < cd, "AB should be above CD: {text:?}");
985    }
986
987    /// Mid-row colour change places a styled space and changes the pen colour.
988    #[test]
989    fn mid_row_colour() {
990        let mut dec = Cea608Decoder::new();
991        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL
992        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15
993        dec.push_pair(false, set_odd_parity(b'A'), set_odd_parity(0x00));
994        dec.push_pair(false, set_odd_parity(0x11), set_odd_parity(0x22)); // mid-row Green
995        dec.push_pair(false, set_odd_parity(b'B'), set_odd_parity(0x00));
996        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC
997        // Find the styled cells; "B" must be green.
998        let screen = dec.screen(Cea608Channel::Cc1);
999        let mut found_green_b = false;
1000        for row in screen.rows() {
1001            for (_, c) in row.styled_cells() {
1002                if c.ch == 'B' {
1003                    assert_eq!(c.color, Cea608Color::Green);
1004                    found_green_b = true;
1005                }
1006            }
1007        }
1008        assert!(found_green_b, "expected a green 'B'");
1009    }
1010
1011    #[test]
1012    fn caption_text_is_tracked_per_channel() {
1013        let mut dec = Cea608Decoder::new();
1014        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x29));
1015        dec.push_pair(false, set_odd_parity(b'H'), set_odd_parity(b'I'));
1016        assert!(dec.has_caption_text(Cea608Channel::Cc2));
1017        assert!(!dec.has_caption_text(Cea608Channel::Cc1));
1018        assert!(!dec.has_caption_text(Cea608Channel::Cc3));
1019        assert!(!dec.has_caption_text(Cea608Channel::Cc4));
1020    }
1021
1022    #[test]
1023    fn control_codes_xds_and_text_mode_are_not_caption_text() {
1024        let mut dec = Cea608Decoder::new();
1025        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20));
1026        dec.push_pair(true, set_odd_parity(0x01), set_odd_parity(0x03));
1027        dec.push_pair(true, set_odd_parity(b'A'), set_odd_parity(b'B'));
1028        dec.push_pair(true, set_odd_parity(0x0F), set_odd_parity(0x2C));
1029        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2A));
1030        dec.push_pair(false, set_odd_parity(b'T'), set_odd_parity(b'X'));
1031        for ch in [
1032            Cea608Channel::Cc1,
1033            Cea608Channel::Cc2,
1034            Cea608Channel::Cc3,
1035            Cea608Channel::Cc4,
1036        ] {
1037            assert!(!dec.has_caption_text(ch), "{}", ch.name());
1038        }
1039    }
1040
1041    /// Special character (musical note) via 0x11 0x37.
1042    #[test]
1043    fn special_char_music_note() {
1044        let mut dec = Cea608Decoder::new();
1045        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // RDC (paint-on → displayed)
1046        dec.push_pair(false, set_odd_parity(0x11), set_odd_parity(0x37)); // ♪ on CC1
1047        assert!(dec.channel_text(Cea608Channel::Cc1).contains('\u{266A}'));
1048    }
1049
1050    /// Extended char with automatic backspace: provider sends 'u' then ü code.
1051    #[test]
1052    fn extended_char_backspace() {
1053        let mut dec = Cea608Decoder::new();
1054        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x29)); // RDC
1055        dec.push_pair(false, set_odd_parity(b'u'), set_odd_parity(0x00)); // fallback 'u'
1056        dec.push_pair(false, set_odd_parity(0x12), set_odd_parity(0x25)); // extended ü (block1 0x25)
1057        let t = dec.channel_text(Cea608Channel::Cc1);
1058        assert_eq!(t, "\u{00FC}"); // just ü, the 'u' was backspaced
1059    }
1060
1061    /// Channel routing: a CC2 control (0x1C…) writes to CC2, not CC1.
1062    #[test]
1063    fn channel_cc2() {
1064        let mut dec = Cea608Decoder::new();
1065        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x29)); // RDC on data channel 2 → CC2
1066        assert_eq!(dec.mode(Cea608Channel::Cc2), Cea608Mode::PaintOn);
1067        assert_eq!(dec.mode(Cea608Channel::Cc1), Cea608Mode::None);
1068    }
1069
1070    /// Field 2 → CC3. CTA-608-E §8.4(a): field-2 misc-control's own first
1071    /// byte is `0x15` (the `0x14`→`0x15` shift), not the field-1 `0x14` byte
1072    /// (issue #1043 — the previous version of this test used `0x14` on
1073    /// field 2, which happened to pass for the wrong reason: `0x14` is not a
1074    /// valid field-2 misc-control byte at all, so it exercised no real code
1075    /// path distinct from field 1's).
1076    #[test]
1077    fn field2_cc3() {
1078        let mut dec = Cea608Decoder::new();
1079        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x29)); // RDC field 2 ch1 (0x15) → CC3
1080        assert_eq!(dec.mode(Cea608Channel::Cc3), Cea608Mode::PaintOn);
1081    }
1082
1083    /// Field 2, data channel 2 → CC4. CTA-608-E §8.4(b): the `0x1C`→`0x1D`
1084    /// shift (issue #1043).
1085    #[test]
1086    fn field2_cc4() {
1087        let mut dec = Cea608Decoder::new();
1088        dec.push_pair(true, set_odd_parity(0x1D), set_odd_parity(0x29)); // RDC field 2 ch2 (0x1D) → CC4
1089        assert_eq!(dec.mode(Cea608Channel::Cc4), Cea608Mode::PaintOn);
1090        assert_eq!(dec.mode(Cea608Channel::Cc3), Cea608Mode::None);
1091    }
1092
1093    /// XDS on field 2 is detected and skipped (no caption output).
1094    #[test]
1095    fn xds_skipped() {
1096        let mut dec = Cea608Decoder::new();
1097        dec.push_pair(true, set_odd_parity(0x01), set_odd_parity(0x02)); // XDS start (Current class)
1098        dec.push_pair(true, set_odd_parity(0x20), set_odd_parity(0x21)); // XDS informational
1099        dec.push_pair(true, set_odd_parity(0x0F), set_odd_parity(0x40)); // XDS end + checksum
1100        assert_eq!(dec.channel_text(Cea608Channel::Cc3), "");
1101    }
1102
1103    /// CC-W2 (#1107): a caption control code sent while an XDS sub-packet is
1104    /// open must interrupt it, not be swallowed. Pre-fix, the `xds_active`
1105    /// short-circuit ran before the control-code check, so every code between
1106    /// XDS Start and End (here, all of RCL/PAC/EOC) was silently dropped and
1107    /// "HI" was never displayed.
1108    #[test]
1109    fn control_code_interrupts_open_xds() {
1110        let mut dec = Cea608Decoder::new();
1111        dec.push_pair(true, set_odd_parity(0x01), set_odd_parity(0x02)); // XDS start (Current class)
1112        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x20)); // RCL on CC3 (field-2 misc)
1113        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x70)); // PAC row 15 white indent0
1114        dec.push_pair(true, set_odd_parity(b'H'), set_odd_parity(b'I'));
1115        dec.push_pair(true, set_odd_parity(0x15), set_odd_parity(0x2F)); // EOC → flip to displayed
1116        assert_eq!(dec.channel_text(Cea608Channel::Cc3), "HI");
1117    }
1118
1119    /// CC-W1 (#1107): standard (untagged) characters must route to the
1120    /// channel targeted by the field's last control code, not a hardcoded
1121    /// CC1/CC3. Pre-fix, `default_channel` always returned CC1 for field 1,
1122    /// so CC2's characters were written into CC1's memory and interleaved
1123    /// with CC1's own text.
1124    #[test]
1125    fn standard_chars_follow_last_control_channel() {
1126        let mut dec = Cea608Decoder::new();
1127        // CC1: pop-on "AB".
1128        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x20)); // RCL (CC1, base1=0x14)
1129        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x70)); // PAC row 15 (CC1)
1130        dec.push_pair(false, set_odd_parity(b'A'), set_odd_parity(b'B'));
1131        dec.push_pair(false, set_odd_parity(0x14), set_odd_parity(0x2F)); // EOC (CC1)
1132        // CC2: pop-on "CD" — b1 in 0x18..=0x1F selects data channel 2.
1133        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x20)); // RCL (CC2, base1=0x14 folded)
1134        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x70)); // PAC row 15 (CC2)
1135        dec.push_pair(false, set_odd_parity(b'C'), set_odd_parity(b'D'));
1136        dec.push_pair(false, set_odd_parity(0x1C), set_odd_parity(0x2F)); // EOC (CC2)
1137        assert_eq!(dec.channel_text(Cea608Channel::Cc1), "AB");
1138        assert_eq!(dec.channel_text(Cea608Channel::Cc2), "CD");
1139    }
1140
1141    #[test]
1142    fn standard_char_accents() {
1143        assert_eq!(Cea608Decoder::standard_char(0x2A), '\u{00E1}'); // á
1144        assert_eq!(Cea608Decoder::standard_char(b'A'), 'A');
1145        assert_eq!(Cea608Decoder::standard_char(0x7F), '\u{25A0}'); // ■
1146    }
1147
1148    #[test]
1149    fn no_panic_on_arbitrary_input() {
1150        let mut dec = Cea608Decoder::new();
1151        let mut x: u32 = 0xDEAD_BEEF;
1152        for _ in 0..8192 {
1153            x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
1154            let b1 = (x >> 8) as u8;
1155            let b2 = (x >> 16) as u8;
1156            let f2 = (x & 1) != 0;
1157            dec.push_pair(f2, b1, b2);
1158        }
1159        // Also via triplets, including invalid + truncated patterns.
1160        let triplets = [
1161            CcTriplet {
1162                cc_valid: true,
1163                cc_type: CcType::Ntsc608Field1,
1164                cc_data_1: 0x14,
1165                cc_data_2: 0x2D,
1166            },
1167            CcTriplet {
1168                cc_valid: false,
1169                cc_type: CcType::Ntsc608Field2,
1170                cc_data_1: 0xFF,
1171                cc_data_2: 0xFF,
1172            },
1173            CcTriplet {
1174                cc_valid: true,
1175                cc_type: CcType::Ntsc608Field2,
1176                cc_data_1: 0x01,
1177                cc_data_2: 0x00,
1178            },
1179        ];
1180        dec.push_triplets(&triplets);
1181    }
1182
1183    fn pair(d: &mut Cea608Decoder, a: u8, b: u8) {
1184        d.push_pair(false, set_odd_parity(a), set_odd_parity(b));
1185    }
1186
1187    #[test]
1188    fn text_restart_does_not_erase_the_caption_screen() {
1189        let mut d = Cea608Decoder::new();
1190        pair(&mut d, 0x14, 0x20);
1191        pair(&mut d, 0x14, 0x70);
1192        pair(&mut d, b'H', b'I');
1193        pair(&mut d, 0x14, 0x2F);
1194        assert_eq!(d.channel_text(Cea608Channel::Cc1), "HI");
1195        pair(&mut d, 0x14, 0x2A);
1196        pair(&mut d, b'T', b'X');
1197        assert_eq!(d.channel_text(Cea608Channel::Cc1), "HI");
1198    }
1199
1200    #[test]
1201    fn a_control_pair_after_a_null_pair_is_not_a_doubled_control() {
1202        let mut d = Cea608Decoder::new();
1203        pair(&mut d, 0x14, 0x25);
1204        pair(&mut d, b'A', b'B');
1205        pair(&mut d, 0x14, 0x2D);
1206        pair(&mut d, b'C', b'D');
1207        assert_eq!(d.channel_text(Cea608Channel::Cc1), "AB\nCD");
1208        pair(&mut d, 0x14, 0x2D);
1209        d.push_pair(false, 0x80, 0x80);
1210        pair(&mut d, 0x14, 0x2D);
1211        assert_eq!(d.channel_text(Cea608Channel::Cc1), "");
1212    }
1213
1214    #[test]
1215    fn a_field1_pair_with_first_byte_in_the_xds_range_prints_no_text() {
1216        let mut d = Cea608Decoder::new();
1217        pair(&mut d, 0x14, 0x29);
1218        pair(&mut d, 0x14, 0x70);
1219        pair(&mut d, 0x01, b'X');
1220        assert_eq!(d.channel_text(Cea608Channel::Cc1), "");
1221    }
1222}