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