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