broadcast-common 15.0.0

Foundation for the rust-broadcast crates: CRC-32/MPEG-2, BCD + MJD time codecs, hex and base64 codecs, 33-bit/PCR clock arithmetic, wrap-safe modular counters, SDP media sections and the bounded XML reader. no_std + alloc.
Documentation

broadcast-common

crates.io docs.rs License

Shared primitives of the rust-broadcast workspace above the broadcast-core wire contract: CRC-32/MPEG-2, BCD and MJD time codecs, the 33-bit/PCR clock arithmetic and wrap-safe modular counters, BER lengths and KLV triplets, odd parity, hex, bounded whole-document reads, the SDP media-section model and the bounded XML reader.

What it does / what it does not

Nearly every crate in the workspace depends on broadcast-common, so it holds only the code that must be defined exactly once above the wire contract: the small codecs the DVB/MPEG family shares (CRC, BCD, MJD, odd parity, hex), the clock arithmetic that PTS/DTS, PCR, SCTE-35 and SRT all need, and the bounded readers (bounded, xml). The wire contract itself (the symmetric Parse/Serialize traits, bit I/O, the shared error kinds, the checked field-width helpers, the media timescale, the big-endian field readers) and the Stage driver contract live in broadcast-core, which this crate depends on and re-exports nothing from; import those as broadcast_core::.... The runtime and HTTP helpers live in broadcast-net. Use this crate directly when you need one of those primitives.

It deliberately has no shared error enum (each crate owns a domain Error, reached through type Error on the traits), no CRC-8 (only dvb-bbframe needs it), no concrete media or codec types, and no heavy dependencies (jiff, serde are optional; hex and thiserror are the only unconditional dependencies, both no_std).

Standards supported

This crate implements primitives rather than a wire format, so the table lists the specification each primitive follows.

Standard Edition Scope Status Notes
ITU-T H.222.0 / ISO/IEC 13818-1 H.222.0 v9 (08/2023), verified against the vendored copy Annex A CRC decoder model, the CRC-32 (crc32_mpeg2); §2.4.3.4/§2.4.3.7 PCR (27 MHz) and 33-bit PTS/DTS clocks and the 5-byte marker-bit timestamp field (clock33) Full for the primitives listed Higher layers (TS, PES, PSI) live in mpeg-ts, mpeg-pes, dvb-si.
ETSI EN 300 468 V1.20.1 (vendored; the 2038 MJD wrap rule is from this edition) Annex A CRC-32 (same polynomial as above); Annex C MJD + BCD UTC time and BCD durations (time, bcd) Full for the codecs MJD range 1948-08-05 ..= 2128-01-09. Integer proleptic-Gregorian arithmetic (no closed-form Annex C formula limit).
ETSI TS 102 773 V1.4.1 Annex A CRC-32 for T2-MI packets (same crc32_mpeg2) Full for the CRC The packet format is in dvb-t2mi.
ETSI EN 300 706 V1.2.1 §8.1 odd-parity protected byte (parity) Partial: parity primitive only Also used for CEA-608 line-21 bytes. Detect-only by design.
RFC 1982 serial-number arithmetic n/a modular::Modulus wrap-safe sequence comparison (RTP 16-bit, SRT 31-bit) Comparable, not spec-cited Implementation policy, not defined by RTP/SRT.

The runtime and HTTP helpers (backoff, timeouts, abr, net, range, content_range, http_date, url_ref, ...) live in the separate broadcast-net crate.

Feature flags

Feature Default What it enables
std yes Links std, forwarding to jiff/std, serde?/std and erased-serde?/std when those are on. Off gives #![no_std] + alloc; the error types implement core::error::Error.
jiff no jiff::Timestamp conversions in time (decode_mjd_bcd_utc/encode_mjd_bcd_utc, decode_seconds_since_2000_utc/encode_seconds_since_2000_utc); no_std compatible. Without it the plain MjdBcdDateTime, MJD and duration helpers stay available.
serde no serde::Serialize on the shared types that carry one (clock33 values, klv items), with broadcast-core/serde.
xml no xml (the bounded quick-xml tree reader: depth, attribute, size limits; DOCTYPE refused) and xml_chars (XML 1.0 character data with the typed XmlCharError, XmlLimits/XmlBudget, XmlWriter, whose write helpers refuse a character outside the Char production with WriteRefusal::InvalidChar). Implies std.
lang no lang: ISO 639 -> BCP 47 canonicalisation (bcp47_language, also at the crate root) and language_matches. Implies std.
base64 no base64: base64_encode, base64_decode_strict, base64_decode_lenient (RFC 4648), base64_url_encode_nopad/base64_url_decode_nopad (URL-safe alphabet, no padding), Base64DecodeError. no_std + alloc.
[dependencies]
broadcast-common = "15"
# embedded (no_std + alloc):
# broadcast-common = { version = "15", default-features = false }

Quick start

use broadcast_core::{Parse, Serialize};
use broadcast_common::{bcd, clock33, crc32_mpeg2};

// CRC-32/MPEG-2 over a real PAT section (from the committed m6-single.ts fixture):
// the CRC of the body equals the trailing CRC_32 field.
let section = [
    0x00, 0xB0, 0x0D, 0x00, 0x01, 0xC1, 0x00, 0x00, 0x04, 0x01, 0xE0, 0x64,
    0xF9, 0xB4, 0x63, 0xEF,
];
let crc = crc32_mpeg2::compute(&section[..section.len() - 4]);
assert_eq!(crc, 0xF9B4_63EF);

// BCD and 33-bit clock arithmetic.
assert_eq!(bcd::from_bcd_byte(0x42), Some(42));
assert_eq!(clock33::add(clock33::WRAP_33BIT - 1, 2), 1);
assert_eq!(clock33::signed_distance(clock33::WRAP_33BIT - 10, 5), 15);

// Implement the symmetric contract for your own wire type.
#[derive(Debug, PartialEq)]
struct Toy { tag: u8, value: u16 }

impl<'a> Parse<'a> for Toy {
    type Error = &'static str;
    fn parse(b: &'a [u8]) -> Result<Self, Self::Error> {
        if b.len() < 3 { return Err("short"); }
        Ok(Toy { tag: b[0], value: u16::from_be_bytes([b[1], b[2]]) })
    }
}
impl Serialize for Toy {
    type Error = &'static str;
    fn serialized_len(&self) -> usize { 3 }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        if buf.len() < 3 { return Err("short"); }
        buf[0] = self.tag;
        buf[1..3].copy_from_slice(&self.value.to_be_bytes());
        Ok(3)
    }
}
let wire = [0x42, 0x12, 0x34];
let toy = Toy::parse(&wire)?;
assert_eq!(toy.try_to_bytes()?, wire); // the workspace round-trip invariant
# Ok::<(), &'static str>(())

Runnable examples: crc_and_bcd, timestamps, dvb_time and klv_items (cargo run -p broadcast-common --example <name>). The implement_parse_serialize example lives in broadcast-core: cargo run -p broadcast-core --example implement_parse_serialize.

What is implemented

Module Public API
crc32_mpeg2 compute, seal, verify, verify_trailer and TRAILER_LEN (poly 0x04C1_1DB7, init 0xFFFF_FFFF, MSB-first, no reflection, no final XOR; table built at compile time)
bcd from_bcd_byte, to_bcd_byte and wider helpers; None on out-of-range input, never garbage
time MjdBcdDateTime, decode_mjd_bcd/encode_mjd_bcd, decode_bcd_duration/encode_bcd_duration, mjd_to_ymd/ymd_to_mjd; with jiff: decode_mjd_bcd_utc/encode_mjd_bcd_utc, decode_seconds_since_2000_utc/encode_seconds_since_2000_utc (jiff::Timestamp). The encoder rejects impossible days (31 Feb)
clock33 Clock33 (validated 33-bit 90 kHz sample: try_new, ZERO, wrapping_add, wrapping_add_signed, signed_distance_to) and Clock27 (base * 300 + ext 27 MHz value: strict from_parts/from_27mhz, lossless from_wire_parts, checked to_clock27/is_valid, ticks, signed_distance_to), the workspace's one PTS/DTS and PCR/ESCR/SCR representation, with ClockOutOfRange; WRAP_33BIT, unwrap_delta, wrapping_forward_distance, add, add_signed, signed_distance, PTS_SPACE, Clock33::from_ticks_wrapping; PCR: PTS_HZ, PCR_HZ, PCR_EXT_MODULUS, PCR_WRAP_27MHZ, pcr_from_parts, pcr_split, pcr_forward_distance, pcr_signed_distance, pcr_ticks_from_duration, PCR_TICKS_PER_MICRO; marker-bit timestamp field: MARKED_FIELD_LEN, Marked, MARKERS_ALL_SET, unpack_marked, pack_marked, pack_marked_with
sdp SdpMedia, SdpMediaType, SdpAttribute: the media-section model the RTP crates exchange, so no SDP library type is in a public API
modular Modulus (new::<BITS>, try_new, add, forward, signed, lt/leq/gt/geq, is_tie, in_closed_range, extend_near) and Unwrapper: wrap-safe arithmetic on 16/31/32/33-bit counters
parity has_odd_parity, set_odd_parity, strip_parity
hex hex_encode, hex_encode_upper, hex_decode (even-length hex of either case, else None), hex_decode_into (exactly 2 * out.len() digits into a fixed slice, typed HexDecodeError)
bounded read_bounded, read_file_bounded, read_file_bounded_string under a named Limit (Limit::new), BoundedReadError (TooLarge { limit_name, limit_bytes }, Io, NotUtf8): the one whole-document read, so a wrong or hostile path cannot exhaust memory
ber decode_ber_length, encode_ber_length, encode_ber_length_as, ber_length_size, ber_length_size_for (X.690 definite-form lengths)
klv KlvItem (parse_prefix), walk_klv_items, collect_klv_items, UniversalLabel, BerLength, KlvError (SMPTE ST 336 triplets)
wire_enum! A #[repr] spec enum with a checked TryFrom, a total From and name()/Display from one declaration.
erased declare_object_trait! support: the type-erased value face behind the dvb-si/dvb-t2mi runtime registries
base64, lang, xml, xml_chars Feature-gated; see the feature table above

Design notes

  • Reserved-bit and trailing-byte policy (workspace-wide, issue #1139): parse is tolerant; serialize preserves what was parsed in typed, spec-named fields (no raw passthrough blobs); hand-built values default to the edition value (1 for reserved_future_use, 0 for reserved_zero_future_use); reserved bytes are always written explicitly; trailing bytes are never dropped without a documented decision.
  • Round-trip invariant. Every wire type parses to a borrowed struct and serializes back byte-identically; broadcast-core supplies the traits and the rule and this crate the shared codecs, and each crate carries the round-trip tests.
  • Checked widths, not masks. broadcast_core::len::fit_* returns FieldOverflow when a value does not fit its field; the & MASK idiom is banned in serializers.
  • One clock implementation. PCR/PTS/DTS/pts_time wrap arithmetic lives in clock33; the 2^33 modulus must not be re-derived elsewhere, and the values are its types: Clock33 for a 33-bit 90 kHz sample, Clock27 for a 27 MHz base * 300 + ext. Constructing is strict and parsing is lossless: a wire field goes through Clock27::from_wire_parts, and to_clock27 is the checked view that reports an off-clock value (a 9-bit extension of 300..=511) instead of making real data unparseable.
  • Label convention. broadcast_core::impl_spec_display! keeps Display in lockstep with the hand-written name() of every public spec enum.
  • #![forbid(unsafe_code)], #![warn(missing_docs)], no_std + alloc without std.

Related crates and licence

Versioned independently of the DVB lockstep crates (it ships from its own broadcast-common-v* tag). Every protocol crate depends on it; it depends on none of them. See the workspace README for the crate map.

MSRV 1.95.0. Licensed under MIT OR Apache-2.0, at your option.