1use crate::descriptors::ca::CaDescriptor;
11use crate::error::{Error, Result};
12use crate::traits::Table;
13use dvb_common::{Parse, Serialize};
14
15pub const TABLE_ID: u8 = 0x01;
17pub const PID: u16 = 0x0001;
19
20const MIN_HEADER_LEN: usize = 3;
21const EXTENSION_HEADER_LEN: usize = 5;
22const CRC_LEN: usize = 4;
23
24#[derive(Debug, Clone, PartialEq, Eq, Default)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28pub struct CatCaEntry {
29 pub ca_system_id: u16,
32 pub ca_pid: u16,
34 pub private_data: Vec<u8>,
36}
37
38#[derive(Debug, Clone, Default, PartialEq, Eq)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
41pub struct Cat {
42 pub version_number: u8,
44 pub current_next_indicator: bool,
46 pub section_number: u8,
48 pub last_section_number: u8,
50 pub descriptors: Vec<u8>,
55}
56
57impl Cat {
58 #[must_use]
62 pub fn ca_descriptors(&self) -> Vec<CatCaEntry> {
63 let mut out = Vec::new();
64 let mut pos = 0;
65 while pos + 2 <= self.descriptors.len() {
66 let tag = self.descriptors[pos];
67 let length = self.descriptors[pos + 1] as usize;
68 let end = pos + 2 + length;
69 if end > self.descriptors.len() {
70 break;
71 }
72 if tag == crate::descriptors::ca::TAG {
73 if let Ok(ca) = CaDescriptor::parse(&self.descriptors[pos..end]) {
74 out.push(CatCaEntry {
75 ca_system_id: ca.ca_system_id,
76 ca_pid: ca.ca_pid,
77 private_data: ca.private_data.to_vec(),
78 });
79 }
80 }
81 pos = end;
82 }
83 out
84 }
85}
86
87impl<'a> Parse<'a> for Cat {
88 type Error = Error;
89
90 fn parse(bytes: &'a [u8]) -> Result<Self> {
91 if bytes.len() < MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN {
92 return Err(Error::BufferTooShort {
93 need: MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN,
94 have: bytes.len(),
95 what: "Cat",
96 });
97 }
98
99 if bytes[0] != TABLE_ID {
100 return Err(Error::UnexpectedTableId {
101 table_id: bytes[0],
102 what: "Cat",
103 expected: &[TABLE_ID],
104 });
105 }
106
107 let section_length = (((bytes[1] & 0x0F) as u16) << 8) | bytes[2] as u16;
108 let total = MIN_HEADER_LEN + section_length as usize;
109 if bytes.len() < total {
110 return Err(Error::SectionLengthOverflow {
111 declared: section_length as usize,
112 available: bytes.len() - MIN_HEADER_LEN,
113 });
114 }
115
116 let version_number = (bytes[5] >> 1) & 0x1F;
120 let current_next_indicator = (bytes[5] & 0x01) != 0;
121 let section_number = bytes[6];
122 let last_section_number = bytes[7];
123
124 let descriptors_end = total - CRC_LEN;
127
128 Ok(Cat {
129 version_number,
130 current_next_indicator,
131 section_number,
132 last_section_number,
133 descriptors: bytes[8..descriptors_end].to_vec(),
134 })
135 }
136}
137
138impl Serialize for Cat {
139 type Error = Error;
140
141 fn serialized_len(&self) -> usize {
142 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.descriptors.len() + CRC_LEN
143 }
144
145 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
146 let len = self.serialized_len();
147 if buf.len() < len {
148 return Err(Error::OutputBufferTooSmall {
149 need: len,
150 have: buf.len(),
151 });
152 }
153 let section_length = (len - MIN_HEADER_LEN) as u16;
154 buf[0] = TABLE_ID;
155 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
156 buf[2] = (section_length & 0xFF) as u8;
157 buf[3] = 0xFF;
159 buf[4] = 0xFF;
160 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
161 buf[6] = self.section_number;
162 buf[7] = self.last_section_number;
163 let desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
164 buf[desc_start..desc_start + self.descriptors.len()].copy_from_slice(&self.descriptors);
165 let crc_pos = len - CRC_LEN;
166 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
167 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
168 Ok(len)
169 }
170}
171
172impl<'a> Table<'a> for Cat {
173 const TABLE_ID: u8 = TABLE_ID;
174 const PID: u16 = PID;
175}
176
177impl<'a> crate::traits::TableDef<'a> for Cat {
178 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
179 const NAME: &'static str = "CONDITIONAL_ACCESS";
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 fn build_cat(version: u8, descriptors: &[u8]) -> Vec<u8> {
188 let section_length: u16 =
189 (EXTENSION_HEADER_LEN as u16) + descriptors.len() as u16 + (CRC_LEN as u16);
190 let mut v = Vec::new();
191 v.push(TABLE_ID);
192 v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
193 v.push((section_length & 0xFF) as u8);
194 v.extend_from_slice(&[0xFF, 0xFF]);
196 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01); v.push(0x00); v.push(0x00); v.extend_from_slice(descriptors);
200 v.extend_from_slice(&[0, 0, 0, 0]); v
202 }
203
204 fn ca_descriptor(ca_system_id: u16, ca_pid: u16) -> [u8; 6] {
205 [
206 0x09,
207 0x04,
208 (ca_system_id >> 8) as u8,
209 (ca_system_id & 0xFF) as u8,
210 0xE0 | ((ca_pid >> 8) as u8 & 0x1F),
211 (ca_pid & 0xFF) as u8,
212 ]
213 }
214
215 #[test]
216 fn parse_empty_cat_zero_descriptors() {
217 let bytes = build_cat(5, &[]);
218 let cat = Cat::parse(&bytes).expect("parse");
219 assert_eq!(cat.version_number, 5);
220 assert!(cat.current_next_indicator);
221 assert!(cat.descriptors.is_empty());
222 assert_eq!(cat.ca_descriptors().len(), 0);
223 }
224
225 #[test]
226 fn parse_single_ca_descriptor_extracts_caid_and_pid() {
227 let mut desc = Vec::new();
228 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
229 let bytes = build_cat(0, &desc);
230 let cat = Cat::parse(&bytes).unwrap();
231 let cas = cat.ca_descriptors();
232 assert_eq!(cas.len(), 1);
233 assert_eq!(cas[0].ca_system_id, 0x0500);
234 assert_eq!(cas[0].ca_pid, 0x0050);
235 assert!(cas[0].private_data.is_empty());
236 }
237
238 #[test]
239 fn parse_multiple_ca_descriptors_preserves_order() {
240 let mut desc = Vec::new();
241 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
242 desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
243 desc.extend_from_slice(&ca_descriptor(0x0100, 0x0080));
244 let bytes = build_cat(2, &desc);
245 let cat = Cat::parse(&bytes).unwrap();
246 let cas = cat.ca_descriptors();
247 assert_eq!(cas.len(), 3);
248 assert_eq!(cas[0].ca_system_id, 0x0500);
249 assert_eq!(cas[1].ca_system_id, 0x0650);
250 assert_eq!(cas[2].ca_system_id, 0x0100);
251 assert_eq!(cas[1].ca_pid, 0x0062);
252 }
253
254 #[test]
255 fn parse_rejects_wrong_table_id() {
256 let mut bytes = build_cat(0, &[]);
257 bytes[0] = 0x02; let err = Cat::parse(&bytes).unwrap_err();
259 assert!(matches!(
260 err,
261 Error::UnexpectedTableId { table_id: 0x02, .. }
262 ));
263 }
264
265 #[test]
266 fn parse_rejects_short_buffer() {
267 let err = Cat::parse(&[0x01, 0x00]).unwrap_err();
268 assert!(matches!(err, Error::BufferTooShort { .. }));
269 }
270
271 #[test]
274 fn non_ca_descriptors_skipped_by_view_but_round_trip() {
275 let mut desc = Vec::new();
276 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
277 desc.extend_from_slice(&[0x12, 0x02, 0xAA, 0xBB]); desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
279 let bytes = build_cat(0, &desc);
280 let cat = Cat::parse(&bytes).unwrap();
281 let cas = cat.ca_descriptors();
282 assert_eq!(cas.len(), 2);
283 assert_eq!(cas[0].ca_system_id, 0x0500);
284 assert_eq!(cas[1].ca_system_id, 0x0650);
285 assert_eq!(cat.descriptors, desc);
287 let mut buf = vec![0u8; cat.serialized_len()];
288 cat.serialize_into(&mut buf).unwrap();
289 let re = Cat::parse(&buf).unwrap();
290 assert_eq!(re.descriptors, desc);
291 }
292
293 #[test]
294 fn serialize_round_trip() {
295 let mut desc = Vec::new();
296 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
297 desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
298 let cat = Cat::parse(&build_cat(3, &desc)).unwrap();
299 let mut buf = vec![0u8; cat.serialized_len()];
300 cat.serialize_into(&mut buf).unwrap();
301 assert_eq!(Cat::parse(&buf).unwrap(), cat);
302 }
303
304 #[test]
305 fn table_trait_constants() {
306 assert_eq!(<Cat as Table>::TABLE_ID, 0x01);
307 assert_eq!(<Cat as Table>::PID, 0x0001);
308 }
309
310 #[test]
311 fn serde_json_round_trip() {
312 let cat = Cat::parse(&build_cat(1, &ca_descriptor(0x0500, 0x0050))).unwrap();
313 let j = serde_json::to_string(&cat).unwrap();
314 assert_eq!(serde_json::from_str::<Cat>(&j).unwrap(), cat);
315 }
316}