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