Skip to main content

cc_data/decode/
cea708.rs

1//! CEA-708 (DTVCC) caption decode — ANSI/CTA-708-E S-2023 §5–§8 + 47 CFR §79.102.
2//!
3//! Decode pipeline (`private/specs-verified/captions/cc-data/decode/cea708-decode.md`):
4//! `cc_data` byte pairs → Caption Channel Packets (§5) → Service Blocks (§6) →
5//! the C0/C1/G0/G1/G2/G3 command interpreter (§7/§8) driving the window + pen
6//! model. Up to six services (47 CFR §79.102 (c)) are tracked; each service has
7//! eight windows (DF0–DF7) and a current pen. Decoded window text is exposed.
8//!
9//! Decoder is panic-free on arbitrary input: short / over-length packets, bad
10//! service blocks and truncated commands are ignored.
11
12use crate::cc_data::{CcTriplet, CcType};
13use crate::decode::screen::{
14    Color, EdgeType, FontStyle, Justify, Opacity, PenOffset, PenSize, PrintDirection,
15    ScrollDirection,
16};
17use alloc::string::String;
18use alloc::vec::Vec;
19
20/// Anchor point of a CEA-708 window — which corner / edge / centre the anchor
21/// coordinates refer to (CTA-708-E §8.4.6, 4-bit `ap` field, values 0–8).
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize))]
24#[non_exhaustive]
25pub enum AnchorPoint {
26    /// Top-left corner (ap = 0).
27    #[default]
28    TopLeft,
29    /// Top centre (ap = 1).
30    TopCenter,
31    /// Top-right corner (ap = 2).
32    TopRight,
33    /// Middle-left edge (ap = 3).
34    MiddleLeft,
35    /// Middle centre (ap = 4).
36    MiddleCenter,
37    /// Middle-right edge (ap = 5).
38    MiddleRight,
39    /// Bottom-left corner (ap = 6).
40    BottomLeft,
41    /// Bottom centre (ap = 7).
42    BottomCenter,
43    /// Bottom-right corner (ap = 8).
44    BottomRight,
45}
46
47impl AnchorPoint {
48    /// From the 4-bit `ap` wire value (§8.4.6; values 9–15 fold to `TopLeft`).
49    #[must_use]
50    pub fn from_bits(v: u8) -> Self {
51        match v & 0x0F {
52            0 => Self::TopLeft,
53            1 => Self::TopCenter,
54            2 => Self::TopRight,
55            3 => Self::MiddleLeft,
56            4 => Self::MiddleCenter,
57            5 => Self::MiddleRight,
58            6 => Self::BottomLeft,
59            7 => Self::BottomCenter,
60            8 => Self::BottomRight,
61            _ => Self::TopLeft,
62        }
63    }
64    /// Label per the project's `name()` convention.
65    #[must_use]
66    pub fn name(&self) -> &'static str {
67        match self {
68            Self::TopLeft => "top_left",
69            Self::TopCenter => "top_center",
70            Self::TopRight => "top_right",
71            Self::MiddleLeft => "middle_left",
72            Self::MiddleCenter => "middle_center",
73            Self::MiddleRight => "middle_right",
74            Self::BottomLeft => "bottom_left",
75            Self::BottomCenter => "bottom_center",
76            Self::BottomRight => "bottom_right",
77        }
78    }
79}
80broadcast_common::impl_spec_display!(AnchorPoint);
81
82// ── Service / window counts (§6.1, §8) ──────────────────────────────────────
83/// Number of standard services tracked (47 CFR §79.102 (c): Caption Service #1–#6).
84const NUM_SERVICES: usize = 6;
85const MIN_SERVICE_NUMBER: u8 = 1;
86const MAX_SERVICE_NUMBER: u8 = 63;
87/// Windows per service (DF0–DF7).
88const NUM_WINDOWS: usize = 8;
89/// Maximum rows in a window (rc field, virtual rows − 1, max 11 → 12 rows).
90const MAX_WINDOW_ROWS: usize = 12;
91/// Maximum columns in a window (cc field, virtual cols − 1, max 41 → 42 cols).
92const MAX_WINDOW_COLS: usize = 42;
93
94// ── Packet layer (§5) ───────────────────────────────────────────────────────
95/// `packet_size_code == 0` ⇒ 127 data bytes (§5.1).
96const PACKET_SIZE_ZERO_DATA: usize = 127;
97
98// ── Service block (§6.2) ──────────────────────────────────────────────────────
99/// `service_number == 7` is the extended-service escape (§6.2.2).
100const EXTENDED_SERVICE_ESCAPE: u8 = 7;
101
102// ── C0 control codes (§7.1.4, Table 13) ───────────────────────────────────────
103const C0_NUL: u8 = 0x00;
104const C0_ETX: u8 = 0x03;
105const C0_BS: u8 = 0x08;
106const C0_FF: u8 = 0x0C;
107const C0_CR: u8 = 0x0D;
108const C0_HCR: u8 = 0x0E;
109const C0_EXT1: u8 = 0x10;
110const C0_P16: u8 = 0x18;
111
112// ── C1 caption command opcodes (§7.1.5, Table 14) ─────────────────────────────
113const C1_CW0: u8 = 0x80; // CW0..CW7 = 0x80..=0x87
114const C1_CW7: u8 = 0x87;
115const C1_CLW: u8 = 0x88;
116const C1_DSW: u8 = 0x89;
117const C1_HDW: u8 = 0x8A;
118const C1_TGW: u8 = 0x8B;
119const C1_DLW: u8 = 0x8C;
120const C1_DLY: u8 = 0x8D;
121const C1_DLC: u8 = 0x8E;
122const C1_RST: u8 = 0x8F;
123const C1_SPA: u8 = 0x90;
124const C1_SPC: u8 = 0x91;
125const C1_SPL: u8 = 0x92;
126const C1_SWA: u8 = 0x97;
127const C1_DF0: u8 = 0x98; // DF0..DF7 = 0x98..=0x9F
128const C1_DF7: u8 = 0x9F;
129
130// ── Code-space range boundaries (§7.1, Table 11) ──────────────────────────────
131const C0_END: u8 = 0x1F;
132const G0_START: u8 = 0x20;
133const G0_END: u8 = 0x7F;
134const C1_START: u8 = 0x80;
135const C1_END: u8 = 0x9F;
136const G1_START: u8 = 0xA0;
137
138// ── G0 substitution (§7.1.6): 0x7F is the musical note, not DEL ───────────────
139const G0_MUSIC_NOTE: u8 = 0x7F;
140
141/// State of a window's display (§8.10.5 DisplayWindows / HideWindows / Toggle).
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
143#[cfg_attr(feature = "serde", derive(serde::Serialize))]
144#[non_exhaustive]
145pub enum WindowState {
146    /// Window defined but not yet shown (default after DefineWindow).
147    #[default]
148    Hidden,
149    /// Window is being displayed.
150    Visible,
151}
152
153impl WindowState {
154    /// Label per the project's `name()` convention.
155    #[must_use]
156    pub fn name(&self) -> &'static str {
157        match self {
158            Self::Hidden => "hidden",
159            Self::Visible => "visible",
160        }
161    }
162}
163broadcast_common::impl_spec_display!(WindowState);
164
165/// A decoded CEA-708 caption window (§8.4 window model).
166///
167/// Holds the window attributes set by `DefineWindow` / `SetWindowAttributes`,
168/// the pen attributes set by `SetPenAttributes` / `SetPenColor`, and the painted
169/// text grid. Only created when a `DefineWindow` for its ID is received.
170#[derive(Debug, Clone, PartialEq, Eq)]
171#[cfg_attr(feature = "serde", derive(serde::Serialize))]
172pub struct Window {
173    /// Whether the window is currently displayed.
174    pub state: WindowState,
175    /// Window priority, 0 (highest) – 7.
176    pub priority: u8,
177    /// Anchor point (which corner/edge/centre the anchor coordinates refer to).
178    pub anchor_point: AnchorPoint,
179    /// Anchor vertical coordinate.
180    pub anchor_vertical: u8,
181    /// Anchor horizontal coordinate.
182    pub anchor_horizontal: u8,
183    /// `true` if the anchor coordinates are relative (percent).
184    pub relative_position: bool,
185    /// Row count (virtual rows; = rc + 1).
186    pub row_count: u8,
187    /// Column count (virtual cols; = cc + 1).
188    pub column_count: u8,
189    /// Row lock.
190    pub row_lock: bool,
191    /// Column lock.
192    pub column_lock: bool,
193    /// Window-style preset ID (0–7) requested in the last DefineWindow.
194    pub window_style: u8,
195    /// Pen-style preset ID (0–7) requested in the last DefineWindow.
196    pub pen_style: u8,
197    /// Justification.
198    pub justify: Justify,
199    /// Print direction.
200    pub print_direction: PrintDirection,
201    /// Scroll direction.
202    pub scroll_direction: ScrollDirection,
203    /// Word wrap.
204    pub word_wrap: bool,
205    /// Window fill colour.
206    pub fill_color: Color,
207    /// Window fill opacity.
208    pub fill_opacity: Opacity,
209    /// Border colour.
210    pub border_color: Color,
211    /// Border type (none / raised / depressed / uniform / shadow).
212    pub border_type: EdgeType,
213    /// Pen size.
214    pub pen_size: PenSize,
215    /// Pen offset (subscript/normal/superscript).
216    pub pen_offset: PenOffset,
217    /// Font style.
218    pub font_style: FontStyle,
219    /// Pen italics.
220    pub italics: bool,
221    /// Pen underline.
222    pub underline: bool,
223    /// Pen edge type.
224    pub edge_type: EdgeType,
225    /// Pen edge colour (SPC parm3, §8.10.5.10) — distinct from the window's
226    /// `border_color` (SWA parm2, §8.10.5.8): the edge is drawn around each
227    /// glyph per `edge_type`, the border is drawn around the whole window.
228    pub edge_color: Color,
229    /// Pen foreground colour.
230    pub fg_color: Color,
231    /// Pen foreground opacity.
232    pub fg_opacity: Opacity,
233    /// Pen background colour.
234    pub bg_color: Color,
235    /// Pen background opacity.
236    pub bg_opacity: Opacity,
237    /// Text grid, `row_count` rows of `column_count` chars (rows are `String`s).
238    rows: Vec<String>,
239    /// Current pen row.
240    pen_row: usize,
241    /// Current pen column.
242    pen_col: usize,
243}
244
245impl Window {
246    fn new() -> Self {
247        Window {
248            state: WindowState::Hidden,
249            priority: 0,
250            anchor_point: AnchorPoint::TopLeft,
251            anchor_vertical: 0,
252            anchor_horizontal: 0,
253            relative_position: false,
254            row_count: 1,
255            column_count: 1,
256            row_lock: false,
257            column_lock: false,
258            window_style: 0,
259            pen_style: 0,
260            justify: Justify::Left,
261            print_direction: PrintDirection::LeftToRight,
262            scroll_direction: ScrollDirection::BottomToTop,
263            word_wrap: false,
264            fill_color: Color::BLACK,
265            fill_opacity: Opacity::Solid,
266            border_color: Color::BLACK,
267            border_type: EdgeType::None,
268            pen_size: PenSize::Standard,
269            pen_offset: PenOffset::Normal,
270            font_style: FontStyle::Default,
271            italics: false,
272            underline: false,
273            edge_type: EdgeType::None,
274            edge_color: Color::BLACK,
275            fg_color: Color::WHITE,
276            fg_opacity: Opacity::Solid,
277            bg_color: Color::BLACK,
278            bg_opacity: Opacity::Solid,
279            rows: Vec::new(),
280            pen_row: 0,
281            pen_col: 0,
282        }
283    }
284
285    fn ensure_grid(&mut self) {
286        let rows = (self.row_count as usize).clamp(1, MAX_WINDOW_ROWS);
287        if self.rows.len() != rows {
288            self.rows = alloc::vec![String::new(); rows];
289        }
290    }
291
292    fn clear_text(&mut self) {
293        for r in &mut self.rows {
294            r.clear();
295        }
296        self.pen_row = 0;
297        self.pen_col = 0;
298    }
299
300    fn cols(&self) -> usize {
301        (self.column_count as usize).clamp(1, MAX_WINDOW_COLS)
302    }
303
304    /// Write a character at the current pen position (overwriting any cell there), advancing the pen.
305    fn put_char(&mut self, ch: char) {
306        self.ensure_grid();
307        let cols = self.cols();
308        if self.pen_row >= self.rows.len() {
309            return;
310        }
311        // pad row out to pen_col with spaces
312        let row = &mut self.rows[self.pen_row];
313        while row.chars().count() < self.pen_col {
314            row.push(' ');
315        }
316        if self.pen_col < cols {
317            match row.char_indices().nth(self.pen_col) {
318                Some((at, old)) => {
319                    row.replace_range(at..at + old.len_utf8(), ch.encode_utf8(&mut [0; 4]))
320                }
321                None => row.push(ch),
322            }
323            self.pen_col += 1;
324        }
325    }
326
327    /// Back Space (C0 BS).
328    fn back_space(&mut self) {
329        if self.pen_col > 0 {
330            self.pen_col -= 1;
331            if self.pen_row < self.rows.len() {
332                let row = &mut self.rows[self.pen_row];
333                let mut chars: Vec<char> = row.chars().collect();
334                if self.pen_col < chars.len() {
335                    chars.truncate(self.pen_col);
336                    *row = chars.into_iter().collect();
337                }
338            }
339        }
340    }
341
342    /// Carriage Return (C0 CR): start of next row; roll up if past the bottom.
343    fn carriage_return(&mut self) {
344        self.ensure_grid();
345        self.pen_col = 0;
346        if self.pen_row + 1 < self.rows.len() {
347            self.pen_row += 1;
348        } else if !self.rows.is_empty() {
349            // roll up: drop the top row, append a blank at the bottom
350            self.rows.remove(0);
351            self.rows.push(String::new());
352            self.pen_row = self.rows.len() - 1;
353        }
354    }
355
356    /// Horizontal Carriage Return (C0 HCR): start of current row, erase the row.
357    fn horizontal_cr(&mut self) {
358        self.ensure_grid();
359        if self.pen_row < self.rows.len() {
360            self.rows[self.pen_row].clear();
361        }
362        self.pen_col = 0;
363    }
364
365    fn set_pen_location(&mut self, row: usize, col: usize) {
366        self.ensure_grid();
367        self.pen_row = row.min(self.rows.len().saturating_sub(1));
368        self.pen_col = col.min(self.cols());
369    }
370
371    /// The window's visible text, non-empty rows joined with `\n`, per-row
372    /// trailing spaces removed. Blank rows (interior or trailing) are dropped
373    /// entirely rather than emitted as an empty line: a run of them would
374    /// otherwise produce consecutive `\n`s, which downstream consumers (e.g.
375    /// `timed-metadata`'s WebVTT cue writer) read as a cue-block terminator.
376    #[must_use]
377    pub fn text(&self) -> String {
378        let lines: Vec<&str> = self
379            .rows
380            .iter()
381            .map(|r| r.trim_end())
382            .filter(|l| !l.is_empty())
383            .collect();
384        lines.join("\n")
385    }
386}
387
388/// One DTVCC service (§6.1): up to eight windows + a current-window pointer.
389#[derive(Debug, Clone, PartialEq, Eq, Default)]
390#[cfg_attr(feature = "serde", derive(serde::Serialize))]
391struct Service {
392    windows: [Option<Window>; NUM_WINDOWS],
393    /// Current window ID (0–7), or `None` when unknown.
394    current_window: Option<usize>,
395}
396
397impl Service {
398    fn reset(&mut self) {
399        *self = Service::default();
400    }
401
402    fn current(&mut self) -> Option<&mut Window> {
403        let id = self.current_window?;
404        self.windows.get_mut(id)?.as_mut()
405    }
406}
407
408/// CEA-708 (DTVCC) caption decoder.
409///
410/// Feed it [`CcTriplet`]s (or raw `cc_data` byte pairs) from the DTVCC stream
411/// (`cc_type` 2/3); read decoded window text per service via
412/// [`service_text`](Cea708Decoder::service_text) / [`windows`](Cea708Decoder::windows).
413///
414/// ```
415/// use cc_data::decode::Cea708Decoder;
416/// let mut dec = Cea708Decoder::new();
417/// // A CCP (header + service-1 block) carrying the DefineWindow worked example
418/// // for window 2: 0x9A 38 4A D1 8B 0F 11.
419/// dec.push_packet(&[0x05, 0x27, 0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11]);
420/// let w = &dec.windows(1)[2];
421/// assert!(w.is_some());
422/// ```
423#[derive(Debug, Clone, PartialEq, Eq)]
424#[cfg_attr(feature = "serde", derive(serde::Serialize))]
425pub struct Cea708Decoder {
426    services: [Service; NUM_SERVICES],
427    /// Accumulated CCP data for the in-progress packet.
428    packet: Vec<u8>,
429    /// Last sequence number seen (for discontinuity detection).
430    last_seq: Option<u8>,
431    /// Bit `n` set once a service block with content has arrived for service
432    /// `n` (1 to 63), whether or not this decoder models that service.
433    services_seen: u64,
434}
435
436impl Default for Cea708Decoder {
437    fn default() -> Self {
438        Self::new()
439    }
440}
441
442impl Cea708Decoder {
443    /// A new decoder with no services defined.
444    #[must_use]
445    pub fn new() -> Self {
446        Cea708Decoder {
447            services: Default::default(),
448            packet: Vec::new(),
449            last_seq: None,
450            services_seen: 0,
451        }
452    }
453
454    /// The service numbers (1 to 63) for which a service block carrying at
455    /// least one non-null byte has been received, ascending. Covers every
456    /// service number the wire can address, not only the 1 to 6 this decoder
457    /// interprets.
458    #[must_use]
459    pub fn services_seen(&self) -> Vec<u8> {
460        (MIN_SERVICE_NUMBER..=MAX_SERVICE_NUMBER)
461            .filter(|n| self.services_seen & (1u64 << n) != 0)
462            .collect()
463    }
464
465    /// Reset every service (§8.9.5 packet-loss recovery / RST).
466    pub fn reset(&mut self) {
467        for s in &mut self.services {
468            s.reset();
469        }
470        self.packet.clear();
471        self.last_seq = None;
472    }
473
474    /// Feed the decoder the 708 (DTVCC) triplets of a [`crate::CcData`].
475    ///
476    /// A `cc_type == Dtvcc708Start` triplet begins a new Caption Channel Packet;
477    /// `Dtvcc708Data` triplets continue it. Invalid triplets are skipped. A CCP
478    /// is not required to fit in one call (CEA-708 §4/§5: a `cc_data()` access
479    /// unit typically carries far fewer DTVCC bytes than a full CCP), so the
480    /// partial packet buffer is kept across calls and only decoded once it is
481    /// complete (its declared `packet_size_code` worth of bytes has arrived)
482    /// or a new packet starts.
483    pub fn push_triplets<'a, I>(&mut self, triplets: I)
484    where
485        I: IntoIterator<Item = &'a CcTriplet>,
486    {
487        for t in triplets {
488            if !t.cc_valid {
489                continue;
490            }
491            match t.cc_type {
492                CcType::Dtvcc708Start => {
493                    // A new CCP starts; flush whatever the previous one
494                    // accumulated first (§5.1) rather than silently merging
495                    // it with the new packet's bytes.
496                    self.flush_packet();
497                    self.packet.clear();
498                    self.packet.push(t.cc_data_1);
499                    self.packet.push(t.cc_data_2);
500                }
501                CcType::Dtvcc708Data => {
502                    if self.packet.is_empty() {
503                        // Data with no open packet (e.g. the Start triplet
504                        // was lost, or right after a reset): a lone Data
505                        // byte pair is not a valid CCP header, so it must
506                        // not seed one (§4) -- drop it instead of decoding
507                        // it as a header on the next flush.
508                        continue;
509                    }
510                    self.packet.push(t.cc_data_1);
511                    self.packet.push(t.cc_data_2);
512                }
513                _ => {}
514            }
515        }
516        // Flush only once the buffered bytes form a complete CCP; a partial
517        // packet is left in the buffer for the next call. This is the fix
518        // for issue #1042: the previous unconditional flush here decoded
519        // (and cleared) every still-partial CCP at the end of every single
520        // call, destroying any packet that spanned more than one call.
521        if self.packet_is_complete() {
522            self.flush_packet();
523        }
524    }
525
526    /// Feed one complete Caption Channel Packet (the CCP header byte followed by
527    /// its data bytes). Useful for testing / when packets are pre-assembled.
528    pub fn push_packet(&mut self, ccp: &[u8]) {
529        self.decode_packet(ccp);
530    }
531
532    /// Whether the accumulated packet buffer holds a full CCP: the header
533    /// byte plus its declared `data_size` bytes (§5, the same accounting
534    /// `decode_packet` uses).
535    fn packet_is_complete(&self) -> bool {
536        let Some(&header) = self.packet.first() else {
537            return false;
538        };
539        let size_code = header & 0x3F;
540        let data_size = if size_code == 0 {
541            PACKET_SIZE_ZERO_DATA
542        } else {
543            (size_code as usize) * 2 - 1
544        };
545        self.packet.len() > data_size
546    }
547
548    /// Flush the accumulated packet buffer if it forms a complete CCP.
549    fn flush_packet(&mut self) {
550        if self.packet.is_empty() {
551            return;
552        }
553        let packet = core::mem::take(&mut self.packet);
554        self.decode_packet(&packet);
555    }
556
557    /// Decode a Caption Channel Packet (§5): header byte + service blocks.
558    fn decode_packet(&mut self, ccp: &[u8]) {
559        let Some((&header, rest)) = ccp.split_first() else {
560            return;
561        };
562        let seq = (header >> 6) & 0x03;
563        let size_code = header & 0x3F;
564        let data_size = if size_code == 0 {
565            PACKET_SIZE_ZERO_DATA
566        } else {
567            (size_code as usize) * 2 - 1
568        };
569        // discontinuity check (§5.1): non-consecutive seq ⇒ reset every service
570        if let Some(prev) = self.last_seq
571            && seq != (prev + 1) & 0x03
572        {
573            for s in &mut self.services {
574                s.reset();
575            }
576        }
577        self.last_seq = Some(seq);
578        let end = data_size.min(rest.len());
579        self.decode_service_blocks(&rest[..end]);
580    }
581
582    /// Walk the service blocks of a CCP (§6.2).
583    fn decode_service_blocks(&mut self, mut data: &[u8]) {
584        loop {
585            let Some((&header, rest)) = data.split_first() else {
586                return;
587            };
588            // Null Service Block Header (§6.2.3): all-zero ⇒ no more blocks.
589            if header == 0 {
590                return;
591            }
592            let mut service_number = u16::from((header >> 5) & 0x07);
593            let block_size = (header & 0x1F) as usize;
594            let mut body = rest;
595            if service_number == u16::from(EXTENDED_SERVICE_ESCAPE) && block_size != 0 {
596                // Extended Service Block Header (§6.2.2): 2nd byte low 6 bits.
597                let Some((&ext, after)) = rest.split_first() else {
598                    return;
599                };
600                service_number = u16::from(ext & 0x3F);
601                body = after;
602            }
603            if block_size > body.len() {
604                // truncated block — process what we have, then stop
605                self.dispatch_service(service_number, body);
606                return;
607            }
608            let (block, next) = body.split_at(block_size);
609            self.dispatch_service(service_number, block);
610            data = next;
611        }
612    }
613
614    fn dispatch_service(&mut self, service_number: u16, block: &[u8]) {
615        if (u16::from(MIN_SERVICE_NUMBER)..=u16::from(MAX_SERVICE_NUMBER)).contains(&service_number)
616            && block.iter().any(|&b| b != 0)
617        {
618            self.services_seen |= 1u64 << service_number;
619        }
620        // We track standard services 1–6 (47 CFR §79.102 (c)).
621        if service_number == 0 || service_number as usize > NUM_SERVICES {
622            return;
623        }
624        let idx = service_number as usize - 1;
625        Self::interpret(&mut self.services[idx], block);
626    }
627
628    /// The C0/C1/G0/G1/G2/G3 command interpreter (§7/§8) for one service block.
629    fn interpret(service: &mut Service, block: &[u8]) {
630        let mut i = 0usize;
631        while i < block.len() {
632            let b = block[i];
633            let consumed = match b {
634                0x00..=C0_END => Self::handle_c0(service, &block[i..]),
635                G0_START..=G0_END => {
636                    Self::put(service, Self::g0_char(b));
637                    1
638                }
639                C1_START..=C1_END => Self::handle_c1(service, &block[i..]),
640                G1_START..=0xFF => {
641                    // G1 = ISO 8859-1 Latin-1: byte value is the code point.
642                    Self::put(service, char::from(b));
643                    1
644                }
645            };
646            i += consumed.max(1);
647        }
648    }
649
650    /// Handle a C0 control code (§7.1.4). Returns bytes consumed (≥1).
651    fn handle_c0(service: &mut Service, data: &[u8]) -> usize {
652        let b = data[0];
653        match b {
654            C0_NUL => 1,
655            C0_ETX => 1,
656            // Each of BS/FF/CR/HCR is a no-op when there's no current window
657            // (falls through to the trailing `_ => 1`, same as the guard-true
658            // arms below — every path through this match returns 1).
659            C0_BS if let Some(w) = service.current() => {
660                w.back_space();
661                1
662            }
663            C0_FF if let Some(w) = service.current() => {
664                w.clear_text();
665                1
666            }
667            C0_CR if let Some(w) = service.current() => {
668                w.carriage_return();
669                1
670            }
671            C0_HCR if let Some(w) = service.current() => {
672                w.horizontal_cr();
673                1
674            }
675            C0_EXT1 => Self::handle_ext1(service, data),
676            C0_P16 => 3, // P16: command + 2 bytes (16-bit char addressing)
677            // Undefined codes: 0x11–0x17 ⇒ 2 bytes; 0x19–0x1F ⇒ 3 bytes; all
678            // other (undefined 0x00–0x0F) ⇒ 1 byte (§7.1.4).
679            0x11..=0x17 => 2,
680            0x19..=0x1F => 3,
681            _ => 1,
682        }
683    }
684
685    /// EXT1 (0x10) prefix → C2/G2/C3/G3 (§7.1.1). Returns total bytes consumed
686    /// including the EXT1 byte.
687    fn handle_ext1(service: &mut Service, data: &[u8]) -> usize {
688        let Some(&base) = data.get(1) else {
689            return 1;
690        };
691        match base {
692            // C2 (0x00–0x1F): EXT1 + base + 0..=3 data bytes (Table 20).
693            0x00..=0x07 => 2,
694            0x08..=0x0F => 3,
695            0x10..=0x17 => 4,
696            0x18..=0x1F => 5,
697            // G2 (0x20–0x7F): EXT1 + base (two-byte element).
698            0x20..=0x7F => {
699                Self::put(service, Self::g2_char(base));
700                2
701            }
702            // C3 (0x80–0x9F): fixed/variable length (Tables 22/23).
703            0x80..=0x87 => 6,
704            0x88..=0x8F => 7,
705            0x90..=0x9F => {
706                // variable: 1-byte header after the command; N = (data1 & 0x3F)+1.
707                let n = data.get(2).map_or(0, |d| (d & 0x3F) as usize + 1);
708                3 + n
709            }
710            // G3 (0xA0–0xFF): EXT1 + base (two-byte element).
711            _ => {
712                Self::put(service, Self::g3_char(base));
713                2
714            }
715        }
716    }
717
718    /// Handle a C1 caption command (§7.1.5 / §8.10.5). Returns bytes consumed.
719    fn handle_c1(service: &mut Service, data: &[u8]) -> usize {
720        let op = data[0];
721        match op {
722            C1_CW0..=C1_CW7 => {
723                let id = (op - C1_CW0) as usize;
724                if service.windows.get(id).and_then(|w| w.as_ref()).is_some() {
725                    service.current_window = Some(id);
726                }
727                1
728            }
729            C1_CLW => Self::window_map_cmd(service, data, WindowMapOp::Clear),
730            C1_DSW => Self::window_map_cmd(service, data, WindowMapOp::Display),
731            C1_HDW => Self::window_map_cmd(service, data, WindowMapOp::Hide),
732            C1_TGW => Self::window_map_cmd(service, data, WindowMapOp::Toggle),
733            C1_DLW => Self::window_map_cmd(service, data, WindowMapOp::Delete),
734            C1_DLY => 2, // DLY: command + tenths-of-seconds
735            C1_DLC => 1, // DLC: no parameters
736            C1_RST => {
737                service.reset();
738                1
739            }
740            C1_SPA => Self::set_pen_attributes(service, data),
741            C1_SPC => Self::set_pen_color(service, data),
742            C1_SPL => Self::set_pen_location(service, data),
743            C1_SWA => Self::set_window_attributes(service, data),
744            C1_DF0..=C1_DF7 => Self::define_window(service, data),
745            // 0x93–0x96 reserved 1-byte window commands (§7.1.5.1).
746            _ => 1,
747        }
748    }
749
750    fn window_map_cmd(service: &mut Service, data: &[u8], op: WindowMapOp) -> usize {
751        let Some(&map) = data.get(1) else {
752            return 1;
753        };
754        for id in 0..NUM_WINDOWS {
755            if map & (1 << id) == 0 {
756                continue;
757            }
758            match op {
759                WindowMapOp::Clear if let Some(w) = service.windows[id].as_mut() => {
760                    w.clear_text();
761                }
762                WindowMapOp::Clear => {}
763                WindowMapOp::Display if let Some(w) = service.windows[id].as_mut() => {
764                    w.state = WindowState::Visible;
765                }
766                WindowMapOp::Display => {}
767                WindowMapOp::Hide if let Some(w) = service.windows[id].as_mut() => {
768                    w.state = WindowState::Hidden;
769                }
770                WindowMapOp::Hide => {}
771                WindowMapOp::Toggle if let Some(w) = service.windows[id].as_mut() => {
772                    w.state = match w.state {
773                        WindowState::Visible => WindowState::Hidden,
774                        WindowState::Hidden => WindowState::Visible,
775                    };
776                }
777                WindowMapOp::Toggle => {}
778                WindowMapOp::Delete => {
779                    service.windows[id] = None;
780                    if service.current_window == Some(id) {
781                        service.current_window = None;
782                    }
783                }
784            }
785        }
786        2
787    }
788
789    /// DefineWindow DF0–DF7 (§8.10.5.2): 6 parameter bytes.
790    fn define_window(service: &mut Service, data: &[u8]) -> usize {
791        const TOTAL: usize = 7;
792        if data.len() < TOTAL {
793            return data.len().max(1);
794        }
795        let id = (data[0] - C1_DF0) as usize;
796        let p1 = data[1];
797        let p2 = data[2];
798        let p3 = data[3];
799        let p4 = data[4];
800        let p5 = data[5];
801        let p6 = data[6];
802
803        let creating = service.windows[id].is_none();
804        let w = service.windows[id].get_or_insert_with(Window::new);
805
806        w.priority = p1 & 0x07;
807        w.column_lock = (p1 >> 3) & 0x01 != 0;
808        w.row_lock = (p1 >> 4) & 0x01 != 0;
809        w.state = if (p1 >> 5) & 0x01 != 0 {
810            WindowState::Visible
811        } else {
812            WindowState::Hidden
813        };
814        w.relative_position = (p2 >> 7) & 0x01 != 0;
815        w.anchor_vertical = p2 & 0x7F;
816        w.anchor_horizontal = p3;
817        w.anchor_point = AnchorPoint::from_bits((p4 >> 4) & 0x0F);
818        w.row_count = (p4 & 0x0F) + 1;
819        w.column_count = (p5 & 0x3F) + 1;
820        w.window_style = (p6 >> 3) & 0x07;
821        w.pen_style = p6 & 0x07;
822
823        if creating {
824            // On create: apply preset window/pen styles, fill, pen at (0,0).
825            apply_window_style(
826                w,
827                if w.window_style == 0 {
828                    1
829                } else {
830                    w.window_style
831                },
832            );
833            apply_pen_style(w, if w.pen_style == 0 { 1 } else { w.pen_style });
834            w.ensure_grid();
835            w.clear_text();
836        } else {
837            // On update: a non-zero style preset is re-applied; pen unaffected.
838            if w.window_style != 0 {
839                apply_window_style(w, w.window_style);
840            }
841            if w.pen_style != 0 {
842                apply_pen_style(w, w.pen_style);
843            }
844            w.ensure_grid();
845        }
846        service.current_window = Some(id);
847        TOTAL
848    }
849
850    /// SetWindowAttributes SWA (§8.10.5.8): 4 parameter bytes.
851    fn set_window_attributes(service: &mut Service, data: &[u8]) -> usize {
852        const TOTAL: usize = 5;
853        if data.len() < TOTAL {
854            return data.len().max(1);
855        }
856        let p1 = data[1];
857        let p2 = data[2];
858        let p3 = data[3];
859        let p4 = data[4];
860        if let Some(w) = service.current() {
861            w.fill_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
862            w.fill_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
863            let bt_lo = (p2 >> 6) & 0x03;
864            w.border_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
865            let bt_hi = (p3 >> 7) & 0x01;
866            w.border_type = EdgeType::from_bits((bt_hi << 2) | bt_lo);
867            w.word_wrap = (p3 >> 6) & 0x01 != 0;
868            w.print_direction = PrintDirection::from_bits((p3 >> 4) & 0x03);
869            w.scroll_direction = ScrollDirection::from_bits((p3 >> 2) & 0x03);
870            w.justify = Justify::from_bits(p3 & 0x03);
871            // p4: effect speed / direction / display effect — not rendered here.
872            let _ = p4;
873        }
874        TOTAL
875    }
876
877    /// SetPenAttributes SPA (§8.10.5.9): 2 parameter bytes.
878    fn set_pen_attributes(service: &mut Service, data: &[u8]) -> usize {
879        const TOTAL: usize = 3;
880        if data.len() < TOTAL {
881            return data.len().max(1);
882        }
883        let p1 = data[1];
884        let p2 = data[2];
885        if let Some(w) = service.current() {
886            w.pen_offset = PenOffset::from_bits((p1 >> 2) & 0x03);
887            w.pen_size = PenSize::from_bits(p1 & 0x03);
888            w.italics = (p2 >> 7) & 0x01 != 0;
889            w.underline = (p2 >> 6) & 0x01 != 0;
890            w.edge_type = EdgeType::from_bits((p2 >> 3) & 0x07);
891            w.font_style = FontStyle::from_bits(p2 & 0x07);
892        }
893        TOTAL
894    }
895
896    /// SetPenColor SPC (§8.10.5.10): 3 parameter bytes.
897    fn set_pen_color(service: &mut Service, data: &[u8]) -> usize {
898        const TOTAL: usize = 4;
899        if data.len() < TOTAL {
900            return data.len().max(1);
901        }
902        let p1 = data[1];
903        let p2 = data[2];
904        let p3 = data[3];
905        if let Some(w) = service.current() {
906            w.fg_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
907            w.fg_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
908            w.bg_opacity = Opacity::from_bits((p2 >> 6) & 0x03);
909            w.bg_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
910            // p3 = edge colour (the pen's own edge, not the window border).
911            w.edge_color = Color::new((p3 >> 4) & 0x03, (p3 >> 2) & 0x03, p3 & 0x03);
912        }
913        TOTAL
914    }
915
916    /// SetPenLocation SPL (§8.10.5.11): 2 parameter bytes.
917    fn set_pen_location(service: &mut Service, data: &[u8]) -> usize {
918        const TOTAL: usize = 3;
919        if data.len() < TOTAL {
920            return data.len().max(1);
921        }
922        let row = (data[1] & 0x0F) as usize;
923        let col = (data[2] & 0x3F) as usize;
924        if let Some(w) = service.current() {
925            w.set_pen_location(row, col);
926        }
927        TOTAL
928    }
929
930    fn put(service: &mut Service, ch: char) {
931        if let Some(w) = service.current() {
932            w.put_char(ch);
933        }
934    }
935
936    /// G0 byte → glyph (§7.1.6): ASCII printable, 0x7F = musical note ♪.
937    fn g0_char(b: u8) -> char {
938        if b == G0_MUSIC_NOTE {
939            '\u{266A}'
940        } else {
941            char::from(b)
942        }
943    }
944
945    /// G2 byte → glyph (§7.1.8 / Table 17), with substitution for the rest.
946    fn g2_char(b: u8) -> char {
947        match b {
948            0x20 | 0x21 => ' ', // TSP / NBTSP — transparent space
949            0x25 => '\u{2026}', // …
950            0x2A => '\u{0160}', // Š
951            0x2C => '\u{0152}', // Œ
952            0x30 => '\u{25A0}', // ■ solid block
953            0x31 => '\u{2018}', // ‘
954            0x32 => '\u{2019}', // ’
955            0x33 => '\u{201C}', // "
956            0x34 => '\u{201D}', // "
957            0x35 => '\u{2022}', // • bullet
958            0x39 => '\u{2122}', // ™
959            0x3A => '\u{0161}', // š
960            0x3C => '\u{0153}', // œ
961            0x3D => '\u{2120}', // ℠
962            0x3F => '\u{0178}', // Ÿ
963            0x76 => '\u{215B}', // ⅛
964            0x77 => '\u{215C}', // ⅜
965            0x78 => '\u{215D}', // ⅝
966            0x79 => '\u{215E}', // ⅞
967            _ => '_',           // unsupported G2 ⇒ underscore (Table 28 floor)
968        }
969    }
970
971    /// G3 byte → glyph (§7.1.9): 0xA0 = [CC] icon; the rest substitute `_`.
972    fn g3_char(b: u8) -> char {
973        if b == 0xA0 {
974            '\u{1F4FA}' // 📺 stand-in for the [CC] icon
975        } else {
976            '_'
977        }
978    }
979
980    /// Read the windows of a service (`1`–`6`). Returns an empty array view for
981    /// an out-of-range service number.
982    #[must_use]
983    pub fn windows(&self, service_number: usize) -> &[Option<Window>; NUM_WINDOWS] {
984        const EMPTY: [Option<Window>; NUM_WINDOWS] =
985            [None, None, None, None, None, None, None, None];
986        if service_number == 0 || service_number > NUM_SERVICES {
987            return &EMPTY;
988        }
989        &self.services[service_number - 1].windows
990    }
991
992    /// All decoded text for a service (`1`–`6`), visible-window text joined with
993    /// `\n` in window-priority order (0 = highest first), then by window ID.
994    #[must_use]
995    pub fn service_text(&self, service_number: usize) -> String {
996        if service_number == 0 || service_number > NUM_SERVICES {
997            return String::new();
998        }
999        let svc = &self.services[service_number - 1];
1000        let mut idxs: Vec<usize> = (0..NUM_WINDOWS)
1001            .filter(|&i| {
1002                svc.windows[i]
1003                    .as_ref()
1004                    .is_some_and(|w| w.state == WindowState::Visible)
1005            })
1006            .collect();
1007        idxs.sort_by_key(|&i| {
1008            svc.windows[i]
1009                .as_ref()
1010                .map_or((u8::MAX, i), |w| (w.priority, i))
1011        });
1012        let mut out = String::new();
1013        for i in idxs {
1014            if let Some(w) = svc.windows[i].as_ref() {
1015                let t = w.text();
1016                if t.is_empty() {
1017                    continue;
1018                }
1019                if !out.is_empty() {
1020                    out.push('\n');
1021                }
1022                out.push_str(&t);
1023            }
1024        }
1025        out
1026    }
1027}
1028
1029/// The window-map command kinds that share the CLW/DSW/HDW/TGW/DLW bitmap byte.
1030#[derive(Clone, Copy)]
1031enum WindowMapOp {
1032    Clear,
1033    Display,
1034    Hide,
1035    Toggle,
1036    Delete,
1037}
1038
1039/// Apply a predefined window style 1–7 (Table 26).
1040fn apply_window_style(w: &mut Window, id: u8) {
1041    // All presets: print dir L→R (except 7), scroll BOTTOM→TOP (except 7),
1042    // border NONE, display effect SNAP. justify + wordwrap + fill vary.
1043    w.border_type = EdgeType::None;
1044    match id {
1045        1 => style(w, Justify::Left, false, Some(Color::BLACK), Opacity::Solid),
1046        2 => style(w, Justify::Left, false, None, Opacity::Transparent),
1047        3 => style(
1048            w,
1049            Justify::Center,
1050            false,
1051            Some(Color::BLACK),
1052            Opacity::Solid,
1053        ),
1054        4 => style(w, Justify::Left, true, Some(Color::BLACK), Opacity::Solid),
1055        5 => style(w, Justify::Left, true, None, Opacity::Transparent),
1056        6 => style(w, Justify::Center, true, Some(Color::BLACK), Opacity::Solid),
1057        7 => {
1058            w.justify = Justify::Left;
1059            w.word_wrap = false;
1060            w.print_direction = PrintDirection::TopToBottom;
1061            w.scroll_direction = ScrollDirection::RightToLeft;
1062            w.fill_color = Color::BLACK;
1063            w.fill_opacity = Opacity::Solid;
1064        }
1065        _ => {}
1066    }
1067}
1068
1069fn style(w: &mut Window, j: Justify, ww: bool, fill: Option<Color>, op: Opacity) {
1070    w.justify = j;
1071    w.word_wrap = ww;
1072    w.print_direction = PrintDirection::LeftToRight;
1073    w.scroll_direction = ScrollDirection::BottomToTop;
1074    w.fill_opacity = op;
1075    if let Some(c) = fill {
1076        w.fill_color = c;
1077    }
1078}
1079
1080/// Apply a predefined pen style 1–7 (Table 27).
1081fn apply_pen_style(w: &mut Window, id: u8) {
1082    w.pen_size = PenSize::Standard;
1083    w.pen_offset = PenOffset::Normal;
1084    w.italics = false;
1085    w.underline = false;
1086    w.fg_color = Color::WHITE;
1087    w.fg_opacity = Opacity::Solid;
1088    match id {
1089        1 => pen(
1090            w,
1091            FontStyle::Default,
1092            EdgeType::None,
1093            Color::BLACK,
1094            Opacity::Solid,
1095        ),
1096        2 => pen(
1097            w,
1098            FontStyle::MonospacedSerif,
1099            EdgeType::None,
1100            Color::BLACK,
1101            Opacity::Solid,
1102        ),
1103        3 => pen(
1104            w,
1105            FontStyle::ProportionalSerif,
1106            EdgeType::None,
1107            Color::BLACK,
1108            Opacity::Solid,
1109        ),
1110        4 => pen(
1111            w,
1112            FontStyle::MonospacedSansSerif,
1113            EdgeType::None,
1114            Color::BLACK,
1115            Opacity::Solid,
1116        ),
1117        5 => pen(
1118            w,
1119            FontStyle::ProportionalSansSerif,
1120            EdgeType::None,
1121            Color::BLACK,
1122            Opacity::Solid,
1123        ),
1124        6 => pen(
1125            w,
1126            FontStyle::MonospacedSansSerif,
1127            EdgeType::Uniform,
1128            Color::BLACK,
1129            Opacity::Transparent,
1130        ),
1131        7 => pen(
1132            w,
1133            FontStyle::ProportionalSansSerif,
1134            EdgeType::Uniform,
1135            Color::BLACK,
1136            Opacity::Transparent,
1137        ),
1138        _ => {}
1139    }
1140}
1141
1142fn pen(w: &mut Window, font: FontStyle, edge: EdgeType, bg: Color, bg_op: Opacity) {
1143    w.font_style = font;
1144    w.edge_type = edge;
1145    w.bg_color = bg;
1146    w.bg_opacity = bg_op;
1147}
1148
1149#[cfg(test)]
1150mod tests {
1151    use super::*;
1152
1153    /// Build a single-service CCP carrying `cmds` as service `svc`'s block.
1154    fn ccp(svc: u8, cmds: &[u8]) -> Vec<u8> {
1155        let mut sb = alloc::vec![(svc << 5) | (cmds.len() as u8)];
1156        sb.extend_from_slice(cmds);
1157        // size_code = number of byte-pairs including the header byte.
1158        let size_code = (sb.len().div_ceil(2) + 1) as u8 & 0x3F;
1159        let mut packet = alloc::vec![size_code];
1160        packet.extend_from_slice(&sb);
1161        packet
1162    }
1163
1164    /// CTA-708-E DefineWindow worked example (`cea708-decode.md`, p.66–67):
1165    /// `0x9A 38 4A D1 8B 0F 11` → window id=2, visible=YES, rl=YES, cl=YES,
1166    /// priority=0, rp=0, av=74, ah=209, ap=8, rc=11 (→12 rows), cc=15 (→16 cols),
1167    /// ws=2, ps=1.
1168    #[test]
1169    fn define_window_worked_example() {
1170        let mut dec = Cea708Decoder::new();
1171        let packet = ccp(1, &[0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11]);
1172        dec.push_packet(&packet);
1173        let w = dec.windows(1)[2].as_ref().expect("window 2 defined");
1174        assert_eq!(w.state, WindowState::Visible);
1175        assert!(w.row_lock);
1176        assert!(w.column_lock);
1177        assert_eq!(w.priority, 0);
1178        assert!(!w.relative_position);
1179        assert_eq!(w.anchor_vertical, 74);
1180        assert_eq!(w.anchor_horizontal, 209);
1181        assert_eq!(w.anchor_point, AnchorPoint::BottomRight);
1182        assert_eq!(w.row_count, 12);
1183        assert_eq!(w.column_count, 16);
1184        assert_eq!(w.window_style, 2);
1185        assert_eq!(w.pen_style, 1);
1186    }
1187
1188    /// SWA worked example (`cea708-decode.md`, p.76):
1189    /// `0x97,0x64,0x53,0x88,0x22` → border type = 5 (SHADOW_RIGHT).
1190    #[test]
1191    fn swa_border_type_split() {
1192        let mut dec = Cea708Decoder::new();
1193        // define a window first (so there is a current window), then SWA.
1194        let packet = ccp(
1195            1,
1196            &[
1197                0x98, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, // DF0 visible, defaults
1198                0x97, 0x64, 0x53, 0x88, 0x22, // SWA
1199            ],
1200        );
1201        dec.push_packet(&packet);
1202        let w = dec.windows(1)[0].as_ref().expect("window 0");
1203        assert_eq!(w.border_type, EdgeType::RightDropShadow);
1204    }
1205
1206    /// A simple caption: define a window (visible), write "Hi", read service text.
1207    #[test]
1208    fn decode_text() {
1209        let mut dec = Cea708Decoder::new();
1210        let packet = ccp(
1211            1,
1212            &[
1213                0x98, 0x20, 0x00, 0x00, 0x02, 0x0F, 0x00, // DF0 visible, 3 rows × 16
1214                b'H', b'i',
1215            ],
1216        );
1217        dec.push_packet(&packet);
1218        assert_eq!(dec.service_text(1), "Hi");
1219    }
1220
1221    /// ≥2 services + multi-window exercised in one packet.
1222    #[test]
1223    fn two_services_multi_window() {
1224        let mut dec = Cea708Decoder::new();
1225        // Service 1: define window 0 visible, write "S1".
1226        let s1_block = [0x98, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'1'];
1227        // Service 2: define window 1 visible, write "S2".
1228        let s2_block = [0x99, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'2'];
1229        let mut data = Vec::new();
1230        data.push((1 << 5) | (s1_block.len() as u8));
1231        data.extend_from_slice(&s1_block);
1232        data.push((2 << 5) | (s2_block.len() as u8));
1233        data.extend_from_slice(&s2_block);
1234        let size_code = (data.len().div_ceil(2) + 1) as u8 & 0x3F;
1235        let mut packet = alloc::vec![size_code];
1236        packet.extend_from_slice(&data);
1237        dec.push_packet(&packet);
1238        assert_eq!(dec.service_text(1), "S1");
1239        assert_eq!(dec.service_text(2), "S2");
1240        assert!(dec.windows(1)[0].is_some());
1241        assert!(dec.windows(2)[1].is_some());
1242    }
1243
1244    #[test]
1245    fn services_seen_covers_unmodelled_and_extended_services() {
1246        let mut dec = Cea708Decoder::new();
1247        dec.push_packet(&ccp(1, b"A"));
1248        dec.push_packet(&ccp(2, &[0x00, 0x00]));
1249        let extended = [(7 << 5) | 1, 63, b'Z'];
1250        let size_code = (extended.len().div_ceil(2) + 1) as u8 & 0x3F;
1251        let mut packet = alloc::vec![size_code];
1252        packet.extend_from_slice(&extended);
1253        dec.push_packet(&packet);
1254        assert_eq!(dec.services_seen(), alloc::vec![1, 63]);
1255    }
1256
1257    #[test]
1258    fn carriage_return_rolls_up() {
1259        let mut w = Window::new();
1260        w.row_count = 2;
1261        w.column_count = 10;
1262        w.ensure_grid();
1263        w.put_char('A');
1264        w.carriage_return();
1265        w.put_char('B');
1266        w.carriage_return(); // now at bottom; should roll up
1267        w.put_char('C');
1268        assert_eq!(w.text(), "B\nC");
1269    }
1270
1271    #[test]
1272    fn g0_music_note() {
1273        assert_eq!(Cea708Decoder::g0_char(0x7F), '\u{266A}');
1274        assert_eq!(Cea708Decoder::g0_char(b'A'), 'A');
1275    }
1276
1277    #[test]
1278    fn no_panic_on_arbitrary_input() {
1279        // Feed adversarial / truncated / malformed bytes; must never panic.
1280        let inputs: &[&[u8]] = &[
1281            &[],
1282            &[0x00],
1283            &[0xFF],
1284            &[0x01, 0x98],                               // DefineWindow truncated
1285            &[0x3F, 0x80, 0x90, 0x91, 0x92, 0x97, 0x98], // size_code huge, partial cmds
1286            &[0x20, 0xEE, (7 << 5) | 1],                 // extended service escape truncated
1287            &[0x10, 0x9A],                               // C0 EXT1 → C3 variable, truncated
1288            &[0x18, 0x00],                               // P16 truncated
1289        ];
1290        for inp in inputs {
1291            let mut dec = Cea708Decoder::new();
1292            dec.push_packet(inp);
1293        }
1294        // a long pseudo-random stream
1295        let mut dec = Cea708Decoder::new();
1296        let mut x: u32 = 0x1234_5678;
1297        let mut buf = Vec::new();
1298        for _ in 0..4096 {
1299            x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
1300            buf.push((x >> 16) as u8);
1301        }
1302        dec.push_packet(&buf);
1303        // also drive it via triplets
1304        let mut dec2 = Cea708Decoder::new();
1305        let triplets: Vec<CcTriplet> = buf
1306            .chunks(2)
1307            .map(|c| CcTriplet {
1308                cc_valid: true,
1309                cc_type: CcType::Dtvcc708Data,
1310                cc_data_1: c[0],
1311                cc_data_2: *c.get(1).unwrap_or(&0),
1312            })
1313            .collect();
1314        dec2.push_triplets(&triplets);
1315    }
1316
1317    #[test]
1318    fn set_pen_location_back_over_existing_text_overwrites() {
1319        let mut d = Cea708Decoder::new();
1320        d.push_packet(&[0x05, 0x27, 0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11, 0x00]);
1321        d.push_packet(&[0x45, 0x26, b'A', b'B', b'C', 0x92, 0x00, 0x00, 0x00, 0x00]);
1322        d.push_packet(&[0x82, 0x22, b'X', 0x00]);
1323        let w = d.windows(1)[2].as_ref().unwrap();
1324        assert_eq!(w.text(), "XBC");
1325    }
1326}