Skip to main content

dvb_si/tables/
sit.rs

1//! Selection Information Table — ETSI EN 300 468 §7.1.2.
2//!
3//! Carried on PID 0x001F with table_id 0x7F, only in partial transport streams
4//! (e.g. a recording). After the section header it has two loops:
5//!   1. `transmission_info_descriptors` — descriptors describing the whole
6//!      partial stream, prefixed by a 12-bit length;
7//!   2. a per-service loop: `service_id(16) + reserved(1) + running_status(3) +
8//!      service_descriptors_length(12) + descriptors`.
9//!
10//! Both loops are exposed as raw bytes for the caller to walk with the
11//! descriptor parsers.
12
13use crate::descriptors::DescriptorLoop;
14use crate::error::{Error, Result};
15use crate::traits::Table;
16use dvb_common::{Parse, Serialize};
17
18/// table_id for the Selection Information Table.
19pub const TABLE_ID: u8 = 0x7F;
20/// Well-known PID on which the SIT is carried.
21pub const PID: u16 = 0x001F;
22
23const MIN_HEADER_LEN: usize = 3;
24const EXTENSION_HEADER_LEN: usize = 5;
25const DESC_LOOP_LEN_FIELD: usize = 2;
26const CRC_LEN: usize = 4;
27
28/// Selection Information Table (§7.1.2, Table 164).
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize))]
31pub struct Sit<'a> {
32    /// 16-bit field after section_length — reserved_future_use for the SIT
33    /// (conventionally 0xFFFF); retained verbatim.
34    pub table_id_extension: u16,
35    /// 5-bit version_number.
36    pub version_number: u8,
37    /// current_next_indicator bit.
38    pub current_next_indicator: bool,
39    /// section_number in the sub-table sequence.
40    pub section_number: u8,
41    /// last_section_number in the sub-table sequence.
42    pub last_section_number: u8,
43    /// Transmission-info descriptor loop (the first loop). Serializes as the
44    /// typed descriptor sequence; `.raw()` yields the wire bytes.
45    pub transmission_info_descriptors: DescriptorLoop<'a>,
46    /// Per-service loop bytes (service_id + running_status + descriptors), raw.
47    /// Not a flat descriptor loop, so kept as raw bytes.
48    pub service_loop: &'a [u8],
49}
50
51impl<'a> Parse<'a> for Sit<'a> {
52    type Error = crate::error::Error;
53
54    fn parse(bytes: &'a [u8]) -> Result<Self> {
55        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;
56        if bytes.len() < min_len {
57            return Err(Error::BufferTooShort {
58                need: min_len,
59                have: bytes.len(),
60                what: "Sit",
61            });
62        }
63        if bytes[0] != TABLE_ID {
64            return Err(Error::UnexpectedTableId {
65                table_id: bytes[0],
66                what: "Sit",
67                expected: &[TABLE_ID],
68            });
69        }
70        let section_length = ((bytes[1] & 0x0F) as usize) << 8 | bytes[2] as usize;
71        let total = MIN_HEADER_LEN + section_length;
72        if bytes.len() < total {
73            return Err(Error::SectionLengthOverflow {
74                declared: section_length,
75                available: bytes.len() - MIN_HEADER_LEN,
76            });
77        }
78
79        let table_id_extension = u16::from_be_bytes([bytes[3], bytes[4]]);
80        let version_number = (bytes[5] >> 1) & 0x1F;
81        let current_next_indicator = (bytes[5] & 0x01) != 0;
82        let section_number = bytes[6];
83        let last_section_number = bytes[7];
84
85        let dl_pos = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
86        let ti_len = (((bytes[dl_pos] & 0x0F) as usize) << 8) | bytes[dl_pos + 1] as usize;
87        let ti_start = dl_pos + DESC_LOOP_LEN_FIELD;
88        let ti_end = ti_start + ti_len;
89        let crc_start = total - CRC_LEN;
90        if ti_end > crc_start {
91            return Err(Error::SectionLengthOverflow {
92                declared: ti_len,
93                available: crc_start.saturating_sub(ti_start),
94            });
95        }
96
97        Ok(Sit {
98            table_id_extension,
99            version_number,
100            current_next_indicator,
101            section_number,
102            last_section_number,
103            transmission_info_descriptors: DescriptorLoop::new(&bytes[ti_start..ti_end]),
104            // Everything between the transmission-info loop and the CRC is the
105            // per-service loop, kept raw.
106            service_loop: &bytes[ti_end..crc_start],
107        })
108    }
109}
110
111impl Serialize for Sit<'_> {
112    type Error = crate::error::Error;
113
114    fn serialized_len(&self) -> usize {
115        MIN_HEADER_LEN
116            + EXTENSION_HEADER_LEN
117            + DESC_LOOP_LEN_FIELD
118            + self.transmission_info_descriptors.len()
119            + self.service_loop.len()
120            + CRC_LEN
121    }
122
123    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
124        let len = self.serialized_len();
125        if buf.len() < len {
126            return Err(Error::OutputBufferTooSmall {
127                need: len,
128                have: buf.len(),
129            });
130        }
131        let section_length = (len - MIN_HEADER_LEN) as u16;
132        buf[0] = TABLE_ID;
133        buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
134        buf[2] = (section_length & 0xFF) as u8;
135        buf[3..5].copy_from_slice(&self.table_id_extension.to_be_bytes());
136        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
137        buf[6] = self.section_number;
138        buf[7] = self.last_section_number;
139
140        let dl_pos = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
141        let ti_len = self.transmission_info_descriptors.len() as u16;
142        buf[dl_pos] = 0xF0 | ((ti_len >> 8) as u8 & 0x0F);
143        buf[dl_pos + 1] = (ti_len & 0xFF) as u8;
144        let ti_start = dl_pos + DESC_LOOP_LEN_FIELD;
145        let ti_end = ti_start + self.transmission_info_descriptors.len();
146        buf[ti_start..ti_end].copy_from_slice(self.transmission_info_descriptors.raw());
147        let sl_end = ti_end + self.service_loop.len();
148        buf[ti_end..sl_end].copy_from_slice(self.service_loop);
149
150        let crc_pos = len - CRC_LEN;
151        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
152        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
153        Ok(len)
154    }
155}
156
157impl<'a> Table<'a> for Sit<'a> {
158    const TABLE_ID: u8 = TABLE_ID;
159    const PID: u16 = PID;
160}
161
162impl<'a> crate::traits::TableDef<'a> for Sit<'a> {
163    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
164    const NAME: &'static str = "SELECTION_INFORMATION";
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    fn build_sit(
172        table_id_extension: u16,
173        version: u8,
174        ti_desc: &[u8],
175        service_loop: &[u8],
176    ) -> Vec<u8> {
177        let section_length = (EXTENSION_HEADER_LEN
178            + DESC_LOOP_LEN_FIELD
179            + ti_desc.len()
180            + service_loop.len()
181            + CRC_LEN) as u16;
182        let mut v = vec![
183            TABLE_ID,
184            0xB0 | ((section_length >> 8) as u8 & 0x0F),
185            (section_length & 0xFF) as u8,
186        ];
187        v.extend_from_slice(&table_id_extension.to_be_bytes());
188        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
189        v.push(0x00);
190        v.push(0x00);
191        let dl = ti_desc.len() as u16;
192        v.push(0xF0 | ((dl >> 8) as u8 & 0x0F));
193        v.push((dl & 0xFF) as u8);
194        v.extend_from_slice(ti_desc);
195        v.extend_from_slice(service_loop);
196        v.extend_from_slice(&[0, 0, 0, 0]);
197        v
198    }
199
200    #[test]
201    fn parse_rejects_wrong_tag() {
202        let mut bytes = build_sit(0x1234, 5, &[], &[]);
203        bytes[0] = 0x7E;
204        assert!(matches!(
205            Sit::parse(&bytes).unwrap_err(),
206            Error::UnexpectedTableId { table_id: 0x7E, .. }
207        ));
208    }
209
210    #[test]
211    fn parse_rejects_short_buffer() {
212        assert!(matches!(
213            Sit::parse(&[0x7F, 0xB0]).unwrap_err(),
214            Error::BufferTooShort { .. }
215        ));
216    }
217
218    #[test]
219    fn parse_empty() {
220        let bytes = build_sit(0x1234, 5, &[], &[]);
221        let sit = Sit::parse(&bytes).unwrap();
222        assert_eq!(sit.table_id_extension, 0x1234);
223        assert_eq!(sit.version_number, 5);
224        assert!(sit.current_next_indicator);
225        assert!(sit.transmission_info_descriptors.is_empty());
226        assert!(sit.service_loop.is_empty());
227    }
228
229    #[test]
230    fn parse_separates_both_loops() {
231        let ti = [0x4D, 0x02, 0x01, 0x02]; // a transmission-info descriptor
232                                           // one service entry: service_id=0x0001, running_status=4, svc_desc_len=0
233        let service = [0x00, 0x01, 0x80 | (4 << 4), 0x00];
234        let bytes = build_sit(0xABCD, 7, &ti, &service);
235        let sit = Sit::parse(&bytes).unwrap();
236        assert_eq!(sit.transmission_info_descriptors.raw(), &ti[..]);
237        assert_eq!(sit.service_loop, &service[..]);
238    }
239
240    #[test]
241    fn serialize_round_trip() {
242        let ti = [0x4D, 0x02, 0x01, 0x02];
243        let service = [0x00, 0x01, 0xC0, 0x00];
244        let bytes = build_sit(0xCAFE, 3, &ti, &service);
245        let sit = Sit::parse(&bytes).unwrap();
246        let mut buf = vec![0u8; sit.serialized_len()];
247        sit.serialize_into(&mut buf).unwrap();
248        assert_eq!(Sit::parse(&buf).unwrap(), sit);
249    }
250
251    #[test]
252    fn serialize_round_trip_empty() {
253        let bytes = build_sit(0x0001, 0, &[], &[]);
254        let sit = Sit::parse(&bytes).unwrap();
255        let mut buf = vec![0u8; sit.serialized_len()];
256        sit.serialize_into(&mut buf).unwrap();
257        assert_eq!(Sit::parse(&buf).unwrap(), sit);
258    }
259
260    #[test]
261    fn table_trait_constants() {
262        assert_eq!(<Sit<'_> as Table>::TABLE_ID, 0x7F);
263        assert_eq!(<Sit<'_> as Table>::PID, 0x001F);
264    }
265
266    #[cfg(feature = "serde")]
267    #[test]
268    fn sit_serializes_typed_loop() {
269        // SIT now borrows both loops (3.0): serialize-only. The
270        // transmission_info loop serializes as the typed descriptor sequence.
271        let bytes = build_sit(0xDEAD, 9, &[0x4D, 0x00], &[0x00, 0x01, 0xC0, 0x00]);
272        let sit = Sit::parse(&bytes).unwrap();
273        let v = serde_json::to_value(&sit).unwrap();
274        assert!(
275            v["transmission_info_descriptors"].is_array(),
276            "transmission_info_descriptors must serialize as a typed sequence, got {v}"
277        );
278    }
279}