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::descriptors::DescriptorLoop;
9use crate::error::{Error, Result};
10use crate::traits::Table;
11use dvb_common::{Parse, Serialize};
12
13/// table_id value for SDT describing services on the actual TS.
14pub const TABLE_ID_ACTUAL: u8 = 0x42;
15/// table_id value for SDT describing services on other TSes.
16pub const TABLE_ID_OTHER: u8 = 0x46;
17/// Well-known PID on which SDT is carried.
18pub const PID: u16 = 0x0011;
19
20const MIN_HEADER_LEN: usize = 3;
21const EXTENSION_HEADER_LEN: usize = 5;
22/// Bytes after the extension header and before the first service entry:
23/// 2 bytes of original_network_id + 1 reserved_future_use byte.
24const POST_EXTENSION_LEN: usize = 3;
25const CRC_LEN: usize = 4;
26const SERVICE_HEADER_LEN: usize = 5;
27
28/// SDT kind — distinguishes `0x42` (actual) from `0x46` (other).
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize))]
31pub enum SdtKind {
32    /// Services on the transport stream the receiver is tuned to.
33    Actual,
34    /// Services on other transport streams (cross-TS SDT).
35    Other,
36}
37
38/// One service entry in an SDT.
39#[derive(Debug, Clone, PartialEq, Eq)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize))]
41pub struct SdtService<'a> {
42    /// service_id (matches `program_number` in the PAT).
43    pub service_id: u16,
44    /// EIT schedule flag — present-and-following events are in the EIT/schedule.
45    pub eit_schedule_flag: bool,
46    /// EIT P/F flag — present-and-following events are in the EIT present/following.
47    pub eit_present_following_flag: bool,
48    /// 3-bit running_status (0=undefined .. 4=running).
49    pub running_status: u8,
50    /// free_CA_mode: `true` = at least one elementary stream is scrambled.
51    pub free_ca_mode: bool,
52    /// Descriptor loop for this service (service_descriptor etc.). Serializes
53    /// as the typed descriptor sequence; `.raw()` yields the wire bytes.
54    pub descriptors: DescriptorLoop<'a>,
55}
56
57/// Service Description Table.
58#[derive(Debug, Clone, PartialEq, Eq)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize))]
60pub struct Sdt<'a> {
61    /// Variant discriminator (table_id 0x42 vs 0x46).
62    pub kind: SdtKind,
63    /// transport_stream_id of the described TS.
64    pub transport_stream_id: u16,
65    /// 5-bit version_number.
66    pub version_number: u8,
67    /// current_next_indicator bit.
68    pub current_next_indicator: bool,
69    /// section_number in the sub-table sequence.
70    pub section_number: u8,
71    /// last_section_number in the sub-table sequence.
72    pub last_section_number: u8,
73    /// original_network_id of the described TS.
74    pub original_network_id: u16,
75    /// Services in wire order.
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: DescriptorLoop::new(&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()]
211                .copy_from_slice(svc.descriptors.raw());
212            pos = desc_start + svc.descriptors.len();
213        }
214
215        let crc_pos = len - CRC_LEN;
216        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
217        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
218        Ok(len)
219    }
220}
221
222impl<'a> Table<'a> for Sdt<'a> {
223    const TABLE_ID: u8 = TABLE_ID_ACTUAL;
224    const PID: u16 = PID;
225}
226
227impl<'a> crate::traits::TableDef<'a> for Sdt<'a> {
228    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[
229        (TABLE_ID_ACTUAL, TABLE_ID_ACTUAL),
230        (TABLE_ID_OTHER, TABLE_ID_OTHER),
231    ];
232    const NAME: &'static str = "SERVICE_DESCRIPTION";
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    type TestService = (u16, bool, bool, u8, bool, Vec<u8>);
240
241    fn build_sdt(
242        kind: SdtKind,
243        tsid: u16,
244        version: u8,
245        original_network_id: u16,
246        services: &[TestService],
247    ) -> Vec<u8> {
248        let svc_bytes: usize = services
249            .iter()
250            .map(|(_, _, _, _, _, d)| SERVICE_HEADER_LEN + d.len())
251            .sum();
252        let section_length: u16 =
253            (EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + svc_bytes + CRC_LEN) as u16;
254        let mut v = Vec::new();
255        v.push(match kind {
256            SdtKind::Actual => TABLE_ID_ACTUAL,
257            SdtKind::Other => TABLE_ID_OTHER,
258        });
259        v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
260        v.push((section_length & 0xFF) as u8);
261        v.extend_from_slice(&tsid.to_be_bytes());
262        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
263        v.push(0);
264        v.push(0);
265        v.extend_from_slice(&original_network_id.to_be_bytes());
266        v.push(0xFF);
267        for (sid, eit_s, eit_pf, rs, fca, desc) in services {
268            v.extend_from_slice(&sid.to_be_bytes());
269            let flags = 0xFC | (u8::from(*eit_s) << 1) | u8::from(*eit_pf);
270            v.push(flags);
271            let dll = desc.len() as u16;
272            v.push(((*rs & 0x07) << 5) | (u8::from(*fca) << 4) | ((dll >> 8) as u8 & 0x0F));
273            v.push((dll & 0xFF) as u8);
274            v.extend_from_slice(desc);
275        }
276        v.extend_from_slice(&[0, 0, 0, 0]);
277        v
278    }
279
280    #[test]
281    fn parse_actual_and_other_tables_distinguished_by_table_id() {
282        let a = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
283        let o = build_sdt(SdtKind::Other, 1, 0, 0x20, &[]);
284        assert!(matches!(Sdt::parse(&a).unwrap().kind, SdtKind::Actual));
285        assert!(matches!(Sdt::parse(&o).unwrap().kind, SdtKind::Other));
286    }
287
288    #[test]
289    fn parse_services_with_descriptor_bytes() {
290        let bytes = build_sdt(
291            SdtKind::Actual,
292            1,
293            0,
294            0x20,
295            &[(
296                100,
297                true,
298                true,
299                4,
300                false,
301                vec![0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05],
302            )],
303        );
304        let sdt = Sdt::parse(&bytes).unwrap();
305        assert_eq!(sdt.services.len(), 1);
306        assert_eq!(sdt.services[0].service_id, 100);
307        assert!(sdt.services[0].eit_schedule_flag);
308        assert!(sdt.services[0].eit_present_following_flag);
309        assert_eq!(sdt.services[0].running_status, 4);
310        assert!(!sdt.services[0].free_ca_mode);
311        assert_eq!(
312            sdt.services[0].descriptors.raw(),
313            &[0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05][..]
314        );
315    }
316
317    #[test]
318    fn service_free_ca_mode_flag_extracted() {
319        let bytes = build_sdt(
320            SdtKind::Actual,
321            1,
322            0,
323            0x20,
324            &[(1, false, false, 0, true, vec![])],
325        );
326        let sdt = Sdt::parse(&bytes).unwrap();
327        assert!(sdt.services[0].free_ca_mode);
328    }
329
330    #[test]
331    fn service_running_status_extracted() {
332        let bytes = build_sdt(
333            SdtKind::Actual,
334            1,
335            0,
336            0x20,
337            &[(1, false, false, 2, false, vec![])],
338        );
339        let sdt = Sdt::parse(&bytes).unwrap();
340        assert_eq!(sdt.services[0].running_status, 2);
341    }
342
343    #[test]
344    fn parse_rejects_short_buffer() {
345        let err = Sdt::parse(&[0x42, 0x00]).unwrap_err();
346        assert!(matches!(err, Error::BufferTooShort { .. }));
347    }
348
349    #[test]
350    fn parse_rejects_wrong_table_id() {
351        let mut bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
352        bytes[0] = 0x00;
353        let err = Sdt::parse(&bytes).unwrap_err();
354        assert!(matches!(
355            err,
356            Error::UnexpectedTableId { table_id: 0x00, .. }
357        ));
358    }
359
360    #[test]
361    fn serialize_round_trip() {
362        let desc1: [u8; 4] = [0x48, 0x02, 0xAA, 0xBB];
363        let sdt = Sdt {
364            kind: SdtKind::Actual,
365            transport_stream_id: 0x1234,
366            version_number: 5,
367            current_next_indicator: true,
368            section_number: 0,
369            last_section_number: 0,
370            original_network_id: 0x0020,
371            services: vec![
372                SdtService {
373                    service_id: 100,
374                    eit_schedule_flag: true,
375                    eit_present_following_flag: false,
376                    running_status: 4,
377                    free_ca_mode: false,
378                    descriptors: DescriptorLoop::new(&desc1),
379                },
380                SdtService {
381                    service_id: 101,
382                    eit_schedule_flag: false,
383                    eit_present_following_flag: true,
384                    running_status: 2,
385                    free_ca_mode: true,
386                    descriptors: DescriptorLoop::new(&[]),
387                },
388            ],
389        };
390        let mut buf = vec![0u8; sdt.serialized_len()];
391        sdt.serialize_into(&mut buf).unwrap();
392        let re = Sdt::parse(&buf).unwrap();
393        assert_eq!(sdt, re);
394    }
395
396    #[test]
397    fn zero_services_is_valid() {
398        let bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
399        let sdt = Sdt::parse(&bytes).unwrap();
400        assert_eq!(sdt.services.len(), 0);
401    }
402}