Skip to main content

cc_data/
cc_data.rs

1//! cc_data() — ETSI TS 101 154 §B.5, Table B.9.
2
3use crate::error::{Error, Result};
4use alloc::vec::Vec;
5use broadcast_common::{Parse, Serialize};
6
7/// Largest `cc_count` the 5-bit field can carry.
8const MAX_CC_COUNT: usize = 31;
9/// Fixed `0xFF` reserved byte after cc_count, and the trailing marker byte.
10const FF: u8 = 0xFF;
11/// Byte 0 bit 7: `reserved (set to "1")` in TS 101 154 Table B.9, the
12/// `process_em_data_flag` of the ATSC A/53 / CEA-708 lineage the syntax is
13/// shared with.
14const PROCESS_EM_DATA_FLAG_BIT: u8 = 0x80;
15/// Byte 0 bit 6: `process_cc_data_flag`.
16const PROCESS_CC_DATA_FLAG_BIT: u8 = 0x40;
17/// Byte 0 bit 5: `zero_bit (set to "0")` in Table B.9, the
18/// `additional_data_flag` of the A/53 / CEA-708 lineage.
19const ADDITIONAL_DATA_FLAG_BIT: u8 = 0x20;
20/// `cc_count` — byte 0 bits `[4:0]`.
21const CC_COUNT_MASK: u8 = 0x1F;
22/// Triplet byte 0 bits `[7:3]`: `one_bit`(1) + `reserved`(4), all set to 1
23/// (TS 101 154 Table B.9); also the value they must hold.
24const TRIPLET_FIXED_MASK: u8 = 0xF8;
25
26/// `cc_type` — the type of the caption data byte pair (TS 101 154 Table B.9 /
27/// CEA-708-E). 2-bit field.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize))]
30#[non_exhaustive]
31pub enum CcType {
32    /// CEA-608 NTSC line-21 field 1 (cc_type 0).
33    Ntsc608Field1,
34    /// CEA-608 NTSC line-21 field 2 (cc_type 1).
35    Ntsc608Field2,
36    /// DTVCC (CEA-708) channel-packet data (cc_type 2).
37    Dtvcc708Data,
38    /// DTVCC (CEA-708) channel-packet start (cc_type 3).
39    Dtvcc708Start,
40}
41
42impl CcType {
43    /// From the 2-bit wire value.
44    #[must_use]
45    pub fn from_bits(v: u8) -> Self {
46        match v & 0x03 {
47            0 => Self::Ntsc608Field1,
48            1 => Self::Ntsc608Field2,
49            2 => Self::Dtvcc708Data,
50            _ => Self::Dtvcc708Start,
51        }
52    }
53    /// The 2-bit wire value.
54    #[must_use]
55    pub fn to_bits(self) -> u8 {
56        match self {
57            Self::Ntsc608Field1 => 0,
58            Self::Ntsc608Field2 => 1,
59            Self::Dtvcc708Data => 2,
60            Self::Dtvcc708Start => 3,
61        }
62    }
63    /// `true` for the CEA-608 (line-21) types.
64    #[must_use]
65    pub fn is_cea608(self) -> bool {
66        matches!(self, Self::Ntsc608Field1 | Self::Ntsc608Field2)
67    }
68    /// `true` for the CEA-708 (DTVCC) types.
69    #[must_use]
70    pub fn is_cea708(self) -> bool {
71        matches!(self, Self::Dtvcc708Data | Self::Dtvcc708Start)
72    }
73    /// Label per the project's `name()` convention.
74    #[must_use]
75    pub fn name(&self) -> &'static str {
76        match self {
77            Self::Ntsc608Field1 => "ntsc_608_field1",
78            Self::Ntsc608Field2 => "ntsc_608_field2",
79            Self::Dtvcc708Data => "dtvcc_708_data",
80            Self::Dtvcc708Start => "dtvcc_708_start",
81        }
82    }
83}
84
85broadcast_common::impl_spec_display!(CcType);
86
87/// One closed-caption construct (the per-`cc_count` loop entry of Table B.9).
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89#[cfg_attr(feature = "serde", derive(serde::Serialize))]
90pub struct CcTriplet {
91    /// `cc_valid` — the two caption bytes are valid.
92    pub cc_valid: bool,
93    /// `cc_type` — type of the caption byte pair.
94    pub cc_type: CcType,
95    /// `cc_data_1` — first caption byte (contents per CEA-708-E).
96    pub cc_data_1: u8,
97    /// `cc_data_2` — second caption byte.
98    pub cc_data_2: u8,
99}
100
101/// `cc_data()` — the DVB closed-caption carriage structure (Table B.9).
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[cfg_attr(feature = "serde", derive(serde::Serialize))]
104pub struct CcData {
105    /// Byte 0 bit 7. Table B.9 calls it `reserved (set to "1")`; in the ATSC
106    /// A/53 / CEA-708 lineage the same bit is `process_em_data_flag`, and real
107    /// A/53 captures (shaka-player's `captions-test.ts`) carry `0` here.
108    /// Parsed tolerantly and preserved so the round-trip stays byte-exact;
109    /// construct with `true` to match Table B.9's own default.
110    pub process_em_data_flag: bool,
111    /// `process_cc_data_flag` — when `true`, the cc_data is to be processed.
112    pub process_cc_data_flag: bool,
113    /// Byte 0 bit 5. Table B.9 calls it `zero_bit (set to "0")`; in the A/53 /
114    /// CEA-708 lineage it is `additional_data_flag`. Parsed tolerantly and
115    /// preserved; construct with `false` to match Table B.9's default.
116    pub additional_data_flag: bool,
117    /// The byte after `cc_count`, Table B.9's `reserved (set to "1111 1111")`.
118    /// Real streams (this byte is `em_data` in the ATSC A/53 lineage this
119    /// syntax is shared with) don't always hold `0xFF` here, so it is
120    /// preserved verbatim rather than assumed, to keep the round-trip
121    /// byte-exact. Construct with `0xFF` to match Table B.9's own default.
122    pub reserved_byte1: u8,
123    /// The caption constructs (`cc_count` is `triplets.len()`).
124    pub triplets: Vec<CcTriplet>,
125}
126
127impl CcData {
128    /// Iterator over the CEA-608 (line-21) triplets.
129    pub fn cea608(&self) -> impl Iterator<Item = &CcTriplet> {
130        self.triplets.iter().filter(|t| t.cc_type.is_cea608())
131    }
132    /// Iterator over the CEA-708 (DTVCC) triplets.
133    pub fn cea708(&self) -> impl Iterator<Item = &CcTriplet> {
134        self.triplets.iter().filter(|t| t.cc_type.is_cea708())
135    }
136}
137
138impl<'a> Parse<'a> for CcData {
139    type Error = Error;
140    fn parse(b: &'a [u8]) -> Result<Self> {
141        // byte0: reserved(1) | process_cc_data_flag(1) | zero_bit(1) | cc_count(5)
142        // byte1: reserved 0xFF
143        if b.len() < 2 {
144            return Err(Error::BufferTooShort {
145                need: 2,
146                have: b.len(),
147                what: "cc_data header",
148            });
149        }
150        // byte0 bits 7 and 5 are reserved/zero in Table B.9 but carry
151        // `process_em_data_flag` / `additional_data_flag` in real A/53
152        // streams: accept either value and keep it (reserved-bit policy).
153        let process_em_data_flag = b[0] & PROCESS_EM_DATA_FLAG_BIT != 0;
154        let process_cc_data_flag = b[0] & PROCESS_CC_DATA_FLAG_BIT != 0;
155        let additional_data_flag = b[0] & ADDITIONAL_DATA_FLAG_BIT != 0;
156        let cc_count = usize::from(b[0] & CC_COUNT_MASK);
157        let reserved_byte1 = b[1];
158        let total = 2 + cc_count * 3 + 1; // header + triplets + marker
159        if b.len() < total {
160            return Err(Error::BufferTooShort {
161                need: total,
162                have: b.len(),
163                what: "cc_data triplets",
164            });
165        }
166        let mut triplets = Vec::with_capacity(cc_count);
167        let mut pos = 2;
168        for _ in 0..cc_count {
169            let flags = b[pos];
170            // one_bit(1) | reserved(4, set to "1111") | cc_valid(1) | cc_type(2)
171            if flags & TRIPLET_FIXED_MASK != TRIPLET_FIXED_MASK {
172                return Err(Error::InvalidFixedBits {
173                    what: "one_bit/reserved",
174                    got: flags & TRIPLET_FIXED_MASK,
175                    expected: TRIPLET_FIXED_MASK,
176                    mask: TRIPLET_FIXED_MASK,
177                });
178            }
179            triplets.push(CcTriplet {
180                cc_valid: (flags >> 2) & 0x01 != 0,
181                cc_type: CcType::from_bits(flags),
182                cc_data_1: b[pos + 1],
183                cc_data_2: b[pos + 2],
184            });
185            pos += 3;
186        }
187        if b[pos] != FF {
188            return Err(Error::InvalidFixedBits {
189                what: "marker_bits",
190                got: b[pos],
191                expected: FF,
192                mask: FF,
193            });
194        }
195        Ok(CcData {
196            process_em_data_flag,
197            process_cc_data_flag,
198            additional_data_flag,
199            reserved_byte1,
200            triplets,
201        })
202    }
203}
204
205impl Serialize for CcData {
206    type Error = Error;
207    fn serialized_len(&self) -> usize {
208        2 + self.triplets.len() * 3 + 1
209    }
210    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
211        if self.triplets.len() > MAX_CC_COUNT {
212            return Err(Error::TooManyTriplets(self.triplets.len()));
213        }
214        let len = self.serialized_len();
215        if buf.len() < len {
216            return Err(Error::OutputBufferTooSmall {
217                need: len,
218                have: buf.len(),
219            });
220        }
221        // process_em_data_flag, process_cc_data_flag, additional_data_flag,
222        // cc_count (<= MAX_CC_COUNT, checked above).
223        let cc_count = self.triplets.len() as u8;
224        buf[0] = (u8::from(self.process_em_data_flag) * PROCESS_EM_DATA_FLAG_BIT)
225            | (u8::from(self.process_cc_data_flag) * PROCESS_CC_DATA_FLAG_BIT)
226            | (u8::from(self.additional_data_flag) * ADDITIONAL_DATA_FLAG_BIT)
227            | cc_count;
228        buf[1] = self.reserved_byte1;
229        let mut pos = 2;
230        for t in &self.triplets {
231            // one_bit=1, reserved=1111, cc_valid, cc_type
232            buf[pos] = TRIPLET_FIXED_MASK | (u8::from(t.cc_valid) << 2) | t.cc_type.to_bits();
233            buf[pos + 1] = t.cc_data_1;
234            buf[pos + 2] = t.cc_data_2;
235            pos += 3;
236        }
237        buf[pos] = FF; // marker_bits
238        Ok(len)
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    fn tr(cc_valid: bool, cc_type: CcType, d1: u8, d2: u8) -> CcTriplet {
247        CcTriplet {
248            cc_valid,
249            cc_type,
250            cc_data_1: d1,
251            cc_data_2: d2,
252        }
253    }
254
255    fn sample() -> CcData {
256        CcData {
257            process_em_data_flag: true,
258            process_cc_data_flag: true,
259            additional_data_flag: false,
260            reserved_byte1: FF,
261            triplets: alloc::vec![
262                tr(true, CcType::Dtvcc708Start, 0xC1, 0x02),
263                tr(true, CcType::Ntsc608Field1, 0x94, 0x2C),
264                tr(false, CcType::Dtvcc708Data, 0x00, 0x00),
265            ],
266        }
267    }
268
269    #[test]
270    fn round_trip_constructed() {
271        let cc = sample();
272        let bytes = cc.try_to_bytes().unwrap();
273        // construct → serialize → re-parse → equal (no raw stash to lean on)
274        assert_eq!(CcData::parse(&bytes).unwrap(), cc);
275        // header sanity: reserved=1, pcdf=1, zero=0, cc_count=3
276        assert_eq!(bytes[0], 0b1100_0011);
277        assert_eq!(bytes[1], 0xFF);
278        assert_eq!(*bytes.last().unwrap(), 0xFF);
279    }
280
281    #[test]
282    fn mutate_field_changes_output() {
283        let a = sample().try_to_bytes().unwrap();
284        let mut cc = sample();
285        cc.triplets[0].cc_data_1 = 0x42;
286        let b = cc.try_to_bytes().unwrap();
287        assert_ne!(a, b, "mutating a field must change serialized bytes");
288    }
289
290    #[test]
291    fn splits_608_708() {
292        let cc = sample();
293        assert_eq!(cc.cea608().count(), 1);
294        assert_eq!(cc.cea708().count(), 2);
295    }
296
297    #[test]
298    fn empty_round_trip() {
299        let cc = CcData {
300            process_em_data_flag: true,
301            process_cc_data_flag: false,
302            additional_data_flag: false,
303            reserved_byte1: FF,
304            triplets: alloc::vec![],
305        };
306        let bytes = cc.try_to_bytes().unwrap();
307        assert_eq!(bytes, [0x80, 0xFF, 0xFF]); // reserved=1, pcdf=0, count=0; 0xFF; marker
308        assert_eq!(CcData::parse(&bytes).unwrap(), cc);
309    }
310
311    #[test]
312    fn reserved_byte1_round_trips_verbatim() {
313        // A real-world (ATSC-lineage) stream where byte 1 after cc_count isn't
314        // 0xFF: pre-fix, parse discarded it and serialize always wrote 0xFF,
315        // so this round-trip was NOT byte-exact (bytes[1] silently changed).
316        let mut cc = sample();
317        cc.reserved_byte1 = 0x3A;
318        let bytes = cc.try_to_bytes().unwrap();
319        assert_eq!(bytes[1], 0x3A);
320        let reparsed = CcData::parse(&bytes).unwrap();
321        assert_eq!(reparsed.reserved_byte1, 0x3A);
322        assert_eq!(reparsed, cc);
323    }
324
325    /// A real frame: the first `GA94` cc_data() of shaka-player's
326    /// `captions-test.ts` (private submodule, `private/fixtures/captions/shaka/`; the media licence is unclear). Its header
327    /// byte is `0x54`: `process_em_data_flag = 0`, `process_cc_data_flag = 1`,
328    /// `additional_data_flag = 0`, `cc_count = 20`, and its em_data byte is
329    /// `0x00`, not Table B.9's `0xFF`. A header check that insists on bit 7 = 1
330    /// rejects every frame of that capture.
331    const SHAKA_REAL_FRAME: &str = "5400fc94aefd8080ff4527fe9800fe0000fe0116fe1100fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000ff";
332
333    fn unhex(h: &str) -> Vec<u8> {
334        (0..h.len())
335            .step_by(2)
336            .map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap())
337            .collect()
338    }
339
340    #[test]
341    fn real_a53_header_with_clear_em_data_flag_parses_and_round_trips() {
342        let bytes = unhex(SHAKA_REAL_FRAME);
343        let cc = CcData::parse(&bytes).unwrap();
344        assert!(!cc.process_em_data_flag);
345        assert!(cc.process_cc_data_flag);
346        assert!(!cc.additional_data_flag);
347        assert_eq!(cc.reserved_byte1, 0x00);
348        assert_eq!(cc.triplets.len(), 20);
349        assert_eq!(cc.try_to_bytes().unwrap(), bytes);
350    }
351
352    #[test]
353    fn additional_data_flag_set_is_preserved() {
354        let mut bytes = sample().try_to_bytes().unwrap();
355        bytes[0] |= 0x20; // additional_data_flag = 1 (Table B.9 "zero_bit")
356        bytes[0] &= !0x80; // process_em_data_flag = 0
357        let cc = CcData::parse(&bytes).unwrap();
358        assert!(cc.additional_data_flag);
359        assert!(!cc.process_em_data_flag);
360        assert_eq!(cc.try_to_bytes().unwrap(), bytes);
361    }
362
363    #[test]
364    fn hand_built_header_defaults_to_the_table_b9_values() {
365        let bytes = sample().try_to_bytes().unwrap();
366        assert_eq!(bytes[0] & 0xA0, 0x80);
367    }
368
369    #[test]
370    fn parse_rejects_bad_triplet_fixed_bits() {
371        let mut bytes = sample().try_to_bytes().unwrap();
372        bytes[2] &= !0x80; // clear the triplet's "one_bit=1"
373        assert!(matches!(
374            CcData::parse(&bytes),
375            Err(Error::InvalidFixedBits {
376                what: "one_bit/reserved",
377                ..
378            })
379        ));
380    }
381
382    #[test]
383    fn parse_rejects_bad_marker_bits() {
384        let mut bytes = sample().try_to_bytes().unwrap();
385        let last = bytes.len() - 1;
386        bytes[last] = 0x00;
387        assert!(matches!(
388            CcData::parse(&bytes),
389            Err(Error::InvalidFixedBits {
390                what: "marker_bits",
391                ..
392            })
393        ));
394    }
395
396    #[test]
397    fn serialize_rejects_over_31_triplets() {
398        let cc = CcData {
399            process_em_data_flag: true,
400            process_cc_data_flag: true,
401            additional_data_flag: false,
402            reserved_byte1: FF,
403            triplets: alloc::vec![tr(true, CcType::Ntsc608Field1, 0, 0); 32],
404        };
405        let mut buf = [0u8; 200];
406        assert!(matches!(
407            cc.serialize_into(&mut buf),
408            Err(Error::TooManyTriplets(32))
409        ));
410    }
411}