mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f68805b981 | ||
|
|
db53845b01 | ||
|
|
3ffe34bb7d | ||
|
|
0706baee4e | ||
|
|
1b7450fb4b | ||
|
|
84acab1f50 | ||
|
|
25280d1eba | ||
|
|
6350c5deb0 | ||
|
|
b6dad1b8aa | ||
|
|
4c3a3ba799 | ||
|
|
6d076868f0 | ||
|
|
119f458018 | ||
|
|
1899d29dff |
No files matched your search
Generated
+31
-1
@@ -13654,10 +13654,11 @@ dependencies = [
|
||||
name = "raea-app-check"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-check-cause",
|
||||
"raea-app-check-flash",
|
||||
"raea-app-check-inbox",
|
||||
"raea-app-check-read",
|
||||
"raea-app-check-text",
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"raea-io-ffmpeg",
|
||||
@@ -13667,6 +13668,15 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-check-cause"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-check-flash"
|
||||
version = "0.1.0"
|
||||
@@ -13683,13 +13693,24 @@ 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",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-check-text"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-core-facts",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-ci"
|
||||
version = "0.1.0"
|
||||
@@ -13705,6 +13726,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-check",
|
||||
"raea-app-check-text",
|
||||
"raea-app-notes",
|
||||
"raea-app-registry",
|
||||
"raea-core-brief",
|
||||
@@ -16081,10 +16103,18 @@ dependencies = [
|
||||
"cpal 0.15.3",
|
||||
"firewheel",
|
||||
"raea-io-media",
|
||||
"raea-sys-mix-level",
|
||||
"raea-sys-tone",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mix-level"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-io-media",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-ml"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -80,6 +80,7 @@ members = [
|
||||
"systems/k",
|
||||
"systems/tone",
|
||||
"systems/mix",
|
||||
"systems/mix/level",
|
||||
"systems/ml",
|
||||
"systems/mlx",
|
||||
"systems/kimodo",
|
||||
@@ -187,9 +188,11 @@ members = [
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/check",
|
||||
"apps/check/cause",
|
||||
"apps/check/flash",
|
||||
"apps/check/inbox",
|
||||
"apps/check/read",
|
||||
"apps/check/text",
|
||||
"apps/direction",
|
||||
"apps/notes",
|
||||
"apps/fingerprint",
|
||||
|
||||
@@ -7,7 +7,6 @@ publish = false
|
||||
description = "`raea check`: the floor's measurable lines on an export, ranked P0-P3"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0)
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
# a transcript's words, read as `raea world` reads them (docs/direction.feature DR1)
|
||||
@@ -21,6 +20,10 @@ raea-io-ffmpeg = { path = "../../io/ffmpeg" }
|
||||
raea-sys-measure = { path = "../../systems/measure" }
|
||||
# what it reads of a video, through FFmpeg or raea's own decoders where it isn't installed
|
||||
raea-app-check-read = { path = "read" }
|
||||
# who can fix what it finds: the encode's or the picture's own, carried, a source (split out to keep this crate small)
|
||||
raea-app-check-cause = { path = "cause" }
|
||||
# the text rules on a render's manifest (split out: raea render holds its own text to them)
|
||||
raea-app-check-text = { path = "text" }
|
||||
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
|
||||
raea-app-check-flash = { path = "flash" }
|
||||
# what the person sent from the raea app, handed to the agent (split out to keep this crate small)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "raea-app-check-cause"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Who can fix what raea check finds: the encode's or the picture's own, carried from an earlier export, a source rather than a delivery"
|
||||
|
||||
[dependencies]
|
||||
# a project's record of renders and checks (DR3)
|
||||
raea-core-facts = { path = "../../../core/facts" }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Who can fix what `raea check` finds, so a round is spent only on what another render can change (11-19: two
|
||||
//! Telluride projects took nine renders, five of them for findings no render could move). Three things, for any rule:
|
||||
//!
|
||||
//! - **Introduced or there already.** A rule an encode can cause is measured again on the composition's own frames,
|
||||
//! rendered without encoding (`unencoded`), and the export is set against them (`against`): what the picture already
|
||||
//! held is the footage's (a note), what the export adds is the encode's (the error, with a fix raea has).
|
||||
//! - **Carried.** A finding an earlier export of the same composition had at the same moment (`earlier`, `carried`)
|
||||
//! says since when: the change between them didn't move it, so doing that again won't.
|
||||
//! - **A source isn't a delivery.** A take or a download checked on its own (`is_source`) isn't held to a delivery's
|
||||
//! loudness target.
|
||||
//!
|
||||
//! None of it changes what a rule measures or where it draws the line.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use raea_core_facts::{Finding, record};
|
||||
|
||||
pub type R<T> = Result<T, String>;
|
||||
|
||||
/// Whether a record entry is the render that wrote `out` (a path as the record names it)
|
||||
fn rendered(e: &record::Entry, out: &str) -> bool {
|
||||
e.by == "raea render" && e.out.as_deref() == Some(out)
|
||||
}
|
||||
|
||||
/// The composition a video was rendered from, and its project: the newest `raea render` writing it in the project's
|
||||
/// record (DR3). None outside a project, or for a video no render there wrote (a take, a download).
|
||||
pub fn composition_of(video: &Path) -> Option<(PathBuf, PathBuf)> {
|
||||
let project = record::up(video, ".raea/project")?;
|
||||
let want = record::rel(&project, video);
|
||||
let made = record::read(&project).into_iter().rev().find(|e| e.kind == "video" && rendered(e, &want))?;
|
||||
let of = project.join(&made.of);
|
||||
of.is_file().then_some((project, of))
|
||||
}
|
||||
|
||||
/// Whether a file is one of a project's sources (a take or a download under assets/ or media/ that no render wrote):
|
||||
/// it isn't a delivery, so a delivery's rules (its loudness target) don't hold it
|
||||
pub fn is_source(video: &Path) -> bool {
|
||||
let Some(project) = record::up(video, ".raea/project") else { return false };
|
||||
let me = record::rel(&project, video);
|
||||
(me.starts_with("assets/") || me.starts_with("media/")) && !record::read(&project).iter().any(|e| rendered(e, &me))
|
||||
}
|
||||
|
||||
/// Luma as a decoder of raea's export gives it to the check (BT.709, full range: FFmpeg's format=gray of the
|
||||
/// encoder's limited-range picture), from 8-bit RGBA `width` wide, its top-left `w` x `h`
|
||||
pub fn luma(rgba: &[u8], width: usize, w: usize, h: usize) -> Vec<u8> {
|
||||
let mut y = Vec::with_capacity(w * h);
|
||||
for r in 0..h {
|
||||
for p in rgba[r * width * 4..][..w * 4].chunks_exact(4) {
|
||||
y.push((0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32).round().clamp(0.0, 255.0) as u8);
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
|
||||
/// `frames` as `comp` draws them, never encoded, as luma `w` x `h` (top-left): `raea render COMP --at F,... -o DIR/`
|
||||
/// (PNG) run by `raea` from the project, kept out of its record as the quick check's stills are
|
||||
pub fn unencoded(raea: &Path, project: &Path, comp: &Path, frames: &[i64], w: usize, h: usize) -> R<Vec<Vec<u8>>> {
|
||||
let mut wanted: Vec<i64> = frames.to_vec();
|
||||
wanted.sort_unstable();
|
||||
wanted.dedup();
|
||||
let tmp = std::env::temp_dir().join(format!("raea-unencoded-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
let at = wanted.iter().map(|f| f.to_string()).collect::<Vec<_>>().join(",");
|
||||
let read = (|| {
|
||||
let run = Command::new(raea).arg("render").arg(comp).args(["--at", &at, "-o"]).arg(format!("{}/", tmp.display())).current_dir(project).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
|
||||
let mut pngs: Vec<PathBuf> = std::fs::read_dir(&tmp).map_err(|e| e.to_string())?.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|x| x == "png")).collect();
|
||||
pngs.sort();
|
||||
if pngs.len() != wanted.len() {
|
||||
let said = String::from_utf8_lossy(&run.stderr).lines().chain(String::from_utf8_lossy(&run.stdout).lines()).find(|l| l.contains("REFUSED") || l.contains("rror")).unwrap_or("").to_string();
|
||||
return Err(format!("its render gave {} of {} frames {said}", pngs.len(), wanted.len()).trim_end().to_string());
|
||||
}
|
||||
let mut by_frame = std::collections::HashMap::new();
|
||||
for (f, p) in wanted.iter().zip(&pngs) {
|
||||
let img = image::open(p).map_err(|e| format!("{}: {e}", p.display()))?.to_rgba8();
|
||||
let (iw, ih) = (img.width() as usize, img.height() as usize);
|
||||
if iw < w || ih < h {
|
||||
return Err(format!("it draws {iw}x{ih}, smaller than the export's {w}x{h}"));
|
||||
}
|
||||
by_frame.insert(*f, luma(img.as_raw(), iw, w, h));
|
||||
}
|
||||
Ok(frames.iter().map(|f| by_frame[f].clone()).collect())
|
||||
})();
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
read
|
||||
}
|
||||
|
||||
/// The frame a check reads for each sample taken every `every` seconds from 0: the last frame before the sample's
|
||||
/// middle, as ffmpeg's fps filter picks it (and raea-app-check-read's readers), held to the picture's `last` frame
|
||||
pub fn sampled(samples: usize, every: f64, fps: f64, last: i64) -> Vec<i64> {
|
||||
(0..samples).map(|k| (((k as f64 + 0.5) * every * fps).ceil() as i64 - 1).clamp(0, last.max(0))).collect()
|
||||
}
|
||||
|
||||
/// A sampled measure of the export against the same measure of the unencoded frames.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Against {
|
||||
/// samples over the rule's line that the export made worse by more than its noise
|
||||
pub worse: usize,
|
||||
/// samples over the line before encoding: the picture's own
|
||||
pub before: usize,
|
||||
/// samples compared
|
||||
pub of: usize,
|
||||
/// the mean of the export's measure less the unencoded one's
|
||||
pub added: f64,
|
||||
}
|
||||
|
||||
impl Against {
|
||||
/// Whether the export added to it, beyond what a clean encode moves: at least three samples (and a tenth) worse,
|
||||
/// and more than half the noise on average
|
||||
pub fn by_encode(&self, noise: f64) -> bool {
|
||||
self.worse >= 3usize.max(self.of / 10) && self.added > noise / 2.0
|
||||
}
|
||||
|
||||
/// The first sample the export made worse
|
||||
pub fn first(out: &[Option<f64>], before: &[Option<f64>], line: f64, noise: f64) -> Option<usize> {
|
||||
out.iter().zip(before).position(|(o, b)| o.unwrap_or(0.0) > line && o.unwrap_or(0.0) - b.unwrap_or(0.0) > noise)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per sample, the export's measure against the unencoded frames' (None: nothing to measure, read as 0), over a
|
||||
/// rule's `line`, where a clean encode moves it at most `noise`
|
||||
pub fn against(out: &[Option<f64>], before: &[Option<f64>], line: f64, noise: f64) -> Against {
|
||||
let n = out.len().min(before.len());
|
||||
let at = |s: &[Option<f64>], i: usize| s[i].unwrap_or(0.0);
|
||||
let worse = (0..n).filter(|&i| at(out, i) > line && at(out, i) - at(before, i) > noise).count();
|
||||
let was = (0..n).filter(|&i| at(before, i) > line).count();
|
||||
let added = (0..n).map(|i| at(out, i) - at(before, i)).sum::<f64>() / n.max(1) as f64;
|
||||
Against { worse, before: was, of: n, added }
|
||||
}
|
||||
|
||||
/// The newest check, in the project's record, of an earlier export of the composition `video` was rendered from
|
||||
pub fn earlier(video: &Path) -> Option<record::Entry> {
|
||||
let project = record::up(video, ".raea/project")?;
|
||||
let me = record::rel(&project, video);
|
||||
let entries = record::read(&project);
|
||||
let made = entries.iter().rposition(|e| rendered(e, &me))?;
|
||||
// the composition's exports rendered before this one; a versioned copy (NAME-v2.tsx) is the same piece
|
||||
let stem = |of: &str| piece(&Path::new(of).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
|
||||
let comp = stem(&entries[made].of);
|
||||
let exports: Vec<String> = entries[..made].iter().filter(|e| e.by == "raea render" && e.kind == "video" && stem(&e.of) == comp).filter_map(|e| e.out.clone()).filter(|o| *o != me).collect();
|
||||
entries.into_iter().rev().find(|e| e.by == "raea check" && exports.contains(&e.of))
|
||||
}
|
||||
|
||||
/// A composition's name without its version: walkaround-v2 is walkaround
|
||||
pub fn piece(stem: &str) -> String {
|
||||
match stem.rfind("-v") {
|
||||
Some(i) if i + 2 < stem.len() && stem[i + 2..].bytes().all(|b| b.is_ascii_digit()) => stem[..i].to_string(),
|
||||
_ => stem.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same finding in another export: the same rule, about the same thing, at the same moment (within a second; a
|
||||
/// finding about the whole piece matches one about the whole piece). Its words may differ ("worst 13%", "worst 15%").
|
||||
pub fn alike(a: &Finding, b: &Finding, fps: f64) -> bool {
|
||||
let about = |f: &Finding| f.about.iter().map(|a| a.key.clone().unwrap_or_else(|| a.name.clone())).collect::<Vec<_>>();
|
||||
a.check == b.check && about(a) == about(b) && match (a.frames, b.frames) {
|
||||
(Some([x, _]), Some([y, _])) => ((x - y).abs() as f64) <= fps.max(1.0),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each finding an earlier check had at the same moment says so, and that its fix hasn't moved it: rank and words
|
||||
/// otherwise as measured
|
||||
pub fn carried(now: &mut [Finding], before: &record::Entry, fps: f64) {
|
||||
for f in now.iter_mut() {
|
||||
if before.findings.iter().any(|b| alike(b, f, fps)) {
|
||||
f.says.push_str(&format!(" [also in {} ({}): what changed between them didn't move it]", before.of, before.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,107 @@
|
||||
use super::*;
|
||||
use raea_core_facts::Level;
|
||||
|
||||
// The 28 samples `raea check` takes of the 11-16 Telluride walkaround (55.8 s, 24 fps, phone footage), as its
|
||||
// blotching measures them: rendered to PNG with no encoding (BEFORE), those PNGs through x264 crf 12, and raea's own
|
||||
// exports at --quality high and master. Blotching's line is 0.009; x264 moved a sample at most 0.005.
|
||||
const BEFORE: [Option<f64>; 28] = [Some(0.0), None, Some(0.052), Some(0.062), None, Some(0.062), None, None, Some(0.076), Some(0.009), Some(0.03), Some(0.039), Some(0.068), None, None, None, None, Some(0.077), Some(0.062), None, None, Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0)];
|
||||
const X264: [Option<f64>; 28] = [Some(0.0), None, Some(0.052), Some(0.062), None, Some(0.059), None, None, Some(0.078), Some(0.008), Some(0.028), Some(0.034), Some(0.071), None, None, None, None, Some(0.078), Some(0.062), None, Some(0.039), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0)];
|
||||
const HIGH: [Option<f64>; 28] = [Some(0.0), None, Some(0.042), Some(0.024), Some(0.052), Some(0.064), Some(0.05), None, Some(0.126), Some(0.063), Some(0.061), Some(0.122), Some(0.088), Some(0.04), Some(0.029), Some(0.047), Some(0.044), Some(0.096), Some(0.09), None, Some(0.029), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0)];
|
||||
const MASTER: [Option<f64>; 28] = [Some(0.0), None, Some(0.026), Some(0.002), None, Some(0.03), None, None, Some(0.022), None, None, None, None, None, None, None, None, Some(0.071), Some(0.053), None, None, Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0), Some(0.0)];
|
||||
const LINE: f64 = 0.009;
|
||||
const NOISE: f64 = 0.005;
|
||||
|
||||
/// What the picture already held is told from what the encode added: a clean encode and raea's master add nothing,
|
||||
/// its high adds to 14 of 28 samples, and 9 samples hold the footage's own either way
|
||||
#[test]
|
||||
fn the_picture_s_own_is_told_from_the_encode_s() {
|
||||
let clean = against(&X264, &BEFORE, LINE, NOISE);
|
||||
assert!(!clean.by_encode(NOISE), "{clean:?}");
|
||||
assert!(clean.added.abs() < 0.002, "{clean:?}");
|
||||
let high = against(&HIGH, &BEFORE, LINE, NOISE);
|
||||
assert!(high.by_encode(NOISE), "{high:?}");
|
||||
assert_eq!((high.worse, high.before, high.of), (14, 9, 28));
|
||||
assert_eq!(Against::first(&HIGH, &BEFORE, LINE, NOISE), Some(4));
|
||||
let master = against(&MASTER, &BEFORE, LINE, NOISE);
|
||||
assert!(!master.by_encode(NOISE), "{master:?}");
|
||||
assert_eq!(master.worse, 0);
|
||||
// a small, even addition over a clean picture still counts (VideoToolbox over a dark render, 10-25)
|
||||
assert!(against(&[Some(0.013); 16], &[Some(0.003); 16], LINE, NOISE).by_encode(NOISE));
|
||||
}
|
||||
|
||||
/// The frame read for each sample is the last before its middle, as the fps filter picks it
|
||||
#[test]
|
||||
fn the_sampled_frames_are_the_check_s() {
|
||||
assert_eq!(sampled(3, 2.0, 24.0, 1338), vec![23, 71, 119]);
|
||||
assert_eq!(sampled(2, 2.0, 30.0, 1000), vec![29, 89]);
|
||||
assert_eq!(sampled(2, 2.0, 30000.0 / 1001.0, 1000), vec![29, 89]);
|
||||
assert_eq!(sampled(2, 2.0, 24.0, 50), vec![23, 50]);
|
||||
}
|
||||
|
||||
/// Luma as the check reads raea's export: BT.709 weights, full range, cropped to the top-left
|
||||
#[test]
|
||||
fn luma_is_bt709_cropped() {
|
||||
let px = |r: u8, g: u8, b: u8| [r, g, b, 255];
|
||||
let rgba: Vec<u8> = [px(255, 255, 255), px(0, 0, 0), px(255, 0, 0), px(0, 255, 0)].concat();
|
||||
assert_eq!(luma(&rgba, 2, 2, 2), vec![255, 0, 54, 182]);
|
||||
assert_eq!(luma(&rgba, 2, 1, 2), vec![255, 54]);
|
||||
}
|
||||
|
||||
fn finding(check: &str, frame: Option<i64>, says: &str) -> Finding {
|
||||
let f = Finding::new(check, Level::Error, says, "raea check");
|
||||
match frame {
|
||||
Some(n) => f.frames(n, n + 1),
|
||||
None => f,
|
||||
}
|
||||
}
|
||||
|
||||
/// A finding is carried when the same rule finds the same thing at the same moment, whatever its numbers say
|
||||
#[test]
|
||||
fn a_carried_finding_is_the_same_rule_at_the_same_moment() {
|
||||
let fps = 24.0;
|
||||
assert!(alike(&finding("blotching", Some(96), "worst 13%"), &finding("blotching", Some(96), "worst 15%"), fps));
|
||||
assert!(alike(&finding("clipping", Some(624), "9 runs"), &finding("clipping", Some(640), "6 runs"), fps));
|
||||
assert!(!alike(&finding("clipping", Some(624), "9 runs"), &finding("clipping", Some(1104), "11 runs"), fps));
|
||||
assert!(!alike(&finding("clipping", Some(624), "x"), &finding("dropout", Some(624), "x"), fps));
|
||||
assert!(alike(&finding("brand", None, "a"), &finding("brand", None, "b"), fps));
|
||||
assert_eq!(piece("walkaround-v2"), "walkaround");
|
||||
assert_eq!(piece("edit-video"), "edit-video");
|
||||
assert_eq!(piece("telluride-v12"), "telluride");
|
||||
}
|
||||
|
||||
/// A project whose record holds two renders of one composition and a check of the first: the second's check finds
|
||||
/// that one, its blotching carried and its clipping new; a take under assets/ is a source, an export isn't
|
||||
#[test]
|
||||
fn the_earlier_check_is_of_the_composition_s_other_export() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-cause-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
for d in [".raea/record", "out", "assets/footage", "compositions"] {
|
||||
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||
}
|
||||
std::fs::write(dir.join(".raea/project"), "[project]\n\tid = pj_test\n").unwrap();
|
||||
for f in ["out/a-v1.mp4", "out/a-v2.mp4", "assets/footage/take.mov", "compositions/a.tsx", "compositions/a-v2.tsx"] {
|
||||
std::fs::write(dir.join(f), b"").unwrap();
|
||||
}
|
||||
let entry = |id: &str, by: &str, of: &str, out: Option<&str>, kind: &str, findings: Vec<Finding>| record::Entry { id: id.into(), at: 0, by: by.into(), of: of.into(), out: out.map(Into::into), kind: kind.into(), commit: None, findings, despite: vec![] };
|
||||
let entries = [
|
||||
entry("20261116-170223-a", "raea render", "compositions/a.tsx", Some("out/a-v1.mp4"), "video", vec![]),
|
||||
entry("20261116-170252-a-v1", "raea check", "out/a-v1.mp4", None, "check", vec![finding("blotching", Some(96), "worst 13%")]),
|
||||
entry("20261116-171601-a-v2", "raea render", "compositions/a-v2.tsx", Some("out/a-v2.mp4"), "video", vec![]),
|
||||
];
|
||||
for e in &entries {
|
||||
std::fs::write(dir.join(format!(".raea/record/{}.json", e.id)), serde_json::to_vec(e).unwrap()).unwrap();
|
||||
}
|
||||
let v2 = dir.join("out/a-v2.mp4");
|
||||
assert_eq!(composition_of(&v2).map(|(_, c)| c.ends_with("compositions/a-v2.tsx")), Some(true));
|
||||
let before = earlier(&v2).expect("the check of a-v1");
|
||||
assert_eq!(before.of, "out/a-v1.mp4");
|
||||
let mut now = vec![finding("blotching", Some(96), "worst 15%"), finding("clipping", Some(624), "9 runs")];
|
||||
carried(&mut now, &before, 24.0);
|
||||
assert!(now[0].says.contains("also in out/a-v1.mp4 (20261116-170252-a-v1)"), "{}", now[0].says);
|
||||
assert_eq!(now[1].says, "9 runs");
|
||||
// nothing was rendered before a-v1, so its check has no earlier one, even with a-v2's check in the record
|
||||
assert!(earlier(&dir.join("out/a-v1.mp4")).is_none());
|
||||
assert!(is_source(&dir.join("assets/footage/take.mov")));
|
||||
assert!(!is_source(&v2));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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 {
|
||||
@@ -41,6 +43,8 @@ pub struct Probe {
|
||||
/// past the picture, and the container's duration counts that
|
||||
pub picture: f64,
|
||||
pub audio: bool,
|
||||
/// the picture's frames a second (0 when it doesn't say)
|
||||
pub fps: f64,
|
||||
}
|
||||
|
||||
/// The picture's size, the file's duration, where the picture ends and whether there's sound: ffprobe's stream and
|
||||
@@ -50,7 +54,7 @@ pub fn probe(video: &str) -> R<Probe> {
|
||||
let p = raea_app_media::probe_of(Path::new(video))?;
|
||||
let v = p.video.as_ref().ok_or("no video stream")?;
|
||||
let picture = p.track.as_ref().map_or(v.duration, |t| t.duration);
|
||||
return Ok(Probe { w: v.width as f64, h: v.height as f64, duration: p.duration.max(picture), picture, audio: p.audio.is_some() });
|
||||
return Ok(Probe { w: v.width as f64, h: v.height as f64, duration: p.duration.max(picture), picture, audio: p.audio.is_some(), fps: v.fps });
|
||||
}
|
||||
let entries = "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time";
|
||||
let out = Command::new("ffprobe").args(["-v", "error", "-show_entries", entries, "-of", "json", video]).output().map_err(|e| format!("ffprobe: {e}"))?;
|
||||
@@ -65,7 +69,11 @@ pub fn probe(video: &str) -> R<Probe> {
|
||||
None => last_packet_end(video).map_or(duration, |end| end - origin),
|
||||
};
|
||||
let audio = streams.iter().any(|s| s["codec_type"] == "audio");
|
||||
Ok(Probe { w: vid["width"].as_f64().unwrap_or(1920.0), h: vid["height"].as_f64().unwrap_or(1080.0), duration, picture, audio })
|
||||
let fps = vid["r_frame_rate"].as_str().and_then(|r| {
|
||||
let (n, d) = r.split_once('/').unwrap_or((r, "1"));
|
||||
Some(n.parse::<f64>().ok()? / d.parse::<f64>().ok().filter(|d| *d > 0.0)?)
|
||||
});
|
||||
Ok(Probe { w: vid["width"].as_f64().unwrap_or(1920.0), h: vid["height"].as_f64().unwrap_or(1080.0), duration, picture, audio, fps: fps.unwrap_or(0.0) })
|
||||
}
|
||||
|
||||
/// Where the picture's last packet ends, for a container that doesn't state the video stream's own length (Matroska)
|
||||
@@ -146,7 +154,30 @@ pub fn flash_frames(video: &str, w: usize, h: usize, mut each: impl FnMut(f64, &
|
||||
|
||||
/// `ffmpeg -i V -vn -ac 1 -ar RATE -f f32le -` (sound.rs sound): the sound folded to mono at `rate`
|
||||
pub fn mono(video: &str, rate: u32) -> R<Vec<f32>> {
|
||||
Ok(raea_app_media::audio_folded(Path::new(video), rate, true, None, None, false)?.channels.swap_remove(0))
|
||||
if native() {
|
||||
return Ok(raea_app_media::audio_folded(Path::new(video), rate, true, None, None, false)?.channels.swap_remove(0));
|
||||
}
|
||||
ffmpeg_f32(video, 1, rate)
|
||||
}
|
||||
|
||||
/// `ffmpeg -i V -vn -ac N -ar R -f f32le -`: the sound as N interleaved channels of floats
|
||||
fn ffmpeg_f32(video: &str, channels: u32, rate: u32) -> R<Vec<f32>> {
|
||||
let out = Command::new("ffmpeg").args(["-v", "error", "-i", video, "-vn", "-ac", &channels.to_string(), "-ar", &rate.to_string(), "-f", "f32le", "-"]).output().map_err(|e| format!("ffmpeg: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("ffmpeg couldn't read the sound of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));
|
||||
}
|
||||
Ok(out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())
|
||||
}
|
||||
|
||||
/// `ffmpeg -i V -vn -ac 2 -ar R -f f32le -` (defects.rs clipping): each channel at its own level. Clipping is a
|
||||
/// channel's: on the mono fold (L + R) * 0.707 a centred voice reads 3 dB hotter than either side, and a master at
|
||||
/// -1.6 dBTP read as full scale (11-19, the walkaround's flat tops).
|
||||
pub fn channels(video: &str, rate: u32) -> R<Vec<Vec<f32>>> {
|
||||
if native() {
|
||||
return Ok(raea_app_media::audio_folded(Path::new(video), rate, false, None, None, false)?.channels);
|
||||
}
|
||||
let x = ffmpeg_f32(video, 2, rate)?;
|
||||
Ok(vec![x.iter().step_by(2).copied().collect(), x.iter().skip(1).step_by(2).copied().collect()])
|
||||
}
|
||||
|
||||
/// `ffmpeg -i V -vn -af ebur128=metadata=1,ametadata=print:key=lavfi.r128.M:file=- -f null -` (sound.rs sound): the
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+27
-11
@@ -11,8 +11,12 @@ pub(crate) const FULL: f32 = 0.999;
|
||||
pub(crate) const FLAT_LEVEL: f32 = 0.05;
|
||||
pub(crate) const CLIP_RUNS: usize = 3;
|
||||
|
||||
pub(crate) fn clipped(x: &[f32]) -> Vec<(f64, String)> {
|
||||
let mut per: Vec<usize> = vec![0; x.len() / SR + 1];
|
||||
pub(crate) fn clipped(channels: &[Vec<f32>]) -> Vec<(f64, String)> {
|
||||
let len = channels.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let mut per: Vec<usize> = vec![0; len / SR + 1];
|
||||
// each channel's runs, a second's count the most any channel had: clipping is a channel's
|
||||
for x in channels {
|
||||
let mut own: Vec<usize> = vec![0; len / SR + 1];
|
||||
let mut i = 0;
|
||||
while i < x.len() {
|
||||
let v = x[i];
|
||||
@@ -22,18 +26,22 @@ pub(crate) fn clipped(x: &[f32]) -> Vec<(f64, String)> {
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 3 {
|
||||
per[i / SR] += 1;
|
||||
own[i / SR] += 1;
|
||||
}
|
||||
} else if v.abs() >= FLAT_LEVEL {
|
||||
while j < x.len() && x[j].to_bits() == v.to_bits() {
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 4 {
|
||||
per[i / SR] += 1;
|
||||
own[i / SR] += 1;
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
for (p, o) in per.iter_mut().zip(own) {
|
||||
*p = (*p).max(o);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut s = 0;
|
||||
while s < per.len() {
|
||||
@@ -123,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
|
||||
@@ -145,8 +161,8 @@ pub(crate) fn moments(rule: &'static str, p: u8, found: Vec<(f64, String)>) -> i
|
||||
}
|
||||
|
||||
/// The sound's defects on the decoded mix (sound.rs decodes it once)
|
||||
pub(crate) fn sound_defects(x: &[f32], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
for (rule, found, ok) in [("clipping", clipped(x), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {
|
||||
pub(crate) fn sound_defects(x: &[f32], channels: &[Vec<f32>], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
for (rule, found, ok) in [("clipping", clipped(channels), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {
|
||||
if found.is_empty() {
|
||||
passed.push(ok.into());
|
||||
}
|
||||
|
||||
+34
-23
@@ -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};
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
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()?))
|
||||
}
|
||||
|
||||
/// 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 rest = rest.strip_prefix('[')?;
|
||||
Some(&rest[..rest.find(']')?])
|
||||
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));
|
||||
}
|
||||
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 {
|
||||
|
||||
+17
-23
@@ -22,8 +22,10 @@ mod flash;
|
||||
use flash::*;
|
||||
mod defects;
|
||||
use defects::*;
|
||||
mod text;
|
||||
use text::*;
|
||||
/// what a render's text breaks, from its manifest (split out: a render holds its own text to it)
|
||||
use raea_app_check_text::*;
|
||||
/// who can fix what it finds: the encode's or the picture's own, carried from an earlier export, a source
|
||||
use raea_app_check_cause as cause;
|
||||
/// a video read through FFmpeg, or raea's own decoders where it isn't installed
|
||||
use raea_app_check_read::{self as read, Probe};
|
||||
pub mod quick;
|
||||
@@ -32,15 +34,6 @@ pub use raea_app_check_inbox as inbox;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Issue {
|
||||
rule: &'static str,
|
||||
p: u8,
|
||||
at: Option<f64>,
|
||||
says: String,
|
||||
}
|
||||
|
||||
/// `raea check …` with the person's taste, none or more (taste.ts and the kinds beside it, which the raea CLI evaluates: it owns the engine):
|
||||
/// its rules' checks hold the export to the person's own lines.
|
||||
@@ -159,14 +152,17 @@ 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)?;
|
||||
}
|
||||
// a take or a download isn't a delivery: the mix sets the delivery's level, so its own is said, not held to the target
|
||||
if cause::is_source(std::path::Path::new(&video)) {
|
||||
for i in issues.iter_mut().filter(|i| i.rule == "loudness") {
|
||||
(i.p, i.says) = (3, format!("a source, not a delivery: {} (the mix sets the delivery's level)", i.says));
|
||||
}
|
||||
}
|
||||
if let Some(manifest) = &manifest {
|
||||
let runs = text_runs(manifest);
|
||||
let (w, h) = (manifest["width"].as_f64().unwrap_or(probe.w), manifest["height"].as_f64().unwrap_or(probe.h));
|
||||
@@ -204,19 +200,17 @@ fn things(p: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
/// `fps`), with `more` (a render's own), worst first then by time.
|
||||
fn findings_of(mut issues: Vec<Issue>, more: Vec<Finding>, fps: f64) -> Vec<Finding> {
|
||||
issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));
|
||||
let mut found = Vec::new();
|
||||
for i in &issues {
|
||||
// an issue at a second is about the frame it falls on
|
||||
let (f, fr) = (Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check"), (i.at.unwrap_or(0.0) * fps).round() as i64);
|
||||
found.push(if i.at.is_some() { f.frames(fr, fr + 1) } else { f });
|
||||
}
|
||||
finding::ranked(found.into_iter().chain(more).collect())
|
||||
finding::ranked(issues.iter().map(|i| i.finding("raea check", fps)).chain(more).collect())
|
||||
}
|
||||
|
||||
/// The findings (`findings_of`), written to -o as JSON when asked, and the report's text with the count last. True
|
||||
/// when an error is among them.
|
||||
fn report(video: &str, issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<String>, out: Option<&str>, fps: f64) -> R<(String, bool)> {
|
||||
let found = findings_of(issues, more, fps);
|
||||
let mut found = findings_of(issues, more, fps);
|
||||
// what an earlier export of the same composition already had says so: the change between them didn't move it
|
||||
if let Some(e) = cause::earlier(std::path::Path::new(video)) {
|
||||
cause::carried(&mut found, &e, fps);
|
||||
}
|
||||
let bad = found.iter().any(|f| f.level == Level::Error);
|
||||
if let Some(out) = out {
|
||||
let j = json!({"file": video, "fps": fps, "findings": found, "passed": passed});
|
||||
|
||||
+94
-27
@@ -101,30 +101,41 @@ pub(crate) fn x264_crf(head: &[u8]) -> Option<f64> {
|
||||
/// in its darks is the picture's own (8-bit glows and faint panels), which blotch_score can't always tell apart
|
||||
pub(crate) const X264_KEEPS: f64 = 16.0;
|
||||
|
||||
pub(crate) fn blotching(video: &str, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
/// How far a clean encode moves a sample's blotching (x264 crf 12 over the walkaround's unencoded frames, 11-19: at most 0.005)
|
||||
pub(crate) const BLOTCH_NOISE: f64 = 0.005;
|
||||
|
||||
/// Blotching's samples against the same frames of the composition drawn without encoding (raea-app-check-cause): None
|
||||
/// when the video isn't a render in a raea project's record
|
||||
fn blotching_cause(video: &str, probe: &Probe, scores: &[Option<f64>], w: usize, h: usize) -> Option<R<(cause::Against, Vec<Option<f64>>)>> {
|
||||
let (project, comp) = cause::composition_of(std::path::Path::new(video))?;
|
||||
Some((|| {
|
||||
if probe.fps <= 0.0 {
|
||||
return Err("the video doesn't say its frame rate".to_string());
|
||||
}
|
||||
let frames = cause::sampled(scores.len(), 2.0, probe.fps, (probe.picture * probe.fps).round() as i64 - 1);
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let before: Vec<Option<f64>> = cause::unencoded(&me, &project, &comp, &frames, w, h)?.iter().map(|y| blotch_score(y, w, h)).collect();
|
||||
Ok((cause::against(scores, &before, BLOTCHY, BLOTCH_NOISE), before))
|
||||
})())
|
||||
}
|
||||
|
||||
/// 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 frame = |buf: &[u8]| {
|
||||
if let Some(s) = blotch_score(buf, w, h) {
|
||||
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 scores: Vec<Option<f64>> = Vec::new();
|
||||
let mut frame = scorer(&mut scores, w, h);
|
||||
if crate::read::native() {
|
||||
crate::read::crops(video, w, h, &mut frame)?;
|
||||
} else {
|
||||
@@ -140,21 +151,77 @@ 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;
|
||||
issues.push(Issue {
|
||||
rule: "blotching",
|
||||
p: if share > 0.2 { 1 } else { 2 },
|
||||
at: Some(at),
|
||||
says: format!(
|
||||
"blocky patches in dark areas in {} of {seen} sampled frames (worst {:.0}% of dark blocks stepping); the encoder starved the near-blacks: export as PNG frames and encode with more bits for darks",
|
||||
bad.len(),
|
||||
worst * 100.0
|
||||
),
|
||||
});
|
||||
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) {
|
||||
// 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 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))
|
||||
}
|
||||
Some(Err(why)) => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
|
||||
None => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
|
||||
};
|
||||
issues.push(Issue { rule: "blotching", p, at, says });
|
||||
} 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
|
||||
/// behind are the half of the box least like the text.
|
||||
pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let (sx, sy) = (probe.w / w, probe.h / h);
|
||||
let mut low = 0;
|
||||
let mut measured = 0;
|
||||
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
|
||||
let [x, y, bw, bh] = r.box_;
|
||||
let crop = [(x * sx).max(0.0) as u32, (y * sy).max(0.0) as u32, (bw * sx) as u32, (bh * sy) as u32];
|
||||
if crop[0] + crop[2] > probe.w as u32 || crop[1] + crop[3] > probe.h as u32 {
|
||||
continue;
|
||||
}
|
||||
let t = (r.from + r.to) / 2.0;
|
||||
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
|
||||
let Some(ratio) = ratio else { continue };
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
low += 1;
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
|
||||
}
|
||||
}
|
||||
if measured > 0 && low == 0 {
|
||||
passed.push(format!("contrast: {measured} texts at 3:1 or better against their pixels"));
|
||||
}
|
||||
}
|
||||
+10
-12
@@ -162,17 +162,9 @@ pub(crate) fn bed_up(rms: &[f64], speak: &[bool]) -> Vec<(f64, String)> {
|
||||
/// The sound's rules on an export: dead stops always; with the voice's words, a stretch with no voice over it and a bed
|
||||
/// too close under it
|
||||
pub(crate) fn sound(video: &str, words: Option<&[Word]>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
let x = if crate::read::native() {
|
||||
crate::read::mono(video, SR as u32)?
|
||||
} else {
|
||||
let out = Command::new("ffmpeg").args(["-v", "error", "-i", video, "-vn", "-ac", "1", "-ar", &SR.to_string(), "-f", "f32le", "-"]).output().map_err(|e| format!("ffmpeg: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("ffmpeg couldn't read the sound of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));
|
||||
}
|
||||
out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
|
||||
};
|
||||
let x = crate::read::mono(video, SR as u32)?;
|
||||
let (rms, bands) = levels(&x);
|
||||
sound_defects(&x, issues, passed);
|
||||
sound_defects(&x, &crate::read::channels(video, SR as u32)?, issues, passed);
|
||||
let found = |list: Vec<(f64, String)>, p: u8| crate::defects::moments("sound", p, list);
|
||||
let stops = dead_stops(&rms, &bands);
|
||||
if stops.is_empty() {
|
||||
@@ -273,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 {
|
||||
@@ -284,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(())
|
||||
}
|
||||
+12
-4
@@ -356,15 +356,23 @@ fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
|
||||
fn clipping_is_found_and_a_loud_clean_tone_isnt() {
|
||||
// a clean tone near full scale, then the same tone clamped (a limiter's flat tops), then pushed past full scale
|
||||
let loud = tone(3.0, &[(0.0, 3.0, -1.0)]);
|
||||
assert!(clipped(&loud).is_empty(), "{:?}", clipped(&loud));
|
||||
let one = |x: &[f32]| clipped(&[x.to_vec()]);
|
||||
assert!(one(&loud).is_empty(), "{:?}", one(&loud));
|
||||
let clamped: Vec<f32> = loud.iter().map(|v| (v * 10.0).clamp(-0.3, 0.3)).collect();
|
||||
assert_eq!(clipped(&clamped).len(), 1);
|
||||
assert_eq!(one(&clamped).len(), 1);
|
||||
let over: Vec<f32> = loud.iter().map(|v| (v * 2.0).clamp(-1.0, 1.0)).collect();
|
||||
assert_eq!(clipped(&over).len(), 1);
|
||||
assert_eq!(one(&over).len(), 1);
|
||||
// one transient hitting full scale once isn't clipping
|
||||
let mut once = tone(3.0, &[(0.0, 3.0, -20.0)]);
|
||||
once[SR] = 1.0;
|
||||
assert!(clipped(&once).is_empty());
|
||||
assert!(one(&once).is_empty());
|
||||
// clipping is a channel's: one side clipped is found; a centred voice at -1.6 dBFS a side is clean, though the mono
|
||||
// fold (L + R) * 0.707 takes it past full scale (11-19: the walkaround's master read as clipping)
|
||||
assert_eq!(clipped(&[loud.clone(), over.clone()]).len(), 1);
|
||||
let centred: Vec<f32> = loud.iter().map(|v| v * 0.92).collect();
|
||||
assert!(clipped(&[centred.clone(), centred.clone()]).is_empty());
|
||||
let folded: Vec<f32> = centred.iter().map(|v| (v + v) * 0.7071).collect();
|
||||
assert_eq!(one(&folded).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "raea-app-check-text"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea check's text rules on a render's manifest: clipped, UI zones, reading time, face, cues, brand kit"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
serde_json = "1"
|
||||
# a transcript's words, read as `raea world` reads them (docs/direction.feature DR1)
|
||||
raea-core-facts = { path = "../../../core/facts" }
|
||||
@@ -1,25 +1,56 @@
|
||||
use super::*;
|
||||
//! What a render's text breaks, from its manifest alone: clipped, in the platform's UI zones, too brief to read, over
|
||||
//! the face, off its cue, and the brand kit it was styled from. raea check's text rules, split out of raea-app-check so
|
||||
//! `raea render --manifest` holds its own text to them as it finishes, a check's round sooner.
|
||||
use serde_json::Value;
|
||||
|
||||
pub type R<T> = Result<T, String>;
|
||||
|
||||
use raea_core_facts::{Finding, Level};
|
||||
|
||||
/// One thing a rule found: its rule, its rank (P0 breaks the piece to P3 polish), when (seconds) and what to do.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Issue {
|
||||
pub rule: &'static str,
|
||||
pub p: u8,
|
||||
pub at: Option<f64>,
|
||||
pub says: String,
|
||||
}
|
||||
|
||||
impl Issue {
|
||||
/// As a Finding `by` a command (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note), about the
|
||||
/// frame its second falls on at `fps`
|
||||
pub fn finding(&self, by: &str, fps: f64) -> Finding {
|
||||
let f = Finding::new(self.rule, Level::of_rank(self.p), &self.says, by);
|
||||
match self.at {
|
||||
Some(t) => {
|
||||
let n = (t * fps).round() as i64;
|
||||
f.frames(n, n + 1)
|
||||
}
|
||||
None => f,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A text as it stays on screen: from the frame it comes on to the frame it leaves. Typing (a text growing into the
|
||||
/// next) and counting (only its digits changing) are one run, judged by its last text.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Run {
|
||||
pub(crate) text: String,
|
||||
pub(crate) from: f64,
|
||||
pub(crate) to: f64,
|
||||
pub(crate) box_: [f64; 4],
|
||||
pub struct Run {
|
||||
pub text: String,
|
||||
pub from: f64,
|
||||
pub to: f64,
|
||||
pub box_: [f64; 4],
|
||||
/// where its letters are on every frame it shows its whole text (the manifest's `ink`, else its box: a centred line in
|
||||
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
|
||||
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
|
||||
pub(crate) boxes: Vec<[f64; 4]>,
|
||||
pub(crate) color: String,
|
||||
pub(crate) size: f64,
|
||||
pub boxes: Vec<[f64; 4]>,
|
||||
pub color: String,
|
||||
pub size: f64,
|
||||
}
|
||||
|
||||
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
|
||||
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, P1; a brand.css
|
||||
/// with no brand.json beside it wasn't read from the brand at all, P2
|
||||
pub(crate) fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for start in near.iter().filter(|p| !p.is_empty()) {
|
||||
let abs = dunce::canonicalize(&std::path::Path::new(start)).unwrap_or_else(|_| std::path::PathBuf::from(start));
|
||||
@@ -50,7 +81,7 @@ pub(crate) fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
pub fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
let fps = manifest["fps"].as_f64().unwrap_or(30.0);
|
||||
let frames = manifest["frames"].as_array().cloned().unwrap_or_default();
|
||||
let mut open: Vec<Run> = Vec::new();
|
||||
@@ -95,11 +126,11 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
}
|
||||
|
||||
/// The share of the face's area a text may cover before it's a fault (@raea/video's proofBoxes keeps the same 8%)
|
||||
pub(crate) const FACE_COVER: f64 = 0.08;
|
||||
pub const FACE_COVER: f64 = 0.08;
|
||||
|
||||
/// The face over time from a perception.json (`raea cut`: each clip's first frame, the face at its middle in the
|
||||
/// edit's px): [from, to) in seconds and the face's box, for the stretches that have one
|
||||
pub(crate) fn faces_of(perception: &Value, fps: f64) -> Vec<(f64, f64, [f64; 4])> {
|
||||
pub fn faces_of(perception: &Value, fps: f64) -> Vec<(f64, f64, [f64; 4])> {
|
||||
let mut keys: Vec<(f64, Option<[f64; 4]>)> = perception.as_object().into_iter().flatten().filter_map(|(k, v)| {
|
||||
let face = v["face"].as_object().map(|f| ["x", "y", "w", "h"].map(|n| f.get(n).and_then(Value::as_f64).unwrap_or(0.0)));
|
||||
Some((k.parse::<f64>().ok()? / fps, face))
|
||||
@@ -110,7 +141,7 @@ pub(crate) fn faces_of(perception: &Value, fps: f64) -> Vec<(f64, f64, [f64; 4])
|
||||
|
||||
/// Text over the face: a run that covers more than FACE_COVER of the face's area while that face is up, on every frame
|
||||
/// that shows it whole (a text the camera carries counts only when no frame shows it clear)
|
||||
pub(crate) fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let share = |b: &[f64; 4], f: &[f64; 4]| {
|
||||
let ox = (b[0] + b[2]).min(f[0] + f[2]) - b[0].max(f[0]);
|
||||
let oy = (b[1] + b[3]).min(f[1] + f[3]) - b[1].max(f[1]);
|
||||
@@ -134,7 +165,7 @@ pub(crate) fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &
|
||||
}
|
||||
|
||||
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/floor.md)
|
||||
pub(crate) fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
|
||||
pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
|
||||
let r = w / h;
|
||||
let shape = shape.unwrap_or(if r < 0.7 { "9:16" } else if r < 0.9 { "4:5" } else if r < 1.2 { "1:1" } else { "16:9" });
|
||||
let z = match (shape, platform) {
|
||||
@@ -153,12 +184,12 @@ pub(crate) fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>)
|
||||
/// A caption the voice reads out: every word of the text is said while it's on screen (from a little before it comes
|
||||
/// on). The viewer hears it as it shows, so it needs no reading time of its own (karaoke groups are up for as long as
|
||||
/// they take to say).
|
||||
pub(crate) fn spoken(r: &Run, words: &[Word]) -> bool {
|
||||
pub fn spoken(r: &Run, words: &[Word]) -> bool {
|
||||
let tokens: Vec<String> = r.text.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
|
||||
!tokens.is_empty() && tokens.iter().all(|t| words.iter().any(|w| norm(&w.text) == *t && w.start >= r.from - 0.3 && w.start <= r.to + 0.1))
|
||||
}
|
||||
|
||||
pub(crate) fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: Option<&str>, platform: Option<&str>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
pub fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: Option<&str>, platform: Option<&str>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let [zt, zr, zb, zl] = zones(w, h, shape, platform);
|
||||
let (mut clipped, mut unsafe_, mut brief) = (0, 0, 0);
|
||||
for r in runs {
|
||||
@@ -194,57 +225,30 @@ pub(crate) fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, s
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn quote(s: &str) -> String {
|
||||
pub fn quote(s: &str) -> String {
|
||||
let s: String = s.chars().take(40).collect();
|
||||
format!("\u{201c}{s}\u{201d}")
|
||||
}
|
||||
|
||||
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
|
||||
/// behind are the half of the box least like the text.
|
||||
pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let (sx, sy) = (probe.w / w, probe.h / h);
|
||||
let mut low = 0;
|
||||
let mut measured = 0;
|
||||
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
|
||||
let [x, y, bw, bh] = r.box_;
|
||||
let crop = [(x * sx).max(0.0) as u32, (y * sy).max(0.0) as u32, (bw * sx) as u32, (bh * sy) as u32];
|
||||
if crop[0] + crop[2] > probe.w as u32 || crop[1] + crop[3] > probe.h as u32 {
|
||||
continue;
|
||||
}
|
||||
let t = (r.from + r.to) / 2.0;
|
||||
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
|
||||
let Some(ratio) = ratio else { continue };
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
low += 1;
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
|
||||
}
|
||||
}
|
||||
if measured > 0 && low == 0 {
|
||||
passed.push(format!("contrast: {measured} texts at 3:1 or better against their pixels"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A transcript's word: its text, start and end in seconds (its end is its start when the transcript doesn't say).
|
||||
pub(crate) use raea_core_facts::Word;
|
||||
pub use raea_core_facts::Word;
|
||||
|
||||
/// A transcript's words (raea_core_facts::transcript_words: {text, start} in seconds, or t, start_ms, or {text, from}
|
||||
/// in frames at `fps`), as the app's words.json and `raea render --words` have them.
|
||||
pub(crate) fn transcript(path: &str, fps: f64) -> R<Vec<Word>> {
|
||||
pub fn transcript(path: &str, fps: f64) -> R<Vec<Word>> {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?).map_err(|e| format!("{path}: {e}"))?;
|
||||
v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
|
||||
Ok(raea_core_facts::transcript_words(&v, fps))
|
||||
}
|
||||
|
||||
pub(crate) use raea_core_facts::word_key as norm;
|
||||
pub use raea_core_facts::word_key as norm;
|
||||
|
||||
pub(crate) const SMALL: [&str; 24] = ["the", "and", "you", "your", "for", "with", "that", "this", "its", "it's", "are", "was", "our", "out", "from", "into", "then", "than", "but", "not", "all", "can", "has", "have"];
|
||||
pub const SMALL: [&str; 24] = ["the", "and", "you", "your", "for", "with", "that", "this", "its", "it's", "are", "was", "our", "out", "from", "into", "then", "than", "but", "not", "all", "can", "has", "have"];
|
||||
|
||||
/// Cues land on their words: a text whose words the voice says nearby comes on with the first of them, not after it.
|
||||
/// The text is found by its first word of weight, and then measured from the first word it shows: a caption "of the
|
||||
/// spend" comes on with "of", when the voice says "of the" just before "spend".
|
||||
pub(crate) fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let (mut checked, mut off) = (0, 0);
|
||||
for r in runs {
|
||||
let shown: Vec<String> = r.text.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
|
||||
@@ -19,6 +19,8 @@ serde_json = "1"
|
||||
# project's compositions
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
raea-app-check = { path = "../check" }
|
||||
# the check's text rules, held to a video render's manifest as it ends
|
||||
raea-app-check-text = { path = "../check/text" }
|
||||
raea-app-registry = { path = "../workspace/registry" }
|
||||
# the project's notes, whose asks' checks raea check runs beside its rules (DR6)
|
||||
raea-app-notes = { path = "../notes" }
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
if args.first().map(String::as_str) != Some("render") {
|
||||
return 0;
|
||||
}
|
||||
let found = finding::taken();
|
||||
let mut found = finding::taken();
|
||||
let through = despite(args, std::env::var("RAEA_DESPITE").ok());
|
||||
let excused: Vec<Despite> = through.iter().map(|(c, w)| Despite { check: c.clone(), why: w.clone() }).collect();
|
||||
let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
|
||||
@@ -46,6 +46,13 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
let manifest = raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?))));
|
||||
if let Some(m) = manifest {
|
||||
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
|
||||
// a video's text, held to the check's text rules as it finishes, a check's round sooner
|
||||
if out.as_deref().and_then(|o| o.extension()).is_some_and(|x| x == "mp4" || x == "mov") {
|
||||
for f in text_found(&v) {
|
||||
println!("{}", f.line());
|
||||
found.push(f);
|
||||
}
|
||||
}
|
||||
v["findings"] = json!(found);
|
||||
if !excused.is_empty() {
|
||||
v["despite"] = json!(excused);
|
||||
@@ -63,6 +70,26 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
code
|
||||
}
|
||||
|
||||
/// What a video render's text breaks, from its manifest (raea-app-check-text, the rules `raea check` holds it to): text
|
||||
/// off the frame is an error, as the check has it; text in a UI zone a warn, by the default zones, since the platform's
|
||||
/// are the check's to decide (`--platform`); reading time waits for the check, which has the transcript to tell a
|
||||
/// caption the voice reads out from one that has to be read.
|
||||
fn text_found(manifest: &Value) -> Vec<Finding> {
|
||||
let runs = raea_app_check_text::text_runs(manifest);
|
||||
let (w, h, fps) = (manifest["width"].as_f64().unwrap_or(1080.0), manifest["height"].as_f64().unwrap_or(1920.0), manifest["fps"].as_f64().unwrap_or(30.0));
|
||||
let (mut issues, mut passed) = (Vec::new(), Vec::new());
|
||||
raea_app_check_text::text_rules(&runs, None, w, h, None, None, &mut issues, &mut passed);
|
||||
let mut found = Vec::new();
|
||||
for mut i in issues.into_iter().filter(|i| i.rule != "reading") {
|
||||
if i.rule == "safe-area" {
|
||||
i.p = 2;
|
||||
i.says.push_str(" (by the default zones: `raea check --platform P` holds it to the platform's)");
|
||||
}
|
||||
found.push(i.finding("raea render", fps));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -71,6 +98,23 @@ mod tests {
|
||||
v.iter().map(|a| a.to_string()).collect()
|
||||
}
|
||||
|
||||
/// A video's text off the frame fails its render, as the check fails it; text in a UI zone is a warn by the
|
||||
/// default zones; a word on screen too briefly is left to the check, which has the transcript
|
||||
#[test]
|
||||
fn a_video_render_holds_its_text_to_the_check_s_rules() {
|
||||
let text = |t: &str, b: [f64; 4]| json!({"text": t, "box": b, "opacity": 1.0, "size": 60.0, "color": "rgb(255, 255, 255)"});
|
||||
let frames: Vec<Value> = (0..48).map(|f| json!({"frame": f, "videos": [], "text": [
|
||||
text("OFF THE EDGE", [900.0, 800.0, 400.0, 80.0]),
|
||||
text("Per month", [700.0, 1233.0, 318.0, 44.0]),
|
||||
if f < 3 { text("Two words", [200.0, 900.0, 300.0, 80.0]) } else { json!({"text": "", "box": [0, 0, 0, 0]}) },
|
||||
]})).collect();
|
||||
let found = text_found(&json!({"width": 1080, "height": 1920, "fps": 24, "frames": frames}));
|
||||
let got: Vec<(&str, Level)> = found.iter().map(|f| (f.check.as_str(), f.level)).collect();
|
||||
assert_eq!(got, vec![("clipped", Level::Error), ("safe-area", Level::Warn)], "{found:?}");
|
||||
assert!(found[1].says.contains("--platform"));
|
||||
assert_eq!(found[0].frames, Some([0, 1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_fails_the_render_unless_it_is_let_through_and_says_by_what() {
|
||||
let found = vec![Finding::new("clips", Level::Error, "rider in seat", "raea render"), Finding::new("tilted", Level::Warn, "vase leans", "raea render")];
|
||||
|
||||
@@ -32,6 +32,11 @@ pub const USAGE: &str = "raea export-game EDIT.tsx -o OUT [--target mac-app|mac-
|
||||
|
||||
/// `raea export-game EDIT.tsx -o OUT ...`
|
||||
pub fn export(args: &[String]) -> R<String> {
|
||||
// its targets are a Mac's, signed with codesign, and raea's Windows and Linux releases carry no game player: there
|
||||
// it said "no player ... (build it: cargo build ...)", which a person can't act on
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Err("raea export-game makes a Mac game (an .app or a command) and runs on a Mac; Windows and Linux games aren't there yet (sdk/react/docs/game-export.md)".into());
|
||||
}
|
||||
let usage = USAGE;
|
||||
let tsx = PathBuf::from(args.get(1).filter(|a| !a.starts_with("--")).ok_or(usage)?);
|
||||
let tsx = dunce::canonicalize(&tsx).map_err(|e| format!("{}: {e}", tsx.display()))?;
|
||||
|
||||
@@ -353,3 +353,14 @@ notes and is worth shipping without it: a person gets word scores, checks and bo
|
||||
5. **CLAP joins the stack** (Shane, 11-12: "include clap if we can if its not too much work"). It is about 300 lines
|
||||
of Rust on ort: the 48 kHz log-mel front end and the audio session (200), and the text tower with its tokenizer
|
||||
(100), run only when an axis's words change. Both are checked against the spike's vectors at cosine 0.999.
|
||||
6. **Pro and Studio include checks and content intelligence** (Shane, 11-20). Each month's pool (about 8,000 frames
|
||||
checked on Pro, ten times that on Studio) stops when it's spent and is never billed past. It pays for two things:
|
||||
- **clef-omni answering the fingerprint's questions** about a render's frames (`POST /v1/clef/ask`), so the agent
|
||||
reads answers in words and opens only the frames they flag. Its verdicts are another eye's (FP6d), and it serves
|
||||
the axes with no labels yet.
|
||||
- **content intelligence for references** (`GET /v1/intel/...`): public posts, videos, transcripts and ads, to find
|
||||
a videoform's references by what performs and keep them current (docs/videoform.md). A source's views and
|
||||
engagement are another eye's evidence too, never the person's taste. A reference found this way is still read
|
||||
once, as VF1 reads any link, and VF1's rights confirmation still applies.
|
||||
|
||||
Without a pool, everything here still works locally, and clef runs on the person's own Cloudflare account.
|
||||
@@ -54,8 +54,11 @@ By default the bitrate follows the size and frame rate: about 20 Mbit/s at 1080p
|
||||
`--quality` asks for constant quality: each frame gets the bits it needs, so a flat motion graphic stays small and a
|
||||
busy one stays clean.
|
||||
|
||||
Blotchy dark areas come from the encoder, not the composition. Export dark material as PNG frames and encode them
|
||||
with more bits for the darks:
|
||||
Blotchy dark areas come from the encoder, or from the footage itself: a phone's own compression shows in its darks.
|
||||
When `raea check` finds them on a render made in a raea project, it draws the composition again at the frames it
|
||||
sampled, without encoding, and tells the two apart. The picture's own is a note, since no render setting removes it.
|
||||
What the encode added is the error, and `--quality master` gives the darks the bits they need. To hand dark material on
|
||||
as frames instead, export PNG frames:
|
||||
|
||||
```sh
|
||||
RAEA_READBACK=rgba raea render piece.tsx -o frames/
|
||||
@@ -106,8 +109,14 @@ out of order, a phrase `word()` can't find, or a missing prop.
|
||||
|
||||
## Loudness
|
||||
|
||||
When the composition has a `<Mix>`, the export comes out at -14 LUFS integrated (within 1) with true peak at or below
|
||||
-1 dBTP, which is what the major platforms play back at.
|
||||
raea mixes and masters every render's sound. First the mix: each line of dialogue (a clip on the `voice` bus, or
|
||||
footage's own sound on no bus) is measured over the part of its take it plays and brought to the same level, so no line
|
||||
is louder or quieter than the next. Room tone and silent takes keep their level, and so do music, effects and anything
|
||||
on another bus, which sit under the dialogue as their buses set them. A clip's `gainDb` is an offset on top of the
|
||||
level. Then the master: a leveller rounds the loud passages, the whole piece comes up to its loudness, and a true-peak
|
||||
limiter holds it at the ceiling. A join that drops into dead silence gets the room's own tone. The export comes out at
|
||||
-14 LUFS integrated (within 1) with true peak at or below -1 dBTP, which is what the major platforms play back at;
|
||||
`<Mix lufs={…} ceiling={…}>` sets another target.
|
||||
|
||||
## Mistakes to avoid
|
||||
|
||||
|
||||
@@ -27,6 +27,13 @@ the platform's buttons, captions held too briefly and caption contrast. The tran
|
||||
word and music fighting the voice; the perception adds text over a face. A taste file adds the person's own rules,
|
||||
each an error when broken, since their rule beats the floor's default.
|
||||
|
||||
On a render made in a raea project, the check also uses the project's record. A finding an earlier export of the
|
||||
same composition had at the same moment ends `[also in …]`: the change between them didn't move it, so don't do that
|
||||
again; try something else, or say why it stands. A rule an encode can cause (blotching) is measured again on the
|
||||
composition drawn without encoding, so what the footage already holds is a note and only what the encode added is an
|
||||
error. A take or a download under the project's `assets/` or `media/` is a source, not a delivery: its loudness is
|
||||
reported as a note, since the mix sets the delivery's level.
|
||||
|
||||
## Every rule a project holds
|
||||
|
||||
On a project, or a composition's file, with no `--quick`, `raea check` runs every rule that applies to each
|
||||
|
||||
@@ -126,7 +126,7 @@ frame, on Windows too.
|
||||
Fedora 40 and later).
|
||||
- On Windows with Intel or AMD graphics, DirectX 12 compiles 3D shaders more slowly, so a 3D render can take
|
||||
about 15 seconds longer to start.
|
||||
- TokenSynth installs on Windows but hasn't been run end to end there yet, and it runs on the CPU there.
|
||||
- On Windows, TokenSynth runs on the CPU, so each note takes a minute or more to make.
|
||||
- A seek while a film plays in the timeline can show one frame from before the seek (about 33 ms) before it jumps.
|
||||
- A long 4K `raea render` can still hang before its first frame (#158).
|
||||
- Characters (the Character SDK) come in a later release.
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
@spec
|
||||
Feature: Videoform: the kind of video a person makes again and again, read once from their own finished videos, followed and checked on every cut
|
||||
The person, 2026-11-19: an agency or creator "making the same type of video over and over again can drop in a bunch
|
||||
of those videos, and raea codifies that style so the user can then drop a bucket of raw footage and raea with great
|
||||
accuracy and intent edits the raw footage into the exact style it has learned ... and it all needs to happen FAST".
|
||||
Then: the embedding route, on the models raea ships; "the point is to embed them, store the embeds, and be able to
|
||||
repeat the style without having to go back to the references themselves"; a videoform is "a kind of fingerprint,
|
||||
flowing into what has already been built". The plan, its decisions and why: docs/videoform.md.
|
||||
|
||||
The model this file sets:
|
||||
1. A videoform is a fingerprint (docs/fingerprint.feature FP14) with a `videoform` section: its context, its
|
||||
references, its vocabulary, its template and its rules. It's found, inherited, taught and shared as a
|
||||
fingerprint is.
|
||||
2. Each part flows into the part of raea that does that job already: its ranges into its profile (FP6e), its rules
|
||||
into the section's `rules`, each in a taste line's shape (words, a check, its values, a level; DR4, DR8), its
|
||||
structure into a NAME.script.ts template, its references into brief.ts's `references` shape.
|
||||
3. A reference is read once, from the local drive or streamed from a URL, and never needed again: its per-shot rows,
|
||||
its vocabulary's vectors, its ranges, its structure and its rules are all that following and checking read.
|
||||
4. What stays the same across the references is the videoform; what varies is content. A rule's strength is its
|
||||
consistency, and every videoform is tested leave one out.
|
||||
5. What ships runs on the models raea ships, on the person's machine. The domain vocabulary is written by the
|
||||
person's own AI. No paid model API is in the product.
|
||||
6. Checks start from the composition: a videoform's rules run in `raea check PROJECT` before any render, and
|
||||
embeddings only for shots that changed.
|
||||
|
||||
Start here (the order of work, and where it touches what exists):
|
||||
- The order: VF1 and VF2 (a reference in, a videoform made), VF3 (each reference read once into the kept rows), then
|
||||
VF4 with VF12 (the ranges, judged on the test bench). That pair is the gate: it passes on at least five of the
|
||||
person's sets before VF1b's platform pages or anything in VF9-VF11 is built.
|
||||
- New crates hold the work: raea-app-videoform (apps/videoform: ingest, rights, reading, the verbs, the bench),
|
||||
raea-sys-videoform (systems/videoform: the maths over kept rows) and raea-io-resolve (io/resolve, VF1b). The
|
||||
videoform section's types are core/brief's videoform.rs.
|
||||
- Three small hooks into what exists: fingerprint.ts's optional `videoform` field (systems/fingerprint taxonomy.rs,
|
||||
VF2), `raea context` printing a project's videoform (engine/cli guide.rs, VF2), and `raea check PROJECT` holding
|
||||
the rules of the fingerprint that judges the piece (apps/direction check.rs, VF8).
|
||||
- The bench (VF12) runs after every step, on every set, from the kept files alone; its numbers are the progress.
|
||||
|
||||
Background:
|
||||
Given the readers raea has: footage perception (systems/footage), Fingerprint's columns (systems/columns: SigLIP 2,
|
||||
CLAP, YAMNet, cached by content hash), Parakeet's words, Beat This!, HTDemucs and Silero VAD (systems/song), OCR,
|
||||
Depth Anything 3, and raea check's one decode of the picture (raea-app-check-read once.rs)
|
||||
And Fingerprint's fingerprint.ts (`about`, `extends`, `applies`, axes, encoder pins), its profiles (FP6e: ranges by
|
||||
measure name, critique, leave-one-out), `which` (FP14c) and evidence rows (FP2c)
|
||||
And taste lines' checks (raea's six forms, a check by name, a `.ts` check written with raea/check over the world;
|
||||
DR4), run by `raea check PROJECT`
|
||||
And the crate limits (a file at most 500 lines, a crate at most 2,000): raea-sys-fingerprint, -fingerprint-use and
|
||||
raea-app-fingerprint are each within 150 lines of theirs, so a videoform's code is its own crates, and the
|
||||
fingerprint crates grow only by a field and a map
|
||||
And the layers: a systems crate depends sideways only on a facility, so reading (which uses footage, columns and
|
||||
song) is apps' (raea-app-videoform), and the maths over kept rows is systems' (raea-sys-videoform)
|
||||
|
||||
Rule: VF1. Videos in: from the local drive, or streamed from a URL, read once
|
||||
|
||||
@needs:VF2
|
||||
Scenario: VF1. A reference from the drive or a URL, with nothing downloaded
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-videoform | apps/videoform/src/ingest.rs | 220 | paths, folders and URLs to sources: content hash, source URL, title, creator, date; a source read before is recognised and not read again |
|
||||
| raea-app-videoform | apps/videoform/src/rights.rs | 80 | the rights prompt, once per account, and its answer kept with the account |
|
||||
When the person runs `raea videoform add NAME PATH|URL...`
|
||||
Then a file or a folder on the drive is read where it is, with no copy made
|
||||
And a direct link to a media file is decoded straight from the network, and a platform page, a playlist or a
|
||||
channel (`--last N`) is resolved (VF1b) into stream URLs that are decoded the same way
|
||||
And nothing but the readings is written: no video file is kept, in a cache or anywhere else
|
||||
And each source is known by the content hash of its decoded picture and sound, beside its URL, title, creator
|
||||
and date, so adding it again reads nothing
|
||||
And before the first source from a URL, once per account, the person confirms they have the right to use what
|
||||
they add; raea says a videoform keeps measurements and vectors, never the video, and that a platform's terms
|
||||
are the person's to keep
|
||||
And a login-only or private link is refused with the site's reason, and streams are read at 1080p at most
|
||||
|
||||
@needs:VF1
|
||||
Scenario: VF1b. The resolver: yt-dlp, kept current by raea
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-io-resolve | io/resolve/src/lib.rs | 60 | a page URL to its videos' stream URLs and headers |
|
||||
| raea-io-resolve | io/resolve/src/fetch.rs | 220 | the standalone yt-dlp for this platform fetched into ~/.raea/bin, checked against the release's SHA-256 sums; the pinned version, the daily move forward, the one before kept |
|
||||
| raea-io-resolve | io/resolve/src/formats.rs | 140 | `yt-dlp -J` read: the best stream at 1080p or under, its URL and headers; a playlist's or channel's entries |
|
||||
Then yt-dlp (Unlicense) is used only to resolve, never to download, and is fetched on first use as FFmpeg is on
|
||||
Windows
|
||||
And each raea release pins the version it was tested with; between releases raea checks the latest at most once
|
||||
a day when a URL is added, checks it against its sums, and keeps the version before
|
||||
And when resolving fails with an extractor error, raea fetches the latest and tries once more; if the new one
|
||||
fails where the old one worked, it goes back and says which site failed
|
||||
And a site that needs JavaScript run (YouTube) gets a runtime raea ships or fetches, named to yt-dlp
|
||||
And `raea doctor` prints the yt-dlp in use, its date and the last site that failed
|
||||
|
||||
Rule: VF2. A videoform is a kind of fingerprint
|
||||
|
||||
Scenario: VF2. `videoform` in fingerprint.ts, and `raea videoform new`
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-core-brief | core/brief/src/videoform.rs | 140 | the videoform section's types (context, references, vocabulary, template, rules), with their TypeScript |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/taxonomy.rs | 20 | the optional `videoform` field on a fingerprint |
|
||||
| raea-app-videoform | apps/videoform/src/lib.rs | 120 | `raea videoform`: its usage, flags and the verbs' dispatch |
|
||||
| raea-app-videoform | apps/videoform/src/verbs.rs | 240 | new, add, report and refresh |
|
||||
When the person runs `raea videoform new NAME --context "…" [--extends FP] [--kinds K] [--tags T] [SOURCE...]`
|
||||
Then a fingerprint folder is made with a `videoform` section, `extends` the person's fingerprint by default, and
|
||||
`applies` from --kinds and --tags, where fingerprints are kept (the project's, the workspace's or the person's)
|
||||
And `raea fingerprint which PATH` finds it for a piece as it finds any fingerprint, and says why
|
||||
And `raea context` prints a project's videoform with its brief: its context, template, rules and ranges
|
||||
And its references use brief.ts's `references` shape, `{ target, note }`, the target the source's hash and URL
|
||||
|
||||
Rule: VF3. Each reference read once, into the rows a videoform keeps
|
||||
|
||||
@needs:VF1
|
||||
Scenario: VF3. One pass, every reader on its share
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-videoform | apps/videoform/src/pass.rs | 300 | one decode of a file or a stream: shot bounds from the same pass, each shot's frames held until it ends, each reader fed |
|
||||
| raea-app-videoform | apps/videoform/src/readers.rs | 260 | perception, columns, words, the voice's pauses, beats, stems, OCR and depth into per-shot rows |
|
||||
| raea-sys-videoform | systems/videoform/src/rows.rs | 160 | the kept rows: per shot its SigLIP 2 vector, its CLAP vector and its measures, f16, with the encoders' pins |
|
||||
Then each reference is decoded once, whether from the drive or a stream, and every reader takes its share
|
||||
And each shot gets its SigLIP 2 vector (a few frames pooled), its CLAP vector over its sound, and its measures:
|
||||
length, scale, camera move, caption boxes, light and colour, words, pauses at its edges, its place in the video
|
||||
And reading runs at about real time or faster, measured on the test sets
|
||||
|
||||
@needs:VF3
|
||||
Scenario: VF3b. What's kept is enough
|
||||
Then a videoform keeps its per-shot rows, its vocabulary's vectors, its profile, its structure and rules, a small
|
||||
still for each shot kind, and the person's evidence, and no reference video
|
||||
And ten one-minute references come to about 1.5 MB, small enough to load at once and keep in git
|
||||
And every test on the test sets (VF12) reads a set's references once, then runs on the kept files alone, with the
|
||||
references moved away, and passes the same
|
||||
|
||||
Rule: VF4-VF8. Writing the videoform from the kept rows
|
||||
|
||||
@needs:VF3
|
||||
Scenario: VF4. The ranges, in the videoform's profile
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/ranges.rs | 220 | the measures across the references: shot lengths, cuts a minute, pauses inside a line, between lines and between sections, words a minute, cuts against beats and sentence ends, music under voice, caption size, place and words at once, talking head against cutaway |
|
||||
| raea-sys-fingerprint-use | systems/fingerprint-use/src/profile.rs | 30 | a profile's measures beyond the fixed ones, by name, ranged and critiqued like the rest |
|
||||
Then the videoform's profile holds every measure's range across the references, leave one out as FP6e checks it
|
||||
And `raea fingerprint score --profile NAME` critiques a cut against the new measures as against the old
|
||||
And a measure whose range is wide is recorded as free, not as part of the videoform
|
||||
|
||||
@needs:VF2,VF3
|
||||
Scenario: VF5. The vocabulary, written by the person's AI
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/vocab.rs | 180 | vocabulary.ts's terms against the kept rows: never fires, fires everywhere, confused pairs, recurring shots no term names |
|
||||
When the person's AI writes vocabulary.ts from the context (places, things in them with several phrasings,
|
||||
near-misses, OCR patterns for text on screen, things to ignore)
|
||||
Then its terms become the videoform's word heads (FP2e), embedded once by the text towers
|
||||
And `raea videoform report NAME` says what each term did on the references, and the AI revises it from that
|
||||
|
||||
@needs:VF5
|
||||
Scenario: VF6. The shot vocabulary
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/kinds.rs | 220 | the reference shots clustered on vectors and measures; each cluster named from the vocabulary, its ranges and how many references have it |
|
||||
Then every reference shot belongs to a shot kind, named in the vocabulary's words, with its scale, move and length
|
||||
ranges and the share of references that have it
|
||||
|
||||
@needs:VF6
|
||||
Scenario: VF7. The structure, as a script template
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/structure.rs | 300 | the references aligned by their run of shot kinds and their script's meaning, into slots with their lengths and kinds; the template as NAME.script.ts |
|
||||
Then the videoform's slots (open, sections, close) each have a length range, their shot kinds and what's on screen
|
||||
And the template is a NAME.script.ts a project made to the videoform starts from, checked by `raea spec`
|
||||
|
||||
@needs:VF6,VF7
|
||||
Scenario: VF8. Rules, with their strength, in the videoform's rules
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/rules.rs | 240 | coverage, order and event rules from the kept rows, each with how strongly it holds; written into the section's `rules`, each a taste line with its check and values |
|
||||
| raea-app-direction | apps/direction/src/check.rs | 15 | tastes(): the rules of the fingerprint `which` names for the project, after the person's, the workspace's and the project's taste |
|
||||
Then a rule that holds in most references (a punch-in when a number is said; a close-up of the counters in every
|
||||
kitchen) is a line in the section's `rules`, with its strength and its check
|
||||
And `raea check PROJECT` holds a piece to the rules of the fingerprint that judges it (raea-sys-fingerprint-use
|
||||
`which`), beside the person's, the workspace's and the project's taste
|
||||
And the person confirms the strongest rules once, on a contact sheet of shot-kind stills, and each answer is
|
||||
evidence in the videoform
|
||||
|
||||
@needs:VF4,VF6
|
||||
Scenario: VF8b. When it doesn't hold together
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/groups.rs | 180 | too few references, references in groups, traits that vary, outliers |
|
||||
Then under five references every rule and range is weak, and nothing gates on it
|
||||
And references that fall into clear groups are reported, with a videoform offered for each, never averaged
|
||||
And one reference far from the others on several measures is named, for the person to keep or drop
|
||||
|
||||
@needs:VF3
|
||||
Scenario: VF8c. References added and removed; encoders upgraded
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/pins.rs | 100 | the encoders' pins on the kept rows; what carries over an upgrade and what waits for refresh |
|
||||
Then adding a reference reads only it and makes the videoform again from the kept rows, in seconds; removing one
|
||||
drops its rows; the person's evidence stays through both
|
||||
And a new encoder in raea leaves the videoform on its rows' pins, working as it was; the measures carry over; `raea
|
||||
videoform refresh NAME SOURCE...` reads the references again for the new encoder, the one time they're needed
|
||||
|
||||
Rule: VF9-VF11. Following it, and checking it fast
|
||||
|
||||
@needs:VF7,VF8
|
||||
Scenario: VF9. Following: the footage matched, what's missing said, the cut planned to the template
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-videoform | apps/videoform/src/follow.rs | 200 | new footage read and matched to shot kinds; what the footage lacks; the plan slot by slot |
|
||||
Then new raw footage is read as references are, and each shot matched to a shot kind against the kept rows
|
||||
And before any cut the agent says what the footage lacks ("no close-up of the counters, which every kitchen in the
|
||||
references has"), a shot list for the person
|
||||
And the agent plans the cut from the template, slot by slot, and edits to the ranges
|
||||
|
||||
@needs:VF8
|
||||
Scenario: VF10. A videoform's rules checked on the composition, before any render
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-videoform | apps/videoform/src/checks.rs | 220 | the videoform's checks by name over the world: order, slot lengths, coverage, shot lengths, pauses, caption places and sizes |
|
||||
| raea-app-direction | apps/direction/src/check.rs | 15 | the videoform's checks run with the project's rules |
|
||||
Then `raea check PROJECT` runs the videoform's rules with raea's floor and the person's taste, in milliseconds
|
||||
And each finding is routed as raea-app-check-cause routes any: a footage's own fault a note, a carried one said
|
||||
|
||||
@needs:VF6,VF10
|
||||
Scenario: VF11. Embedding checks, only for shots that changed
|
||||
Then each changed shot is held against its slot's shot kind, one SigLIP 2 frame a shot, and the run of shots
|
||||
against the structure
|
||||
And a shot that didn't change since the last check is not embedded again
|
||||
|
||||
Rule: VF12-VF13. Judged on the person's test sets
|
||||
|
||||
@needs:VF4
|
||||
Scenario: VF12. The test bench
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-videoform | apps/videoform/src/bench.rs | 200 | the person's sets as fixtures: leave one out, telling sets apart, edit to it, the verdicts kept |
|
||||
Given the person's sets, 8 to 10 videos each from one creator or one format, some with raw footage
|
||||
Then for each set, a videoform built from all but one reference holds the one left out (its rules pass, its
|
||||
measures in range) more often than other sets' videos do, and rejects other sets' videos
|
||||
And where raw footage for a held-out reference exists, the agent edits it to the videoform, set beside the original
|
||||
And the bench runs after every step of this file, on every set, from the kept files alone
|
||||
And the first proof that matters: on at least five sets, each videoform built leave one out holds its left-out
|
||||
video's pacing and shot lengths and rejects other sets' videos, more often than chance by a clear margin
|
||||
|
||||
@needs:VF12
|
||||
Scenario: VF13. The person's blind judging, kept as evidence
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-videoform | apps/videoform/src/judge.rs | 150 | a pair shown unlabelled in a random order; the pick, the scores and the words kept, and as evidence |
|
||||
Then the person sees the original and raea's edit side by side, unlabelled, in a random order, picks which they'd
|
||||
post, scores pacing, shot choice, structure, graphics, sound and overall feel from 1 to 5, and says what's wrong
|
||||
And each verdict is kept in the bench's record and is evidence in the videoform: a pick a pair (FP6b), a note a
|
||||
label (FP5)
|
||||
|
||||
Rule: Deferred
|
||||
Scenario: Not in this file yet
|
||||
Then an automatic judge for the test bench (a video-capable language model, paid by the person, in the bench only,
|
||||
never shipped: fidelity, pairs, and gaps between what the references show and what the videoform holds)
|
||||
And the order of the test sets
|
||||
@@ -0,0 +1,318 @@
|
||||
# Videoform: the plan
|
||||
|
||||
An agency or a creator makes the same kind of video again and again: a listing walkthrough, a recipe short, a podcast
|
||||
clip, a product unboxing. They give raea five to ten finished videos of that kind, from their own drive or by link, and
|
||||
a line of context ("real estate walkthroughs for agents' Reels"). raea reads them and writes down what makes them that
|
||||
kind of video: its **videoform**. From then on raea cuts new raw footage to it, and checks every pass against it,
|
||||
quickly.
|
||||
|
||||
This is the one plan for videoforms: what one is, how it flows into what raea already has (a videoform is a kind of
|
||||
fingerprint), how videos come in (from the local drive, or streamed from a URL with nothing downloaded), how each is
|
||||
read once into embeddings and measures that are all a videoform ever needs again, how it's followed and checked, how
|
||||
it holds up when references disagree or encoders change, how it's judged, and the build order with a confidence for
|
||||
each step. The rask tasks follow in `videoform.feature` once this plan is agreed.
|
||||
|
||||
## Why a videoform is read from approved work, not written from notes
|
||||
|
||||
A style written by hand from a person's corrections records only what went wrong once. What was right from the start
|
||||
is never said, so it's never written down. Pacing is the plainest case: if the first cut's voice was tight, nobody
|
||||
leaves a note about it, the written style never mentions it, and the next cut made from that style can be slack while
|
||||
satisfying every line of it. The approved videos already hold the answer, in numbers: how long the pauses are, how
|
||||
long the shots are, how fast the words come, where the cuts fall. A videoform read from them carries what was approved,
|
||||
not only what was corrected. Notes still matter. They teach what the numbers can't (DR6-DR8, FP5), on top of it.
|
||||
|
||||
## Decisions taken
|
||||
|
||||
- **The name is videoform.** The spec is `videoform` (raea/brief), and the command is `raea videoform`.
|
||||
- **A videoform is a kind of fingerprint,** flowing into what's built. It's a fingerprint (FP14) that `extends` the
|
||||
person's own and adds what a kind of video needs: its context, its references, its vocabulary, its structure and its
|
||||
rules. Everything Fingerprint already does applies to it: finding the one that applies, inheriting evidence, being
|
||||
taught by notes, being shared with a team and keeping its evidence when an encoder upgrades.
|
||||
- **What ships runs on shipped models, on the person's machine.** Reading, embedding, storing and building new videos
|
||||
from a videoform use only the models raea ships, plus at most one or two light additions. There are no paid language
|
||||
model APIs in the product.
|
||||
- **The domain vocabulary comes from the person's own AI.** The agent already in raea (Claude, Kimi, any of them) turns
|
||||
the context line into the things to look for. That adds no new bill and no shipped domain packs.
|
||||
- **What stays the same across the references is the videoform; what varies is the content.** A rule's strength is
|
||||
its consistency across the references. Every videoform is checked by building it from all references but one and
|
||||
testing it on the one left out.
|
||||
- **A reference is read once, and never needed again.** Its embeddings and measures are what the videoform keeps, and
|
||||
they're enough to follow it and check against it forever after. Following and checking never open a reference, so
|
||||
they stay fast, and the references can be deleted, offline or behind a dead link without the videoform noticing.
|
||||
- **Checks start from the composition.** Most of a videoform's rules are measured on what raea knows it put where,
|
||||
before any render. Embeddings run only on shots that changed.
|
||||
|
||||
## What raea already has, and what this builds on
|
||||
|
||||
| Already in raea | What it gives a videoform | Gap this plan fills |
|
||||
|---|---|---|
|
||||
| Fingerprint: `fingerprint.ts` with `about`, `extends`, `applies` kinds and tags; `which` finds one by project, workspace and account; a child inherits its parent's evidence, its own counted more; notes teach the one that judged (FP14a-e) | the home: a videoform is one of these | the fields a kind of video needs |
|
||||
| Fingerprint's frozen encoders (SigLIP 2, CLAP, YAMNet, EmbeddingGemma 2, Depth Anything 3), columns cached by content hash, word and learned heads, evidence in f16 rows (FP1-FP4) | the per-shot vectors and measures, and where they're kept | no shot vocabulary, no structure |
|
||||
| Fingerprint profiles: ranges from admired work, critique against them, a leave-one-out test (FP6e, `raea fingerprint profile`) | a videoform's ranges, and its validation | few measures (loudness, tilt, cut rate, motion, light, colour, sharpness) |
|
||||
| Notes become checks, and climb to project, workspace and taste (DR5-DR8, `raea notes keep`) | the path a correction takes to becoming a rule | a videoform's rules start from evidence, not notes |
|
||||
| `raea check`: findings and the record (DR3); who can fix what, carried findings, one decode (raea-app-check-cause, PR #205) | the check every pass runs | a videoform's rules join it as more rules |
|
||||
| `NAME.script.ts` (scenes, beats, lines, cut); `brief.ts` (`references`, `look`, `mode`, `deliver`) | a storyboard spec, and a brief that names references | no template made from references; references named, never read |
|
||||
| `taste.ts` lines: words, and a check that holds them (one of six forms, a check by name, or a `.ts` check on raea/check's world; DR4) | the person's, the workspace's and the project's standing lines, which `raea check PROJECT` and every agent hold work to | none written from references |
|
||||
| Footage perception (`systems/footage`: shots, cuts, camera, faces, words on screen, scene labels, performance, facts.json) | what each reference shot is | read for raw footage, not for references |
|
||||
| Transcription (Parakeet), beats, stems and voice activity (`raea song`, HTDemucs, Silero VAD), OCR | words, pauses, cuts against beats, music under voice, captions | not gathered into a videoform |
|
||||
| Index and libraries (SigLIP over a person's media; turbopuffer in the cloud) | finding footage by meaning; vector storage for teams | — |
|
||||
| video2raea sound, img2raea | reverse engineering a piece, with answer keys from our own films | — |
|
||||
| The video-decompiler skill (raea-skills): one admired film taken apart into a written dossier (`REFERENCE.md`), `vd pin` writing a film's numbers as targets | holding a piece to a reference, and measured targets | one reference, read by hand; product films made from code, not footage cuts |
|
||||
| raea's URL cache (`io/net`): a direct file URL fetched once into a cache | reading a media link | it saves the file; no platform pages, playlists or channels |
|
||||
|
||||
## A videoform is a kind of fingerprint
|
||||
|
||||
`fingerprint.ts` gains an optional `videoform` section. A fingerprint with one is a videoform. It's found by `which`
|
||||
like any other (its `applies` names the kinds and tags of piece it judges), it `extends` the person's fingerprint, so
|
||||
their general taste carries in, and it's kept and shared where fingerprints are (`.raea/fingerprints/NAME`, a
|
||||
project's, a workspace's or the person's own).
|
||||
|
||||
```
|
||||
.raea/fingerprints/listing-walkthrough/
|
||||
fingerprint.ts about, extends, applies, axes; and videoform: { context, references, vocabulary, template, rules }
|
||||
vocabulary.ts what to look for, written by the person's AI from the context
|
||||
profiles/ the videoform's ranges (FP6e's profile, measures added)
|
||||
read/ the references' per-shot rows, in the f16 format Fingerprint's evidence uses; the structure; the report
|
||||
evidence.jsonl as any fingerprint: the person's notes, picks and verdicts on pieces it judged
|
||||
```
|
||||
|
||||
Each part of a videoform flows into the part of raea that already does that job:
|
||||
|
||||
| A videoform's... | Flows into | So that |
|
||||
|---|---|---|
|
||||
| ranges (pace, pauses, shot lengths, loudness, colour, captions) | its own profile (FP6e) | `raea fingerprint score --profile` critiques a cut against them, and leave-one-out is already built |
|
||||
| the taste taught later | its own evidence and heads (FP2, FP14b-d) | a note on a piece it judged teaches it, never the person's general fingerprint unless they move it up |
|
||||
| rules (coverage, order, event rules, limits) | the section's `rules`, each in a taste line's shape (words, check, values, level) | `raea check PROJECT` runs them for a piece the videoform judges (`which`), beside the taste |
|
||||
| structure (slots, their order and lengths) | a `NAME.script.ts` template, which `videoform.template` names | a project made to the videoform starts from it, and agents plan from it as from any storyboard |
|
||||
| references | `brief.ts`'s existing `references` shape, `{ target, note }`, with the source kept by content hash | a reference is named the way a brief already names one |
|
||||
|
||||
`raea videoform new NAME --context "…" REF...` makes one, as `raea fingerprint new` does. `raea fingerprint which` on a
|
||||
piece names the videoform that judges it and why, and `raea context` prints it with the brief.
|
||||
|
||||
## Bringing videos in, with nothing downloaded
|
||||
|
||||
- **From the local drive.** A file or a folder (`raea videoform add NAME ~/Videos/listings/`), or a library's files, is
|
||||
read where it is. No copy is made.
|
||||
- **From a URL, streamed.** `raea videoform add NAME URL...` reads the video over the network in one pass and keeps only
|
||||
what was measured:
|
||||
- **A direct link to a file** (an `.mp4` on a server, S3, a share link that serves the file) is decoded straight from
|
||||
the network.
|
||||
- **A platform page** (YouTube, TikTok, Instagram, Vimeo, X), a playlist or a creator's channel with `--last N`
|
||||
isn't a video file: it's a page with a player, and the video sits behind it as short-lived, signed stream URLs,
|
||||
often in segments. A resolver (yt-dlp, Unlicense, fetched on first use as raea fetches FFmpeg on Windows) turns
|
||||
the page into those stream URLs, and raea streams them. Nothing is written to disk.
|
||||
- **One pass.** A streamed video can't be sought cheaply, so every reader takes its share of the one decode, as raea
|
||||
check's picture rules now do. Shot bounds come from the same pass, and the per-shot reads hold a shot's frames until
|
||||
it ends.
|
||||
- **What's kept.** Each video's readings (below), by content hash of the decoded stream, with its source URL, title,
|
||||
creator and date. The video itself is not kept. A video already read is recognised by its hash and never read twice.
|
||||
- **Rights.** Once per account, before the first reference is read from a URL, raea asks the person to confirm they have
|
||||
the right to use what they add (their own work, a client's, or licensed), says that a videoform keeps measurements and
|
||||
vectors and never the video, and that a platform's terms are theirs to keep. The answer is kept with the account.
|
||||
- **Limits.** Login-only and private links are refused, with the reason given. Streams are read at 1080p at most;
|
||||
reading never needs more.
|
||||
|
||||
## The resolver, and keeping it current
|
||||
|
||||
A platform page is resolved by **yt-dlp** (Unlicense): the most widely used and most actively kept page resolver, with
|
||||
extractors for over a thousand sites and releases every week or two. raea uses it only to resolve, never to download:
|
||||
`yt-dlp -J URL` (a playlist or channel: `--flat-playlist`, `--playlist-end N`) gives each video's formats as JSON, with
|
||||
their stream URLs and the headers they need, and raea picks the best stream at 1080p or under and decodes it itself.
|
||||
|
||||
Sites change their pages often, and an old resolver stops working within weeks, so it's kept current by raea, not by
|
||||
the person:
|
||||
- **Fetched, not installed.** The official standalone binary for the platform (`yt-dlp_macos`, `yt-dlp_linux`,
|
||||
`yt-dlp.exe`) is fetched on first use into `~/.raea/bin`, as raea fetches FFmpeg on Windows, and checked against the
|
||||
release's published SHA-256 sums before it runs.
|
||||
- **Pinned, then moved forward.** Each raea release pins the yt-dlp version it was tested with. Between raea releases,
|
||||
raea checks yt-dlp's latest release at most once a day when a URL is added, fetches it, checks its sums, and keeps the
|
||||
one before it.
|
||||
- **Updated when a site breaks.** When resolving fails with an extractor error, raea fetches the latest release and
|
||||
tries once more. If the new one fails where the old one worked, it goes back to the old one and says which site
|
||||
failed.
|
||||
- **Said, not hidden.** `raea doctor` prints the yt-dlp in use, its date, and the last site that failed. A link that
|
||||
can't be resolved is refused with the site's reason, and the person can add the file from their drive instead.
|
||||
- **Its needs.** Some sites' pages (YouTube's) make yt-dlp run JavaScript, for which it uses a JavaScript runtime on the
|
||||
machine. raea gives it one: yt-dlp is pointed at a runtime raea ships or fetches, and the bench checks it against
|
||||
each site raea names as supported.
|
||||
- **Tested.** The test bench resolves one public video from each supported site each night, so a broken site is known
|
||||
before a person finds it.
|
||||
|
||||
## Reading a reference
|
||||
|
||||
Each video is read into rows by what raea already runs:
|
||||
- footage perception: shots, cuts, camera, faces, words on screen, scene labels;
|
||||
- Fingerprint's columns: SigLIP 2 per shot, CLAP and YAMNet over the sound;
|
||||
- Parakeet's words, and the voice's pauses;
|
||||
- beats and stems;
|
||||
- OCR's caption boxes;
|
||||
- depth, for shot scale.
|
||||
|
||||
All of it is keyed by content hash, as Fingerprint's columns are, so a reference read for one videoform serves every
|
||||
videoform that uses it.
|
||||
|
||||
## What a videoform keeps, and why it's enough
|
||||
|
||||
Following and checking need four kinds of thing from the references, and a videoform keeps exactly those:
|
||||
|
||||
| Kept | What it is | What uses it |
|
||||
|---|---|---|
|
||||
| per-shot rows | each reference shot's SigLIP 2 vector (one pooled vector, a few frames averaged), its CLAP vector over the shot's sound, and its measures (length, scale, camera move, caption boxes, light and colour, words, pauses at its edges, its place in the video) | the shot vocabulary; matching new footage to shot kinds; the embedding checks |
|
||||
| the vocabulary's vectors | each term's phrasings through the text towers, as word heads store them (FP2e) | naming shot kinds; finding domain things in new footage |
|
||||
| the profile | the ranges of every measure across the references (FP6e) | the critique, and composition-first range checks |
|
||||
| the structure and the rules | the slots with their lengths and shot kinds; the event and coverage rules with their strength | the template, and the rules `raea check` runs |
|
||||
|
||||
Also kept: one small still for each shot kind (a thumbnail, a few kilobytes), so the person can see what a kind is when
|
||||
confirming rules, and the evidence the person adds over time. The reference videos aren't kept.
|
||||
|
||||
**Sizes.** A videoform of ten one-minute references, about 50 shots each, keeps about 500 per-shot rows of about 3 KB
|
||||
each (SigLIP 2's 768 values and CLAP's 512, in f16, with the measures): about 1.5 MB with its profile, structure, rules
|
||||
and stills. That's small enough to load at once, keep in git with the project, and share with a team.
|
||||
|
||||
**Times, measured and held to.** Reading a reference is once only, at about real time or faster: one decode, every
|
||||
reader on its share of it. Making the videoform's ranges, shot vocabulary, structure and rules from its rows takes
|
||||
seconds. Following and checking read only what's kept: the composition-first checks in milliseconds, matching a new
|
||||
shot to its kind in well under a millisecond against ~500 rows, and one SigLIP frame for each changed shot.
|
||||
|
||||
## When it doesn't hold together
|
||||
|
||||
- **Too few references.** Under five, every rule and range is reported as weak, and nothing gates on it. Leave one out
|
||||
needs at least five to mean anything.
|
||||
- **References that aren't one kind of video.** If the references fall into two or more clear groups (by structure, by
|
||||
shot kinds, by pace), raea says so and offers a videoform for each, rather than averaging them into one that fits
|
||||
none.
|
||||
- **A trait that varies.** A measure whose range across the references is wide, or a rule that holds in few of them, is
|
||||
a free choice, not part of the videoform. It's recorded as free, so the agent knows it may decide.
|
||||
- **An outlier.** One reference far from the others on several measures is named ("number 7 runs twice as fast as the
|
||||
rest"), and the person decides whether it belongs.
|
||||
|
||||
## Adding and removing references
|
||||
|
||||
Adding a reference reads only the new one, then makes the ranges, shot vocabulary, structure and rules again from the
|
||||
kept rows, in seconds. Removing one drops its rows, and the same. The person's evidence (their notes, picks and
|
||||
verdicts) stays through both, as a fingerprint's does.
|
||||
|
||||
## When an encoder changes
|
||||
|
||||
A videoform records the encoders its rows came from (their pins, as `fingerprint.ts` does). A raea that ships a new
|
||||
encoder keeps using the videoform's rows with the old encoder's pin, for matching and checking against it. The measures
|
||||
(lengths, pauses, captions, light) don't depend on an encoder and carry over as they are. To move a videoform to the new
|
||||
encoder, its references are read again (`raea videoform refresh NAME`, given the files or links). Until then it keeps
|
||||
working as it was. This is the one time a reference is needed again, and it's the person's choice.
|
||||
|
||||
## Writing the videoform
|
||||
|
||||
1. **The vocabulary.** The person's AI expands the context line into `vocabulary.ts`:
|
||||
- places, then the things in each place, each with several phrasings;
|
||||
- near-misses (a kitchen against a dining room);
|
||||
- OCR patterns for text on screen (prices, addresses);
|
||||
- things to ignore.
|
||||
|
||||
These become the videoform's word heads (FP2e), scored by SigLIP's and CLAP's text towers. raea reports what each
|
||||
did on the references: never fires, fires everywhere, confused with another, or a recurring shot no term names. The
|
||||
AI revises the vocabulary, and two or three rounds is usually enough.
|
||||
2. **The ranges,** across the references, into the videoform's profile:
|
||||
- shot lengths, and cuts a minute;
|
||||
- the voice's pauses: inside a line, between lines, between sections;
|
||||
- words a minute, and cuts against beats and sentence ends;
|
||||
- loudness, and music under voice;
|
||||
- caption size, place and words on screen at once;
|
||||
- colour and grade;
|
||||
- talking head against cutaway.
|
||||
3. **The shot vocabulary.** Every reference shot is clustered on its vectors and measures. Each cluster gets its terms
|
||||
from the vocabulary, its measured ranges (scale, move, length) and how many references have it.
|
||||
4. **The structure.** The references are aligned by their run of shot kinds and their script's meaning, into slots
|
||||
(open, sections, close), each with its length range, its shot kinds and what's on screen. This becomes the script
|
||||
template.
|
||||
5. **The event rules.** How often one thing comes with another across the references ("a punch-in when a number is
|
||||
said", "a close-up of the counters in every kitchen"). Those that hold in most references become the videoform's
|
||||
rules, each stating how strongly it holds.
|
||||
6. **The person confirms the strongest rules once,** on a contact sheet ("countertop close-up in every kitchen: 9 of
|
||||
10"). Each yes or no is evidence in the videoform, as any label is in a fingerprint.
|
||||
|
||||
## Following it
|
||||
|
||||
- `raea context` prints the videoform: its template, its rules and its ranges.
|
||||
- New raw footage is read the same way, and each shot is matched to the videoform's shot kinds.
|
||||
- Before any cut, the agent is told what the footage lacks: "no close-up of the counters, which every kitchen in the
|
||||
references has". That's a shot list for the person.
|
||||
- The agent plans the cut to the template, slot by slot, and edits to the ranges (cut points, pauses, shot lengths).
|
||||
|
||||
## Checking it, fast
|
||||
|
||||
1. **On the composition, before any render, in milliseconds:**
|
||||
- order and slot lengths;
|
||||
- coverage;
|
||||
- shot lengths and pauses (the voice's cut points are in the composition);
|
||||
- caption places and sizes.
|
||||
|
||||
These are the videoform's rules, run by `raea check PROJECT` with the taste.
|
||||
2. **On the render manifest and measures, in seconds:** loudness, light and colour against the profile (`raea
|
||||
fingerprint score --profile`).
|
||||
3. **On embeddings, only for shots that changed:** each shot against its slot's shot kind (one SigLIP frame a shot);
|
||||
the run of shots against the structure.
|
||||
|
||||
The routing from raea-app-check-cause (PR #205) applies unchanged: the footage's own faults are notes, carried findings
|
||||
say so, and a round goes only to what another render can change.
|
||||
|
||||
## Judging
|
||||
|
||||
Judging is for testing the build, set by set. The person's verdict is the judge; a second, automatic judge for the
|
||||
test bench is deferred (see the end).
|
||||
|
||||
**The person's judgement (the one that decides).** For each test, raea shows the original and its own edit side by side,
|
||||
unlabelled, in a random order (a feed artifact, or `raea show --question`). The person:
|
||||
- picks which they'd post;
|
||||
- scores pacing, shot choice, structure, graphics, sound and overall feel, 1 to 5;
|
||||
- writes what's wrong in their own words.
|
||||
|
||||
Each verdict is kept in the test bench's record, and is also evidence in the videoform (a pick is a pair, FP6b; a note
|
||||
is a label, FP5). The judging trains the videoform as well as grading it.
|
||||
|
||||
## The test sets
|
||||
|
||||
The person provides the sets: 8 to 10 videos each, from one creator or one format, with raw footage for a few where it
|
||||
exists. Every test reads a set's references once, then runs only on what the videoform kept, so the tests also prove
|
||||
that a videoform is enough without its references. For each set:
|
||||
- **Leave one out:** a videoform built from all but one reference must hold the one left out (its rules pass, its
|
||||
measures fall in range) more often than other sets' videos do.
|
||||
- **Tells sets apart:** each videoform must reject other sets' videos. This is profile FP6e's test, extended to rules
|
||||
and structure.
|
||||
- **Edit to it:** where raw footage for a held-out reference exists, the agent edits it to the videoform, and the cut is
|
||||
set beside the original.
|
||||
- **Judged:** by the person, as above.
|
||||
|
||||
The sets, their answers and their verdicts are kept as fixtures, so each step of the build is measured on all of them.
|
||||
|
||||
## Build order, with confidence
|
||||
|
||||
| Phase | Step | What | Confidence | Why |
|
||||
|---|---|---|---|---|
|
||||
| 1, in | VF1 | ingest from the local drive, and streamed from direct links, platform pages, playlists and channels; read once, nothing kept but the readings; the rights prompt, once per account | high, medium for platform pages |
|
||||
| | VF1b | the resolver: yt-dlp fetched and checked against its sums, pinned per release, moved forward daily, updated and retried when a site breaks, rolled back when the new one is worse, a nightly site check | high to build, medium to keep | the sites change; the update loop is what keeps it working | decoding over the network is standard; platform pages depend on the resolver keeping up with the sites |
|
||||
| | VF2 | `videoform` in `fingerprint.ts`, found, inherited and taught as a fingerprint; `raea videoform new` and `add` | high | FP14's machinery exists |
|
||||
| | VF3 | reading references in one pass: perception, columns, words, pauses, beats, stems, OCR, depth, into the kept rows | high | every reader exists; one decode is already done for raea check |
|
||||
| | VF3b | what a videoform keeps, its sizes and times, and the proof that following and checking never open a reference | high | the rows are Fingerprint's format; the test sets prove it |
|
||||
| 2, read | VF4 | ranges into the videoform's profile, measures added (pauses, words a minute, shot lengths, captions, cuts against beats) | high | FP6e computes ranges and leave-one-out already |
|
||||
| | VF5 | the vocabulary loop with the person's AI, as word heads | medium-high | word heads already score from text; the report is new |
|
||||
| | VF6 | the shot vocabulary (clusters named from the vocabulary) | medium | clustering is plain; naming quality varies by domain |
|
||||
| | VF7 | the structure template | medium | alignment across varied videos is the hard part |
|
||||
| | VF8 | event rules into the videoform's rules, with strength, confirmed by the person; `raea check` holds them | medium | co-occurrence is plain; telling habit from style needs the person |
|
||||
| | VF8b | when it doesn't hold together: too few, mixed kinds (split into videoforms), traits that vary, outliers | medium-high | groups and spreads come from the kept rows |
|
||||
| | VF8c | adding and removing references from kept rows; encoder pins and `refresh` | high | Fingerprint keeps evidence across upgrades the same way (FP8c) |
|
||||
| 3, use | VF9 | following: context, coverage gaps, planning to the template | medium-high | context and scripts exist |
|
||||
| | VF10 | composition-first checks for the videoform's rules | high | rules as `.ts` checks over the world exist (DR4) |
|
||||
| | VF11 | embedding checks on changed shots | medium | per-shot SigLIP is cheap; thresholds need the test sets |
|
||||
| 4, judge | VF12 | the test bench: the sets as fixtures, leave-one-out and telling sets apart, run after every step | high | the measures are defined above |
|
||||
| | VF13 | the person's blind judging, kept as evidence | high to build | an artifact and the evidence rows exist |
|
||||
|
||||
**The first proof that matters is VF4 with VF12.** On at least five of the person's sets, each videoform, built leave
|
||||
one out, holds its left-out video's pacing and shot lengths, and rejects other sets' videos, more often than chance by
|
||||
a clear margin. If the numbers alone can't tell videoforms apart, nothing built above them will.
|
||||
|
||||
## Deferred
|
||||
|
||||
- **An automatic judge for the test bench:** a video-capable language model, paid for by the person, in the bench only
|
||||
(never shipped), answering fidelity, pairs and gaps (what the references show that the videoform doesn't hold),
|
||||
calibrated against the person's verdicts.
|
||||
- **The order of the test sets.**
|
||||
+43
-2
@@ -4,10 +4,33 @@
|
||||
pub mod sdk;
|
||||
pub mod shared;
|
||||
|
||||
/// What a folder takes on disk, as `du -sh` says it (`links`: through a link to its files), or "?".
|
||||
/// What a folder takes on disk, as `du -sh` says it (`links`: through a link to its files). Windows has no du (raea
|
||||
/// setup-audio said "(?)" for every model there): its files' sizes are added up instead, in du's units.
|
||||
pub fn disk_use(dir: &std::path::Path, links: bool) -> String {
|
||||
let o = std::process::Command::new("du").arg(if links { "-shL" } else { "-sh" }).arg(dir).output();
|
||||
o.ok().and_then(|o| String::from_utf8_lossy(&o.stdout).split_whitespace().next().map(str::to_string)).unwrap_or_else(|| "?".into())
|
||||
o.ok().and_then(|o| String::from_utf8_lossy(&o.stdout).split_whitespace().next().map(str::to_string)).unwrap_or_else(|| du_units(bytes_in(dir, links, 0)))
|
||||
}
|
||||
|
||||
/// The bytes of the files under `p` (through links when `links`, 64 folders deep at most, so a link's loop ends).
|
||||
fn bytes_in(p: &std::path::Path, links: bool, depth: u32) -> u64 {
|
||||
let md = if links { std::fs::metadata(p) } else { std::fs::symlink_metadata(p) };
|
||||
match md {
|
||||
Ok(m) if m.is_dir() && depth < 64 => std::fs::read_dir(p).map(|d| d.flatten().map(|e| bytes_in(&e.path(), links, depth + 1)).sum()).unwrap_or(0),
|
||||
Ok(m) if m.is_file() => m.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` bytes as `du -h` writes them: 1024s, one decimal under 10 ("1.9G", "512M", "0B").
|
||||
fn du_units(n: u64) -> String {
|
||||
let mut v = n as f64;
|
||||
let mut unit = 0;
|
||||
while v >= 1024.0 && unit < 4 {
|
||||
v /= 1024.0;
|
||||
unit += 1;
|
||||
}
|
||||
let u = ["B", "K", "M", "G", "T"][unit];
|
||||
if unit == 0 { format!("{n}B") } else if v < 10.0 { format!("{v:.1}{u}") } else { format!("{v:.0}{u}") }
|
||||
}
|
||||
|
||||
/// Where raea's own files are (the SDK's TypeScript, the lite runtime and its packages, the shell's sources, the
|
||||
@@ -173,6 +196,24 @@ pub fn from_url_path_on(s: &str, windows: bool) -> &str {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_folder_is_sized_without_du() {
|
||||
assert_eq!(super::du_units(0), "0B");
|
||||
assert_eq!(super::du_units(1023), "1023B");
|
||||
assert_eq!(super::du_units(1536), "1.5K");
|
||||
assert_eq!(super::du_units(512 << 20), "512M");
|
||||
assert_eq!(super::du_units((19 << 30) / 10), "1.9G");
|
||||
let d = std::env::temp_dir().join(format!("raea-du-{}", std::process::id()));
|
||||
std::fs::create_dir_all(d.join("a/b")).unwrap();
|
||||
std::fs::write(d.join("x"), vec![0u8; 1000]).unwrap();
|
||||
std::fs::write(d.join("a/b/y"), vec![0u8; 2500]).unwrap();
|
||||
assert_eq!(super::bytes_in(&d, false, 0), 3500);
|
||||
assert_eq!(super::bytes_in(&d, true, 0), 3500);
|
||||
assert_eq!(super::bytes_in(&d.join("none"), false, 0), 0);
|
||||
assert_ne!(super::disk_use(&d, false), "?");
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_src_is_a_file_url_on_windows() {
|
||||
assert_eq!(super::src_on("/Users/a/assets/m.png", false), "/Users/a/assets/m.png");
|
||||
|
||||
@@ -188,6 +188,8 @@ fn push_sound(cx: &mut Ctx, props: &Map<String, Value>, skey: &str) {
|
||||
// a sound track with samples: a short window says so (decoding the whole take for it held a long take whole)
|
||||
let audible = *cx.audible.entry(file.clone()).or_insert_with(|| raea_io_media::decode_audio_window(&file, 0.0, 0.05).is_ok_and(|a| a.len() > 0));
|
||||
if !muted && volume > 0.0 && audible {
|
||||
// raea's mix: dialogue at one level, gainDb an offset on it (raea-sys-mix level.rs), as live play has it
|
||||
let volume = volume * raea_sys_mix::level::gain(&file, num(props, "data-clip-from").unwrap_or(0.0), num(props, "data-clip-to"), props.get("data-bus").and_then(|v| v.as_str())) as f64;
|
||||
cx.sounds.push(Sound { src: file.display().to_string(), at, volume, rate: num(props, "data-playback-rate").unwrap_or(1.0), key: skey.to_string(), fade_in: num(props, "data-fade-in"), fade_out: num(props, "data-fade-out"), bus: props.get("data-bus").and_then(|v| v.as_str()).map(str::to_string) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,15 +150,35 @@ fn with_exposure(said: String, out: &Path, manifest: Option<&Path>) -> String {
|
||||
return said;
|
||||
}
|
||||
match raea_sys_light_meter::exposure::of_pngs(&pngs) {
|
||||
Ok((e, v)) => {
|
||||
let fs = raea_sys_light_meter::exposure::said(&v); // counted with the render's other findings (DR3)
|
||||
if let Some(m) = manifest {
|
||||
if let Ok(mut doc) = std::fs::read_to_string(m).map_err(|e| e.to_string()).and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(|e| e.to_string())) {
|
||||
if let Some(o) = doc.as_object_mut() {
|
||||
o.insert("exposure".into(), v.clone());
|
||||
let _ = std::fs::write(m, doc.to_string());
|
||||
Ok((e, mut v)) => {
|
||||
// a frame of the page's own fill (no 3D, no footage: a brand card's ground) is lit by design, so the 3D lighting
|
||||
// advice is measured, not said; a frame with footage keeps it (a clip that drew black). 11-19: a logo card's warn
|
||||
let doc: Option<serde_json::Value> = manifest.and_then(|m| std::fs::read_to_string(m).ok()).and_then(|t| serde_json::from_str(&t).ok());
|
||||
if let Some(d) = doc.as_ref().filter(|d| d["has3d"] == false) {
|
||||
let frames = d["frames"].as_array().cloned().unwrap_or_default();
|
||||
fn fill(f: &serde_json::Value) -> bool {
|
||||
f["videos"].as_array().is_none_or(Vec::is_empty)
|
||||
}
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
if pngs.len() == 1 && frames.len() == 1 && fill(&frames[0]) {
|
||||
names.push("the frame".into());
|
||||
} else if pngs.len() == frames.len() {
|
||||
for (p, f) in pngs.iter().zip(&frames) {
|
||||
if let (true, Some(n)) = (fill(f), p.file_name()) {
|
||||
names.push(n.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(found) = v["found"].as_array_mut() {
|
||||
found.retain(|f| !names.iter().any(|n| f["says"].as_str().is_some_and(|s| s.starts_with(&format!("{n}:")))));
|
||||
}
|
||||
}
|
||||
let fs = raea_sys_light_meter::exposure::said(&v); // counted with the render's other findings (DR3)
|
||||
if let (Some(m), Some(mut doc)) = (manifest, doc)
|
||||
&& let Some(o) = doc.as_object_mut()
|
||||
{
|
||||
o.insert("exposure".into(), v.clone());
|
||||
let _ = std::fs::write(m, doc.to_string());
|
||||
}
|
||||
let mut msg = format!("{said}\nEXPOSURE {}", e.line());
|
||||
for f in &fs {
|
||||
|
||||
@@ -84,11 +84,13 @@ pub fn sounds_into<'a>(items: impl IntoIterator<Item = (&'a str, Option<&'a Map<
|
||||
continue;
|
||||
}
|
||||
let (key, bus) = SOUND_NAMES.with_borrow_mut(|n| (n.key(node, &file), props.get("data-bus").and_then(|v| v.as_str()).map(|b| n.bus(b))));
|
||||
// raea's mix: dialogue at one level, gainDb an offset on it (raea-sys-mix level.rs)
|
||||
let level = raea_sys_mix::level::gain(&file, num(props, "data-clip-from").unwrap_or(0.0), num(props, "data-clip-to"), props.get("data-bus").and_then(|v| v.as_str()));
|
||||
out.push(Sound {
|
||||
key,
|
||||
file,
|
||||
at,
|
||||
volume: volume as f32,
|
||||
volume: volume as f32 * level,
|
||||
rate: num(props, "data-playback-rate").unwrap_or(1.0),
|
||||
fade_in: num(props, "data-fade-in").unwrap_or(0.0),
|
||||
fade_out: num(props, "data-fade-out").unwrap_or(0.0),
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
`raea check out/launch-9x16.mp4 --manifest out/render.json --shape 9:16 --platform tiktok`.
|
||||
- Captions: burn them in for feeds that play without sound, unless the delivery controller says captions off; then
|
||||
burn none, and leave the words file beside the export for the platform's own captions.
|
||||
- Sound to -14 LUFS integrated with true peak at or below -1 dBTP: one `<Mix lufs={-14} ceiling={-1.5} />` per
|
||||
composition does it (`motion/sound`). A spec that names another number wins.
|
||||
- Sound to -14 LUFS integrated with true peak at or below -1 dBTP: raea's mix and master do it on every render
|
||||
(`motion/sound`). A spec that names another number wins: `<Mix lufs={…} ceiling={…} />` sets it.
|
||||
- Render the export at `--quality master` (motion graphics and type) or `--quality high` (a film), and versions made
|
||||
for notes with no `--quality` flag; name it in lowercase letters, digits and hyphens, with its shape and length:
|
||||
`spring-launch-9x16-15s.mp4`. Each version is a new file beside the last, never written over it.
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
It measures clipped text, text under a platform's buttons, text over the face, captions on too briefly to read,
|
||||
caption contrast against the pixels behind them, frozen stretches, flashing past the limit, cues that miss their word, loudness, a sound that
|
||||
stops dead or (with `--words`) fights the voice, and encoder blotching in the darks. Each finding is ranked P0 to P3
|
||||
with its fix; it exits 1 while a P0 or P1 stands, and `-o check.json` writes them for the critique. An
|
||||
with its fix; it exits 1 while a P0 or P1 stands, and `-o check.json` writes them for the critique. Fix every error
|
||||
in one pass before rendering again. A finding that ends `[also in …]` was in the earlier export too: what you changed
|
||||
didn't move it, so don't repeat that change; try another, or say why it stands. A note is for the person, not a
|
||||
reason to render again. An
|
||||
exception in the composition (an unclamped value going NaN, keyframes out of order, a phrase `word()` can't find, a
|
||||
missing prop) fails the render and names the line.
|
||||
- **Watch it as a viewer would once the piece is close.** `raea check` measures; it can't judge a frame cropped too
|
||||
@@ -21,7 +24,10 @@
|
||||
- **Without `--manifest`**, `raea render` writes the export alone, without the measurements `raea check` reads. Render
|
||||
another deliverable from its own file the same way (`raea render NAME.tsx -o NAME.mp4 --manifest NAME.json`) and
|
||||
check it.
|
||||
- **Loudness** comes out at -14 LUFS integrated (±1) with true peak at or below -1 dBTP when `<Mix>` is in the tree.
|
||||
- **Loudness** comes out at -14 LUFS integrated (±1) with true peak at or below -1 dBTP: raea levels each line of
|
||||
dialogue (the `voice` bus, or footage on no bus) to the same loudness and masters the piece, so don't measure lines
|
||||
or set `gainDb` to level them, and don't master the voice outside raea. `gainDb` is for a deliberate change, on top
|
||||
of raea's level. `<Mix lufs={…} ceiling={…}>` sets another target.
|
||||
|
||||
## Why
|
||||
|
||||
@@ -45,9 +51,10 @@ looking again, finds more than a still per change and costs less.
|
||||
A video's bitrate follows its size and frame rate (about 20 Mbit/s at 1080p30, 80 at 4K30; VideoToolbox spends less on
|
||||
flat pictures), and `--kbps N` sets it. `--quality draft|high|master` (or 0..1: 0.6, 0.85, 0.95) asks for constant
|
||||
quality instead, each frame getting the bits it needs: `master` keeps thin type and hard vector edges clean at 4K
|
||||
(about 31 Mbit/s on flat motion graphics). Blotching in dark areas is the encoder, not the composition: export dark
|
||||
material as PNG frames (`RAEA_READBACK=rgba raea render piece.tsx -o piece.frames/`) and encode them with more bits for
|
||||
the darks. A `NAME.frames/` folder is never committed, and raea's storage dry run lists it a day after
|
||||
(about 31 Mbit/s on flat motion graphics). Blotching in dark areas is the encoder's or the footage's own, and on a
|
||||
render made in a project `raea check` says which: the footage's is a note to pass on, never a reason to render again;
|
||||
for the encode's, render with `--quality master`. Dark material can also go out as PNG frames
|
||||
(`RAEA_READBACK=rgba raea render piece.tsx -o piece.frames/`). A `NAME.frames/` folder is never committed, and raea's storage dry run lists it a day after
|
||||
the render unless something names it.
|
||||
|
||||
Which to ask for. A version made for notes (a cut to review, a shot that will be joined, a preview) takes no
|
||||
|
||||
@@ -36,11 +36,14 @@
|
||||
- Narration over the picture, when the footage has no voice for it, is
|
||||
`<Speech text="the words" start={frame} />` from `raea/speech` (Pocket TTS, on this computer; `voice` picks a
|
||||
Pocket voice or a WAV of one).
|
||||
- Master the sum with one `<Mix lufs={-14} ceiling={-1.5} />` per composition. It brings the whole mix to -14 LUFS
|
||||
integrated and limits true peaks under the ceiling, which is what the floor's loudness defect asks for.
|
||||
- raea mixes and masters every render: each line of dialogue (the `voice` bus, or footage on no bus) comes to the same
|
||||
loudness, a join into dead silence gets the room's tone, and the whole mix comes to -14 LUFS integrated with true
|
||||
peaks under -1 dBTP, which is what the floor's loudness defect asks for. Don't level lines with `gainDb` or master
|
||||
the voice outside raea. One `<Mix lufs={…} ceiling={…} />` per composition sets another target.
|
||||
- Put the sounds in the tree in time order. The engine keys a sound's stretch by its place in the tree, so adding a
|
||||
sound in the middle of the list can split the ones after it.
|
||||
- Balance relative to the voice. The approved pieces, mastered by `<Mix>` to -14 LUFS, sit like this:
|
||||
- Balance relative to the voice. The approved pieces, mastered to -14 LUFS, sit like this (each a `gainDb` on top of
|
||||
raea's level for the voice, or on the sound's own level for the rest):
|
||||
|
||||
| sound | with a voice | without one (promo, deck, game) |
|
||||
|---|---|---|
|
||||
@@ -110,7 +113,6 @@ ends up shouting over the narrator while another is inaudible.
|
||||
- `loop` on an `<Audio>` without `endAt` to stretch a short ambience: nothing loops, it plays once and stops dead
|
||||
(the render warns). With `endAt` it repeats with a hard jump at each loop; tile copies with crossfades instead.
|
||||
- Two `<Mix>` in one composition: it throws.
|
||||
- No `<Mix>`: the sum plays as it is, at whatever loudness it adds up to.
|
||||
- Rewording a `sao()` prompt on every pass. Each new prompt makes a new sound.
|
||||
- `style` on an `<Audio>`: Audio has no picture and takes no style.
|
||||
- Hand-placing dozens of game sounds from a log. Cue them from `useGameEvents` (`motion/games`).
|
||||
|
||||
@@ -224,6 +224,9 @@ function useMediaAttrs(owner: string, props: MediaProps, src = props.src as stri
|
||||
"data-playback-rate": rate,
|
||||
"data-start-from": props.startFrom ?? props.trimBefore ?? 0,
|
||||
"data-end-at": props.endAt ?? props.trimAfter,
|
||||
// the clip's span of its source in seconds, where raea's mix measures it to level dialogue (raea-sys-mix level.rs)
|
||||
"data-clip-from": (props.startFrom ?? props.trimBefore ?? 0) / fps,
|
||||
"data-clip-to": endAt === undefined ? undefined : endAt / fps,
|
||||
"data-loop": props.loop ? "true" : undefined,
|
||||
"data-muted": props.muted ? "true" : undefined,
|
||||
"data-ended": t.ended ? "true" : undefined,
|
||||
|
||||
@@ -7,6 +7,8 @@ license = "FSL-1.1-ALv2"
|
||||
description = "raea's one mixer core: the same Firewheel graph plays live in the device callback and renders offline as the bounce, so a render and a play sound the same, sample for sample (sdk/react/docs/audio-stack.md)"
|
||||
|
||||
[dependencies]
|
||||
# the mix before the master: dialogue at one level, room tone at the joins
|
||||
raea-sys-mix-level = { path = "level" }
|
||||
# the audio graph: sample-accurate scheduled events, custom nodes, a CPAL stream live and a processor pulled by hand
|
||||
# offline. 0.12 because bevy_seedling 0.8 pins it: one Firewheel for raea and Bevy. On Bevy 0.20 both are vendored and
|
||||
# ported (vendor/firewheel*, vendor/bevy_seedling) until their releases catch up.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "raea-sys-mix-level"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea's mix before its master: dialogue at one level, and the room's tone at a join into dead silence"
|
||||
|
||||
[dependencies]
|
||||
raea-io-media = { path = "../../../io/media", default-features = false, features = ["soft-audio"] }
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Room tone at the joins: a gap the mix drops into digital silence and comes straight back from (two lines of a
|
||||
//! take joined with a gap between them) is filled with the room's own tone, the quietest stretch of sound before it.
|
||||
//! A dead-silent gap reads as a dropout (11-14: the walkaround's v1; raea check called it one, and the agent rebuilt
|
||||
//! the voice outside raea to fill its gaps). The tone is the quietest stretch of sound within LOOK of the gap, before
|
||||
//! it or, where the line before runs on without a pause, after it. The gap is the check's dropout exactly (raea check's defects.rs): from
|
||||
//! HAD dBFS or more to under SILENT in one 10 ms step, back within two to within 10 dB, 50 ms to 3 s later. A pause that
|
||||
//! fades out or in is the edit's own and is left as it is. The render's master fills them (it has the whole bounce);
|
||||
//! live play hears the gap.
|
||||
use raea_io_media::Audio;
|
||||
|
||||
/// The check's dropout: from this level (dBFS, a 10 ms step's RMS) ...
|
||||
pub const HAD: f64 = -45.0;
|
||||
/// ... to under this
|
||||
pub const SILENT: f64 = -80.0;
|
||||
/// How far back the room tone is looked for (s), and how long a stretch of it is taken (s)
|
||||
const LOOK: f64 = 3.0;
|
||||
const TONE: f64 = 0.3;
|
||||
/// How far under HAD a gap's edge may be and still be a hard join (dB)
|
||||
const EDGE: f64 = 5.0;
|
||||
/// A stretch quieter than this is silence, not tone (dBFS)
|
||||
const QUIETEST: f64 = -75.0;
|
||||
|
||||
fn db(sq: f64) -> f64 {
|
||||
10.0 * sq.max(1e-20).log10()
|
||||
}
|
||||
|
||||
/// Each 10 ms step's level (dBFS RMS over the channels)
|
||||
fn steps(a: &Audio, hop: usize) -> Vec<f64> {
|
||||
let n = a.len() / hop;
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for k in 0..n {
|
||||
let mut s = 0f64;
|
||||
for c in &a.channels {
|
||||
for v in &c[k * hop..(k + 1) * hop] {
|
||||
s += (*v as f64) * (*v as f64);
|
||||
}
|
||||
}
|
||||
out.push(db(s / (hop * a.channels.len().max(1)) as f64));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The gaps (first and last step, end exclusive) the check would call dropouts, on steps measured as the master will
|
||||
/// play them: a run of dead silence, 50 ms to 3 s, with sound (within EDGE dB of HAD) inside the three steps either
|
||||
/// side of it. The check's own grid of steps can split a 12 ms fade where this one doesn't, so the edge is looked for
|
||||
/// over 30 ms; a fade that takes longer than that is a pause, and stays.
|
||||
pub fn gaps(rms: &[f64]) -> Vec<(usize, usize)> {
|
||||
let loud = |s: &[f64]| s.iter().any(|l| *l >= HAD - EDGE);
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i < rms.len() {
|
||||
if rms[i] >= SILENT || rms[i - 1] < SILENT {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while j < rms.len() && rms[j] < SILENT {
|
||||
j += 1;
|
||||
}
|
||||
if (5..=300).contains(&(j - i)) && loud(&rms[i.saturating_sub(3)..i]) && loud(&rms[j..(j + 3).min(rms.len())]) {
|
||||
out.push((i, j));
|
||||
}
|
||||
i = j.max(i + 1);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `a` with each dropout filled by the room's tone: the quietest TONE of sound (not silence) in the LOOK before it,
|
||||
/// looped with 10 ms crossfades and faded in and out at the gap's edges. Its gaps are found as the master will play
|
||||
/// it, `gain` dB up, where the check hears them. Unchanged where there's none.
|
||||
pub fn filled(a: &Audio, gain: f64) -> Audio {
|
||||
let hop = (a.rate as usize / 100).max(1);
|
||||
let rms: Vec<f64> = steps(a, hop).into_iter().map(|l| l + gain).collect();
|
||||
let found = gaps(&rms);
|
||||
if found.is_empty() {
|
||||
return a.clone();
|
||||
}
|
||||
let mut out = a.clone();
|
||||
let longest = (TONE * 100.0) as usize;
|
||||
let xf = hop;
|
||||
for (i, j) in found {
|
||||
// the quietest stretch of sound near the gap, before it or after it: the room between words, the longest of
|
||||
// them up to TONE (a line that runs on leaves only short pauses: 120 ms loops well enough under a short gap)
|
||||
let quietest = |tone: usize| {
|
||||
let near = (i.saturating_sub((LOOK * 100.0) as usize)..i.saturating_sub(tone)).chain(j..(j + (LOOK * 100.0) as usize).min(rms.len().saturating_sub(tone)));
|
||||
near.filter(|&s| rms[s..s + tone].iter().all(|l| *l >= QUIETEST && *l < HAD + 15.0)).min_by(|&x, &y| {
|
||||
let m = |s: usize| rms[s..s + tone].iter().sum::<f64>();
|
||||
m(x).total_cmp(&m(y))
|
||||
}).map(|t| (t, tone))
|
||||
};
|
||||
let Some((t, tone)) = [longest, longest * 2 / 3, longest * 2 / 5].into_iter().find_map(quietest) else {
|
||||
continue;
|
||||
};
|
||||
let (src, len) = (t * hop, tone * hop);
|
||||
let (start, end) = (i * hop, (j * hop).min(a.len()));
|
||||
for c in 0..out.channels.len() {
|
||||
for (k, s) in (start..end).enumerate() {
|
||||
// looped, each pass crossfaded into the next; in and out over 10 ms at the gap's edges
|
||||
let (pass, at) = (k / (len - xf), k % (len - xf));
|
||||
let mut v = a.channels[c][src + at];
|
||||
if pass > 0 && at < xf {
|
||||
let w = at as f32 / xf as f32;
|
||||
v = v * w + a.channels[c][src + len - xf + at] * (1.0 - w);
|
||||
}
|
||||
let edge = (k.min(end - s) as f32 / xf as f32).min(1.0);
|
||||
out.channels[c][s] += v * edge;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn noise(n: usize, level: f32, seed: &mut u32) -> Vec<f32> {
|
||||
(0..n).map(|_| {
|
||||
*seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
((*seed >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0) * level
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// Two lines with room tone under them and a dead gap between: the gap is filled, and the check's dropout is gone;
|
||||
/// a pause that fades is left alone
|
||||
#[test]
|
||||
fn a_dead_gap_gets_the_room_s_tone() {
|
||||
let rate = 48_000u32;
|
||||
let mut seed = 7;
|
||||
// 1 s of a line (-20 dBFS) with a pause of room tone in it (-65), 0.2 s dead, 1 s more
|
||||
let mut x = noise(rate as usize, 0.1, &mut seed);
|
||||
for v in x[rate as usize / 4..].iter_mut().take(rate as usize / 2) {
|
||||
*v *= 0.01;
|
||||
}
|
||||
x.extend(vec![0.0; rate as usize / 5]);
|
||||
x.extend(noise(rate as usize, 0.1, &mut seed));
|
||||
let a = Audio { rate, channels: vec![x.clone(), x] };
|
||||
let hop = rate as usize / 100;
|
||||
assert_eq!(gaps(&steps(&a, hop)).len(), 1);
|
||||
let f = filled(&a, 0.0);
|
||||
// a gap under the line before the master's gain is still one once it's played: found at the level heard
|
||||
let quiet = Audio { rate, channels: a.channels.iter().map(|c| c.iter().map(|v| v * 0.03).collect()).collect() };
|
||||
assert!(gaps(&steps(&quiet, hop)).is_empty());
|
||||
assert!(!gaps(&steps(&quiet, hop).into_iter().map(|l| l + 30.0).collect::<Vec<_>>()).is_empty());
|
||||
assert!(gaps(&steps(&filled(&quiet, 30.0), hop).into_iter().map(|l| l + 30.0).collect::<Vec<_>>()).is_empty());
|
||||
assert!(gaps(&steps(&f, hop)).is_empty());
|
||||
let gap = &f.channels[0][rate as usize + rate as usize / 20..rate as usize + rate as usize / 10];
|
||||
assert!(gap.iter().any(|v| v.abs() > 1e-4), "the gap holds tone");
|
||||
// a fade to silence and back over 0.3 s is a pause, not a dropout
|
||||
let fade: Vec<f32> = (0..rate as usize * 2).map(|i| {
|
||||
let t = i as f32 / rate as f32;
|
||||
let g = ((t - 1.0).abs() / 0.15).min(1.0);
|
||||
((i % 97) as f32 / 97.0 - 0.5) * 0.2 * g
|
||||
}).collect();
|
||||
assert!(gaps(&steps(&Audio { rate, channels: vec![fade] }, hop)).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//! raea's mix, before its master: every line of dialogue at one loudness, so the master brings the whole piece to its
|
||||
//! target without a line louder or quieter than the next (11-14: a phone walkaround's lines ran from -13.8 to -26.9
|
||||
//! LUFS; the agent measured each and set its gainDb, and the limiter still flattened the loud ones).
|
||||
//!
|
||||
//! Dialogue is a clip on the voice bus, or footage (a video file's sound) on no bus. It's measured over the span of its
|
||||
//! source it plays (BS.1770 integrated loudness, gated, so its pauses don't count) and brought to DIALOGUE, by at most
|
||||
//! REACH either way. A clip quieter than ROOM is room tone or a silent take: it keeps its level. Everything else (music,
|
||||
//! effects, ambience, anything on another bus) keeps its own level and its bus's settings, which now sit under dialogue
|
||||
//! that's always at the same place. A clip's gainDb is an offset on top of the level, never undone by it.
|
||||
//!
|
||||
//! Live play and the render call the same function on the same span, so they hear the same mix; each span is measured
|
||||
//! once a process.
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
/// Where dialogue sits before the master: EBU R128's programme level, the master brings it up to the delivery's
|
||||
pub const DIALOGUE: f64 = -23.0;
|
||||
/// The most a clip is moved, up or down (dB)
|
||||
pub const REACH: f64 = 12.0;
|
||||
/// Under this a clip is room tone or silence, not a line (LUFS)
|
||||
pub const ROOM: f64 = -45.0;
|
||||
/// A span with no end is measured this far
|
||||
const OPEN: f64 = 30.0;
|
||||
|
||||
/// Each file's measured spans, (from ms, to ms or -1, gain): looked up by the path as it is, without making a key,
|
||||
/// since live play asks every frame
|
||||
static LEVELS: Mutex<Option<HashMap<PathBuf, Vec<(i64, i64, f32)>>>> = Mutex::new(None);
|
||||
|
||||
/// A video file's extension (its sound is the footage's own)
|
||||
fn footage(ext: &str) -> bool {
|
||||
for v in ["mov", "mp4", "m4v", "webm", "mkv"] {
|
||||
if ext.eq_ignore_ascii_case(v) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether a clip is dialogue: on the voice bus, or a video file's sound on no bus
|
||||
pub fn is_dialogue(file: &Path, bus: Option<&str>) -> bool {
|
||||
match bus {
|
||||
Some(b) => b == "voice",
|
||||
None => file.extension().and_then(|x| x.to_str()).is_some_and(footage),
|
||||
}
|
||||
}
|
||||
|
||||
/// The gain (dB) that brings a clip of `loudness` LUFS to DIALOGUE: 0 for room tone or an unmeasurable span
|
||||
pub fn to_dialogue(loudness: f64) -> f64 {
|
||||
if !loudness.is_finite() || loudness < ROOM { 0.0 } else { (DIALOGUE - loudness).clamp(-REACH, REACH) }
|
||||
}
|
||||
|
||||
fn millis(s: f64) -> i64 {
|
||||
(s * 1000.0).round() as i64
|
||||
}
|
||||
|
||||
/// A span of `file` measured before: its gain
|
||||
fn known(file: &Path, a: i64, b: i64) -> Option<f32> {
|
||||
let levels = LEVELS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for s in levels.as_ref()?.get(file)? {
|
||||
if s.0 == a && s.1 == b {
|
||||
return Some(s.2);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The linear gain raea's mix puts on a clip playing `file` from `from` to `to` seconds of it (None: to its end, or
|
||||
/// OPEN on), on `bus`: dialogue's level, else 1
|
||||
pub fn gain(file: &Path, from: f64, to: Option<f64>, bus: Option<&str>) -> f32 {
|
||||
if !is_dialogue(file, bus) {
|
||||
return 1.0;
|
||||
}
|
||||
let (a, b) = (millis(from), to.map_or(-1, millis));
|
||||
if let Some(g) = known(file, a, b) {
|
||||
return g;
|
||||
}
|
||||
let secs = to.map_or(OPEN, |t| (t - from).max(0.4));
|
||||
let loud = raea_io_media::decode_audio_window(file, from.max(0.0), secs).map_or(f64::NAN, |a| raea_io_media::audio::lufs(&a));
|
||||
let g = 10f64.powf(to_dialogue(loud) / 20.0) as f32;
|
||||
LEVELS.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(HashMap::new).entry(file.to_path_buf()).or_default().push((a, b, g));
|
||||
g
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The walkaround's lines, measured 11-14, all come to -23; room tone and silence keep their level; nothing moves
|
||||
/// further than REACH
|
||||
#[test]
|
||||
fn dialogue_comes_to_one_level() {
|
||||
for (line, loud) in [("intro", -22.1), ("ext5", -26.9), ("rear2", -16.4), ("trunk1", -13.8)] {
|
||||
let g = to_dialogue(loud);
|
||||
assert!((loud + g - DIALOGUE).abs() < 1e-9, "{line}: {loud} + {g}");
|
||||
}
|
||||
assert_eq!(to_dialogue(-50.0), 0.0);
|
||||
assert_eq!(to_dialogue(f64::NEG_INFINITY), 0.0);
|
||||
assert_eq!(to_dialogue(-40.0), REACH);
|
||||
assert_eq!(to_dialogue(0.0), -REACH);
|
||||
}
|
||||
|
||||
/// Dialogue is the voice bus, or footage on no bus; music, effects and ambience keep their own level
|
||||
#[test]
|
||||
fn what_is_dialogue() {
|
||||
assert!(is_dialogue(Path::new("take.MOV"), None));
|
||||
assert!(is_dialogue(Path::new("vo.wav"), Some("voice")));
|
||||
assert!(!is_dialogue(Path::new("song.mp3"), None));
|
||||
assert!(!is_dialogue(Path::new("take.mov"), Some("music")));
|
||||
assert!(!is_dialogue(Path::new("hit.wav"), Some("sfx")));
|
||||
assert_eq!(gain(Path::new("song.mp3"), 0.0, None, None), 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! raea's mix before its master (raea-sys-mix masters it): every line of dialogue at one level (level.rs) and the
|
||||
//! room's tone at a join the mix drops into dead silence (joins.rs). Live play and the render level clips the same way;
|
||||
//! the render's master fills the joins.
|
||||
pub mod joins;
|
||||
pub mod level;
|
||||
@@ -7,6 +7,7 @@
|
||||
//! Neural models never sit here: generated sound is rendered once, cached as PCM keyed by its inputs, and comes in as a
|
||||
//! plain source like any file (sdk/react/docs/audio-stack.md).
|
||||
|
||||
pub use raea_sys_mix_level::{joins, level};
|
||||
pub mod live;
|
||||
pub mod nodes;
|
||||
pub mod offline;
|
||||
@@ -17,7 +18,7 @@ use std::sync::Arc;
|
||||
|
||||
/// The version of the core's mastering (a raw bounce, its gain, the limiter): caches of a master or a mastered track
|
||||
/// carry it, so one an earlier core made isn't taken for this one's.
|
||||
pub const MASTER_VERSION: u32 = 3;
|
||||
pub const MASTER_VERSION: u32 = 4;
|
||||
|
||||
/// The core's rate: a render's bounce, and live play when the device takes it.
|
||||
pub const RATE: u32 = 48_000;
|
||||
|
||||
@@ -18,8 +18,19 @@ pub struct Limiter {
|
||||
/// each channel's last TAPS samples in
|
||||
hist: [[f32; TAPS]; 2],
|
||||
taps: [[f32; TAPS]; 3],
|
||||
/// the leveller's mean square of the mix, followed
|
||||
env: f32,
|
||||
}
|
||||
|
||||
/// The leveller ahead of the limiter (raea's master, 11-19): from LEVEL dB under the ceiling, RATIO to 1 on the mix's
|
||||
/// RMS (ATTACK in, RELEASE out), so phone speech brought up to a delivery's loudness rounds its peaks instead of the
|
||||
/// limiter flattening them (the walkaround's lines peaked 15-19 dB over their loudness: the limiter alone flat-topped
|
||||
/// them, and raea check found the sound clipping). Under it, nothing changes.
|
||||
pub const LEVEL: f32 = 9.0;
|
||||
pub const RATIO: f32 = 3.0;
|
||||
pub const ATTACK: f64 = 0.010;
|
||||
pub const RELEASE: f64 = 0.150;
|
||||
|
||||
const TAPS: usize = 12;
|
||||
|
||||
impl Default for Limiter {
|
||||
@@ -41,7 +52,7 @@ impl Limiter {
|
||||
*t = (sinc * w) as f32;
|
||||
}
|
||||
}
|
||||
Limiter { delay: Vec::new(), need: Vec::new(), at: 0, gain: 1.0, pre: 1.0, ceiling: CEILING, hist: [[0.0; TAPS]; 2], taps }
|
||||
Limiter { delay: Vec::new(), need: Vec::new(), at: 0, gain: 1.0, pre: 1.0, ceiling: CEILING, hist: [[0.0; TAPS]; 2], taps, env: 0.0 }
|
||||
}
|
||||
|
||||
pub fn run(&mut self, l: &mut [f32], r: &mut [f32], rate: f64) {
|
||||
@@ -56,8 +67,16 @@ impl Limiter {
|
||||
// aimed 0.26 dB under: the 12-tap meter reads a peak between samples up to ~1% low
|
||||
let (pre, ceiling) = (self.pre, self.ceiling * 0.97);
|
||||
let need = |v: f32| if v > ceiling { ceiling / v } else { 1.0 };
|
||||
let (up, down) = ((1.0 - (-1.0 / (ATTACK * rate)).exp()) as f32, (1.0 - (-1.0 / (RELEASE * rate)).exp()) as f32);
|
||||
let floor = (self.ceiling * 10f32.powf(-LEVEL / 20.0)).powi(2);
|
||||
for i in 0..l.len() {
|
||||
let frame = [l[i] * pre, r[i] * pre];
|
||||
let mut frame = [l[i] * pre, r[i] * pre];
|
||||
let p = 0.5 * (frame[0] * frame[0] + frame[1] * frame[1]);
|
||||
self.env += if p > self.env { up } else { down } * (p - self.env);
|
||||
if self.env > floor {
|
||||
let lg = (floor / self.env).powf(0.5 * (1.0 - 1.0 / RATIO));
|
||||
frame = [frame[0] * lg, frame[1] * lg];
|
||||
}
|
||||
// the sample leaving the window: its own need, settled
|
||||
let own = self.need[self.at];
|
||||
let late = std::mem::replace(&mut self.delay[self.at], frame);
|
||||
|
||||
@@ -181,15 +181,31 @@ pub fn master_raw(raw: &raea_io_media::Audio, master: Option<(f64, f64)>) -> rae
|
||||
raea_io_media::Audio { rate: raw.rate, channels: vec![l, r] }
|
||||
}
|
||||
|
||||
/// What raea masters a piece to when it has no <Mix>: the major platforms' loudness (LUFS) and a -1 dBTP ceiling
|
||||
pub const MIX: (f64, f64) = (-14.0, -1.0);
|
||||
|
||||
/// The master over a raw bounce, the one function every render uses (react's fed and page renders, raea-render's SQL renders, a
|
||||
/// play's master-gain): with a <Mix> (`mix`: target LUFS, ceiling dBTP), the gain from the raw sound to the target, then
|
||||
/// the limiter at the ceiling, the ceiling lowered by any overshoot `encode` (an AAC round trip) puts back (twice at most);
|
||||
/// without one, the live default. Returns the master it used and the mastered sound.
|
||||
/// without one, MIX; the leveller (nodes::LEVEL) rounds the loud passages first, and the gain is made up for what it
|
||||
/// took. Returns the master it used and the mastered sound.
|
||||
pub fn master_mix(raw: &raea_io_media::Audio, mix: Option<(f64, f64)>, encode: Option<&dyn Fn(&raea_io_media::Audio) -> Result<raea_io_media::Audio, String>>) -> (Option<(f64, f64)>, raea_io_media::Audio) {
|
||||
let Some((lufs, ceiling)) = mix.filter(|_| raea_io_media::audio::lufs(raw).is_finite()) else { return (None, master_raw(raw, None)) };
|
||||
let gain = raea_io_media::audio::master_gained(raw, lufs, ceiling).1;
|
||||
// raea masters whatever it renders (11-19): without a <Mix>, to MIX's loudness and ceiling
|
||||
let Some((lufs, ceiling)) = mix.or(Some(MIX)).filter(|_| raea_io_media::audio::lufs(raw).is_finite()) else { return (None, master_raw(raw, None)) };
|
||||
let mut gain = raea_io_media::audio::master_gained(raw, lufs, ceiling).1;
|
||||
// a join the mix drops into dead silence gets the room's tone, found at the level the master plays it (joins.rs)
|
||||
let raw = &crate::joins::filled(raw, gain);
|
||||
let mut a = master_raw(raw, Some((gain, ceiling)));
|
||||
// the leveller takes a little loudness with the peaks: made up, twice at most
|
||||
for _ in 0..2 {
|
||||
let got = raea_io_media::audio::lufs(&a);
|
||||
if !got.is_finite() || (got - lufs).abs() <= 0.2 {
|
||||
break;
|
||||
}
|
||||
gain += lufs - got;
|
||||
a = master_raw(raw, Some((gain, ceiling)));
|
||||
}
|
||||
let mut master = Some((gain, ceiling));
|
||||
let mut a = master_raw(raw, master);
|
||||
if let Some(enc) = encode {
|
||||
let mut c = ceiling;
|
||||
for _ in 0..2 {
|
||||
|
||||
@@ -50,6 +50,7 @@ raea-core-calls = "core"
|
||||
raea-core-brief = "core"
|
||||
raea-sys-k = "systems"
|
||||
raea-sys-mix = "systems"
|
||||
raea-sys-mix-level = "systems"
|
||||
raea-sys-tone = "systems"
|
||||
raea-seedling = "systems"
|
||||
raea-sys-ml = "systems"
|
||||
@@ -178,9 +179,11 @@ raea-runtime-scene2d = "runtime"
|
||||
raea-runtime-shared = "runtime"
|
||||
raea-page = "runtime"
|
||||
raea-app-check = "apps"
|
||||
raea-app-check-cause = "apps"
|
||||
raea-app-check-flash = "apps"
|
||||
raea-app-check-inbox = "apps"
|
||||
raea-app-check-read = "apps"
|
||||
raea-app-check-text = "apps"
|
||||
raea-app-direction = "apps"
|
||||
raea-app-notes = "apps"
|
||||
# `raea fingerprint`: its verbs and the resident service that keeps the encoders loaded
|
||||
@@ -261,6 +264,8 @@ raea-sys-volume = true
|
||||
# the scene's ray tracing (the traced-light pass reads its scene)
|
||||
raea-sys-rt = true
|
||||
raea-sys-mix = true
|
||||
# the mix before the master: dialogue at one level, room tone at the joins (the mix masters what it gives)
|
||||
raea-sys-mix-level = true
|
||||
raea-sys-tone = true
|
||||
raea-sys-ml = true
|
||||
raea-sys-mlx = true
|
||||
|
||||
Reference in new issue
Block a user