| 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 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | use std::collections::VecDeque; |
| 44 | use std::path::Path; |
| 45 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; |
| 46 | use std::sync::mpsc::Receiver; |
| 47 | use std::sync::Arc; |
| 48 | |
| 49 | use crate::decode::{DecodeSession, Frame}; |
| 50 | use crate::demux::{Demuxer, VideoMeta}; |
| 51 | |
| 52 | |
| 53 | pub const THUMB_W: usize = 64; |
| 54 | pub const THUMB_H: usize = 36; |
| 55 | |
| 56 | const BINS: usize = 64; |
| 57 | |
| 58 | const WINDOW: usize = 8; |
| 59 | |
| 60 | const ADAPT: f32 = 2.0; |
| 61 | |
| 62 | pub const BLACK_LUMA: f32 = 16.0; |
| 63 | |
| 64 | pub const BLACK_RUN: usize = 3; |
| 65 | |
| 66 | pub const LONG_FILE_SECS: f64 = 60.0; |
| 67 | pub const LONG_FILE_SAMPLE_FPS: f64 = 10.0; |
| 68 | pub const DEFAULT_THRESHOLD: f32 = 0.35; |
| 69 | pub const DEFAULT_MIN_SHOT_SECS: f64 = 0.6; |
| 70 | |
| 71 | |
| 72 | |
| 73 | const DISSOLVE_MAD_MAX: f32 = 0.05; |
| 74 | const DISSOLVE_HIST_MIN: f32 = 0.03; |
| 75 | |
| 76 | const DISSOLVE_MIN_STEPS: usize = 4; |
| 77 | |
| 78 | |
| 79 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 80 | pub struct SceneSettings { |
| 81 | |
| 82 | pub threshold: f32, |
| 83 | |
| 84 | pub min_shot_secs: f64, |
| 85 | |
| 86 | pub sample_fps: Option<f64>, |
| 87 | } |
| 88 | |
| 89 | impl Default for SceneSettings { |
| 90 | fn default() -> Self { |
| 91 | Self { threshold: DEFAULT_THRESHOLD, min_shot_secs: DEFAULT_MIN_SHOT_SECS, sample_fps: None } |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | impl SceneSettings { |
| 96 | |
| 97 | |
| 98 | pub fn for_duration(secs: f64) -> Self { |
| 99 | let sample_fps = (secs > LONG_FILE_SECS).then_some(LONG_FILE_SAMPLE_FPS); |
| 100 | Self { sample_fps, ..Self::default() } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 105 | pub enum CutKind { |
| 106 | |
| 107 | Hard, |
| 108 | |
| 109 | FadeBlack, |
| 110 | |
| 111 | |
| 112 | Dissolve { end: u32 }, |
| 113 | } |
| 114 | |
| 115 | |
| 116 | |
| 117 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 118 | pub struct Cut { |
| 119 | pub frame: u32, |
| 120 | pub score: f32, |
| 121 | pub kind: CutKind, |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | pub fn detect( |
| 135 | path: &Path, |
| 136 | range: Option<(u32, u32)>, |
| 137 | s: &SceneSettings, |
| 138 | progress: Option<&AtomicU32>, |
| 139 | cancel: Option<&AtomicBool>, |
| 140 | ) -> crate::Result<Vec<Cut>> { |
| 141 | validate(s)?; |
| 142 | let (from, to) = range.unwrap_or((0, u32::MAX)); |
| 143 | let (head, _) = Demuxer::open(path)?; |
| 144 | let fps = if head.frame_rate.is_finite() && head.frame_rate > 0.0 { head.frame_rate } else { 25.0 }; |
| 145 | let step = s.sample_fps.map_or(1.0, |sf| (fps / sf).max(1.0)); |
| 146 | let pre = (WINDOW as f64 * step).ceil() as u32 + 1; |
| 147 | let start = from.saturating_sub(pre); |
| 148 | let (meta, rx, decoder) = open_analysis(path, start, to)?; |
| 149 | let to = to.min(meta.frame_count); |
| 150 | if from >= to { |
| 151 | decoder.store(true, Ordering::Relaxed); |
| 152 | return Ok(Vec::new()); |
| 153 | } |
| 154 | let span = f64::from(to - from); |
| 155 | let min_shot = (s.min_shot_secs * fps).ceil().max(0.0) as u32; |
| 156 | |
| 157 | |
| 158 | let mut due = (f64::from(start) / step).ceil() * step; |
| 159 | let mut prev: Option<(u32, Thumb)> = None; |
| 160 | let mut window: VecDeque<f32> = VecDeque::with_capacity(WINDOW); |
| 161 | |
| 162 | let mut means: Vec<(u32, f32)> = Vec::new(); |
| 163 | |
| 164 | let mut hard: Vec<(Cut, u32)> = Vec::new(); |
| 165 | |
| 166 | let mut run: Option<DissolveRun> = None; |
| 167 | let mut dissolves: Vec<Cut> = Vec::new(); |
| 168 | |
| 169 | for frame in rx.iter() { |
| 170 | if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) { |
| 171 | decoder.store(true, Ordering::Relaxed); |
| 172 | return Err("scene detection cancelled".into()); |
| 173 | } |
| 174 | let idx = frame.index; |
| 175 | if idx >= to { |
| 176 | break; |
| 177 | } |
| 178 | if f64::from(idx) < due { |
| 179 | continue; |
| 180 | } |
| 181 | due += step; |
| 182 | while due <= f64::from(idx) { |
| 183 | due += step; |
| 184 | } |
| 185 | if let Some(p) = progress { |
| 186 | let done = (f64::from(idx.saturating_sub(from)) / span * 100.0).clamp(0.0, 100.0); |
| 187 | p.store(done as u32, Ordering::Relaxed); |
| 188 | } |
| 189 | let Some(thumb) = Thumb::of(&frame) else { continue }; |
| 190 | means.push((idx, thumb.mean)); |
| 191 | if let Some((prev_idx, before)) = &prev { |
| 192 | let raw = score(before, &thumb); |
| 193 | let median = median(&window); |
| 194 | if raw >= s.threshold && raw >= ADAPT * median && idx >= from { |
| 195 | hard.push((Cut { frame: idx, score: raw, kind: CutKind::Hard }, *prev_idx)); |
| 196 | } |
| 197 | if window.len() == WINDOW { |
| 198 | window.pop_front(); |
| 199 | } |
| 200 | window.push_back(raw); |
| 201 | let (mad, hist) = parts(before, &thumb); |
| 202 | if is_dissolve_step(mad, hist, before.mean.min(thumb.mean) < BLACK_LUMA) { |
| 203 | let r = run.get_or_insert_with(|| DissolveRun::start(*prev_idx, before)); |
| 204 | r.push(idx, &thumb); |
| 205 | } else if let Some(r) = run.take() { |
| 206 | dissolves.extend(r.close(s.threshold)); |
| 207 | } |
| 208 | } |
| 209 | prev = Some((idx, thumb)); |
| 210 | } |
| 211 | decoder.store(true, Ordering::Relaxed); |
| 212 | if let Some(p) = progress { |
| 213 | p.store(100, Ordering::Relaxed); |
| 214 | } |
| 215 | if let Some(r) = run.take() { |
| 216 | dissolves.extend(r.close(s.threshold)); |
| 217 | } |
| 218 | |
| 219 | let fades = black_runs(&means); |
| 220 | |
| 221 | hard.retain(|(c, _)| !fades.iter().any(|f| f.lo <= c.frame && c.frame <= f.hi)); |
| 222 | |
| 223 | let fade_win = fps.round().max(1.0) as u32; |
| 224 | dissolves.retain(|d| !fades.iter().any(|f| dissolve_in_fade(d, f, fade_win))); |
| 225 | |
| 226 | hard.retain(|(c, _)| !dissolves.iter().any(|d| inside_dissolve(d, c.frame))); |
| 227 | let mut all: Vec<Cut> = Vec::new(); |
| 228 | for (c, before) in hard { |
| 229 | |
| 230 | |
| 231 | let frame = if step > 1.0 { refine_change(path, before, c.frame).unwrap_or(c.frame) } else { c.frame }; |
| 232 | all.push(Cut { frame, ..c }); |
| 233 | } |
| 234 | for f in &fades { |
| 235 | |
| 236 | let frame = if step > 1.0 { refine_fade(path, f.lo, f.cut.frame).unwrap_or(f.cut.frame) } else { f.cut.frame }; |
| 237 | all.push(Cut { frame, ..f.cut }); |
| 238 | } |
| 239 | all.extend(dissolves); |
| 240 | all.retain(|c| c.frame >= from && c.frame < to); |
| 241 | all.sort_by_key(|c| c.frame); |
| 242 | Ok(collapse(all, min_shot)) |
| 243 | } |
| 244 | |
| 245 | |
| 246 | fn thumbs(path: &Path, lo: u32, hi: u32) -> Option<Vec<(u32, Thumb)>> { |
| 247 | let (_, rx, cancel) = DecodeSession::open_range(path, lo, hi.saturating_add(1)).ok()?; |
| 248 | let mut out = Vec::new(); |
| 249 | for frame in rx.iter() { |
| 250 | if frame.index > hi { |
| 251 | break; |
| 252 | } |
| 253 | if let Some(t) = Thumb::of(&frame) { |
| 254 | out.push((frame.index, t)); |
| 255 | } |
| 256 | } |
| 257 | cancel.store(true, Ordering::Relaxed); |
| 258 | Some(out) |
| 259 | } |
| 260 | |
| 261 | |
| 262 | fn refine_change(path: &Path, lo: u32, hi: u32) -> Option<u32> { |
| 263 | let frames = thumbs(path, lo, hi)?; |
| 264 | let mut best: Option<(f32, u32)> = None; |
| 265 | for pair in frames.windows(2) { |
| 266 | let sc = score(&pair[0].1, &pair[1].1); |
| 267 | if best.is_none_or(|(b, _)| sc > b) { |
| 268 | best = Some((sc, pair[1].0)); |
| 269 | } |
| 270 | } |
| 271 | best.map(|(_, f)| f) |
| 272 | } |
| 273 | |
| 274 | |
| 275 | fn refine_fade(path: &Path, lo: u32, hi: u32) -> Option<u32> { |
| 276 | thumbs(path, lo, hi)? |
| 277 | .into_iter() |
| 278 | .find(|(f, t)| *f > lo && t.mean >= BLACK_LUMA) |
| 279 | .map(|(f, _)| f) |
| 280 | } |
| 281 | |
| 282 | fn validate(s: &SceneSettings) -> crate::Result<()> { |
| 283 | if !(s.threshold.is_finite() && (0.0..=1.0).contains(&s.threshold)) { |
| 284 | return Err(format!("threshold must be between 0 and 1, not {}", s.threshold).into()); |
| 285 | } |
| 286 | if !(s.min_shot_secs.is_finite() && s.min_shot_secs >= 0.0) { |
| 287 | return Err(format!("min_shot_secs must be 0 or more, not {}", s.min_shot_secs).into()); |
| 288 | } |
| 289 | if let Some(sf) = s.sample_fps && !(sf.is_finite() && sf > 0.0) { |
| 290 | return Err(format!("sample_fps must be above 0, not {sf}").into()); |
| 291 | } |
| 292 | Ok(()) |
| 293 | } |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | fn open_analysis( |
| 299 | path: &Path, |
| 300 | from: u32, |
| 301 | to: u32, |
| 302 | ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> { |
| 303 | let (meta, rx, cancel) = DecodeSession::open_range(path, from, to)?; |
| 304 | if let Some(proxy) = crate::proxy::cached(path) |
| 305 | && let Ok((pmeta, prx, pcancel)) = DecodeSession::open_range(&proxy, from, to) |
| 306 | { |
| 307 | if pmeta.frame_count == meta.frame_count { |
| 308 | cancel.store(true, Ordering::Relaxed); |
| 309 | return Ok((meta, prx, pcancel)); |
| 310 | } |
| 311 | pcancel.store(true, Ordering::Relaxed); |
| 312 | } |
| 313 | Ok((meta, rx, cancel)) |
| 314 | } |
| 315 | |
| 316 | |
| 317 | #[derive(Clone)] |
| 318 | struct Thumb { |
| 319 | |
| 320 | luma: Vec<u8>, |
| 321 | |
| 322 | hist: [f32; BINS], |
| 323 | |
| 324 | mean: f32, |
| 325 | } |
| 326 | |
| 327 | impl Thumb { |
| 328 | fn of(f: &Frame) -> Option<Thumb> { |
| 329 | let (w, h) = (f.width as usize, f.height as usize); |
| 330 | if w == 0 || h == 0 || f.bgra.len() < w * h * 4 { |
| 331 | return None; |
| 332 | } |
| 333 | let mut luma = Vec::with_capacity(THUMB_W * THUMB_H); |
| 334 | let mut counts = [0u32; BINS]; |
| 335 | let mut sum = 0u64; |
| 336 | for ty in 0..THUMB_H { |
| 337 | let sy = (ty * 2 + 1) * h / (2 * THUMB_H); |
| 338 | for tx in 0..THUMB_W { |
| 339 | let sx = (tx * 2 + 1) * w / (2 * THUMB_W); |
| 340 | let p = (sy * w + sx) * 4; |
| 341 | |
| 342 | let b = i32::from(f.bgra[p]); |
| 343 | let g = i32::from(f.bgra[p + 1]); |
| 344 | let r = i32::from(f.bgra[p + 2]); |
| 345 | let y = ((77 * r + 150 * g + 29 * b) >> 8).clamp(0, 255); |
| 346 | let u = (((-43 * r - 85 * g + 128 * b) >> 8) + 128).clamp(0, 255); |
| 347 | let v = (((128 * r - 107 * g - 21 * b) >> 8) + 128).clamp(0, 255); |
| 348 | counts[((u >> 5) * 8 + (v >> 5)) as usize] += 1; |
| 349 | luma.push(y as u8); |
| 350 | sum += y as u64; |
| 351 | } |
| 352 | } |
| 353 | let n = (THUMB_W * THUMB_H) as f32; |
| 354 | let mut hist = [0f32; BINS]; |
| 355 | for (dst, c) in hist.iter_mut().zip(counts) { |
| 356 | *dst = c as f32 / n; |
| 357 | } |
| 358 | Some(Thumb { luma, hist, mean: sum as f32 / n }) |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | |
| 363 | |
| 364 | fn score(a: &Thumb, b: &Thumb) -> f32 { |
| 365 | let (mad, hist) = parts(a, b); |
| 366 | (0.5 * mad + 0.5 * hist).clamp(0.0, 1.0) |
| 367 | } |
| 368 | |
| 369 | |
| 370 | |
| 371 | fn parts(a: &Thumb, b: &Thumb) -> (f32, f32) { |
| 372 | let total: u64 = a |
| 373 | .luma |
| 374 | .iter() |
| 375 | .zip(&b.luma) |
| 376 | .map(|(x, y)| u64::from(x.abs_diff(*y))) |
| 377 | .sum(); |
| 378 | let mad = total as f32 / (a.luma.len() as f32 * 255.0); |
| 379 | let hist: f32 = 1.0 |
| 380 | - a.hist |
| 381 | .iter() |
| 382 | .zip(&b.hist) |
| 383 | .map(|(x, y)| x.min(*y)) |
| 384 | .sum::<f32>(); |
| 385 | (mad, hist.max(0.0)) |
| 386 | } |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | fn is_dissolve_step(mad: f32, hist: f32, dark: bool) -> bool { |
| 392 | !dark && mad > 0.0 && mad <= DISSOLVE_MAD_MAX && hist >= DISSOLVE_HIST_MIN |
| 393 | } |
| 394 | |
| 395 | |
| 396 | |
| 397 | struct DissolveRun { |
| 398 | anchor: u32, |
| 399 | anchor_thumb: Thumb, |
| 400 | last: u32, |
| 401 | last_thumb: Thumb, |
| 402 | steps: usize, |
| 403 | } |
| 404 | |
| 405 | impl DissolveRun { |
| 406 | fn start(anchor: u32, before: &Thumb) -> Self { |
| 407 | Self { anchor, anchor_thumb: before.clone(), last: anchor, last_thumb: before.clone(), steps: 0 } |
| 408 | } |
| 409 | |
| 410 | fn push(&mut self, idx: u32, thumb: &Thumb) { |
| 411 | self.last = idx; |
| 412 | self.last_thumb = thumb.clone(); |
| 413 | self.steps += 1; |
| 414 | } |
| 415 | |
| 416 | |
| 417 | |
| 418 | fn close(self, threshold: f32) -> Option<Cut> { |
| 419 | if self.steps < DISSOLVE_MIN_STEPS { |
| 420 | return None; |
| 421 | } |
| 422 | let raw = score(&self.anchor_thumb, &self.last_thumb); |
| 423 | (raw >= threshold).then_some(Cut { frame: self.anchor, score: raw, kind: CutKind::Dissolve { end: self.last } }) |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | |
| 428 | |
| 429 | fn dissolve_in_fade(d: &Cut, f: &Fade, win: u32) -> bool { |
| 430 | d.frame <= f.cut.frame + win && dissolve_end(d) >= f.lo |
| 431 | } |
| 432 | |
| 433 | |
| 434 | fn inside_dissolve(d: &Cut, frame: u32) -> bool { |
| 435 | frame > d.frame && frame <= dissolve_end(d) |
| 436 | } |
| 437 | |
| 438 | |
| 439 | fn dissolve_end(c: &Cut) -> u32 { |
| 440 | match c.kind { |
| 441 | CutKind::Dissolve { end } => end, |
| 442 | _ => c.frame, |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | |
| 447 | |
| 448 | fn median(window: &VecDeque<f32>) -> f32 { |
| 449 | if window.is_empty() { |
| 450 | return 0.0; |
| 451 | } |
| 452 | let mut v: Vec<f32> = window.iter().copied().collect(); |
| 453 | v.sort_by(|a, b| a.total_cmp(b)); |
| 454 | let mid = v.len() / 2; |
| 455 | if v.len().is_multiple_of(2) { (v[mid - 1] + v[mid]) / 2.0 } else { v[mid] } |
| 456 | } |
| 457 | |
| 458 | |
| 459 | struct Fade { |
| 460 | cut: Cut, |
| 461 | |
| 462 | lo: u32, |
| 463 | |
| 464 | hi: u32, |
| 465 | } |
| 466 | |
| 467 | |
| 468 | fn black_runs(means: &[(u32, f32)]) -> Vec<Fade> { |
| 469 | let mut out = Vec::new(); |
| 470 | let mut i = 0; |
| 471 | while i < means.len() { |
| 472 | if means[i].1 >= BLACK_LUMA { |
| 473 | i += 1; |
| 474 | continue; |
| 475 | } |
| 476 | let start = i; |
| 477 | while i < means.len() && means[i].1 < BLACK_LUMA { |
| 478 | i += 1; |
| 479 | } |
| 480 | let end = i; |
| 481 | if end - start >= BLACK_RUN { |
| 482 | let lo = means[start.saturating_sub(1)].0; |
| 483 | let hi = means[end.min(means.len() - 1)].0; |
| 484 | out.push(Fade { |
| 485 | cut: Cut { frame: hi, score: 1.0, kind: CutKind::FadeBlack }, |
| 486 | lo, |
| 487 | hi, |
| 488 | }); |
| 489 | } |
| 490 | } |
| 491 | out |
| 492 | } |
| 493 | |
| 494 | |
| 495 | fn collapse(sorted: Vec<Cut>, min_shot: u32) -> Vec<Cut> { |
| 496 | let mut out: Vec<Cut> = Vec::with_capacity(sorted.len()); |
| 497 | for c in sorted { |
| 498 | if let Some(last) = out.last_mut() |
| 499 | && c.frame.saturating_sub(last.frame) < min_shot |
| 500 | { |
| 501 | |
| 502 | let fade_wins = c.kind == CutKind::FadeBlack && last.kind == CutKind::Hard; |
| 503 | if c.score > last.score || fade_wins { |
| 504 | *last = c; |
| 505 | } |
| 506 | continue; |
| 507 | } |
| 508 | out.push(c); |
| 509 | } |
| 510 | out |
| 511 | } |
| 512 | |
| 513 | #[cfg(test)] |
| 514 | mod tests { |
| 515 | use super::*; |
| 516 | use std::path::PathBuf; |
| 517 | use crate::scratch::Scratch; |
| 518 | use std::process::Command; |
| 519 | use std::time::Instant; |
| 520 | |
| 521 | fn asset(name: &str) -> PathBuf { |
| 522 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 523 | } |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 528 | fn three_shots(name: &str, seconds: u32) -> (Scratch, [u32; 2]) { |
| 529 | let joined = Scratch::file(name, "mp4"); |
| 530 | let dir = joined.parent().unwrap().to_path_buf(); |
| 531 | let parts = [ |
| 532 | ("testsrc2", dir.join("a.mp4")), |
| 533 | ("mandelbrot", dir.join("b.mp4")), |
| 534 | ("smptebars", dir.join("c.mp4")), |
| 535 | ]; |
| 536 | for (src, out) in &parts { |
| 537 | let lavfi = format!("{src}=size=640x360:rate=25"); |
| 538 | let ok = Command::new("ffmpeg") |
| 539 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", &lavfi, "-t", &seconds.to_string()]) |
| 540 | .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"]) |
| 541 | .arg(out) |
| 542 | .status() |
| 543 | .expect("ffmpeg runs") |
| 544 | .success(); |
| 545 | assert!(ok, "ffmpeg made {src}"); |
| 546 | } |
| 547 | let ok = Command::new("ffmpeg") |
| 548 | .args(["-v", "error", "-y"]) |
| 549 | .args(["-i"]).arg(&parts[0].1) |
| 550 | .args(["-i"]).arg(&parts[1].1) |
| 551 | .args(["-i"]).arg(&parts[2].1) |
| 552 | .args(["-filter_complex", "[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]", "-map", "[v]"]) |
| 553 | .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"]) |
| 554 | .arg(&*joined) |
| 555 | .status() |
| 556 | .expect("ffmpeg runs") |
| 557 | .success(); |
| 558 | assert!(ok, "ffmpeg joined the shots"); |
| 559 | let per = seconds * 25; |
| 560 | (joined, [per, 2 * per]) |
| 561 | } |
| 562 | |
| 563 | fn near(cuts: &[Cut], want: u32, slack: u32) -> bool { |
| 564 | cuts.iter().any(|c| c.frame.abs_diff(want) <= slack && c.kind == CutKind::Hard) |
| 565 | } |
| 566 | |
| 567 | #[test] |
| 568 | fn finds_the_joins_of_three_sources() { |
| 569 | let (path, joins) = three_shots("joins", 2); |
| 570 | let cuts = detect(&path, None, &SceneSettings::default(), None, None).unwrap(); |
| 571 | for j in joins { |
| 572 | assert!(near(&cuts, j, 2), "no cut within 2 frames of {j}: {cuts:?}"); |
| 573 | } |
| 574 | assert_eq!(cuts.len(), 2, "exactly the two joins: {cuts:?}"); |
| 575 | } |
| 576 | |
| 577 | #[test] |
| 578 | fn a_range_only_sees_the_cuts_inside_it() { |
| 579 | let (path, joins) = three_shots("range", 2); |
| 580 | let cuts = detect(&path, Some((joins[0] - 10, joins[0] + 30)), &SceneSettings::default(), None, None).unwrap(); |
| 581 | assert!(near(&cuts, joins[0], 2), "{cuts:?}"); |
| 582 | assert!(cuts.iter().all(|c| c.frame < joins[1]), "{cuts:?}"); |
| 583 | } |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | #[test] |
| 589 | fn a_range_agrees_with_the_whole_file() { |
| 590 | let (path, joins) = three_shots("agree", 2); |
| 591 | let whole = detect(&path, None, &SceneSettings::default(), None, None).unwrap(); |
| 592 | for (from, to) in [(joins[0] - 3, joins[0] + 20), (joins[0] + 1, joins[1] + 5), (5, 3 * 50)] { |
| 593 | let part = detect(&path, Some((from, to)), &SceneSettings::default(), None, None).unwrap(); |
| 594 | let want: Vec<u32> = whole.iter().map(|c| c.frame).filter(|&f| f >= from && f < to).collect(); |
| 595 | let got: Vec<u32> = part.iter().map(|c| c.frame).collect(); |
| 596 | assert_eq!(got, want, "range {from}..{to}"); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | #[test] |
| 601 | fn a_decimated_run_lands_on_the_first_frame_of_the_new_shot() { |
| 602 | let (path, joins) = three_shots("decimated", 2); |
| 603 | let s = SceneSettings { sample_fps: Some(4.0), ..SceneSettings::default() }; |
| 604 | let cuts = detect(&path, None, &s, None, None).unwrap(); |
| 605 | assert_eq!(cuts.iter().map(|c| c.frame).collect::<Vec<_>>(), joins.to_vec(), "{cuts:?}"); |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn a_continuous_shot_has_at_most_one_cut() { |
| 610 | let cuts = detect(&asset("test_av.mp4"), None, &SceneSettings::default(), None, None).unwrap(); |
| 611 | assert!(cuts.len() <= 1, "a single shot should not cut: {cuts:?}"); |
| 612 | } |
| 613 | |
| 614 | #[test] |
| 615 | fn a_fade_through_black_is_one_cut_at_the_first_picture_frame() { |
| 616 | let path = Scratch::file("fade", "mp4"); |
| 617 | |
| 618 | let filter = "[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]"; |
| 619 | let ok = Command::new("ffmpeg") |
| 620 | .args(["-v", "error", "-y", "-f", "lavfi", "-t", "2", "-i", "testsrc2=size=320x180:rate=25"]) |
| 621 | .args(["-f", "lavfi", "-t", "1", "-i", "color=c=black:size=320x180:rate=25"]) |
| 622 | .args(["-f", "lavfi", "-t", "2", "-i", "mandelbrot=size=320x180:rate=25"]) |
| 623 | .args(["-filter_complex", filter, "-map", "[v]"]) |
| 624 | .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"]) |
| 625 | .arg(&path) |
| 626 | .status() |
| 627 | .expect("ffmpeg runs") |
| 628 | .success(); |
| 629 | assert!(ok); |
| 630 | let cuts = detect(&path, None, &SceneSettings::default(), None, None).unwrap(); |
| 631 | let fades: Vec<_> = cuts.iter().filter(|c| c.kind == CutKind::FadeBlack).collect(); |
| 632 | assert_eq!(fades.len(), 1, "{cuts:?}"); |
| 633 | |
| 634 | assert!(fades[0].frame.abs_diff(75) <= 1, "{cuts:?}"); |
| 635 | assert_eq!(fades[0].score, 1.0); |
| 636 | } |
| 637 | |
| 638 | |
| 639 | fn flat(level: f32, bin: usize) -> Thumb { |
| 640 | Thumb { luma: vec![level as u8; THUMB_W * THUMB_H], hist: one_bin(bin, 1.0), mean: level } |
| 641 | } |
| 642 | |
| 643 | |
| 644 | fn one_bin(bin: usize, w: f32) -> [f32; BINS] { |
| 645 | let mut hist = [0f32; BINS]; |
| 646 | hist[bin] = w; |
| 647 | hist[(bin + 1) % BINS] += 1.0 - w; |
| 648 | hist |
| 649 | } |
| 650 | |
| 651 | |
| 652 | |
| 653 | fn walk(series: &[Thumb], threshold: f32) -> Vec<Cut> { |
| 654 | let mut out = Vec::new(); |
| 655 | let mut run: Option<DissolveRun> = None; |
| 656 | for i in 1..series.len() { |
| 657 | let (mad, hist) = parts(&series[i - 1], &series[i]); |
| 658 | let dark = series[i - 1].mean.min(series[i].mean) < BLACK_LUMA; |
| 659 | if is_dissolve_step(mad, hist, dark) { |
| 660 | run.get_or_insert_with(|| DissolveRun::start(i as u32 - 1, &series[i - 1])).push(i as u32, &series[i]); |
| 661 | } else if let Some(r) = run.take() { |
| 662 | out.extend(r.close(threshold)); |
| 663 | } |
| 664 | } |
| 665 | if let Some(r) = run.take() { |
| 666 | out.extend(r.close(threshold)); |
| 667 | } |
| 668 | out |
| 669 | } |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | fn ramp_series(n: usize) -> Vec<Thumb> { |
| 675 | let mut s: Vec<Thumb> = (0..20).map(|_| flat(130.0, 5)).collect(); |
| 676 | for k in 1..=n { |
| 677 | let level = 130.0 - k as f32; |
| 678 | let w = 1.0 - k as f32 / (n + 1) as f32; |
| 679 | s.push(Thumb { luma: vec![level as u8; THUMB_W * THUMB_H], hist: one_bin(5, w), mean: level }); |
| 680 | } |
| 681 | let last = 130.0 - n as f32; |
| 682 | s.extend((0..20).map(|_| Thumb { luma: vec![last as u8; THUMB_W * THUMB_H], hist: one_bin(6, 1.0), mean: last })); |
| 683 | s |
| 684 | } |
| 685 | |
| 686 | #[test] |
| 687 | fn a_dissolve_is_one_boundary_from_its_first_frame_to_its_last() { |
| 688 | let cuts = walk(&ramp_series(20), 0.35); |
| 689 | assert_eq!(cuts.len(), 1, "{cuts:?}"); |
| 690 | assert_eq!(cuts[0].frame, 19, "{cuts:?}"); |
| 691 | assert_eq!(cuts[0].kind, CutKind::Dissolve { end: 39 }, "{cuts:?}"); |
| 692 | } |
| 693 | |
| 694 | |
| 695 | #[test] |
| 696 | fn a_dissolve_below_the_threshold_is_not_reported() { |
| 697 | assert!(walk(&ramp_series(20), 0.9).is_empty()); |
| 698 | } |
| 699 | |
| 700 | |
| 701 | #[test] |
| 702 | fn a_dissolve_needs_four_steps() { |
| 703 | assert!(walk(&ramp_series(3), 0.35).is_empty()); |
| 704 | assert_eq!(walk(&ramp_series(4), 0.35).len(), 1); |
| 705 | } |
| 706 | |
| 707 | |
| 708 | #[test] |
| 709 | fn a_pan_is_not_a_dissolve() { |
| 710 | let s: Vec<Thumb> = (0..40).map(|i| flat(130.0 - 2.0 * i as f32, 5)).collect(); |
| 711 | assert!(walk(&s, 0.05).is_empty()); |
| 712 | } |
| 713 | |
| 714 | |
| 715 | #[test] |
| 716 | fn a_hard_cut_is_not_a_dissolve() { |
| 717 | let mut s: Vec<Thumb> = (0..20).map(|_| flat(130.0, 5)).collect(); |
| 718 | s.extend((0..20).map(|_| flat(40.0, 9))); |
| 719 | assert!(walk(&s, 0.05).is_empty()); |
| 720 | } |
| 721 | |
| 722 | #[test] |
| 723 | fn dissolve_steps_are_the_moving_pairs_that_are_not_dark() { |
| 724 | |
| 725 | assert!(is_dissolve_step(0.0118, 0.05, false)); |
| 726 | assert!(!is_dissolve_step(0.0118, 0.05, true)); |
| 727 | |
| 728 | assert!(!is_dissolve_step(0.4, 0.75, false)); |
| 729 | assert!(!is_dissolve_step(0.04, 0.0, false)); |
| 730 | assert!(!is_dissolve_step(0.0, 0.0, false)); |
| 731 | } |
| 732 | |
| 733 | |
| 734 | #[test] |
| 735 | fn the_steps_of_a_dissolve_are_inside_it() { |
| 736 | let d = Cut { frame: 19, score: 0.6, kind: CutKind::Dissolve { end: 40 } }; |
| 737 | assert!(!inside_dissolve(&d, 19)); |
| 738 | assert!(inside_dissolve(&d, 20)); |
| 739 | assert!(inside_dissolve(&d, 40)); |
| 740 | assert!(!inside_dissolve(&d, 41)); |
| 741 | } |
| 742 | |
| 743 | |
| 744 | |
| 745 | #[test] |
| 746 | fn a_real_dissolve_is_one_boundary_at_any_threshold() { |
| 747 | let path = Scratch::file("xfade", "mp4"); |
| 748 | let ok = Command::new("ffmpeg") |
| 749 | .args(["-v", "error", "-y", "-f", "lavfi", "-t", "2", "-i", "testsrc2=size=320x180:rate=25"]) |
| 750 | .args(["-f", "lavfi", "-t", "2", "-i", "mandelbrot=size=320x180:rate=25"]) |
| 751 | .args(["-filter_complex", "[0:v][1:v]xfade=transition=fade:duration=1:offset=1[v]", "-map", "[v]"]) |
| 752 | .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"]) |
| 753 | .arg(&path) |
| 754 | .status() |
| 755 | .expect("ffmpeg runs") |
| 756 | .success(); |
| 757 | assert!(ok); |
| 758 | for threshold in [DEFAULT_THRESHOLD, 0.1] { |
| 759 | let s = SceneSettings { threshold, ..SceneSettings::default() }; |
| 760 | let cuts = detect(&path, None, &s, None, None).unwrap(); |
| 761 | let dissolves: Vec<&Cut> = cuts.iter().filter(|c| matches!(c.kind, CutKind::Dissolve { .. })).collect(); |
| 762 | assert_eq!(dissolves.len(), 1, "threshold {threshold}: {cuts:?}"); |
| 763 | let d = dissolves[0]; |
| 764 | let CutKind::Dissolve { end } = d.kind else { unreachable!() }; |
| 765 | assert!(d.frame.abs_diff(25) <= 2 && end.abs_diff(50) <= 2, "threshold {threshold}: {cuts:?}"); |
| 766 | assert!(cuts.iter().all(|c| !inside_dissolve(d, c.frame)), "threshold {threshold}: {cuts:?}"); |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | #[test] |
| 771 | fn settings_out_of_range_are_refused() { |
| 772 | let s = SceneSettings { threshold: 1.5, ..SceneSettings::default() }; |
| 773 | assert!(detect(&asset("test_av.mp4"), None, &s, None, None).is_err()); |
| 774 | let s = SceneSettings { sample_fps: Some(0.0), ..SceneSettings::default() }; |
| 775 | assert!(detect(&asset("test_av.mp4"), None, &s, None, None).is_err()); |
| 776 | } |
| 777 | |
| 778 | #[test] |
| 779 | fn cancel_stops_the_walk() { |
| 780 | let (path, _) = three_shots("cancel", 2); |
| 781 | let cancel = AtomicBool::new(true); |
| 782 | assert!(detect(&path, None, &SceneSettings::default(), None, Some(&cancel)).is_err()); |
| 783 | } |
| 784 | |
| 785 | |
| 786 | |
| 787 | #[test] |
| 788 | #[ignore] |
| 789 | fn speed() { |
| 790 | let path = Scratch::file("speed", "mp4"); |
| 791 | let ok = Command::new("ffmpeg") |
| 792 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=25:duration=5"]) |
| 793 | .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"]) |
| 794 | .arg(&path) |
| 795 | .status() |
| 796 | .expect("ffmpeg runs") |
| 797 | .success(); |
| 798 | assert!(ok); |
| 799 | for sample in [None, Some(LONG_FILE_SAMPLE_FPS)] { |
| 800 | let s = SceneSettings { sample_fps: sample, ..SceneSettings::default() }; |
| 801 | let t = Instant::now(); |
| 802 | let cuts = detect(&path, None, &s, None, None).unwrap(); |
| 803 | let secs = t.elapsed().as_secs_f64(); |
| 804 | println!("sample {sample:?}: 125 frames in {secs:.3}s = {:.0} frames/s, {} cuts", 125.0 / secs, cuts.len()); |
| 805 | } |
| 806 | } |
| 807 | } |