cc-data 0.7.1

Closed-caption cc_data() carriage (CEA-608/708), per ETSI TS 101 154 Table B.9.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! cc_data() — ETSI TS 101 154 §B.5, Table B.9.

use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};

/// Largest `cc_count` the 5-bit field can carry.
const MAX_CC_COUNT: usize = 31;
/// Fixed `0xFF` reserved byte after cc_count, and the trailing marker byte.
const FF: u8 = 0xFF;
/// Byte 0 bit 7: `reserved (set to "1")` in TS 101 154 Table B.9, the
/// `process_em_data_flag` of the ATSC A/53 / CEA-708 lineage the syntax is
/// shared with.
const PROCESS_EM_DATA_FLAG_BIT: u8 = 0x80;
/// Byte 0 bit 6: `process_cc_data_flag`.
const PROCESS_CC_DATA_FLAG_BIT: u8 = 0x40;
/// Byte 0 bit 5: `zero_bit (set to "0")` in Table B.9, the
/// `additional_data_flag` of the A/53 / CEA-708 lineage.
const ADDITIONAL_DATA_FLAG_BIT: u8 = 0x20;
/// `cc_count` — byte 0 bits `[4:0]`.
const CC_COUNT_MASK: u8 = 0x1F;
/// Triplet byte 0 bits `[7:3]`: `one_bit`(1) + `reserved`(4), all set to 1
/// (TS 101 154 Table B.9); also the value they must hold.
const TRIPLET_FIXED_MASK: u8 = 0xF8;

/// `cc_type` — the type of the caption data byte pair (TS 101 154 Table B.9 /
/// CEA-708-E). 2-bit field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum CcType {
    /// CEA-608 NTSC line-21 field 1 (cc_type 0).
    Ntsc608Field1,
    /// CEA-608 NTSC line-21 field 2 (cc_type 1).
    Ntsc608Field2,
    /// DTVCC (CEA-708) channel-packet data (cc_type 2).
    Dtvcc708Data,
    /// DTVCC (CEA-708) channel-packet start (cc_type 3).
    Dtvcc708Start,
}

impl CcType {
    /// From the 2-bit wire value.
    #[must_use]
    pub fn from_bits(v: u8) -> Self {
        match v & 0x03 {
            0 => Self::Ntsc608Field1,
            1 => Self::Ntsc608Field2,
            2 => Self::Dtvcc708Data,
            _ => Self::Dtvcc708Start,
        }
    }
    /// The 2-bit wire value.
    #[must_use]
    pub fn to_bits(self) -> u8 {
        match self {
            Self::Ntsc608Field1 => 0,
            Self::Ntsc608Field2 => 1,
            Self::Dtvcc708Data => 2,
            Self::Dtvcc708Start => 3,
        }
    }
    /// `true` for the CEA-608 (line-21) types.
    #[must_use]
    pub fn is_cea608(self) -> bool {
        matches!(self, Self::Ntsc608Field1 | Self::Ntsc608Field2)
    }
    /// `true` for the CEA-708 (DTVCC) types.
    #[must_use]
    pub fn is_cea708(self) -> bool {
        matches!(self, Self::Dtvcc708Data | Self::Dtvcc708Start)
    }
    /// Label per the project's `name()` convention.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Ntsc608Field1 => "ntsc_608_field1",
            Self::Ntsc608Field2 => "ntsc_608_field2",
            Self::Dtvcc708Data => "dtvcc_708_data",
            Self::Dtvcc708Start => "dtvcc_708_start",
        }
    }
}

broadcast_common::impl_spec_display!(CcType);

/// One closed-caption construct (the per-`cc_count` loop entry of Table B.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CcTriplet {
    /// `cc_valid` — the two caption bytes are valid.
    pub cc_valid: bool,
    /// `cc_type` — type of the caption byte pair.
    pub cc_type: CcType,
    /// `cc_data_1` — first caption byte (contents per CEA-708-E).
    pub cc_data_1: u8,
    /// `cc_data_2` — second caption byte.
    pub cc_data_2: u8,
}

/// `cc_data()` — the DVB closed-caption carriage structure (Table B.9).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CcData {
    /// Byte 0 bit 7. Table B.9 calls it `reserved (set to "1")`; in the ATSC
    /// A/53 / CEA-708 lineage the same bit is `process_em_data_flag`, and real
    /// A/53 captures (shaka-player's `captions-test.ts`) carry `0` here.
    /// Parsed tolerantly and preserved so the round-trip stays byte-exact;
    /// construct with `true` to match Table B.9's own default.
    pub process_em_data_flag: bool,
    /// `process_cc_data_flag` — when `true`, the cc_data is to be processed.
    pub process_cc_data_flag: bool,
    /// Byte 0 bit 5. Table B.9 calls it `zero_bit (set to "0")`; in the A/53 /
    /// CEA-708 lineage it is `additional_data_flag`. Parsed tolerantly and
    /// preserved; construct with `false` to match Table B.9's default.
    pub additional_data_flag: bool,
    /// The byte after `cc_count`, Table B.9's `reserved (set to "1111 1111")`.
    /// Real streams (this byte is `em_data` in the ATSC A/53 lineage this
    /// syntax is shared with) don't always hold `0xFF` here, so it is
    /// preserved verbatim rather than assumed, to keep the round-trip
    /// byte-exact. Construct with `0xFF` to match Table B.9's own default.
    pub reserved_byte1: u8,
    /// The caption constructs (`cc_count` is `triplets.len()`).
    pub triplets: Vec<CcTriplet>,
}

impl CcData {
    /// Iterator over the CEA-608 (line-21) triplets.
    pub fn cea608(&self) -> impl Iterator<Item = &CcTriplet> {
        self.triplets.iter().filter(|t| t.cc_type.is_cea608())
    }
    /// Iterator over the CEA-708 (DTVCC) triplets.
    pub fn cea708(&self) -> impl Iterator<Item = &CcTriplet> {
        self.triplets.iter().filter(|t| t.cc_type.is_cea708())
    }
}

impl<'a> Parse<'a> for CcData {
    type Error = Error;
    fn parse(b: &'a [u8]) -> Result<Self> {
        // byte0: reserved(1) | process_cc_data_flag(1) | zero_bit(1) | cc_count(5)
        // byte1: reserved 0xFF
        if b.len() < 2 {
            return Err(Error::BufferTooShort {
                need: 2,
                have: b.len(),
                what: "cc_data header",
            });
        }
        // byte0 bits 7 and 5 are reserved/zero in Table B.9 but carry
        // `process_em_data_flag` / `additional_data_flag` in real A/53
        // streams: accept either value and keep it (reserved-bit policy).
        let process_em_data_flag = b[0] & PROCESS_EM_DATA_FLAG_BIT != 0;
        let process_cc_data_flag = b[0] & PROCESS_CC_DATA_FLAG_BIT != 0;
        let additional_data_flag = b[0] & ADDITIONAL_DATA_FLAG_BIT != 0;
        let cc_count = usize::from(b[0] & CC_COUNT_MASK);
        let reserved_byte1 = b[1];
        let total = 2 + cc_count * 3 + 1; // header + triplets + marker
        if b.len() < total {
            return Err(Error::BufferTooShort {
                need: total,
                have: b.len(),
                what: "cc_data triplets",
            });
        }
        let mut triplets = Vec::with_capacity(cc_count);
        let mut pos = 2;
        for _ in 0..cc_count {
            let flags = b[pos];
            // one_bit(1) | reserved(4, set to "1111") | cc_valid(1) | cc_type(2)
            if flags & TRIPLET_FIXED_MASK != TRIPLET_FIXED_MASK {
                return Err(Error::InvalidFixedBits {
                    what: "one_bit/reserved",
                    got: flags & TRIPLET_FIXED_MASK,
                    expected: TRIPLET_FIXED_MASK,
                    mask: TRIPLET_FIXED_MASK,
                });
            }
            triplets.push(CcTriplet {
                cc_valid: (flags >> 2) & 0x01 != 0,
                cc_type: CcType::from_bits(flags),
                cc_data_1: b[pos + 1],
                cc_data_2: b[pos + 2],
            });
            pos += 3;
        }
        if b[pos] != FF {
            return Err(Error::InvalidFixedBits {
                what: "marker_bits",
                got: b[pos],
                expected: FF,
                mask: FF,
            });
        }
        Ok(CcData {
            process_em_data_flag,
            process_cc_data_flag,
            additional_data_flag,
            reserved_byte1,
            triplets,
        })
    }
}

impl Serialize for CcData {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        2 + self.triplets.len() * 3 + 1
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        if self.triplets.len() > MAX_CC_COUNT {
            return Err(Error::TooManyTriplets(self.triplets.len()));
        }
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        // process_em_data_flag, process_cc_data_flag, additional_data_flag,
        // cc_count (<= MAX_CC_COUNT, checked above).
        let cc_count = self.triplets.len() as u8;
        buf[0] = (u8::from(self.process_em_data_flag) * PROCESS_EM_DATA_FLAG_BIT)
            | (u8::from(self.process_cc_data_flag) * PROCESS_CC_DATA_FLAG_BIT)
            | (u8::from(self.additional_data_flag) * ADDITIONAL_DATA_FLAG_BIT)
            | cc_count;
        buf[1] = self.reserved_byte1;
        let mut pos = 2;
        for t in &self.triplets {
            // one_bit=1, reserved=1111, cc_valid, cc_type
            buf[pos] = TRIPLET_FIXED_MASK | (u8::from(t.cc_valid) << 2) | t.cc_type.to_bits();
            buf[pos + 1] = t.cc_data_1;
            buf[pos + 2] = t.cc_data_2;
            pos += 3;
        }
        buf[pos] = FF; // marker_bits
        Ok(len)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tr(cc_valid: bool, cc_type: CcType, d1: u8, d2: u8) -> CcTriplet {
        CcTriplet {
            cc_valid,
            cc_type,
            cc_data_1: d1,
            cc_data_2: d2,
        }
    }

    fn sample() -> CcData {
        CcData {
            process_em_data_flag: true,
            process_cc_data_flag: true,
            additional_data_flag: false,
            reserved_byte1: FF,
            triplets: alloc::vec![
                tr(true, CcType::Dtvcc708Start, 0xC1, 0x02),
                tr(true, CcType::Ntsc608Field1, 0x94, 0x2C),
                tr(false, CcType::Dtvcc708Data, 0x00, 0x00),
            ],
        }
    }

    #[test]
    fn round_trip_constructed() {
        let cc = sample();
        let bytes = cc.try_to_bytes().unwrap();
        // construct → serialize → re-parse → equal (no raw stash to lean on)
        assert_eq!(CcData::parse(&bytes).unwrap(), cc);
        // header sanity: reserved=1, pcdf=1, zero=0, cc_count=3
        assert_eq!(bytes[0], 0b1100_0011);
        assert_eq!(bytes[1], 0xFF);
        assert_eq!(*bytes.last().unwrap(), 0xFF);
    }

    #[test]
    fn mutate_field_changes_output() {
        let a = sample().try_to_bytes().unwrap();
        let mut cc = sample();
        cc.triplets[0].cc_data_1 = 0x42;
        let b = cc.try_to_bytes().unwrap();
        assert_ne!(a, b, "mutating a field must change serialized bytes");
    }

    #[test]
    fn splits_608_708() {
        let cc = sample();
        assert_eq!(cc.cea608().count(), 1);
        assert_eq!(cc.cea708().count(), 2);
    }

    #[test]
    fn empty_round_trip() {
        let cc = CcData {
            process_em_data_flag: true,
            process_cc_data_flag: false,
            additional_data_flag: false,
            reserved_byte1: FF,
            triplets: alloc::vec![],
        };
        let bytes = cc.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x80, 0xFF, 0xFF]); // reserved=1, pcdf=0, count=0; 0xFF; marker
        assert_eq!(CcData::parse(&bytes).unwrap(), cc);
    }

    #[test]
    fn reserved_byte1_round_trips_verbatim() {
        // A real-world (ATSC-lineage) stream where byte 1 after cc_count isn't
        // 0xFF: pre-fix, parse discarded it and serialize always wrote 0xFF,
        // so this round-trip was NOT byte-exact (bytes[1] silently changed).
        let mut cc = sample();
        cc.reserved_byte1 = 0x3A;
        let bytes = cc.try_to_bytes().unwrap();
        assert_eq!(bytes[1], 0x3A);
        let reparsed = CcData::parse(&bytes).unwrap();
        assert_eq!(reparsed.reserved_byte1, 0x3A);
        assert_eq!(reparsed, cc);
    }

    /// A real frame: the first `GA94` cc_data() of shaka-player's
    /// `captions-test.ts` (private submodule, `private/fixtures/captions/shaka/`; the media licence is unclear). Its header
    /// byte is `0x54`: `process_em_data_flag = 0`, `process_cc_data_flag = 1`,
    /// `additional_data_flag = 0`, `cc_count = 20`, and its em_data byte is
    /// `0x00`, not Table B.9's `0xFF`. A header check that insists on bit 7 = 1
    /// rejects every frame of that capture.
    const SHAKA_REAL_FRAME: &str = "5400fc94aefd8080ff4527fe9800fe0000fe0116fe1100fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000fa0000ff";

    fn unhex(h: &str) -> Vec<u8> {
        (0..h.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap())
            .collect()
    }

    #[test]
    fn real_a53_header_with_clear_em_data_flag_parses_and_round_trips() {
        let bytes = unhex(SHAKA_REAL_FRAME);
        let cc = CcData::parse(&bytes).unwrap();
        assert!(!cc.process_em_data_flag);
        assert!(cc.process_cc_data_flag);
        assert!(!cc.additional_data_flag);
        assert_eq!(cc.reserved_byte1, 0x00);
        assert_eq!(cc.triplets.len(), 20);
        assert_eq!(cc.try_to_bytes().unwrap(), bytes);
    }

    #[test]
    fn additional_data_flag_set_is_preserved() {
        let mut bytes = sample().try_to_bytes().unwrap();
        bytes[0] |= 0x20; // additional_data_flag = 1 (Table B.9 "zero_bit")
        bytes[0] &= !0x80; // process_em_data_flag = 0
        let cc = CcData::parse(&bytes).unwrap();
        assert!(cc.additional_data_flag);
        assert!(!cc.process_em_data_flag);
        assert_eq!(cc.try_to_bytes().unwrap(), bytes);
    }

    #[test]
    fn hand_built_header_defaults_to_the_table_b9_values() {
        let bytes = sample().try_to_bytes().unwrap();
        assert_eq!(bytes[0] & 0xA0, 0x80);
    }

    #[test]
    fn parse_rejects_bad_triplet_fixed_bits() {
        let mut bytes = sample().try_to_bytes().unwrap();
        bytes[2] &= !0x80; // clear the triplet's "one_bit=1"
        assert!(matches!(
            CcData::parse(&bytes),
            Err(Error::InvalidFixedBits {
                what: "one_bit/reserved",
                ..
            })
        ));
    }

    #[test]
    fn parse_rejects_bad_marker_bits() {
        let mut bytes = sample().try_to_bytes().unwrap();
        let last = bytes.len() - 1;
        bytes[last] = 0x00;
        assert!(matches!(
            CcData::parse(&bytes),
            Err(Error::InvalidFixedBits {
                what: "marker_bits",
                ..
            })
        ));
    }

    #[test]
    fn serialize_rejects_over_31_triplets() {
        let cc = CcData {
            process_em_data_flag: true,
            process_cc_data_flag: true,
            additional_data_flag: false,
            reserved_byte1: FF,
            triplets: alloc::vec![tr(true, CcType::Ntsc608Field1, 0, 0); 32],
        };
        let mut buf = [0u8; 200];
        assert!(matches!(
            cc.serialize_into(&mut buf),
            Err(Error::TooManyTriplets(32))
        ));
    }
}