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