forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

psi.rs302 lines, 9.1 KiBHistoryRawDownload
1//! Program Specific Information: section reassembly, CRC32/MPEG-2, PAT and PMT.
2
3/// Longest section a PSI table may have (12-bit length + 3 header bytes).
4pub(crate) const MAX_SECTION: usize = 4096;
5
6/// CRC-32/MPEG-2 (poly 0x04C11DB7, init all ones, no reflection, no final xor).
7pub(crate) fn crc32_mpeg(data: &[u8]) -> u32 {
8 let mut crc = 0xFFFF_FFFFu32;
9 for &b in data {
10 crc ^= u32::from(b) << 24;
11 for _ in 0..8 {
12 crc = if crc & 0x8000_0000 != 0 {
13 (crc << 1) ^ 0x04C1_1DB7
14 } else {
15 crc << 1
16 };
17 }
18 }
19 crc
20}
21
22/// Reassembles one PID's sections.
23#[derive(Debug, Default)]
24pub(crate) struct SectionBuf {
25 buf: Vec<u8>,
26 active: bool,
27}
28
29impl SectionBuf {
30 pub(crate) fn reset(&mut self) {
31 self.buf.clear();
32 self.active = false;
33 }
34
35 /// Feeds one packet payload; complete, CRC-checked sections go to `out`.
36 /// Returns the number of sections dropped for a bad CRC or length.
37 pub(crate) fn push(&mut self, pusi: bool, payload: &[u8], out: &mut Vec<Vec<u8>>) -> u32 {
38 let mut bad = 0;
39 let mut data = payload;
40 if pusi {
41 let Some((&ptr, rest)) = data.split_first() else {
42 return 0;
43 };
44 let ptr = usize::from(ptr);
45 if ptr > rest.len() {
46 self.reset();
47 return 0;
48 }
49 // The tail of the section in flight, then sections starting here.
50 if self.active {
51 self.buf.extend_from_slice(&rest[..ptr]);
52 bad += self.drain(out);
53 }
54 self.reset();
55 data = &rest[ptr..];
56 self.active = true;
57 } else if !self.active {
58 return 0;
59 }
60 self.buf.extend_from_slice(data);
61 bad += self.drain(out);
62 if self.buf.len() > MAX_SECTION {
63 self.reset();
64 }
65 bad
66 }
67
68 /// Pulls every whole section off the front of the buffer.
69 fn drain(&mut self, out: &mut Vec<Vec<u8>>) -> u32 {
70 let mut bad = 0;
71 loop {
72 if self.buf.len() < 3 {
73 return bad;
74 }
75 if self.buf[0] == 0xFF {
76 // Stuffing: nothing else in this payload.
77 self.reset();
78 return bad;
79 }
80 let len = 3 + ((usize::from(self.buf[1] & 0x0f) << 8) | usize::from(self.buf[2]));
81 if len > MAX_SECTION {
82 self.reset();
83 return bad + 1;
84 }
85 if self.buf.len() < len {
86 return bad;
87 }
88 let section: Vec<u8> = self.buf.drain(..len).collect();
89 let long_form = section[1] & 0x80 != 0;
90 if long_form && (len < 12 || crc32_mpeg(&section) != 0) {
91 bad += 1;
92 } else {
93 out.push(section);
94 }
95 if self.buf.is_empty() {
96 self.active = false;
97 return bad;
98 }
99 }
100 }
101}
102
103/// One program as the PAT lists it.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct PatEntry {
106 /// `program_number` (never 0, which names the NIT).
107 pub program_number: u16,
108 /// PID carrying this program's PMT.
109 pub pmt_pid: u16,
110}
111
112/// Parses a PAT section (already CRC-checked). `None` when it is not a PAT.
113pub(crate) fn parse_pat(section: &[u8]) -> Option<(u8, Vec<PatEntry>)> {
114 if *section.first()? != 0x00 || section.len() < 12 {
115 return None;
116 }
117 let current = section[5] & 1 != 0;
118 if !current {
119 return None;
120 }
121 let version = (section[5] >> 1) & 0x1f;
122 let body = section.get(8..section.len() - 4)?;
123 let mut out = Vec::new();
124 for e in body.as_chunks::<4>().0.iter().take(1024) {
125 let program_number = u16::from_be_bytes([e[0], e[1]]);
126 let pid = (u16::from(e[2] & 0x1f) << 8) | u16::from(e[3]);
127 if program_number != 0 {
128 out.push(PatEntry {
129 program_number,
130 pmt_pid: pid,
131 });
132 }
133 }
134 Some((version, out))
135}
136
137/// One elementary stream of a PMT.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct EsEntry {
140 /// `stream_type`.
141 pub stream_type: u8,
142 /// Elementary PID.
143 pub pid: u16,
144 /// `ES_info` descriptors as `(tag, body)`.
145 pub descriptors: Vec<(u8, Vec<u8>)>,
146}
147
148impl EsEntry {
149 /// Body of the first descriptor with `tag`.
150 pub fn descriptor(&self, tag: u8) -> Option<&[u8]> {
151 self.descriptors
152 .iter()
153 .find(|(t, _)| *t == tag)
154 .map(|(_, b)| b.as_slice())
155 }
156
157 /// Registration descriptor `format_identifier`, when present.
158 pub fn registration(&self) -> Option<[u8; 4]> {
159 self.descriptor(0x05)
160 .and_then(|b| b.get(..4))
161 .map(|b| [b[0], b[1], b[2], b[3]])
162 }
163
164 /// ISO 639 language code of the first language descriptor.
165 pub fn language(&self) -> Option<String> {
166 let b = self.descriptor(0x0A)?.get(..3)?;
167 if b.iter().all(u8::is_ascii_alphabetic) {
168 Some(String::from_utf8_lossy(b).to_ascii_lowercase())
169 } else {
170 None
171 }
172 }
173}
174
175/// A parsed PMT.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Pmt {
178 /// `program_number`.
179 pub program_number: u16,
180 /// `version_number`.
181 pub version: u8,
182 /// PID that carries the PCR.
183 pub pcr_pid: u16,
184 /// Elementary streams in PMT order.
185 pub streams: Vec<EsEntry>,
186}
187
188/// Elementary streams kept per program; a PMT cannot name more than 8191 PIDs, but
189/// nothing sane has more than this.
190pub(crate) const MAX_ES: usize = 64;
191
192pub(crate) fn descriptors(mut b: &[u8]) -> Vec<(u8, Vec<u8>)> {
193 let mut out = Vec::new();
194 while b.len() >= 2 && out.len() < 32 {
195 let (tag, len) = (b[0], usize::from(b[1]));
196 let Some(body) = b.get(2..2 + len) else {
197 break;
198 };
199 out.push((tag, body.to_vec()));
200 b = &b[2 + len..];
201 }
202 out
203}
204
205/// Parses a PMT section (already CRC-checked). `None` when it is not a PMT.
206pub(crate) fn parse_pmt(section: &[u8]) -> Option<Pmt> {
207 if *section.first()? != 0x02 || section.len() < 16 {
208 return None;
209 }
210 if section[5] & 1 == 0 {
211 return None;
212 }
213 let program_number = u16::from_be_bytes([section[3], section[4]]);
214 let version = (section[5] >> 1) & 0x1f;
215 let pcr_pid = (u16::from(section[8] & 0x1f) << 8) | u16::from(section[9]);
216 let info_len = (usize::from(section[10] & 0x0f) << 8) | usize::from(section[11]);
217 let end = section.len().checked_sub(4)?;
218 let mut at = 12usize.checked_add(info_len)?;
219 let mut streams = Vec::new();
220 while at + 5 <= end && streams.len() < MAX_ES {
221 let stream_type = section[at];
222 let pid = (u16::from(section[at + 1] & 0x1f) << 8) | u16::from(section[at + 2]);
223 let es_len = (usize::from(section[at + 3] & 0x0f) << 8) | usize::from(section[at + 4]);
224 let d = section.get(at + 5..(at + 5 + es_len).min(end))?;
225 streams.push(EsEntry {
226 stream_type,
227 pid,
228 descriptors: descriptors(d),
229 });
230 at += 5 + es_len;
231 }
232 Some(Pmt {
233 program_number,
234 version,
235 pcr_pid,
236 streams,
237 })
238}
239
240#[cfg(test)]
241pub(crate) fn build_section(table_id: u8, ext: u16, body: &[u8]) -> Vec<u8> {
242 let len = 5 + body.len() + 4;
243 let mut s = vec![table_id, 0xB0 | ((len >> 8) as u8 & 0x0f), len as u8];
244 s.extend_from_slice(&ext.to_be_bytes());
245 s.push(0xC1);
246 s.extend_from_slice(&[0, 0]);
247 s.extend_from_slice(body);
248 let crc = crc32_mpeg(&s);
249 s.extend_from_slice(&crc.to_be_bytes());
250 s
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 #[test]
258 fn crc_of_a_section_with_its_crc_is_zero() {
259 let s = build_section(0, 1, &[0, 1, 0xE1, 0x00]);
260 assert_eq!(crc32_mpeg(&s), 0);
261 let (v, e) = parse_pat(&s).unwrap();
262 assert_eq!(v, 0);
263 assert_eq!(
264 e,
265 vec![PatEntry {
266 program_number: 1,
267 pmt_pid: 0x100
268 }]
269 );
270 }
271
272 #[test]
273 fn section_split_over_packets_and_bad_crc() {
274 let s = build_section(0, 1, &[0, 1, 0xE1, 0x00]);
275 let mut buf = SectionBuf::default();
276 let mut out = Vec::new();
277 let mut first = vec![0u8];
278 first.extend_from_slice(&s[..5]);
279 assert_eq!(buf.push(true, &first, &mut out), 0);
280 assert!(out.is_empty());
281 buf.push(false, &s[5..], &mut out);
282 assert_eq!(out.len(), 1);
283 let mut bad = s.clone();
284 bad[9] ^= 1;
285 let mut p = vec![0u8];
286 p.extend_from_slice(&bad);
287 assert_eq!(buf.push(true, &p, &mut out), 1);
288 assert_eq!(out.len(), 1);
289 }
290
291 #[test]
292 fn pmt_parses() {
293 let mut body = vec![0xE1, 0x01, 0xF0, 0x00];
294 body.extend_from_slice(&[0x1B, 0xE1, 0x01, 0xF0, 0x00]);
295 body.extend_from_slice(&[0x06, 0xE1, 0x02, 0xF0, 0x05, 0x6A, 0x01, 0x00, 0x0A, 0x00]);
296 let s = build_section(2, 1, &body);
297 let pmt = parse_pmt(&s).unwrap();
298 assert_eq!(pmt.pcr_pid, 0x101);
299 assert_eq!(pmt.streams.len(), 2);
300 assert_eq!(pmt.streams[1].descriptors[0].0, 0x6A);
301 }
302}