mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 12:44:11 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a8a7df53d | ||
|
|
ef8ea7563d | ||
|
|
6716b6b9f0 | ||
|
|
313ac8ab83 | ||
|
|
cdfb043026 |
No files matched your search
@@ -40,6 +40,29 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
|
||||
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
|
||||
}
|
||||
|
||||
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
|
||||
/// interview: 7 s one after another, 4 s so).
|
||||
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
|
||||
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
|
||||
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
|
||||
let next = AtomicUsize::new(0);
|
||||
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..workers {
|
||||
s.spawn(|| {
|
||||
loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
if i >= n {
|
||||
break;
|
||||
}
|
||||
*out[i].lock().unwrap() = Some(f(i));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
|
||||
}
|
||||
|
||||
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
|
||||
if files.is_empty() {
|
||||
return Err("raea media sheet FILE... -o OUT: which files?".into());
|
||||
@@ -47,10 +70,9 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
|
||||
let mut tiles = Vec::new();
|
||||
if files.len() == 1 {
|
||||
let p = probe_of(&files[0])?;
|
||||
for i in 0..n.max(1) {
|
||||
let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
|
||||
tiles.push((t, frame(&files[0], t)?));
|
||||
}
|
||||
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect();
|
||||
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?;
|
||||
tiles.extend(at.into_iter().zip(read));
|
||||
} else {
|
||||
for f in files {
|
||||
let p = probe_of(f)?;
|
||||
|
||||
+69
-62
@@ -1,6 +1,7 @@
|
||||
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
|
||||
|
||||
use super::*;
|
||||
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
|
||||
|
||||
pub(crate) fn round3(x: f64) -> f64 {
|
||||
(x * 1000.0).round() / 1000.0
|
||||
@@ -38,7 +39,11 @@ pub fn probe_of(path: &Path) -> R<Probe> {
|
||||
}
|
||||
i
|
||||
});
|
||||
let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
|
||||
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way)
|
||||
let audio = match audio_track(path) {
|
||||
Some(a) => Some(a),
|
||||
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
|
||||
};
|
||||
if video.is_none() && audio.is_none() {
|
||||
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads
|
||||
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
|
||||
@@ -124,74 +129,37 @@ impl Track {
|
||||
}
|
||||
}
|
||||
|
||||
/// The boxes inside `b` (a box's payload): (type, payload).
|
||||
pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i + 8 <= b.len() {
|
||||
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
|
||||
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
|
||||
let mut hdr = 8;
|
||||
if size == 1 && i + 16 <= b.len() {
|
||||
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = b.len() - i;
|
||||
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe`
|
||||
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk).
|
||||
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> {
|
||||
audio_in(&moov_of(path)?)
|
||||
}
|
||||
|
||||
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
|
||||
for (k, trak) in boxes(moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
}
|
||||
if size < hdr || i + size > b.len() {
|
||||
break;
|
||||
let Some(mdia) = child(trak, b"mdia") else { continue };
|
||||
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) {
|
||||
continue;
|
||||
}
|
||||
out.push((kind, &b[i + hdr..i + size]));
|
||||
i += size;
|
||||
let mdhd = child(mdia, b"mdhd")?;
|
||||
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
|
||||
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
|
||||
// them again as a double at 48 and a count at 56
|
||||
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
|
||||
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
|
||||
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
|
||||
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
|
||||
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
None
|
||||
}
|
||||
|
||||
/// The first video track's timing, for MP4 and QuickTime files.
|
||||
pub fn video_track(path: &Path) -> Option<Track> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
let len = f.metadata().ok()?.len();
|
||||
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
|
||||
let mut at = 0u64;
|
||||
let moov = loop {
|
||||
if at + 8 > len {
|
||||
return None;
|
||||
}
|
||||
let mut h = [0u8; 16];
|
||||
f.seek(SeekFrom::Start(at)).ok()?;
|
||||
f.read_exact(&mut h[..8]).ok()?;
|
||||
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
|
||||
let mut hdr = 8u64;
|
||||
if size == 1 {
|
||||
f.read_exact(&mut h[8..]).ok()?;
|
||||
size = u64::from_be_bytes(h[8..].try_into().ok()?);
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = len - at;
|
||||
}
|
||||
if size < hdr {
|
||||
return None;
|
||||
}
|
||||
if &h[4..8] == b"moov" {
|
||||
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
|
||||
f.read_exact(&mut m).ok()?;
|
||||
break m;
|
||||
}
|
||||
at += size;
|
||||
};
|
||||
let moov = moov_of(path)?;
|
||||
for (k, trak) in boxes(&moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
@@ -295,3 +263,42 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
|
||||
}
|
||||
|
||||
// ---- pictures
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
|
||||
v.extend_from_slice(kind);
|
||||
v.extend_from_slice(body);
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sound_track_is_read_from_the_file_s_own_tables() {
|
||||
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
|
||||
let mut mdhd = vec![0u8; 24];
|
||||
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
|
||||
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
|
||||
let mut hdlr = vec![0u8; 24];
|
||||
hdlr[8..12].copy_from_slice(b"soun");
|
||||
let mut stsd = vec![0u8; 44];
|
||||
stsd[7] = 1;
|
||||
stsd[12..16].copy_from_slice(b"mp4a");
|
||||
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
|
||||
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
|
||||
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
|
||||
// a picture track ahead of it is passed over
|
||||
let mut vh = vec![0u8; 24];
|
||||
vh[8..12].copy_from_slice(b"vide");
|
||||
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
|
||||
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
|
||||
// no sound track, or one that states no rate: nothing (the track is decoded instead)
|
||||
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
|
||||
let mut silent = stsd.clone();
|
||||
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
|
||||
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
|
||||
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,11 @@ const EXTS: &[&str] = &["", ".ts", ".tsx", ".mts", ".js", ".mjs", ".cjs", ".json
|
||||
/// `spec` imported from a file in `dir` (`esm`: an import, else a require), to the file it names
|
||||
pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> {
|
||||
let raw = spec.strip_prefix("file://").unwrap_or(spec);
|
||||
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." {
|
||||
let want = if raw.starts_with('/') { PathBuf::from(raw) } else { dir.join(raw) };
|
||||
// (a path whole on Windows too, `D:\..`: the React raea ships, found, was asked for again by its path and read as a package's name, #278)
|
||||
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." || Path::new(raw).is_absolute() {
|
||||
let want = if raw.starts_with('/') || Path::new(raw).is_absolute() { PathBuf::from(raw) } else { dir.join(raw) };
|
||||
return as_file(&want).ok_or_else(|| format!("Cannot find module '{spec}' from {}", dir.display()));
|
||||
}
|
||||
// a package: its name (a scope takes two parts) and the subpath after it
|
||||
let mut parts = raw.splitn(if raw.starts_with('@') { 3 } else { 2 }, '/');
|
||||
let name = if raw.starts_with('@') { format!("{}/{}", parts.next().unwrap_or(""), parts.next().unwrap_or("")) } else { parts.next().unwrap_or("").to_string() };
|
||||
let sub = parts.next().map(|s| format!("./{s}")).unwrap_or_else(|| ".".into());
|
||||
@@ -53,9 +53,9 @@ pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String
|
||||
return Ok(f);
|
||||
}
|
||||
}
|
||||
// raea's own file (sdk/app, under `raea goal check`) importing a package raea ships: a release has those in the React runtime's node_modules alone (#278)
|
||||
let (home, own) = (raea_io_home::home(), raea_io_home::home().join("sdk/react/js/node_modules").join(&name));
|
||||
if dir.starts_with(&home) && own.is_dir() {
|
||||
// a package raea ships, imported by a file with no node_modules of its own: raea's (sdk/app), or a project's brief.ts or scene (#278)
|
||||
let own = raea_io_home::home().join("sdk/react/js/node_modules").join(&name);
|
||||
if own.is_dir() {
|
||||
return package_entry(&own, &sub, esm).ok_or_else(|| format!("Cannot find module '{spec}': {} has no {sub}", own.display()));
|
||||
}
|
||||
Err(format!("Cannot find package '{name}' imported from {}", dir.display()))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! A file of raea's own importing a package raea ships finds it in the React runtime's node_modules (#278): a release has
|
||||
//! A file importing a package raea ships (raea's own, or a project's with no node_modules) finds it in the React runtime's node_modules (#278): a release has
|
||||
//! no node_modules above sdk/app, so `raea goal check` ended every render "Cannot find package 'react'". Its own test
|
||||
//! binary: raea's home is read once a process.
|
||||
#![cfg(feature = "modules")]
|
||||
@@ -16,7 +16,21 @@ fn raeas_own_file_finds_the_react_raea_ships() {
|
||||
// SAFETY: the one test here, before anything reads the environment
|
||||
unsafe { std::env::set_var("RAEA_HOME", &home) };
|
||||
assert_eq!(raea_native::node::resolve_file("react", &own, true).unwrap(), pkg.join("index.js"));
|
||||
// a project's own file never reaches into raea's packages
|
||||
assert!(raea_native::node::resolve_file("react", &theirs, true).unwrap_err().contains("Cannot find package 'react'"));
|
||||
// a project's file with no node_modules of its own gets the same React (brief.ts, a scene it registers): a release's
|
||||
// render was applied and then failed its checks on "Cannot find package 'react'"
|
||||
fs::create_dir_all(&theirs).unwrap();
|
||||
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), pkg.join("index.js"));
|
||||
// its own copy, when it has one, wins
|
||||
let mine = theirs.join("node_modules/react");
|
||||
fs::create_dir_all(&mine).unwrap();
|
||||
fs::write(mine.join("package.json"), r#"{"name":"react","main":"index.js"}"#).unwrap();
|
||||
fs::write(mine.join("index.js"), "module.exports = {}").unwrap();
|
||||
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), mine.join("index.js"));
|
||||
// a file asked for by its whole path is that file, on Windows too (`D:\..` was read as a package's name)
|
||||
let whole = pkg.join("index.js");
|
||||
assert_eq!(raea_native::node::resolve_file(whole.to_str().unwrap(), &theirs, true).unwrap(), whole);
|
||||
// and a package raea doesn't ship is still not found
|
||||
assert!(raea_native::node::resolve_file("left-pad", &own, true).unwrap_err().contains("Cannot find package 'left-pad'"));
|
||||
fs::remove_dir_all(&theirs).ok();
|
||||
fs::remove_dir_all(&home).ok();
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
pub mod audio;
|
||||
pub mod mezz;
|
||||
pub mod mp4box;
|
||||
#[cfg(feature = "mux")]
|
||||
pub mod remux;
|
||||
pub mod samples;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! An MP4 or QuickTime file's boxes, read directly: what `media probe` and the ffmpeg backend take a track's own facts
|
||||
//! from (its frame times, its sound's rate) without reading the gigabytes of pictures beside them.
|
||||
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::Path;
|
||||
|
||||
/// The boxes inside `b` (a box's payload): (type, payload).
|
||||
pub fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i + 8 <= b.len() {
|
||||
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
|
||||
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
|
||||
let mut hdr = 8;
|
||||
if size == 1 && i + 16 <= b.len() {
|
||||
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = b.len() - i;
|
||||
}
|
||||
if size < hdr || i + size > b.len() {
|
||||
break;
|
||||
}
|
||||
out.push((kind, &b[i + hdr..i + size]));
|
||||
i += size;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
pub fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
pub fn be64(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// The file's moov box, read alone (mdat can be gigabytes).
|
||||
pub fn moov_of(path: &Path) -> Option<Vec<u8>> {
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
let len = f.metadata().ok()?.len();
|
||||
let mut at = 0u64;
|
||||
loop {
|
||||
if at + 8 > len {
|
||||
return None;
|
||||
}
|
||||
let mut h = [0u8; 16];
|
||||
f.seek(SeekFrom::Start(at)).ok()?;
|
||||
f.read_exact(&mut h[..8]).ok()?;
|
||||
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
|
||||
let mut hdr = 8u64;
|
||||
if size == 1 {
|
||||
f.read_exact(&mut h[8..]).ok()?;
|
||||
size = u64::from_be_bytes(h[8..].try_into().ok()?);
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = len - at;
|
||||
}
|
||||
if size < hdr {
|
||||
return None;
|
||||
}
|
||||
if &h[4..8] == b"moov" {
|
||||
let mut m = vec![0u8; usize::try_from(size - hdr).ok().filter(|n| *n <= 256 << 20)?];
|
||||
f.read_exact(&mut m).ok()?;
|
||||
return Some(m);
|
||||
}
|
||||
at += size;
|
||||
}
|
||||
}
|
||||
+19
-10
@@ -9,6 +9,8 @@ use raea_io_codec::{
|
||||
Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of,
|
||||
};
|
||||
|
||||
mod mov;
|
||||
|
||||
pub struct Ffmpeg;
|
||||
|
||||
/// The ffmpeg or ffprobe to run: the PATH's, else raea's own (raea_io_assets::ffmpeg_tool). Opening a video (`fetch`)
|
||||
@@ -124,6 +126,12 @@ const NVENC: [&str; 14] = ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq",
|
||||
/// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with
|
||||
/// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113).
|
||||
fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
probe_with(path, mov::frame_times(path))
|
||||
}
|
||||
|
||||
/// `tabled`: the frame times the file's own tables state (mov.rs). Without them ffprobe is asked for every packet's
|
||||
/// time, which reads the whole file.
|
||||
fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
let out = cli("ffprobe", named_video(path))?
|
||||
.args([
|
||||
"-v",
|
||||
@@ -132,11 +140,9 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration",
|
||||
"-show_entries",
|
||||
"packet=pts_time",
|
||||
"-of",
|
||||
"json",
|
||||
])
|
||||
.args(if tabled.is_none() { &["-show_entries", "packet=pts_time"][..] } else { &[] })
|
||||
.args(["-of", "json"])
|
||||
.arg(path)
|
||||
.output()
|
||||
.map_err(|e| format!("ffprobe: {e}"))?;
|
||||
@@ -159,12 +165,15 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
.and_then(|r| r.split_once('/'))
|
||||
.map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0))
|
||||
.unwrap_or(30.0);
|
||||
let mut pts: Vec<f64> = j["packets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
|
||||
.collect();
|
||||
let mut pts: Vec<f64> = match tabled {
|
||||
Some(t) => t,
|
||||
None => j["packets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
|
||||
.collect(),
|
||||
};
|
||||
pts.sort_by(f64::total_cmp);
|
||||
let duration = j["format"]["duration"]
|
||||
.as_str()
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! An MP4 or QuickTime file's frame times from its own sample tables. Opening a video asked ffprobe for every packet's
|
||||
//! time, and for these files ffprobe reads every packet to say it: each open of a 1 GB interview read 1 GB (two
|
||||
//! minutes on a cloud Sprite's disk, 12-01), and a contact sheet opened its file once a frame.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use raea_io_codec::mp4box::{be32, be64, boxes, child, moov_of};
|
||||
|
||||
/// Every frame's presentation time in seconds, sorted, as ffprobe's packets give them up to one shift of them all
|
||||
/// (the decoder uses them from the first on). None for a file that isn't MP4 or QuickTime, one in fragments (mvex), and one
|
||||
/// whose edit list does more than set where the track starts: those are asked of ffprobe as before.
|
||||
pub(crate) fn frame_times(path: &Path) -> Option<Vec<f64>> {
|
||||
let ext = path.extension()?.to_string_lossy().to_ascii_lowercase();
|
||||
if !["mp4", "mov", "m4v"].contains(&ext.as_str()) {
|
||||
return None;
|
||||
}
|
||||
times_in(&moov_of(path)?)
|
||||
}
|
||||
|
||||
fn times_in(moov: &[u8]) -> Option<Vec<f64>> {
|
||||
if child(moov, b"mvex").is_some() {
|
||||
return None;
|
||||
}
|
||||
for (k, trak) in boxes(moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
}
|
||||
let Some(mdia) = child(trak, b"mdia") else { continue };
|
||||
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"vide"[..]) {
|
||||
continue;
|
||||
}
|
||||
// an edit list that plays the track from one place on is a shift of every time; one with a gap ahead of it,
|
||||
// or more than one piece, moves frames apart
|
||||
if let Some(elst) = child(trak, b"edts").and_then(|e| child(e, b"elst")) {
|
||||
if be32(elst, 4)? != 1 {
|
||||
return None;
|
||||
}
|
||||
let from = if elst.first() == Some(&1) { be64(elst, 16)? as i64 } else { be32(elst, 12)? as i32 as i64 };
|
||||
if from < 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mdhd = child(mdia, b"mdhd")?;
|
||||
let scale = if mdhd.first() == Some(&1) { be32(mdhd, 20)? } else { be32(mdhd, 12)? } as f64;
|
||||
if scale <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let stbl = child(child(mdia, b"minf")?, b"stbl")?;
|
||||
let stts = child(stbl, b"stts")?;
|
||||
let mut times: Vec<i64> = Vec::new();
|
||||
let mut dts = 0i64;
|
||||
for e in 0..be32(stts, 4)? as usize {
|
||||
let (n, d) = (be32(stts, 8 + e * 8)?, be32(stts, 12 + e * 8)? as i64);
|
||||
// a table that claims more frames than a day of 240 a second isn't one to trust
|
||||
if times.len() + n as usize > 20_736_000 {
|
||||
return None;
|
||||
}
|
||||
for _ in 0..n {
|
||||
times.push(dts);
|
||||
dts += d;
|
||||
}
|
||||
}
|
||||
if let Some(ctts) = child(stbl, b"ctts") {
|
||||
let mut i = 0usize;
|
||||
for e in 0..be32(ctts, 4)? as usize {
|
||||
// signed whatever the version says: QuickTime writes negative offsets in version 0 boxes
|
||||
let (n, off) = (be32(ctts, 8 + e * 8)? as usize, be32(ctts, 12 + e * 8)? as i32 as i64);
|
||||
for t in times.iter_mut().skip(i).take(n) {
|
||||
*t += off;
|
||||
}
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
if times.is_empty() {
|
||||
return None;
|
||||
}
|
||||
times.sort_unstable();
|
||||
return Some(times.into_iter().map(|t| t as f64 / scale).collect());
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -65,3 +65,39 @@ fn a_system_encoder_takes_the_bitrate() {
|
||||
assert!(ok && std::fs::metadata(&out).is_ok_and(|m| m.len() > 500), "ffmpeg encodes with the system encoder's arguments");
|
||||
let _ = std::fs::remove_file(&out);
|
||||
}
|
||||
|
||||
/// An MP4's and a QuickTime file's frame times, read from their own tables, are the ones ffprobe's packets give (up to
|
||||
/// one shift of them all), with B-frames, at a rate that isn't whole, and the same frames come out either way.
|
||||
#[test]
|
||||
fn a_file_s_own_tables_give_ffprobe_s_frame_times() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-ffmpeg-tables-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let make = |name: &str, args: &[&str]| {
|
||||
let p = dir.join(name);
|
||||
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=128x72:r=30000/1001:d=2", "-pix_fmt", "yuv420p"]).args(args).arg(&p).status().is_ok_and(|s| s.success());
|
||||
ok.then_some(p)
|
||||
};
|
||||
let files = [make("b.mp4", &["-c:v", "libx264", "-bf", "3"]), make("b.mov", &["-c:v", "libx264", "-bf", "2", "-g", "12"]), make("plain.mp4", &["-c:v", "mpeg4"])];
|
||||
let mut seen = 0;
|
||||
for f in files.into_iter().flatten() {
|
||||
let Some(tabled) = mov::frame_times(&f) else { panic!("{}: its tables weren't read", f.display()) };
|
||||
let (_, asked, ..) = probe_with(&f, None).unwrap();
|
||||
assert_eq!(tabled.len(), asked.len(), "{}: as many frames", f.display());
|
||||
for (a, b) in tabled.iter().zip(&asked) {
|
||||
assert!(((a - tabled[0]) - (b - asked[0])).abs() < 2e-4, "{}: {a} against {b}", f.display());
|
||||
}
|
||||
// and the decoder gives the same picture at a time either way
|
||||
let (info, pts, ..) = probe(&f).unwrap();
|
||||
assert_eq!(pts.len(), info.frames);
|
||||
let mut d = Ffmpeg.open_video(&f).unwrap();
|
||||
let at = d.frame_at(1.0).unwrap();
|
||||
assert!((at.pts - 1.0).abs() < 0.04, "{}: the frame at 1 s is at {}", f.display(), at.pts);
|
||||
seen += 1;
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
if seen == 0 {
|
||||
eprintln!("skipped: no ffmpeg here to make a file with");
|
||||
}
|
||||
// a file in fragments, or of another kind, is asked of ffprobe as before
|
||||
assert!(mov::frame_times(Path::new("a.webm")).is_none());
|
||||
}
|
||||
@@ -86,7 +86,8 @@ up)
|
||||
# rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest).
|
||||
if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then
|
||||
for i in $(seq 1 90); do
|
||||
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null" | python3 -c 'import json,sys
|
||||
# (a Sprite just made has no server yet: curl's own exit ended this script, 12-01)
|
||||
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null || true" | python3 -c 'import json,sys
|
||||
try: print(json.load(sys.stdin).get("running", "unknown"))
|
||||
except Exception: print("down")')
|
||||
# down: nothing to cut off; unknown: a server too old to say, so it isn't rebuilt blind
|
||||
|
||||
@@ -21,6 +21,11 @@ say packages
|
||||
sudo -E apt-get update -qq
|
||||
sudo -E apt-get install -y -qq --no-install-recommends ca-certificates curl git git-lfs zstd xz-utils procps ripgrep \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools > /dev/null
|
||||
# faces an ad is set in (12-01: a box had Liberation and DejaVu alone, so every cut fell back to Liberation Sans): the
|
||||
# open families brands are closest to, each taken when this Ubuntu has it
|
||||
for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do
|
||||
dpkg -s "$f" > /dev/null 2>&1 || sudo -E apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || say "no $f here"
|
||||
done
|
||||
node -v 2> /dev/null | grep -q '^v24' || {
|
||||
say "node $NODE"
|
||||
curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | sudo tar -xJ -C /opt
|
||||
@@ -103,6 +108,9 @@ cat > /opt/raea-cloud/image/sprite-start.sh << 'EOF'
|
||||
set -a
|
||||
. ~/.raea-cloud.env
|
||||
set +a
|
||||
# footage is read 16 MB ahead: a Sprite's disk answers each read in about 26 ms, and at its own 256 KB a pass over
|
||||
# a 1 GB interview took two minutes that takes 14 s so (12-01, measured). Set at each start: a Sprite woken keeps none.
|
||||
for b in /sys/class/bdi/*/read_ahead_kb /sys/block/*/queue/read_ahead_kb; do sudo sh -c "echo 16384 > $b" 2> /dev/null || true; done
|
||||
export PORT=8080 RAEA_CLOUD_DEVICE=cpu WGPU_BACKEND=vulkan __EGL_VENDOR_LIBRARY_DIRS=/nonexistent
|
||||
export VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1)
|
||||
mkdir -p ~/work
|
||||
|
||||
+25
-12
@@ -40,20 +40,32 @@ export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned
|
||||
if (!s.surprise?.trim() || !MOMENT.test(s.surprise)) found({ says: `${path.basename(f.path)}'s surprise isn't named with its moment ("12.5 s: the dog barks on the punchline")`, fix: `raea goal seen ${f.path} "..." --surprise "SECONDS s: what it is"` })
|
||||
})
|
||||
|
||||
/** what the second opinion is asked of a whole cut, picture and sound (`raea ask`, clef-omni) */
|
||||
/** what the second opinion is asked of a whole cut, picture and sound (`raea ask`, clef-omni): pointed checks, each
|
||||
* a yes when the fault is there. Never "does it look good": asked whether Dutch's plain boxes looked designed, clef
|
||||
* said "strong". 12-01, Shane: "you just have to have them be more specific or pointed like giving it some list of
|
||||
* design checks to answer ... a few catch all checks on visual and audio design"; "the agent itself is really
|
||||
* responsible for design" */
|
||||
export const SECOND = [
|
||||
"Do the on-screen graphics (captions, cards, badges, the end card) look designed for this brand, at the level of a professionally produced social ad, rather than plain boxes of text?",
|
||||
"Is every word that matters large, sharp against what is behind it, and on long enough to read?",
|
||||
"Is the voice clear over everything else, with music and effects marking moments rather than filling space?",
|
||||
"In the first two seconds, is there a picture, a word or a sound that would make this audience stop?",
|
||||
"Is the frame free of clutter throughout: never more than two separate text boxes at once, and no text over a person?",
|
||||
// picture
|
||||
"Are three or more separate text boxes or cards on screen at the same moment at any point?",
|
||||
"Do the captions, cards and badges all look like the same plain rounded box, with nothing but colour telling them apart?",
|
||||
"Is any text too small or too cluttered to read at a glance on a phone?",
|
||||
"Does any text or graphic cover a person's face, or sit cut off at the edge of the frame?",
|
||||
"Is a product or an app shown only as a box of text, and never as the real product or its screen?",
|
||||
"Does the end card hold more than a logo, one line and one thing to do?",
|
||||
"Is there a rendering glitch: a black or frozen frame, torn or blocky video, or a flash?",
|
||||
// sound
|
||||
"Is a voice muffled, distant or hard to understand, or is music louder than the person speaking?",
|
||||
"Is there harsh, shrill or clipping sound, or music that starts or stops abruptly?",
|
||||
"Is there a stretch of dead air, where nothing is said and nothing is heard?",
|
||||
"Is the same sound effect used in the same way more than three times?",
|
||||
]
|
||||
type Opinion = { says?: string; value?: number }
|
||||
type Opinion = { choice?: string; says?: string }
|
||||
|
||||
/** a second opinion on a cut, from clef watching and hearing all of it (12-01, Shane: "the agent itself should be
|
||||
* watching and revising itself always and use clef omni as a secondary opinion or catch all"): each question's grade,
|
||||
* lowest first, kept beside the file (FILE.second.json) for the file as it is now. It's an opinion, never the look:
|
||||
* on 12-01 it graded Dutch's plain boxes "strong". Null where it couldn't be asked. */
|
||||
* watching and revising itself always and use clef omni as a secondary opinion or catch all"): each check, the
|
||||
* faults it found first, kept beside the file (FILE.second.json) for the file as it is now. Null where it couldn't
|
||||
* be asked. */
|
||||
export function second(file: string, ask = askSecond): string | null {
|
||||
const [st, kept] = [statSync(file), `${stem(file)}.second.json`]
|
||||
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
|
||||
@@ -63,11 +75,12 @@ export function second(file: string, ask = askSecond): string | null {
|
||||
} catch {}
|
||||
const got = ask(file)
|
||||
if (got.length !== SECOND.length) return null
|
||||
const says = got.map((o, i) => ({ q: SECOND[i], says: o.says ?? "no answer", value: o.value ?? 0 })).sort((a, b) => a.value - b.value).map((o) => ` ${o.says}: ${o.q}`).join("\n")
|
||||
const rows = got.map((o, i) => ({ q: SECOND[i], found: o.choice === "yes", says: o.says ?? o.choice ?? "no answer" }))
|
||||
const says = [...rows.filter((r) => r.found), ...rows.filter((r) => !r.found)].map((r) => ` ${r.found ? "FOUND" : "clear"} (${r.says}): ${r.q}`).join("\n")
|
||||
writeFileSync(kept, `${JSON.stringify({ render: stamp, says }, null, 1)}\n`)
|
||||
return says
|
||||
}
|
||||
function askSecond(file: string): Opinion[] {
|
||||
const r = spawnSync(RAEA, ["ask", file, ...SECOND, "--grade", "--json", "--brief", "none"], { cwd: path.dirname(file), encoding: "utf8", maxBuffer: 1 << 26 })
|
||||
const r = spawnSync(RAEA, ["ask", file, ...SECOND, "--choose", "yes,no", "--json", "--brief", "none"], { cwd: path.dirname(file), encoding: "utf8", maxBuffer: 1 << 26 })
|
||||
return String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Opinion] : [] } catch { return [] } })
|
||||
}
|
||||
+1
-1
@@ -262,7 +262,7 @@ export async function main(argv: string[]): Promise<number> {
|
||||
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : []
|
||||
// on raea cloud (where the critic is clef), a second opinion on the whole cut with its sound: never the look itself
|
||||
const op = full.length && critic() === "clef" ? second(path.resolve(file)) : null
|
||||
if (op) console.log(`a second opinion (clef watched and heard all of it; lowest first; weigh it, then look yourself):\n${op}`)
|
||||
if (op) console.log(`a second opinion (clef watched and heard all of it and answered a list of checks; a FOUND is a fix or a reason it's wrong; how it looks is still yours to judge, on the frames):\n${op}`)
|
||||
console.log(`${sheet}\n${full.join("\n")}\nlook at every frame of the sheet for what happens, and open each full-size frame for how it looks (type, captions, cards, the end: beside a reference ad's frame, not from the sheet), then: raea goal seen ${file} "what you see and would change"${full.length ? ' --look "its design at full size, beside a reference, and what you changed"' : ""}`)
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -24,12 +24,13 @@ test("a look at the sheet alone doesn't pass: the design is judged at full size,
|
||||
expect(unjudged({ look: "Captions are 72 px bold with the spoken word in yellow, as the reference's; the offer is one pill, not three boxes." })).toBe(false)
|
||||
})
|
||||
|
||||
test("the second opinion is asked once for a file as it is, lowest grade first, and again after it changes", () => {
|
||||
test("the second opinion is asked once for a file as it is, the faults it found first, and again after it changes", () => {
|
||||
const f = put(project({}), "out/cuts/acme_dog_hook1_v1_9x16.mp4", readFileSync(CLIP))
|
||||
let asked = 0
|
||||
const ask = () => (asked++, SECOND.map((_, i) => ({ says: `grade ${i}`, value: SECOND.length - i })))
|
||||
const ask = () => (asked++, SECOND.map((_, i) => ({ choice: i === 3 ? "yes" : "no", says: i === 3 ? "yes (0.81)" : "no (0.9)" })))
|
||||
const says = second(f, ask)!
|
||||
expect(says.split("\n")[0]).toContain(`grade ${SECOND.length - 1}`)
|
||||
expect(says.split("\n")[0]).toBe(` FOUND (yes (0.81)): ${SECOND[3]}`)
|
||||
expect(says.split("\n")[1]).toStartWith(" clear")
|
||||
expect(second(f, ask)).toBe(says)
|
||||
expect(asked).toBe(1)
|
||||
touch(f, 60)
|
||||
|
||||
@@ -195,6 +195,14 @@ if [ -f "$check/raea/bin/raea.exe" ]; then
|
||||
done
|
||||
"$check/raea/bin/uv.exe" --version 2>&1 | grep -q '^uv ' || fail "bin/uv.exe doesn't run"
|
||||
fi
|
||||
# a project whose brief.ts imports React, as its scenes do, and has no node_modules: a render's own checks load brief.ts,
|
||||
# and a render that was applied ended "Cannot find package 'react'" and "render again" (#278). The checks' verdict on
|
||||
# an empty project isn't the point here: that brief.ts ran is
|
||||
mkdir -p "$check/brief" && cp "$check/p/hello.tsx" "$check/brief/hello.tsx"
|
||||
printf '%s\n' 'import { useMemo } from "react"' 'import { goal } from "raea/goal"' 'export const hook = useMemo' 'export default goal({ title: "Check", make: "one short video" })' > "$check/brief/brief.ts"
|
||||
(cd "$check/brief" && RAEA_NO_TREE=1 "$raea" goal check > check.log 2>&1) || true
|
||||
[ -s "$check/brief/check.log" ] || fail "raea goal check said nothing beside a brief.ts that imports react"
|
||||
! grep -q "Cannot find package\|doesn't run" "$check/brief/check.log" || { tail -20 "$check/brief/check.log" >&2; fail "a brief.ts that imports react doesn't run: a package raea ships wasn't found"; }
|
||||
# RAEA_CHECK_HARD=1 (tools/release-machines.sh, on real machines: a PC's own GPU, the Linux box): what reports from
|
||||
# other systems needed and a runner's one pass doesn't show.
|
||||
if [ "${RAEA_CHECK_HARD:-}" = 1 ]; then
|
||||
|
||||
Reference in new issue
Block a user