Skip to main content

mpeg_ts/
pid.rs

1//! MPEG-TS Packet Identifier (PID) types and well-known PID constants.
2//!
3//! Specified by ITU-T H.222.0 §2.4 (= ISO/IEC 13818-1). DVB-specific
4//! well-known PID assignments are also listed in ETSI EN 300 468 §5.1.3 Table 1.
5
6/// A 13-bit MPEG-TS Packet Identifier.
7///
8/// Thin newtype over the wire `u16`, always in `0x0000..=0x1FFF` (the
9/// transport header field width, ISO/IEC 13818-1 §2.4.3.2). Construction never
10/// masks a caller-supplied value: [`Pid::try_new`] rejects an out-of-range
11/// one, [`Pid::from_wire_masked`] is the explicit parse-site constructor, and
12/// [`Pid::from_const`] is the compile-time constructor for constants.
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize))]
15#[cfg_attr(feature = "serde", serde(transparent))]
16pub struct Pid(u16);
17
18impl Pid {
19    /// Mask covering the 13 valid PID bits.
20    pub const MASK: u16 = 0x1FFF;
21
22    /// Construct a constant `Pid`, **failing compilation** (a `const` panic)
23    /// when `value` exceeds [`Pid::MASK`].
24    ///
25    /// This is the constructor for well-known PIDs and table constants: a
26    /// mistyped literal is a build error, never a silently masked different
27    /// PID. Runtime values use [`Pid::try_new`].
28    ///
29    /// ```
30    /// use mpeg_ts::pid::Pid;
31    /// const PMT: Pid = Pid::from_const(0x0100);
32    /// assert_eq!(PMT.value(), 0x0100);
33    /// ```
34    #[must_use]
35    pub const fn from_const(value: u16) -> Self {
36        assert!(
37            value <= Self::MASK,
38            "PID constant exceeds the 13-bit range 0x0000..=0x1FFF"
39        );
40        Self(value)
41    }
42
43    /// Construct a `Pid` from the low 13 bits of `value`, **deliberately**
44    /// discarding the rest: the explicit name for extracting the 13-bit PID
45    /// field out of a wider wire word (e.g. `reserved(3)` + `PID(13)`), where
46    /// masking is the specified behaviour. Use this only at parse sites, so a
47    /// caller-supplied value is never masked by accident; use
48    /// [`Pid::try_new`] for those and [`Pid::from_const`] for constants.
49    ///
50    /// ```
51    /// use mpeg_ts::pid::Pid;
52    /// // reserved(3) = 0b111 followed by PID 0x0100.
53    /// assert_eq!(Pid::from_wire_masked(0xE100).value(), 0x0100);
54    /// assert_eq!(Pid::try_new(0xE100).unwrap_err().value, 0xE100);
55    /// ```
56    #[must_use]
57    pub const fn from_wire_masked(value: u16) -> Self {
58        Self(value & Self::MASK)
59    }
60
61    /// Construct a `Pid`, rejecting any value above [`Pid::MASK`] (`0x1FFF`).
62    ///
63    /// Use this at API boundaries that take a caller-supplied value.
64    ///
65    /// # Errors
66    /// [`PidOutOfRange`] when `value > 0x1FFF`.
67    pub const fn try_new(value: u16) -> Result<Self, PidOutOfRange> {
68        if value > Self::MASK {
69            Err(PidOutOfRange { value })
70        } else {
71            Ok(Self(value))
72        }
73    }
74
75    /// The raw 13-bit value.
76    #[must_use]
77    pub const fn value(self) -> u16 {
78        self.0
79    }
80}
81
82/// A value that does not fit the 13-bit PID field (ISO/IEC 13818-1 §2.4.3.2).
83#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
84#[error("PID 0x{value:04X} exceeds the 13-bit range 0x0000..=0x1FFF")]
85#[non_exhaustive]
86pub struct PidOutOfRange {
87    /// The rejected value.
88    pub value: u16,
89}
90
91impl TryFrom<u16> for Pid {
92    type Error = PidOutOfRange;
93    fn try_from(value: u16) -> Result<Self, Self::Error> {
94        Self::try_new(value)
95    }
96}
97
98/// Why [`Pid`]'s `FromStr` rejected a string.
99#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
100#[non_exhaustive]
101pub enum ParsePidError {
102    /// Not a decimal or `0x`-prefixed hexadecimal number.
103    #[error("PID is not a decimal or 0x-prefixed hexadecimal number: {0}")]
104    Number(#[from] core::num::ParseIntError),
105    /// A number above the 13-bit range.
106    #[error(transparent)]
107    OutOfRange(#[from] PidOutOfRange),
108}
109
110/// Radix of a `0x`-prefixed PID.
111const HEX_RADIX: u32 = 16;
112
113impl core::str::FromStr for Pid {
114    type Err = ParsePidError;
115
116    /// A PID as a decimal number or `0x`-prefixed hexadecimal, within the
117    /// 13-bit range.
118    fn from_str(s: &str) -> Result<Self, Self::Err> {
119        let value = match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
120            Some(hex) => u16::from_str_radix(hex, HEX_RADIX)?,
121            None => s.parse::<u16>()?,
122        };
123        Ok(Self::try_new(value)?)
124    }
125}
126
127impl From<Pid> for u16 {
128    fn from(pid: Pid) -> Self {
129        pid.0
130    }
131}
132
133impl core::fmt::Debug for Pid {
134    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
135        write!(f, "Pid(0x{:04X})", self.0)
136    }
137}
138
139impl core::fmt::UpperHex for Pid {
140    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
141        core::fmt::UpperHex::fmt(&self.0, f)
142    }
143}
144
145impl core::fmt::LowerHex for Pid {
146    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
147        core::fmt::LowerHex::fmt(&self.0, f)
148    }
149}
150
151impl core::fmt::Display for Pid {
152    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
153        write!(f, "0x{:04X}", self.0)
154    }
155}
156
157/// Well-known PIDs. The transport stream MUST carry the corresponding tables
158/// on these PIDs.
159///
160/// Each constant is a [`crate::pid::Pid`]; call `.value()` to obtain the raw
161/// `u16`, or use `Pid::try_from(u16)` / `u16::from(Pid)` for conversions.
162pub mod well_known {
163    use super::Pid;
164
165    /// Program Association Table (MPEG-2).
166    pub const PAT: Pid = Pid::from_const(0x0000);
167    /// Conditional Access Table (MPEG-2).
168    pub const CAT: Pid = Pid::from_const(0x0001);
169    /// Transport Stream Description Table (MPEG-2).
170    pub const TSDT: Pid = Pid::from_const(0x0002);
171    /// IPMP Control Information Table (MPEG-2).
172    pub const IPMP_CIT: Pid = Pid::from_const(0x0003);
173    /// Network Information Table (DVB).
174    pub const NIT: Pid = Pid::from_const(0x0010);
175    /// Service Description Table + Bouquet Association Table (DVB).
176    pub const SDT_BAT: Pid = Pid::from_const(0x0011);
177    /// Event Information Table (DVB).
178    pub const EIT: Pid = Pid::from_const(0x0012);
179    /// Running Status Table (DVB).
180    pub const RST: Pid = Pid::from_const(0x0013);
181    /// Time and Date + Time Offset + Stuffing (DVB).
182    pub const TDT_TOT: Pid = Pid::from_const(0x0014);
183    /// Network synchronisation.
184    pub const NETWORK_SYNC: Pid = Pid::from_const(0x0015);
185    /// Resolution Notification Table.
186    pub const RNT: Pid = Pid::from_const(0x0016);
187    /// Satellite Access Table (EN 300 468 Table 1).
188    pub const SAT: Pid = Pid::from_const(0x001B);
189    /// Link-local inband signalling (EN 300 468 Table 1); only for use between
190    /// devices in a controlled environment, never on a broadcast signal.
191    pub const INBAND_SIGNALLING: Pid = Pid::from_const(0x001C);
192    /// Measurement (reserved).
193    pub const MEASUREMENT: Pid = Pid::from_const(0x001D);
194    /// Discontinuity Information Table.
195    pub const DIT: Pid = Pid::from_const(0x001E);
196    /// Selection Information Table.
197    pub const SIT: Pid = Pid::from_const(0x001F);
198
199    /// ATSC PSIP base PID.
200    pub const ATSC_PSIP: Pid = Pid::from_const(0x1FFB);
201
202    /// Null-packet padding PID. Payload is ignored.
203    pub const NULL: Pid = Pid::from_const(0x1FFF);
204}
205
206#[cfg(test)]
207mod tests {
208    #[test]
209    fn from_str_accepts_decimal_and_hex_within_13_bits() {
210        assert_eq!("256".parse::<Pid>(), Ok(Pid::from_const(0x100)));
211        assert_eq!("0x100".parse::<Pid>(), Ok(Pid::from_const(0x100)));
212        assert_eq!("0X1FFF".parse::<Pid>(), Ok(Pid::from_const(0x1FFF)));
213        assert!(matches!(
214            "8192".parse::<Pid>(),
215            Err(ParsePidError::OutOfRange(_))
216        ));
217        assert!(matches!(
218            "0x2000".parse::<Pid>(),
219            Err(ParsePidError::OutOfRange(_))
220        ));
221        assert!(matches!(
222            "pat".parse::<Pid>(),
223            Err(ParsePidError::Number(_))
224        ));
225        assert!(matches!("".parse::<Pid>(), Err(ParsePidError::Number(_))));
226    }
227
228    use super::*;
229
230    #[test]
231    fn from_const_is_the_compile_time_constructor() {
232        const PMT: Pid = Pid::from_const(0x0100);
233        assert_eq!(PMT.value(), 0x0100);
234        assert_eq!(Pid::from_const(0).value(), 0);
235        assert_eq!(Pid::from_const(Pid::MASK).value(), 0x1FFF);
236    }
237
238    #[test]
239    fn try_new_and_from_wire_masked_differ_only_in_policy() {
240        assert_eq!(Pid::try_new(0x0000), Ok(well_known::PAT));
241        assert_eq!(Pid::try_new(Pid::MASK), Ok(well_known::NULL));
242        assert!(Pid::try_new(0x2000).is_err());
243        assert_eq!(Pid::from_wire_masked(0xE100).value(), 0x0100);
244    }
245
246    #[test]
247    fn inband_signalling_sits_between_sat_and_measurement() {
248        assert_eq!(well_known::INBAND_SIGNALLING.value(), 0x001C);
249        assert_eq!(
250            well_known::INBAND_SIGNALLING.value(),
251            well_known::SAT.value() + 1
252        );
253        assert_eq!(
254            well_known::MEASUREMENT.value(),
255            well_known::INBAND_SIGNALLING.value() + 1
256        );
257    }
258}