Skip to main content

Crate cc_data

Crate cc_data 

Source
Expand description

§cc-data

crates.io docs.rs License

Closed-caption cc_data() carriage (CEA-608 / CEA-708) parser and builder, plus an optional CEA-608 / CEA-708 caption decoder. no_std + alloc, depends only on broadcast-common.

Formerly dvb-cc (through 0.2.0); a dvb-cc 0.2.1 shim re-exports this crate.

[dependencies]
cc-data = "0.9"

§What it does / what it does not

cc_data() is the structure that carries closed captions inside MPEG-2 / AVC / HEVC picture user_data (ATSC A/53 style, and the DVB-native form in ETSI TS 101 154). This crate parses it into typed caption triplets (cc_valid, cc_type, cc_data_1, cc_data_2), splits CEA-608 (line 21, cc_type 0/1) from CEA-708 (DTVCC, cc_type 2/3), and serializes it back byte for byte. With the decode feature it interprets those byte pairs into displayed text.

It does not locate cc_data() inside a picture’s user_data / SEI (the caller, or transmux, does that), render pixels, or decode the XDS metadata catalogue (field-2 XDS is detected and skipped). Format conversion to WebVTT / SRT lives in timed-metadata and caption-convert.

§Standards supported

StandardEditionScope / clausesStatusNotes
ETSI TS 101 154 DVB audio/video codingV2.6.1 (2019-09), as transcribed in private/specs-verified/captions/cc-data/ts_101_154/b9-cc-data.md; also present in private/specs-md as V2.6.1, V2.7.1 draft and V2.10.1§B.5 / Table B.9 cc_data()Fullprocess_em_data_flag / additional_data_flag preserved verbatim (real A/53 captures carry process_em_data_flag = 0).
ANSI/CTA-608-E (line-21 captions)-E; not vendored (copyright, cart-gated; no copy in private/specs or private/specs-verified/). private/specs-verified/captions/cc-data/decode/cea608-decode.md was transcribed in June 2026 from a locally held PDF copy that is no longer retrievable, so its tables cannot be re-verifiedpop-on / roll-up / paint-on, PACs, mid-row codes, tab offsets, Western-European character sets, CC1-CC4, doubling, XDS detect-and-skipPartial (decode)feature decode; XDS content is not decoded
ANSI/CTA-708-E (DTVCC)-E; not vendored, same caveat for private/specs-verified/captions/cc-data/decode/cea708-decode.md. Vendored cross-source: GY/T 270-2013 (private/specs/nrta_gyt_270_2013_dtv_closed_caption_system.pdf, a Chinese adaptation: check differences from CTA-708)CCP reassembly, Service Blocks (extended service), C0/C1/G0/G1/G2/G3, windows (DF0-7, attributes, show/hide/toggle/delete), pens, DLY/DLC/RST; services 1-6Partial (decode)feature decode
47 CFR §79.102 (US decoder requirements)public domain; transcribed in private/specs-verified/captions/cc-data/decode/cea708-conformance.md708 semantic model, window/pen enumerationsFull as a grounding source

§Feature flags

FeatureDefaultDescription
stdonLink the standard library. Without it the crate is #![no_std] + alloc.
decodeonCea608Decoder / Cea708Decoder and the caption screen / window model (additive, no_std + alloc).
serdeoffserde::Serialize on public types.

§Quick start

use broadcast_common::{Parse, Serialize};
use cc_data::{CcData, CcTriplet, CcType};

// Build a cc_data() with one 608 field-1 pair and one 708 start triplet.
let cc = CcData {
    process_em_data_flag: true,
    process_cc_data_flag: true,
    additional_data_flag: false,
    reserved_byte1: 0xFF,
    triplets: vec![
        CcTriplet {
            cc_valid: true,
            cc_type: CcType::Dtvcc708Start,
            cc_data_1: 0xC1,
            cc_data_2: 0x02,
        },
        CcTriplet {
            cc_valid: true,
            cc_type: CcType::Ntsc608Field1,
            cc_data_1: 0x94,
            cc_data_2: 0x2C,
        },
    ],
};

// Serialize, parse back byte-exactly, and split 608 from 708.
let bytes = cc.try_to_bytes().unwrap();
let back = CcData::parse(&bytes).unwrap();
assert_eq!(back, cc);
assert_eq!(back.cea608().count(), 1);
assert_eq!(back.cea708().count(), 1);

Decoding (feature decode):

use cc_data::decode::{Cea608Channel, Cea608Decoder};

let mut dec = Cea608Decoder::new();
// RCL, PAC row 15, "HI", EOC: a pop-on caption on CC1 (field 1).
dec.push_pair(false, 0x14, 0x20); // RCL (field 1 -> CC1)
dec.push_pair(false, 0x14, 0x20); // doubled control, ignored
dec.push_pair(false, 0x14, 0x70); // PAC row 15 indent 0
dec.push_pair(false, b'H', b'I');
dec.push_pair(false, 0x14, 0x2F); // EOC -> flip
assert_eq!(dec.channel_text(Cea608Channel::Cc1), "HI");

Examples: parse_cc_data, build_cc_data, decode_cea608, decode_cea708 (cargo run -p cc-data --example <name>).

§What is implemented

  • Carriage: CcData, CcTriplet, CcType (Ntsc608Field1, Ntsc608Field2, Dtvcc708Data, Dtvcc708Start), cea608() / cea708() iterators.
  • Cea608Decoder (decode): the line-21 state machine with per-channel screen model (rows x styled cells) and displayed text per channel. RCL only selects pop-on style (ENM erases), so real SCC files that re-issue RCL before EDM + EOC decode; field-2 control codes are recognised; characters route to the channel of the last control code on their field.
  • Cea708Decoder (decode): a Caption Channel Packet that spans several cc_data() access units is kept across calls and decoded when complete; exposes the six services’ window text.
  • Caption detection helpers: Cea608Decoder::has_caption_text(channel) reports whether displayable text has been written to a CC1-CC4 channel; Cea608Channel is Copy/PartialOrd/Ord/Hash with number() (1 to 4); Cea708Decoder::services_seen() lists service numbers 1 to 63 that received a non-null byte (issue #1428).
  • CcData: processed_triplets() returns all triplets when process_cc_data_flag is set and none otherwise (ETSI TS 101 154 Table B.9: discarded when the flag is clear); cea608()/cea708() iterate over those.
  • Both decoders are one-way (bytes to caption state) and panic-free on arbitrary, truncated or malformed input (tests/it/hostility.rs).

§Design notes

  • Zero-copy-style Parse / Serialize pair; the carriage round trip is byte-identical, including the preserved flag bits and reserved_byte1.
  • Error is #[non_exhaustive]; odd-parity checking is broadcast_common::parity.
  • Decode is grounded in the transcriptions under private/specs-verified/captions/cc-data/decode/; CTA-608-E/708-E are not vendored (see the standards table); GY/T 270-2013 is the vendored cross-source for the DTVCC layer.

Depends only on broadcast-common. Used by timed-metadata (cue extraction), and caption-convert. dvb-vbi carries VBI data units (Teletext, Closed Captioning) separately.

§MSRV and licence

Rust 1.95.0. MIT OR Apache-2.0.

§Examples

Runnable examples ship with this crate (cargo run -p cc-data --example <name>).

§parse_cc_data

ⓘ
//! Basic: parse a `cc_data()` byte sequence and split CEA-608 / CEA-708 triplets.
//!
//! Run with: `cargo run -p cc-data --example parse_cc_data`

use broadcast_common::Parse;
use cc_data::CcData;

fn main() {
    // cc_data: process_cc_data_flag=1, cc_count=2; one DTVCC-start triplet + one
    // 608-field-1 triplet; trailing 0xFF marker.
    #[rustfmt::skip]
    let bytes = [
        0b1100_0010, // reserved=1, process=1, zero=0, cc_count=2
        0xFF,        // reserved
        0xFF, 0xC1, 0x02, // one_bit+rsvd(F8) | valid=1 | type=3 (708 start); data C1 02
        0xFC, 0x94, 0x2C, // F8 | valid=1 | type=0 (608 field1); data 94 2C
        0xFF,        // marker
    ];

    let cc = CcData::parse(&bytes).expect("valid cc_data");
    println!("process_cc_data_flag : {}", cc.process_cc_data_flag);
    println!("triplets             : {}", cc.triplets.len());
    for t in &cc.triplets {
        println!(
            "  {:<16} valid={} data={:02X} {:02X}",
            t.cc_type.name(),
            t.cc_valid,
            t.cc_data_1,
            t.cc_data_2
        );
    }
    println!("CEA-608 triplets     : {}", cc.cea608().count());
    println!("CEA-708 triplets     : {}", cc.cea708().count());
}

§build_cc_data

ⓘ
//! Advanced: build a `cc_data()` from typed triplets, serialize, and round-trip.
//!
//! Run with: `cargo run -p cc-data --example build_cc_data`

use broadcast_common::{Parse, Serialize};
use cc_data::{CcData, CcTriplet, CcType};

fn main() {
    let cc = CcData {
        process_em_data_flag: true,
        process_cc_data_flag: true,
        additional_data_flag: false,
        reserved_byte1: 0xFF,
        triplets: vec![
            CcTriplet {
                cc_valid: true,
                cc_type: CcType::Dtvcc708Start,
                cc_data_1: 0xC1,
                cc_data_2: 0x02,
            },
            CcTriplet {
                cc_valid: true,
                cc_type: CcType::Ntsc608Field1,
                cc_data_1: 0x94,
                cc_data_2: 0x2C,
            },
        ],
    };

    let bytes = cc.try_to_bytes().unwrap();
    println!("serialized {} bytes: {:02X?}", bytes.len(), bytes);

    let back = CcData::parse(&bytes).expect("round-trip parse");
    assert_eq!(back, cc, "round-trip must be lossless");
    println!(
        "round-trip OK — {} triplets ({} 608, {} 708)",
        back.triplets.len(),
        back.cea608().count(),
        back.cea708().count()
    );
}

§decode_cea608

ⓘ
//! Decode a CEA-608 (line-21) pop-on caption to on-screen text.
//!
//! Run with: `cargo run -p cc-data --example decode_cea608`

use broadcast_common::parity::set_odd_parity;
use cc_data::decode::{Cea608Channel, Cea608Decoder};

fn main() {
    let mut dec = Cea608Decoder::new();

    // A pop-on caption on CC1 (field 1):
    //   RCL  (14 20)  — Resume Caption Loading (pop-on)
    //   PAC  (14 70)  — row 15, white, indent 0
    //   "HELLO"
    //   EOC  (14 2F)  — flip back buffer to the screen
    let pairs: &[(u8, u8)] = &[
        (0x14, 0x20),
        (0x14, 0x70),
        (b'H', b'E'),
        (b'L', b'L'),
        (b'O', 0x00),
        (0x14, 0x2F),
    ];
    for &(b1, b2) in pairs {
        dec.push_pair(false, set_odd_parity(b1), set_odd_parity(b2));
    }

    println!("CC1 mode : {}", dec.mode(Cea608Channel::Cc1));
    println!("CC1 text : {:?}", dec.channel_text(Cea608Channel::Cc1));

    // A roll-up caption (2 rows) on CC1.
    let mut dec2 = Cea608Decoder::new();
    let roll: &[(u8, u8)] = &[
        (0x14, 0x25), // RU2
        (b'O', b'N'),
        (b'E', 0x00),
        (0x14, 0x2D), // CR
        (b'T', b'W'),
        (b'O', 0x00),
    ];
    for &(b1, b2) in roll {
        dec2.push_pair(false, set_odd_parity(b1), set_odd_parity(b2));
    }
    println!("\nRoll-up mode : {}", dec2.mode(Cea608Channel::Cc1));
    println!("Roll-up text :\n{}", dec2.channel_text(Cea608Channel::Cc1));
}

§decode_cea708

ⓘ
//! Decode a CEA-708 (DTVCC) caption packet to window text.
//!
//! Run with: `cargo run -p cc-data --example decode_cea708`

use cc_data::decode::Cea708Decoder;

fn main() {
    let mut dec = Cea708Decoder::new();

    // Build a Caption Channel Packet carrying one Service Block for service 1
    // that: DefineWindow DF0 (visible, 2 rows × 16 cols), writes "HI THERE".
    let block: &[u8] = &[
        0x98, // DefineWindow DF0
        0x20, // parm1: visible=YES, priority 0
        0x00, // parm2: rp=0, anchor vertical 0
        0x00, // parm3: anchor horizontal 0
        0x01, // parm4: anchor point 0, row count = 1+1 = 2
        0x0F, // parm5: column count = 15+1 = 16
        0x00, // parm6: window/pen style 0 (auto)
        b'H', b'I', b' ', b'T', b'H', b'E', b'R', b'E',
    ];

    // Service Block header: service_number = 1, block_size = block.len().
    let mut sb: Vec<u8> = Vec::new();
    sb.push((1 << 5) | (block.len() as u8));
    sb.extend_from_slice(block);

    // CCP header: sequence_number 0, packet_size_code covers the data.
    let size_code = (sb.len().div_ceil(2) + 1) as u8;
    let mut ccp: Vec<u8> = Vec::new();
    ccp.push(size_code & 0x3F);
    ccp.extend_from_slice(&sb);

    dec.push_packet(&ccp);

    println!("Service 1 text : {:?}", dec.service_text(1));
    if let Some(w) = dec.windows(1)[0].as_ref() {
        println!("Window 0 state : {}", w.state);
        println!("Window 0 rows  : {}", w.row_count);
        println!("Window 0 cols  : {}", w.column_count);
        println!("Window 0 text  : {:?}", w.text());
    }
}

Modules§

decodedecode
CEA-608 / CEA-708 caption decode — the meaning of the caption byte pairs that the crate::CcData carriage demuxes out of cc_data().

Structs§

CcData
cc_data() — the DVB closed-caption carriage structure (Table B.9).
CcTriplet
One closed-caption construct (the per-cc_count loop entry of Table B.9).

Enums§

CcType
cc_type — the type of the caption data byte pair (TS 101 154 Table B.9 / CEA-708-E). 2-bit field.
Error
A cc_data parse error.

Type Aliases§

Result
Result alias.