1use crate::descriptors::DescriptorLoop;
7use crate::error::{Error, Result};
8use crate::traits::Table;
9use dvb_common::{Parse, Serialize};
10
11pub const TABLE_ID: u8 = 0x74;
13pub const PID: u16 = 0x0000;
15
16const MIN_HEADER_LEN: usize = 3;
17const EXTENSION_HEADER_LEN: usize = 5;
18const COMMON_DESC_LEN_BYTES: usize = 2;
19const APP_LOOP_LEN_BYTES: usize = 2;
20const CRC_LEN: usize = 4;
21const APP_HEADER_LEN: usize = 9;
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize))]
26pub struct ApplicationIdentifier {
27 pub organisation_id: u32,
29 pub application_id: u16,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize))]
36#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
37pub struct AitApplication<'a> {
38 pub identifier: ApplicationIdentifier,
40 pub control_code: u8,
42 pub descriptors: DescriptorLoop<'a>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize))]
51#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
52pub struct Ait<'a> {
53 pub application_type: u16,
55 pub test_application_flag: bool,
57 pub version_number: u8,
59 pub current_next_indicator: bool,
61 pub section_number: u8,
63 pub last_section_number: u8,
65 pub common_descriptors: DescriptorLoop<'a>,
69 pub applications: Vec<AitApplication<'a>>,
71}
72
73impl<'a> Parse<'a> for Ait<'a> {
74 type Error = crate::error::Error;
75 fn parse(bytes: &'a [u8]) -> Result<Self> {
76 let min_len = MIN_HEADER_LEN
77 + EXTENSION_HEADER_LEN
78 + COMMON_DESC_LEN_BYTES
79 + APP_LOOP_LEN_BYTES
80 + CRC_LEN;
81 if bytes.len() < min_len {
82 return Err(Error::BufferTooShort {
83 need: min_len,
84 have: bytes.len(),
85 what: "Ait",
86 });
87 }
88
89 if bytes[0] != TABLE_ID {
90 return Err(Error::UnexpectedTableId {
91 table_id: bytes[0],
92 what: "Ait",
93 expected: &[TABLE_ID],
94 });
95 }
96
97 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
98 let total = MIN_HEADER_LEN + section_length as usize;
99 if bytes.len() < total {
100 return Err(Error::SectionLengthOverflow {
101 declared: section_length as usize,
102 available: bytes.len() - MIN_HEADER_LEN,
103 });
104 }
105
106 let test_application_flag = (bytes[3] & 0x80) != 0;
107 let application_type = (((bytes[3] & 0x7F) as u16) << 8) | (bytes[4] as u16);
108 let version_number = (bytes[5] >> 1) & 0x1F;
109 let current_next_indicator = (bytes[5] & 0x01) != 0;
110 let section_number = bytes[6];
111 let last_section_number = bytes[7];
112
113 let common_descriptors_length = (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
114 let common_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + COMMON_DESC_LEN_BYTES;
115 let common_desc_end = common_desc_start + common_descriptors_length;
116 let app_loop_end = total - CRC_LEN;
117 if common_desc_end > app_loop_end {
118 return Err(Error::SectionLengthOverflow {
119 declared: common_descriptors_length,
120 available: app_loop_end - common_desc_start,
121 });
122 }
123 let common_descriptors = DescriptorLoop::new(&bytes[common_desc_start..common_desc_end]);
124
125 let app_loop_length =
126 (((bytes[common_desc_end] & 0x0F) as usize) << 8) | bytes[common_desc_end + 1] as usize;
127 let app_loop_start = common_desc_end + APP_LOOP_LEN_BYTES;
128 let app_loop_actual_end = app_loop_start + app_loop_length;
129 if app_loop_actual_end > app_loop_end {
130 return Err(Error::SectionLengthOverflow {
131 declared: app_loop_length,
132 available: app_loop_end - app_loop_start,
133 });
134 }
135
136 let mut applications = Vec::new();
137 let mut pos = app_loop_start;
138 while pos + APP_HEADER_LEN <= app_loop_actual_end {
139 let organisation_id = ((bytes[pos] as u32) << 24)
140 | ((bytes[pos + 1] as u32) << 16)
141 | ((bytes[pos + 2] as u32) << 8)
142 | (bytes[pos + 3] as u32);
143 let application_id = u16::from_be_bytes([bytes[pos + 4], bytes[pos + 5]]);
144 let control_code = bytes[pos + 6];
145 let app_desc_length =
146 (((bytes[pos + 7] & 0x0F) as usize) << 8) | bytes[pos + 8] as usize;
147 let app_desc_start = pos + APP_HEADER_LEN;
148 let app_desc_end = app_desc_start + app_desc_length;
149 if app_desc_end > app_loop_actual_end {
150 return Err(Error::SectionLengthOverflow {
151 declared: app_desc_length,
152 available: app_loop_actual_end - app_desc_start,
153 });
154 }
155 applications.push(AitApplication {
156 identifier: ApplicationIdentifier {
157 organisation_id,
158 application_id,
159 },
160 control_code,
161 descriptors: DescriptorLoop::new(&bytes[app_desc_start..app_desc_end]),
162 });
163 pos = app_desc_end;
164 }
165
166 Ok(Ait {
167 application_type,
168 test_application_flag,
169 version_number,
170 current_next_indicator,
171 section_number,
172 last_section_number,
173 common_descriptors,
174 applications,
175 })
176 }
177}
178
179impl Serialize for Ait<'_> {
180 type Error = crate::error::Error;
181 fn serialized_len(&self) -> usize {
182 let app_bytes: usize = self
183 .applications
184 .iter()
185 .map(|a| APP_HEADER_LEN + a.descriptors.len())
186 .sum();
187 MIN_HEADER_LEN
188 + EXTENSION_HEADER_LEN
189 + COMMON_DESC_LEN_BYTES
190 + self.common_descriptors.len()
191 + APP_LOOP_LEN_BYTES
192 + app_bytes
193 + CRC_LEN
194 }
195
196 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
197 let len = self.serialized_len();
198 if buf.len() < len {
199 return Err(Error::OutputBufferTooSmall {
200 need: len,
201 have: buf.len(),
202 });
203 }
204
205 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
206 buf[0] = TABLE_ID;
207 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
208 buf[2] = (section_length & 0xFF) as u8;
209 buf[3] = (u8::from(self.test_application_flag) << 7)
210 | ((self.application_type >> 8) as u8 & 0x7F);
211 buf[4] = (self.application_type & 0xFF) as u8;
212 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
213 buf[6] = self.section_number;
214 buf[7] = self.last_section_number;
215
216 let cdl = self.common_descriptors.len() as u16;
217 buf[8] = 0xF0 | ((cdl >> 8) as u8 & 0x0F);
218 buf[9] = (cdl & 0xFF) as u8;
219
220 let common_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + COMMON_DESC_LEN_BYTES;
221 buf[common_desc_start..common_desc_start + self.common_descriptors.len()]
222 .copy_from_slice(self.common_descriptors.raw());
223
224 let app_loop_start = common_desc_start + self.common_descriptors.len();
225 let app_bytes: usize = self
226 .applications
227 .iter()
228 .map(|a| APP_HEADER_LEN + a.descriptors.len())
229 .sum();
230 let apl = app_bytes as u16;
231 buf[app_loop_start] = 0xF0 | ((apl >> 8) as u8 & 0x0F);
232 buf[app_loop_start + 1] = (apl & 0xFF) as u8;
233
234 let mut pos = app_loop_start + APP_LOOP_LEN_BYTES;
235 for app in &self.applications {
236 buf[pos..pos + 4].copy_from_slice(&app.identifier.organisation_id.to_be_bytes());
237 buf[pos + 4..pos + 6].copy_from_slice(&app.identifier.application_id.to_be_bytes());
238 buf[pos + 6] = app.control_code;
239 let adl = app.descriptors.len() as u16;
240 buf[pos + 7] = 0xF0 | ((adl >> 8) as u8 & 0x0F);
241 buf[pos + 8] = (adl & 0xFF) as u8;
242 let desc_start = pos + APP_HEADER_LEN;
243 buf[desc_start..desc_start + app.descriptors.len()]
244 .copy_from_slice(app.descriptors.raw());
245 pos = desc_start + app.descriptors.len();
246 }
247
248 let crc_pos = len - CRC_LEN;
249 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
250 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
251 Ok(len)
252 }
253}
254
255impl<'a> Table<'a> for Ait<'a> {
256 const TABLE_ID: u8 = TABLE_ID;
257 const PID: u16 = PID;
258}
259
260impl<'a> crate::traits::TableDef<'a> for Ait<'a> {
261 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
262 const NAME: &'static str = "APPLICATION_INFORMATION";
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 fn build_ait(
270 application_type: u16,
271 test_flag: bool,
272 version: u8,
273 common_descriptors: &[u8],
274 applications: &[(u32, u16, u8, Vec<u8>)],
275 ) -> Vec<u8> {
276 let app_bytes: usize = applications
277 .iter()
278 .map(|(_, _, _, d)| APP_HEADER_LEN + d.len())
279 .sum();
280 let section_length: u16 = (EXTENSION_HEADER_LEN
281 + COMMON_DESC_LEN_BYTES
282 + common_descriptors.len()
283 + APP_LOOP_LEN_BYTES
284 + app_bytes
285 + CRC_LEN) as u16;
286 let mut v = vec![
287 TABLE_ID,
288 0xB0 | ((section_length >> 8) as u8 & 0x0F),
289 (section_length & 0xFF) as u8,
290 (u8::from(test_flag) << 7) | ((application_type >> 8) as u8 & 0x7F),
291 (application_type & 0xFF) as u8,
292 0xC0 | ((version & 0x1F) << 1) | 0x01,
293 0,
294 0,
295 ];
296 let cdl = common_descriptors.len() as u16;
297 v.push(0xF0 | ((cdl >> 8) as u8 & 0x0F));
298 v.push((cdl & 0xFF) as u8);
299 v.extend_from_slice(common_descriptors);
300 let apl = app_bytes as u16;
301 v.push(0xF0 | ((apl >> 8) as u8 & 0x0F));
302 v.push((apl & 0xFF) as u8);
303 for &(org_id, app_id, cc, ref desc) in applications {
304 v.extend_from_slice(&org_id.to_be_bytes());
305 v.extend_from_slice(&app_id.to_be_bytes());
306 v.push(cc);
307 let adl = desc.len() as u16;
308 v.push(0xF0 | ((adl >> 8) as u8 & 0x0F));
309 v.push((adl & 0xFF) as u8);
310 v.extend_from_slice(desc);
311 }
312 v.extend_from_slice(&[0, 0, 0, 0]);
313 v
314 }
315
316 #[test]
317 fn parse_rejects_wrong_table_id() {
318 let mut bytes = build_ait(0x0010, false, 0, &[], &[]);
319 bytes[0] = 0x00;
320 let err = Ait::parse(&bytes).unwrap_err();
321 assert!(matches!(
322 err,
323 Error::UnexpectedTableId { table_id: 0x00, .. }
324 ));
325 }
326
327 #[test]
328 fn parse_rejects_short_buffer() {
329 let err = Ait::parse(&[0x74, 0x00]).unwrap_err();
330 assert!(matches!(err, Error::BufferTooShort { .. }));
331 }
332
333 #[test]
334 fn parse_empty_ait_no_applications() {
335 let bytes = build_ait(0x0010, false, 5, &[], &[]);
336 let ait = Ait::parse(&bytes).expect("parse");
337 assert_eq!(ait.application_type, 0x0010);
338 assert!(!ait.test_application_flag);
339 assert_eq!(ait.version_number, 5);
340 assert!(ait.current_next_indicator);
341 assert_eq!(ait.section_number, 0);
342 assert_eq!(ait.last_section_number, 0);
343 assert_eq!(ait.common_descriptors.len(), 0);
344 assert_eq!(ait.applications.len(), 0);
345 }
346
347 #[test]
348 fn parse_test_application_flag_extracted() {
349 let bytes = build_ait(0x0010, true, 0, &[], &[]);
350 let ait = Ait::parse(&bytes).unwrap();
351 assert!(ait.test_application_flag);
352 }
353
354 #[test]
355 fn parse_common_descriptors_preserved() {
356 let desc = vec![0x00, 0x02, 0xAA, 0xBB];
357 let bytes = build_ait(0x0010, false, 0, &desc, &[]);
358 let ait = Ait::parse(&bytes).unwrap();
359 assert_eq!(ait.common_descriptors.raw(), &desc[..]);
360 }
361
362 #[test]
363 fn parse_single_application() {
364 let desc = vec![0x02, 0x03, 0xCC, 0xDD, 0xEE];
365 let bytes = build_ait(
366 0x0010,
367 false,
368 0,
369 &[],
370 &[(0x12345678, 0xABCD, 0x01, desc.clone())],
371 );
372 let ait = Ait::parse(&bytes).unwrap();
373 assert_eq!(ait.applications.len(), 1);
374 assert_eq!(ait.applications[0].identifier.organisation_id, 0x12345678);
375 assert_eq!(ait.applications[0].identifier.application_id, 0xABCD);
376 assert_eq!(ait.applications[0].control_code, 0x01);
377 assert_eq!(ait.applications[0].descriptors.raw(), &desc[..]);
378 }
379
380 #[test]
381 fn parse_multiple_applications_preserve_order() {
382 let bytes = build_ait(
383 0x0010,
384 false,
385 0,
386 &[],
387 &[
388 (0x00000001, 0x0001, 0x01, vec![]),
389 (0x00000002, 0x0002, 0x02, vec![0x01]),
390 (0x00000003, 0x0003, 0x03, vec![0x02, 0x03]),
391 ],
392 );
393 let ait = Ait::parse(&bytes).unwrap();
394 assert_eq!(ait.applications.len(), 3);
395 assert_eq!(ait.applications[0].identifier.organisation_id, 1);
396 assert_eq!(ait.applications[1].identifier.organisation_id, 2);
397 assert_eq!(ait.applications[2].identifier.organisation_id, 3);
398 }
399
400 #[test]
401 fn serialize_round_trip_empty() {
402 let ait = Ait {
403 application_type: 0x0010,
404 test_application_flag: false,
405 version_number: 3,
406 current_next_indicator: true,
407 section_number: 0,
408 last_section_number: 0,
409 common_descriptors: DescriptorLoop::new(&[]),
410 applications: vec![],
411 };
412 let mut buf = vec![0u8; ait.serialized_len()];
413 ait.serialize_into(&mut buf).unwrap();
414 let reparsed = Ait::parse(&buf).unwrap();
415 assert_eq!(ait, reparsed);
416 }
417
418 #[test]
419 fn serialize_round_trip_with_applications() {
420 let desc1: [u8; 2] = [0xAA, 0xBB];
421 let ait = Ait {
422 application_type: 0x0010,
423 test_application_flag: true,
424 version_number: 7,
425 current_next_indicator: true,
426 section_number: 1,
427 last_section_number: 2,
428 common_descriptors: DescriptorLoop::new(&[0x01, 0x00]),
429 applications: vec![
430 AitApplication {
431 identifier: ApplicationIdentifier {
432 organisation_id: 0x12345678,
433 application_id: 0xABCD,
434 },
435 control_code: 0x01,
436 descriptors: DescriptorLoop::new(&desc1),
437 },
438 AitApplication {
439 identifier: ApplicationIdentifier {
440 organisation_id: 0x87654321,
441 application_id: 0x00EF,
442 },
443 control_code: 0x02,
444 descriptors: DescriptorLoop::new(&[]),
445 },
446 ],
447 };
448 let mut buf = vec![0u8; ait.serialized_len()];
449 ait.serialize_into(&mut buf).unwrap();
450 let reparsed = Ait::parse(&buf).unwrap();
451 assert_eq!(ait, reparsed);
452 }
453}