forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf7fa0feTahinli25 days ago1027 commits

mpeg2.rs228 lines, 9.2 KiBHistoryRawDownload
1//! The MPEG-1/2 video software seat: one span of `ec-mpeg2` through the same
2//! [`Render`] door every other seat's pictures go through. Export reads the same
3//! [`Stream`] to decode its sources. Always software: no GPU path exists for it here.
4//!
5//! `ec-mpeg2` takes one coded picture per packet (what the transport-stream demuxer
6//! hands out, with the sequence header in front of a keyframe that lacks one) and
7//! releases frames in display order, I and P one reference late and B at once; the
8//! last ones wait in it until the stream is flushed.
9//!
10//! **Seeking.** A span starts on the keyframe at or before the target: a sequence
11//! header or an I picture. A B picture of an open GOP that follows it and needs the
12//! reference before it has none, so `ec-mpeg2` drops it, as ffmpeg does; those
13//! pictures sit *before* the landing I picture in display order, so the display index
14//! counts from the I picture, where the demuxer put it.
15//!
16//! **Interlace.** Field pictures come out woven, with the field order in the frame. An
17//! interlaced sequence (`progressive_sequence` 0) goes through the same deinterlacer
18//! H.264 does ([`crate::deinterlace`]), picture by picture: a picture coded
19//! progressive (`progressive_frame` 1, a film cadence inside an interlaced sequence)
20//! is left exactly as it was. As for H.264 the stage runs one picture behind, so a
21//! seek lands one picture earlier and the target is filtered from the same neighbours
22//! a sequential decode gave it.
23//!
24//! **Chroma.** 4:2:2 (the 4:2:2 profile) has its chroma averaged down a pair of rows
25//! to 4:2:0 as H.264 and HEVC 4:2:2 do ([`Deep`]).
26//!
27//! `repeat_first_field` (3:2 pulldown) is not applied: the timeline is frame-locked
28//! and the demuxer counts one frame per coded picture.
29
30use std::sync::mpsc::SyncSender;
31
32use ec_core::frame::{Frame as Decoded, Interlace, PixelFormat, VideoFrame};
33use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
34use ec_core::{Packet, TimeBase};
35use ec_mpeg2::Mpeg2Decoder;
36
37use super::{Abort, Deep, DecodeFailure, Frame, I420, LATE_RUN, Render, skip_for_speed};
38use crate::deinterlace::Deinterlacer;
39use crate::demux::Demuxer;
40use crate::project::{Deinterlace, Speed};
41
42/// One MPEG-1/2 decode, pulled a picture at a time.
43pub(crate) struct Stream {
44 decoder: Mpeg2Decoder,
45 /// Display index of the next picture the decoder releases. Signed: the landing
46 /// keyframe can sit before frame 0.
47 index: i64,
48 /// Set once the demuxer runs dry and the decoder has been flushed.
49 flushed: bool,
50 deint: Deinterlacer,
51 deep: Deep,
52 /// Pictures the deinterlacing stage has released and `next` has not yet handed
53 /// out (pulldown removal can release two at once).
54 ready: std::collections::VecDeque<(i64, VideoFrame)>,
55}
56
57impl Stream {
58 /// A decoder positioned at the keyframe at or before `start_frame` (one earlier
59 /// for an interlaced sequence, whose deinterlacer wants the picture before).
60 pub(crate) fn open(demuxer: &mut Demuxer, start_frame: u32, mode: Deinterlace) -> Self {
61 let interlaced = demuxer.h264_interlaced();
62 let deint = Deinterlacer::new(interlaced, i64::from(start_frame), Interlace::Progressive)
63 .flagged_only()
64 .cadenced(mode, demuxer);
65 let index = demuxer.seek_to_sync_at_or_before(deint.landing(start_frame));
66 Self {
67 decoder: Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video))
68 .expect("ec-mpeg2 takes its own codec id"),
69 index,
70 flushed: false,
71 deint,
72 deep: Deep::default(),
73 ready: Default::default(),
74 }
75 }
76
77 /// The next picture in display order, narrowed into `out`, with its display
78 /// index. `None` at end of stream; `Err` names a refusal, and the pictures before
79 /// it stand.
80 pub(crate) fn next(
81 &mut self,
82 demuxer: &mut Demuxer,
83 out: &mut I420,
84 ) -> Result<Option<i64>, String> {
85 loop {
86 if let Some((due, pic)) = self.ready.pop_front() {
87 self.narrow(&pic, out)?;
88 return Ok(Some(due));
89 }
90 match self.decoder.receive_frame() {
91 Ok(Decoded::Video(pic)) => {
92 let tag = self.index;
93 self.index += 1;
94 self.ready.extend(self.deint.push_all(tag, pic));
95 continue;
96 }
97 Ok(_) => continue,
98 Err(e) if e.is_need_more() || e.is_eof() => {}
99 Err(e) => {
100 return Err(format!("software MPEG-2 decode failed at frame {}: {e}", self.index));
101 }
102 }
103 if self.flushed {
104 // The end of the stream releases the picture the stage was holding
105 // for a successor.
106 self.ready.extend(self.deint.finish_all());
107 return match self.ready.pop_front() {
108 Some((due, pic)) => {
109 self.narrow(&pic, out)?;
110 Ok(Some(due))
111 }
112 None => Ok(None),
113 };
114 }
115 match demuxer.next_access_unit() {
116 Ok(Some(au)) => {
117 let packet = Packet::new(0, TimeBase::new(1, 1), au);
118 self.decoder.send_packet(&packet).map_err(|e| {
119 format!("software MPEG-2 decode failed at frame {}: {e}", self.index)
120 })?;
121 }
122 Ok(None) => {
123 self.flushed = true;
124 self.decoder
125 .flush()
126 .map_err(|e| format!("software MPEG-2 decode failed at end of stream: {e}"))?;
127 }
128 Err(e) => return Err(format!("demux error: {e}")),
129 }
130 }
131 }
132
133 /// One picture as the tightly packed 8-bit 4:2:0 every converter takes.
134 fn narrow(&mut self, pic: &VideoFrame, out: &mut I420) -> Result<(), String> {
135 match pic.format {
136 PixelFormat::I420 => {
137 out.width = pic.width;
138 out.height = pic.height;
139 let (cw, ch) = (pic.width.div_ceil(2) as usize, pic.height.div_ceil(2) as usize);
140 let dims = [(pic.width as usize, pic.height as usize), (cw, ch), (cw, ch)];
141 for ((plane, (w, h)), dst) in pic
142 .planes
143 .iter()
144 .zip(dims)
145 .zip([&mut out.y, &mut out.u, &mut out.v])
146 {
147 dst.clear();
148 for row in plane.data.chunks(plane.stride).take(h) {
149 dst.extend_from_slice(&row[..w]);
150 }
151 }
152 Ok(())
153 }
154 PixelFormat::I422 => {
155 self.deep.load(pic, false);
156 std::mem::swap(out, &mut self.deep.narrow);
157 Ok(())
158 }
159 other => Err(format!(
160 "software MPEG-2 frame {} is {other:?}, and only 4:2:0 and 4:2:2 are carried",
161 self.index
162 )),
163 }
164 }
165}
166
167/// The MPEG-1/2 software seat over `[start_frame, end_frame)`. A span decodes from
168/// the keyframe at or before `start_frame`; pictures before the target are decoded
169/// (the target references them) but never sent.
170///
171/// A refusal out of `ec-mpeg2` fails the span in words: named on stderr, the pictures
172/// decoded so far stand, and no garbage is sent.
173// The eight inputs every software span takes (`run_hevc` has the same shape); a
174// one-off struct would only ever be built and taken apart here.
175#[allow(clippy::too_many_arguments)]
176pub(super) fn run_mpeg2(
177 demuxer: &mut Demuxer,
178 tx: &SyncSender<Frame>,
179 start_frame: u32,
180 end_frame: u32,
181 render: &mut Render,
182 abort: &Abort,
183 speed: Speed,
184 failure: &DecodeFailure,
185 deint: Deinterlace,
186) {
187 let mut stream = Stream::open(demuxer, start_frame, deint);
188 let mut out = I420::default();
189 let mut skipped = 0;
190 while !abort.hit() {
191 let due = match stream.next(demuxer, &mut out) {
192 Ok(Some(due)) => due,
193 Ok(None) => break,
194 Err(e) => {
195 failure.set(e);
196 break;
197 }
198 };
199 if due < i64::from(start_frame) {
200 continue;
201 }
202 let due = due as u32;
203 let sent = if abort.late(due) {
204 if skipped < LATE_RUN {
205 skipped += 1;
206 false
207 } else {
208 skipped = 0;
209 send(&out, due, render, tx)
210 }
211 } else if skip_for_speed(speed, start_frame, due, end_frame) {
212 false
213 } else {
214 skipped = 0;
215 send(&out, due, render, tx)
216 };
217 if sent || i64::from(due) + 1 >= i64::from(end_frame) {
218 break;
219 }
220 }
221}
222
223/// Queues one picture through the shared [`Render`]. `true` when the consumer went
224/// away, so the span stops rather than keeps decoding into a void.
225fn send(out: &I420, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
226 let frame = render.frame(due, &out.y, &out.u, &out.v, out.width, out.height);
227 tx.send(frame).is_err()
228}