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