Skip to main content

broadcast_common/
lib.rs

1//! Shared primitives for the dvb_si / dvb_t2mi / dvb_bbframe family.
2//!
3//! See individual modules for documentation: the [`Parse`] / [`Serialize`]
4//! traits every wire type implements, the MPEG-2 [`crc32_mpeg2`] CRC, the
5//! [`bcd`] / [`time`] / [`hex`] codecs, the [`mux`] container-mux traits, and
6//! the [`cenc`] Common Encryption scheme identity those traits protect with.
7//!
8//! # Container-mux traits ([`mux`])
9//!
10//! The [`mux`] module defines the codec-agnostic vocabulary for the any-to-any
11//! muxing hub, mirroring the [`Parse`] / [`Serialize`] symmetry:
12//!
13//! - [`Unpackage`] — demux a packaged container into an in-memory media IR.
14//! - [`Package`] — mux a media IR back into a packaged container.
15//! - [`Decrypt`] / [`Encrypt`] — in-place sample (un)protection.
16//!
17//! Each is generic over its input/output/media/config/key associated types plus
18//! `type Error`; no concrete media or codec types appear here. `Unpackage` ⇄
19//! `Package` and `Decrypt` ⇄ `Encrypt` are inverse pairs. Concrete
20//! implementations live in the container crates (e.g. `transmux`).
21//!
22//! These are the *batch* container-mux contract, operating on a whole packaged
23//! container at once. For the complementary *incremental* contract — feed
24//! bytes in, poll typed output out, drive on a clock — see [`stage`].
25//!
26//! # Incremental staging ([`stage`])
27//!
28//! The [`stage`] module defines [`Stage`](stage::Stage), the drive shape every
29//! streaming stage in the workspace (TS/FLV demuxers, HLS/LL-HLS segmenters,
30//! conformance monitors, …) is converging on: `feed`/`poll`/`finish` plus a
31//! [`Timestamp`](stage::Timestamp) clock parameter and deadline hooks for
32//! purely time-driven work, and a [`Demand`](stage::Demand) backpressure hint.
33//!
34//! # Quick start
35//! ```
36//! use broadcast_common::{bcd, crc32_mpeg2};
37//!
38//! // Binary-coded decimal (as used in MJD/BCD time fields):
39//! assert_eq!(bcd::from_bcd_byte(0x42), Some(42));
40//! assert_eq!(bcd::to_bcd_byte(42), Some(0x42));
41//!
42//! // MPEG-2 CRC-32 over a section body (deterministic):
43//! let crc = crc32_mpeg2::compute(&[0xDE, 0xAD, 0xBE, 0xEF]);
44//! assert_eq!(crc, crc32_mpeg2::compute(&[0xDE, 0xAD, 0xBE, 0xEF]));
45//! ```
46
47#![forbid(unsafe_code)]
48#![warn(missing_docs)]
49#![cfg_attr(docsrs, feature(doc_cfg))]
50#![cfg_attr(not(feature = "std"), no_std)]
51// The crate's runnable examples, embedded so they render on docs.rs and stay in
52// sync with the actual `examples/*.rs` files (shown, not compiled).
53#![doc = "\n# Examples\n"]
54#![doc = "Two runnable examples ship with this crate (`cargo run -p broadcast-common --example <name>`).\n"]
55#![doc = "\n## `crc_and_bcd`\n\n```rust,ignore"]
56#![doc = include_str!("../examples/crc_and_bcd.rs")]
57#![doc = "```\n\n## `implement_parse_serialize`\n\n```rust,ignore"]
58#![doc = include_str!("../examples/implement_parse_serialize.rs")]
59#![doc = "```"]
60
61extern crate alloc;
62
63pub mod bcd;
64pub mod bits;
65pub mod cenc;
66pub mod crc32_mpeg2;
67pub mod hex;
68pub mod mux;
69pub mod stage;
70pub mod time;
71pub mod traits;
72
73pub use cenc::CencScheme;
74pub use mux::{Decrypt, Encrypt, Package, Unpackage};
75pub use stage::{Demand, Stage, Timestamp};
76pub use traits::{Parse, Serialize};
77
78/// Generate a [`core::fmt::Display`] impl for a spec/field enum that delegates
79/// to an inherent `fn name(&self) -> &'static str`.
80///
81/// This is the project-wide convention for every public spec/field enum across
82/// the `dvb-*` crates (see issue #204): `name()` is the hand-written,
83/// zero-alloc static spec token (lossy on the reserved/unknown arm, which
84/// returns `"reserved"`), and `Display` is the lossless, composable view that
85/// delegates to it. The labels themselves live in `name()` in source — never in
86/// this macro — so they sit next to the variant docs and stay greppable. This
87/// macro carries no labels; it only removes the otherwise-identical `Display`
88/// boilerplate and keeps the two in lockstep.
89///
90/// # Forms
91/// - `impl_spec_display!(Ty)` — every variant's `Display` is exactly `name()`.
92///   Use when there is no byte-bearing catch-all (or its byte need not be
93///   shown), e.g. a unit `Reserved` variant.
94/// - `impl_spec_display!(Ty, Var1, Var2, …)` — each named variant is a
95///   single-field tuple binding a byte; `Display` renders it as
96///   `"{name}(0x{:02X})"` so the value is preserved (e.g. `Reserved(0x1A)` →
97///   `reserved(0x1A)`, `UserDefined(0x1A)` → `user defined(0x1A)`). All other
98///   variants delegate to `name()`.
99///
100/// ```
101/// pub enum Mode { Normal, HighEfficiency, Reserved(u8) }
102/// impl Mode {
103///     pub fn name(&self) -> &'static str {
104///         match self {
105///             Self::Normal => "normal",
106///             Self::HighEfficiency => "high efficiency",
107///             Self::Reserved(_) => "reserved",
108///         }
109///     }
110/// }
111/// broadcast_common::impl_spec_display!(Mode, Reserved);
112/// assert_eq!(Mode::Normal.to_string(), "normal");
113/// assert_eq!(Mode::Reserved(0x1A).to_string(), "reserved(0x1A)");
114/// ```
115#[macro_export]
116macro_rules! impl_spec_display {
117    ($ty:ty) => {
118        impl ::core::fmt::Display for $ty {
119            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
120                f.write_str(self.name())
121            }
122        }
123    };
124    ($ty:ty, $($resv:ident),+ $(,)?) => {
125        impl ::core::fmt::Display for $ty {
126            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
127                match self {
128                    $( Self::$resv(v) => ::core::write!(f, "{}(0x{:02X})", self.name(), v), )+
129                    other => f.write_str(other.name()),
130                }
131            }
132        }
133    };
134}