1use crate::descriptors::DescriptorLoop;
7use crate::error::{Error, Result};
8use crate::traits::Table;
9use dvb_common::{Parse, Serialize};
10
11pub const TABLE_ID: u8 = 0x03;
13pub const PID: u16 = 0x0002;
15
16const MIN_HEADER_LEN: usize = 3;
17const EXTENSION_HEADER_LEN: usize = 5;
18const CRC_LEN: usize = 4;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize))]
23pub struct Tsdt<'a> {
24 pub table_id_extension: u16,
26 pub version_number: u8,
28 pub current_next_indicator: bool,
30 pub section_number: u8,
32 pub last_section_number: u8,
34 pub descriptors: DescriptorLoop<'a>,
37}
38
39impl<'a> Parse<'a> for Tsdt<'a> {
40 type Error = crate::error::Error;
41
42 fn parse(bytes: &'a [u8]) -> Result<Self> {
43 let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
44 if bytes.len() < min_len {
45 return Err(Error::BufferTooShort {
46 need: min_len,
47 have: bytes.len(),
48 what: "Tsdt",
49 });
50 }
51
52 if bytes[0] != TABLE_ID {
53 return Err(Error::UnexpectedTableId {
54 table_id: bytes[0],
55 what: "Tsdt",
56 expected: &[TABLE_ID],
57 });
58 }
59
60 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
61 let total = MIN_HEADER_LEN + section_length as usize;
62 if bytes.len() < total {
63 return Err(Error::SectionLengthOverflow {
64 declared: section_length as usize,
65 available: bytes.len() - MIN_HEADER_LEN,
66 });
67 }
68
69 let table_id_extension = u16::from_be_bytes([bytes[3], bytes[4]]);
70 let version_number = (bytes[5] >> 1) & 0x1F;
71 let current_next_indicator = (bytes[5] & 0x01) != 0;
72 let section_number = bytes[6];
73 let last_section_number = bytes[7];
74
75 let desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
78 let desc_end = total - CRC_LEN;
79
80 Ok(Tsdt {
81 table_id_extension,
82 version_number,
83 current_next_indicator,
84 section_number,
85 last_section_number,
86 descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
87 })
88 }
89}
90
91impl Serialize for Tsdt<'_> {
92 type Error = crate::error::Error;
93
94 fn serialized_len(&self) -> usize {
95 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.descriptors.len() + CRC_LEN
96 }
97
98 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
99 let len = self.serialized_len();
100 if buf.len() < len {
101 return Err(Error::OutputBufferTooSmall {
102 need: len,
103 have: buf.len(),
104 });
105 }
106
107 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
108 buf[0] = TABLE_ID;
109 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
110 buf[2] = (section_length & 0xFF) as u8;
111 buf[3..5].copy_from_slice(&self.table_id_extension.to_be_bytes());
112 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
113 buf[6] = self.section_number;
114 buf[7] = self.last_section_number;
115
116 let desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
117 buf[desc_start..desc_start + self.descriptors.len()]
118 .copy_from_slice(self.descriptors.raw());
119
120 let crc_pos = len - CRC_LEN;
121 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
122 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
123
124 Ok(len)
125 }
126}
127
128impl<'a> Table<'a> for Tsdt<'a> {
129 const TABLE_ID: u8 = TABLE_ID;
130 const PID: u16 = PID;
131}
132
133impl<'a> crate::traits::TableDef<'a> for Tsdt<'a> {
134 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
135 const NAME: &'static str = "TRANSPORT_STREAM_DESCRIPTION";
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 fn build_tsdt(table_id_extension: u16, version: u8, descriptors: &[u8]) -> Vec<u8> {
143 let section_length: u16 = (EXTENSION_HEADER_LEN + descriptors.len() + CRC_LEN) as u16;
144 let mut v = Vec::new();
145 v.push(TABLE_ID);
146 v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
147 v.push((section_length & 0xFF) as u8);
148 v.extend_from_slice(&table_id_extension.to_be_bytes());
149 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
150 v.push(0x00);
151 v.push(0x00);
152 v.extend_from_slice(descriptors);
153 v.extend_from_slice(&[0, 0, 0, 0]);
154 v
155 }
156
157 #[test]
158 fn parse_rejects_wrong_tag() {
159 let mut bytes = build_tsdt(0x1234, 5, &[]);
160 bytes[0] = 0x02;
161 assert!(matches!(
162 Tsdt::parse(&bytes).unwrap_err(),
163 Error::UnexpectedTableId { table_id: 0x02, .. }
164 ));
165 }
166
167 #[test]
168 fn parse_rejects_short_buffer() {
169 let err = Tsdt::parse(&[0x03, 0xB0]).unwrap_err();
170 assert!(matches!(err, Error::BufferTooShort { .. }));
171 }
172
173 #[test]
174 fn parse_empty_descriptor_loop() {
175 let bytes = build_tsdt(0x1234, 5, &[]);
176 let tsdt = Tsdt::parse(&bytes).unwrap();
177 assert_eq!(tsdt.table_id_extension, 0x1234);
178 assert_eq!(tsdt.version_number, 5);
179 assert!(tsdt.current_next_indicator);
180 assert_eq!(tsdt.section_number, 0);
181 assert_eq!(tsdt.last_section_number, 0);
182 assert!(tsdt.descriptors.is_empty());
183 }
184
185 #[test]
186 fn parse_with_descriptors() {
187 let descriptors = [0x01, 0x03, 0xAA, 0xBB, 0xCC];
188 let bytes = build_tsdt(0xABCD, 7, &descriptors);
189 let tsdt = Tsdt::parse(&bytes).unwrap();
190 assert_eq!(tsdt.table_id_extension, 0xABCD);
191 assert_eq!(tsdt.version_number, 7);
192 assert_eq!(tsdt.descriptors.raw(), &descriptors[..]);
193 }
194
195 #[test]
196 fn serialize_round_trip() {
197 let descriptors = [0x4D, 0x02, 0x01, 0x02];
198 let bytes = build_tsdt(0xCAFE, 3, &descriptors);
199 let tsdt = Tsdt::parse(&bytes).unwrap();
200 let mut buf = vec![0u8; tsdt.serialized_len()];
201 tsdt.serialize_into(&mut buf).unwrap();
202 let re = Tsdt::parse(&buf).unwrap();
203 assert_eq!(tsdt, re);
204 }
205
206 #[test]
207 fn serialize_round_trip_empty() {
208 let bytes = build_tsdt(0x0001, 0, &[]);
209 let tsdt = Tsdt::parse(&bytes).unwrap();
210 let mut buf = vec![0u8; tsdt.serialized_len()];
211 tsdt.serialize_into(&mut buf).unwrap();
212 let re = Tsdt::parse(&buf).unwrap();
213 assert_eq!(tsdt, re);
214 }
215
216 #[test]
217 fn table_trait_constants() {
218 assert_eq!(<Tsdt<'_> as Table>::TABLE_ID, 0x03);
219 assert_eq!(<Tsdt<'_> as Table>::PID, 0x0002);
220 }
221
222 #[cfg(feature = "serde")]
223 #[test]
224 fn tsdt_serializes_typed_loop() {
225 let descriptors = [0x4D, 0x02, b'e', b'n']; let bytes = build_tsdt(0xDEAD, 9, &descriptors);
229 let tsdt = Tsdt::parse(&bytes).unwrap();
230 let v = serde_json::to_value(&tsdt).unwrap();
231 assert!(
232 v["descriptors"].is_array(),
233 "descriptors must serialize as a typed sequence, got {v}"
234 );
235 }
236}