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