Skip to main content

dvb_si/tables/
sdt.rs

1//! Service Description Table — ETSI EN 300 468 §5.2.3.
2//!
3//! SDT lists the services available in a transport stream, with a
4//! descriptor loop per service (service_descriptor etc.). The table is
5//! split into two variants by table_id: `0x42` for the actual TS the
6//! receiver is tuned to, `0x46` for services on other TSes.
7
8use crate::error::{Error, Result};
9use crate::traits::Table;
10use dvb_common::{Parse, Serialize};
11
12/// table_id value for SDT describing services on the actual TS.
13pub const TABLE_ID_ACTUAL: u8 = 0x42;
14/// table_id value for SDT describing services on other TSes.
15pub const TABLE_ID_OTHER: u8 = 0x46;
16/// Well-known PID on which SDT is carried.
17pub const PID: u16 = 0x0011;
18
19const MIN_HEADER_LEN: usize = 3;
20const EXTENSION_HEADER_LEN: usize = 5;
21/// Bytes after the extension header and before the first service entry:
22/// 2 bytes of original_network_id + 1 reserved_future_use byte.
23const POST_EXTENSION_LEN: usize = 3;
24const CRC_LEN: usize = 4;
25const SERVICE_HEADER_LEN: usize = 5;
26
27/// SDT kind — distinguishes `0x42` (actual) from `0x46` (other).
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub enum SdtKind {
31    /// Services on the transport stream the receiver is tuned to.
32    Actual,
33    /// Services on other transport streams (cross-TS SDT).
34    Other,
35}
36
37/// One service entry in an SDT.
38#[derive(Debug, Clone, PartialEq, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub struct SdtService<'a> {
41    /// service_id (matches `program_number` in the PAT).
42    pub service_id: u16,
43    /// EIT schedule flag — present-and-following events are in the EIT/schedule.
44    pub eit_schedule_flag: bool,
45    /// EIT P/F flag — present-and-following events are in the EIT present/following.
46    pub eit_present_following_flag: bool,
47    /// 3-bit running_status (0=undefined .. 4=running).
48    pub running_status: u8,
49    /// free_CA_mode: `true` = at least one elementary stream is scrambled.
50    pub free_ca_mode: bool,
51    /// Raw descriptor bytes for this service (descriptor parsing lives elsewhere).
52    #[cfg_attr(feature = "serde", serde(borrow))]
53    pub descriptors: &'a [u8],
54}
55
56/// Service Description Table.
57#[derive(Debug, Clone, PartialEq, Eq)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59pub struct Sdt<'a> {
60    /// Variant discriminator (table_id 0x42 vs 0x46).
61    pub kind: SdtKind,
62    /// transport_stream_id of the described TS.
63    pub transport_stream_id: u16,
64    /// 5-bit version_number.
65    pub version_number: u8,
66    /// current_next_indicator bit.
67    pub current_next_indicator: bool,
68    /// section_number in the sub-table sequence.
69    pub section_number: u8,
70    /// last_section_number in the sub-table sequence.
71    pub last_section_number: u8,
72    /// original_network_id of the described TS.
73    pub original_network_id: u16,
74    /// Services in wire order.
75    #[cfg_attr(feature = "serde", serde(borrow))]
76    pub services: Vec<SdtService<'a>>,
77}
78
79impl<'a> Parse<'a> for Sdt<'a> {
80    type Error = crate::error::Error;
81    fn parse(bytes: &'a [u8]) -> Result<Self> {
82        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
83        if bytes.len() < min_len {
84            return Err(Error::BufferTooShort {
85                need: min_len,
86                have: bytes.len(),
87                what: "Sdt",
88            });
89        }
90        let kind = match bytes[0] {
91            TABLE_ID_ACTUAL => SdtKind::Actual,
92            TABLE_ID_OTHER => SdtKind::Other,
93            other => {
94                return Err(Error::UnexpectedTableId {
95                    table_id: other,
96                    what: "Sdt",
97                    expected: &[TABLE_ID_ACTUAL, TABLE_ID_OTHER],
98                });
99            }
100        };
101
102        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
103        let total = MIN_HEADER_LEN + section_length as usize;
104        if bytes.len() < total {
105            return Err(Error::SectionLengthOverflow {
106                declared: section_length as usize,
107                available: bytes.len() - MIN_HEADER_LEN,
108            });
109        }
110
111        let transport_stream_id = u16::from_be_bytes([bytes[3], bytes[4]]);
112        let version_number = (bytes[5] >> 1) & 0x1F;
113        let current_next_indicator = (bytes[5] & 0x01) != 0;
114        let section_number = bytes[6];
115        let last_section_number = bytes[7];
116        let original_network_id = u16::from_be_bytes([bytes[8], bytes[9]]);
117
118        let services_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
119        let services_end = total - CRC_LEN;
120        let mut services = Vec::new();
121        let mut pos = services_start;
122        while pos + SERVICE_HEADER_LEN <= services_end {
123            let service_id = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
124            let flags = bytes[pos + 2];
125            let eit_schedule_flag = (flags & 0x02) != 0;
126            let eit_present_following_flag = (flags & 0x01) != 0;
127            let status_and_len_hi = bytes[pos + 3];
128            let running_status = (status_and_len_hi >> 5) & 0x07;
129            let free_ca_mode = (status_and_len_hi & 0x10) != 0;
130            let descriptors_loop_length =
131                (((status_and_len_hi & 0x0F) as usize) << 8) | bytes[pos + 4] as usize;
132            let desc_start = pos + SERVICE_HEADER_LEN;
133            let desc_end = desc_start + descriptors_loop_length;
134            if desc_end > services_end {
135                return Err(Error::SectionLengthOverflow {
136                    declared: descriptors_loop_length,
137                    available: services_end - desc_start,
138                });
139            }
140            services.push(SdtService {
141                service_id,
142                eit_schedule_flag,
143                eit_present_following_flag,
144                running_status,
145                free_ca_mode,
146                descriptors: &bytes[desc_start..desc_end],
147            });
148            pos = desc_end;
149        }
150
151        Ok(Sdt {
152            kind,
153            transport_stream_id,
154            version_number,
155            current_next_indicator,
156            section_number,
157            last_section_number,
158            original_network_id,
159            services,
160        })
161    }
162}
163
164impl Serialize for Sdt<'_> {
165    type Error = crate::error::Error;
166    fn serialized_len(&self) -> usize {
167        let svc_bytes: usize = self
168            .services
169            .iter()
170            .map(|s| SERVICE_HEADER_LEN + s.descriptors.len())
171            .sum();
172        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + svc_bytes + CRC_LEN
173    }
174
175    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
176        let len = self.serialized_len();
177        if buf.len() < len {
178            return Err(Error::OutputBufferTooSmall {
179                need: len,
180                have: buf.len(),
181            });
182        }
183        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
184        buf[0] = match self.kind {
185            SdtKind::Actual => TABLE_ID_ACTUAL,
186            SdtKind::Other => TABLE_ID_OTHER,
187        };
188        buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
189        buf[2] = (section_length & 0xFF) as u8;
190        buf[3..5].copy_from_slice(&self.transport_stream_id.to_be_bytes());
191        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
192        buf[6] = self.section_number;
193        buf[7] = self.last_section_number;
194        buf[8..10].copy_from_slice(&self.original_network_id.to_be_bytes());
195        buf[10] = 0xFF; // reserved_future_use
196
197        let mut pos = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
198        for svc in &self.services {
199            buf[pos..pos + 2].copy_from_slice(&svc.service_id.to_be_bytes());
200            let flags = 0xFC
201                | (u8::from(svc.eit_schedule_flag) << 1)
202                | u8::from(svc.eit_present_following_flag);
203            buf[pos + 2] = flags;
204            let dll = svc.descriptors.len() as u16;
205            buf[pos + 3] = ((svc.running_status & 0x07) << 5)
206                | (u8::from(svc.free_ca_mode) << 4)
207                | ((dll >> 8) as u8 & 0x0F);
208            buf[pos + 4] = (dll & 0xFF) as u8;
209            let desc_start = pos + SERVICE_HEADER_LEN;
210            buf[desc_start..desc_start + svc.descriptors.len()].copy_from_slice(svc.descriptors);
211            pos = desc_start + svc.descriptors.len();
212        }
213
214        let crc_pos = len - CRC_LEN;
215        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
216        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
217        Ok(len)
218    }
219}
220
221impl<'a> Table<'a> for Sdt<'a> {
222    const TABLE_ID: u8 = TABLE_ID_ACTUAL;
223    const PID: u16 = PID;
224}
225
226impl<'a> crate::traits::TableDef<'a> for Sdt<'a> {
227    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[
228        (TABLE_ID_ACTUAL, TABLE_ID_ACTUAL),
229        (TABLE_ID_OTHER, TABLE_ID_OTHER),
230    ];
231    const NAME: &'static str = "SERVICE_DESCRIPTION";
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    type TestService = (u16, bool, bool, u8, bool, Vec<u8>);
239
240    fn build_sdt(
241        kind: SdtKind,
242        tsid: u16,
243        version: u8,
244        original_network_id: u16,
245        services: &[TestService],
246    ) -> Vec<u8> {
247        let svc_bytes: usize = services
248            .iter()
249            .map(|(_, _, _, _, _, d)| SERVICE_HEADER_LEN + d.len())
250            .sum();
251        let section_length: u16 =
252            (EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + svc_bytes + CRC_LEN) as u16;
253        let mut v = Vec::new();
254        v.push(match kind {
255            SdtKind::Actual => TABLE_ID_ACTUAL,
256            SdtKind::Other => TABLE_ID_OTHER,
257        });
258        v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
259        v.push((section_length & 0xFF) as u8);
260        v.extend_from_slice(&tsid.to_be_bytes());
261        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
262        v.push(0);
263        v.push(0);
264        v.extend_from_slice(&original_network_id.to_be_bytes());
265        v.push(0xFF);
266        for (sid, eit_s, eit_pf, rs, fca, desc) in services {
267            v.extend_from_slice(&sid.to_be_bytes());
268            let flags = 0xFC | (u8::from(*eit_s) << 1) | u8::from(*eit_pf);
269            v.push(flags);
270            let dll = desc.len() as u16;
271            v.push(((*rs & 0x07) << 5) | (u8::from(*fca) << 4) | ((dll >> 8) as u8 & 0x0F));
272            v.push((dll & 0xFF) as u8);
273            v.extend_from_slice(desc);
274        }
275        v.extend_from_slice(&[0, 0, 0, 0]);
276        v
277    }
278
279    #[test]
280    fn parse_actual_and_other_tables_distinguished_by_table_id() {
281        let a = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
282        let o = build_sdt(SdtKind::Other, 1, 0, 0x20, &[]);
283        assert!(matches!(Sdt::parse(&a).unwrap().kind, SdtKind::Actual));
284        assert!(matches!(Sdt::parse(&o).unwrap().kind, SdtKind::Other));
285    }
286
287    #[test]
288    fn parse_services_with_descriptor_bytes() {
289        let bytes = build_sdt(
290            SdtKind::Actual,
291            1,
292            0,
293            0x20,
294            &[(
295                100,
296                true,
297                true,
298                4,
299                false,
300                vec![0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05],
301            )],
302        );
303        let sdt = Sdt::parse(&bytes).unwrap();
304        assert_eq!(sdt.services.len(), 1);
305        assert_eq!(sdt.services[0].service_id, 100);
306        assert!(sdt.services[0].eit_schedule_flag);
307        assert!(sdt.services[0].eit_present_following_flag);
308        assert_eq!(sdt.services[0].running_status, 4);
309        assert!(!sdt.services[0].free_ca_mode);
310        assert_eq!(
311            sdt.services[0].descriptors,
312            &[0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05][..]
313        );
314    }
315
316    #[test]
317    fn service_free_ca_mode_flag_extracted() {
318        let bytes = build_sdt(
319            SdtKind::Actual,
320            1,
321            0,
322            0x20,
323            &[(1, false, false, 0, true, vec![])],
324        );
325        let sdt = Sdt::parse(&bytes).unwrap();
326        assert!(sdt.services[0].free_ca_mode);
327    }
328
329    #[test]
330    fn service_running_status_extracted() {
331        let bytes = build_sdt(
332            SdtKind::Actual,
333            1,
334            0,
335            0x20,
336            &[(1, false, false, 2, false, vec![])],
337        );
338        let sdt = Sdt::parse(&bytes).unwrap();
339        assert_eq!(sdt.services[0].running_status, 2);
340    }
341
342    #[test]
343    fn parse_rejects_short_buffer() {
344        let err = Sdt::parse(&[0x42, 0x00]).unwrap_err();
345        assert!(matches!(err, Error::BufferTooShort { .. }));
346    }
347
348    #[test]
349    fn parse_rejects_wrong_table_id() {
350        let mut bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
351        bytes[0] = 0x00;
352        let err = Sdt::parse(&bytes).unwrap_err();
353        assert!(matches!(
354            err,
355            Error::UnexpectedTableId { table_id: 0x00, .. }
356        ));
357    }
358
359    #[test]
360    fn serialize_round_trip() {
361        let desc1: [u8; 4] = [0x48, 0x02, 0xAA, 0xBB];
362        let sdt = Sdt {
363            kind: SdtKind::Actual,
364            transport_stream_id: 0x1234,
365            version_number: 5,
366            current_next_indicator: true,
367            section_number: 0,
368            last_section_number: 0,
369            original_network_id: 0x0020,
370            services: vec![
371                SdtService {
372                    service_id: 100,
373                    eit_schedule_flag: true,
374                    eit_present_following_flag: false,
375                    running_status: 4,
376                    free_ca_mode: false,
377                    descriptors: &desc1,
378                },
379                SdtService {
380                    service_id: 101,
381                    eit_schedule_flag: false,
382                    eit_present_following_flag: true,
383                    running_status: 2,
384                    free_ca_mode: true,
385                    descriptors: &[],
386                },
387            ],
388        };
389        let mut buf = vec![0u8; sdt.serialized_len()];
390        sdt.serialize_into(&mut buf).unwrap();
391        let re = Sdt::parse(&buf).unwrap();
392        assert_eq!(sdt, re);
393    }
394
395    #[test]
396    fn zero_services_is_valid() {
397        let bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
398        let sdt = Sdt::parse(&bytes).unwrap();
399        assert_eq!(sdt.services.len(), 0);
400    }
401}