1use crate::descriptors::DescriptorLoop;
9use crate::error::{Error, Result};
10use alloc::vec::Vec;
11use dvb_common::{Parse, Serialize};
12
13pub const TABLE_ID_ACTUAL: u8 = 0x40;
15pub const TABLE_ID_OTHER: u8 = 0x41;
17pub const PID: u16 = 0x0010;
19
20const MIN_HEADER_LEN: usize = 3;
21const EXTENSION_HEADER_LEN: usize = 5;
22const 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;
29const TS_HEADER_LEN: usize = 6;
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize))]
35#[non_exhaustive]
36pub enum NitKind {
37 Actual,
39 Other,
41}
42
43#[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 pub transport_stream_id: u16,
50 pub original_network_id: u16,
52 pub descriptors: DescriptorLoop<'a>,
56}
57
58#[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 pub kind: NitKind,
65 pub network_id: u16,
67 pub version_number: u8,
69 pub current_next_indicator: bool,
71 pub section_number: u8,
73 pub last_section_number: u8,
75 pub network_descriptors: DescriptorLoop<'a>,
79 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 let network_id = u16::from_be_bytes([bytes[3], bytes[4]]);
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 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 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 let ts_loop_start = network_desc_end;
143 let ts_loop_end = total - CRC_LEN;
144
145 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 transport_stream_id = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
179 let original_network_id = u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]);
180
181 let transport_descriptors_length =
183 (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
184
185 let desc_start = pos + TS_HEADER_LEN;
186 let desc_end = desc_start + transport_descriptors_length;
187
188 if desc_end > loop_end {
189 return Err(Error::SectionLengthOverflow {
190 declared: transport_descriptors_length,
191 available: loop_end - desc_start,
192 });
193 }
194
195 transport_streams.push(NitTransportStream {
196 transport_stream_id,
197 original_network_id,
198 descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
199 });
200
201 pos = desc_end;
202 }
203
204 Ok(NitSection {
205 kind,
206 network_id,
207 version_number,
208 current_next_indicator,
209 section_number,
210 last_section_number,
211 network_descriptors,
212 transport_streams,
213 })
214 }
215}
216
217impl Serialize for NitSection<'_> {
218 type Error = crate::error::Error;
219 fn serialized_len(&self) -> usize {
220 let net_desc_len = self.network_descriptors.len();
221 let ts_bytes: usize = self
222 .transport_streams
223 .iter()
224 .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
225 .sum();
226 MIN_HEADER_LEN
227 + EXTENSION_HEADER_LEN
228 + POST_EXTENSION_LEN
229 + net_desc_len
230 + 2 + ts_bytes
232 + CRC_LEN
233 }
234
235 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
236 let len = self.serialized_len();
237 if buf.len() < len {
238 return Err(Error::OutputBufferTooSmall {
239 need: len,
240 have: buf.len(),
241 });
242 }
243
244 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
245 buf[0] = match self.kind {
246 NitKind::Actual => TABLE_ID_ACTUAL,
247 NitKind::Other => TABLE_ID_OTHER,
248 };
249 buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
250 buf[2] = (section_length & 0xFF) as u8;
251
252 buf[3..5].copy_from_slice(&self.network_id.to_be_bytes());
257 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
258 buf[6] = self.section_number;
259 buf[7] = self.last_section_number;
260
261 let net_dll = self.network_descriptors.len() as u16;
263 buf[8] = 0xF0 | ((net_dll >> 8) as u8 & 0x0F);
264 buf[9] = (net_dll & 0xFF) as u8;
265
266 let net_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
267 buf[net_desc_start..net_desc_start + self.network_descriptors.len()]
268 .copy_from_slice(self.network_descriptors.raw());
269
270 let ts_loop_start = net_desc_start + self.network_descriptors.len();
271 let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
272 buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
273 buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
274
275 let mut pos = ts_loop_start + 2;
276 for ts in &self.transport_streams {
277 buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
278 buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
279 let ts_dll = ts.descriptors.len() as u16;
280 buf[pos + 4] = 0xF0 | ((ts_dll >> 8) as u8 & 0x0F);
281 buf[pos + 5] = (ts_dll & 0xFF) as u8;
282 let desc_start = pos + TS_HEADER_LEN;
283 buf[desc_start..desc_start + ts.descriptors.len()]
284 .copy_from_slice(ts.descriptors.raw());
285 pos = desc_start + ts.descriptors.len();
286 }
287
288 let crc_pos = len - CRC_LEN;
289 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
290 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
291 Ok(len)
292 }
293}
294impl<'a> crate::traits::TableDef<'a> for NitSection<'a> {
295 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID_ACTUAL, TABLE_ID_OTHER)];
296 const NAME: &'static str = "NETWORK_INFORMATION";
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 type TestTs = (u16, u16, Vec<u8>);
304
305 fn build_nit(
306 kind: NitKind,
307 network_id: u16,
308 network_desc: &[u8],
309 transport_streams: &[TestTs],
310 ) -> Vec<u8> {
311 let ts_bytes: usize = transport_streams
312 .iter()
313 .map(|(_, _, d)| TS_HEADER_LEN + d.len())
314 .sum();
315 let loop_length = ts_bytes as u16;
316 let section_length: u16 = (EXTENSION_HEADER_LEN
317 + POST_EXTENSION_LEN
318 + network_desc.len()
319 + 2
320 + ts_bytes
321 + CRC_LEN) as u16;
322 let mut v = Vec::new();
323 v.push(match kind {
324 NitKind::Actual => TABLE_ID_ACTUAL,
325 NitKind::Other => TABLE_ID_OTHER,
326 });
327 v.push(super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F));
328 v.push((section_length & 0xFF) as u8);
329 v.extend_from_slice(&network_id.to_be_bytes());
331 v.push(0xC0 | 0x01); v.push(0); v.push(0); let net_dll = network_desc.len() as u16;
336 v.push(0xF0 | ((net_dll >> 8) as u8 & 0x0F));
337 v.push((net_dll & 0xFF) as u8);
338 v.extend_from_slice(network_desc);
339 v.push(0xF0 | ((loop_length >> 8) as u8 & 0x0F));
341 v.push((loop_length & 0xFF) as u8);
342 for (tsid, onid, desc) in transport_streams {
343 v.extend_from_slice(&tsid.to_be_bytes());
344 v.extend_from_slice(&onid.to_be_bytes());
345 let ts_dll = desc.len() as u16;
346 v.push(0xF0 | ((ts_dll >> 8) as u8 & 0x0F));
348 v.push((ts_dll & 0xFF) as u8);
349 v.extend_from_slice(desc);
350 }
351 v.extend_from_slice(&[0, 0, 0, 0]); v
353 }
354
355 #[test]
356 fn parse_actual_and_other_distinguished_by_table_id() {
357 let a = build_nit(NitKind::Actual, 0x0001, &[], &[]);
358 let o = build_nit(NitKind::Other, 0x0001, &[], &[]);
359 assert!(matches!(
360 NitSection::parse(&a).unwrap().kind,
361 NitKind::Actual
362 ));
363 assert!(matches!(
364 NitSection::parse(&o).unwrap().kind,
365 NitKind::Other
366 ));
367 }
368
369 #[test]
370 fn parse_network_id_extracted() {
371 let bytes = build_nit(NitKind::Actual, 0x0020, &[], &[]);
372 let nit = NitSection::parse(&bytes).unwrap();
373 assert_eq!(nit.network_id, 0x0020);
374 }
375
376 #[test]
377 fn parse_network_wide_descriptors() {
378 let net_desc: [u8; 4] = [0x40, 0x02, 0x4E, 0x65]; let bytes = build_nit(NitKind::Actual, 0x0001, &net_desc, &[]);
380 let nit = NitSection::parse(&bytes).unwrap();
381 assert_eq!(nit.network_descriptors.raw(), &net_desc[..]);
382 }
383
384 #[test]
385 fn parse_transport_stream_entries() {
386 let bytes = build_nit(
387 NitKind::Actual,
388 0x0001,
389 &[],
390 &[
391 (
392 0x1234,
393 0x0020,
394 vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05],
395 ),
396 (0x5678, 0x0020, vec![]),
397 ],
398 );
399 let nit = NitSection::parse(&bytes).unwrap();
400 assert_eq!(nit.transport_streams.len(), 2);
401 assert_eq!(nit.transport_streams[0].transport_stream_id, 0x1234);
402 assert_eq!(nit.transport_streams[0].original_network_id, 0x0020);
403 assert_eq!(
404 nit.transport_streams[0].descriptors.raw(),
405 &[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
406 );
407 assert_eq!(nit.transport_streams[1].transport_stream_id, 0x5678);
408 assert_eq!(nit.transport_streams[1].descriptors.len(), 0);
409 }
410
411 #[test]
412 fn parse_version_and_current_next() {
413 let bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
414 let nit = NitSection::parse(&bytes).unwrap();
415 assert_eq!(nit.version_number, 0);
416 assert!(nit.current_next_indicator);
417 }
418
419 #[test]
420 fn serialize_round_trip() {
421 let net_desc: [u8; 4] = [0x40, 0x02, 0x4E, 0x65];
422 let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
423 let nit = NitSection {
424 kind: NitKind::Actual,
425 network_id: 0x0020,
426 version_number: 3,
427 current_next_indicator: true,
428 section_number: 0,
429 last_section_number: 0,
430 network_descriptors: DescriptorLoop::new(&net_desc),
431 transport_streams: vec![
432 NitTransportStream {
433 transport_stream_id: 0x1234,
434 original_network_id: 0x0020,
435 descriptors: DescriptorLoop::new(&ts_desc),
436 },
437 NitTransportStream {
438 transport_stream_id: 0x5678,
439 original_network_id: 0x0020,
440 descriptors: DescriptorLoop::new(&[]),
441 },
442 ],
443 };
444 let mut buf = vec![0u8; nit.serialized_len()];
445 nit.serialize_into(&mut buf).unwrap();
446 let re = NitSection::parse(&buf).unwrap();
447 assert_eq!(nit, re);
448 }
449
450 #[test]
451 fn zero_transport_streams_is_valid() {
452 let bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
453 let nit = NitSection::parse(&bytes).unwrap();
454 assert_eq!(nit.transport_streams.len(), 0);
455 }
456
457 #[test]
458 fn parse_rejects_short_buffer() {
459 let err = NitSection::parse(&[0x40, 0x00]).unwrap_err();
460 assert!(matches!(err, Error::BufferTooShort { .. }));
461 }
462
463 #[test]
464 fn parse_rejects_wrong_table_id() {
465 let mut bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
466 bytes[0] = 0x00;
467 let err = NitSection::parse(&bytes).unwrap_err();
468 assert!(matches!(
469 err,
470 Error::UnexpectedTableId { table_id: 0x00, .. }
471 ));
472 }
473
474 #[test]
475 fn serialize_too_small_buffer_returns_error() {
476 let nit = NitSection {
477 kind: NitKind::Actual,
478 network_id: 0x0001,
479 version_number: 0,
480 current_next_indicator: true,
481 section_number: 0,
482 last_section_number: 0,
483 network_descriptors: DescriptorLoop::new(&[]),
484 transport_streams: vec![],
485 };
486 let mut buf = vec![0u8; 2];
487 let err = nit.serialize_into(&mut buf).unwrap_err();
488 assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
489 }
490
491 #[test]
492 fn parse_rejects_zero_section_length() {
493 let mut buf = vec![0u8; 64];
494 buf[0] = TABLE_ID_ACTUAL;
495 buf[1] = 0xF0;
496 buf[2] = 0x00;
497 for b in &mut buf[3..] {
498 *b = 0xFF;
499 }
500 assert!(matches!(
501 NitSection::parse(&buf).unwrap_err(),
502 Error::SectionLengthOverflow { .. }
503 ));
504 }
505}