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