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