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