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