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