| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | use std::collections::HashMap; |
| 35 | use std::path::{Path, PathBuf}; |
| 36 | use std::sync::{Mutex, OnceLock}; |
| 37 | |
| 38 | use ec_core::registry::{CodecId, CodecParameters, Decoder}; |
| 39 | use ec_core::{Frame, Interlace, Packet, PixelFormat, Plane, TimeBase, VideoFrame}; |
| 40 | |
| 41 | use crate::demux::{Codec, Demuxer}; |
| 42 | |
| 43 | |
| 44 | pub const SAMPLE: usize = 60; |
| 45 | |
| 46 | |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 48 | pub struct Cadence { |
| 49 | |
| 50 | pub phase: u8, |
| 51 | |
| 52 | pub order: Interlace, |
| 53 | } |
| 54 | |
| 55 | impl 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 | |
| 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 | |
| 78 | |
| 79 | pub fn input_of(self, k: u32) -> u32 { |
| 80 | 5 * (k / 4) + self.offsets()[(k % 4) as usize] |
| 81 | } |
| 82 | |
| 83 | |
| 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 | |
| 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 | |
| 98 | |
| 99 | |
| 100 | pub 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 | |
| 130 | |
| 131 | pub struct Stage { |
| 132 | cadence: Cadence, |
| 133 | |
| 134 | first_wanted: i64, |
| 135 | |
| 136 | held: Option<(i64, VideoFrame)>, |
| 137 | } |
| 138 | |
| 139 | impl Stage { |
| 140 | pub fn new(cadence: Cadence, first_wanted: i64) -> Self { |
| 141 | Self { cadence, first_wanted, held: None } |
| 142 | } |
| 143 | |
| 144 | |
| 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 | |
| 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 | |
| 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 | |
| 199 | |
| 200 | |
| 201 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 202 | pub enum Telecine { |
| 203 | |
| 204 | Auto, |
| 205 | |
| 206 | On, |
| 207 | } |
| 208 | |
| 209 | |
| 210 | fn 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 | |
| 231 | |
| 232 | fn 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 | |
| 248 | fn 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 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | pub 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 | |
| 307 | pub 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 | |
| 326 | fn 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 | |
| 345 | fn 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 | |
| 373 | |
| 374 | |
| 375 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 376 | pub struct Repeats { |
| 377 | |
| 378 | pub pictures: u32, |
| 379 | |
| 380 | |
| 381 | pub tripled: u32, |
| 382 | } |
| 383 | |
| 384 | impl Repeats { |
| 385 | |
| 386 | |
| 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 | |
| 392 | |
| 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 | |
| 410 | |
| 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 | |
| 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)] |
| 468 | mod tests { |
| 469 | use super::*; |
| 470 | |
| 471 | #[test] |
| 472 | fn mpeg2_repeat_flags_are_counted() { |
| 473 | |
| 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 | } |