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