forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

ivtc.rs508 lines, 19.1 KiBHistoryRawDownload
1//! Inverse telecine ("remove pulldown"): 29.97i film that carries 23.976p pictures
2//! in 3:2 pulldown comes back as the 23.976p pictures.
3//!
4//! **Hard pulldown** is baked into the pictures. Four film frames A B C D become
5//! five interlaced frames `AA BB BC CD DD` (field pairs; the 2-3 pattern, and its
6//! rotations such as `AA AB BC CC DD`): three of the five are clean, and two
7//! consecutive ones are mixed, each holding one field of C and one of another
8//! film frame. Within every block of five, the mixed pair starts at the input
9//! frame whose index is `phase` modulo five, so
10//!
11//! * the clean frames are the film frames as they are,
12//! * the mixed pair `(m, m + 1)` is one film frame: the second field of `m` and the
13//! first field of `m + 1` (a field match, ffmpeg's `fieldmatch`), woven together,
14//! * the second frame of the pair is dropped (the decimation, ffmpeg's `decimate`):
15//! five frames in, four out.
16//!
17//! The mapping of output frame `k` to input frames is then pure arithmetic
18//! ([`Cadence::input_of`]), so a seek lands on the same picture a sequential decode
19//! gives, and the output timeline is exactly 4/5 of the input's frame rate.
20//!
21//! The phase and the field order are found once per file by [`cadence_for`], from the
22//! first [`SAMPLE`] pictures: for each candidate phase the woven film frame must be
23//! free of combing where its two source frames are combed, in every block that has
24//! motion in it. Material that is truly interlaced (every frame combed) never
25//! satisfies that, so [`Telecine::Auto`] leaves it to the deinterlacer. One cadence
26//! is assumed for the whole file: a cadence broken by an edit is not followed.
27//!
28//! **Soft pulldown** (MPEG-2 `repeat_first_field`, H.264 `pic_struct`) leaves the
29//! film frames coded as they are and only asks the player to repeat fields; the
30//! decoder counts coded pictures, which are the 23.976p frames, so the only work is
31//! to state their rate ([`Repeats`] finds the flags; the transport stream reader
32//! states the rate).
33
34use std::collections::HashMap;
35use std::path::{Path, PathBuf};
36use std::sync::{Mutex, OnceLock};
37
38use ec_core::registry::{CodecId, CodecParameters, Decoder};
39use ec_core::{Frame, Interlace, Packet, PixelFormat, Plane, TimeBase, VideoFrame};
40
41use crate::demux::{Codec, Demuxer};
42
43/// Pictures looked at to find the cadence: twelve blocks of five.
44pub const SAMPLE: usize = 60;
45
46/// Where the mixed pair of a block of five starts, and which field displays first.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct Cadence {
49 /// Input frames `i` with `i % 5 == phase` start a mixed pair.
50 pub phase: u8,
51 /// `TopFieldFirst` or `BottomFieldFirst`.
52 pub order: Interlace,
53}
54
55impl Cadence {
56 fn skipped(self, i: u32) -> bool {
57 (i % 5 + 5 - u32::from(self.phase)) % 5 == 1
58 }
59
60 fn starts_pair(self, i: u32) -> bool {
61 i % 5 == u32::from(self.phase)
62 }
63
64 /// The four offsets in a block of five that produce an output.
65 fn offsets(self) -> [u32; 4] {
66 let mut out = [0; 4];
67 let mut n = 0;
68 for k in 0..5 {
69 if !self.skipped(k) {
70 out[n] = k;
71 n += 1;
72 }
73 }
74 out
75 }
76
77 /// The input frame that starts output frame `k` (for a woven one, the first of
78 /// its two).
79 pub fn input_of(self, k: u32) -> u32 {
80 5 * (k / 4) + self.offsets()[(k % 4) as usize]
81 }
82
83 /// The output frame input frame `i` produces (starts), `None` for the dropped one.
84 pub fn output_of(self, i: u32) -> Option<u32> {
85 if self.skipped(i) {
86 return None;
87 }
88 Some(4 * (i / 5) + self.offsets().iter().filter(|&&o| o < i % 5).count() as u32)
89 }
90
91 /// How many output frames `frames` input frames make.
92 pub fn out_count(self, frames: u32) -> u32 {
93 4 * (frames / 5) + self.offsets().iter().filter(|&&o| o < frames % 5).count() as u32
94 }
95}
96
97/// The film frame in a mixed pair: `first` supplies the rows of the field that
98/// displays first, `second` those of the one that displays second (the pair's first
99/// frame, which holds the film frame as its second field).
100pub fn weave(first: &VideoFrame, second: &VideoFrame, order: Interlace) -> VideoFrame {
101 let mut out = first.clone();
102 out.interlace = Interlace::Progressive;
103 let parity = if order == Interlace::BottomFieldFirst { 0 } else { 1 };
104 let alike = first.format == second.format
105 && first.width == second.width
106 && first.height == second.height
107 && first.planes.len() == second.planes.len();
108 if !alike {
109 return out;
110 }
111 let geometry = first.format.plane_geometry(first.width, first.height);
112 for (i, (row_bytes, rows)) in geometry.into_iter().enumerate() {
113 let (stride, src) = (out.planes[i].stride, &second.planes[i]);
114 if src.stride != stride || src.data.len() != out.planes[i].data.len() {
115 continue;
116 }
117 let mut data = out.planes[i].data.to_vec();
118 for y in (parity..rows).step_by(2) {
119 let (a, b) = (y * stride, y * stride + row_bytes);
120 if b <= data.len() {
121 data[a..b].copy_from_slice(&src.data[a..b]);
122 }
123 }
124 out.planes[i] = Plane::new(data, stride);
125 }
126 out
127}
128
129/// The decode layer's stage: input frames in display order with their display index,
130/// the film frames out, tagged with their output index.
131pub struct Stage {
132 cadence: Cadence,
133 /// Output frames below this are dropped (a seek decodes from earlier).
134 first_wanted: i64,
135 /// The first frame of a mixed pair, waiting for its second.
136 held: Option<(i64, VideoFrame)>,
137}
138
139impl Stage {
140 pub fn new(cadence: Cadence, first_wanted: i64) -> Self {
141 Self { cadence, first_wanted, held: None }
142 }
143
144 /// The input frame a demuxer seek should land at or before for output `start`.
145 pub fn landing(&self, start: u32) -> u32 {
146 self.cadence.input_of(start)
147 }
148
149 fn solo(&self, pic: &VideoFrame) -> VideoFrame {
150 let keep = crate::deinterlace::Keep::first_of(self.cadence.order);
151 crate::deinterlace::filter_frame(pic, pic, pic, keep, 1)
152 }
153
154 fn tagged(&self, i: u32, pic: VideoFrame) -> Vec<(i64, VideoFrame)> {
155 match self.cadence.output_of(i) {
156 Some(k) if i64::from(k) >= self.first_wanted => vec![(i64::from(k), pic)],
157 _ => Vec::new(),
158 }
159 }
160
161 pub fn push_all(&mut self, tag: i64, pic: VideoFrame) -> Vec<(i64, VideoFrame)> {
162 let Ok(i) = u32::try_from(tag) else { return Vec::new() };
163 let mut out = Vec::new();
164 if let Some((t, orphan)) = self.held.take() {
165 if t + 1 == tag {
166 // `pic` is the second of the pair.
167 let film = weave(&pic, &orphan, self.cadence.order);
168 out.extend(self.tagged(t as u32, film));
169 return out;
170 }
171 let solo = self.solo(&orphan);
172 out.extend(self.tagged(t as u32, solo));
173 }
174 if self.cadence.skipped(i) {
175 // Its mate is not in hand (a seek landed on it): nothing to show.
176 } else if self.cadence.starts_pair(i) {
177 self.held = Some((tag, pic));
178 } else {
179 let mut clean = pic;
180 clean.interlace = Interlace::Progressive;
181 out.extend(self.tagged(i, clean));
182 }
183 out
184 }
185
186 pub fn finish_all(&mut self) -> Vec<(i64, VideoFrame)> {
187 match self.held.take() {
188 Some((t, orphan)) => {
189 let solo = self.solo(&orphan);
190 self.tagged(t as u32, solo)
191 }
192 None => Vec::new(),
193 }
194 }
195}
196
197// ----------------------------------------------------------------------------
198// Detection
199
200/// How a clip's pulldown removal is asked for.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum Telecine {
203 /// Only a cadence that holds clearly over the sample.
204 Auto,
205 /// The best cadence the sample has, however weak.
206 On,
207}
208
209/// Luma at 8 bits, tightly packed, of a planar picture.
210fn luma(f: &VideoFrame) -> Option<(Vec<u8>, usize, usize)> {
211 let (w, h) = (f.width as usize, f.height as usize);
212 let plane = f.planes.first()?;
213 let wide = match f.format {
214 PixelFormat::I420 | PixelFormat::I422 | PixelFormat::I444 => false,
215 PixelFormat::I010 | PixelFormat::I210 | PixelFormat::I410 => true,
216 _ => return None,
217 };
218 let mut out = Vec::with_capacity(w * h);
219 for y in 0..h {
220 let row = plane.data.get(y * plane.stride..)?;
221 if wide {
222 out.extend((0..w).map(|x| (u16::from_le_bytes([row[2 * x], row[2 * x + 1]]) >> 2) as u8));
223 } else {
224 out.extend_from_slice(row.get(..w)?);
225 }
226 }
227 Some((out, w, h))
228}
229
230/// The share of pixels that stick out of both rows next to them, the signature of
231/// two fields from different moments woven together.
232fn comb(l: &[u8], w: usize, h: usize) -> f64 {
233 const T: i32 = 12;
234 let mut n = 0usize;
235 for y in 1..h.saturating_sub(1) {
236 let (a, b, c) = (&l[(y - 1) * w..y * w], &l[y * w..(y + 1) * w], &l[(y + 1) * w..(y + 2) * w]);
237 for x in 0..w {
238 let (a, b, c) = (i32::from(a[x]), i32::from(b[x]), i32::from(c[x]));
239 if (b - a > T && b - c > T) || (a - b > T && c - b > T) {
240 n += 1;
241 }
242 }
243 }
244 n as f64 / (w * h).max(1) as f64
245}
246
247/// Luma of the film frame a mixed pair `(a, b)` makes under `order`.
248fn woven_luma(a: &[u8], b: &[u8], w: usize, h: usize, order: Interlace) -> Vec<u8> {
249 let parity = if order == Interlace::BottomFieldFirst { 0 } else { 1 };
250 let mut out = b.to_vec();
251 for y in (parity..h).step_by(2) {
252 out[y * w..(y + 1) * w].copy_from_slice(&a[y * w..(y + 1) * w]);
253 }
254 out
255}
256
257/// The cadence of `frames` (display order), if there is one.
258///
259/// The best cadence the pictures show, and whether it holds clearly: in at least four
260/// blocks with motion in them, and in nine of ten of those.
261pub fn detect(frames: &[VideoFrame]) -> Option<(Cadence, bool)> {
262 let planes: Vec<(Vec<u8>, usize, usize)> = frames.iter().map(luma).collect::<Option<_>>()?;
263 let n = planes.len();
264 if n < 10 {
265 return None;
266 }
267 let (w, h) = (planes[0].1, planes[0].2);
268 if planes.iter().any(|p| p.1 != w || p.2 != h) || h < 8 {
269 return None;
270 }
271 let cf: Vec<f64> = planes.iter().map(|p| comb(&p.0, w, h)).collect();
272 let mut best: Option<(Cadence, usize, usize, f64)> = None;
273 for order in [Interlace::TopFieldFirst, Interlace::BottomFieldFirst] {
274 let cw: Vec<f64> = (0..n - 1)
275 .map(|i| comb(&woven_luma(&planes[i].0, &planes[i + 1].0, w, h, order), w, h))
276 .collect();
277 for phase in 0..5u8 {
278 let (mut informative, mut passed, mut margin) = (0usize, 0usize, 0.0f64);
279 let mut i = usize::from(phase);
280 while i + 1 < n {
281 let hi = cf[i].min(cf[i + 1]);
282 let lo = (i + 2..(i + 5).min(n)).fold(cw[i], |m, j| m.max(cf[j]));
283 if hi > 0.0004 {
284 informative += 1;
285 if hi >= 3.0 * lo {
286 passed += 1;
287 }
288 }
289 margin += hi - lo;
290 i += 5;
291 }
292 let c = Cadence { phase, order };
293 let better = match &best {
294 None => true,
295 Some((_, p, _, m)) => (passed, margin) > (*p, *m),
296 };
297 if better {
298 best = Some((c, passed, informative, margin));
299 }
300 }
301 }
302 let (c, passed, informative, margin) = best?;
303 Some((c, informative >= 4 && passed * 10 >= informative * 9 && margin > 0.0))
304}
305
306/// The cadence a file's first pictures show, remembered per file. Only software-decoded interlaced H.264 and MPEG-2 have one.
307pub fn cadence_for(path: &Path, how: Telecine) -> Option<Cadence> {
308 type Known = Mutex<HashMap<PathBuf, Option<(Cadence, bool)>>>;
309 static KNOWN: OnceLock<Known> = OnceLock::new();
310 let known = KNOWN.get_or_init(Default::default);
311 let cached = known.lock().ok().and_then(|k| k.get(path).copied());
312 let found = match cached {
313 Some(found) => found,
314 None => {
315 let found = sample(path).and_then(|frames| detect(&frames));
316 if let Ok(mut k) = known.lock() {
317 k.insert(path.to_path_buf(), found);
318 }
319 found
320 }
321 };
322 found.filter(|(_, clear)| *clear || how == Telecine::On).map(|(c, _)| c)
323}
324
325/// The first [`SAMPLE`] pictures of an interlaced H.264 or MPEG-2 file, decoded.
326fn sample(path: &Path) -> Option<Vec<VideoFrame>> {
327 let (meta, mut demuxer) = Demuxer::open(path).ok()?;
328 if !demuxer.h264_interlaced() {
329 return None;
330 }
331 demuxer.seek_to_sync_at_or_before(0);
332 match meta.codec {
333 Codec::H264 => {
334 let d = ec_h264::H264Decoder::new(CodecParameters::new(CodecId::H264)).ok()?;
335 pull(&mut demuxer, d)
336 }
337 Codec::Mpeg2 => {
338 let d = ec_mpeg2::Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video)).ok()?;
339 pull(&mut demuxer, d)
340 }
341 _ => None,
342 }
343}
344
345fn pull<D: Decoder>(demuxer: &mut Demuxer, mut decoder: D) -> Option<Vec<VideoFrame>> {
346 let mut frames = Vec::new();
347 let take = |decoder: &mut D, frames: &mut Vec<VideoFrame>| loop {
348 match decoder.receive_frame() {
349 Ok(Frame::Video(pic)) => frames.push(pic),
350 Ok(_) => {}
351 Err(_) => return,
352 }
353 };
354 while frames.len() < SAMPLE {
355 match demuxer.next_access_unit() {
356 Ok(Some(au)) => {
357 decoder.send_packet(&Packet::new(0, TimeBase::new(1, 1), au)).ok()?;
358 take(&mut decoder, &mut frames);
359 }
360 _ => break,
361 }
362 }
363 if frames.len() < SAMPLE {
364 decoder.flush().ok()?;
365 take(&mut decoder, &mut frames);
366 }
367 frames.truncate(SAMPLE);
368 Some(frames)
369}
370
371// ----------------------------------------------------------------------------
372// Soft pulldown
373
374/// What a stream's first pictures say about repeating fields.
375#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
376pub struct Repeats {
377 /// Pictures that state it either way.
378 pub pictures: u32,
379 /// Pictures that ask for a third field: MPEG-2 `repeat_first_field`, H.264
380 /// `pic_struct` 5 and 6.
381 pub tripled: u32,
382}
383
384impl Repeats {
385 /// 3:2 soft pulldown asks for a third field on every other picture; a stream
386 /// that does it on about half of them, over enough of them, is film.
387 pub fn soft(self) -> bool {
388 self.pictures >= 8 && self.tripled * 10 >= self.pictures * 3 && self.tripled * 10 <= self.pictures * 7
389 }
390
391 /// Takes one MPEG-2 picture (an access unit) in: its picture coding extension's
392 /// `repeat_first_field`, for a frame picture coded progressive.
393 pub fn mpeg2(&mut self, au: &[u8]) {
394 let mut i = 0;
395 while let Some(at) = au[i..].windows(5).position(|w| w[..4] == [0, 0, 1, 0xB5] && w[4] >> 4 == 8) {
396 let ext = &au[i + at + 4..];
397 if ext.len() >= 5 {
398 let (frame_picture, rff, progressive) = (ext[2] & 3 == 3, ext[3] >> 1 & 1 == 1, ext[4] >> 7 == 1);
399 if frame_picture && progressive {
400 self.pictures += 1;
401 self.tripled += u32::from(rff);
402 }
403 return;
404 }
405 i += at + 4;
406 }
407 }
408
409 /// Takes one H.264 access unit in: the `pic_struct` of its picture timing SEI.
410 /// `sets` is the stream's SPS and PPS (Annex B), which say whether it is there.
411 pub fn h264(&mut self, sets: &[u8], au: &[u8]) {
412 use ec_h264_syntax::nal::{AnnexBIter, unescape_rbsp};
413 let Some(vui) = AnnexBIter::new(sets)
414 .find(|n| n.first().is_some_and(|b| b & 0x1f == 7))
415 .and_then(|n| {
416 let mut rbsp = Vec::new();
417 unescape_rbsp(&n[1..], &mut rbsp);
418 ec_h264_syntax::Sps::parse(&rbsp).ok()
419 })
420 .and_then(|sps| sps.vui)
421 else {
422 return;
423 };
424 if !vui.pic_struct_present {
425 return;
426 }
427 let delays = vui.nal_hrd.as_ref().or(vui.vcl_hrd.as_ref()).map(|h| {
428 (u32::from(h.cpb_removal_delay_length_minus1) + 1, u32::from(h.dpb_output_delay_length_minus1) + 1)
429 });
430 for nal in AnnexBIter::new(au).filter(|n| n.first().is_some_and(|b| b & 0x1f == 6)) {
431 let mut rbsp = Vec::new();
432 unescape_rbsp(&nal[1..], &mut rbsp);
433 let mut at = 0;
434 while at + 2 <= rbsp.len() {
435 let mut kind = 0usize;
436 while rbsp.get(at) == Some(&0xFF) {
437 kind += 255;
438 at += 1;
439 }
440 kind += usize::from(*rbsp.get(at).unwrap_or(&0));
441 at += 1;
442 let mut size = 0usize;
443 while rbsp.get(at) == Some(&0xFF) {
444 size += 255;
445 at += 1;
446 }
447 size += usize::from(*rbsp.get(at).unwrap_or(&0));
448 at += 1;
449 if kind == 1 {
450 let skip = delays.map_or(0, |(a, b)| a + b) as usize;
451 // pic_struct is the four bits after the delays.
452 let (byte, bit) = (at + skip / 8, skip % 8);
453 if let Some(&b) = rbsp.get(byte) {
454 let next = rbsp.get(byte + 1).copied().unwrap_or(0);
455 let pic_struct = (u16::from_be_bytes([b, next]) >> (12 - bit)) & 0xF;
456 self.pictures += 1;
457 self.tripled += u32::from(pic_struct == 5 || pic_struct == 6);
458 }
459 return;
460 }
461 at += size;
462 }
463 }
464 }
465}
466
467#[cfg(test)]
468mod tests {
469 use super::*;
470
471 #[test]
472 fn mpeg2_repeat_flags_are_counted() {
473 // A picture coding extension: frame picture, tff, repeat_first_field, progressive_frame.
474 let au = |rff: bool| [0, 0, 1, 0xB5, 0x8F, 0xFF, 0xF3, 0x80 | (u8::from(rff) << 1), 0x80];
475 let mut r = Repeats::default();
476 for n in 0..12 {
477 r.mpeg2(&au(n % 2 == 0));
478 }
479 assert_eq!(r, Repeats { pictures: 12, tripled: 6 });
480 assert!(r.soft());
481 let mut still = Repeats::default();
482 for _ in 0..12 {
483 still.mpeg2(&au(false));
484 }
485 assert!(!still.soft(), "no repeats is not pulldown");
486 }
487
488 #[test]
489 fn offsets_cover_four_of_five() {
490 for phase in 0..5u8 {
491 let c = Cadence { phase, order: Interlace::TopFieldFirst };
492 let mut k = 0;
493 for i in 0..50u32 {
494 match c.output_of(i) {
495 Some(o) => {
496 assert_eq!(o, k, "phase {phase} input {i}");
497 assert_eq!(c.input_of(o), i);
498 k += 1;
499 }
500 None => assert!(c.skipped(i)),
501 }
502 }
503 assert_eq!(c.out_count(50), k);
504 assert_eq!(c.out_count(50), 40);
505 assert_eq!(c.out_count(7), (0..7).filter(|&i| !c.skipped(i)).count() as u32);
506 }
507 }
508}