forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

deinterlace.rs756 lines, 29.4 KiBHistoryRawDownload
1//! Deinterlacing of woven H.264 pictures: a spatial-temporal, motion-adaptive
2//! filter after `bwdif` (Bob Weaver Deinterlacing Filter, itself a yadif
3//! derivative), in Rust and with no dependency.
4//!
5//! `ec-h264` hands over **woven** frames (both fields interleaved on the even
6//! and odd lines) with the field order in [`VideoFrame::interlace`]. This turns
7//! each into one progressive frame of the same rate ("send_frame" in ffmpeg's
8//! words): the field that displays first is kept line for line, and the lines
9//! of the other field are rebuilt from
10//!
11//! * the kept lines above and below (a 4-tap vertical filter, with a
12//! high-frequency term from the temporal neighbours when the picture moves),
13//! * the same lines in the previous and the current frame (what the second
14//! field looked like a field before and a field after the kept one), and
15//! * how much the kept lines changed from the previous to the next frame, which
16//! bounds how far the rebuilt line may stray from the temporal estimate.
17//!
18//! A static picture therefore keeps its full vertical detail, and a moving edge
19//! is interpolated instead of combed. The filter needs the **previous** and the
20//! **next** frame, so [`Deinterlacer`] runs one frame behind its input; the
21//! first frame has itself as its past and the last as its future.
22//!
23//! The double-rate form (one frame per field, 50i -> 50p, a clip's
24//! [`Deinterlace::Field`]) is the same filter run twice per input frame:
25//! [`filter_field`] with the first field kept, then the second with its own
26//! temporal neighbours (the current and the next frame), `bwdif=mode=send_field`.
27
28use std::io::{Read, Seek, SeekFrom};
29use std::path::Path;
30
31use ec_core::registry::{CodecId, CodecParameters};
32use ec_core::{Frame, Interlace, Packet, PixelFormat, Plane, TimeBase, VideoFrame};
33use ec_h264::H264Decoder;
34
35use crate::demux::Demuxer;
36use crate::project::Deinterlace;
37
38/// Which field of a woven frame survives untouched.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Keep {
41 /// The top field (even lines) stays; the odd lines are rebuilt. Top-field-first
42 /// content shown at its frame rate, and the second field of bottom-first
43 /// content in a double-rate output.
44 Top,
45 /// The bottom field (odd lines) stays; the even lines are rebuilt.
46 Bottom,
47}
48
49impl Keep {
50 /// The field a frame-rate output keeps: the one that displays first.
51 pub fn first_of(order: Interlace) -> Keep {
52 match order {
53 Interlace::BottomFieldFirst => Keep::Bottom,
54 _ => Keep::Top,
55 }
56 }
57
58 /// Parity (0 even, 1 odd) of the lines that are rebuilt.
59 fn missing(self) -> usize {
60 match self {
61 Keep::Top => 1,
62 Keep::Bottom => 0,
63 }
64 }
65}
66
67/// The field order of an interlaced H.264 stream, as `ffprobe` spells it
68/// (`"tff"` or `"bff"`), `None` for a stream that is not interlaced.
69///
70/// The stream's own word comes first: the first picture `ec-h264` releases
71/// states its order (the field with the lower picture order count displays
72/// first). A stream that states none falls to the container (an mp4 `fiel`
73/// box, a Matroska `FieldOrder`), and then to top-field-first, which is what
74/// ffmpeg's deinterlacers assume. Leaves `demuxer` at the start of the stream.
75pub fn field_order(demuxer: &mut Demuxer, path: &Path) -> Option<&'static str> {
76 // ProRes, DNxHD and MJPEG state theirs in the first sample, read at open.
77 let intra = demuxer.intra();
78 if intra.interlaced {
79 return Some(if intra.field_order() == Interlace::BottomFieldFirst { "bff" } else { "tff" });
80 }
81 if !demuxer.h264_interlaced() {
82 return None;
83 }
84 let order = stream_order(demuxer);
85 demuxer.seek_to_sync_at_or_before(0);
86 let order = order
87 .filter(|o| o.is_interlaced())
88 .or_else(|| container_order(path))
89 .unwrap_or(Interlace::TopFieldFirst);
90 Some(if order == Interlace::BottomFieldFirst { "bff" } else { "tff" })
91}
92
93/// The order the first decoded picture states.
94fn stream_order(demuxer: &mut Demuxer) -> Option<Interlace> {
95 demuxer.seek_to_sync_at_or_before(0);
96 if demuxer.is_mpeg2() {
97 let decoder = ec_mpeg2::Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video)).ok()?;
98 return first_order(demuxer, decoder, |pic| pic.interlace.is_interlaced());
99 }
100 let decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).ok()?;
101 first_order(demuxer, decoder, |_| true)
102}
103
104/// Feeds `decoder` until a picture `counts` comes out, and returns its order. MPEG-2
105/// skips the pictures coded progressive: they state no order.
106fn first_order<D: ec_core::registry::Decoder>(
107 demuxer: &mut Demuxer,
108 mut decoder: D,
109 counts: impl Fn(&VideoFrame) -> bool,
110) -> Option<Interlace> {
111 let take = |decoder: &mut D| loop {
112 match decoder.receive_frame() {
113 Ok(Frame::Video(pic)) if counts(&pic) => return Some(pic.interlace),
114 Ok(_) => {}
115 Err(_) => return None,
116 }
117 };
118 for _ in 0..64 {
119 let Ok(Some(au)) = demuxer.next_access_unit() else { break };
120 decoder.send_packet(&Packet::new(0, TimeBase::new(1, 1), au)).ok()?;
121 if let Some(order) = take(&mut decoder) {
122 return Some(order);
123 }
124 }
125 decoder.flush().ok()?;
126 take(&mut decoder)
127}
128
129/// What the container says, where it says anything: the mp4 `fiel` box
130/// (QuickTime field-handling, detail 1 and 14 display the top field first, 6
131/// and 9 the bottom) and the Matroska `FieldOrder` element (1 tff, 6 bff).
132/// Looked for in the head and the tail of the file, where an mp4's `moov` and
133/// an mkv's `Tracks` live.
134pub(crate) fn container_order(path: &Path) -> Option<Interlace> {
135 const WINDOW: u64 = 8 << 20;
136 let mut file = std::fs::File::open(path).ok()?;
137 let len = file.metadata().ok()?.len();
138 let mut windows = vec![(0, len.min(WINDOW))];
139 if len > WINDOW {
140 windows.push((len - WINDOW, WINDOW));
141 }
142 for (at, size) in windows {
143 let mut buf = vec![0u8; size as usize];
144 file.seek(SeekFrom::Start(at)).ok()?;
145 file.read_exact(&mut buf).ok()?;
146 if let Some(i) = buf.windows(4).position(|w| w == b"fiel")
147 && let (Some(&count), Some(&detail)) = (buf.get(i + 4), buf.get(i + 5))
148 && count == 2
149 {
150 match detail {
151 1 | 14 => return Some(Interlace::TopFieldFirst),
152 6 | 9 => return Some(Interlace::BottomFieldFirst),
153 _ => {}
154 }
155 }
156 if let Some(head) = buf.get(..65536.min(buf.len()))
157 && let Some(i) = head.windows(2).position(|w| w == [0x9D, 0x81])
158 {
159 match head.get(i + 2) {
160 Some(1) => return Some(Interlace::TopFieldFirst),
161 Some(6) => return Some(Interlace::BottomFieldFirst),
162 _ => {}
163 }
164 }
165 }
166 None
167}
168
169const COEF_LF: [i32; 2] = [4309, 213];
170const COEF_HF: [i32; 3] = [5570, 3801, 1016];
171const COEF_SP: [i32; 2] = [5077, 981];
172
173/// A sample width: 8-bit bytes or 10-bit little-endian words.
174trait Px {
175 const BYTES: usize;
176 const MAX: i32;
177 fn get(row: &[u8], x: usize) -> i32;
178 fn put(row: &mut [u8], x: usize, v: i32);
179}
180
181struct P8;
182struct P16;
183
184impl Px for P8 {
185 const BYTES: usize = 1;
186 const MAX: i32 = 255;
187 #[inline(always)]
188 fn get(row: &[u8], x: usize) -> i32 {
189 i32::from(row[x])
190 }
191 #[inline(always)]
192 fn put(row: &mut [u8], x: usize, v: i32) {
193 row[x] = v as u8;
194 }
195}
196
197impl Px for P16 {
198 const BYTES: usize = 2;
199 const MAX: i32 = 1023;
200 #[inline(always)]
201 fn get(row: &[u8], x: usize) -> i32 {
202 i32::from(u16::from_le_bytes([row[2 * x], row[2 * x + 1]]))
203 }
204 #[inline(always)]
205 fn put(row: &mut [u8], x: usize, v: i32) {
206 row[2 * x..2 * x + 2].copy_from_slice(&(v as u16).to_le_bytes());
207 }
208}
209
210/// One plane of the three frames, read-only.
211#[derive(Clone, Copy)]
212struct Src<'a> {
213 prev: &'a [u8],
214 cur: &'a [u8],
215 next: &'a [u8],
216 /// The frames the rebuilt line's temporal estimate reads (bwdif's `prev2` and
217 /// `next2`): previous and current for the first field of a frame, current and
218 /// next for the second.
219 p2: &'a [u8],
220 n2: &'a [u8],
221 stride: usize,
222 rows: usize,
223}
224
225impl<'a> Src<'a> {
226 #[inline(always)]
227 fn row(&self, data: &'a [u8], y: usize, row_bytes: usize) -> &'a [u8] {
228 &data[y * self.stride..y * self.stride + row_bytes]
229 }
230}
231
232/// Rebuilds row `y` (a missing-parity row) into `dst`.
233#[inline(always)]
234fn line<S: Px>(dst: &mut [u8], src: &Src<'_>, y: usize, w: usize) {
235 let rb = w * S::BYTES;
236 let h = src.rows;
237 // The kept rows around `y`, and the missing rows of the previous and
238 // current frame at `y` (the temporal neighbours `prev2` and `next2`).
239 let above = if y > 0 { y - 1 } else { y + 1 };
240 let below = if y + 1 < h { y + 1 } else { y - 1 };
241 let c = src.row(src.cur, above, rb);
242 let e = src.row(src.cur, below, rb);
243 let pc = src.row(src.prev, above, rb);
244 let pe = src.row(src.prev, below, rb);
245 let nc = src.row(src.next, above, rb);
246 let ne = src.row(src.next, below, rb);
247 let p0 = src.row(src.p2, y, rb);
248 let n0 = src.row(src.n2, y, rb);
249 if y >= 4 && y + 4 < h {
250 let c3 = src.row(src.cur, y - 3, rb);
251 let e3 = src.row(src.cur, y + 3, rb);
252 let pm2 = src.row(src.p2, y - 2, rb);
253 let pp2 = src.row(src.p2, y + 2, rb);
254 let pm4 = src.row(src.p2, y - 4, rb);
255 let pp4 = src.row(src.p2, y + 4, rb);
256 let nm2 = src.row(src.n2, y - 2, rb);
257 let np2 = src.row(src.n2, y + 2, rb);
258 let nm4 = src.row(src.n2, y - 4, rb);
259 let np4 = src.row(src.n2, y + 4, rb);
260 for x in 0..w {
261 let (cv, ev) = (S::get(c, x), S::get(e, x));
262 let (pa, na) = (S::get(p0, x), S::get(n0, x));
263 let d = (pa + na) >> 1;
264 let td0 = (pa - na).abs();
265 let td1 = ((S::get(pc, x) - cv).abs() + (S::get(pe, x) - ev).abs()) >> 1;
266 let td2 = ((S::get(nc, x) - cv).abs() + (S::get(ne, x) - ev).abs()) >> 1;
267 let mut diff = (td0 >> 1).max(td1).max(td2);
268 if diff == 0 {
269 S::put(dst, x, d);
270 continue;
271 }
272 let b = ((S::get(pm2, x) + S::get(nm2, x)) >> 1) - cv;
273 let f = ((S::get(pp2, x) + S::get(np2, x)) >> 1) - ev;
274 let (dc, de) = (d - cv, d - ev);
275 let max = de.max(dc).max(b.min(f));
276 let min = de.min(dc).min(b.max(f));
277 diff = diff.max(min).max(-max);
278 let sum3 = S::get(c3, x) + S::get(e3, x);
279 let interpol = if (cv - ev).abs() > td0 {
280 (((COEF_HF[0] * (pa + na)
281 - COEF_HF[1] * (S::get(pm2, x) + S::get(nm2, x) + S::get(pp2, x) + S::get(np2, x))
282 + COEF_HF[2]
283 * (S::get(pm4, x) + S::get(nm4, x) + S::get(pp4, x) + S::get(np4, x)))
284 >> 2)
285 + COEF_LF[0] * (cv + ev)
286 - COEF_LF[1] * sum3)
287 >> 13
288 } else {
289 (COEF_SP[0] * (cv + ev) - COEF_SP[1] * sum3) >> 13
290 };
291 let v = interpol.clamp(d - diff, d + diff).clamp(0, S::MAX);
292 S::put(dst, x, v);
293 }
294 } else {
295 // The first and last rows have too few neighbours for the long
296 // filter: the plain average, held to the temporal estimate.
297 for x in 0..w {
298 let (cv, ev) = (S::get(c, x), S::get(e, x));
299 let (pa, na) = (S::get(p0, x), S::get(n0, x));
300 let d = (pa + na) >> 1;
301 let td0 = (pa - na).abs();
302 let td1 = ((S::get(pc, x) - cv).abs() + (S::get(pe, x) - ev).abs()) >> 1;
303 let td2 = ((S::get(nc, x) - cv).abs() + (S::get(ne, x) - ev).abs()) >> 1;
304 let diff = (td0 >> 1).max(td1).max(td2);
305 let v = ((cv + ev) >> 1).clamp(d - diff, d + diff).clamp(0, S::MAX);
306 S::put(dst, x, v);
307 }
308 }
309}
310
311/// Rebuilds every missing row of one plane into `out` (a copy of the current
312/// plane), `bands` threads wide.
313fn plane<S: Px>(src: Src<'_>, w: usize, missing: usize, bands: usize) -> Vec<u8> {
314 let mut out = src.cur.to_vec();
315 let stride = src.stride;
316 let rows = src.rows;
317 let work = |first: usize, data: &mut [u8]| {
318 for (i, chunk) in data.chunks_mut(stride).enumerate() {
319 let y = first + i;
320 if y >= rows {
321 break;
322 }
323 if y % 2 == missing {
324 line::<S>(chunk, &src, y, w);
325 }
326 }
327 };
328 if bands <= 1 || rows < 64 {
329 work(0, &mut out);
330 return out;
331 }
332 // Bands of an even number of rows, so every band starts on the same parity.
333 let per = (rows.div_ceil(bands) + 1) & !1;
334 std::thread::scope(|scope| {
335 for (n, data) in out.chunks_mut(per * stride).enumerate() {
336 let work = &work;
337 scope.spawn(move || work(n * per, data));
338 }
339 });
340 out
341}
342
343fn threads_for(width: u32, height: u32) -> usize {
344 if u64::from(width) * u64::from(height) < 400_000 {
345 return 1;
346 }
347 std::thread::available_parallelism().map_or(1, |n| n.get()).min(4)
348}
349
350/// One progressive frame from `cur` and its neighbours. `prev` and `next` are
351/// `cur` itself at the ends of a stream. A frame of a layout other than the planar
352/// 8 and 10-bit 4:2:0, 4:2:2 and 4:4:4 ones (I420, I422, I444, I010, I210, I410), or of different geometry from `cur`, comes back as it is.
353pub fn filter_frame(
354 prev: &VideoFrame,
355 cur: &VideoFrame,
356 next: &VideoFrame,
357 keep: Keep,
358 threads: usize,
359) -> VideoFrame {
360 filter_field(prev, cur, next, keep, false, threads)
361}
362
363/// One progressive picture of a field: `keep` is the field that survives. With
364/// `second` false this is [`filter_frame`] (the first field of a frame, whose
365/// missing lines are estimated from the previous and the current frame); with
366/// `second` true it is bwdif's second field of the same frame, whose missing lines
367/// are estimated from the current and the next frame. A double-rate output is the
368/// first field with `Keep::first_of(order)`, then the other with `second` set.
369pub fn filter_field(
370 prev: &VideoFrame,
371 cur: &VideoFrame,
372 next: &VideoFrame,
373 keep: Keep,
374 second: bool,
375 threads: usize,
376) -> VideoFrame {
377 let mut out = cur.clone();
378 out.interlace = Interlace::Progressive;
379 let wide = match cur.format {
380 PixelFormat::I420 | PixelFormat::I422 | PixelFormat::I444 => false,
381 PixelFormat::I010 | PixelFormat::I210 | PixelFormat::I410 => true,
382 _ => return out,
383 };
384 let same = |f: &VideoFrame| {
385 f.format == cur.format
386 && f.width == cur.width
387 && f.height == cur.height
388 && f.planes.len() == cur.planes.len()
389 && f.planes.iter().zip(&cur.planes).all(|(a, b)| a.stride == b.stride && a.data.len() == b.data.len())
390 };
391 if !same(prev) || !same(next) {
392 return out;
393 }
394 let geometry = cur.format.plane_geometry(cur.width, cur.height);
395 for (i, (row_bytes, rows)) in geometry.into_iter().enumerate() {
396 let src = Src {
397 prev: &prev.planes[i].data,
398 cur: &cur.planes[i].data,
399 next: &next.planes[i].data,
400 p2: if second { &cur.planes[i].data } else { &prev.planes[i].data },
401 n2: if second { &next.planes[i].data } else { &cur.planes[i].data },
402 stride: cur.planes[i].stride,
403 rows,
404 };
405 if rows < 2 {
406 continue;
407 }
408 let data = if wide {
409 plane::<P16>(src, row_bytes / 2, keep.missing(), threads)
410 } else {
411 plane::<P8>(src, row_bytes, keep.missing(), threads)
412 };
413 out.planes[i] = Plane::new(data, src.stride);
414 }
415 out
416}
417
418/// The decode layer's deinterlacing stage: pictures go in in display order with
419/// a tag (their display index), progressive ones come out one input behind.
420///
421/// Disabled it is a pass-through that holds nothing and touches no byte, which
422/// is what keeps every progressive source exactly what it was.
423///
424/// In field mode ([`Deinterlace::Field`](crate::project::Deinterlace)) every
425/// frame comes out as two pictures, the first field's and then the second's,
426/// tagged `2 * tag` and `2 * tag + 1`: the stage's tags are field indices from
427/// then on, and so is `first_wanted`.
428pub struct Deinterlacer {
429 on: bool,
430 /// Whether the stream is interlaced at all, filtered or not (`Off` leaves the
431 /// fields woven, but the stream still has no resumable display index).
432 interlaced: bool,
433 fields: bool,
434 /// Pictures tagged below this are consumed for their neighbours but never
435 /// filtered or returned: the ones a seek decodes before its target.
436 first_wanted: i64,
437 prev: Option<VideoFrame>,
438 cur: Option<(i64, VideoFrame)>,
439 /// The order of the last picture that stated one; a picture that states
440 /// none (a frame picture of an interlaced sequence) takes it.
441 order: Interlace,
442 threads: usize,
443 /// MPEG-2: a picture coded progressive passes untouched; only the pictures that
444 /// state a field order are filtered.
445 flagged_only: bool,
446 /// Pulldown removal ([`crate::ivtc`]): input pictures in, film frames out, tagged
447 /// by output index. When set, nothing else here acts.
448 ivtc: Option<crate::ivtc::Stage>,
449}
450
451impl Deinterlacer {
452 /// `on` for a stream whose SPS says frame_mbs_only_flag = 0. `default_order`
453 /// is what a picture with no order of its own takes until one states it.
454 pub fn new(on: bool, first_wanted: i64, default_order: Interlace) -> Self {
455 Self {
456 on,
457 interlaced: on,
458 fields: false,
459 first_wanted,
460 prev: None,
461 cur: None,
462 order: if default_order.is_interlaced() { default_order } else { Interlace::TopFieldFirst },
463 threads: 0,
464 flagged_only: false,
465 ivtc: None,
466 }
467 }
468
469 /// For [`Deinterlace::Ivtc`] over `demuxer`'s file: the stage that removes its
470 /// pulldown, tags and `first_wanted` being film-frame indices from then on. Any
471 /// other mode, and a file with no cadence, leave the stage as it was.
472 pub fn cadenced(mut self, mode: Deinterlace, demuxer: &Demuxer) -> Self {
473 if mode == Deinterlace::Ivtc
474 && let Some(cadence) =
475 demuxer.path().and_then(|p| crate::ivtc::cadence_for(p, crate::ivtc::Telecine::On))
476 {
477 self.ivtc = Some(crate::ivtc::Stage::new(cadence, self.first_wanted));
478 self.on = true;
479 self.interlaced = true;
480 }
481 self
482 }
483
484 /// The stage for a clip's [`Deinterlace`] setting over a stream that is (or
485 /// is not) `interlaced`. A progressive stream is a pass-through whatever the
486 /// setting; `Off` is a pass-through (the woven pictures as decoded); `Frame`
487 /// is [`Deinterlacer::new`]; `Field` doubles the rate, and `first_wanted` is
488 /// then a field index (see [`Deinterlacer::landing`]).
489 pub fn with_mode(mode: Deinterlace, interlaced: bool, first_wanted: i64, default_order: Interlace) -> Self {
490 let on = interlaced && mode != Deinterlace::Off;
491 Self {
492 fields: on && mode == Deinterlace::Field,
493 interlaced,
494 ..Self::new(on, first_wanted, default_order)
495 }
496 }
497
498 /// For MPEG-2 video, whose pictures each say whether they are interlaced.
499 pub fn flagged_only(mut self) -> Self {
500 self.flagged_only = true;
501 self
502 }
503
504 /// Whether this stage filters at all.
505 pub fn is_on(&self) -> bool {
506 self.on
507 }
508
509 /// Whether the stream is interlaced, filtered or not.
510 pub fn is_interlaced(&self) -> bool {
511 self.interlaced
512 }
513
514 /// Whether this stage doubles the rate: its tags and `first_wanted` count
515 /// fields, two to each frame the demuxer counts.
516 pub fn is_fields(&self) -> bool {
517 self.fields
518 }
519
520 /// The display index of the frame a demuxer seek should land at or before for
521 /// the first wanted picture `start` (a field index in field mode): the frame
522 /// that holds it, and one more before it when the stage filters, so the target
523 /// is filtered with its true predecessor.
524 pub fn landing(&self, start: u32) -> u32 {
525 if let Some(stage) = &self.ivtc {
526 return stage.landing(start);
527 }
528 let frame = if self.fields { start / 2 } else { start };
529 if self.on { frame.saturating_sub(1) } else { frame }
530 }
531
532 /// Takes the next picture in display order. Returns the picture that is now
533 /// complete (its successor has arrived): the same one back when disabled,
534 /// the previous one filtered when enabled, `None` while priming and for a
535 /// picture below `first_wanted`. Frame mode only; a field-mode stage hands
536 /// two pictures per frame, which [`push_all`](Self::push_all) returns.
537 pub fn push(&mut self, tag: i64, pic: VideoFrame) -> Option<(i64, VideoFrame)> {
538 self.push_all(tag, pic).into_iter().next()
539 }
540
541 /// As [`push`](Self::push), for any mode: zero, one or (field mode) two
542 /// pictures, in display order.
543 pub fn push_all(&mut self, tag: i64, pic: VideoFrame) -> Vec<(i64, VideoFrame)> {
544 if let Some(stage) = &mut self.ivtc {
545 return stage.push_all(tag, pic);
546 }
547 if !self.on {
548 return vec![(tag, pic)];
549 }
550 if pic.interlace.is_interlaced() {
551 self.order = pic.interlace;
552 }
553 let done = match self.cur.take() {
554 Some((t, cur)) => {
555 let out = self.emit(t, &cur, &pic);
556 self.prev = Some(cur);
557 out
558 }
559 None => Vec::new(),
560 };
561 self.cur = Some((tag, pic));
562 done
563 }
564
565 /// Ends the stream: the last picture, with itself as its future.
566 pub fn finish(&mut self) -> Option<(i64, VideoFrame)> {
567 self.finish_all().into_iter().next()
568 }
569
570 /// As [`finish`](Self::finish), for any mode.
571 pub fn finish_all(&mut self) -> Vec<(i64, VideoFrame)> {
572 if let Some(stage) = &mut self.ivtc {
573 return stage.finish_all();
574 }
575 if !self.on {
576 return Vec::new();
577 }
578 let Some((t, cur)) = self.cur.take() else { return Vec::new() };
579 let next = cur.clone();
580 self.emit(t, &cur, &next)
581 }
582
583 fn emit(&mut self, tag: i64, cur: &VideoFrame, next: &VideoFrame) -> Vec<(i64, VideoFrame)> {
584 let count = if self.fields { 2 } else { 1 };
585 let base = if self.fields { 2 * tag } else { tag };
586 if base + count <= self.first_wanted {
587 return Vec::new();
588 }
589 if self.flagged_only && !cur.interlace.is_interlaced() {
590 return vec![(tag, cur.clone())];
591 }
592 if self.threads == 0 {
593 self.threads = threads_for(cur.width, cur.height);
594 }
595 let order = if cur.interlace.is_interlaced() { cur.interlace } else { self.order };
596 let prev = self.prev.as_ref().unwrap_or(cur);
597 let first = Keep::first_of(order);
598 let second = match first {
599 Keep::Top => Keep::Bottom,
600 Keep::Bottom => Keep::Top,
601 };
602 let mut out = Vec::with_capacity(2);
603 for k in 0..count {
604 if base + k < self.first_wanted {
605 continue;
606 }
607 let pic = match k {
608 0 => filter_field(prev, cur, next, first, false, self.threads),
609 _ => filter_field(prev, cur, next, second, true, self.threads),
610 };
611 out.push((base + k, pic));
612 }
613 out
614 }
615}
616
617/// Whether `path` is interlaced H.264, which is the only thing a clip's
618/// deinterlace setting acts on. Remembered per path.
619pub fn is_interlaced(path: &Path) -> bool {
620 use std::collections::HashMap;
621 use std::sync::{Mutex, OnceLock};
622 static KNOWN: OnceLock<Mutex<HashMap<std::path::PathBuf, bool>>> = OnceLock::new();
623 let known = KNOWN.get_or_init(Default::default);
624 if let Some(&v) = known.lock().ok().and_then(|k| k.get(path).copied()).as_ref() {
625 return v;
626 }
627 let v = Demuxer::open(path)
628 .is_ok_and(|(meta, d)| meta.codec == crate::demux::Codec::H264 && d.h264_interlaced());
629 if let Ok(mut k) = known.lock() {
630 k.insert(path.to_path_buf(), v);
631 }
632 v
633}
634
635/// The setting that actually applies to `path`: the clip's own for interlaced
636/// H.264, [`Deinterlace::Frame`] for every other source (which ignores it). The two
637/// pulldown settings resolve here: to [`Deinterlace::Ivtc`] when the file has a
638/// cadence to remove (`IvtcAuto`: a clear one), else to `Frame`.
639pub fn effective(mode: Deinterlace, path: &Path) -> Deinterlace {
640 use crate::ivtc::{Telecine, cadence_for};
641 match mode {
642 Deinterlace::Ivtc if cadence_for(path, Telecine::On).is_some() => Deinterlace::Ivtc,
643 Deinterlace::IvtcAuto if cadence_for(path, Telecine::Auto).is_some() => Deinterlace::Ivtc,
644 Deinterlace::Ivtc | Deinterlace::IvtcAuto => Deinterlace::Frame,
645 _ if mode != Deinterlace::Frame && !is_interlaced(path) => Deinterlace::Frame,
646 _ => mode,
647 }
648}
649
650/// Frames of a file with `frames` pictures, as the decode layer numbers them under
651/// `mode` (already [`effective`]): fields in field mode, film frames under
652/// [`Deinterlace::Ivtc`], pictures otherwise.
653pub fn counted_frames(mode: Deinterlace, path: &Path, frames: u32) -> u32 {
654 match mode {
655 Deinterlace::Field => frames * 2,
656 Deinterlace::Ivtc => crate::ivtc::cadence_for(path, crate::ivtc::Telecine::On)
657 .map_or(frames, |c| c.out_count(frames)),
658 _ => frames,
659 }
660}
661
662/// `rate` (a file's frames per timeline frame) for the way `mode` (already
663/// [`effective`]) numbers a file's pictures: doubled in field mode, four fifths of
664/// it once pulldown is removed.
665pub fn counted_rate(mode: Deinterlace, rate: crate::project::Rate) -> crate::project::Rate {
666 match mode {
667 Deinterlace::Field => fields_rate(rate),
668 Deinterlace::Ivtc => film_rate(rate),
669 _ => rate,
670 }
671}
672
673/// The file's picture that decode-layer frame `n` (numbered as `mode`, already
674/// [`effective`], numbers them) comes from.
675pub fn file_frame(mode: Deinterlace, path: &Path, n: u32) -> u32 {
676 match mode {
677 Deinterlace::Field => n / 2,
678 Deinterlace::Ivtc => crate::ivtc::cadence_for(path, crate::ivtc::Telecine::On).map_or(n, |c| c.input_of(n)),
679 _ => n,
680 }
681}
682
683/// `rate` for a file whose pulldown is removed: 4 film frames for every 5 pictures.
684pub fn film_rate(rate: crate::project::Rate) -> crate::project::Rate {
685 rate.then(crate::project::Rate::from_fps(24.0, 30.0).unwrap_or(crate::project::Rate::REAL_TIME))
686}
687
688/// `rate` (a file's frames per timeline frame) for a source whose pictures are
689/// fields: twice as many of them per timeline frame, counted from the file's first
690/// field. The one conversion a field-mode clip's frame mapping needs; the decode
691/// layer's frame numbers are then field numbers (`2 * frame + 0 or 1`).
692pub fn fields_rate(rate: crate::project::Rate) -> crate::project::Rate {
693 rate.then(crate::project::Rate::from_fps(2.0, 1.0).unwrap_or(crate::project::Rate::REAL_TIME))
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699
700 fn frame(w: u32, h: u32, f: impl Fn(usize, usize) -> u8) -> VideoFrame {
701 let mut v = VideoFrame::alloc(PixelFormat::I420, w, h);
702 for (i, plane) in v.planes.iter_mut().enumerate() {
703 let stride = plane.stride;
704 let data: Vec<u8> = (0..plane.data.len())
705 .map(|n| if i == 0 { f(n % stride, n / stride) } else { 128 })
706 .collect();
707 *plane = Plane::new(data, stride);
708 }
709 v.interlace = Interlace::TopFieldFirst;
710 v
711 }
712
713 #[test]
714 fn a_static_picture_keeps_its_kept_field_and_a_flat_one_is_unchanged() {
715 let flat = frame(64, 64, |_, _| 90);
716 let out = filter_frame(&flat, &flat, &flat, Keep::Top, 1);
717 assert!(out.planes[0].data.iter().all(|&b| b == 90));
718 let stripes = frame(64, 64, |_, y| (y * 3) as u8);
719 let out = filter_frame(&stripes, &stripes, &stripes, Keep::Top, 1);
720 // Kept (even) lines are untouched; a static picture's rebuilt lines are
721 // its own (the temporal estimate), so nothing moves at all.
722 assert!(out.planes[0].data == stripes.planes[0].data);
723 assert_eq!(out.interlace, Interlace::Progressive);
724 }
725
726 #[test]
727 fn a_disabled_stage_is_the_identity_with_no_delay() {
728 let a = frame(32, 32, |x, y| (x + y) as u8);
729 let mut d = Deinterlacer::new(false, 0, Interlace::Progressive);
730 let (t, out) = d.push(7, a.clone()).expect("immediately");
731 assert_eq!(t, 7);
732 assert!(out == a);
733 assert!(d.finish().is_none());
734 }
735
736 #[test]
737 fn the_stage_runs_one_behind_and_drains_at_the_end() {
738 let a = frame(32, 32, |x, y| (x + y) as u8);
739 let mut d = Deinterlacer::new(true, 0, Interlace::Progressive);
740 assert!(d.push(0, a.clone()).is_none());
741 assert_eq!(d.push(1, a.clone()).map(|o| o.0), Some(0));
742 assert_eq!(d.finish().map(|o| o.0), Some(1));
743 assert!(d.finish().is_none());
744 }
745
746 #[test]
747 fn threaded_and_single_thread_agree() {
748 let f = |x: usize, y: usize| ((x * 7 + y * 13) ^ (y * y)) as u8;
749 let (a, b, c) = (frame(200, 300, f), frame(200, 300, |x, y| f(x + 3, y)), frame(200, 300, |x, y| f(x + 6, y)));
750 assert!(filter_frame(&a, &b, &c, Keep::Top, 1) == filter_frame(&a, &b, &c, Keep::Top, 4));
751 assert!(filter_frame(&a, &b, &c, Keep::Bottom, 1) == filter_frame(&a, &b, &c, Keep::Bottom, 3));
752 }
753}
754
755#[cfg(test)]
756mod session_tests;