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