1use super::RunningStatus;
9use crate::descriptors::DescriptorLoop;
10use crate::error::{Error, Result};
11use alloc::vec::Vec;
12use broadcast_common::{Parse, Serialize};
13
14pub const TABLE_ID_ACTUAL: u8 = 0x42;
16pub const TABLE_ID_OTHER: u8 = 0x46;
18pub const PID: u16 = 0x0011;
20
21const MIN_HEADER_LEN: usize = 3;
22const EXTENSION_HEADER_LEN: usize = 5;
23const POST_EXTENSION_LEN: usize = 3;
26const CRC_LEN: usize = 4;
27const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
28const SERVICE_HEADER_LEN: usize = 5;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize))]
33#[non_exhaustive]
34pub enum SdtKind {
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 SdtService<'a> {
46 pub service_id: u16,
48 pub eit_schedule_flag: bool,
50 pub eit_present_following_flag: bool,
52 pub running_status: RunningStatus,
54 pub free_ca_mode: bool,
56 pub descriptors: DescriptorLoop<'a>,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63#[cfg_attr(feature = "serde", derive(serde::Serialize))]
64#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
65pub struct SdtSection<'a> {
66 pub kind: SdtKind,
68 pub transport_stream_id: u16,
70 pub version_number: u8,
72 pub current_next_indicator: bool,
74 pub section_number: u8,
76 pub last_section_number: u8,
78 pub original_network_id: u16,
80 pub services: Vec<SdtService<'a>>,
82}
83
84impl<'a> Parse<'a> for SdtSection<'a> {
85 type Error = crate::error::Error;
86 fn parse(bytes: &'a [u8]) -> Result<Self> {
87 let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
88 if bytes.len() < min_len {
89 return Err(Error::BufferTooShort {
90 need: min_len,
91 have: bytes.len(),
92 what: "SdtSection",
93 });
94 }
95 let kind = match bytes[0] {
96 TABLE_ID_ACTUAL => SdtKind::Actual,
97 TABLE_ID_OTHER => SdtKind::Other,
98 other => {
99 return Err(Error::UnexpectedTableId {
100 table_id: other,
101 what: "SdtSection",
102 expected: &[TABLE_ID_ACTUAL, TABLE_ID_OTHER],
103 });
104 }
105 };
106
107 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
108 let total = super::check_section_length(
109 bytes.len(),
110 MIN_HEADER_LEN,
111 section_length as usize,
112 MIN_SECTION_LEN,
113 )?;
114
115 let transport_stream_id = u16::from_be_bytes(*bytes[3..].first_chunk::<2>().unwrap());
116 let version_number = (bytes[5] >> 1) & 0x1F;
117 let current_next_indicator = (bytes[5] & 0x01) != 0;
118 let section_number = bytes[6];
119 let last_section_number = bytes[7];
120 let original_network_id = u16::from_be_bytes(*bytes[8..].first_chunk::<2>().unwrap());
121
122 let services_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
123 let services_end = total - CRC_LEN;
124 let mut services = Vec::new();
125 let mut pos = services_start;
126 while pos + SERVICE_HEADER_LEN <= services_end {
127 let (b2, _) = bytes
128 .get(pos..)
129 .and_then(|s| s.split_first_chunk::<2>())
130 .ok_or(Error::BufferTooShort {
131 need: pos + 2,
132 have: services_end,
133 what: "SdtSection service_id",
134 })?;
135 let service_id = u16::from_be_bytes(*b2);
136 let flags = bytes[pos + 2];
137 let eit_schedule_flag = (flags & 0x02) != 0;
138 let eit_present_following_flag = (flags & 0x01) != 0;
139 let status_and_len_hi = bytes[pos + 3];
140 let running_status = RunningStatus::from_u8((status_and_len_hi >> 5) & 0x07);
141 let free_ca_mode = (status_and_len_hi & 0x10) != 0;
142 let descriptors_loop_length =
143 (((status_and_len_hi & 0x0F) as usize) << 8) | bytes[pos + 4] as usize;
144 let desc_start = pos + SERVICE_HEADER_LEN;
145 let desc_end = desc_start + descriptors_loop_length;
146 if desc_end > services_end {
147 return Err(Error::SectionLengthOverflow {
148 declared: descriptors_loop_length,
149 available: services_end.saturating_sub(desc_start),
150 });
151 }
152 services.push(SdtService {
153 service_id,
154 eit_schedule_flag,
155 eit_present_following_flag,
156 running_status,
157 free_ca_mode,
158 descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
159 });
160 pos = desc_end;
161 }
162
163 if pos != services_end {
164 return Err(Error::BufferTooShort {
165 need: services_end - pos,
166 have: 0,
167 what: "SdtSection trailing service bytes",
168 });
169 }
170
171 Ok(SdtSection {
172 kind,
173 transport_stream_id,
174 version_number,
175 current_next_indicator,
176 section_number,
177 last_section_number,
178 original_network_id,
179 services,
180 })
181 }
182}
183
184impl Serialize for SdtSection<'_> {
185 type Error = crate::error::Error;
186 fn serialized_len(&self) -> usize {
187 let svc_bytes: usize = self
188 .services
189 .iter()
190 .map(|s| SERVICE_HEADER_LEN + s.descriptors.len())
191 .sum();
192 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + svc_bytes + CRC_LEN
193 }
194
195 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
196 let len = self.serialized_len();
197 if buf.len() < len {
198 return Err(Error::OutputBufferTooSmall {
199 need: len,
200 have: buf.len(),
201 });
202 }
203 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
204 buf[0] = match self.kind {
205 SdtKind::Actual => TABLE_ID_ACTUAL,
206 SdtKind::Other => TABLE_ID_OTHER,
207 };
208 buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
209 buf[2] = (section_length & 0xFF) as u8;
210 buf[3..5].copy_from_slice(&self.transport_stream_id.to_be_bytes());
211 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
212 buf[6] = self.section_number;
213 buf[7] = self.last_section_number;
214 buf[8..10].copy_from_slice(&self.original_network_id.to_be_bytes());
215 buf[10] = 0xFF; let mut pos = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
218 for svc in &self.services {
219 buf[pos..pos + 2].copy_from_slice(&svc.service_id.to_be_bytes());
220 let flags = 0xFC
221 | (u8::from(svc.eit_schedule_flag) << 1)
222 | u8::from(svc.eit_present_following_flag);
223 buf[pos + 2] = flags;
224 let dll = svc.descriptors.len() as u16;
225 buf[pos + 3] = (svc.running_status.to_u8() << 5)
226 | (u8::from(svc.free_ca_mode) << 4)
227 | ((dll >> 8) as u8 & 0x0F);
228 buf[pos + 4] = (dll & 0xFF) as u8;
229 let desc_start = pos + SERVICE_HEADER_LEN;
230 buf[desc_start..desc_start + svc.descriptors.len()]
231 .copy_from_slice(svc.descriptors.raw());
232 pos = desc_start + svc.descriptors.len();
233 }
234
235 let crc_pos = len - CRC_LEN;
236 let crc = broadcast_common::crc32_mpeg2::compute(&buf[..crc_pos]);
237 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
238 Ok(len)
239 }
240}
241impl<'a> crate::traits::TableDef<'a> for SdtSection<'a> {
242 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[
243 (TABLE_ID_ACTUAL, TABLE_ID_ACTUAL),
244 (TABLE_ID_OTHER, TABLE_ID_OTHER),
245 ];
246 const NAME: &'static str = "SERVICE_DESCRIPTION";
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 type TestService = (u16, bool, bool, u8, bool, Vec<u8>);
254
255 fn build_sdt(
256 kind: SdtKind,
257 tsid: u16,
258 version: u8,
259 original_network_id: u16,
260 services: &[TestService],
261 ) -> Vec<u8> {
262 let svc_bytes: usize = services
263 .iter()
264 .map(|(_, _, _, _, _, d)| SERVICE_HEADER_LEN + d.len())
265 .sum();
266 let section_length: u16 =
267 (EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + svc_bytes + CRC_LEN) as u16;
268 let mut v = Vec::new();
269 v.push(match kind {
270 SdtKind::Actual => TABLE_ID_ACTUAL,
271 SdtKind::Other => TABLE_ID_OTHER,
272 });
273 v.push(super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F));
274 v.push((section_length & 0xFF) as u8);
275 v.extend_from_slice(&tsid.to_be_bytes());
276 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
277 v.push(0);
278 v.push(0);
279 v.extend_from_slice(&original_network_id.to_be_bytes());
280 v.push(0xFF);
281 for (sid, eit_s, eit_pf, rs, fca, desc) in services {
282 v.extend_from_slice(&sid.to_be_bytes());
283 let flags = 0xFC | (u8::from(*eit_s) << 1) | u8::from(*eit_pf);
284 v.push(flags);
285 let dll = desc.len() as u16;
286 v.push(((*rs & 0x07) << 5) | (u8::from(*fca) << 4) | ((dll >> 8) as u8 & 0x0F));
287 v.push((dll & 0xFF) as u8);
288 v.extend_from_slice(desc);
289 }
290 v.extend_from_slice(&[0, 0, 0, 0]);
291 v
292 }
293
294 #[test]
295 fn parse_actual_and_other_tables_distinguished_by_table_id() {
296 let a = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
297 let o = build_sdt(SdtKind::Other, 1, 0, 0x20, &[]);
298 assert!(matches!(
299 SdtSection::parse(&a).unwrap().kind,
300 SdtKind::Actual
301 ));
302 assert!(matches!(
303 SdtSection::parse(&o).unwrap().kind,
304 SdtKind::Other
305 ));
306 }
307
308 #[test]
309 fn parse_services_with_descriptor_bytes() {
310 let bytes = build_sdt(
311 SdtKind::Actual,
312 1,
313 0,
314 0x20,
315 &[(
316 100,
317 true,
318 true,
319 4,
320 false,
321 vec![0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05],
322 )],
323 );
324 let sdt = SdtSection::parse(&bytes).unwrap();
325 assert_eq!(sdt.services.len(), 1);
326 assert_eq!(sdt.services[0].service_id, 100);
327 assert!(sdt.services[0].eit_schedule_flag);
328 assert!(sdt.services[0].eit_present_following_flag);
329 assert_eq!(sdt.services[0].running_status, RunningStatus::Running);
330 assert!(!sdt.services[0].free_ca_mode);
331 assert_eq!(
332 sdt.services[0].descriptors.raw(),
333 &[0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05][..]
334 );
335 }
336
337 #[test]
338 fn service_free_ca_mode_flag_extracted() {
339 let bytes = build_sdt(
340 SdtKind::Actual,
341 1,
342 0,
343 0x20,
344 &[(1, false, false, 0, true, vec![])],
345 );
346 let sdt = SdtSection::parse(&bytes).unwrap();
347 assert!(sdt.services[0].free_ca_mode);
348 }
349
350 #[test]
351 fn service_running_status_extracted() {
352 let bytes = build_sdt(
353 SdtKind::Actual,
354 1,
355 0,
356 0x20,
357 &[(1, false, false, 2, false, vec![])],
358 );
359 let sdt = SdtSection::parse(&bytes).unwrap();
360 assert_eq!(
361 sdt.services[0].running_status,
362 RunningStatus::StartsInAFewSeconds
363 );
364 }
365
366 #[test]
367 fn parse_rejects_short_buffer() {
368 let err = SdtSection::parse(&[0x42, 0x00]).unwrap_err();
369 assert!(matches!(err, Error::BufferTooShort { .. }));
370 }
371
372 #[test]
373 fn parse_rejects_wrong_table_id() {
374 let mut bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
375 bytes[0] = 0x00;
376 let err = SdtSection::parse(&bytes).unwrap_err();
377 assert!(matches!(
378 err,
379 Error::UnexpectedTableId { table_id: 0x00, .. }
380 ));
381 }
382
383 #[test]
384 fn serialize_round_trip() {
385 let desc1: [u8; 4] = [0x48, 0x02, 0xAA, 0xBB];
386 let sdt = SdtSection {
387 kind: SdtKind::Actual,
388 transport_stream_id: 0x1234,
389 version_number: 5,
390 current_next_indicator: true,
391 section_number: 0,
392 last_section_number: 0,
393 original_network_id: 0x0020,
394 services: vec![
395 SdtService {
396 service_id: 100,
397 eit_schedule_flag: true,
398 eit_present_following_flag: false,
399 running_status: RunningStatus::Running,
400 free_ca_mode: false,
401 descriptors: DescriptorLoop::new(&desc1),
402 },
403 SdtService {
404 service_id: 101,
405 eit_schedule_flag: false,
406 eit_present_following_flag: true,
407 running_status: RunningStatus::StartsInAFewSeconds,
408 free_ca_mode: true,
409 descriptors: DescriptorLoop::new(&[]),
410 },
411 ],
412 };
413 let mut buf = vec![0u8; sdt.serialized_len()];
414 sdt.serialize_into(&mut buf).unwrap();
415 let re = SdtSection::parse(&buf).unwrap();
416 assert_eq!(sdt, re);
417 }
418
419 #[test]
420 fn zero_services_is_valid() {
421 let bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
422 let sdt = SdtSection::parse(&bytes).unwrap();
423 assert_eq!(sdt.services.len(), 0);
424 }
425
426 #[test]
427 fn parse_rejects_zero_section_length() {
428 let mut buf = vec![0u8; 64];
429 buf[0] = TABLE_ID_ACTUAL;
430 buf[1] = 0xF0;
431 buf[2] = 0x00;
432 for b in &mut buf[3..] {
433 *b = 0xFF;
434 }
435 assert!(matches!(
436 SdtSection::parse(&buf).unwrap_err(),
437 Error::SectionLengthOverflow { .. }
438 ));
439 }
440
441 #[test]
442 fn parse_rejects_trailing_slack_bytes() {
443 let mut bytes = build_sdt(
448 SdtKind::Actual,
449 1,
450 0,
451 0x20,
452 &[(1, false, false, 0, false, vec![])],
453 );
454 let sl = (bytes.len() - MIN_HEADER_LEN) as u16 + 2;
455 bytes[1] = (bytes[1] & 0xF0) | ((sl >> 8) as u8 & 0x0F);
456 bytes[2] = (sl & 0xFF) as u8;
457 let crc_pos = bytes.len() - CRC_LEN;
458 bytes.splice(crc_pos..crc_pos, [0xFF, 0xFF]);
459 let err = SdtSection::parse(&bytes).unwrap_err();
460 assert!(matches!(
461 err,
462 Error::BufferTooShort {
463 what: "SdtSection trailing service bytes",
464 ..
465 }
466 ));
467 }
468
469 #[test]
470 fn parse_accepts_well_formed_service_loop_with_no_slack() {
471 let bytes = build_sdt(
472 SdtKind::Actual,
473 1,
474 0,
475 0x20,
476 &[
477 (1, false, false, 0, false, vec![]),
478 (2, true, true, 4, false, vec![0x48, 0x02, 0xAA, 0xBB]),
479 ],
480 );
481 let sdt = SdtSection::parse(&bytes).unwrap();
482 assert_eq!(sdt.services.len(), 2);
483 }
484}