1use crate::descriptors::DescriptorLoop;
9use crate::error::{Error, Result};
10use crate::traits::Table;
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 TS_HEADER_LEN: usize = 6;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize))]
34pub enum NitKind {
35 Actual,
37 Other,
39}
40
41#[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 pub transport_stream_id: u16,
48 pub original_network_id: u16,
50 pub descriptors: DescriptorLoop<'a>,
54}
55
56#[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 pub kind: NitKind,
63 pub network_id: u16,
65 pub version_number: u8,
67 pub current_next_indicator: bool,
69 pub section_number: u8,
71 pub last_section_number: u8,
73 pub network_descriptors: DescriptorLoop<'a>,
77 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 = 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 network_id = u16::from_be_bytes([bytes[3], bytes[4]]);
119 let version_number = (bytes[5] >> 1) & 0x1F;
120 let current_next_indicator = (bytes[5] & 0x01) != 0;
121 let section_number = bytes[6];
122 let last_section_number = bytes[7];
123
124 let network_descriptors_length = (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
126
127 let network_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
128 let network_desc_end = network_desc_start + network_descriptors_length;
129
130 if network_desc_end > total - CRC_LEN {
132 return Err(Error::SectionLengthOverflow {
133 declared: network_descriptors_length,
134 available: (total - CRC_LEN) - network_desc_start,
135 });
136 }
137
138 let network_descriptors = DescriptorLoop::new(&bytes[network_desc_start..network_desc_end]);
139
140 let ts_loop_start = network_desc_end;
142 let ts_loop_end = total - CRC_LEN;
143
144 if ts_loop_end - ts_loop_start < 2 {
146 return Err(Error::BufferTooShort {
147 need: ts_loop_end - ts_loop_start + 2,
148 have: ts_loop_end - ts_loop_start,
149 what: "NitSection transport_stream_loop",
150 });
151 }
152
153 let transport_stream_loop_length =
154 (((bytes[ts_loop_start] & 0x0F) as usize) << 8) | bytes[ts_loop_start + 1] as usize;
155
156 let mut pos = ts_loop_start + 2;
157 let loop_end = ts_loop_start + 2 + transport_stream_loop_length;
158
159 if loop_end > ts_loop_end {
160 return Err(Error::SectionLengthOverflow {
161 declared: transport_stream_loop_length,
162 available: ts_loop_end - (ts_loop_start + 2),
163 });
164 }
165
166 let mut transport_streams = Vec::new();
167
168 while pos < loop_end {
169 if pos + TS_HEADER_LEN > loop_end {
170 return Err(Error::BufferTooShort {
171 need: pos + TS_HEADER_LEN,
172 have: loop_end,
173 what: "NitSection transport_stream_entry",
174 });
175 }
176
177 let transport_stream_id = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
178 let original_network_id = u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]);
179
180 let transport_descriptors_length =
182 (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
183
184 let desc_start = pos + TS_HEADER_LEN;
185 let desc_end = desc_start + transport_descriptors_length;
186
187 if desc_end > loop_end {
188 return Err(Error::SectionLengthOverflow {
189 declared: transport_descriptors_length,
190 available: loop_end - desc_start,
191 });
192 }
193
194 transport_streams.push(NitTransportStream {
195 transport_stream_id,
196 original_network_id,
197 descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
198 });
199
200 pos = desc_end;
201 }
202
203 Ok(NitSection {
204 kind,
205 network_id,
206 version_number,
207 current_next_indicator,
208 section_number,
209 last_section_number,
210 network_descriptors,
211 transport_streams,
212 })
213 }
214}
215
216impl Serialize for NitSection<'_> {
217 type Error = crate::error::Error;
218 fn serialized_len(&self) -> usize {
219 let net_desc_len = self.network_descriptors.len();
220 let ts_bytes: usize = self
221 .transport_streams
222 .iter()
223 .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
224 .sum();
225 MIN_HEADER_LEN
226 + EXTENSION_HEADER_LEN
227 + POST_EXTENSION_LEN
228 + net_desc_len
229 + 2 + ts_bytes
231 + CRC_LEN
232 }
233
234 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
235 let len = self.serialized_len();
236 if buf.len() < len {
237 return Err(Error::OutputBufferTooSmall {
238 need: len,
239 have: buf.len(),
240 });
241 }
242
243 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
244 buf[0] = match self.kind {
245 NitKind::Actual => TABLE_ID_ACTUAL,
246 NitKind::Other => TABLE_ID_OTHER,
247 };
248 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
249 buf[2] = (section_length & 0xFF) as u8;
250
251 buf[3..5].copy_from_slice(&self.network_id.to_be_bytes());
256 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
257 buf[6] = self.section_number;
258 buf[7] = self.last_section_number;
259
260 let net_dll = self.network_descriptors.len() as u16;
262 buf[8] = 0xF0 | ((net_dll >> 8) as u8 & 0x0F);
263 buf[9] = (net_dll & 0xFF) as u8;
264
265 let net_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
266 buf[net_desc_start..net_desc_start + self.network_descriptors.len()]
267 .copy_from_slice(self.network_descriptors.raw());
268
269 let ts_loop_start = net_desc_start + self.network_descriptors.len();
270 let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
271 buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
272 buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
273
274 let mut pos = ts_loop_start + 2;
275 for ts in &self.transport_streams {
276 buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
277 buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
278 let ts_dll = ts.descriptors.len() as u16;
279 buf[pos + 4] = 0xF0 | ((ts_dll >> 8) as u8 & 0x0F);
280 buf[pos + 5] = (ts_dll & 0xFF) as u8;
281 let desc_start = pos + TS_HEADER_LEN;
282 buf[desc_start..desc_start + ts.descriptors.len()]
283 .copy_from_slice(ts.descriptors.raw());
284 pos = desc_start + ts.descriptors.len();
285 }
286
287 let crc_pos = len - CRC_LEN;
288 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
289 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
290 Ok(len)
291 }
292}
293
294impl<'a> Table<'a> for NitSection<'a> {
295 const TABLE_ID: u8 = TABLE_ID_ACTUAL;
296 const PID: u16 = PID;
297}
298
299impl<'a> crate::traits::TableDef<'a> for NitSection<'a> {
300 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID_ACTUAL, TABLE_ID_OTHER)];
301 const NAME: &'static str = "NETWORK_INFORMATION";
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 type TestTs = (u16, u16, Vec<u8>);
309
310 fn build_nit(
311 kind: NitKind,
312 network_id: u16,
313 network_desc: &[u8],
314 transport_streams: &[TestTs],
315 ) -> Vec<u8> {
316 let ts_bytes: usize = transport_streams
317 .iter()
318 .map(|(_, _, d)| TS_HEADER_LEN + d.len())
319 .sum();
320 let loop_length = ts_bytes as u16;
321 let section_length: u16 = (EXTENSION_HEADER_LEN
322 + POST_EXTENSION_LEN
323 + network_desc.len()
324 + 2
325 + ts_bytes
326 + CRC_LEN) as u16;
327 let mut v = Vec::new();
328 v.push(match kind {
329 NitKind::Actual => TABLE_ID_ACTUAL,
330 NitKind::Other => TABLE_ID_OTHER,
331 });
332 v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
333 v.push((section_length & 0xFF) as u8);
334 v.extend_from_slice(&network_id.to_be_bytes());
336 v.push(0xC0 | 0x01); v.push(0); v.push(0); let net_dll = network_desc.len() as u16;
341 v.push(0xF0 | ((net_dll >> 8) as u8 & 0x0F));
342 v.push((net_dll & 0xFF) as u8);
343 v.extend_from_slice(network_desc);
344 v.push(0xF0 | ((loop_length >> 8) as u8 & 0x0F));
346 v.push((loop_length & 0xFF) as u8);
347 for (tsid, onid, desc) in transport_streams {
348 v.extend_from_slice(&tsid.to_be_bytes());
349 v.extend_from_slice(&onid.to_be_bytes());
350 let ts_dll = desc.len() as u16;
351 v.push(0xF0 | ((ts_dll >> 8) as u8 & 0x0F));
353 v.push((ts_dll & 0xFF) as u8);
354 v.extend_from_slice(desc);
355 }
356 v.extend_from_slice(&[0, 0, 0, 0]); v
358 }
359
360 #[test]
361 fn parse_actual_and_other_distinguished_by_table_id() {
362 let a = build_nit(NitKind::Actual, 0x0001, &[], &[]);
363 let o = build_nit(NitKind::Other, 0x0001, &[], &[]);
364 assert!(matches!(
365 NitSection::parse(&a).unwrap().kind,
366 NitKind::Actual
367 ));
368 assert!(matches!(
369 NitSection::parse(&o).unwrap().kind,
370 NitKind::Other
371 ));
372 }
373
374 #[test]
375 fn parse_network_id_extracted() {
376 let bytes = build_nit(NitKind::Actual, 0x0020, &[], &[]);
377 let nit = NitSection::parse(&bytes).unwrap();
378 assert_eq!(nit.network_id, 0x0020);
379 }
380
381 #[test]
382 fn parse_network_wide_descriptors() {
383 let net_desc: [u8; 4] = [0x40, 0x02, 0x4E, 0x65]; let bytes = build_nit(NitKind::Actual, 0x0001, &net_desc, &[]);
385 let nit = NitSection::parse(&bytes).unwrap();
386 assert_eq!(nit.network_descriptors.raw(), &net_desc[..]);
387 }
388
389 #[test]
390 fn parse_transport_stream_entries() {
391 let bytes = build_nit(
392 NitKind::Actual,
393 0x0001,
394 &[],
395 &[
396 (
397 0x1234,
398 0x0020,
399 vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05],
400 ),
401 (0x5678, 0x0020, vec![]),
402 ],
403 );
404 let nit = NitSection::parse(&bytes).unwrap();
405 assert_eq!(nit.transport_streams.len(), 2);
406 assert_eq!(nit.transport_streams[0].transport_stream_id, 0x1234);
407 assert_eq!(nit.transport_streams[0].original_network_id, 0x0020);
408 assert_eq!(
409 nit.transport_streams[0].descriptors.raw(),
410 &[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
411 );
412 assert_eq!(nit.transport_streams[1].transport_stream_id, 0x5678);
413 assert_eq!(nit.transport_streams[1].descriptors.len(), 0);
414 }
415
416 #[test]
417 fn parse_version_and_current_next() {
418 let bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
419 let nit = NitSection::parse(&bytes).unwrap();
420 assert_eq!(nit.version_number, 0);
421 assert!(nit.current_next_indicator);
422 }
423
424 #[test]
425 fn serialize_round_trip() {
426 let net_desc: [u8; 4] = [0x40, 0x02, 0x4E, 0x65];
427 let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
428 let nit = NitSection {
429 kind: NitKind::Actual,
430 network_id: 0x0020,
431 version_number: 3,
432 current_next_indicator: true,
433 section_number: 0,
434 last_section_number: 0,
435 network_descriptors: DescriptorLoop::new(&net_desc),
436 transport_streams: vec![
437 NitTransportStream {
438 transport_stream_id: 0x1234,
439 original_network_id: 0x0020,
440 descriptors: DescriptorLoop::new(&ts_desc),
441 },
442 NitTransportStream {
443 transport_stream_id: 0x5678,
444 original_network_id: 0x0020,
445 descriptors: DescriptorLoop::new(&[]),
446 },
447 ],
448 };
449 let mut buf = vec![0u8; nit.serialized_len()];
450 nit.serialize_into(&mut buf).unwrap();
451 let re = NitSection::parse(&buf).unwrap();
452 assert_eq!(nit, re);
453 }
454
455 #[test]
456 fn zero_transport_streams_is_valid() {
457 let bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
458 let nit = NitSection::parse(&bytes).unwrap();
459 assert_eq!(nit.transport_streams.len(), 0);
460 }
461
462 #[test]
463 fn parse_rejects_short_buffer() {
464 let err = NitSection::parse(&[0x40, 0x00]).unwrap_err();
465 assert!(matches!(err, Error::BufferTooShort { .. }));
466 }
467
468 #[test]
469 fn parse_rejects_wrong_table_id() {
470 let mut bytes = build_nit(NitKind::Actual, 0x0001, &[], &[]);
471 bytes[0] = 0x00;
472 let err = NitSection::parse(&bytes).unwrap_err();
473 assert!(matches!(
474 err,
475 Error::UnexpectedTableId { table_id: 0x00, .. }
476 ));
477 }
478
479 #[test]
480 fn serialize_too_small_buffer_returns_error() {
481 let nit = NitSection {
482 kind: NitKind::Actual,
483 network_id: 0x0001,
484 version_number: 0,
485 current_next_indicator: true,
486 section_number: 0,
487 last_section_number: 0,
488 network_descriptors: DescriptorLoop::new(&[]),
489 transport_streams: vec![],
490 };
491 let mut buf = vec![0u8; 2];
492 let err = nit.serialize_into(&mut buf).unwrap_err();
493 assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
494 }
495}