1use crate::descriptors::ca::CaDescriptor;
11use crate::descriptors::DescriptorLoop;
12use crate::error::{Error, Result};
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;
23const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
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 CatSection<'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> CatSection<'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 CatSection<'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: "CatSection",
99 });
100 }
101
102 if bytes[0] != TABLE_ID {
103 return Err(Error::UnexpectedTableId {
104 table_id: bytes[0],
105 what: "CatSection",
106 expected: &[TABLE_ID],
107 });
108 }
109
110 let section_length = (((bytes[1] & 0x0F) as u16) << 8) | bytes[2] as u16;
111 let total = super::check_section_length(
112 bytes.len(),
113 MIN_HEADER_LEN,
114 section_length as usize,
115 MIN_SECTION_LEN,
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(CatSection {
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 CatSection<'_> {
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] = super::SECTION_B1_FLAGS_PSI | ((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}
174impl<'a> crate::traits::TableDef<'a> for CatSection<'a> {
175 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
176 const NAME: &'static str = "CONDITIONAL_ACCESS";
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 fn build_cat(version: u8, descriptors: &[u8]) -> Vec<u8> {
185 let section_length: u16 =
186 (EXTENSION_HEADER_LEN as u16) + descriptors.len() as u16 + (CRC_LEN as u16);
187 let mut v = Vec::new();
188 v.push(TABLE_ID);
189 v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
190 v.push((section_length & 0xFF) as u8);
191 v.extend_from_slice(&[0xFF, 0xFF]);
193 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01); v.push(0x00); v.push(0x00); v.extend_from_slice(descriptors);
197 v.extend_from_slice(&[0, 0, 0, 0]); v
199 }
200
201 fn ca_descriptor(ca_system_id: u16, ca_pid: u16) -> [u8; 6] {
202 [
203 0x09,
204 0x04,
205 (ca_system_id >> 8) as u8,
206 (ca_system_id & 0xFF) as u8,
207 0xE0 | ((ca_pid >> 8) as u8 & 0x1F),
208 (ca_pid & 0xFF) as u8,
209 ]
210 }
211
212 #[test]
213 fn parse_empty_cat_zero_descriptors() {
214 let bytes = build_cat(5, &[]);
215 let cat = CatSection::parse(&bytes).expect("parse");
216 assert_eq!(cat.version_number, 5);
217 assert!(cat.current_next_indicator);
218 assert!(cat.descriptors.is_empty());
219 assert_eq!(cat.ca_descriptors().len(), 0);
220 }
221
222 #[test]
223 fn parse_single_ca_descriptor_extracts_caid_and_pid() {
224 let mut desc = Vec::new();
225 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
226 let bytes = build_cat(0, &desc);
227 let cat = CatSection::parse(&bytes).unwrap();
228 let cas = cat.ca_descriptors();
229 assert_eq!(cas.len(), 1);
230 assert_eq!(cas[0].ca_system_id, 0x0500);
231 assert_eq!(cas[0].ca_pid, 0x0050);
232 assert!(cas[0].private_data.is_empty());
233 }
234
235 #[test]
236 fn parse_multiple_ca_descriptors_preserves_order() {
237 let mut desc = Vec::new();
238 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
239 desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
240 desc.extend_from_slice(&ca_descriptor(0x0100, 0x0080));
241 let bytes = build_cat(2, &desc);
242 let cat = CatSection::parse(&bytes).unwrap();
243 let cas = cat.ca_descriptors();
244 assert_eq!(cas.len(), 3);
245 assert_eq!(cas[0].ca_system_id, 0x0500);
246 assert_eq!(cas[1].ca_system_id, 0x0650);
247 assert_eq!(cas[2].ca_system_id, 0x0100);
248 assert_eq!(cas[1].ca_pid, 0x0062);
249 }
250
251 #[test]
252 fn parse_rejects_wrong_table_id() {
253 let mut bytes = build_cat(0, &[]);
254 bytes[0] = 0x02; let err = CatSection::parse(&bytes).unwrap_err();
256 assert!(matches!(
257 err,
258 Error::UnexpectedTableId { table_id: 0x02, .. }
259 ));
260 }
261
262 #[test]
263 fn parse_rejects_short_buffer() {
264 let err = CatSection::parse(&[0x01, 0x00]).unwrap_err();
265 assert!(matches!(err, Error::BufferTooShort { .. }));
266 }
267
268 #[test]
271 fn non_ca_descriptors_skipped_by_view_but_round_trip() {
272 let mut desc = Vec::new();
273 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
274 desc.extend_from_slice(&[0x12, 0x02, 0xAA, 0xBB]); desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
276 let bytes = build_cat(0, &desc);
277 let cat = CatSection::parse(&bytes).unwrap();
278 let cas = cat.ca_descriptors();
279 assert_eq!(cas.len(), 2);
280 assert_eq!(cas[0].ca_system_id, 0x0500);
281 assert_eq!(cas[1].ca_system_id, 0x0650);
282 assert_eq!(cat.descriptors.raw(), desc);
284 let mut buf = vec![0u8; cat.serialized_len()];
285 cat.serialize_into(&mut buf).unwrap();
286 let re = CatSection::parse(&buf).unwrap();
287 assert_eq!(re.descriptors.raw(), desc);
288 }
289
290 #[test]
291 fn serialize_round_trip() {
292 let mut desc = Vec::new();
293 desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
294 desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
295 let bytes = build_cat(3, &desc);
296 let cat = CatSection::parse(&bytes).unwrap();
297 let mut buf = vec![0u8; cat.serialized_len()];
298 cat.serialize_into(&mut buf).unwrap();
299 assert_eq!(CatSection::parse(&buf).unwrap(), cat);
300 }
301
302 #[test]
303 fn table_trait_constants() {
304 assert_eq!(TABLE_ID, 0x01);
305 assert_eq!(PID, 0x0001);
306 }
307
308 #[cfg(feature = "serde")]
312 #[test]
313 fn serde_json_serializes_typed_loop() {
314 let bytes = build_cat(1, &ca_descriptor(0x0500, 0x0050));
315 let cat = CatSection::parse(&bytes).unwrap();
316 let v = serde_json::to_value(&cat).unwrap();
317 let loop_ = v["descriptors"]
318 .as_array()
319 .expect("typed descriptor sequence");
320 assert_eq!(loop_.len(), 1);
321 assert_eq!(loop_[0]["ca"]["ca_system_id"], 0x0500);
322 assert_eq!(loop_[0]["ca"]["ca_pid"], 0x0050);
323 }
324
325 #[test]
326 fn parse_rejects_zero_section_length() {
327 let mut buf = vec![0u8; 64];
328 buf[0] = TABLE_ID;
329 buf[1] = 0xF0;
330 buf[2] = 0x00;
331 for b in &mut buf[3..] {
332 *b = 0xFF;
333 }
334 assert!(matches!(
335 CatSection::parse(&buf).unwrap_err(),
336 Error::SectionLengthOverflow { .. }
337 ));
338 }
339}