Skip to main content

dvb_si/tables/
tsdt.rs

1//! Transport Stream Description Table — ISO/IEC 13818-1 §2.4.5.
2//!
3//! TSDT is carried on PID 0x0002 with table_id 0x03. It provides a
4//! means of describing the transport stream using descriptors.
5
6use crate::descriptors::DescriptorLoop;
7use crate::error::{Error, Result};
8use dvb_common::{Parse, Serialize};
9
10/// table_id for Transport Stream Description Table.
11pub const TABLE_ID: u8 = 0x03;
12/// Well-known PID on which TSDT is carried.
13pub const PID: u16 = 0x0002;
14
15const MIN_HEADER_LEN: usize = 3;
16const EXTENSION_HEADER_LEN: usize = 5;
17const CRC_LEN: usize = 4;
18const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
19
20/// Transport Stream Description Table.
21#[derive(Debug, Clone, PartialEq, Eq)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize))]
23#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
24pub struct TsdtSection<'a> {
25    /// 16-bit table_id_extension.
26    pub table_id_extension: u16,
27    /// 5-bit version_number.
28    pub version_number: u8,
29    /// current_next_indicator bit.
30    pub current_next_indicator: bool,
31    /// section_number in the sub-table sequence.
32    pub section_number: u8,
33    /// last_section_number in the sub-table sequence.
34    pub last_section_number: u8,
35    /// Descriptor loop. Serializes as the typed descriptor sequence;
36    /// `.raw()` yields the wire bytes.
37    pub descriptors: DescriptorLoop<'a>,
38}
39
40impl<'a> Parse<'a> for TsdtSection<'a> {
41    type Error = crate::error::Error;
42
43    fn parse(bytes: &'a [u8]) -> Result<Self> {
44        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
45        if bytes.len() < min_len {
46            return Err(Error::BufferTooShort {
47                need: min_len,
48                have: bytes.len(),
49                what: "TsdtSection",
50            });
51        }
52
53        if bytes[0] != TABLE_ID {
54            return Err(Error::UnexpectedTableId {
55                table_id: bytes[0],
56                what: "TsdtSection",
57                expected: &[TABLE_ID],
58            });
59        }
60
61        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
62        let total = super::check_section_length(
63            bytes.len(),
64            MIN_HEADER_LEN,
65            section_length as usize,
66            MIN_SECTION_LEN,
67        )?;
68
69        let table_id_extension = u16::from_be_bytes([bytes[3], bytes[4]]);
70        let version_number = (bytes[5] >> 1) & 0x1F;
71        let current_next_indicator = (bytes[5] & 0x01) != 0;
72        let section_number = bytes[6];
73        let last_section_number = bytes[7];
74
75        // §2.4.4.12: descriptors run directly from byte 8 to the CRC; there is
76        // no descriptor_loop_length field. The section_length bounds the loop.
77        let desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
78        let desc_end = total - CRC_LEN;
79
80        Ok(TsdtSection {
81            table_id_extension,
82            version_number,
83            current_next_indicator,
84            section_number,
85            last_section_number,
86            descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
87        })
88    }
89}
90
91impl Serialize for TsdtSection<'_> {
92    type Error = crate::error::Error;
93
94    fn serialized_len(&self) -> usize {
95        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.descriptors.len() + CRC_LEN
96    }
97
98    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
99        let len = self.serialized_len();
100        if buf.len() < len {
101            return Err(Error::OutputBufferTooSmall {
102                need: len,
103                have: buf.len(),
104            });
105        }
106
107        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
108        buf[0] = TABLE_ID;
109        buf[1] = super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F);
110        buf[2] = (section_length & 0xFF) as u8;
111        buf[3..5].copy_from_slice(&self.table_id_extension.to_be_bytes());
112        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
113        buf[6] = self.section_number;
114        buf[7] = self.last_section_number;
115
116        let desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
117        buf[desc_start..desc_start + self.descriptors.len()]
118            .copy_from_slice(self.descriptors.raw());
119
120        let crc_pos = len - CRC_LEN;
121        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
122        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
123
124        Ok(len)
125    }
126}
127impl<'a> crate::traits::TableDef<'a> for TsdtSection<'a> {
128    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
129    const NAME: &'static str = "TRANSPORT_STREAM_DESCRIPTION";
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    fn build_tsdt(table_id_extension: u16, version: u8, descriptors: &[u8]) -> Vec<u8> {
137        let section_length: u16 = (EXTENSION_HEADER_LEN + descriptors.len() + CRC_LEN) as u16;
138        let mut v = Vec::new();
139        v.push(TABLE_ID);
140        v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
141        v.push((section_length & 0xFF) as u8);
142        v.extend_from_slice(&table_id_extension.to_be_bytes());
143        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
144        v.push(0x00);
145        v.push(0x00);
146        v.extend_from_slice(descriptors);
147        v.extend_from_slice(&[0, 0, 0, 0]);
148        v
149    }
150
151    #[test]
152    fn parse_rejects_wrong_tag() {
153        let mut bytes = build_tsdt(0x1234, 5, &[]);
154        bytes[0] = 0x02;
155        assert!(matches!(
156            TsdtSection::parse(&bytes).unwrap_err(),
157            Error::UnexpectedTableId { table_id: 0x02, .. }
158        ));
159    }
160
161    #[test]
162    fn parse_rejects_short_buffer() {
163        let err = TsdtSection::parse(&[0x03, 0xB0]).unwrap_err();
164        assert!(matches!(err, Error::BufferTooShort { .. }));
165    }
166
167    #[test]
168    fn parse_empty_descriptor_loop() {
169        let bytes = build_tsdt(0x1234, 5, &[]);
170        let tsdt = TsdtSection::parse(&bytes).unwrap();
171        assert_eq!(tsdt.table_id_extension, 0x1234);
172        assert_eq!(tsdt.version_number, 5);
173        assert!(tsdt.current_next_indicator);
174        assert_eq!(tsdt.section_number, 0);
175        assert_eq!(tsdt.last_section_number, 0);
176        assert!(tsdt.descriptors.is_empty());
177    }
178
179    #[test]
180    fn parse_with_descriptors() {
181        let descriptors = [0x01, 0x03, 0xAA, 0xBB, 0xCC];
182        let bytes = build_tsdt(0xABCD, 7, &descriptors);
183        let tsdt = TsdtSection::parse(&bytes).unwrap();
184        assert_eq!(tsdt.table_id_extension, 0xABCD);
185        assert_eq!(tsdt.version_number, 7);
186        assert_eq!(tsdt.descriptors.raw(), &descriptors[..]);
187    }
188
189    #[test]
190    fn serialize_round_trip() {
191        let descriptors = [0x4D, 0x02, 0x01, 0x02];
192        let bytes = build_tsdt(0xCAFE, 3, &descriptors);
193        let tsdt = TsdtSection::parse(&bytes).unwrap();
194        let mut buf = vec![0u8; tsdt.serialized_len()];
195        tsdt.serialize_into(&mut buf).unwrap();
196        let re = TsdtSection::parse(&buf).unwrap();
197        assert_eq!(tsdt, re);
198    }
199
200    #[test]
201    fn serialize_round_trip_empty() {
202        let bytes = build_tsdt(0x0001, 0, &[]);
203        let tsdt = TsdtSection::parse(&bytes).unwrap();
204        let mut buf = vec![0u8; tsdt.serialized_len()];
205        tsdt.serialize_into(&mut buf).unwrap();
206        let re = TsdtSection::parse(&buf).unwrap();
207        assert_eq!(tsdt, re);
208    }
209
210    #[test]
211    fn table_trait_constants() {
212        assert_eq!(TABLE_ID, 0x03);
213        assert_eq!(PID, 0x0002);
214    }
215
216    #[cfg(feature = "serde")]
217    #[test]
218    fn tsdt_serializes_typed_loop() {
219        // TSDT now borrows its descriptor loop (3.0): serialize-only, the loop
220        // emits the typed descriptor sequence (here a short_event, tag 0x4D).
221        let descriptors = [0x4D, 0x02, b'e', b'n']; // valid short_event header bytes
222        let bytes = build_tsdt(0xDEAD, 9, &descriptors);
223        let tsdt = TsdtSection::parse(&bytes).unwrap();
224        let v = serde_json::to_value(&tsdt).unwrap();
225        assert!(
226            v["descriptors"].is_array(),
227            "descriptors must serialize as a typed sequence, got {v}"
228        );
229    }
230
231    #[test]
232    fn parse_rejects_zero_section_length() {
233        let mut buf = vec![0u8; 64];
234        buf[0] = TABLE_ID;
235        buf[1] = 0xF0;
236        buf[2] = 0x00;
237        for b in &mut buf[3..] {
238            *b = 0xFF;
239        }
240        assert!(matches!(
241            TsdtSection::parse(&buf).unwrap_err(),
242            Error::SectionLengthOverflow { .. }
243        ));
244    }
245}