forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ts.rs214 lines, 6.1 KiBHistoryRawDownload
1//! Transport packet layer: packet-size detection, resynchronisation, the 4-byte
2//! header and the adaptation field.
3
4/// The sync byte every transport packet starts with.
5pub(crate) const SYNC: u8 = 0x47;
6
7/// Bytes of a bare transport packet.
8pub(crate) const TS_LEN: usize = 188;
9
10/// How many consecutive sync bytes at the packet stride make a candidate real.
11const CONFIRM: usize = 4;
12
13/// Packet stride and where the sync byte sits inside one stride.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub(crate) struct Layout {
16 /// 188 (bare), 192 (BDAV with a 4-byte `TP_extra_header`) or 204 (Reed-Solomon trailer).
17 pub size: usize,
18 /// 4 for BDAV, 0 otherwise.
19 pub sync_off: usize,
20}
21
22impl Layout {
23 pub(crate) const ALL: [Layout; 3] = [
24 Layout {
25 size: 188,
26 sync_off: 0,
27 },
28 Layout {
29 size: 192,
30 sync_off: 4,
31 },
32 Layout {
33 size: 204,
34 sync_off: 0,
35 },
36 ];
37}
38
39/// True when `buf[at]` is a sync byte and the following strides agree: up to
40/// `CONFIRM` more sync bytes. A candidate near the end of the buffer needs at
41/// least one confirmation unless the buffer holds nothing more.
42fn confirmed(buf: &[u8], at: usize, size: usize) -> bool {
43 if buf.get(at) != Some(&SYNC) {
44 return false;
45 }
46 let mut seen = 0;
47 for k in 1..=CONFIRM {
48 match buf.get(at + k * size) {
49 Some(&SYNC) => seen += 1,
50 Some(_) => return false,
51 None => break,
52 }
53 }
54 // Small inputs cannot confirm four strides; one is enough when it is all there is.
55 seen >= CONFIRM.min(2) || (seen >= 1 && at + (seen + 1) * size + size > buf.len())
56}
57
58/// First packet start in `buf` at or after `from` whose sync byte is confirmed at
59/// `layout`'s stride.
60pub(crate) fn find_sync(buf: &[u8], from: usize, layout: Layout) -> Option<usize> {
61 let mut i = from.checked_add(layout.sync_off)?;
62 while i < buf.len() {
63 let rest = buf.get(i..)?;
64 let k = rest.iter().position(|&b| b == SYNC)?;
65 let at = i + k;
66 if confirmed(buf, at, layout.size) {
67 return Some(at - layout.sync_off);
68 }
69 i = at + 1;
70 }
71 None
72}
73
74/// Detects the packet layout of `buf` (the head of a file): the earliest confirmed
75/// sync position over the three strides. Returns the layout and the offset of the
76/// first packet.
77pub(crate) fn detect(buf: &[u8]) -> Option<(Layout, usize)> {
78 let mut best: Option<(Layout, usize)> = None;
79 for layout in Layout::ALL {
80 if let Some(at) = find_sync(buf, 0, layout)
81 && best.is_none_or(|(_, b)| at < b)
82 {
83 best = Some((layout, at));
84 }
85 }
86 best
87}
88
89/// True when `buf` begins like a transport stream at some stride.
90pub(crate) fn looks_like_ts(buf: &[u8]) -> bool {
91 detect(buf).is_some_and(|(_, at)| at < 4 * TS_LEN)
92}
93
94/// A parsed 188-byte packet.
95#[derive(Debug, Clone, Copy)]
96pub(crate) struct Header {
97 pub pid: u16,
98 pub tei: bool,
99 pub pusi: bool,
100 pub cc: u8,
101 pub has_payload: bool,
102 /// Payload range inside the 188 bytes (empty when there is none).
103 pub payload: (usize, usize),
104 pub discontinuity: bool,
105 pub random_access: bool,
106 /// PCR in 27 MHz units.
107 pub pcr: Option<u64>,
108}
109
110/// Parses the header of `p`, which must hold at least 4 bytes. `None` for a packet
111/// whose sync byte or adaptation field is broken.
112pub(crate) fn parse(p: &[u8]) -> Option<Header> {
113 let p = p.get(..TS_LEN)?;
114 if p[0] != SYNC {
115 return None;
116 }
117 let tei = p[1] & 0x80 != 0;
118 let pusi = p[1] & 0x40 != 0;
119 let pid = (u16::from(p[1] & 0x1f) << 8) | u16::from(p[2]);
120 let afc = (p[3] >> 4) & 3;
121 let cc = p[3] & 15;
122 let mut h = Header {
123 pid,
124 tei,
125 pusi,
126 cc,
127 has_payload: afc & 1 != 0,
128 payload: (4, TS_LEN),
129 discontinuity: false,
130 random_access: false,
131 pcr: None,
132 };
133 if afc == 0 {
134 // Reserved: no payload, nothing to read.
135 h.has_payload = false;
136 h.payload = (TS_LEN, TS_LEN);
137 return Some(h);
138 }
139 if afc & 2 != 0 {
140 let len = usize::from(p[4]);
141 let end = 5 + len;
142 if end > TS_LEN {
143 return None;
144 }
145 if len > 0 {
146 let f = p[5];
147 h.discontinuity = f & 0x80 != 0;
148 h.random_access = f & 0x40 != 0;
149 if f & 0x10 != 0 && len >= 7 {
150 let b = &p[6..12];
151 let base = (u64::from(b[0]) << 25)
152 | (u64::from(b[1]) << 17)
153 | (u64::from(b[2]) << 9)
154 | (u64::from(b[3]) << 1)
155 | u64::from(b[4] >> 7);
156 let ext = (u64::from(b[4] & 1) << 8) | u64::from(b[5]);
157 h.pcr = Some(base * 300 + ext);
158 }
159 }
160 h.payload = if afc & 1 != 0 {
161 (end, TS_LEN)
162 } else {
163 (TS_LEN, TS_LEN)
164 };
165 }
166 Some(h)
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn stream(size: usize, sync_off: usize, n: usize) -> Vec<u8> {
174 let mut v = vec![0u8; size * n];
175 for k in 0..n {
176 v[k * size + sync_off] = SYNC;
177 }
178 v
179 }
180
181 #[test]
182 fn detects_the_three_strides() {
183 for (size, off) in [(188, 0), (192, 4), (204, 0)] {
184 let (l, at) = detect(&stream(size, off, 10)).unwrap();
185 assert_eq!((l.size, at), (size, 0));
186 }
187 }
188
189 #[test]
190 fn resyncs_past_garbage() {
191 let mut v = vec![0x11u8; 77];
192 v.extend(stream(188, 0, 10));
193 let (l, at) = detect(&v).unwrap();
194 assert_eq!((l.size, at), (188, 77));
195 }
196
197 #[test]
198 fn header_fields() {
199 let mut p = [0xffu8; 188];
200 p[0] = SYNC;
201 p[1] = 0x41;
202 p[2] = 0x00;
203 p[3] = 0x30 | 5;
204 p[4] = 7;
205 p[5] = 0x50;
206 p[6..12].copy_from_slice(&[0, 0, 0, 1, 0x80, 0x00]);
207 let h = parse(&p).unwrap();
208 assert!(h.pusi && h.random_access && !h.discontinuity);
209 assert_eq!(h.pid, 0x100);
210 assert_eq!(h.cc, 5);
211 assert_eq!(h.pcr, Some(3 * 300));
212 assert_eq!(h.payload, (12, 188));
213 }
214}