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