Skip to main content

dvb_si/tables/
nit.rs

1//! Network Information Table — ETSI EN 300 468 §5.2.1.
2//!
3//! NIT describes the transport streams belonging to a DVB network, with
4//! network-wide descriptors and per-transport-stream descriptors. The
5//! table is split into two variants by table_id: `0x40` for the actual
6//! TS the receiver is tuned to, `0x41` for other TSes in the same network.
7
8use crate::descriptors::DescriptorLoop;
9use crate::error::{Error, Result};
10use alloc::vec::Vec;
11use dvb_common::{Parse, Serialize};
12
13/// table_id value for NIT actual (current TS).
14pub const TABLE_ID_ACTUAL: u8 = 0x40;
15/// table_id value for NIT other (other TSes in the network).
16pub const TABLE_ID_OTHER: u8 = 0x41;
17/// Well-known PID on which NIT is carried.
18pub const PID: u16 = 0x0010;
19
20const MIN_HEADER_LEN: usize = 3;
21const EXTENSION_HEADER_LEN: usize = 5;
22/// Bytes after the extension header: reserved_future_use (4 bits) + network_descriptors_length (12 bits) = 2 bytes.
23/// (Previously incorrectly defined as 4 — the parser assumed `network_id`
24/// was duplicated *after* the extension header; spec says it lives IN
25/// the extension header at bytes 3-4 as `table_id_extension`.)
26const POST_EXTENSION_LEN: usize = 2;
27const CRC_LEN: usize = 4;
28const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
29/// Per-transport-stream header: ts_id (2) + original_network_id (2) + reserved_future_use (4 bits) + transport_descriptors_length (12 bits).
30const TS_HEADER_LEN: usize = 6;
31
32/// NIT kind — distinguishes `0x40` (actual) from `0x41` (other).
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize))]
35#[non_exhaustive]
36pub enum NitKind {
37    /// NIT for the transport stream the receiver is tuned to.
38    Actual,
39    /// NIT describing other transport streams in the same network.
40    Other,
41}
42
43/// One transport-stream entry inside the NIT transport_stream_loop.
44#[derive(Debug, Clone, PartialEq, Eq)]
45#[cfg_attr(feature = "serde", derive(serde::Serialize))]
46#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
47pub struct NitTransportStream<'a> {
48    /// transport_stream_id of the described TS.
49    pub transport_stream_id: u16,
50    /// original_network_id of the described TS.
51    pub original_network_id: u16,
52    /// Raw descriptor bytes for this transport stream.
53    /// Per-TS descriptor loop. Serializes as the typed descriptor sequence;
54    /// `.raw()` yields the wire bytes.
55    pub descriptors: DescriptorLoop<'a>,
56}
57
58/// Network Information 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 NitSection<'a> {
63    /// Variant discriminator (table_id 0x40 vs 0x41).
64    pub kind: NitKind,
65    /// Network identifier.
66    pub network_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    /// Raw network-wide descriptor bytes.
76    /// Network descriptor loop. Serializes as the typed descriptor sequence;
77    /// `.raw()` yields the wire bytes.
78    pub network_descriptors: DescriptorLoop<'a>,
79    /// Transport-stream loop entries in wire order.
80    pub transport_streams: Vec<NitTransportStream<'a>>,
81}
82
83impl<'a> Parse<'a> for NitSection<'a> {
84    type Error = crate::error::Error;
85    fn parse(bytes: &'a [u8]) -> Result<Self> {
86        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
87        if bytes.len() < min_len {
88            return Err(Error::BufferTooShort {
89                need: min_len,
90                have: bytes.len(),
91                what: "NitSection",
92            });
93        }
94        let kind = match bytes[0] {
95            TABLE_ID_ACTUAL => NitKind::Actual,
96            TABLE_ID_OTHER => NitKind::Other,
97            other => {
98                return Err(Error::UnexpectedTableId {
99                    table_id: other,
100                    what: "NitSection",
101                    expected: &[TABLE_ID_ACTUAL, TABLE_ID_OTHER],
102                });
103            }
104        };
105
106        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
107        let total = super::check_section_length(
108            bytes.len(),
109            MIN_HEADER_LEN,
110            section_length as usize,
111            MIN_SECTION_LEN,
112        )?;
113
114        // Extension header bytes [3..8] per ETSI EN 300 468 §5.2.1:
115        //   bytes[3..5] = table_id_extension = network_id (16 bits)
116        //   bytes[5]    = reserved(2) | version_number(5) | current_next_indicator(1)
117        //   bytes[6]    = section_number
118        //   bytes[7]    = last_section_number
119        let network_id = u16::from_be_bytes(*bytes[3..].first_chunk::<2>().unwrap());
120        let version_number = (bytes[5] >> 1) & 0x1F;
121        let current_next_indicator = (bytes[5] & 0x01) != 0;
122        let section_number = bytes[6];
123        let last_section_number = bytes[7];
124
125        // bytes[8..10] = reserved(4) | network_descriptors_length(12)
126        let network_descriptors_length = (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
127
128        let network_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
129        let network_desc_end = network_desc_start + network_descriptors_length;
130
131        // Verify network descriptors don't overflow
132        if network_desc_end > total - CRC_LEN {
133            return Err(Error::SectionLengthOverflow {
134                declared: network_descriptors_length,
135                available: (total - CRC_LEN).saturating_sub(network_desc_start),
136            });
137        }
138
139        let network_descriptors = DescriptorLoop::new(&bytes[network_desc_start..network_desc_end]);
140
141        // Parse transport stream loop starting after network descriptors
142        let ts_loop_start = network_desc_end;
143        let ts_loop_end = total - CRC_LEN;
144
145        // First 2 bytes of the loop are: reserved_future_use (4 bits) + transport_stream_loop_length (12 bits)
146        if ts_loop_end - ts_loop_start < 2 {
147            return Err(Error::BufferTooShort {
148                need: ts_loop_end - ts_loop_start + 2,
149                have: ts_loop_end - ts_loop_start,
150                what: "NitSection transport_stream_loop",
151            });
152        }
153
154        let transport_stream_loop_length =
155            (((bytes[ts_loop_start] & 0x0F) as usize) << 8) | bytes[ts_loop_start + 1] as usize;
156
157        let mut pos = ts_loop_start + 2;
158        let loop_end = ts_loop_start + 2 + transport_stream_loop_length;
159
160        if loop_end > ts_loop_end {
161            return Err(Error::SectionLengthOverflow {
162                declared: transport_stream_loop_length,
163                available: ts_loop_end - (ts_loop_start + 2),
164            });
165        }
166
167        let mut transport_streams = Vec::new();
168
169        while pos < loop_end {
170            if pos + TS_HEADER_LEN > loop_end {
171                return Err(Error::BufferTooShort {
172                    need: pos + TS_HEADER_LEN,
173                    have: loop_end,
174                    what: "NitSection transport_stream_entry",
175                });
176            }
177
178            let hdr = &bytes[pos..pos + TS_HEADER_LEN];
179            let transport_stream_id = u16::from_be_bytes(*hdr[0..].first_chunk::<2>().unwrap());
180            let original_network_id = u16::from_be_bytes(*hdr[2..].first_chunk::<2>().unwrap());
181
182            // transport_descriptors_length is 12 bits: high 4 bits reserved, low 12 bits length
183            let transport_descriptors_length =
184                (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
185
186            let desc_start = pos + TS_HEADER_LEN;
187            let desc_end = desc_start + transport_descriptors_length;
188
189            if desc_end > loop_end {
190                return Err(Error::SectionLengthOverflow {
191                    declared: transport_descriptors_length,
192                    available: loop_end - desc_start,
193                });
194            }
195
196            transport_streams.push(NitTransportStream {
197                transport_stream_id,
198                original_network_id,
199                descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
200            });
201
202            pos = desc_end;
203        }
204
205        Ok(NitSection {
206            kind,
207            network_id,
208            version_number,
209            current_next_indicator,
210            section_number,
211            last_section_number,
212            network_descriptors,
213            transport_streams,
214        })
215    }
216}
217
218impl Serialize for NitSection<'_> {
219    type Error = crate::error::Error;
220    fn serialized_len(&self) -> usize {
221        let net_desc_len = self.network_descriptors.len();
222        let ts_bytes: usize = self
223            .transport_streams
224            .iter()
225            .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
226            .sum();
227        MIN_HEADER_LEN
228            + EXTENSION_HEADER_LEN
229            + POST_EXTENSION_LEN
230            + net_desc_len
231            + 2 // transport_stream_loop_length header
232            + ts_bytes
233            + CRC_LEN
234    }
235
236    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
237        let len = self.serialized_len();
238        if buf.len() < len {
239            return Err(Error::OutputBufferTooSmall {
240                need: len,
241                have: buf.len(),
242            });
243        }
244
245        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
246        buf[0] = match self.kind {
247            NitKind::Actual => TABLE_ID_ACTUAL,
248            NitKind::Other => TABLE_ID_OTHER,
249        };
250        buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
251        buf[2] = (section_length & 0xFF) as u8;
252
253        // Extension header per ETSI EN 300 468 §5.2.1:
254        //   bytes[3..5] = network_id (table_id_extension)
255        //   bytes[5]    = reserved | version | current_next
256        //   bytes[6..8] = section_number + last_section_number
257        buf[3..5].copy_from_slice(&self.network_id.to_be_bytes());
258        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
259        buf[6] = self.section_number;
260        buf[7] = self.last_section_number;
261
262        // bytes[8..10] = reserved(4) | network_descriptors_length(12)
263        let net_dll = self.network_descriptors.len() as u16;
264        buf[8] = 0xF0 | ((net_dll >> 8) as u8 & 0x0F);
265        buf[9] = (net_dll & 0xFF) as u8;
266
267        let net_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
268        buf[net_desc_start..net_desc_start + self.network_descriptors.len()]
269            .copy_from_slice(self.network_descriptors.raw());
270
271        let ts_loop_start = net_desc_start + self.network_descriptors.len();
272        let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
273        buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
274        buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
275
276        let mut pos = ts_loop_start + 2;
277        for ts in &self.transport_streams {
278            buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
279            buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
280            let ts_dll = ts.descriptors.len() as u16;
281            buf[pos + 4] = 0xF0 | ((ts_dll >> 8) as u8 & 0x0F);
282            buf[pos + 5] = (ts_dll & 0xFF) as u8;
283            let desc_start = pos + TS_HEADER_LEN;
284            buf[desc_start..desc_start + ts.descriptors.len()]
285                .copy_from_slice(ts.descriptors.raw());
286            pos = desc_start + ts.descriptors.len();
287        }
288
289        let crc_pos = len - CRC_LEN;
290        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
291        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
292        Ok(len)
293    }
294}
295impl<'a> crate::traits::TableDef<'a> for NitSection<'a> {
296    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID_ACTUAL, TABLE_ID_OTHER)];
297    const NAME: &'static str = "NETWORK_INFORMATION";
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    type TestTs = (u16, u16, Vec<u8>);
305
306    fn build_nit(
307        kind: NitKind,
308        network_id: u16,
309        network_desc: &[u8],
310        transport_streams: &[TestTs],
311    ) -> Vec<u8> {
312        let ts_bytes: usize = transport_streams
313            .iter()
314            .map(|(_, _, d)| TS_HEADER_LEN + d.len())
315            .sum();
316        let loop_length = ts_bytes as u16;
317        let section_length: u16 = (EXTENSION_HEADER_LEN
318            + POST_EXTENSION_LEN
319            + network_desc.len()
320            + 2
321            + ts_bytes
322            + CRC_LEN) as u16;
323        let mut v = Vec::new();
324        v.push(match kind {
325            NitKind::Actual => TABLE_ID_ACTUAL,
326            NitKind::Other => TABLE_ID_OTHER,
327        });
328        v.push(super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F));
329        v.push((section_length & 0xFF) as u8);
330        // Extension header (spec layout): bytes[3..5] = network_id
331        v.extend_from_slice(&network_id.to_be_bytes());
332        v.push(0xC0 | 0x01); // version=0, current_next=1
333        v.push(0); // section_number
334        v.push(0); // last_section_number
335                   // bytes[8..10] = reserved(4) | network_descriptors_length(12)
336        let net_dll = network_desc.len() as u16;
337        v.push(0xF0 | ((net_dll >> 8) as u8 & 0x0F));
338        v.push((net_dll & 0xFF) as u8);
339        v.extend_from_slice(network_desc);
340        // reserved(4) | transport_stream_loop_length(12)
341        v.push(0xF0 | ((loop_length >> 8) as u8 & 0x0F));
342        v.push((loop_length & 0xFF) as u8);
343        for (tsid, onid, desc) in transport_streams {
344            v.extend_from_slice(&tsid.to_be_bytes());
345            v.extend_from_slice(&onid.to_be_bytes());
346            let ts_dll = desc.len() as u16;
347            // reserved(4) | transport_descriptors_length(12)
348            v.push(0xF0 | ((ts_dll >> 8) as u8 & 0x0F));
349            v.push((ts_dll & 0xFF) as u8);
350            v.extend_from_slice(desc);
351        }
352        v.extend_from_slice(&[0, 0, 0, 0]); // CRC placeholder
353        v
354    }
355
356    #[test]
357    fn parse_actual_and_other_distinguished_by_table_id() {
358        let a = build_nit(NitKind::Actual, 0x0001, &[], &[]);
359        let o = build_nit(NitKind::Other, 0x0001, &[], &[]);
360        assert!(matches!(
361            NitSection::parse(&a).unwrap().kind,
362            NitKind::Actual
363        ));
364        assert!(matches!(
365            NitSection::parse(&o).unwrap().kind,
366            NitKind::Other
367        ));
368    }
369
370    #[test]
371    fn parse_network_id_extracted() {
372        let bytes = build_nit(NitKind::Actual, 0x0020, &[], &[]);
373        let nit = NitSection::parse(&bytes).unwrap();
374        assert_eq!(nit.network_id, 0x0020);
375    }
376
377    #[test]
378    fn parse_network_wide_descriptors() {
379        let net_desc: [u8; 4] = [0x40, 0x02, 0x4E, 0x65]; // network_name descriptor
380        let bytes = build_nit(NitKind::Actual, 0x0001, &net_desc, &[]);
381        let nit = NitSection::parse(&bytes).unwrap();
382        assert_eq!(nit.network_descriptors.raw(), &net_desc[..]);
383    }
384
385    #[test]
386    fn parse_transport_stream_entries() {
387        let bytes = build_nit(
388            NitKind::Actual,
389            0x0001,
390            &[],
391            &[
392                (
393                    0x1234,
394                    0x0020,
395                    vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05],
396                ),
397                (0x5678, 0x0020, vec![]),
398            ],
399        );
400        let nit = NitSection::parse(&bytes).unwrap();
401        assert_eq!(nit.transport_streams.len(), 2);
402        assert_eq!(nit.transport_streams[0].transport_stream_id, 0x1234);
403        assert_eq!(nit.transport_streams[0].original_network_id, 0x0020);
404        assert_eq!(
405            nit.transport_streams[0].descriptors.raw(),
406            &[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
407        );
408        assert_eq!(nit.transport_streams[1].transport_stream_id, 0x5678);
409        assert_eq!(nit.transport_streams[1].descriptors.len(), 0);
410    }
411
412    #[test]
413    fn parse_version_and_current_next() {
414        let bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
415        let nit = NitSection::parse(&bytes).unwrap();
416        assert_eq!(nit.version_number, 0);
417        assert!(nit.current_next_indicator);
418    }
419
420    #[test]
421    fn serialize_round_trip() {
422        let net_desc: [u8; 4] = [0x40, 0x02, 0x4E, 0x65];
423        let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
424        let nit = NitSection {
425            kind: NitKind::Actual,
426            network_id: 0x0020,
427            version_number: 3,
428            current_next_indicator: true,
429            section_number: 0,
430            last_section_number: 0,
431            network_descriptors: DescriptorLoop::new(&net_desc),
432            transport_streams: vec![
433                NitTransportStream {
434                    transport_stream_id: 0x1234,
435                    original_network_id: 0x0020,
436                    descriptors: DescriptorLoop::new(&ts_desc),
437                },
438                NitTransportStream {
439                    transport_stream_id: 0x5678,
440                    original_network_id: 0x0020,
441                    descriptors: DescriptorLoop::new(&[]),
442                },
443            ],
444        };
445        let mut buf = vec![0u8; nit.serialized_len()];
446        nit.serialize_into(&mut buf).unwrap();
447        let re = NitSection::parse(&buf).unwrap();
448        assert_eq!(nit, re);
449    }
450
451    #[test]
452    fn zero_transport_streams_is_valid() {
453        let bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
454        let nit = NitSection::parse(&bytes).unwrap();
455        assert_eq!(nit.transport_streams.len(), 0);
456    }
457
458    #[test]
459    fn parse_rejects_short_buffer() {
460        let err = NitSection::parse(&[0x40, 0x00]).unwrap_err();
461        assert!(matches!(err, Error::BufferTooShort { .. }));
462    }
463
464    #[test]
465    fn parse_rejects_wrong_table_id() {
466        let mut bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
467        bytes[0] = 0x00;
468        let err = NitSection::parse(&bytes).unwrap_err();
469        assert!(matches!(
470            err,
471            Error::UnexpectedTableId { table_id: 0x00, .. }
472        ));
473    }
474
475    #[test]
476    fn serialize_too_small_buffer_returns_error() {
477        let nit = NitSection {
478            kind: NitKind::Actual,
479            network_id: 0x0001,
480            version_number: 0,
481            current_next_indicator: true,
482            section_number: 0,
483            last_section_number: 0,
484            network_descriptors: DescriptorLoop::new(&[]),
485            transport_streams: vec![],
486        };
487        let mut buf = vec![0u8; 2];
488        let err = nit.serialize_into(&mut buf).unwrap_err();
489        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
490    }
491
492    #[test]
493    fn parse_rejects_zero_section_length() {
494        let mut buf = vec![0u8; 64];
495        buf[0] = TABLE_ID_ACTUAL;
496        buf[1] = 0xF0;
497        buf[2] = 0x00;
498        for b in &mut buf[3..] {
499            *b = 0xFF;
500        }
501        assert!(matches!(
502            NitSection::parse(&buf).unwrap_err(),
503            Error::SectionLengthOverflow { .. }
504        ));
505    }
506}