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)]
84#[non_exhaustive]
85pub struct PidOutOfRange {
86    /// The rejected value.
87    pub value: u16,
88}
89
90impl core::fmt::Display for PidOutOfRange {
91    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92        write!(
93            f,
94            "PID 0x{:04X} exceeds the 13-bit range 0x0000..=0x1FFF",
95            self.value
96        )
97    }
98}
99
100impl core::error::Error for PidOutOfRange {}
101
102impl TryFrom<u16> for Pid {
103    type Error = PidOutOfRange;
104    fn try_from(value: u16) -> Result<Self, Self::Error> {
105        Self::try_new(value)
106    }
107}
108
109impl From<Pid> for u16 {
110    fn from(pid: Pid) -> Self {
111        pid.0
112    }
113}
114
115impl core::fmt::Debug for Pid {
116    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
117        write!(f, "Pid(0x{:04X})", self.0)
118    }
119}
120
121impl core::fmt::UpperHex for Pid {
122    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
123        core::fmt::UpperHex::fmt(&self.0, f)
124    }
125}
126
127impl core::fmt::LowerHex for Pid {
128    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
129        core::fmt::LowerHex::fmt(&self.0, f)
130    }
131}
132
133impl core::fmt::Display for Pid {
134    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
135        write!(f, "0x{:04X}", self.0)
136    }
137}
138
139/// Well-known PIDs. The transport stream MUST carry the corresponding tables
140/// on these PIDs.
141///
142/// Each constant is a [`crate::pid::Pid`]; call `.value()` to obtain the raw
143/// `u16`, or use `Pid::try_from(u16)` / `u16::from(Pid)` for conversions.
144pub mod well_known {
145    use super::Pid;
146
147    /// Program Association Table (MPEG-2).
148    pub const PAT: Pid = Pid::from_const(0x0000);
149    /// Conditional Access Table (MPEG-2).
150    pub const CAT: Pid = Pid::from_const(0x0001);
151    /// Transport Stream Description Table (MPEG-2).
152    pub const TSDT: Pid = Pid::from_const(0x0002);
153    /// IPMP Control Information Table (MPEG-2).
154    pub const IPMP_CIT: Pid = Pid::from_const(0x0003);
155    /// Network Information Table (DVB).
156    pub const NIT: Pid = Pid::from_const(0x0010);
157    /// Service Description Table + Bouquet Association Table (DVB).
158    pub const SDT_BAT: Pid = Pid::from_const(0x0011);
159    /// Event Information Table (DVB).
160    pub const EIT: Pid = Pid::from_const(0x0012);
161    /// Running Status Table (DVB).
162    pub const RST: Pid = Pid::from_const(0x0013);
163    /// Time and Date + Time Offset + Stuffing (DVB).
164    pub const TDT_TOT: Pid = Pid::from_const(0x0014);
165    /// Network synchronisation.
166    pub const NETWORK_SYNC: Pid = Pid::from_const(0x0015);
167    /// Resolution Notification Table.
168    pub const RNT: Pid = Pid::from_const(0x0016);
169    /// Satellite Access Table (EN 300 468 Table 1).
170    pub const SAT: Pid = Pid::from_const(0x001B);
171    /// Link-local inband signalling (EN 300 468 Table 1); only for use between
172    /// devices in a controlled environment, never on a broadcast signal.
173    pub const INBAND_SIGNALLING: Pid = Pid::from_const(0x001C);
174    /// Measurement (reserved).
175    pub const MEASUREMENT: Pid = Pid::from_const(0x001D);
176    /// Discontinuity Information Table.
177    pub const DIT: Pid = Pid::from_const(0x001E);
178    /// Selection Information Table.
179    pub const SIT: Pid = Pid::from_const(0x001F);
180
181    /// ATSC PSIP base PID.
182    pub const ATSC_PSIP: Pid = Pid::from_const(0x1FFB);
183
184    /// Null-packet padding PID. Payload is ignored.
185    pub const NULL: Pid = Pid::from_const(0x1FFF);
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn from_const_is_the_compile_time_constructor() {
194        const PMT: Pid = Pid::from_const(0x0100);
195        assert_eq!(PMT.value(), 0x0100);
196        assert_eq!(Pid::from_const(0).value(), 0);
197        assert_eq!(Pid::from_const(Pid::MASK).value(), 0x1FFF);
198    }
199
200    #[test]
201    fn try_new_and_from_wire_masked_differ_only_in_policy() {
202        assert_eq!(Pid::try_new(0x0000), Ok(well_known::PAT));
203        assert_eq!(Pid::try_new(Pid::MASK), Ok(well_known::NULL));
204        assert!(Pid::try_new(0x2000).is_err());
205        assert_eq!(Pid::from_wire_masked(0xE100).value(), 0x0100);
206    }
207
208    #[test]
209    fn inband_signalling_sits_between_sat_and_measurement() {
210        assert_eq!(well_known::INBAND_SIGNALLING.value(), 0x001C);
211        assert_eq!(
212            well_known::INBAND_SIGNALLING.value(),
213            well_known::SAT.value() + 1
214        );
215        assert_eq!(
216            well_known::MEASUREMENT.value(),
217            well_known::INBAND_SIGNALLING.value() + 1
218        );
219    }
220}