Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea check reads the picture once for flashing, freezes, flash frames and blotching: the same findings in half the time

Zachary Guglinb6dad1b8aad4
diff --git a/Cargo.lock b/Cargo.lock
index 7cdaf928..49b07a0a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13693,7 +13693,9 @@ dependencies = [
name = "raea-app-check-read"
version = "0.1.0"
dependencies = [
+ "libc",
"raea-app-media",
+ "raea-io-ffmpeg",
"raea-io-home",
"raea-io-media",
"raea-sys-measure",
diff --git a/apps/check/read/Cargo.toml b/apps/check/read/Cargo.toml
index 2e3a3695..aef29ba6 100644
--- a/apps/check/read/Cargo.toml
+++ b/apps/check/read/Cargo.toml
@@ -11,5 +11,11 @@ serde_json = "1"
raea-io-home = { path = "../../../io/home" }
raea-io-media = { path = "../../../io/media", default-features = false }
raea-app-media = { path = "../../media" }
+# ffmpeg's flag for every decoded frame, by its version (the one read's flashing frames)
+raea-io-ffmpeg = { path = "../../../io/ffmpeg" }
# caption contrast, as `raea world` measures it (DR2)
raea-sys-measure = { path = "../../../systems/measure" }
+
+[target.'cfg(unix)'.dependencies]
+# the one read's named pipes
+libc = "0.2"
diff --git a/apps/check/read/src/lib.rs b/apps/check/read/src/lib.rs
index 200f594e..646d4307 100644
--- a/apps/check/read/src/lib.rs
+++ b/apps/check/read/src/lib.rs
@@ -3,12 +3,14 @@
//! loudness` do, with nothing to install. 0.1.7 refused any video without FFmpeg, which Windows never has (Shane 11-18:
//! "can we make it so ffmpeg does work the way we need it?"). RAEA_CHECK_NATIVE=1 reads natively with FFmpeg there too;
//! tests/parity.rs holds the two to the same answers. Each reader names the FFmpeg command it stands in for.
+pub mod once;
+pub use once::{log_level, showinfo_base, showinfo_frame};
use raea_io_media::VideoDecoder;
use serde_json::Value;
use std::path::Path;
use std::process::Command;
-type R<T> = Result<T, String>;
+pub type R<T> = Result<T, String>;
/// Whether to read natively: FFmpeg's ffmpeg or ffprobe isn't on the PATH, or RAEA_CHECK_NATIVE is on
pub fn native() -> bool {
diff --git a/apps/check/read/src/once.rs b/apps/check/read/src/once.rs
new file mode 100644
index 00000000..99edb4d2
--- /dev/null
+++ b/apps/check/read/src/once.rs
@@ -0,0 +1,205 @@
+//! The picture read once for four of raea check's rules (11-19: flashing, freezes, flash frames and blotching each
+//! decoded the whole file, 3.7 s apiece on a 56 s export, and decoding is the machine's whole CPU, so reading them at
+//! the same time saved nothing). One FFmpeg decodes it and splits the frames into the four filter chains the rules
+//! were tuned on, each to its own output with its own options as when it ran alone, so each rule reads the same bytes:
+//!
+//! - the flashing screen's area- and point-sampled frames (showinfo, rgb24, passthrough) to stdout, their times on stderr;
+//! - freezedetect into a null output, its findings on stderr;
+//! - each frame's 32x18 grey (the flash-frame rule) to a named pipe;
+//! - every 2 s the grey crop blotching scores, to another.
+//!
+//! Unix only (named pipes); elsewhere, and where FFmpeg isn't installed, the rules read on their own as before.
+#[cfg(unix)]
+use std::io::{BufRead, Read};
+#[cfg(unix)]
+use std::path::Path;
+#[cfg(unix)]
+use std::process::{Command, Stdio};
+
+use crate::R;
+
+/// What the one read gave the rules beside the frames it handed on
+pub struct Once {
+ /// the flashing screen's frames read, and whether one came without its time (the read was stopped)
+ pub frames: usize,
+ pub lost: bool,
+ /// FFmpeg ran to its end
+ pub ok: bool,
+ /// errors decoding the picture, and the first of them
+ pub errors: usize,
+ pub first: String,
+ /// freezedetect's lines
+ pub freezes: String,
+ /// each frame's mean brightness, 0 to 1 (defects.rs lumas)
+ pub lumas: Vec<f32>,
+}
+
+/// A frame's number and time from showinfo's log, exact: its `pts` in ticks of the time base. `pts_time` is rounded to six
+/// significant digits, which is enough to push a legal third flash across the one-second line.
+pub fn showinfo_frame(line: &str, base: Option<(i64, i64)>) -> Option<(usize, f64)> {
+ let rest = line.split(" n:").nth(1)?;
+ let n = rest.split_whitespace().next()?.parse().ok()?;
+ let pts: i64 = rest.split("pts:").nth(1)?.split_whitespace().next()?.parse().ok()?;
+ let (num, den) = base?;
+ Some((n, pts as f64 * num as f64 / den as f64))
+}
+
+pub fn showinfo_base(line: &str) -> Option<(i64, i64)> {
+ let (num, den) = line.split("config in time_base:").nth(1)?.split(',').next()?.trim().split_once('/')?;
+ Some((num.parse().ok()?, den.parse().ok()?))
+}
+
+/// A line's severity under `-loglevel level+`: the first bracket after any `[context @ address]`. Searching the whole line
+/// would take a file's own metadata for an error when its title happens to say one.
+pub fn log_level(line: &str) -> Option<&str> {
+ let mut rest = line.trim_start();
+ if rest.starts_with('[') && rest[..rest.find(']')?].contains(" @ ") {
+ rest = rest[rest.find(']')? + 1..].trim_start();
+ }
+ let rest = rest.strip_prefix('[')?;
+ Some(&rest[..rest.find(']')?])
+}
+
+/// Each 32x18 grey frame's mean brightness, 0 to 1 (`scale=32:18:flags=area,format=gray`, defects.rs lumas)
+pub fn lumas_of(grey: &[u8]) -> Vec<f32> {
+ let mut out = Vec::with_capacity(grey.len() / (32 * 18));
+ for f in grey.as_chunks::<{ 32 * 18 }>().0 {
+ let mut sum = 0f32;
+ for &p in f {
+ sum += p as f32;
+ }
+ out.push(sum / (32.0 * 18.0 * 255.0));
+ }
+ out
+}
+
+/// Whether the four rules can read in one: FFmpeg is the reader, and the system has named pipes
+pub fn can() -> bool {
+ cfg!(unix) && !crate::native()
+}
+
+/// The one read: the flashing screen's frames (`flash`, w x h each side) to `screen` with their times, the grey crop
+/// (`crop`, w x h; None when blotching doesn't read) every 2 s to `crops`, freezedetect at `still` seconds
+#[cfg(not(unix))]
+pub fn picture(_: &str, _: (usize, usize), _: Option<(usize, usize)>, _: f64, _: impl FnMut(f64, &[u8]) + Send, _: impl FnMut(&[u8]) + Send) -> R<Once> {
+ Err("one read needs named pipes".into())
+}
+
+#[cfg(unix)]
+pub fn picture(video: &str, flash: (usize, usize), crop: Option<(usize, usize)>, still: f64, mut screen: impl FnMut(f64, &[u8]) + Send, mut crops: impl FnMut(&[u8]) + Send) -> R<Once> {
+ let dir = std::env::temp_dir().join(format!("raea-once-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos())));
+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ let (lumas_at, crops_at) = (dir.join("lumas"), dir.join("crops"));
+ let read = (|| {
+ fifo(&lumas_at)?;
+ if crop.is_some() {
+ fifo(&crops_at)?;
+ }
+ let (w, h) = flash;
+ let mut graph = format!(
+ "[0:v:0]split={}[f][z][l]{};[f]showinfo,split=2[area][point];[area]scale={w}:{h}:flags=area[a];[point]scale={w}:{h}:flags=neighbor[p];[a][p]hstack=inputs=2,format=rgb24[fo];[z]freezedetect=n=-60dB:d={still}[zo];[l]scale=32:18:flags=area,format=gray[lo]",
+ if crop.is_some() { 4 } else { 3 },
+ if crop.is_some() { "[b]" } else { "" }
+ );
+ if let Some((cw, ch)) = crop {
+ graph.push_str(&format!(";[b]fps=0.5,crop={cw}:{ch}:0:0,format=gray[bo]"));
+ }
+ let sync = raea_io_ffmpeg::passthrough();
+ let mut args: Vec<String> = ["-hide_banner", "-nostats", "-nostdin", "-y", "-loglevel", "level+info", "-i", video, "-filter_complex", &graph].map(String::from).to_vec();
+ args.extend(["-map", "[fo]", sync[0], sync[1], "-f", "rawvideo", "pipe:1", "-map", "[zo]", "-f", "null", "-", "-map", "[lo]", "-f", "rawvideo"].map(String::from));
+ args.push(lumas_at.display().to_string());
+ if crop.is_some() {
+ args.extend(["-map", "[bo]", "-f", "rawvideo"].map(String::from));
+ args.push(crops_at.display().to_string());
+ }
+ let mut child = Command::new("ffmpeg").args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("ffmpeg: {e}"))?;
+ let (mut out, err) = (child.stdout.take().unwrap(), child.stderr.take().unwrap());
+ let (times, clock) = std::sync::mpsc::channel();
+ std::thread::scope(|s| {
+ // each output read apart from the others, so that none can fill while another is being waited on
+ let log = s.spawn(move || {
+ let (mut err, mut line) = (std::io::BufReader::new(err), Vec::new());
+ let (mut base, mut errors, mut first, mut freezes) = (None, 0usize, String::new(), String::new());
+ while err.read_until(b'\n', &mut line).is_ok_and(|n| n > 0) {
+ let text = String::from_utf8_lossy(&line);
+ if matches!(log_level(&text), Some("error" | "fatal" | "panic")) {
+ errors += 1;
+ if first.is_empty() {
+ first = text.trim().to_string();
+ }
+ } else if text.trim_start().starts_with("[Parsed_showinfo") {
+ base = showinfo_base(&text).or(base);
+ if let Some(frame) = showinfo_frame(&text, base) {
+ let _ = times.send(frame);
+ }
+ } else if text.contains("freezedetect") {
+ freezes.push_str(&text);
+ }
+ line.clear();
+ }
+ (errors, first, freezes)
+ });
+ let lumas = s.spawn(|| {
+ let mut b = Vec::new();
+ let _ = std::fs::File::open(&lumas_at).and_then(|mut f| f.read_to_end(&mut b));
+ lumas_of(&b)
+ });
+ let crop_reader = crop.map(|(cw, ch)| {
+ let at = &crops_at;
+ let crops = &mut crops;
+ s.spawn(move || {
+ if let Ok(mut f) = std::fs::File::open(at) {
+ let mut buf = vec![0u8; cw * ch];
+ while f.read_exact(&mut buf).is_ok() {
+ crops(&buf);
+ }
+ }
+ })
+ });
+ let mut buf = vec![0u8; w * 2 * h * 3];
+ let (mut frames, mut lost) = (0usize, false);
+ while out.read_exact(&mut buf).is_ok() {
+ // the frame's own line is written before its pixels, so one that doesn't come isn't going to
+ match clock.recv_timeout(std::time::Duration::from_secs(60)) {
+ Ok((n, t)) if n == frames => screen(t, &buf),
+ _ => {
+ lost = true;
+ let _ = child.kill();
+ break;
+ }
+ }
+ frames += 1;
+ }
+ drop(out);
+ let ok = child.wait().is_ok_and(|s| s.success());
+ // a pipe FFmpeg never opened (it stopped first) would hold its reader in open(): opening it to write lets go
+ for p in [&lumas_at, &crops_at] {
+ let _ = unblock(p);
+ }
+ let (errors, first, freezes) = log.join().unwrap_or_default();
+ let lumas = lumas.join().unwrap_or_default();
+ if let Some(c) = crop_reader {
+ let _ = c.join();
+ }
+ Ok(Once { frames, lost, ok, errors, first, freezes, lumas })
+ })
+ })();
+ let _ = std::fs::remove_dir_all(&dir);
+ read
+}
+
+#[cfg(unix)]
+fn fifo(p: &Path) -> R<()> {
+ let c = std::ffi::CString::new(p.as_os_str().as_encoded_bytes()).map_err(|e| e.to_string())?;
+ // SAFETY: a NUL-terminated path, and mkfifo reads nothing else
+ if unsafe { libc::mkfifo(c.as_ptr(), 0o600) } != 0 {
+ return Err(format!("{}: {}", p.display(), std::io::Error::last_os_error()));
+ }
+ Ok(())
+}
+
+#[cfg(unix)]
+fn unblock(p: &Path) -> std::io::Result<()> {
+ use std::os::unix::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new().write(true).custom_flags(libc::O_NONBLOCK).open(p).map(drop)
+}
diff --git a/apps/check/read/tests/parity.rs b/apps/check/read/tests/parity.rs
index eb522971..34f8ce4d 100644
--- a/apps/check/read/tests/parity.rs
+++ b/apps/check/read/tests/parity.rs
@@ -124,3 +124,42 @@ fn the_native_reads_match_ffmpeg_s() {
}
assert!(off.0.iter().all(|(_, by, most)| by < most), "a native read is further from FFmpeg's than a rule allows");
}
+
+/// The one read (once.rs) against the four reads it stands in for, each run alone as raea check ran it: each rule gets
+/// the same bytes, frames and log lines. Away from Unix the rules read alone (no named pipes), and this is skipped.
+#[test]
+fn one_read_gives_each_rule_what_its_own_read_gave() {
+ if !raea_app_check_read::once::can() {
+ eprintln!("skipped: the rules read alone here");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("raea-once-test-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("clip.mp4").to_string_lossy().into_owned();
+ ffmpeg(&["-y", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30:duration=5,tpad=stop_mode=clone:stop_duration=4", "-c:v", "libx264", "-pix_fmt", "yuv420p", &file]);
+ let (w, h, cw, ch) = (192usize, 108usize, 320usize, 176usize);
+ let (mut frames, mut crops) = (Vec::new(), Vec::new());
+ let once = raea_app_check_read::once::picture(&file, (w, h), Some((cw, ch)), 3.0, |t, b| frames.push((t, b.to_vec())), |b| crops.extend_from_slice(b)).unwrap();
+ assert!(once.ok && !once.lost && once.errors == 0);
+ // the flashing screen's frames, as flash.rs read them alone
+ let sync = raea_io_ffmpeg::passthrough();
+ let graph = format!("showinfo,split=2[area][point];[area]scale={w}:{h}:flags=area[a];[point]scale={w}:{h}:flags=neighbor[b];[a][b]hstack=inputs=2,format=rgb24");
+ let (alone, log) = ffmpeg(&["-loglevel", "level+info", "-i", &file, "-map", "0:v:0", "-vf", &graph, sync[0], sync[1], "-f", "rawvideo", "-"]);
+ assert_eq!(frames.len(), alone.len() / (w * 2 * h * 3));
+ assert_eq!(frames.iter().flat_map(|f| f.1.iter().copied()).collect::<Vec<u8>>(), alone);
+ let base = log.lines().find_map(raea_app_check_read::showinfo_base);
+ let times: Vec<f64> = log.lines().filter(|l| l.trim_start().starts_with("[Parsed_showinfo")).filter_map(|l| raea_app_check_read::showinfo_frame(l, base)).map(|f| f.1).collect();
+ assert_eq!(frames.iter().map(|f| f.0).collect::<Vec<f64>>(), times);
+ // each frame's brightness, as defects.rs read it
+ let (grey, _) = ffmpeg(&["-v", "error", "-i", &file, "-map", "0:v:0", "-vf", "scale=32:18:flags=area,format=gray", "-f", "rawvideo", "-"]);
+ assert_eq!(once.lumas, raea_app_check_read::once::lumas_of(&grey));
+ // blotching's crops, as picture.rs read them
+ let (alone, _) = ffmpeg(&["-v", "error", "-i", &file, "-vf", &format!("fps=0.5,crop={cw}:{ch}:0:0,format=gray"), "-f", "rawvideo", "-"]);
+ assert_eq!(crops, alone);
+ // and freezedetect's freeze, as sound.rs read it
+ let (_, log) = ffmpeg(&["-i", &file, "-an", "-vf", "freezedetect=n=-60dB:d=3", "-f", "null", "-"]);
+ let starts = |s: &str| s.lines().filter_map(|l| l.split("freeze_start: ").nth(1).map(|x| x.trim().to_string())).collect::<Vec<_>>();
+ assert_eq!(starts(&once.freezes), starts(&log));
+ assert!(!starts(&log).is_empty());
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/apps/check/src/defects.rs b/apps/check/src/defects.rs
index 44f51b64..daa20d40 100644
--- a/apps/check/src/defects.rs
+++ b/apps/check/src/defects.rs
@@ -131,20 +131,28 @@ fn lumas(video: &str) -> R<(Vec<f32>, f64)> {
if !out.status.success() {
return Err(format!("ffmpeg couldn't read the picture of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
- let l = out.stdout.as_chunks::<{ 32 * 18 }>().0.iter().map(|f| f.iter().map(|&p| p as f32).sum::<f32>() / (32.0 * 18.0 * 255.0)).collect();
+ Ok((crate::read::once::lumas_of(&out.stdout), ffmpeg_rate(video)?))
+}
+
+/// The frame rate `ffmpeg -i` says
+pub(crate) fn ffmpeg_rate(video: &str) -> R<f64> {
let rate = ffmpeg_stderr(&["-hide_banner", "-i", video])?;
- let fps = rate.split(" fps").next().and_then(|s| s.rsplit(", ").next()).and_then(|s| s.trim().parse().ok()).unwrap_or(30.0);
- Ok((l, fps))
+ Ok(rate.split(" fps").next().and_then(|s| s.rsplit(", ").next()).and_then(|s| s.trim().parse().ok()).unwrap_or(30.0))
}
pub(crate) fn flash_frame_rule(video: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
let (l, fps) = lumas(video)?;
- let found = flash_frames(&l, fps);
+ flash_frame_from(&l, fps, issues, passed);
+ Ok(())
+}
+
+/// The stray frames each frame's brightness shows
+pub(crate) fn flash_frame_from(l: &[f32], fps: f64, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
+ let found = flash_frames(l, fps);
if found.is_empty() {
passed.push("flash-frame: no stray black or white frame".into());
}
issues.extend(moments("flash-frame", 1, found));
- Ok(())
}
/// Each moment a rule found, as an issue of that priority
diff --git a/apps/check/src/flash.rs b/apps/check/src/flash.rs
index a6981007..09f5efc6 100644
--- a/apps/check/src/flash.rs
+++ b/apps/check/src/flash.rs
@@ -5,35 +5,46 @@ use raea_app_check_flash::FlashScreen;
/// the area sample and the point sample side by side
const FLASH_W: usize = 192;
-/// A frame's number and time from showinfo's log, exact: its `pts` in ticks of the time base. `pts_time` is rounded to six
-/// significant digits, which is enough to push a legal third flash across the one-second line.
-pub(crate) fn showinfo_frame(line: &str, base: Option<(i64, i64)>) -> Option<(usize, f64)> {
- let rest = line.split(" n:").nth(1)?;
- let n = rest.split_whitespace().next()?.parse().ok()?;
- let pts: i64 = rest.split("pts:").nth(1)?.split_whitespace().next()?.parse().ok()?;
- let (num, den) = base?;
- Some((n, pts as f64 * num as f64 / den as f64))
-}
+pub(crate) use crate::read::{log_level, showinfo_base, showinfo_frame};
-pub(crate) fn showinfo_base(line: &str) -> Option<(i64, i64)> {
- let (num, den) = line.split("config in time_base:").nth(1)?.split(',').next()?.trim().split_once('/')?;
- Some((num.parse().ok()?, den.parse().ok()?))
+/// The flashing screen's frame height for the picture's shape
+fn flash_h(probe: &Probe) -> usize {
+ (((FLASH_W as f64 * probe.h / probe.w.max(1.0)) / 2.0).round() as usize * 2).max(6)
}
-/// A line's severity under `-loglevel level+`: the first bracket after any `[context @ address]`. Searching the whole line
-/// would take a file's own metadata for an error when its title happens to say one.
-pub(crate) fn log_level(line: &str) -> Option<&str> {
- let mut rest = line.trim_start();
- if rest.starts_with('[') && rest[..rest.find(']')?].contains(" @ ") {
- rest = rest[rest.find(']')? + 1..].trim_start();
+/// Freezes, flashing, flash frames and blotching, in that order, from one read of the picture (raea-app-check-read
+/// once.rs: one decode where there were four); each reads on its own where one read can't be had
+pub(crate) fn picture_rules(video: &str, probe: &Probe, taste: Option<&Taste>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
+ if !crate::read::once::can() {
+ freezes(video, probe, taste, issues, passed)?;
+ flashing(video, probe, issues, passed)?;
+ flash_frame_rule(video, issues, passed)?;
+ return blotching(video, probe, issues, passed);
+ }
+ let (w, h) = (FLASH_W, flash_h(probe));
+ let kept = x264_kept(video);
+ let (cw, ch) = (probe.w as usize / 8 * 8, probe.h as usize / 8 * 8);
+ let mut screen = FlashScreen::new(w, h);
+ let mut scores = Vec::new();
+ let once = crate::read::once::picture(video, (w, h), kept.is_none().then_some((cw, ch)), taste.map_or(3.0, |t| t.value), |t, buf| screen.push(buf, t), scorer(&mut scores, cw, ch))?;
+ freezes_from(&once.freezes, probe, taste, issues, passed);
+ if once.lost {
+ return Err(format!("{video}: flashing can't be screened, frame {} has no timestamp of its own", once.frames));
}
- let rest = rest.strip_prefix('[')?;
- Some(&rest[..rest.find(']')?])
+ if !once.ok || once.frames == 0 {
+ return Err(format!("{video}: flashing can't be screened, FFmpeg decoded {} frames ({})", once.frames, once.first));
+ }
+ screened(screen, once.errors, &once.first, issues, passed);
+ flash_frame_from(&once.lumas, ffmpeg_rate(video)?, issues, passed);
+ match kept {
+ Some(crf) => passed.push(format!("blotching: encoded by x264 at crf {crf}, which keeps the darks")),
+ None => blotching_from(video, probe, &scores, issues, passed),
+ }
+ Ok(())
}
pub(crate) fn flashing(video: &str, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
- let w = FLASH_W;
- let h = (((w as f64 * probe.h / probe.w.max(1.0)) / 2.0).round() as usize * 2).max(6);
+ let (w, h) = (FLASH_W, flash_h(probe));
if crate::read::native() {
let mut screen = FlashScreen::new(w, h);
if crate::read::flash_frames(video, w, h, |t, buf| screen.push(buf, t))? == 0 {
diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rs
index 3a799ad2..43725b88 100644
--- a/apps/check/src/lib.rs
+++ b/apps/check/src/lib.rs
@@ -152,10 +152,7 @@ fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<St
loudness(&video, taste_of(&taste, "loudness"), &mut issues, &mut passed)?;
sound(&video, words.as_deref(), &mut issues, &mut passed)?;
}
- freezes(&video, &probe, taste_of(&taste, "still-max"), &mut issues, &mut passed)?;
- flashing(&video, &probe, &mut issues, &mut passed)?;
- flash_frame_rule(&video, &mut issues, &mut passed)?;
- blotching(&video, &probe, &mut issues, &mut passed)?;
+ picture_rules(&video, &probe, taste_of(&taste, "still-max"), &mut issues, &mut passed)?;
brand_kit(&[flag(args, "--manifest").unwrap_or(""), video.as_str()], &mut issues, &mut passed);
if let Some(p) = flag(args, "--things") {
things(p, &mut issues, &mut passed)?;
diff --git a/apps/check/src/picture.rs b/apps/check/src/picture.rs
index f0737d28..af59bec8 100644
--- a/apps/check/src/picture.rs
+++ b/apps/check/src/picture.rs
@@ -119,33 +119,23 @@ fn blotching_cause(video: &str, probe: &Probe, scores: &[Option<f64>], w: usize,
})())
}
-pub(crate) fn blotching(video: &str, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
+/// The crf an x264 encode that keeps the darks was made at: blotching isn't read for it
+pub(crate) fn x264_kept(video: &str) -> Option<f64> {
let mut head = Vec::new();
if let Ok(f) = std::fs::File::open(video) {
let _ = std::io::Read::read_to_end(&mut std::io::Read::take(f, 8 << 20), &mut head);
}
- if let Some(crf) = x264_crf(&head).filter(|c| *c <= X264_KEEPS) {
+ x264_crf(&head).filter(|c| *c <= X264_KEEPS)
+}
+
+pub(crate) fn blotching(video: &str, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
+ if let Some(crf) = x264_kept(video) {
passed.push(format!("blotching: encoded by x264 at crf {crf}, which keeps the darks"));
return Ok(());
}
let (w, h) = (probe.w as usize / 8 * 8, probe.h as usize / 8 * 8);
- let (mut bad, mut seen, mut worst, mut t) = (Vec::new(), 0, 0f64, 0.0);
let mut scores: Vec<Option<f64>> = Vec::new();
- let mut frame = |buf: &[u8]| {
- let score = blotch_score(buf, w, h);
- scores.push(score);
- if let Some(s) = score {
- seen += 1;
- worst = worst.max(s);
- if std::env::var_os("RAEA_CHECK_DEBUG").is_some() {
- eprintln!("blotch {t:6.1}s {s:.3}");
- }
- if s > BLOTCHY {
- bad.push((t, s));
- }
- }
- t += 2.0;
- };
+ let mut frame = scorer(&mut scores, w, h);
if crate::read::native() {
crate::read::crops(video, w, h, &mut frame)?;
} else {
@@ -161,16 +151,42 @@ pub(crate) fn blotching(video: &str, probe: &Probe, issues: &mut Vec<Issue>, pas
}
let _ = child.wait();
}
+ drop(frame);
+ blotching_from(video, probe, &scores, issues, passed);
+ Ok(())
+}
+
+/// Each grey crop's blotching, kept in `scores`
+pub(crate) fn scorer(scores: &mut Vec<Option<f64>>, w: usize, h: usize) -> impl FnMut(&[u8]) + Send + '_ {
+ move |buf| scores.push(blotch_score(buf, w, h))
+}
+
+/// What blotching's samples (one every 2 s) found
+pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
+ let (w, h) = (probe.w as usize / 8 * 8, probe.h as usize / 8 * 8);
+ let (mut bad, mut seen, mut worst) = (Vec::new(), 0, 0f64);
+ for (k, s) in scores.iter().enumerate() {
+ let Some(s) = *s else { continue };
+ let t = k as f64 * 2.0;
+ seen += 1;
+ worst = worst.max(s);
+ if std::env::var_os("RAEA_CHECK_DEBUG").is_some() {
+ eprintln!("blotch {t:6.1}s {s:.3}");
+ }
+ if s > BLOTCHY {
+ bad.push((t, s));
+ }
+ }
if !bad.is_empty() {
let at = bad[0].0;
let share = bad.len() as f64 / seen.max(1) as f64;
let found = format!("blocky patches in dark areas in {} of {seen} sampled frames (worst {:.0}% of dark blocks stepping)", bad.len(), worst * 100.0);
- let (p, at, says) = match blotching_cause(video, probe, &scores, w, h) {
+ let (p, at, says) = match blotching_cause(video, probe, scores, w, h) {
// what the composition draws before any encoding is the picture's own (a phone's compression): no render
// setting removes it, so it's said, not worked on
Some(Ok(a)) if !a.0.by_encode(BLOTCH_NOISE) => (3, Some(at), format!("{found}: the picture's own, there as the composition draws them before any encoding (the footage's compression); the encode added none, so no render setting removes them")),
Some(Ok(a)) => {
- let first = cause::Against::first(&scores, &a.1, BLOTCHY, BLOTCH_NOISE).map(|i| i as f64 * 2.0);
+ let first = cause::Against::first(scores, &a.1, BLOTCHY, BLOTCH_NOISE).map(|i| i as f64 * 2.0);
let own = if a.0.before > 0 { format!("; {} of the samples show the footage's own too, which stays", a.0.before) } else { String::new() };
(if a.0.worse as f64 / a.0.of.max(1) as f64 > 0.2 { 1 } else { 2 }, first.or(Some(at)), format!("the encode added blocky patches in dark areas: {} of {} samples are blotchier than the composition draws them unencoded; render with --quality master, which gives the darks the bits they need{own}", a.0.worse, a.0.of))
}
@@ -181,7 +197,6 @@ pub(crate) fn blotching(video: &str, probe: &Probe, issues: &mut Vec<Issue>, pas
} else if seen > 0 {
passed.push(format!("blotching: dark areas clean in {seen} sampled frames"));
}
- Ok(())
}
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
diff --git a/apps/check/src/sound.rs b/apps/check/src/sound.rs
index 6c02d71c..dc10394f 100644
--- a/apps/check/src/sound.rs
+++ b/apps/check/src/sound.rs
@@ -265,7 +265,14 @@ pub(crate) fn freezes(video: &str, probe: &Probe, taste: Option<&Taste>, issues:
} else {
ffmpeg_stderr(&["-hide_banner", "-nostats", "-i", video, "-an", "-vf", &format!("freezedetect=n=-60dB:d={most}"), "-f", "null", "-"])?
};
- let stretches = frozen_stretches(&err, probe.picture);
+ freezes_from(&err, probe, taste, issues, passed);
+ Ok(())
+}
+
+/// The freezes freezedetect's lines found (`taste`'s still-max when the person set one, else 3 s)
+pub(crate) fn freezes_from(err: &str, probe: &Probe, taste: Option<&Taste>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
+ let most = taste.map_or(3.0, |t| t.value);
+ let stretches = frozen_stretches(err, probe.picture);
for &(s, d) in &stretches {
let says = format!("nothing changes for {d:.1} s; give it a reason to hold, or cut it shorter");
issues.push(match taste {
@@ -276,5 +283,4 @@ pub(crate) fn freezes(video: &str, probe: &Probe, taste: Option<&Taste>, issues:
if stretches.is_empty() {
passed.push(format!("frozen: nothing holds still for {most} s"));
}
- Ok(())
}