forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

intra.rs452 lines, 19.2 KiBHistoryRawDownload
1//! What the three intra-only software seats (`ec-prores`, `ec-dnxhd`, `ec-mjpeg`) share:
2//! the pulled [`Stream`], the span loop [`run`], and the first-sample probe the demuxer
3//! reads a file's facts with ([`probe`]).
4//!
5//! **Seeking.** Every picture of these codecs is a sync sample and references nothing, so
6//! a span starts exactly on its first frame and a seek is one sample read: no
7//! decode-and-drop, and a mid-file start decodes exactly what a sequential decode
8//! reaches. The one exception is an interlaced stream, whose deinterlacer
9//! ([`crate::deinterlace`], the stage H.264 and MPEG-2 use) wants the picture before: the
10//! span then starts one frame earlier and sends nothing before the target.
11//!
12//! **Pictures.** The seats hand over `I420`, `I422`, `I444` (8 bit), `I210`, `I410`, `I412`
13//! (10 and 12 bit), or `Gray8` (MJPEG). [`canon`] folds those into the six shapes the
14//! deinterlacer and [`Deep`] carry: 12-bit is narrowed to 10 (`>> 2`), gray gets neutral
15//! chroma. 4:2:2 and 4:4:4 are averaged down to 4:2:0 by [`Deep`] exactly as H.264 and
16//! HEVC 4:2:2 / 4:4:4 are. ProRes alpha is dropped: the engine has no alpha path for a
17//! video clip (a clip is composited as opaque YUV), so the seat decodes the picture alone.
18//!
19//! **Range.** MJPEG is full range (`yuvj`): [`probe`] states it as the stream's own colour
20//! tags, so the same conversion every full-range source takes applies to it.
21
22use std::sync::mpsc::SyncSender;
23
24use ec_core::frame::{Interlace, PixelFormat, Plane, VideoFrame};
25use ec_core::registry::{CodecId, CodecParameters, MediaParameters};
26
27use super::{Abort, Deep, DecodeFailure, Frame, I420, LATE_RUN, Render, Wide, skip_for_speed};
28use crate::colorspace::{Chroma, Tags};
29use crate::deinterlace::Deinterlacer;
30use crate::demux::{Codec, Demuxer, VideoMeta};
31use crate::project::Speed;
32
33/// The container-independent facts of an intra-only stream that its first sample states.
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
35pub(crate) struct IntraFacts {
36 /// Whether the pictures are two woven fields.
37 pub interlaced: bool,
38 /// The field that displays first: the stream's own word where it has one (ProRes,
39 /// DNxHD), else the container's `fiel` / `FieldOrder`, else top first.
40 pub order: Interlace,
41 /// The container's coded height: what steers MJPEG's two-field packet rule.
42 pub coded_height: u32,
43}
44
45impl IntraFacts {
46 /// `order`, never `Progressive`.
47 pub(crate) fn field_order(self) -> Interlace {
48 if self.order.is_interlaced() { self.order } else { Interlace::TopFieldFirst }
49 }
50}
51
52/// What reading a stream's first sample tells the demuxer about the track.
53pub(crate) struct Probed {
54 pub facts: IntraFacts,
55 pub bit_depth: u8,
56 pub chroma: Chroma,
57 /// Only where the sample states it (DNxHD's compression id); ProRes' comes from the
58 /// sample entry's fourcc.
59 pub profile: Option<&'static str>,
60 /// The colour the stream itself states, merged under the container's.
61 pub tags: Tags,
62}
63
64/// Decodes `sample` (a stream's first) with the seat for `codec` and reads the facts off
65/// the header and the picture. `Ok(None)` when the sample does not decode (a damaged
66/// first frame is the decode's to report, not the open's); `Err` only for a refusal by
67/// name (`Unsupported`), which fails the open the way a refused H.264 profile does.
68pub(crate) fn probe(
69 codec: Codec,
70 sample: &[u8],
71 meta: &VideoMeta,
72 container_order: Option<Interlace>,
73 header: &[u8],
74) -> Result<Option<Probed>, String> {
75 let named = |e: ec_core::Error| match e {
76 ec_core::Error::Unsupported { .. } => Err(format!("{} is not supported: {e}", codec.name())),
77 _ => Ok(None),
78 };
79 match codec {
80 Codec::ProRes => {
81 let mut d = ec_prores::ProResDecoder::new(CodecParameters::new(CodecId::ProRes)).map_err(|e| e.to_string())?;
82 d.set_threads(1);
83 let full = match d.decode_full(sample) {
84 Ok(f) => f,
85 Err(e) => return named(e),
86 };
87 let i = full.info;
88 Ok(Some(Probed {
89 facts: IntraFacts { interlaced: i.interlace.is_interlaced(), order: i.interlace, coded_height: meta.coded_height },
90 bit_depth: if i.is_444 { 12 } else { 10 },
91 chroma: if i.is_444 { Chroma::C444 } else { Chroma::C422 },
92 profile: None,
93 tags: Tags::from_codes(u64::from(i.matrix), u64::from(i.transfer), 0).with_primaries(u64::from(i.primaries)),
94 }))
95 }
96 Codec::Dnxhd => {
97 let mut d = ec_dnxhd::DnxhdDecoder::new(CodecParameters::new(CodecId::Dnxhd)).map_err(|e| e.to_string())?;
98 d.set_threads(1);
99 let pic = match d.decode_native(sample) {
100 Ok(p) => p,
101 Err(e) => return named(e),
102 };
103 let i = pic.info;
104 let order = match (i.interlaced, i.top_field_first) {
105 (false, _) => Interlace::Progressive,
106 (true, true) => Interlace::TopFieldFirst,
107 (true, false) => Interlace::BottomFieldFirst,
108 };
109 Ok(Some(Probed {
110 facts: IntraFacts { interlaced: i.interlaced, order, coded_height: meta.coded_height },
111 bit_depth: i.bit_depth as u8,
112 chroma: match i.chroma {
113 ec_dnxhd::Chroma::C444 => Chroma::C444,
114 _ => Chroma::C422,
115 },
116 profile: crate::video_profile::dnxhd(i.cid, i.bit_depth, sample.len(), meta.frame_rate),
117 tags: Tags::from_codes(u64::from(i.matrix), 0, 0),
118 }))
119 }
120 Codec::Mjpeg => {
121 let mut d = mjpeg_decoder(meta.coded_height, container_order.unwrap_or(Interlace::TopFieldFirst))?;
122 let pic = match d.decode(sample, None) {
123 Ok(p) => p,
124 Err(e) => return named(e),
125 };
126 let interlaced = pic.interlace.is_interlaced();
127 Ok(Some(Probed {
128 facts: IntraFacts {
129 interlaced,
130 order: if interlaced { pic.interlace } else { Interlace::Progressive },
131 coded_height: meta.coded_height,
132 },
133 bit_depth: 8,
134 chroma: match pic.format {
135 PixelFormat::Gray8 => Chroma::Gray,
136 PixelFormat::I422 => Chroma::C422,
137 PixelFormat::I444 => Chroma::C444,
138 _ => Chroma::C420,
139 },
140 profile: None,
141 // JFIF: BT.601, every code used. Stated as the stream's own word so the
142 // conversion reads a `yuvj` file as the full-range source it is; a container
143 // that states its own (an mp4 `colr`) still wins over it.
144 tags: Tags {
145 full_range: Some(true),
146 ..Tags::from_codes(5, 0, 0)
147 },
148 }))
149 }
150 Codec::Dv => {
151 let mut d = ec_dv::DvDecoder::new(CodecParameters::new(CodecId::DvVideo)).map_err(|e| e.to_string())?;
152 let pic = match d.decode_native(sample) {
153 Ok(p) => p,
154 Err(e) => return named(e),
155 };
156 let interlaced = pic.interlace.is_interlaced();
157 Ok(Some(Probed {
158 facts: IntraFacts {
159 interlaced,
160 // The VAUX pack states the order (bottom first for 525 and 625 DV25 and
161 // DV50, top first for DVCPRO HD).
162 order: if interlaced { pic.interlace } else { Interlace::Progressive },
163 coded_height: meta.coded_height,
164 },
165 bit_depth: 8,
166 // 4:1:1 comes out widened to 4:2:2 (exact chroma duplication).
167 chroma: match pic.chroma {
168 ec_dv::Chroma::Yuv420 => Chroma::C420,
169 ec_dv::Chroma::Yuv411 | ec_dv::Chroma::Yuv422 => Chroma::C422,
170 },
171 profile: Some(crate::video_profile::dv(pic.profile)),
172 // Untagged: the size rule reads 525 and 625 lines as BT.601 and DVCPRO HD as BT.709.
173 tags: Tags::default(),
174 }))
175 }
176 Codec::Raw => {
177 let seat = super::raw::RawSeat::open(IntraFacts::default(), header)?;
178 let pic = match seat.0.decode(sample) {
179 Ok(p) => p,
180 Err(e) => return named(e),
181 };
182 let full = Tags { full_range: Some(true), ..Tags::default() };
183 let (chroma, tags, bit_depth) = match pic.format {
184 // RGB is converted to full-range BT.709 4:4:4 by the seat, and says so.
185 PixelFormat::Bgr8 | PixelFormat::Rgb8 | PixelFormat::Bgra8 => {
186 (Chroma::C444, Tags { full_range: Some(true), ..Tags::from_codes(1, 0, 0) }, 8)
187 }
188 PixelFormat::I422 => (Chroma::C422, Tags::default(), 8),
189 PixelFormat::I210 => (Chroma::C422, Tags::default(), 10),
190 PixelFormat::I410 => (Chroma::C444, Tags::default(), 10),
191 // Gray is full range to ffmpeg and to JPEG alike.
192 PixelFormat::Gray8 => (Chroma::Gray, full, 8),
193 PixelFormat::Gray16 => (Chroma::Gray, full, 10),
194 _ => (Chroma::C420, Tags::default(), 8),
195 };
196 Ok(Some(Probed {
197 facts: IntraFacts { coded_height: meta.coded_height, ..IntraFacts::default() },
198 bit_depth,
199 chroma,
200 profile: Some(crate::video_profile::raw(header)),
201 tags,
202 }))
203 }
204 _ => Ok(None),
205 }
206}
207
208pub(super) fn mjpeg_decoder(container_height: u32, order: Interlace) -> Result<ec_mjpeg::MjpegDecoder, String> {
209 let mut params = CodecParameters::new(CodecId::Mjpeg);
210 if let MediaParameters::Video(v) = &mut params.media {
211 v.height = container_height;
212 }
213 let mut d = ec_mjpeg::MjpegDecoder::new(params).map_err(|e| e.to_string())?;
214 d.set_field_order(order);
215 Ok(d)
216}
217
218/// An intra-only software decoder: one sample in, one picture out.
219pub(crate) trait Seat: Sized {
220 const NAME: &'static str;
221 /// `header` is the container's picture header where the codec has none of its own (an AVI's
222 /// raw video `BITMAPINFOHEADER`); empty otherwise.
223 fn open(facts: IntraFacts, header: &[u8]) -> Result<Self, String>;
224 fn decode(&mut self, sample: &[u8]) -> Result<VideoFrame, String>;
225}
226
227/// One intra-only decode, pulled a picture at a time.
228pub(crate) struct Stream<S: Seat> {
229 seat: Result<S, String>,
230 /// Display index of the next picture. Signed like the other seats'.
231 index: i64,
232 flushed: bool,
233 deint: Deinterlacer,
234 deep: Deep,
235 scratch: I420,
236}
237
238impl<S: Seat> Stream<S> {
239 /// A decoder positioned on `start_frame` (one earlier for an interlaced stream, whose
240 /// deinterlacer wants the picture before).
241 pub(crate) fn open(demuxer: &mut Demuxer, start_frame: u32) -> Self {
242 let facts = demuxer.intra();
243 let index = demuxer.seek_to_sync_at_or_before(if facts.interlaced {
244 start_frame.saturating_sub(1)
245 } else {
246 start_frame
247 });
248 Self {
249 seat: S::open(facts, demuxer.video_params().map_or(&[][..], |p| p.3)),
250 index,
251 flushed: false,
252 deint: Deinterlacer::new(facts.interlaced, i64::from(start_frame), Interlace::Progressive).flagged_only(),
253 deep: Deep::default(),
254 scratch: I420::default(),
255 }
256 }
257
258 /// The next picture in display order, narrowed to 8-bit 4:2:0 into `out`.
259 pub(crate) fn next(&mut self, demuxer: &mut Demuxer, out: &mut I420) -> Result<Option<i64>, String> {
260 self.pull(demuxer, Some(out), None)
261 }
262
263 /// As [`Self::next`], at 10-bit scale into `out` (an 8-bit picture shifted up by two).
264 pub(crate) fn next_wide(&mut self, demuxer: &mut Demuxer, out: &mut Wide) -> Result<Option<i64>, String> {
265 self.pull(demuxer, None, Some(out))
266 }
267
268 fn pull(
269 &mut self,
270 demuxer: &mut Demuxer,
271 mut narrow: Option<&mut I420>,
272 mut wide: Option<&mut Wide>,
273 ) -> Result<Option<i64>, String> {
274 loop {
275 if self.flushed {
276 return match self.deint.finish() {
277 Some((due, pic)) => {
278 self.fill(&pic, narrow.as_deref_mut(), wide.as_deref_mut());
279 Ok(Some(due))
280 }
281 None => Ok(None),
282 };
283 }
284 match demuxer.next_access_unit() {
285 Ok(Some(sample)) => {
286 let seat = self.seat.as_mut().map_err(|e| e.clone())?;
287 let pic = seat
288 .decode(&sample)
289 .map_err(|e| format!("software {} decode failed at frame {}: {e}", S::NAME, self.index))?;
290 let tag = self.index;
291 self.index += 1;
292 let Some(pic) = canon(pic) else {
293 return Err(format!("software {} frame {tag} has a pixel layout edith does not carry", S::NAME));
294 };
295 if let Some((due, pic)) = self.deint.push(tag, pic) {
296 self.fill(&pic, narrow.as_deref_mut(), wide.as_deref_mut());
297 return Ok(Some(due));
298 }
299 }
300 Ok(None) => self.flushed = true,
301 Err(e) => return Err(format!("demux error: {e}")),
302 }
303 }
304 }
305
306 /// `pic` (one of the six canonical shapes) into whichever output is asked for.
307 fn fill(&mut self, pic: &VideoFrame, narrow: Option<&mut I420>, wide: Option<&mut Wide>) {
308 let sixteen = matches!(pic.format, PixelFormat::I010 | PixelFormat::I210 | PixelFormat::I410);
309 match (narrow, wide) {
310 (Some(out), _) => self.fill_narrow(pic, out),
311 (None, Some(out)) if sixteen => {
312 self.deep.load(pic, true);
313 std::mem::swap(out, &mut self.deep.wide);
314 }
315 (None, Some(out)) => {
316 let mut tmp = std::mem::take(&mut self.scratch);
317 self.fill_narrow(pic, &mut tmp);
318 out.width = tmp.width;
319 out.height = tmp.height;
320 for (src, dst) in [(&tmp.y, &mut out.y), (&tmp.u, &mut out.u), (&tmp.v, &mut out.v)] {
321 dst.clear();
322 dst.extend(src.iter().map(|&s| u16::from(s) << 2));
323 }
324 self.scratch = tmp;
325 }
326 (None, None) => {}
327 }
328 }
329
330 fn fill_narrow(&mut self, pic: &VideoFrame, out: &mut I420) {
331 if pic.format == PixelFormat::I420 {
332 out.width = pic.width;
333 out.height = pic.height;
334 let (cw, ch) = (pic.width.div_ceil(2) as usize, pic.height.div_ceil(2) as usize);
335 let dims = [(pic.width as usize, pic.height as usize), (cw, ch), (cw, ch)];
336 for ((plane, (w, h)), dst) in pic.planes.iter().zip(dims).zip([&mut out.y, &mut out.u, &mut out.v]) {
337 dst.clear();
338 for row in plane.data.chunks(plane.stride).take(h) {
339 dst.extend_from_slice(&row[..w]);
340 }
341 }
342 } else {
343 self.deep.load(pic, false);
344 std::mem::swap(out, &mut self.deep.narrow);
345 }
346 }
347}
348
349/// Folds a seat's picture into I420, I422, I444, I010, I210 or I410: 12-bit goes to 10
350/// (`>> 2`) and gray gets neutral chroma. `None` for a layout no seat produces.
351fn canon(pic: VideoFrame) -> Option<VideoFrame> {
352 match pic.format {
353 PixelFormat::I420
354 | PixelFormat::I422
355 | PixelFormat::I444
356 | PixelFormat::I010
357 | PixelFormat::I210
358 | PixelFormat::I410 => Some(pic),
359 PixelFormat::I412 => {
360 let mut out = VideoFrame::alloc(PixelFormat::I410, pic.width, pic.height);
361 out.color = pic.color;
362 out.pts = pic.pts;
363 out.interlace = pic.interlace;
364 for (dst, src) in out.planes.iter_mut().zip(&pic.planes) {
365 let stride = dst.stride;
366 let mut data = vec![0u8; dst.data.len()];
367 for (row, line) in data.chunks_mut(stride).enumerate() {
368 let from = &src.data[row * src.stride..row * src.stride + stride];
369 for (d, s) in line.as_chunks_mut::<2>().0.iter_mut().zip(from.as_chunks::<2>().0) {
370 *d = (u16::from_le_bytes(*s) >> 2).to_le_bytes();
371 }
372 }
373 *dst = Plane::new(data, stride);
374 }
375 Some(out)
376 }
377 PixelFormat::Gray8 => {
378 let mut out = VideoFrame::alloc(PixelFormat::I420, pic.width, pic.height);
379 out.color = pic.color;
380 out.pts = pic.pts;
381 out.interlace = pic.interlace;
382 let w = pic.width as usize;
383 let mut luma = vec![0u8; out.planes[0].data.len()];
384 for (row, line) in luma.chunks_mut(out.planes[0].stride).enumerate() {
385 line[..w].copy_from_slice(&pic.planes[0].data[row * pic.planes[0].stride..][..w]);
386 }
387 out.planes[0] = Plane::new(luma, out.planes[0].stride);
388 for p in 1..3 {
389 let stride = out.planes[p].stride;
390 out.planes[p] = Plane::new(vec![128u8; out.planes[p].data.len()], stride);
391 }
392 Some(out)
393 }
394 _ => None,
395 }
396}
397
398/// The span loop for any intra-only seat: `[start_frame, end_frame)` through the shared
399/// [`Render`], with the same lateness and speed rules every software seat applies.
400// The eight inputs every software span takes (`run_hevc` has the same shape).
401#[allow(clippy::too_many_arguments)]
402pub(super) fn run<S: Seat>(
403 demuxer: &mut Demuxer,
404 tx: &SyncSender<Frame>,
405 start_frame: u32,
406 end_frame: u32,
407 render: &mut Render,
408 abort: &Abort,
409 speed: Speed,
410 failure: &DecodeFailure,
411) {
412 let mut stream = Stream::<S>::open(demuxer, start_frame);
413 let mut out = I420::default();
414 let mut skipped = 0;
415 while !abort.hit() {
416 let due = match stream.next(demuxer, &mut out) {
417 Ok(Some(due)) => due,
418 Ok(None) => break,
419 Err(e) => {
420 failure.set(e);
421 break;
422 }
423 };
424 if due < i64::from(start_frame) {
425 continue;
426 }
427 let due = due as u32;
428 let sent = if abort.late(due) {
429 if skipped < LATE_RUN {
430 skipped += 1;
431 false
432 } else {
433 skipped = 0;
434 send(&out, due, render, tx)
435 }
436 } else if skip_for_speed(speed, start_frame, due, end_frame) {
437 false
438 } else {
439 skipped = 0;
440 send(&out, due, render, tx)
441 };
442 if sent || i64::from(due) + 1 >= i64::from(end_frame) {
443 break;
444 }
445 }
446}
447
448/// Queues one picture through the shared [`Render`]. `true` when the consumer went away.
449fn send(out: &I420, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
450 let frame = render.frame(due, &out.y, &out.u, &out.v, out.width, out.height);
451 tx.send(frame).is_err()
452}