forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

psvideo.rs354 lines, 12.4 KiBHistoryRawDownload
1//! MPEG-1/2 video as a program stream carries it: PES packets cut the picture data
2//! anywhere, and a PES timestamp belongs to the first picture that *starts* in that
3//! packet, not to the packet's first byte. The pictures are re-cut on their start
4//! codes in a buffer and every picture takes the timestamp of the packet its first
5//! byte (the first header of its run) lies in.
6
7use std::collections::VecDeque;
8
9use crate::codec::{self, StreamKind};
10use crate::track::{Au, MAX_PES, PesIn, Queued, TICKS, Track};
11
12/// The PES a stretch of the buffer came from.
13struct Mark {
14 start: u64,
15 end: u64,
16 off: u64,
17 pts: Option<i64>,
18 dts: Option<i64>,
19 bad: bool,
20}
21
22/// Unemitted video bytes with their start codes and PES provenance. Positions are
23/// absolute (bytes pushed since the last [`VBuf::clear`]).
24#[derive(Default)]
25pub(crate) struct VBuf {
26 data: Vec<u8>,
27 /// Absolute position of `data[0]`.
28 base: u64,
29 /// Absolute position from which the next scan looks for start codes.
30 scan_from: u64,
31 /// `(position, code)` of every start code at or after `base`.
32 codes: Vec<(u64, u8)>,
33 marks: VecDeque<Mark>,
34 /// Bytes are contiguous in the file (raw elementary stream): picture offsets are exact.
35 pub exact: bool,
36 /// The buffer begins at the start of an access unit.
37 pub at_start: bool,
38 /// Decode-order time (dts, else pts) of the last picture, for pictures that bring none.
39 last_t: Option<i64>,
40 /// Presentation time of temporal reference 0 of the current GOP, once known.
41 gop0: Option<i64>,
42 /// End of the display order so far (latest presentation time plus one frame).
43 disp_end: Option<i64>,
44}
45
46impl VBuf {
47 pub(crate) fn clear(&mut self) {
48 self.data.clear();
49 self.base = 0;
50 self.scan_from = 0;
51 self.codes.clear();
52 self.marks.clear();
53 self.at_start = false;
54 self.last_t = None;
55 self.gop0 = None;
56 self.disp_end = None;
57 }
58}
59
60impl Track {
61 /// Feeds one video PES (or one chunk of a raw stream) to the picture cutter.
62 pub(crate) fn ps_video_push(&mut self, ti: usize, p: &PesIn<'_>, q: &mut VecDeque<Queued>) {
63 let b = &mut self.psv.buf;
64 if b.data.len() + p.payload.len() > MAX_PES {
65 // An unterminated picture: start over rather than grow without bound.
66 let keep = b.base + b.data.len() as u64;
67 b.clear();
68 b.base = keep;
69 b.scan_from = keep;
70 }
71 let start = b.base + b.data.len() as u64;
72 b.data.extend_from_slice(p.payload);
73 let end = start + p.payload.len() as u64;
74 b.marks.push_back(Mark {
75 start,
76 end,
77 off: p.off,
78 pts: p.pts,
79 dts: p.dts,
80 bad: p.bad,
81 });
82 // New start codes: a code can straddle the join, hence the 3 bytes of overlap.
83 let from = (b.scan_from.max(b.base) - b.base) as usize;
84 let d = &b.data;
85 let mut i = from;
86 while i + 4 <= d.len() {
87 if d[i + 2] > 1 {
88 i += 3;
89 } else if d[i] == 0 && d[i + 1] == 0 && d[i + 2] == 1 {
90 b.codes.push((b.base + i as u64, d[i + 3]));
91 i += 4;
92 } else {
93 i += 1;
94 }
95 }
96 b.scan_from = b.base + i.min(d.len()) as u64;
97 self.ps_cut(ti, q, false);
98 }
99
100 /// Emits every picture whose end is known; with `all`, the last one too.
101 fn ps_cut(&mut self, ti: usize, q: &mut VecDeque<Queued>, all: bool) {
102 let mut runs: Vec<u64> = self.ps_runs();
103 runs.dedup();
104 let last = if all {
105 runs.len()
106 } else {
107 runs.len().saturating_sub(1)
108 };
109 if runs.is_empty() || (last == 0 && !all) {
110 // Nothing complete. Bytes before the first run can never form a picture.
111 if runs.is_empty() && !all {
112 self.ps_trim_junk();
113 }
114 return;
115 }
116 let mut cuts: Vec<u64> = runs[..last.min(runs.len())].to_vec();
117 let tail_end = self.psv.buf.base + self.psv.buf.data.len() as u64;
118 let upto = if all {
119 cuts.push(tail_end);
120 tail_end
121 } else {
122 cuts.push(runs[last]);
123 runs[last]
124 };
125 for w in cuts.windows(2) {
126 self.ps_emit(ti, w[0], w[1], q);
127 }
128 let b = &mut self.psv.buf;
129 let n = (upto - b.base) as usize;
130 b.data.drain(..n);
131 b.base = upto;
132 b.at_start = !all;
133 b.codes.retain(|&(p, _)| p >= upto);
134 while b.marks.front().is_some_and(|m| m.end <= upto) {
135 b.marks.pop_front();
136 }
137 }
138
139 /// Where pictures (access units) start in the buffer.
140 fn ps_runs(&self) -> Vec<u64> {
141 let b = &self.psv.buf;
142 let mut runs = Vec::new();
143 let c = &b.codes;
144 match self.kind {
145 StreamKind::H264 | StreamKind::Hevc => {
146 let hevc = self.kind == StreamKind::Hevc;
147 let mut prev_vcl = false;
148 let mut have = b.at_start;
149 if have {
150 runs.push(b.base);
151 }
152 for &(pos, code) in c {
153 let (ty, vcl) = if hevc {
154 let t = (code >> 1) & 0x3F;
155 (t, t < 32)
156 } else {
157 let t = code & 0x1F;
158 (t, (1..=5).contains(&t))
159 };
160 let header = if hevc {
161 matches!(ty, 32..=35 | 39 | 41..=44 | 48..=55)
162 } else {
163 matches!(ty, 6..=9 | 14..=18)
164 };
165 let aud = if hevc { ty == 35 } else { ty == 9 };
166 let mut start = false;
167 if aud || (header && (prev_vcl || !have)) {
168 start = true;
169 } else if vcl && (prev_vcl || !have) {
170 // The first slice of a picture: first_mb_in_slice == 0 (H.264) or
171 // first_slice_segment_in_pic_flag (HEVC), the top bit after the header.
172 let at = (pos - b.base) as usize + 4 + usize::from(hevc);
173 match b.data.get(at) {
174 Some(&x) => start = x & 0x80 != 0,
175 None => break,
176 }
177 }
178 if start {
179 // The zero byte of a 4-byte start code belongs to the unit.
180 let s = if pos > b.base && b.data[(pos - b.base) as usize - 1] == 0 {
181 pos - 1
182 } else {
183 pos
184 };
185 runs.push(s);
186 have = true;
187 prev_vcl = false;
188 }
189 if vcl {
190 prev_vcl = true;
191 } else if !aud && !header {
192 // Parameter sets and other units keep the state.
193 }
194 }
195 }
196 _ => {
197 for (k, &(_, code)) in c.iter().enumerate() {
198 if code == 0 {
199 let mut j = k;
200 while j > 0 && matches!(c[j - 1].1, 0xB2 | 0xB3 | 0xB5 | 0xB8) {
201 j -= 1;
202 }
203 runs.push(c[j].0);
204 }
205 }
206 }
207 }
208 runs
209 }
210
211 /// Drops buffered bytes that precede every picture run, keeping a few bytes in case
212 /// a start code straddles the next join.
213 fn ps_trim_junk(&mut self) {
214 let b = &mut self.psv.buf;
215 let keep_from = (b.base + b.data.len() as u64).saturating_sub(3);
216 if keep_from > b.base + (64 << 10) {
217 let n = (keep_from - b.base) as usize;
218 b.data.drain(..n);
219 b.base = keep_from;
220 b.codes.retain(|&(p, _)| p >= keep_from);
221 while b.marks.front().is_some_and(|m| m.end <= keep_from) {
222 b.marks.pop_front();
223 }
224 }
225 }
226
227 fn ps_emit(&mut self, ti: usize, from: u64, to: u64, q: &mut VecDeque<Queued>) {
228 let b = &self.psv.buf;
229 let piece = b.data[(from - b.base) as usize..(to - b.base) as usize].to_vec();
230 let mark = b.marks.iter().find(|m| m.start <= from && from < m.end);
231 let bad_any = b
232 .marks
233 .iter()
234 .any(|m| m.bad && m.start < to && m.end > from);
235 let (pts, dts, off) = match mark {
236 Some(m) => {
237 let off = if b.exact {
238 m.off + (from - m.start)
239 } else {
240 m.off
241 };
242 (m.pts, m.dts, off)
243 }
244 None => (None, None, 0),
245 };
246 let bad = bad_any || mark.is_none();
247 if matches!(self.kind, StreamKind::H264 | StreamKind::Hevc) {
248 if let Some(m) = self
249 .psv
250 .buf
251 .marks
252 .iter_mut()
253 .find(|m| m.start <= from && from < m.end)
254 {
255 m.pts = None;
256 m.dts = None;
257 }
258 let au = Au {
259 data: piece,
260 pts,
261 dts,
262 off,
263 rai: false,
264 bad,
265 };
266 self.emit_annexb(ti, au, q);
267 return;
268 }
269 let sc = codec::mpeg2_scan(&piece);
270 if self.cfg.mpeg2.is_none() {
271 self.cfg.mpeg2 = sc.facts.clone();
272 }
273 // A picture whose packet carried no timestamp (it shares the packet with the
274 // one before): the decode time follows the previous picture by one frame and the
275 // presentation time follows from the temporal reference, as ffmpeg's parser does
276 // for the decode time (it leaves the presentation time unknown).
277 let ft = self
278 .cfg
279 .mpeg2
280 .as_ref()
281 .map(|f| (TICKS * i64::from(f.rate.1)) / i64::from(f.rate.0.max(1)));
282 let tr = sc.pictures.first().and_then(|&p| {
283 Some((i64::from(*piece.get(p + 4)?) << 2) | i64::from(piece.get(p + 5)? >> 6))
284 });
285 let (mut pts, mut dts) = (pts, dts);
286 let head = &piece[..sc.pictures.first().copied().unwrap_or(0)];
287 let new_gop = head
288 .windows(4)
289 .any(|w| w == [0, 0, 1, 0xB8] || w == [0, 0, 1, 0xB3]);
290 let b = &mut self.psv.buf;
291 if new_gop {
292 b.gop0 = None;
293 }
294 let mut derived = false;
295 if pts.is_none() && dts.is_none() {
296 if let (Some(ft), Some(last)) = (ft, b.last_t) {
297 dts = Some(last + ft);
298 derived = true;
299 }
300 if new_gop && b.gop0.is_none() {
301 // The first picture of a GOP with no stamp: the GOP's display order
302 // continues where the previous one ended (temporal reference 0 there).
303 b.gop0 = b.disp_end;
304 }
305 if let (Some(ft), Some(tr), Some(g)) = (ft, tr, b.gop0) {
306 pts = Some(g + tr * ft);
307 derived = true;
308 }
309 }
310 if let (Some(ft), Some(p)) = (ft, pts) {
311 b.disp_end = Some(b.disp_end.map_or(p + ft, |e| e.max(p + ft)));
312 }
313 if let Some(t) = dts.or(pts) {
314 b.last_t = Some(t);
315 }
316 if let (Some(ft), Some(tr), Some(p)) = (ft, tr, pts) {
317 b.gop0 = Some(p - tr * ft);
318 }
319 // The same packet's timestamp must not be reused by a second picture.
320 let used = self
321 .psv
322 .buf
323 .marks
324 .iter_mut()
325 .find(|m| m.start <= from && from < m.end);
326 if let Some(m) = used {
327 m.pts = None;
328 m.dts = None;
329 }
330 self.emit(
331 q,
332 Queued {
333 track: ti,
334 off,
335 pts,
336 dts,
337 dur: None,
338 key: sc.key,
339 corrupt: bad,
340 derived,
341 data: piece,
342 },
343 );
344 }
345
346 /// Emits what is buffered (end of stream, a seek, a discontinuity).
347 pub(crate) fn ps_flush(&mut self, ti: usize, q: &mut VecDeque<Queued>) {
348 if !self.psv.on {
349 return;
350 }
351 self.ps_cut(ti, q, true);
352 self.psv.buf.clear();
353 }
354}