1use super::RunningStatus;
9use crate::descriptors::DescriptorLoop;
10use crate::error::{Error, Result};
11use alloc::vec::Vec;
12use dvb_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 Ok(SdtSection {
164 kind,
165 transport_stream_id,
166 version_number,
167 current_next_indicator,
168 section_number,
169 last_section_number,
170 original_network_id,
171 services,
172 })
173 }
174}
175
176impl Serialize for SdtSection<'_> {
177 type Error = crate::error::Error;
178 fn serialized_len(&self) -> usize {
179 let svc_bytes: usize = self
180 .services
181 .iter()
182 .map(|s| SERVICE_HEADER_LEN + s.descriptors.len())
183 .sum();
184 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + svc_bytes + CRC_LEN
185 }
186
187 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
188 let len = self.serialized_len();
189 if buf.len() < len {
190 return Err(Error::OutputBufferTooSmall {
191 need: len,
192 have: buf.len(),
193 });
194 }
195 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
196 buf[0] = match self.kind {
197 SdtKind::Actual => TABLE_ID_ACTUAL,
198 SdtKind::Other => TABLE_ID_OTHER,
199 };
200 buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
201 buf[2] = (section_length & 0xFF) as u8;
202 buf[3..5].copy_from_slice(&self.transport_stream_id.to_be_bytes());
203 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
204 buf[6] = self.section_number;
205 buf[7] = self.last_section_number;
206 buf[8..10].copy_from_slice(&self.original_network_id.to_be_bytes());
207 buf[10] = 0xFF; let mut pos = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
210 for svc in &self.services {
211 buf[pos..pos + 2].copy_from_slice(&svc.service_id.to_be_bytes());
212 let flags = 0xFC
213 | (u8::from(svc.eit_schedule_flag) << 1)
214 | u8::from(svc.eit_present_following_flag);
215 buf[pos + 2] = flags;
216 let dll = svc.descriptors.len() as u16;
217 buf[pos + 3] = (svc.running_status.to_u8() << 5)
218 | (u8::from(svc.free_ca_mode) << 4)
219 | ((dll >> 8) as u8 & 0x0F);
220 buf[pos + 4] = (dll & 0xFF) as u8;
221 let desc_start = pos + SERVICE_HEADER_LEN;
222 buf[desc_start..desc_start + svc.descriptors.len()]
223 .copy_from_slice(svc.descriptors.raw());
224 pos = desc_start + svc.descriptors.len();
225 }
226
227 let crc_pos = len - CRC_LEN;
228 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
229 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
230 Ok(len)
231 }
232}
233impl<'a> crate::traits::TableDef<'a> for SdtSection<'a> {
234 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[
235 (TABLE_ID_ACTUAL, TABLE_ID_ACTUAL),
236 (TABLE_ID_OTHER, TABLE_ID_OTHER),
237 ];
238 const NAME: &'static str = "SERVICE_DESCRIPTION";
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 type TestService = (u16, bool, bool, u8, bool, Vec<u8>);
246
247 fn build_sdt(
248 kind: SdtKind,
249 tsid: u16,
250 version: u8,
251 original_network_id: u16,
252 services: &[TestService],
253 ) -> Vec<u8> {
254 let svc_bytes: usize = services
255 .iter()
256 .map(|(_, _, _, _, _, d)| SERVICE_HEADER_LEN + d.len())
257 .sum();
258 let section_length: u16 =
259 (EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + svc_bytes + CRC_LEN) as u16;
260 let mut v = Vec::new();
261 v.push(match kind {
262 SdtKind::Actual => TABLE_ID_ACTUAL,
263 SdtKind::Other => TABLE_ID_OTHER,
264 });
265 v.push(super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F));
266 v.push((section_length & 0xFF) as u8);
267 v.extend_from_slice(&tsid.to_be_bytes());
268 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
269 v.push(0);
270 v.push(0);
271 v.extend_from_slice(&original_network_id.to_be_bytes());
272 v.push(0xFF);
273 for (sid, eit_s, eit_pf, rs, fca, desc) in services {
274 v.extend_from_slice(&sid.to_be_bytes());
275 let flags = 0xFC | (u8::from(*eit_s) << 1) | u8::from(*eit_pf);
276 v.push(flags);
277 let dll = desc.len() as u16;
278 v.push(((*rs & 0x07) << 5) | (u8::from(*fca) << 4) | ((dll >> 8) as u8 & 0x0F));
279 v.push((dll & 0xFF) as u8);
280 v.extend_from_slice(desc);
281 }
282 v.extend_from_slice(&[0, 0, 0, 0]);
283 v
284 }
285
286 #[test]
287 fn parse_actual_and_other_tables_distinguished_by_table_id() {
288 let a = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
289 let o = build_sdt(SdtKind::Other, 1, 0, 0x20, &[]);
290 assert!(matches!(
291 SdtSection::parse(&a).unwrap().kind,
292 SdtKind::Actual
293 ));
294 assert!(matches!(
295 SdtSection::parse(&o).unwrap().kind,
296 SdtKind::Other
297 ));
298 }
299
300 #[test]
301 fn parse_services_with_descriptor_bytes() {
302 let bytes = build_sdt(
303 SdtKind::Actual,
304 1,
305 0,
306 0x20,
307 &[(
308 100,
309 true,
310 true,
311 4,
312 false,
313 vec![0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05],
314 )],
315 );
316 let sdt = SdtSection::parse(&bytes).unwrap();
317 assert_eq!(sdt.services.len(), 1);
318 assert_eq!(sdt.services[0].service_id, 100);
319 assert!(sdt.services[0].eit_schedule_flag);
320 assert!(sdt.services[0].eit_present_following_flag);
321 assert_eq!(sdt.services[0].running_status, RunningStatus::Running);
322 assert!(!sdt.services[0].free_ca_mode);
323 assert_eq!(
324 sdt.services[0].descriptors.raw(),
325 &[0x48, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05][..]
326 );
327 }
328
329 #[test]
330 fn service_free_ca_mode_flag_extracted() {
331 let bytes = build_sdt(
332 SdtKind::Actual,
333 1,
334 0,
335 0x20,
336 &[(1, false, false, 0, true, vec![])],
337 );
338 let sdt = SdtSection::parse(&bytes).unwrap();
339 assert!(sdt.services[0].free_ca_mode);
340 }
341
342 #[test]
343 fn service_running_status_extracted() {
344 let bytes = build_sdt(
345 SdtKind::Actual,
346 1,
347 0,
348 0x20,
349 &[(1, false, false, 2, false, vec![])],
350 );
351 let sdt = SdtSection::parse(&bytes).unwrap();
352 assert_eq!(
353 sdt.services[0].running_status,
354 RunningStatus::StartsInAFewSeconds
355 );
356 }
357
358 #[test]
359 fn parse_rejects_short_buffer() {
360 let err = SdtSection::parse(&[0x42, 0x00]).unwrap_err();
361 assert!(matches!(err, Error::BufferTooShort { .. }));
362 }
363
364 #[test]
365 fn parse_rejects_wrong_table_id() {
366 let mut bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
367 bytes[0] = 0x00;
368 let err = SdtSection::parse(&bytes).unwrap_err();
369 assert!(matches!(
370 err,
371 Error::UnexpectedTableId { table_id: 0x00, .. }
372 ));
373 }
374
375 #[test]
376 fn serialize_round_trip() {
377 let desc1: [u8; 4] = [0x48, 0x02, 0xAA, 0xBB];
378 let sdt = SdtSection {
379 kind: SdtKind::Actual,
380 transport_stream_id: 0x1234,
381 version_number: 5,
382 current_next_indicator: true,
383 section_number: 0,
384 last_section_number: 0,
385 original_network_id: 0x0020,
386 services: vec![
387 SdtService {
388 service_id: 100,
389 eit_schedule_flag: true,
390 eit_present_following_flag: false,
391 running_status: RunningStatus::Running,
392 free_ca_mode: false,
393 descriptors: DescriptorLoop::new(&desc1),
394 },
395 SdtService {
396 service_id: 101,
397 eit_schedule_flag: false,
398 eit_present_following_flag: true,
399 running_status: RunningStatus::StartsInAFewSeconds,
400 free_ca_mode: true,
401 descriptors: DescriptorLoop::new(&[]),
402 },
403 ],
404 };
405 let mut buf = vec![0u8; sdt.serialized_len()];
406 sdt.serialize_into(&mut buf).unwrap();
407 let re = SdtSection::parse(&buf).unwrap();
408 assert_eq!(sdt, re);
409 }
410
411 #[test]
412 fn zero_services_is_valid() {
413 let bytes = build_sdt(SdtKind::Actual, 1, 0, 0x20, &[]);
414 let sdt = SdtSection::parse(&bytes).unwrap();
415 assert_eq!(sdt.services.len(), 0);
416 }
417
418 #[test]
419 fn parse_rejects_zero_section_length() {
420 let mut buf = vec![0u8; 64];
421 buf[0] = TABLE_ID_ACTUAL;
422 buf[1] = 0xF0;
423 buf[2] = 0x00;
424 for b in &mut buf[3..] {
425 *b = 0xFF;
426 }
427 assert!(matches!(
428 SdtSection::parse(&buf).unwrap_err(),
429 Error::SectionLengthOverflow { .. }
430 ));
431 }
432}