forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc439c14Tahinli25 days ago1006 commits

mpeg4.rs159 lines, 6.6 KiBHistoryRawDownload
1//! The MPEG-4 Part 2 / H.263 software seat (and MS-MPEG4 version 2 and 3, which `ec-mpeg4` decodes
2//! the same way, one picture per packet, no reordering): one span of `ec-mpeg4` (Simple and Advanced Simple
3//! profile, H.263 baseline) through the same [`Render`] door every other seat's pictures go
4//! through. Export reads the same [`Stream`] to decode its sources. Always software: no GPU path
5//! exists for it here.
6//!
7//! `ec-mpeg4` takes one access unit per packet (what mp4/3GP, Matroska and AVI store, with the
8//! Visual Object Layer header put in front of a sync sample that lacks one by the demuxer) and
9//! releases pictures in display order: I and P one reference late, B at once, and the last one
10//! when the stream is flushed. A DivX / XviD "packed bitstream" packet is unpacked by the
11//! decoder.
12//!
13//! **Seeking.** A span starts on the sync sample at or before the target, an I picture. A B
14//! picture that follows it in decode order and is displayed before it needs the reference
15//! before the I picture; the display index counts from the I picture, where the demuxer put it.
16//!
17//! **Chroma and fields.** Always 8-bit 4:2:0. An interlaced (field-coded) stream is shown as it
18//! is coded: there is no flag in the output to steer the shared deinterlacer with.
19
20use std::sync::mpsc::SyncSender;
21
22use ec_core::registry::{CodecId, CodecParameters, MediaParameters};
23use ec_mpeg4::Mpeg4Decoder;
24
25use super::{Abort, DecodeFailure, Frame, I420, LATE_RUN, Render, skip_for_speed};
26use crate::demux::Demuxer;
27use crate::project::Speed;
28
29/// One MPEG-4 Part 2 decode, pulled a picture at a time.
30pub(crate) struct Stream {
31 decoder: Mpeg4Decoder,
32 /// Display index of the next picture the decoder releases. Signed: the landing sync
33 /// sample can sit before frame 0.
34 index: i64,
35 /// Set once the demuxer runs dry and the decoder has been flushed.
36 flushed: bool,
37}
38
39impl Stream {
40 /// A decoder positioned at the sync sample at or before `start_frame`.
41 pub(crate) fn open(demuxer: &mut Demuxer, start_frame: u32) -> Self {
42 let index = demuxer.seek_to_sync_at_or_before(start_frame);
43 // MS-MPEG4 (an AVI's `MP42`, `DIV3`...) has no header: the codec id and the size come
44 // from the container.
45 let mut params = CodecParameters::new(CodecId::Mpeg4Part2);
46 if let Some((id, width, height, _)) = demuxer.video_params().filter(|p| p.0 != CodecId::Mpeg4Part2) {
47 params.codec = id;
48 if let MediaParameters::Video(v) = &mut params.media {
49 v.width = width;
50 v.height = height;
51 }
52 }
53 let mut decoder = Mpeg4Decoder::new(params).expect("ec-mpeg4 takes its own codec ids");
54 if let Some(tag) = demuxer.fourcc() {
55 decoder.set_fourcc(tag);
56 }
57 Self { decoder, index, flushed: false }
58 }
59
60 /// The next picture in display order, narrowed into `out`, with its display index. `None`
61 /// at end of stream; `Err` names a refusal, and the pictures before it stand.
62 pub(crate) fn next(&mut self, demuxer: &mut Demuxer, out: &mut I420) -> Result<Option<i64>, String> {
63 loop {
64 if let Some((pic, _)) = self.decoder.pop_picture() {
65 let tag = self.index;
66 self.index += 1;
67 out.width = pic.width;
68 out.height = pic.height;
69 let (cw, ch) = (pic.width.div_ceil(2) as usize, pic.height.div_ceil(2) as usize);
70 let dims = [(pic.width as usize, pic.height as usize), (cw, ch), (cw, ch)];
71 for ((plane, (w, h)), dst) in pic.planes.iter().zip(dims).zip([&mut out.y, &mut out.u, &mut out.v]) {
72 dst.clear();
73 for row in plane.data.chunks(plane.stride).take(h) {
74 dst.extend_from_slice(&row[..w]);
75 }
76 }
77 return Ok(Some(tag));
78 }
79 if self.flushed {
80 return Ok(None);
81 }
82 match demuxer.next_access_unit() {
83 Ok(Some(au)) => {
84 self.decoder
85 .send_bytes(&au, None)
86 .map_err(|e| format!("software MPEG-4 decode failed at frame {}: {e}", self.index))?;
87 }
88 Ok(None) => {
89 self.flushed = true;
90 self.decoder
91 .flush_stream()
92 .map_err(|e| format!("software MPEG-4 decode failed at end of stream: {e}"))?;
93 }
94 Err(e) => return Err(format!("demux error: {e}")),
95 }
96 }
97 }
98}
99
100/// The MPEG-4 Part 2 software seat over `[start_frame, end_frame)`. A span decodes from the
101/// sync sample at or before `start_frame`; pictures before the target are decoded (the target
102/// references them) but never sent.
103///
104/// A refusal out of `ec-mpeg4` fails the span in words: named on stderr, the pictures decoded
105/// so far stand, and no garbage is sent.
106// The eight inputs every software span takes (`run_mpeg2` has the same shape).
107#[allow(clippy::too_many_arguments)]
108pub(super) fn run_mpeg4(
109 demuxer: &mut Demuxer,
110 tx: &SyncSender<Frame>,
111 start_frame: u32,
112 end_frame: u32,
113 render: &mut Render,
114 abort: &Abort,
115 speed: Speed,
116 failure: &DecodeFailure,
117) {
118 let mut stream = Stream::open(demuxer, start_frame);
119 let mut out = I420::default();
120 let mut skipped = 0;
121 while !abort.hit() {
122 let due = match stream.next(demuxer, &mut out) {
123 Ok(Some(due)) => due,
124 Ok(None) => break,
125 Err(e) => {
126 failure.set(e);
127 break;
128 }
129 };
130 if due < i64::from(start_frame) {
131 continue;
132 }
133 let due = due as u32;
134 let sent = if abort.late(due) {
135 if skipped < LATE_RUN {
136 skipped += 1;
137 false
138 } else {
139 skipped = 0;
140 send(&out, due, render, tx)
141 }
142 } else if skip_for_speed(speed, start_frame, due, end_frame) {
143 false
144 } else {
145 skipped = 0;
146 send(&out, due, render, tx)
147 };
148 if sent || i64::from(due) + 1 >= i64::from(end_frame) {
149 break;
150 }
151 }
152}
153
154/// Queues one picture through the shared [`Render`]. `true` when the consumer went away, so the
155/// span stops rather than keeps decoding into a void.
156fn send(out: &I420, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
157 let frame = render.frame(due, &out.y, &out.u, &out.v, out.width, out.height);
158 tx.send(frame).is_err()
159}