1use crate::descriptors::DescriptorLoop;
7use crate::error::{Error, Result};
8use dvb_common::{Parse, Serialize};
9
10pub const TABLE_ID: u8 = 0x74;
12pub const PID: u16 = 0x0000;
14
15const MIN_HEADER_LEN: usize = 3;
16const EXTENSION_HEADER_LEN: usize = 5;
17const COMMON_DESC_LEN_BYTES: usize = 2;
18const APP_LOOP_LEN_BYTES: usize = 2;
19const CRC_LEN: usize = 4;
20const APP_HEADER_LEN: usize = 9;
21const MIN_SECTION_LEN: usize =
22 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + COMMON_DESC_LEN_BYTES + APP_LOOP_LEN_BYTES + CRC_LEN;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize))]
27#[non_exhaustive]
28pub enum ControlCode {
29 Reserved,
31 Autostart,
33 Present,
35 Destroy,
37 Kill,
39 Prefetch,
41 Remote,
43 Disabled,
45 PlaybackAutostart,
47 Unallocated(u8),
49}
50
51impl ControlCode {
52 #[must_use]
53 pub fn from_u8(v: u8) -> Self {
55 match v {
56 0x00 => Self::Reserved,
57 0x01 => Self::Autostart,
58 0x02 => Self::Present,
59 0x03 => Self::Destroy,
60 0x04 => Self::Kill,
61 0x05 => Self::Prefetch,
62 0x06 => Self::Remote,
63 0x07 => Self::Disabled,
64 0x08 => Self::PlaybackAutostart,
65 _ => Self::Unallocated(v),
66 }
67 }
68
69 #[must_use]
70 pub fn to_u8(self) -> u8 {
72 match self {
73 Self::Reserved => 0x00,
74 Self::Autostart => 0x01,
75 Self::Present => 0x02,
76 Self::Destroy => 0x03,
77 Self::Kill => 0x04,
78 Self::Prefetch => 0x05,
79 Self::Remote => 0x06,
80 Self::Disabled => 0x07,
81 Self::PlaybackAutostart => 0x08,
82 Self::Unallocated(v) => v,
83 }
84 }
85
86 #[must_use]
87 pub fn name(self) -> &'static str {
89 match self {
90 Self::Reserved => "Reserved",
91 Self::Autostart => "AUTOSTART",
92 Self::Present => "PRESENT",
93 Self::Destroy => "DESTROY",
94 Self::Kill => "KILL",
95 Self::Prefetch => "PREFETCH",
96 Self::Remote => "REMOTE",
97 Self::Disabled => "DISABLED",
98 Self::PlaybackAutostart => "PLAYBACK_AUTOSTART",
99 Self::Unallocated(_) => "Unallocated",
100 }
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109#[cfg_attr(feature = "serde", derive(serde::Serialize))]
110#[non_exhaustive]
111pub enum ApplicationType {
112 DvbJ,
114 DvbHtml,
116 HbbTv,
118 OipfDae,
120 Reserved(u16),
122 UserDefined(u16),
124}
125
126impl ApplicationType {
127 #[must_use]
128 pub fn from_u16(v: u16) -> Self {
130 match v {
131 0x0001 => Self::DvbJ,
132 0x0002 => Self::DvbHtml,
133 0x0010 => Self::HbbTv,
134 0x0011 => Self::OipfDae,
135 v if v < 0x8000 => Self::Reserved(v),
136 _ => Self::UserDefined(v),
137 }
138 }
139
140 #[must_use]
141 pub fn to_u16(self) -> u16 {
143 match self {
144 Self::DvbJ => 0x0001,
145 Self::DvbHtml => 0x0002,
146 Self::HbbTv => 0x0010,
147 Self::OipfDae => 0x0011,
148 Self::Reserved(v) | Self::UserDefined(v) => v,
149 }
150 }
151
152 #[must_use]
153 pub fn name(self) -> &'static str {
155 match self {
156 Self::DvbJ => "DVB-J",
157 Self::DvbHtml => "DVB-HTML",
158 Self::HbbTv => "HbbTV",
159 Self::OipfDae => "OIPF DAE",
160 Self::Reserved(_) => "Reserved",
161 Self::UserDefined(_) => "User Defined",
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
168#[cfg_attr(feature = "serde", derive(serde::Serialize))]
169pub struct ApplicationIdentifier {
170 pub organisation_id: u32,
172 pub application_id: u16,
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
178#[cfg_attr(feature = "serde", derive(serde::Serialize))]
179#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
180pub struct AitApplication<'a> {
181 pub identifier: ApplicationIdentifier,
183 pub control_code: ControlCode,
185 pub descriptors: DescriptorLoop<'a>,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq)]
193#[cfg_attr(feature = "serde", derive(serde::Serialize))]
194#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
195pub struct AitSection<'a> {
196 pub application_type: ApplicationType,
198 pub test_application_flag: bool,
200 pub version_number: u8,
202 pub current_next_indicator: bool,
204 pub section_number: u8,
206 pub last_section_number: u8,
208 pub common_descriptors: DescriptorLoop<'a>,
212 pub applications: Vec<AitApplication<'a>>,
214}
215
216impl<'a> Parse<'a> for AitSection<'a> {
217 type Error = crate::error::Error;
218 fn parse(bytes: &'a [u8]) -> Result<Self> {
219 let min_len = MIN_HEADER_LEN
220 + EXTENSION_HEADER_LEN
221 + COMMON_DESC_LEN_BYTES
222 + APP_LOOP_LEN_BYTES
223 + CRC_LEN;
224 if bytes.len() < min_len {
225 return Err(Error::BufferTooShort {
226 need: min_len,
227 have: bytes.len(),
228 what: "AitSection",
229 });
230 }
231
232 if bytes[0] != TABLE_ID {
233 return Err(Error::UnexpectedTableId {
234 table_id: bytes[0],
235 what: "AitSection",
236 expected: &[TABLE_ID],
237 });
238 }
239
240 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
241 let total = super::check_section_length(
242 bytes.len(),
243 MIN_HEADER_LEN,
244 section_length as usize,
245 MIN_SECTION_LEN,
246 )?;
247
248 let test_application_flag = (bytes[3] & 0x80) != 0;
249 let application_type_raw = (((bytes[3] & 0x7F) as u16) << 8) | (bytes[4] as u16);
250 let application_type = ApplicationType::from_u16(application_type_raw);
251 let version_number = (bytes[5] >> 1) & 0x1F;
252 let current_next_indicator = (bytes[5] & 0x01) != 0;
253 let section_number = bytes[6];
254 let last_section_number = bytes[7];
255
256 let common_descriptors_length = (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
257 let common_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + COMMON_DESC_LEN_BYTES;
258 let common_desc_end = common_desc_start + common_descriptors_length;
259 let app_loop_end = total - CRC_LEN;
260 if common_desc_end > app_loop_end {
261 return Err(Error::SectionLengthOverflow {
262 declared: common_descriptors_length,
263 available: app_loop_end.saturating_sub(common_desc_start),
264 });
265 }
266 let common_descriptors = DescriptorLoop::new(&bytes[common_desc_start..common_desc_end]);
267
268 let app_loop_length =
269 (((bytes[common_desc_end] & 0x0F) as usize) << 8) | bytes[common_desc_end + 1] as usize;
270 let app_loop_start = common_desc_end + APP_LOOP_LEN_BYTES;
271 let app_loop_actual_end = app_loop_start + app_loop_length;
272 if app_loop_actual_end > app_loop_end {
273 return Err(Error::SectionLengthOverflow {
274 declared: app_loop_length,
275 available: app_loop_end.saturating_sub(app_loop_start),
276 });
277 }
278
279 let mut applications = Vec::new();
280 let mut pos = app_loop_start;
281 while pos + APP_HEADER_LEN <= app_loop_actual_end {
282 let organisation_id = ((bytes[pos] as u32) << 24)
283 | ((bytes[pos + 1] as u32) << 16)
284 | ((bytes[pos + 2] as u32) << 8)
285 | (bytes[pos + 3] as u32);
286 let application_id = u16::from_be_bytes([bytes[pos + 4], bytes[pos + 5]]);
287 let control_code = ControlCode::from_u8(bytes[pos + 6]);
288 let app_desc_length =
289 (((bytes[pos + 7] & 0x0F) as usize) << 8) | bytes[pos + 8] as usize;
290 let app_desc_start = pos + APP_HEADER_LEN;
291 let app_desc_end = app_desc_start + app_desc_length;
292 if app_desc_end > app_loop_actual_end {
293 return Err(Error::SectionLengthOverflow {
294 declared: app_desc_length,
295 available: app_loop_actual_end.saturating_sub(app_desc_start),
296 });
297 }
298 applications.push(AitApplication {
299 identifier: ApplicationIdentifier {
300 organisation_id,
301 application_id,
302 },
303 control_code,
304 descriptors: DescriptorLoop::new(&bytes[app_desc_start..app_desc_end]),
305 });
306 pos = app_desc_end;
307 }
308
309 Ok(AitSection {
310 application_type,
311 test_application_flag,
312 version_number,
313 current_next_indicator,
314 section_number,
315 last_section_number,
316 common_descriptors,
317 applications,
318 })
319 }
320}
321
322impl Serialize for AitSection<'_> {
323 type Error = crate::error::Error;
324 fn serialized_len(&self) -> usize {
325 let app_bytes: usize = self
326 .applications
327 .iter()
328 .map(|a| APP_HEADER_LEN + a.descriptors.len())
329 .sum();
330 MIN_HEADER_LEN
331 + EXTENSION_HEADER_LEN
332 + COMMON_DESC_LEN_BYTES
333 + self.common_descriptors.len()
334 + APP_LOOP_LEN_BYTES
335 + app_bytes
336 + CRC_LEN
337 }
338
339 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
340 let len = self.serialized_len();
341 if buf.len() < len {
342 return Err(Error::OutputBufferTooSmall {
343 need: len,
344 have: buf.len(),
345 });
346 }
347
348 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
349 let app_type_raw = self.application_type.to_u16();
350 buf[0] = TABLE_ID;
351 buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
352 buf[2] = (section_length & 0xFF) as u8;
353 buf[3] = (u8::from(self.test_application_flag) << 7) | ((app_type_raw >> 8) as u8 & 0x7F);
354 buf[4] = (app_type_raw & 0xFF) as u8;
355 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
356 buf[6] = self.section_number;
357 buf[7] = self.last_section_number;
358
359 let cdl = self.common_descriptors.len() as u16;
360 buf[8] = 0xF0 | ((cdl >> 8) as u8 & 0x0F);
361 buf[9] = (cdl & 0xFF) as u8;
362
363 let common_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + COMMON_DESC_LEN_BYTES;
364 buf[common_desc_start..common_desc_start + self.common_descriptors.len()]
365 .copy_from_slice(self.common_descriptors.raw());
366
367 let app_loop_start = common_desc_start + self.common_descriptors.len();
368 let app_bytes: usize = self
369 .applications
370 .iter()
371 .map(|a| APP_HEADER_LEN + a.descriptors.len())
372 .sum();
373 let apl = app_bytes as u16;
374 buf[app_loop_start] = 0xF0 | ((apl >> 8) as u8 & 0x0F);
375 buf[app_loop_start + 1] = (apl & 0xFF) as u8;
376
377 let mut pos = app_loop_start + APP_LOOP_LEN_BYTES;
378 for app in &self.applications {
379 buf[pos..pos + 4].copy_from_slice(&app.identifier.organisation_id.to_be_bytes());
380 buf[pos + 4..pos + 6].copy_from_slice(&app.identifier.application_id.to_be_bytes());
381 buf[pos + 6] = app.control_code.to_u8();
382 let adl = app.descriptors.len() as u16;
383 buf[pos + 7] = 0xF0 | ((adl >> 8) as u8 & 0x0F);
384 buf[pos + 8] = (adl & 0xFF) as u8;
385 let desc_start = pos + APP_HEADER_LEN;
386 buf[desc_start..desc_start + app.descriptors.len()]
387 .copy_from_slice(app.descriptors.raw());
388 pos = desc_start + app.descriptors.len();
389 }
390
391 let crc_pos = len - CRC_LEN;
392 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
393 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
394 Ok(len)
395 }
396}
397impl<'a> crate::traits::TableDef<'a> for AitSection<'a> {
398 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
399 const NAME: &'static str = "APPLICATION_INFORMATION";
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 fn build_ait(
407 application_type: u16,
408 test_flag: bool,
409 version: u8,
410 common_descriptors: &[u8],
411 applications: &[(u32, u16, u8, Vec<u8>)],
412 ) -> Vec<u8> {
413 let app_bytes: usize = applications
414 .iter()
415 .map(|(_, _, _, d)| APP_HEADER_LEN + d.len())
416 .sum();
417 let section_length: u16 = (EXTENSION_HEADER_LEN
418 + COMMON_DESC_LEN_BYTES
419 + common_descriptors.len()
420 + APP_LOOP_LEN_BYTES
421 + app_bytes
422 + CRC_LEN) as u16;
423 let mut v = vec![
424 TABLE_ID,
425 super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F),
426 (section_length & 0xFF) as u8,
427 (u8::from(test_flag) << 7) | ((application_type >> 8) as u8 & 0x7F),
428 (application_type & 0xFF) as u8,
429 0xC0 | ((version & 0x1F) << 1) | 0x01,
430 0,
431 0,
432 ];
433 let cdl = common_descriptors.len() as u16;
434 v.push(0xF0 | ((cdl >> 8) as u8 & 0x0F));
435 v.push((cdl & 0xFF) as u8);
436 v.extend_from_slice(common_descriptors);
437 let apl = app_bytes as u16;
438 v.push(0xF0 | ((apl >> 8) as u8 & 0x0F));
439 v.push((apl & 0xFF) as u8);
440 for &(org_id, app_id, cc, ref desc) in applications {
441 v.extend_from_slice(&org_id.to_be_bytes());
442 v.extend_from_slice(&app_id.to_be_bytes());
443 v.push(cc);
444 let adl = desc.len() as u16;
445 v.push(0xF0 | ((adl >> 8) as u8 & 0x0F));
446 v.push((adl & 0xFF) as u8);
447 v.extend_from_slice(desc);
448 }
449 v.extend_from_slice(&[0, 0, 0, 0]);
450 v
451 }
452
453 #[test]
454 fn parse_rejects_wrong_table_id() {
455 let mut bytes = build_ait(0x0010, false, 0, &[], &[]);
456 bytes[0] = 0x00;
457 let err = AitSection::parse(&bytes).unwrap_err();
458 assert!(matches!(
459 err,
460 Error::UnexpectedTableId { table_id: 0x00, .. }
461 ));
462 }
463
464 #[test]
465 fn parse_rejects_short_buffer() {
466 let err = AitSection::parse(&[0x74, 0x00]).unwrap_err();
467 assert!(matches!(err, Error::BufferTooShort { .. }));
468 }
469
470 #[test]
471 fn parse_empty_ait_no_applications() {
472 let bytes = build_ait(0x0010, false, 5, &[], &[]);
473 let ait = AitSection::parse(&bytes).expect("parse");
474 assert_eq!(ait.application_type, ApplicationType::HbbTv);
475 assert!(!ait.test_application_flag);
476 assert_eq!(ait.version_number, 5);
477 assert!(ait.current_next_indicator);
478 assert_eq!(ait.section_number, 0);
479 assert_eq!(ait.last_section_number, 0);
480 assert_eq!(ait.common_descriptors.len(), 0);
481 assert_eq!(ait.applications.len(), 0);
482 }
483
484 #[test]
485 fn parse_test_application_flag_extracted() {
486 let bytes = build_ait(0x0010, true, 0, &[], &[]);
487 let ait = AitSection::parse(&bytes).unwrap();
488 assert!(ait.test_application_flag);
489 }
490
491 #[test]
492 fn parse_common_descriptors_preserved() {
493 let desc = vec![0x00, 0x02, 0xAA, 0xBB];
494 let bytes = build_ait(0x0010, false, 0, &desc, &[]);
495 let ait = AitSection::parse(&bytes).unwrap();
496 assert_eq!(ait.common_descriptors.raw(), &desc[..]);
497 }
498
499 #[test]
500 fn parse_single_application() {
501 let desc = vec![0x02, 0x03, 0xCC, 0xDD, 0xEE];
502 let bytes = build_ait(
503 0x0010,
504 false,
505 0,
506 &[],
507 &[(0x12345678, 0xABCD, 0x01, desc.clone())],
508 );
509 let ait = AitSection::parse(&bytes).unwrap();
510 assert_eq!(ait.applications.len(), 1);
511 assert_eq!(ait.applications[0].identifier.organisation_id, 0x12345678);
512 assert_eq!(ait.applications[0].identifier.application_id, 0xABCD);
513 assert_eq!(ait.applications[0].control_code, ControlCode::Autostart);
514 assert_eq!(ait.applications[0].descriptors.raw(), &desc[..]);
515 }
516
517 #[test]
518 fn parse_multiple_applications_preserve_order() {
519 let bytes = build_ait(
520 0x0010,
521 false,
522 0,
523 &[],
524 &[
525 (0x00000001, 0x0001, 0x01, vec![]),
526 (0x00000002, 0x0002, 0x02, vec![0x01]),
527 (0x00000003, 0x0003, 0x03, vec![0x02, 0x03]),
528 ],
529 );
530 let ait = AitSection::parse(&bytes).unwrap();
531 assert_eq!(ait.applications.len(), 3);
532 assert_eq!(ait.applications[0].identifier.organisation_id, 1);
533 assert_eq!(ait.applications[1].identifier.organisation_id, 2);
534 assert_eq!(ait.applications[2].identifier.organisation_id, 3);
535 }
536
537 #[test]
538 fn serialize_round_trip_empty() {
539 let ait = AitSection {
540 application_type: ApplicationType::HbbTv,
541 test_application_flag: false,
542 version_number: 3,
543 current_next_indicator: true,
544 section_number: 0,
545 last_section_number: 0,
546 common_descriptors: DescriptorLoop::new(&[]),
547 applications: vec![],
548 };
549 let mut buf = vec![0u8; ait.serialized_len()];
550 ait.serialize_into(&mut buf).unwrap();
551 let reparsed = AitSection::parse(&buf).unwrap();
552 assert_eq!(ait, reparsed);
553 }
554
555 #[test]
556 fn serialize_round_trip_with_applications() {
557 let desc1: [u8; 2] = [0xAA, 0xBB];
558 let ait = AitSection {
559 application_type: ApplicationType::HbbTv,
560 test_application_flag: true,
561 version_number: 7,
562 current_next_indicator: true,
563 section_number: 1,
564 last_section_number: 2,
565 common_descriptors: DescriptorLoop::new(&[0x01, 0x00]),
566 applications: vec![
567 AitApplication {
568 identifier: ApplicationIdentifier {
569 organisation_id: 0x12345678,
570 application_id: 0xABCD,
571 },
572 control_code: ControlCode::Autostart,
573 descriptors: DescriptorLoop::new(&desc1),
574 },
575 AitApplication {
576 identifier: ApplicationIdentifier {
577 organisation_id: 0x87654321,
578 application_id: 0x00EF,
579 },
580 control_code: ControlCode::Present,
581 descriptors: DescriptorLoop::new(&[]),
582 },
583 ],
584 };
585 let mut buf = vec![0u8; ait.serialized_len()];
586 ait.serialize_into(&mut buf).unwrap();
587 let reparsed = AitSection::parse(&buf).unwrap();
588 assert_eq!(ait, reparsed);
589 }
590
591 #[test]
592 fn parse_rejects_zero_section_length() {
593 let mut buf = vec![0u8; 64];
594 buf[0] = TABLE_ID;
595 buf[1] = 0xF0;
596 buf[2] = 0x00;
597 for b in &mut buf[3..] {
598 *b = 0xFF;
599 }
600 assert!(matches!(
601 AitSection::parse(&buf).unwrap_err(),
602 Error::SectionLengthOverflow { .. }
603 ));
604 }
605
606 #[test]
607 fn control_code_full_range_round_trip() {
608 for byte in 0u8..=0xFF {
609 let cc = ControlCode::from_u8(byte);
610 assert_eq!(
611 cc.to_u8(),
612 byte,
613 "ControlCode round-trip failed for {byte:#04x}"
614 );
615 }
616 }
617
618 #[test]
619 fn control_code_named_values() {
620 assert_eq!(ControlCode::Autostart.to_u8(), 0x01);
621 assert_eq!(ControlCode::Kill.to_u8(), 0x04);
622 assert_eq!(ControlCode::Prefetch.to_u8(), 0x05);
623 assert_eq!(ControlCode::PlaybackAutostart.to_u8(), 0x08);
624 }
625
626 #[test]
627 fn application_type_full_range_round_trip() {
628 for at in 0u16..=0xFFFF {
629 let app = ApplicationType::from_u16(at);
630 assert_eq!(
631 app.to_u16(),
632 at,
633 "ApplicationType round-trip failed for {at:#06x}"
634 );
635 }
636 }
637}