Skip to main content

dvb_si/descriptors/
tva_id.rs

1//! TVA_id Descriptor — ETSI TS 102 323 §11.2.4, Table 114 (tag 0x75).
2//!
3//! Lists one or more TV-Anytime identifiers, each with a running_status that
4//! a receiver uses to drive its recording strategy. Per the TVA PDF
5//! (etsi_ts_102_323_v01.04.01, p. 101, Table 114) each loop entry is 3 bytes:
6//! TVA_id(16) + Reserved(5) + running_status(3). running_status values are
7//! defined in Table 115.
8
9use super::descriptor_body;
10use crate::error::{Error, Result};
11use dvb_common::{Parse, Serialize};
12
13/// Descriptor tag for TVA_id_descriptor.
14pub const TAG: u8 = 0x75;
15const HEADER_LEN: usize = 2;
16const ENTRY_LEN: usize = 3;
17
18/// Largest representable 3-bit running_status.
19const RUNNING_STATUS_MAX: u8 = 0x07;
20
21/// TVA running status — ETSI TS 102 323 Table 115.
22///
23/// NOTE: This is the TVA-specific running_status table, NOT the
24/// EN 300 468 Table 6 running_status.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize))]
27#[non_exhaustive]
28pub enum TvaRunningStatus {
29    /// 0 — reserved.
30    Reserved,
31    /// 1 — not yet running.
32    NotYetRunning,
33    /// 2 — starts shortly.
34    StartsShortly,
35    /// 3 — paused.
36    Paused,
37    /// 4 — running.
38    Running,
39    /// 5 — cancelled.
40    Cancelled,
41    /// 6 — completed.
42    Completed,
43    /// Unallocated wire value, preserved verbatim for round-trip.
44    Unallocated(u8),
45}
46
47impl TvaRunningStatus {
48    #[must_use]
49    /// Creates a value from a wire byte, preserving every possible
50    /// byte value for lossless round-trip.
51    pub fn from_u8(v: u8) -> Self {
52        match v {
53            0 => Self::Reserved,
54            1 => Self::NotYetRunning,
55            2 => Self::StartsShortly,
56            3 => Self::Paused,
57            4 => Self::Running,
58            5 => Self::Cancelled,
59            6 => Self::Completed,
60            v => Self::Unallocated(v),
61        }
62    }
63
64    #[must_use]
65    /// Returns the wire byte for this value.
66    pub fn to_u8(self) -> u8 {
67        match self {
68            Self::Reserved => 0,
69            Self::NotYetRunning => 1,
70            Self::StartsShortly => 2,
71            Self::Paused => 3,
72            Self::Running => 4,
73            Self::Cancelled => 5,
74            Self::Completed => 6,
75            Self::Unallocated(v) => v,
76        }
77    }
78
79    #[must_use]
80    /// Returns a human-readable spec name for this value.
81    pub fn name(self) -> &'static str {
82        match self {
83            Self::Reserved => "reserved",
84            Self::NotYetRunning => "not yet running",
85            Self::StartsShortly => "starts shortly",
86            Self::Paused => "paused",
87            Self::Running => "running",
88            Self::Cancelled => "cancelled",
89            Self::Completed => "completed",
90            Self::Unallocated(_) => "unallocated",
91        }
92    }
93}
94
95/// One TVA_id loop entry.
96#[derive(Debug, Clone, PartialEq, Eq)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize))]
98pub struct TvaIdEntry {
99    /// 16-bit TVA_id referencing the item of content.
100    pub tva_id: u16,
101    /// 3-bit running_status (Table 115).
102    pub running_status: TvaRunningStatus,
103}
104
105/// TVA_id Descriptor.
106#[derive(Debug, Clone, PartialEq, Eq)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize))]
108pub struct TvaIdDescriptor {
109    /// Entries in wire order.
110    pub entries: Vec<TvaIdEntry>,
111}
112
113impl<'a> Parse<'a> for TvaIdDescriptor {
114    type Error = crate::error::Error;
115    fn parse(bytes: &'a [u8]) -> Result<Self> {
116        let body = descriptor_body(
117            bytes,
118            TAG,
119            "TvaIdDescriptor",
120            "unexpected tag for TVA_id_descriptor",
121        )?;
122        if body.len() % ENTRY_LEN != 0 {
123            return Err(Error::InvalidDescriptor {
124                tag: TAG,
125                reason: "TVA_id_descriptor length must be a multiple of 3",
126            });
127        }
128        let mut entries = Vec::with_capacity(body.len() / ENTRY_LEN);
129        for chunk in body.chunks_exact(ENTRY_LEN) {
130            let tva_id = u16::from_be_bytes([chunk[0], chunk[1]]);
131            let running_status = TvaRunningStatus::from_u8(chunk[2] & RUNNING_STATUS_MAX);
132            entries.push(TvaIdEntry {
133                tva_id,
134                running_status,
135            });
136        }
137        Ok(Self { entries })
138    }
139}
140
141impl Serialize for TvaIdDescriptor {
142    type Error = crate::error::Error;
143    fn serialized_len(&self) -> usize {
144        HEADER_LEN + self.entries.len() * ENTRY_LEN
145    }
146
147    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
148        for e in &self.entries {
149            if e.running_status.to_u8() > RUNNING_STATUS_MAX {
150                return Err(Error::InvalidDescriptor {
151                    tag: TAG,
152                    reason: "running_status exceeds 3 bits",
153                });
154            }
155        }
156        if self.entries.len() * ENTRY_LEN > u8::MAX as usize {
157            return Err(Error::InvalidDescriptor {
158                tag: TAG,
159                reason: "TVA_id_descriptor body exceeds 255 bytes",
160            });
161        }
162        let len = self.serialized_len();
163        if buf.len() < len {
164            return Err(Error::OutputBufferTooSmall {
165                need: len,
166                have: buf.len(),
167            });
168        }
169        buf[0] = TAG;
170        buf[1] = (self.entries.len() * ENTRY_LEN) as u8;
171        let mut pos = HEADER_LEN;
172        for e in &self.entries {
173            buf[pos..pos + 2].copy_from_slice(&e.tva_id.to_be_bytes());
174            // Reserved(5) emitted as 1s.
175            buf[pos + 2] = 0xF8 | (e.running_status.to_u8() & RUNNING_STATUS_MAX);
176            pos += ENTRY_LEN;
177        }
178        Ok(len)
179    }
180}
181impl<'a> crate::traits::DescriptorDef<'a> for TvaIdDescriptor {
182    const TAG: u8 = TAG;
183    const NAME: &'static str = "TVA_ID";
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn parse_single_entry() {
192        // TVA_id=0x1234, running_status=4 (running), reserved bits set.
193        let bytes = [TAG, 3, 0x12, 0x34, 0xFC];
194        let d = TvaIdDescriptor::parse(&bytes).unwrap();
195        assert_eq!(d.entries.len(), 1);
196        assert_eq!(d.entries[0].tva_id, 0x1234);
197        assert_eq!(d.entries[0].running_status, TvaRunningStatus::Running);
198    }
199
200    #[test]
201    fn parse_multiple_entries() {
202        let bytes = [TAG, 6, 0x00, 0x01, 0x01, 0xAB, 0xCD, 0x06];
203        let d = TvaIdDescriptor::parse(&bytes).unwrap();
204        assert_eq!(d.entries.len(), 2);
205        assert_eq!(d.entries[0].tva_id, 0x0001);
206        assert_eq!(d.entries[0].running_status, TvaRunningStatus::NotYetRunning);
207        assert_eq!(d.entries[1].tva_id, 0xABCD);
208        assert_eq!(d.entries[1].running_status, TvaRunningStatus::Completed);
209    }
210
211    #[test]
212    fn parse_ignores_reserved_bits() {
213        let bytes = [TAG, 3, 0x00, 0x00, 0xFF];
214        let d = TvaIdDescriptor::parse(&bytes).unwrap();
215        assert_eq!(
216            d.entries[0].running_status,
217            TvaRunningStatus::Unallocated(0x07)
218        );
219    }
220
221    #[test]
222    fn parse_rejects_wrong_tag() {
223        assert!(matches!(
224            TvaIdDescriptor::parse(&[0x74, 0]).unwrap_err(),
225            Error::InvalidDescriptor { tag: 0x74, .. }
226        ));
227    }
228
229    #[test]
230    fn parse_rejects_length_not_multiple_of_3() {
231        let bytes = [TAG, 2, 0, 0];
232        assert!(matches!(
233            TvaIdDescriptor::parse(&bytes).unwrap_err(),
234            Error::InvalidDescriptor { .. }
235        ));
236    }
237
238    #[test]
239    fn empty_descriptor_valid() {
240        let bytes = [TAG, 0];
241        let d = TvaIdDescriptor::parse(&bytes).unwrap();
242        assert!(d.entries.is_empty());
243    }
244
245    #[test]
246    fn serialize_round_trip() {
247        let d = TvaIdDescriptor {
248            entries: vec![
249                TvaIdEntry {
250                    tva_id: 0x1000,
251                    running_status: TvaRunningStatus::StartsShortly,
252                },
253                TvaIdEntry {
254                    tva_id: 0xFFFF,
255                    running_status: TvaRunningStatus::Reserved,
256                },
257            ],
258        };
259        let mut buf = vec![0u8; d.serialized_len()];
260        d.serialize_into(&mut buf).unwrap();
261        assert_eq!(TvaIdDescriptor::parse(&buf).unwrap(), d);
262    }
263
264    #[test]
265    fn serialize_rejects_running_status_over_range() {
266        let d = TvaIdDescriptor {
267            entries: vec![TvaIdEntry {
268                tva_id: 0,
269                running_status: TvaRunningStatus::Unallocated(0x08),
270            }],
271        };
272        let mut buf = vec![0u8; d.serialized_len()];
273        assert!(matches!(
274            d.serialize_into(&mut buf).unwrap_err(),
275            Error::InvalidDescriptor { .. }
276        ));
277    }
278
279    #[cfg(feature = "serde")]
280    #[test]
281    fn serde_round_trip() {
282        let d = TvaIdDescriptor {
283            entries: vec![TvaIdEntry {
284                tva_id: 0x4242,
285                running_status: TvaRunningStatus::Running,
286            }],
287        };
288        let j = serde_json::to_string(&d).unwrap();
289        // Serialize-only: assert the emitted JSON re-parses (serialize-stable).
290        let _v: serde_json::Value = serde_json::from_str(&j).unwrap();
291    }
292
293    #[test]
294    fn tva_running_status_full_range_round_trip() {
295        for b in 0..=0xFF_u8 {
296            let rs = TvaRunningStatus::from_u8(b);
297            assert_eq!(rs.to_u8(), b, "round-trip failed for byte 0x{b:02X}");
298        }
299    }
300
301    #[test]
302    fn tva_running_status_name_for_known() {
303        assert_eq!(TvaRunningStatus::NotYetRunning.name(), "not yet running");
304        assert_eq!(TvaRunningStatus::Running.name(), "running");
305        assert_eq!(TvaRunningStatus::Completed.name(), "completed");
306        assert_eq!(TvaRunningStatus::Unallocated(0x07).name(), "unallocated");
307    }
308}