mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 08:46:06 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0699620e39 | ||
|
|
e5f4743dee | ||
|
|
4aff22e31a | ||
|
|
c863adef82 | ||
|
|
8627ba7ab4 |
No files matched your search
Generated
+3
@@ -13919,6 +13919,7 @@ dependencies = [
|
||||
name = "raea-app-motion"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"raea-sys-kimodo",
|
||||
@@ -16054,7 +16055,9 @@ dependencies = [
|
||||
"anyrender",
|
||||
"anyrender_vello",
|
||||
"blitz-paint",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.44.0",
|
||||
"vello",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
@@ -7,6 +7,8 @@ publish = false
|
||||
description = "`raea motion` and `raea setup motion`: body motion made by Kimodo on this machine, on MLX on a Mac, on PyTorch elsewhere"
|
||||
|
||||
[dependencies]
|
||||
# a take's joints as vectors (score.rs)
|
||||
glam = "0.33"
|
||||
# raea's models folder, where the models and the PyTorch environment go
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
serde_json = "1"
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
//! `raea motion` without the rest of the CLI, for working on this crate while the workspace's other crates are mid-change:
|
||||
//! `lane build -- cargo run --release -p raea-app-motion --example motion -- "LINE" --seeds 4 -o CLIP.json`
|
||||
fn main() {
|
||||
let args: Vec<String> = std::iter::once("motion".to_string()).chain(std::env::args().skip(1)).collect();
|
||||
match raea_app_motion::motion(&args) {
|
||||
Ok(s) => println!("{s}"),
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
-19
@@ -9,12 +9,14 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
mod score;
|
||||
|
||||
use raea_runtime_bundle::flag;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
|
||||
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. --seeds N makes N takes (seeds SEED to SEED+N-1) and keeps the one with the fewest faults: a foot sliding while planted, the shoulders shrugging, the hips sinking, a hand or forearm into the torso or head (a skeletal check; each take's score is printed and the kept one's written into the clip). Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
|
||||
|
||||
pub const SETUP_USAGE: &str = "raea setup motion [--check]";
|
||||
pub const SETUP_ABOUT: &str = "what raea motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
|
||||
@@ -27,7 +29,7 @@ fn number(args: &[String], name: &str, default: f64) -> R<f64> {
|
||||
}
|
||||
|
||||
fn line(args: &[String]) -> String {
|
||||
const WITH_VALUE: [&str; 6] = ["--keys", "--seconds", "--frames", "--seed", "--steps", "-o"];
|
||||
const WITH_VALUE: [&str; 7] = ["--keys", "--seconds", "--frames", "--seed", "--seeds", "--steps", "-o"];
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
@@ -50,6 +52,7 @@ struct Ask {
|
||||
constraints: Option<serde_json::Value>,
|
||||
frames: usize,
|
||||
seed: u64,
|
||||
seeds: usize,
|
||||
steps: usize,
|
||||
out: Option<String>,
|
||||
}
|
||||
@@ -64,15 +67,21 @@ pub fn motion(args: &[String]) -> R<String> {
|
||||
Some(_) => number(args, "--frames", 150.0)? as usize,
|
||||
None => (number(args, "--seconds", 5.0)? * 30.0).round() as usize,
|
||||
};
|
||||
if !(2..=600).contains(&frames) {
|
||||
return Err(format!("a clip is 2 to 600 frames (20 s at 30 a second), asked {frames}"));
|
||||
// Kimodo's own limit (its docs, key_concepts/limitations.md): past 10 s a clip drifts and breaks up (11-27: a
|
||||
// 12.3 s talk clip's feet spread 47 -> 69 cm, shoulders rose 9 cm, the last half second glitched)
|
||||
if !(2..=300).contains(&frames) {
|
||||
return Err(format!(
|
||||
"a clip is 2 to 300 frames (10 s at 30 a second, Kimodo's limit: longer clips drift and break up), asked {frames}; \
|
||||
for longer, make 10 s clips one after another, each from --keys holding the last frames of the one before"
|
||||
));
|
||||
}
|
||||
let constraints = match &keys {
|
||||
Some(p) => Some(serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?),
|
||||
None => None,
|
||||
};
|
||||
let (seed, steps) = (number(args, "--seed", 1.0)? as u64, (number(args, "--steps", 100.0)? as usize).max(2));
|
||||
make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })
|
||||
let seeds = (number(args, "--seeds", 1.0)? as usize).clamp(1, 32);
|
||||
make(Ask { words, keys, constraints, frames, seed, seeds, steps, out: flag(args, "-o") })
|
||||
}
|
||||
|
||||
/// -o, else a file named by the line's words in the working folder
|
||||
@@ -83,6 +92,25 @@ fn out_path(out: Option<String>, clean: &str) -> PathBuf {
|
||||
}))
|
||||
}
|
||||
|
||||
/// the take with the lowest score of those made, its seed, and a line per take ("" for a single take)
|
||||
fn keep_best(takes: Vec<(u64, raea_sys_kimodo::decode::Motion)>, sk: &raea_sys_kimodo::skeleton::Skeleton) -> (u64, raea_sys_kimodo::decode::Motion, Option<score::Score>, String) {
|
||||
let one = takes.len() == 1;
|
||||
let mut scored: Vec<(u64, raea_sys_kimodo::decode::Motion, score::Score)> = takes.into_iter().map(|(s, m)| { let sc = score::score(&m, sk); (s, m, sc) }).collect();
|
||||
let report = if one { String::new() } else { scored.iter().map(|(s, _, sc)| format!("\n seed {s}: {}", sc.line())).collect::<String>() };
|
||||
scored.sort_by(|a, b| a.2.total.total_cmp(&b.2.total));
|
||||
let (s, m, sc) = scored.remove(0);
|
||||
(s, m, Some(sc), report)
|
||||
}
|
||||
|
||||
/// the kept take's score, written into the clip
|
||||
fn with_score(mut clip: serde_json::Value, sc: &Option<score::Score>, tried: usize) -> serde_json::Value {
|
||||
if let Some(sc) = sc {
|
||||
clip["score"] = serde_json::json!({"total": sc.total, "foot_drift_cm": sc.foot_drift_cm, "shoulder_rise_cm": sc.shoulder_rise_cm,
|
||||
"hip_drop_cm": sc.hip_drop_cm, "collision_cm": sc.collision_cm, "takes": tried});
|
||||
}
|
||||
clip
|
||||
}
|
||||
|
||||
/// how far the hips end from where they start, on the ground
|
||||
fn travel(m: &raea_sys_kimodo::decode::Motion) -> f32 {
|
||||
let r = &m.root;
|
||||
@@ -109,10 +137,17 @@ fn make(ask: Ask) -> R<String> {
|
||||
));
|
||||
}
|
||||
let keys = ask.keys.as_ref().map(std::path::Path::new);
|
||||
let job = torch::Job { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, keys, cfg: (2.0, 2.0) };
|
||||
let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let (stats, sk) = (Stats::load(&t.checkpoint).map_err(|e| format!("raea motion: {e}"))?, Skeleton::soma().map_err(|e| format!("raea motion: {e}"))?);
|
||||
let motion = decode::decode(&made.features, &stats, &sk);
|
||||
let mut takes = Vec::new();
|
||||
let mut last = None;
|
||||
for s in ask.seed..ask.seed + ask.seeds as u64 {
|
||||
let job = torch::Job { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, keys, cfg: (2.0, 2.0) };
|
||||
let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;
|
||||
takes.push((s, decode::decode(&made.features, &stats, &sk)));
|
||||
last = Some(made);
|
||||
}
|
||||
let made = last.ok_or("raea motion: no take")?;
|
||||
let (seed, motion, sc, report) = keep_best(takes, &sk);
|
||||
let info = &made.info;
|
||||
let clean = info["line"].as_str().unwrap_or(&ask.words).to_string();
|
||||
let (dev, text_dev) = (info["motion"].as_str().unwrap_or("?"), info["text"].as_str().unwrap_or("?"));
|
||||
@@ -120,26 +155,28 @@ fn make(ask: Ask) -> R<String> {
|
||||
Some(g) => format!("on PyTorch {} with CUDA ({g}; the text encoder on {text_dev}), upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
|
||||
None => format!("on PyTorch {} on the CPU, upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
|
||||
};
|
||||
let clip = decode::clip_json_on(&motion, &sk, ask.seed, ask.steps, &clean, ask.constraints.is_some(), &on);
|
||||
let clip = with_score(decode::clip_json_on(&motion, &sk, seed, ask.steps, &clean, ask.constraints.is_some(), &on), &sc, ask.seeds);
|
||||
let out = out_path(ask.out, &clean);
|
||||
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
// the hips as PyTorch decoded them against decode.rs's: the features were read as Kimodo wrote them
|
||||
let ours: Vec<[f32; 3]> = motion.joints77.iter().map(|f| f[0]).collect();
|
||||
let gap = torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default();
|
||||
let gap = if ask.seeds > 1 { String::new() } else { torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default() };
|
||||
let f = |k: &str| info[k].as_f64().unwrap_or(0.0);
|
||||
let read = if f("read_s") > 0.0 { format!(", reading the line {:.1} s after {:.1} s loading its encoder", f("read_s"), f("text_load_s")) } else { String::new() };
|
||||
Ok(format!(
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap})",
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap}; {}){report}",
|
||||
clean,
|
||||
if ask.keys.is_some() { " with keys" } else { "" },
|
||||
ask.frames,
|
||||
ask.frames as f64 / 30.0,
|
||||
ask.seed,
|
||||
seed,
|
||||
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
|
||||
ask.steps,
|
||||
out.display(),
|
||||
f("gen_s"),
|
||||
f("load_s"),
|
||||
travel(&motion),
|
||||
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -154,23 +191,29 @@ fn make(ask: Ask) -> R<String> {
|
||||
let mut k = raea_sys_kimodo::Kimodo::fetch(&mut progress).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let (clean, emb) = k.encode(&ask.words).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let load_s = t0.elapsed().as_secs_f64();
|
||||
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
|
||||
let t1 = std::time::Instant::now();
|
||||
let made = k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let mut takes = Vec::new();
|
||||
for s in ask.seed..ask.seed + ask.seeds as u64 {
|
||||
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
|
||||
takes.push((s, k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?.motion));
|
||||
}
|
||||
let gen_s = t1.elapsed().as_secs_f64();
|
||||
let clip = raea_sys_kimodo::decode::clip_json(&made.motion, &k.skeleton, ask.seed, ask.steps, &clean, ask.constraints.is_some());
|
||||
let (seed, motion, sc, report) = keep_best(takes, &k.skeleton);
|
||||
let clip = with_score(raea_sys_kimodo::decode::clip_json(&motion, &k.skeleton, seed, ask.steps, &clean, ask.constraints.is_some()), &sc, ask.seeds);
|
||||
let out = out_path(ask.out, &clean);
|
||||
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
Ok(format!(
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start)",
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start; {}){report}",
|
||||
clean,
|
||||
if ask.keys.is_some() { " with keys" } else { "" },
|
||||
ask.frames,
|
||||
ask.frames as f64 / 30.0,
|
||||
ask.seed,
|
||||
seed,
|
||||
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
|
||||
ask.steps,
|
||||
out.display(),
|
||||
travel(&made.motion)
|
||||
travel(&motion),
|
||||
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! A take scored for the faults a body shows (sheet3d plan E3), so `raea motion --seeds N` can keep the best of N:
|
||||
//! a foot sliding while it's planted, the shoulders shrugging up, the hips sinking, and a hand or forearm inside the
|
||||
//! torso or head. Read from the take's own joints (Kimodo's SOMA skeleton, metres, Y up) and its foot contacts.
|
||||
//! Collision is a skeletal proxy: capsules round the spine and a sphere for the head, sized for SOMA's average adult;
|
||||
//! the mesh check on the body a clip drives is the join's (sheet3d's join.py: head-in-body frames).
|
||||
|
||||
use raea_sys_kimodo::decode::Motion;
|
||||
use raea_sys_kimodo::skeleton::Skeleton;
|
||||
|
||||
use glam::Vec3;
|
||||
|
||||
/// each fault in centimetres (collision: the deepest a hand or forearm point goes into the torso or head), and
|
||||
/// their sum, each over its own allowance: 1 cm of drift, 3 cm of shrug, 5 cm of sinking, 1 cm into the body
|
||||
pub struct Score {
|
||||
pub foot_drift_cm: f32,
|
||||
pub shoulder_rise_cm: f32,
|
||||
pub hip_drop_cm: f32,
|
||||
pub collision_cm: f32,
|
||||
pub total: f32,
|
||||
}
|
||||
|
||||
fn idx(sk: &Skeleton, n: &str) -> usize {
|
||||
sk.names77.iter().position(|x| x == n).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// how far p is inside the capsule a-b of radius r (0 outside)
|
||||
fn inside(p: [f32; 3], a: [f32; 3], b: [f32; 3], r: f32) -> f32 {
|
||||
let (p, a, b) = (Vec3::from(p), Vec3::from(a), Vec3::from(b));
|
||||
let ab = b - a;
|
||||
let t = ((p - a).dot(ab) / ab.length_squared().max(1e-9)).clamp(0.0, 1.0);
|
||||
(r - p.distance(a + t * ab)).max(0.0)
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f32>) -> f32 {
|
||||
if v.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
v.sort_by(|a, b| a.total_cmp(b));
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
pub fn score(m: &Motion, sk: &Skeleton) -> Score {
|
||||
let j = &m.joints77;
|
||||
let n = j.len();
|
||||
// a foot planted: its horizontal travel over each run of contact frames, the worst run
|
||||
let feet = [("LeftFoot", 0), ("LeftToeBase", 1), ("RightFoot", 3), ("RightToeBase", 4)];
|
||||
let mut drift = 0f32;
|
||||
for (name, c) in feet {
|
||||
let k = idx(sk, name);
|
||||
let mut start: Option<usize> = None;
|
||||
for f in 0..=n {
|
||||
let on = f < n && m.contacts[f][c];
|
||||
match (on, start) {
|
||||
(true, None) => start = Some(f),
|
||||
(false, Some(s)) => {
|
||||
let mut far = 0f32;
|
||||
for g in s..f {
|
||||
let d = Vec3::from(j[g][k]) - Vec3::from(j[s][k]);
|
||||
far = far.max(d.x.hypot(d.z));
|
||||
}
|
||||
drift = drift.max(far);
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// shoulders above the chest: the highest against the take's own usual, both sides
|
||||
let chest = idx(sk, "Chest");
|
||||
let mut rise = 0f32;
|
||||
for s in ["LeftShoulder", "RightShoulder"] {
|
||||
let k = idx(sk, s);
|
||||
let h: Vec<f32> = j.iter().map(|f| f[k][1] - f[chest][1]).collect();
|
||||
let med = median(h.clone());
|
||||
rise = rise.max(h.iter().fold(f32::MIN, |a, &b| a.max(b)) - med);
|
||||
}
|
||||
// hips below where they stand: the lowest against the first second's median
|
||||
let hips = idx(sk, "Hips");
|
||||
let stand = median(j.iter().take(30).map(|f| f[hips][1]).collect());
|
||||
let drop = (stand - j.iter().fold(f32::MAX, |a, f| a.min(f[hips][1]))).max(0.0);
|
||||
// hands and forearms against the torso (hips to chest, chest to neck) and the head
|
||||
let (spine1, neck, head) = (idx(sk, "Spine1"), idx(sk, "Neck1"), idx(sk, "Head"));
|
||||
let limbs: Vec<usize> = ["LeftHand", "RightHand", "LeftHandMiddle1", "RightHandMiddle1"].iter().map(|x| idx(sk, x)).collect();
|
||||
let fore = [("LeftArm", "LeftForeArm", "LeftHand"), ("RightArm", "RightForeArm", "RightHand")];
|
||||
let mut deep = 0f32;
|
||||
for f in j {
|
||||
let mut pts: Vec<[f32; 3]> = limbs.iter().map(|&k| f[k]).collect();
|
||||
for (_, e, h) in fore {
|
||||
let (a, b) = (f[idx(sk, e)], f[idx(sk, h)]);
|
||||
pts.push([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, (a[2] + b[2]) / 2.0]);
|
||||
}
|
||||
for p in pts {
|
||||
let d = inside(p, f[hips], f[spine1], 0.12)
|
||||
.max(inside(p, f[spine1], f[chest], 0.13))
|
||||
.max(inside(p, f[chest], f[neck], 0.11))
|
||||
.max(inside(p, f[head], f[head], 0.09));
|
||||
deep = deep.max(d);
|
||||
}
|
||||
}
|
||||
let (d, r, h, c) = (drift * 100.0, rise * 100.0, drop * 100.0, deep * 100.0);
|
||||
Score { foot_drift_cm: d, shoulder_rise_cm: r, hip_drop_cm: h, collision_cm: c, total: d / 1.0 + r / 3.0 + h / 5.0 + c / 1.0 }
|
||||
}
|
||||
|
||||
impl Score {
|
||||
pub fn line(&self) -> String {
|
||||
format!(
|
||||
"score {:.2} (foot drift {:.1} cm, shoulder rise {:.1} cm, hip drop {:.1} cm, hand into body {:.1} cm)",
|
||||
self.total, self.foot_drift_cm, self.shoulder_rise_cm, self.hip_drop_cm, self.collision_cm
|
||||
)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -139,8 +139,8 @@ Feature: The Linux engine, as fast as it can be in the cloud
|
||||
Scenario: LX7. The clipping check never makes a render wait
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-contact | systems/contact/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
|
||||
| raea-sys-contact | systems/contact/src/clip.rs | 178 | the frames checked on the cores the render leaves idle: Clipping takes each frame as it's drawn since SG4a (docs/stage-guards.feature), so off the render's thread |
|
||||
| raea-sys-clip | systems/clip/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
|
||||
| raea-sys-clip | systems/clip/src/lib.rs | 178 | the frames checked on the cores the render leaves idle: Clipping takes each frame as it's drawn since SG4a (docs/stage-guards.feature), so off the render's thread. The clipping check moves here from raea-sys-contact's clip.rs (11-29: contact plus a broad phase would pass 2000 lines), using contact's deepest, Hit and solid cache as its public interface |
|
||||
Then edit.tsx's clipping check takes at most its frames' own time (from 96.1 s), and RR0's film's at most 300 ms
|
||||
And a render's wall with the check on is within 3% of RAEA_CLIP_CHECK=0
|
||||
And the findings are identical on the RR0 film, edit.tsx and the contact fixtures (systems/contact's tests)
|
||||
|
||||
@@ -12,7 +12,7 @@ Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTo
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json] (body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0)
|
||||
raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json] (body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. --seeds N makes N takes (seeds SEED to SEED+N-1) and keeps the one with the fewest faults: a foot sliding while planted, the shoulders shrugging, the hips sinking, a hand or forearm into the torso or head (a skeletal check; each take's score is printed and the kept one's written into the clip). Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
@@ -21,10 +21,11 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--frames` | `N` | The clip's length in frames at 30 a second, 2 to 600. Instead of `--seconds`. |
|
||||
| `--frames` | `N` | The clip's length in frames at 30 a second, 2 to 300 (10 s, Kimodo's limit: longer clips drift and break up; chain 10 s clips through `--keys` instead). Instead of `--seconds`. |
|
||||
| `--keys` | `KEYS.json` | Kimodo constraints the motion must meet: full-body keyframes, a hand or foot at a place on a frame, a path for the hips. `bun sdk/body/tools/between.ts` writes them between two poses of the body library. |
|
||||
| `--seconds` | `5` | The clip's length in seconds (5 unless said). |
|
||||
| `--seed` | `1` | Which of the motions the line could be: another seed is another take of the same line. A seed on MLX is not that seed on PyTorch (the noise is drawn differently), so the same seed is a different take on a Mac and on Linux or Windows. |
|
||||
| `--seeds` | `1` | How many takes to make, seeds `--seed` up: the one with the lowest score is kept and its score written into the clip (`score`: foot drift while a foot is planted, shoulder rise above the take's usual, hip drop below standing, and how far a hand or forearm goes into the torso or head, in cm, summed over allowances of 1, 3, 5 and 1 cm). The collision is a skeletal check, capsules sized for SOMA's average adult, not the body's mesh. |
|
||||
| `--steps` | `100` | Denoising steps (Kimodo's 100). Fewer is faster and rougher. |
|
||||
| `-o` | `CLIP.json` | Where the clip goes: `{fps, names, root, turns, contacts, ...}`, Kimodo's 77 SOMA joints as each one's turn in the world from the T-pose. Without it, the line's words name the file in the working folder. |
|
||||
|
||||
@@ -40,6 +41,16 @@ bun sdk/body/tools/between.ts skeleton.json LIBDIR aMale2_A1_Stand:0 aMale2_A1_S
|
||||
raea motion "A person waves at the camera with their right hand" --keys stand.json --seconds 4 --seed 2 -o wave.clip.json
|
||||
```
|
||||
|
||||
The best of four takes of a line, by the faults a body would show:
|
||||
|
||||
```sh
|
||||
raea motion "A person stands in place and talks, gesturing with both hands" --seconds 10 --seeds 4 -o talk.clip.json
|
||||
```
|
||||
|
||||
Longer than 10 s, make 10 s clips one after another, each with `--keys` holding the last second of the one before as
|
||||
full-body keyframes, and ease each into the next over those frames: Kimodo keeps full-body keys to a few centimetres,
|
||||
not exactly, so a clip cut straight onto the next would jump.
|
||||
|
||||
A clip takes about 8 seconds on an M5 Pro. `bun sdk/body/tools/makedo.ts` does the whole of it for a stage's lines:
|
||||
three seeds a line, each checked against the captures the body hands on to, and the one that does the most kept in the
|
||||
project's made clips.
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// The joins bench: the same picks from real talking takes cut five ways, each clip written out to be heard again.
|
||||
// bun bench.ts DATA OUT TAKE... (run.sh runs it; DATA holds TAKE.wav, 16 kHz mono, and TAKE.words.json)
|
||||
//
|
||||
// Picks: every other sentence (twice, odd and even), and every other clause (cut at , ; : too: the hard case, edges
|
||||
// inside connected speech). Arms, each on the same spans except B:
|
||||
// A raea cut today (edgesOf, src/joins.ts)
|
||||
// B the feed host today (apps/app/host/take.ts cut: 0.06 s pads, pauses over 0.4 s cut out); sentences only
|
||||
// D A mended without measuring: a lead-in and tail of 0.06 s at least where words abut, the grid outward
|
||||
// M measured placement: from where the sound starts and stops, on quiet, frame grid included
|
||||
// H M where the take has quiet beside the edge, A where it hasn't
|
||||
// Writes OUT/<arm>-<take>-<pick>.wav (the clips with 0.8 s of silence between) and OUT/clips.json for judge.ts.
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { edgesOf, joinsOf, levelsOfWav, type Levels, type Word } from "../../src/joins.ts";
|
||||
import { cut as feedCut, type Sentence } from "../../../../apps/app/host/take.ts";
|
||||
|
||||
const [data, out, ...takes] = process.argv.slice(2);
|
||||
if (!data || !out || !takes.length) throw new Error("bench.ts DATA OUT TAKE...");
|
||||
mkdirSync(out, { recursive: true });
|
||||
const FPS = 30;
|
||||
const RATE = 16000;
|
||||
|
||||
// ---- arm D: A's shares with a floor, rounded away from the words -----------------------------------------------
|
||||
function mended(ws: Word[], spans: [number, number][], least = 0.06): [number, number][] {
|
||||
const sf = 1 / FPS;
|
||||
const mid = (w: Word) => (w.from + w.to) / 2;
|
||||
return spans.map(([i, j], k): [number, number] => {
|
||||
const before = i > 0 ? ws[i].from - ws[i - 1].to : 0.4;
|
||||
const after = j + 1 < ws.length ? ws[j + 1].from - ws[j].to : 0.6;
|
||||
const lo = i > 0 ? mid(ws[i - 1]) : 0;
|
||||
const hi = j + 1 < ws.length ? mid(ws[j + 1]) : Infinity;
|
||||
let a = Math.max(lo, ws[i].from - Math.max(least, Math.min(before * 0.6, 0.12)));
|
||||
let b = Math.min(hi, ws[j].to + Math.max(least, Math.min(after * 0.7, k + 1 === spans.length ? 0.35 : 0.22)));
|
||||
const af = Math.floor(a / sf + 1e-6) * sf;
|
||||
const bc = Math.ceil(b / sf - 1e-6) * sf;
|
||||
a = af >= lo ? af : Math.ceil(a / sf - 1e-6) * sf;
|
||||
b = bc <= hi ? bc : Math.floor(b / sf + 1e-6) * sf;
|
||||
return [Math.max(0, a), Math.max(a + sf, b)];
|
||||
});
|
||||
}
|
||||
|
||||
// ---- arms M and H: placed on the take's sound ------------------------------------------------------------------
|
||||
const quietAt = (lv: Levels, k: number) => k < 0 || k >= lv.db.length || lv.db[k] < lv.quiet;
|
||||
/** the end of the last quiet run (4 hops) going back from hi to lo, and where that run began */
|
||||
function onset(lv: Levels, lo: number, hi: number) {
|
||||
let run = 0;
|
||||
for (let k = Math.floor(hi / 0.01); k >= Math.floor(lo / 0.01); k--) {
|
||||
if (!quietAt(lv, k)) { run = 0; continue; }
|
||||
if (++run < 4) continue;
|
||||
let start = k;
|
||||
while (start - 1 >= Math.floor(lo / 0.01) && quietAt(lv, start - 1)) start--;
|
||||
return { at: (k + run) * 0.01, quietFrom: start * 0.01 };
|
||||
}
|
||||
}
|
||||
/** the start of the first quiet run going on from lo to hi, and where it ends */
|
||||
function release(lv: Levels, lo: number, hi: number) {
|
||||
let run = 0;
|
||||
for (let k = Math.floor(lo / 0.01); k <= Math.floor(hi / 0.01); k++) {
|
||||
if (!quietAt(lv, k)) { run = 0; continue; }
|
||||
if (++run < 4) continue;
|
||||
let end = k;
|
||||
while (end + 1 <= Math.floor(hi / 0.01) && quietAt(lv, end + 1)) end++;
|
||||
return { at: (k - run + 1) * 0.01, quietTo: (end + 1) * 0.01 };
|
||||
}
|
||||
}
|
||||
function quietest(lv: Levels, a: number, b: number) {
|
||||
let best = Math.floor(a / 0.01);
|
||||
for (let k = best; k <= Math.floor(b / 0.01); k++) if (k >= 0 && k < lv.db.length && lv.db[k] < lv.db[best]) best = k;
|
||||
return best * 0.01 + 0.005;
|
||||
}
|
||||
/** M (fallback "quietest") or H (fallback A's edge) */
|
||||
function measured(ws: Word[], spans: [number, number][], lv: Levels, fallback: "quietest" | "A"): { edges: [number, number][]; quiet: [boolean, boolean][] } {
|
||||
const sf = 1 / FPS;
|
||||
const mid = (w: Word) => (w.from + w.to) / 2;
|
||||
const padded = edgesOf(ws, spans, FPS);
|
||||
const end = lv.db.length * 0.01;
|
||||
const quiet: [boolean, boolean][] = [];
|
||||
const edges = spans.map(([i, j], s): [number, number] => {
|
||||
const [first, last] = [ws[i], ws[j]];
|
||||
const loA = i > 0 ? Math.max(mid(ws[i - 1]), first.from - 0.8) : Math.max(0, first.from - 0.8);
|
||||
const hiB = j + 1 < ws.length ? Math.min(mid(ws[j + 1]), last.to + 1.2) : Math.min(end, last.to + 1.2);
|
||||
let a: number;
|
||||
const on = onset(lv, loA, first.from);
|
||||
if (on) {
|
||||
a = on.at - Math.min(0.12, (on.at - on.quietFrom) * 0.6);
|
||||
const [lo, up] = [Math.floor(a / sf + 1e-6) * sf, Math.ceil(a / sf - 1e-6) * sf];
|
||||
a = lo >= on.quietFrom ? lo : up < on.at ? up : lo;
|
||||
} else a = fallback === "A" ? padded[s][0] : Math.floor(quietest(lv, loA, first.from) / sf + 1e-6) * sf;
|
||||
let b: number;
|
||||
const off = release(lv, last.to, hiB);
|
||||
if (off) {
|
||||
b = off.at + Math.min(s + 1 === spans.length ? 0.35 : 0.22, (off.quietTo - off.at) * 0.7);
|
||||
const [lo, up] = [Math.floor(b / sf + 1e-6) * sf, Math.ceil(b / sf - 1e-6) * sf];
|
||||
b = up <= off.quietTo ? up : lo > off.at ? lo : up;
|
||||
} else b = fallback === "A" ? padded[s][1] : Math.ceil(quietest(lv, last.to, hiB) / sf - 1e-6) * sf;
|
||||
quiet.push([!!on, !!off]);
|
||||
return [Math.max(0, a), Math.max(a + sf, b)];
|
||||
});
|
||||
return { edges, quiet };
|
||||
}
|
||||
|
||||
// ---- WAV in and out --------------------------------------------------------------------------------------------
|
||||
function pcmOf(bytes: Uint8Array): Int16Array {
|
||||
const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
for (let p = 12; p + 8 <= v.byteLength; ) {
|
||||
const size = v.getUint32(p + 4, true);
|
||||
if (String.fromCharCode(...bytes.subarray(p, p + 4)) === "data") return new Int16Array(bytes.slice(p + 8, p + 8 + size).buffer);
|
||||
p += 8 + size + (size & 1);
|
||||
}
|
||||
throw new Error("no data chunk");
|
||||
}
|
||||
function wavOf(pcm: Int16Array): Uint8Array {
|
||||
const b = new Uint8Array(44 + pcm.length * 2);
|
||||
const v = new DataView(b.buffer);
|
||||
const s = (o: number, t: string) => [...t].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));
|
||||
s(0, "RIFF"); v.setUint32(4, 36 + pcm.length * 2, true); s(8, "WAVE"); s(12, "fmt ");
|
||||
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true); v.setUint32(24, RATE, true);
|
||||
v.setUint32(28, RATE * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true); s(36, "data"); v.setUint32(40, pcm.length * 2, true);
|
||||
new Int16Array(b.buffer, 44).set(pcm);
|
||||
return b;
|
||||
}
|
||||
|
||||
// ---- the picks, cut and written --------------------------------------------------------------------------------
|
||||
type Clip = { take: string; a: number; b: number; at: number; len: number; want?: [number, number]; q?: [boolean, boolean] };
|
||||
const clips: Record<string, Clip[]> = {};
|
||||
const words: Record<string, Word[]> = {};
|
||||
const runs = (ws: Word[], ends: RegExp) => {
|
||||
const out: [number, number][] = [];
|
||||
let s = 0;
|
||||
ws.forEach((w, i) => { if (ends.test(w.text) || i === ws.length - 1) { out.push([s, i]); s = i + 1; } });
|
||||
return out;
|
||||
};
|
||||
for (const take of takes) {
|
||||
const bytes = new Uint8Array(readFileSync(`${data}/${take}.wav`));
|
||||
const pcm = pcmOf(bytes);
|
||||
const lv = levelsOfWav(bytes);
|
||||
const raw = JSON.parse(readFileSync(`${data}/${take}.words.json`, "utf8")) as { text: string; start_ms: number; end_ms: number }[];
|
||||
const ws: Word[] = raw.filter((w) => w.text.trim()).map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 }));
|
||||
words[take] = ws;
|
||||
const sents = runs(ws, /[.?!]$/);
|
||||
const clauses = runs(ws, /[.?!,;:]$/);
|
||||
const sentences: Sentence[] = sents.map(([a, b], i) => ({ i, start: ws[a].from, end: ws[b].to, text: "", words: ws.slice(a, b + 1).map((w) => ({ text: w.text, start: w.from, end: w.to })) }));
|
||||
for (const pick of [0, 1, 2]) {
|
||||
const picked = sents.map((_, i) => i).filter((i) => i % 2 === pick);
|
||||
const spans = pick < 2 ? picked.map((i) => sents[i]) : clauses.filter((_, i) => i % 2 === 1);
|
||||
const h = measured(ws, spans, lv, "A");
|
||||
// the flag raea cut prints, on the edges it places
|
||||
const flags = joinsOf(ws, spans, lv, edgesOf(ws, spans, FPS)).quiet;
|
||||
const arms: Record<string, [number, number][]> = {
|
||||
A: edgesOf(ws, spans, FPS),
|
||||
...(pick < 2 ? { B: feedCut(sentences, picked, FPS).segments } : {}),
|
||||
D: mended(ws, spans),
|
||||
M: measured(ws, spans, lv, "quietest").edges,
|
||||
H: h.edges,
|
||||
};
|
||||
for (const [arm, segs] of Object.entries(arms)) {
|
||||
const key = `${arm}-${take}-${pick}`;
|
||||
const gap = new Int16Array(Math.round(0.8 * RATE));
|
||||
const parts: Int16Array[] = [];
|
||||
let at = 0;
|
||||
clips[key] = segs.map(([a, b], n) => {
|
||||
const seg = pcm.subarray(Math.round(a * RATE), Math.round(b * RATE));
|
||||
const c: Clip = { take, a, b, at: at / RATE, len: seg.length / RATE, ...(arm === "B" ? {} : { want: spans[n], q: flags[n] }) };
|
||||
parts.push(seg, gap);
|
||||
at += seg.length + gap.length;
|
||||
return c;
|
||||
});
|
||||
const all = new Int16Array(at);
|
||||
let o = 0;
|
||||
for (const p of parts) { all.set(p, o); o += p.length; }
|
||||
writeFileSync(`${out}/${key}.wav`, wavOf(all));
|
||||
}
|
||||
}
|
||||
}
|
||||
writeFileSync(`${out}/clips.json`, JSON.stringify(clips));
|
||||
writeFileSync(`${out}/words.json`, JSON.stringify(words));
|
||||
console.log(`${Object.keys(clips).length} clip files, ${Object.values(clips).reduce((n, c) => n + c.length, 0)} clips`);
|
||||
@@ -0,0 +1,105 @@
|
||||
// The joins bench's judge: each clip heard again (parakeet-mlx, OUT/heard/*.json, run.sh), and each edge graded.
|
||||
// bun judge.ts OUT
|
||||
//
|
||||
// An edge's word is its span's first (last) word that isn't a filler or bare punctuation. lost: it isn't among the
|
||||
// first (last) three words heard in the clip. bleed: it is, but a word was heard before (after) it: the neighbour's.
|
||||
// A defect is either. Heard words go to the clip their middle falls in; a clip heard empty (parakeet sometimes skips
|
||||
// a file's tail) is left out of every comparison it's in. Paired comparisons are A against each arm on the same edges
|
||||
// (an exact sign test on the edges where they differ); B cuts different spans and is only compared overall.
|
||||
// Then: does "no pause beside the edge" (joins.ts) find the defects, and does a gap in the transcript?
|
||||
import { readFileSync } from "node:fs";
|
||||
import { wordsOf } from "../../src/heard.ts";
|
||||
|
||||
const out = process.argv[2];
|
||||
if (!out) throw new Error("judge.ts OUT");
|
||||
type Clip = { take: string; a: number; b: number; at: number; len: number; want?: [number, number]; q?: [boolean, boolean] };
|
||||
const clips = JSON.parse(readFileSync(`${out}/clips.json`, "utf8")) as Record<string, Clip[]>;
|
||||
const words = JSON.parse(readFileSync(`${out}/words.json`, "utf8")) as Record<string, { text: string; from: number; to: number }[]>;
|
||||
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}']/gu, "");
|
||||
const FILL = new Set(["uh", "um", "uhm", "mm", "hmm", "er", "ah", "oh"]);
|
||||
const real = (n: string) => !!n && !FILL.has(n);
|
||||
|
||||
type Edge = { lost: boolean; bleed: boolean; quiet?: boolean; gap?: number } | null;
|
||||
const graded: Record<string, Edge[]> = {};
|
||||
for (const [key, cs] of Object.entries(clips)) {
|
||||
const heard = JSON.parse(readFileSync(`${out}/heard/${key}.json`, "utf8")) as { sentences: { tokens: { text: string; start: number; end: number }[] }[] };
|
||||
const byClip = cs.map(() => [] as string[]);
|
||||
for (const w of heard.sentences.flatMap((s) => wordsOf(s.tokens))) {
|
||||
const n = norm(w.text);
|
||||
if (!real(n)) continue;
|
||||
const m = (w.start + w.end) / 2;
|
||||
const k = cs.findIndex((c) => m >= c.at - 0.3 && m < c.at + c.len + 0.3);
|
||||
if (k >= 0) byClip[k].push(n);
|
||||
}
|
||||
graded[key] = cs.flatMap((c, i) => {
|
||||
const ws = words[c.take];
|
||||
const span = c.want ? ws.slice(c.want[0], c.want[1] + 1) : ws.filter((w) => (w.from + w.to) / 2 >= c.a && (w.from + w.to) / 2 <= c.b);
|
||||
const exp = span.map((w) => norm(w.text)).filter(real);
|
||||
return [0, 1].map((side): Edge => {
|
||||
if (!exp.length || !byClip[i].length) return null;
|
||||
const want = side === 0 ? exp[0] : exp[exp.length - 1];
|
||||
const seq = side === 0 ? byClip[i] : [...byClip[i]].reverse();
|
||||
const k = seq.slice(0, 3).indexOf(want);
|
||||
const gap = c.want && (side === 0 ? (c.want[0] > 0 ? ws[c.want[0]].from - ws[c.want[0] - 1].to : 9) : (c.want[1] + 1 < ws.length ? ws[c.want[1] + 1].from - ws[c.want[1]].to : 9));
|
||||
return { lost: k < 0, bleed: k > 0, quiet: c.q?.[side], gap };
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const pct = (x: number, n: number) => `${((100 * x) / Math.max(1, n)).toFixed(1)}%`;
|
||||
const arms = [...new Set(Object.keys(graded).map((k) => k.split("-")[0]))].sort();
|
||||
console.log("Overall (every judged edge of each arm)");
|
||||
for (const arm of arms) {
|
||||
const e = Object.entries(graded).filter(([k]) => k.startsWith(`${arm}-`)).flatMap(([, v]) => v).filter((x): x is NonNullable<Edge> => !!x);
|
||||
const [l, b] = [e.filter((x) => x.lost).length, e.filter((x) => x.bleed).length];
|
||||
console.log(` ${arm} ${String(e.length).padStart(4)} edges lost ${pct(l, e.length).padStart(6)} bleed ${pct(b, e.length).padStart(6)} defects ${pct(l + b, e.length).padStart(6)}`);
|
||||
}
|
||||
console.log("Sentence picks only (where B, which cuts by sentence, can be compared)");
|
||||
for (const arm of arms) {
|
||||
const e = Object.entries(graded).filter(([k]) => k.startsWith(`${arm}-`) && !k.endsWith("-2")).flatMap(([, v]) => v).filter((x): x is NonNullable<Edge> => !!x);
|
||||
const [l, b] = [e.filter((x) => x.lost).length, e.filter((x) => x.bleed).length];
|
||||
console.log(` ${arm} ${String(e.length).padStart(4)} edges lost ${pct(l, e.length).padStart(6)} bleed ${pct(b, e.length).padStart(6)} defects ${pct(l + b, e.length).padStart(6)}`);
|
||||
}
|
||||
|
||||
/** exact two-sided sign test */
|
||||
function sign(x: number, y: number) {
|
||||
const n = x + y;
|
||||
let p = 0;
|
||||
let c = 1;
|
||||
for (let i = 0; i <= n; i++) {
|
||||
if (i <= Math.min(x, y)) p += c;
|
||||
c = (c * (n - i)) / (i + 1);
|
||||
}
|
||||
return Math.min(1, (2 * p) / 2 ** n);
|
||||
}
|
||||
console.log("\nPaired against A (same spans; edges where exactly one of the two has the defect)");
|
||||
for (const arm of arms.filter((a) => a !== "A" && a !== "B")) {
|
||||
const row: string[] = [];
|
||||
for (const f of ["lost", "bleed"] as const) {
|
||||
let [onlyA, onlyX] = [0, 0];
|
||||
for (const [k, va] of Object.entries(graded)) {
|
||||
if (!k.startsWith("A-")) continue;
|
||||
const vx = graded[arm + k.slice(1)];
|
||||
va.forEach((a, i) => {
|
||||
const x = vx?.[i];
|
||||
if (!a || !x) return;
|
||||
if (a[f] && !x[f]) onlyA++;
|
||||
if (!a[f] && x[f]) onlyX++;
|
||||
});
|
||||
}
|
||||
row.push(`${f}: A only ${onlyA}, ${arm} only ${onlyX} (p=${sign(onlyA, onlyX).toFixed(3)})`);
|
||||
}
|
||||
console.log(` ${arm} ${row.join(" ")}`);
|
||||
}
|
||||
|
||||
console.log("\nDo flags find A's defects?");
|
||||
const ea = Object.entries(graded).filter(([k]) => k.startsWith("A-")).flatMap(([, v]) => v).filter((x): x is NonNullable<Edge> => !!x);
|
||||
const defects = ea.filter((e) => e.lost || e.bleed).length;
|
||||
const flag = (name: string, f: (e: NonNullable<Edge>) => boolean) => {
|
||||
const fl = ea.filter(f);
|
||||
const hit = fl.filter((e) => e.lost || e.bleed).length;
|
||||
const rest = ea.length - fl.length;
|
||||
console.log(` ${name.padEnd(30)} flags ${pct(fl.length, ea.length).padStart(6)} of edges, finds ${pct(hit, defects).padStart(6)} of defects; defects ${pct(hit, fl.length)} flagged vs ${pct(defects - hit, rest)} not`);
|
||||
};
|
||||
flag("no pause beside it (joins.ts)", (e) => e.quiet === false);
|
||||
for (const g of [0.05, 0.1]) flag(`transcript gap under ${g} s`, (e) => (e.gap ?? 9) < g);
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/bash
|
||||
# The joins bench: real talking takes cut five ways by raea cut's edges and the ones tried against them, every clip
|
||||
# heard again by parakeet-mlx, every edge graded (bench.ts says the arms, judge.ts the grades). It decided what
|
||||
# `raea cut` measures (src/joins.ts) against docs/keep-or-replace.md's rubric; rerun it when either changes.
|
||||
#
|
||||
# engine/cli/bench/joins/run.sh DATA [OUT]
|
||||
#
|
||||
# DATA holds each take as TAKE.wav (16 kHz mono 16-bit: `raea media audio TAKE --rate 16000 --mono -o TAKE.wav`) beside
|
||||
# its TAKE.words.json (raea cut's transcript). Takes are a person's footage: DATA and OUT stay outside the repository,
|
||||
# and so do the numbers per take (the rubric doc keeps only totals). OUT defaults to DATA/out.
|
||||
# Needs bun and parakeet-mlx (tools/ensure.sh parakeet-mlx). Hearing runs a few files at a time and picks up where it
|
||||
# stopped, so a run the memory guard ends can be started again.
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
root=$(cd "$here/../../../.." && pwd)
|
||||
data=$(cd "${1:?run.sh DATA [OUT]}" && pwd)
|
||||
out=${2:-$data/out}
|
||||
mkdir -p "$out/heard"
|
||||
out=$(cd "$out" && pwd)
|
||||
case "$out/" in "$root"/*) echo "run.sh: OUT ($out) is inside the repository; keep a person's takes and numbers out of it" >&2; exit 2 ;; esac
|
||||
|
||||
takes=()
|
||||
for w in "$data"/*.words.json; do
|
||||
t=$(basename "$w" .words.json)
|
||||
[ -f "$data/$t.wav" ] && takes+=("$t")
|
||||
done
|
||||
[ ${#takes[@]} -gt 0 ] || { echo "run.sh: no TAKE.wav beside a TAKE.words.json in $data" >&2; exit 2; }
|
||||
|
||||
bun "$here/bench.ts" "$data" "$out" "${takes[@]}"
|
||||
|
||||
parakeet=$(command -v parakeet-mlx || bash "$root/tools/ensure.sh" parakeet-mlx)
|
||||
while :; do
|
||||
todo=()
|
||||
for f in "$out"/*.wav; do
|
||||
k=$(basename "$f" .wav)
|
||||
[ -f "$out/heard/$k.json" ] || todo+=("$f")
|
||||
done
|
||||
[ ${#todo[@]} -eq 0 ] && break
|
||||
"$parakeet" "${todo[@]:0:8}" --output-format json --output-dir "$out/heard" > /dev/null
|
||||
done
|
||||
|
||||
bun "$here/judge.ts" "$out"
|
||||
@@ -0,0 +1,135 @@
|
||||
// `raea cut` reads the take's sound to say which cuts have no pause to sit in (src/joins.ts): a gap in the transcript
|
||||
// isn't a pause until the recording is quiet there. The takes are synthetic: tone bursts for words over a low hiss.
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { edgesOf, joinsOf, levelsOf, levelsOfWav, type Word } from "../src/joins.ts";
|
||||
|
||||
const RATE = 16000;
|
||||
|
||||
/** A take: hiss at -60 dBFS throughout, a 220 Hz tone at -12 dBFS from each [from, to] */
|
||||
function take(seconds: number, sounds: [number, number][]): Int16Array {
|
||||
const pcm = new Int16Array(seconds * RATE);
|
||||
let seed = 1;
|
||||
for (let i = 0; i < pcm.length; i++) {
|
||||
seed = (seed * 1103515245 + 12345) % 2 ** 31;
|
||||
const t = i / RATE;
|
||||
const hiss = (seed / 2 ** 31 - 0.5) * 2 * 0.001;
|
||||
const tone = sounds.some(([a, b]) => t >= a && t < b) ? 0.25 * Math.sin(2 * Math.PI * 220 * t) : 0;
|
||||
pcm[i] = Math.round((hiss + tone) * 32767);
|
||||
}
|
||||
return pcm;
|
||||
}
|
||||
|
||||
function wav(pcm: Int16Array, channels = 1): Uint8Array {
|
||||
const n = pcm.length * channels;
|
||||
const b = new Uint8Array(44 + n * 2);
|
||||
const v = new DataView(b.buffer);
|
||||
const s = (o: number, t: string) => [...t].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));
|
||||
s(0, "RIFF"); v.setUint32(4, 36 + n * 2, true); s(8, "WAVE"); s(12, "fmt ");
|
||||
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, channels, true); v.setUint32(24, RATE, true);
|
||||
v.setUint32(28, RATE * 2 * channels, true); v.setUint16(32, 2 * channels, true); v.setUint16(34, 16, true);
|
||||
s(36, "data"); v.setUint32(40, n * 2, true);
|
||||
// the first channel is the take; any other is silent
|
||||
for (let i = 0; i < pcm.length; i++) v.setInt16(44 + i * 2 * channels, pcm[i], true);
|
||||
return b;
|
||||
}
|
||||
|
||||
// four words: "one" and "two" said straight on, a pause, then "three" "four" straight on. The transcript's tokens abut
|
||||
// throughout, as parakeet's do, so its gaps can't tell the pause from the run-on, and it starts "three" at 1.3 s where
|
||||
// the take is still quiet until 1.6 s
|
||||
const words: Word[] = [
|
||||
{ text: "one", from: 0.5, to: 0.9 },
|
||||
{ text: "two", from: 0.9, to: 1.3 },
|
||||
{ text: "three", from: 1.3, to: 2.0 },
|
||||
{ text: "four", from: 2.0, to: 2.4 },
|
||||
];
|
||||
const sounds: [number, number][] = [[0.5, 1.3], [1.6, 2.0], [2.0, 2.4]];
|
||||
|
||||
describe("raea cut's joins: a cut with no pause beside it is said", () => {
|
||||
const lv = levelsOf(take(3, sounds), RATE);
|
||||
|
||||
test("the take's quiet line sits between its hiss and its words", () => {
|
||||
expect(lv.floor).toBeLessThan(-55);
|
||||
expect(lv.quiet).toBeGreaterThan(lv.floor);
|
||||
expect(lv.quiet).toBeLessThan(-30);
|
||||
});
|
||||
|
||||
test("a cut placed in the pause before a word the transcript starts early is fine", () => {
|
||||
// word times alone: nothing quiet between the middle of "two" and where the transcript starts "three"
|
||||
expect(joinsOf(words, [[2, 3]], lv).quiet[0][0]).toBe(false);
|
||||
// raea cut puts that edge on the frame after 1.3 s, inside the quiet the transcript gave to "three"
|
||||
const placed = joinsOf(words, [[2, 3]], lv, [[40 / 30, 2.6]]);
|
||||
expect(placed.quiet).toEqual([[true, true]]);
|
||||
expect(placed.notes).toEqual([]);
|
||||
});
|
||||
|
||||
test("a line that starts on a word said straight on from the last is noted, both words named", () => {
|
||||
const { quiet, notes } = joinsOf(words, [[1, 1]], lv);
|
||||
expect(quiet[0][0]).toBe(false);
|
||||
expect(notes[0]).toContain(`"two" at 0.90 s follows "one" with no pause in the take`);
|
||||
expect(notes[0]).toContain("start the line where the take pauses");
|
||||
});
|
||||
|
||||
test("an end that runs on into the next word is noted; an end before a pause isn't", () => {
|
||||
const runsOn = joinsOf(words, [[2, 2]], lv, [[40 / 30, 2.0]]);
|
||||
expect(runsOn.quiet).toEqual([[true, false]]);
|
||||
expect(runsOn.notes).toHaveLength(1);
|
||||
expect(runsOn.notes[0]).toContain(`"three" at 2.00 s runs on into "four"`);
|
||||
expect(joinsOf(words, [[0, 1]], lv).quiet[0][1]).toBe(true);
|
||||
});
|
||||
|
||||
test("the take's own start and end count as quiet", () => {
|
||||
expect(joinsOf(words, [[0, 3]], lv).quiet).toEqual([[true, true]]);
|
||||
});
|
||||
|
||||
test("a WAV reads as its PCM does, and a stereo WAV by its first channel", () => {
|
||||
const pcm = take(1, [[0.2, 0.6]]);
|
||||
const mono = levelsOfWav(wav(pcm));
|
||||
const stereo = levelsOfWav(wav(pcm, 2));
|
||||
const direct = levelsOf(pcm, RATE);
|
||||
expect(Array.from(mono.db)).toEqual(Array.from(direct.db));
|
||||
expect(Array.from(stereo.db)).toEqual(Array.from(direct.db));
|
||||
});
|
||||
|
||||
test("a WAV that isn't 16-bit PCM is refused, not misread", () => {
|
||||
const b = wav(take(1, []));
|
||||
new DataView(b.buffer).setUint16(34, 24, true);
|
||||
expect(() => levelsOfWav(b)).toThrow("16-bit PCM");
|
||||
});
|
||||
});
|
||||
|
||||
describe("raea cut's edges: where each cut goes, from the word times", () => {
|
||||
const ws: Word[] = [
|
||||
{ text: "so", from: 1.0, to: 1.2 },
|
||||
{ text: "we", from: 1.5, to: 1.7 },
|
||||
{ text: "went", from: 1.7, to: 2.1 },
|
||||
{ text: "Um.", from: 3.0, to: 3.0 },
|
||||
{ text: "home", from: 3.4, to: 3.9 },
|
||||
];
|
||||
|
||||
test("a share of the gap either side, the grid inward: as raea cut has always placed them", () => {
|
||||
// "we went": 0.3 s before (lead 0.12), 0.9 s after (tail 0.22, not the last span); "home": the last, 0.6 s tail
|
||||
expect(edgesOf(ws, [[1, 2], [4, 4]], 30)).toEqual([
|
||||
[Math.ceil(1.38 * 30) / 30, Math.floor(2.32 * 30) / 30],
|
||||
[Math.ceil((3.4 - 0.12) * 30) / 30, Math.floor(4.25 * 30) / 30],
|
||||
]);
|
||||
});
|
||||
|
||||
test("words that abut get no lead-in, and the grid can start the cut after the word's own start", () => {
|
||||
// the bench's lost first words: "went" follows "we" with no transcript gap
|
||||
const [[a]] = edgesOf([{ text: "we", from: 1.5, to: 1.71 }, { text: "went", from: 1.71, to: 2.1 }], [[1, 1]], 30);
|
||||
expect(a).toBeGreaterThan(1.71);
|
||||
});
|
||||
|
||||
test("a word the transcript gives no length is a frame long, never a cut that ends before it starts", () => {
|
||||
// off the grid with its neighbours abutting, as in the bench: inward rounding put the end a frame before the start
|
||||
const um: Word[] = [{ text: "so", from: 2.5, to: 3.01 }, { text: "Um.", from: 3.01, to: 3.01 }, { text: "right", from: 3.01, to: 3.5 }];
|
||||
const [[a, b]] = edgesOf(um, [[1, 1]], 30);
|
||||
expect(a).toBeCloseTo(91 / 30, 9);
|
||||
expect(b - a).toBeCloseTo(1 / 30, 9);
|
||||
});
|
||||
|
||||
test("a jump cut in the take near the start: the cut starts one take frame after it", () => {
|
||||
const [[a]] = edgesOf(ws, [[1, 2]], 30, [1.4]);
|
||||
expect(a).toBeCloseTo(Math.ceil((1.4 + 1 / 30) * 30) / 30, 9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
// Whether a cut around a run of words has quiet to sit in, read from the recording (`raea cut`, native.ts).
|
||||
//
|
||||
// A transcript's gaps say nothing about pauses: parakeet's tokens abut, so 90% of the edges `raea cut` placed on five
|
||||
// talking takes had a transcript gap under 0.05 s, pause or not. The take's level does say: an edge with no quiet
|
||||
// stretch between it and the word beside it had a defect (its own word clipped, or the neighbour's heard) on 34% of
|
||||
// 142 edges, against 8% of 210 with quiet; it held three quarters of all defects (bench: engine/cli/bench/joins).
|
||||
//
|
||||
// So this measures and reports; it moves nothing. Moving an edge where the speaker runs straight on only traded a
|
||||
// clipped word for the next one's sound in the same bench, and measured edges where there was quiet changed nothing
|
||||
// either. What helps such a join is a different line boundary, which is the agent's call (Scarlet's rule: the tool
|
||||
// measures, the model decides, code overrides only for safety).
|
||||
|
||||
/** A word in the take's seconds */
|
||||
export type Word = { text: string; from: number; to: number };
|
||||
|
||||
/** The take's level in dB every HOP seconds, and the line under which it counts as quiet */
|
||||
export type Levels = { db: Float32Array; floor: number; quiet: number };
|
||||
|
||||
export const HOP = 0.01;
|
||||
const WIN = 0.02;
|
||||
/** quiet this long counts as a pause */
|
||||
const MIN_RUN = 4;
|
||||
|
||||
/** Levels of 16-bit mono PCM at `rate` Hz: RMS over 20 ms every 10 ms; quiet is under the floor (10th percentile)
|
||||
* plus a share of the room up to speech (90th percentile), 6 to 15 dB. */
|
||||
export function levelsOf(pcm: Int16Array, rate: number): Levels {
|
||||
const hop = Math.round(rate * HOP);
|
||||
const half = Math.round((rate * WIN) / 2);
|
||||
const n = Math.max(1, Math.ceil(pcm.length / hop));
|
||||
const db = new Float32Array(n);
|
||||
for (let k = 0; k < n; k++) {
|
||||
const c = k * hop + (hop >> 1);
|
||||
const [a, b] = [Math.max(0, c - half), Math.min(pcm.length, c + half)];
|
||||
let s = 0;
|
||||
for (let i = a; i < b; i++) s += (pcm[i] / 32768) ** 2;
|
||||
db[k] = 10 * Math.log10(s / Math.max(1, b - a) + 1e-12);
|
||||
}
|
||||
const sorted = Float32Array.from(db).sort();
|
||||
const floor = sorted[Math.floor(n * 0.1)];
|
||||
const loud = sorted[Math.floor(n * 0.9)];
|
||||
return { db, floor, quiet: floor + Math.min(15, Math.max(6, (loud - floor) * 0.3)) };
|
||||
}
|
||||
|
||||
/** A WAV file's levels (16-bit PCM; the first channel when there are more) */
|
||||
export function levelsOfWav(bytes: Uint8Array): Levels {
|
||||
const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
let p = 12;
|
||||
let rate = 16000;
|
||||
let channels = 1;
|
||||
while (p + 8 <= v.byteLength) {
|
||||
const id = String.fromCharCode(...bytes.subarray(p, p + 4));
|
||||
const size = v.getUint32(p + 4, true);
|
||||
if (id === "fmt ") {
|
||||
if (v.getUint16(p + 8, true) !== 1 || v.getUint16(p + 22, true) !== 16) throw new Error("levelsOfWav reads 16-bit PCM WAV only");
|
||||
channels = v.getUint16(p + 10, true);
|
||||
rate = v.getUint32(p + 12, true);
|
||||
} else if (id === "data") {
|
||||
const frames = Math.floor(Math.min(size, v.byteLength - p - 8) / (2 * channels));
|
||||
const pcm = new Int16Array(frames);
|
||||
for (let i = 0; i < frames; i++) pcm[i] = v.getInt16(p + 8 + i * 2 * channels, true);
|
||||
return levelsOf(pcm, rate);
|
||||
}
|
||||
p += 8 + size + (size & 1);
|
||||
}
|
||||
throw new Error("levelsOfWav: no data chunk");
|
||||
}
|
||||
|
||||
/** Whether every hop from `a` to `b` seconds is quiet (the take's own start and end count as quiet) */
|
||||
function quietThrough(lv: Levels, a: number, b: number): boolean {
|
||||
for (let k = Math.floor(a / HOP); k <= Math.floor(b / HOP); k++) if (k >= 0 && k < lv.db.length && lv.db[k] >= lv.quiet) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether there's a pause (MIN_RUN quiet hops in a row) anywhere from `a` to `b` seconds */
|
||||
function pauseIn(lv: Levels, a: number, b: number): boolean {
|
||||
let run = 0;
|
||||
for (let k = Math.floor(a / HOP); k <= Math.floor(b / HOP); k++) {
|
||||
const quiet = k < 0 || k >= lv.db.length || lv.db[k] < lv.quiet;
|
||||
run = quiet ? run + 1 : 0;
|
||||
if (run >= MIN_RUN) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** For each span of words [i, j] (indices into `ws`), whether its start and its end have a pause beside them: back from
|
||||
* the first word's start to the middle of the word before, and on from the last word's end to the middle of the word
|
||||
* after (0.8 s and 1.2 s at most, and the take's own start and end count as quiet). A note for each that doesn't,
|
||||
* saying what the join may play and what to do. With `edges` (where each span's cut was placed, in seconds), an edge
|
||||
* that sits in quiet itself (10 ms either side) is fine whatever the words do: the transcript can start a word before
|
||||
* its sound, and the pause is then inside it. */
|
||||
export function joinsOf(ws: Word[], spans: [number, number][], lv: Levels, edges?: [number, number][]): { quiet: [boolean, boolean][]; notes: string[] } {
|
||||
const mid = (w: Word) => (w.from + w.to) / 2;
|
||||
const said = (k: number) => `"${ws[k].text}"`;
|
||||
const notes: string[] = [];
|
||||
const sits = (t: number | undefined) => t !== undefined && quietThrough(lv, t - 0.01, t + 0.01);
|
||||
const quiet = spans.map(([i, j], s): [boolean, boolean] => {
|
||||
const first = ws[i];
|
||||
const last = ws[j];
|
||||
const before = i === 0 || sits(edges?.[s][0]) || pauseIn(lv, Math.max(mid(ws[i - 1]), first.from - 0.8), first.from);
|
||||
const after = j + 1 === ws.length || sits(edges?.[s][1]) || pauseIn(lv, last.to, Math.min(mid(ws[j + 1]), last.to + 1.2));
|
||||
if (!before)
|
||||
notes.push(`${said(i)} at ${first.from.toFixed(2)} s follows ${said(i - 1)} with no pause in the take: the cut may clip ${said(i)} or keep the end of ${said(i - 1)}; start the line where the take pauses, or keep it with the words before`);
|
||||
if (!after)
|
||||
notes.push(`${said(j)} at ${last.to.toFixed(2)} s runs on into ${said(j + 1)} with no pause in the take: the cut may clip ${said(j)} or keep the start of ${said(j + 1)}; end the line where the take pauses, or keep it with the words after`);
|
||||
return [before, after];
|
||||
});
|
||||
return { quiet, notes };
|
||||
}
|
||||
|
||||
/** Where `raea cut` puts each span's cut, from the word times: a share of the gap to the word either side (transcript
|
||||
* word ends run early, so a generous tail, more on the last span, and a short lead-in), off the take's own jump cuts
|
||||
* (`cuts`, in seconds), on the take's frame grid, a frame long at least. Measured placement was tried against this and
|
||||
* changed nothing a listener hears (bench 11-22), so the sound decides what's reported (joinsOf), not where cuts go. */
|
||||
export function edgesOf(ws: Word[], spans: [number, number][], fps: number, cuts: number[] = []): [number, number][] {
|
||||
const sf = 1 / fps;
|
||||
return spans.map(([i, j], k): [number, number] => {
|
||||
const before = i > 0 ? ws[i].from - ws[i - 1].to : 0.4;
|
||||
const after = j + 1 < ws.length ? ws[j + 1].from - ws[j].to : 0.6;
|
||||
let a = ws[i].from - Math.min(before * 0.6, 0.12);
|
||||
let b = ws[j].to + Math.min(after * 0.7, k + 1 === spans.length ? 0.35 : 0.22);
|
||||
// a jump cut in the take near a join: start one take frame after it (or end one before), never on it, or the
|
||||
// other shot's last frame can show
|
||||
const ca = cuts.find((c) => Math.abs(c - a) <= 0.25 && c <= ws[i].from + 0.05);
|
||||
if (ca !== undefined) a = Math.max(a, ca + sf);
|
||||
const cb = cuts.find((c) => Math.abs(c - b) <= 0.25 && c >= ws[j].to - 0.05);
|
||||
if (cb !== undefined) b = Math.min(b, cb - sf);
|
||||
// a word the transcript gives no length ("Um.") rounded inward ended before it started (bench 11-22): a frame at least
|
||||
const from = Math.ceil(Math.max(a, 0) * fps) / fps;
|
||||
return [from, Math.max(from + sf, Math.floor(b * fps) / fps)];
|
||||
});
|
||||
}
|
||||
+24
-17
@@ -10,6 +10,7 @@ import { basename, delimiter, dirname, extname } from "node:path";
|
||||
import { brandKit, pixelsOf } from "./brand";
|
||||
import { readSite, stylesOf } from "./scrape";
|
||||
import { wordsOf } from "./heard";
|
||||
import { edgesOf, joinsOf, levelsOfWav, type Levels } from "./joins";
|
||||
import { harness, library, show, task } from "./app";
|
||||
import { fromCwd } from "./show";
|
||||
import { clothesHost } from "./wardrobe";
|
||||
@@ -98,6 +99,18 @@ function ensure(name: string): string {
|
||||
return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : name;
|
||||
}
|
||||
|
||||
/** The take's level every 10 ms (joins.ts), from its sound at 16 kHz mono; undefined when it has none to read */
|
||||
function levelsOfTake(take: string): Levels | undefined {
|
||||
const dir = mkdtempSync(`${tmpdir()}/raea-levels-`);
|
||||
try {
|
||||
const wav = `${dir}/take.wav`;
|
||||
const a = spawnSync(raea, ["media", "audio", at(take), "--rate", "16000", "--mono", "-o", wav], { encoding: "utf8" });
|
||||
return a.status === 0 && existsSync(wav) ? levelsOfWav(new Uint8Array(readFileSync(wav))) : undefined;
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function hearTake(take: string, out: string) {
|
||||
// parakeet-mlx is Apple silicon's (MLX); elsewhere raea has no transcriber yet, so the two ways that work there
|
||||
if (process.platform !== "darwin")
|
||||
@@ -130,9 +143,11 @@ function cutPlan(take: string, ws: Word[], lines: string[]): { plan: [number, nu
|
||||
let from = 0;
|
||||
const spans: [number, number][] = [];
|
||||
const notes: string[] = [];
|
||||
// every line that can't be cut is named at once, so an agent fixes them in one go (Scarlet: errors name all that failed)
|
||||
const misses: string[] = [];
|
||||
lines.forEach((line, k) => {
|
||||
const want = norm(line).split(/\s+/).filter(Boolean);
|
||||
if (!want.length) throw new Error(`line ${k + 1} is empty`);
|
||||
if (!want.length) return void misses.push(`line ${k + 1} is empty`);
|
||||
const fits = (i: number) => want.every((t, o) => toks[i + o] === t);
|
||||
const close = () => {
|
||||
const n = want.length;
|
||||
@@ -151,7 +166,7 @@ function cutPlan(take: string, ws: Word[], lines: string[]): { plan: [number, nu
|
||||
const i = exact ?? close();
|
||||
if (i === undefined) {
|
||||
const near = toks.flatMap((t, n) => (t === want[0] ? [ws.slice(n, n + 10).map((w) => w.text).join(" ")] : [])).slice(0, 3);
|
||||
throw new Error(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
|
||||
return void misses.push(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
|
||||
}
|
||||
const j = Math.min(i + want.length - 1, toks.length - 1);
|
||||
if (exact === undefined) notes.push(`line ${k + 1} isn't said word for word; cut where the take says "${ws.slice(i, j + 1).map((w) => w.text).join(" ")}"`);
|
||||
@@ -160,21 +175,13 @@ function cutPlan(take: string, ws: Word[], lines: string[]): { plan: [number, nu
|
||||
if (last && last[1] + 1 === i) last[1] = j;
|
||||
else spans.push([i, j]);
|
||||
});
|
||||
const sf = 1 / fps;
|
||||
const plan = spans.map(([i, j], k): [number, number, string] => {
|
||||
const before = i > 0 ? ws[i].from - ws[i - 1].to : 0.4;
|
||||
const after = j + 1 < ws.length ? ws[j + 1].from - ws[j].to : 0.6;
|
||||
// transcript word ends run early: a generous tail (more on the last line), a short lead-in, both inside the pause
|
||||
let a = ws[i].from - Math.min(before * 0.6, 0.12);
|
||||
let b = ws[j].to + Math.min(after * 0.7, k + 1 === spans.length ? 0.35 : 0.22);
|
||||
// a jump cut in the take near a join: start one take frame after it (or end one before), never on it, or the
|
||||
// other shot's last frame can show
|
||||
const ca = cuts.find((c) => Math.abs(c - a) <= 0.25 && c <= ws[i].from + 0.05);
|
||||
if (ca !== undefined) a = Math.max(a, ca + sf);
|
||||
const cb = cuts.find((c) => Math.abs(c - b) <= 0.25 && c >= ws[j].to - 0.05);
|
||||
if (cb !== undefined) b = Math.min(b, cb - sf);
|
||||
return [Math.ceil(Math.max(a, 0) * fps) / fps, Math.floor(b * fps) / fps, ws.slice(i, j + 1).map((w) => w.text).join(" ")];
|
||||
});
|
||||
if (misses.length) throw new Error(misses.join("\n"));
|
||||
const edges = edgesOf(ws, spans, fps, cuts);
|
||||
const plan = spans.map(([i, j], k): [number, number, string] => [...edges[k], ws.slice(i, j + 1).map((w) => w.text).join(" ")]);
|
||||
// each edge with no pause beside it in the take, said (joins.ts): those joins hold most of the clipped words
|
||||
const lv = levelsOfTake(take);
|
||||
if (lv) notes.push(...joinsOf(ws, spans, lv, edges).notes);
|
||||
else notes.push(`couldn't read ${take}'s sound to check that each cut sits in a pause`);
|
||||
return { plan, notes };
|
||||
}
|
||||
|
||||
|
||||
@@ -225,6 +225,8 @@ impl Engine {
|
||||
image.texture_descriptor.view_formats = &[TextureFormat::Rgba8Unorm];
|
||||
let target = app.world_mut().resource_mut::<Assets<Image>>().add(image);
|
||||
app.insert_resource(TagRowTarget(target.clone())).init_resource::<ViewBox>().add_systems(PostUpdate, tag_row_view.before(bevy::camera::CameraUpdateSystems));
|
||||
// a camera drawing a box's view culls by it (#261), once Bevy has made its own frusta
|
||||
app.add_systems(PostUpdate, sub_view_frusta.after(bevy::camera::visibility::VisibilitySystems::UpdateFrusta).before(bevy::camera::visibility::VisibilitySystems::CheckVisibility));
|
||||
// a free camera over the scene (docs/preview.feature PV1c): off until a preview asks for one
|
||||
app.init_resource::<raea_sys_frame::view::FreeView>().add_systems(PostUpdate, raea_sys_frame::view::apply.before(bevy::transform::TransformSystems::Propagate));
|
||||
// without native nothing ever comes back (frames are read back only to be encoded or analysed)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! raea-runtime-gpuframe), the render world's diagnostics forwarded.
|
||||
|
||||
use super::*;
|
||||
pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, tag_row_view};
|
||||
pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, sub_view_frusta, tag_row_view};
|
||||
|
||||
/// Bevy's render diagnostics (each pass's elapsed time, `render/...`): each new measurement into the run's totals (stats.read, the stats table: nobuild NB2a), the smoothed ones into its trace once a second.
|
||||
#[cfg(feature = "native")]
|
||||
|
||||
@@ -198,9 +198,9 @@ const LIVE_PAST: i64 = 3600;
|
||||
/// raea-render program drawn by raea-render into `out` (.mp4, .png for one frame, a folder of PNGs). `dir` is where relative media resolves. `wanted`: the frames (all when None).
|
||||
pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option<Vec<i64>>) -> R<String> {
|
||||
// stills of a 3D scene: its engine opened live beside the page (as the fed path opens it), the page laid over each
|
||||
// frame's 3D and each <Screen> painted from the page's own picture of it
|
||||
// frame's 3D and each <Screen> painted from the page's own picture of it. A .png with no --frame is frame 0, drawn as --frame 0 draws it: the frames path gave a camera in a page element (an <R3F> in a box) the whole frame's view (#261)
|
||||
let ext = out_ext(out);
|
||||
let stills = (ext == "png" && wanted.as_ref().is_some_and(|w| w.len() == 1)) || ext.is_empty();
|
||||
let stills = (ext == "png" && wanted.as_ref().is_none_or(|w| w.len() == 1)) || ext.is_empty();
|
||||
let how = std::env::var_os("RAEA_3D").and_then(|v| v.into_string().ok()).unwrap_or_default();
|
||||
// a game: its 3D made frame by frame as it's stepped (rows made beforehand hold every frame's scene: a 10-minute
|
||||
// game took 24 GB before its first frame); RAEA_3D=live or =program chooses
|
||||
@@ -210,16 +210,16 @@ pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option<Vec<i64>>
|
||||
return render_bundle_with(js, dir, out, wanted, video, None, true);
|
||||
}
|
||||
if stills && how != "files" {
|
||||
let upto = wanted.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1);
|
||||
// a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a
|
||||
// scene for every frame up to it: raea check --quick's three stills of a 13,175-frame film took 10.4 GB that
|
||||
// way and 0.8 GB live, the same pixels as the film's (SG4a)
|
||||
if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && wanted.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) {
|
||||
let still = if ext == "png" && wanted.is_none() { Some(vec![0]) } else { wanted.clone() };
|
||||
let upto = still.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1);
|
||||
// a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a scene for every frame up to it:
|
||||
// raea check --quick's three stills of a 13,175-frame film took 10.4 GB that way and 0.8 GB live, the same pixels as the film's (SG4a)
|
||||
if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && still.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) {
|
||||
raea_runtime_react::startup_mark("stills past the rows' reach: the 3D made live at each");
|
||||
return render_bundle_with(js, dir, out, wanted, false, None, true);
|
||||
return render_bundle_with(js, dir, out, still, false, None, true);
|
||||
}
|
||||
if let Some(scene) = scene_program_checked(js, dir, upto, wanted.as_deref())? {
|
||||
return render_bundle_with(js, dir, out, wanted, false, Some(scene), false);
|
||||
if let Some(scene) = scene_program_checked(js, dir, upto, still.as_deref())? {
|
||||
return render_bundle_with(js, dir, out, still, false, Some(scene), false);
|
||||
}
|
||||
}
|
||||
// a video: fed, its pages handed to the encoder on the GPU (B1d), until a frame holds 3D, which starts it again
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// frame draws runs at the next frame. `new Image()` loads: setting its src fires load (and onload) on the next microtask,
|
||||
// so a preload resolves, and by then naturalWidth and naturalHeight are the picture's size (#253): a data: URL's from its
|
||||
// header, a file's or URL's from the host (native asset.load, which finds staticFile's /media/ paths as <Img> does).
|
||||
// currentSrc is then the file the host found, which a canvas's drawImage draws from (#260).
|
||||
// width and height are the ones given (the constructor's, or set) else the natural size, as a browser has them. A file
|
||||
// the host can't find fires error (and onerror) instead. Under plain bun, with no host, a file's size stays 0.
|
||||
|
||||
@@ -59,13 +60,14 @@ export function frameCallbacks(f: number, fps: number): void {
|
||||
|
||||
type Listener = (e: { type: string; target: unknown; currentTarget: unknown }) => void;
|
||||
|
||||
/** A picture's size: a data: URL's from its header, anything else from the host (asset.load); null when it has none
|
||||
* (no host, or a format the header doesn't say). Throws the host's error for a file that isn't there. */
|
||||
function pictureSize(src: string): [number, number] | null {
|
||||
if (src.startsWith("data:")) return sniffSize(src);
|
||||
if (src.startsWith("blob:") || !hasNative()) return null;
|
||||
/** A picture's size, and the file the host found for it: a data: URL's size from its header, anything else from the host
|
||||
* (asset.load); no size when it has none (no host, or a format the header doesn't say). Throws the host's error for a
|
||||
* file that isn't there. */
|
||||
function picture(src: string): { size: [number, number] | null; file?: string } {
|
||||
if (src.startsWith("data:")) return { size: sniffSize(src) };
|
||||
if (src.startsWith("blob:") || !hasNative()) return { size: null };
|
||||
const got = native("asset.load", { path: src });
|
||||
return got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null;
|
||||
return { size: got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null, file: typeof got?.path === "string" ? got.path : undefined };
|
||||
}
|
||||
|
||||
/** A preloadable image: its src set, load fires, with the picture's size. */
|
||||
@@ -75,6 +77,10 @@ class FrameImage {
|
||||
complete = true;
|
||||
naturalWidth = 0;
|
||||
naturalHeight = 0;
|
||||
/** the picture as it loaded: the file the host found for the src (staticFile's /media/x is the project's media/x),
|
||||
* which is what a canvas's drawImage draws from (#260: read back off the page, a canvas has no project folder to
|
||||
* find /media/ in, and the picture drew nothing); "" until it loads, as in a browser */
|
||||
currentSrc = "";
|
||||
alt = "";
|
||||
crossOrigin: string | null = null;
|
||||
decoding = "auto";
|
||||
@@ -116,14 +122,16 @@ class FrameImage {
|
||||
this.complete = false;
|
||||
this.naturalWidth = 0;
|
||||
this.naturalHeight = 0;
|
||||
this.currentSrc = "";
|
||||
const load = ++this.#loads;
|
||||
queueMicrotask(() => {
|
||||
// a src set again before this one loaded: only the last one's load fires, as in a browser
|
||||
if (load !== this.#loads) return;
|
||||
let type = "load";
|
||||
try {
|
||||
const size = pictureSize(src);
|
||||
const { size, file } = picture(src);
|
||||
if (size) [this.naturalWidth, this.naturalHeight] = size;
|
||||
this.currentSrc = file ?? src;
|
||||
} catch (err) {
|
||||
type = "error";
|
||||
console.warn(`new Image(): ${src} didn't load: ${err instanceof Error ? err.message : String(err)}`);
|
||||
|
||||
@@ -143,11 +143,13 @@ pub(crate) fn page_options() -> usvg::Options<'static> {
|
||||
/// Where a video's or a picture's src is as a file, for drawing it on a canvas (`videos`).
|
||||
static VIDEO_PATHS: std::sync::RwLock<Option<fn(&str) -> Option<std::path::PathBuf>>> = std::sync::RwLock::new(None);
|
||||
|
||||
/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too).
|
||||
/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too); a src that is a file as it
|
||||
/// stands (a loaded Image's currentSrc, the file its host found: #260) is that file whatever the roots make of it.
|
||||
fn media_file(src: &str) -> Option<std::path::PathBuf> {
|
||||
let plain = std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src));
|
||||
match *VIDEO_PATHS.read().unwrap() {
|
||||
Some(f) => f(src),
|
||||
None => Some(std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src))),
|
||||
Some(f) => f(src).filter(|p| p.exists() || !(plain.is_absolute() && plain.is_file())).or(Some(plain)),
|
||||
None => Some(plain),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,4 +14,7 @@ blitz-paint = { version = "=0.3.0-beta.4", default-features = false }
|
||||
# every call's arguments hashed, so the same print draws the same picture
|
||||
rustc-hash = "2"
|
||||
vello = { version = "=0.11.0", default-features = false, features = ["wgpu"] }
|
||||
# a bitmap emoji's strike and its PNG, for the grey ones Vello's glyph run skips (emoji.rs, #262): Vello's own versions
|
||||
skrifa = "0.44.0"
|
||||
png = "0.18.1"
|
||||
wgpu = "=30.0.1"
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Bitmap emoji whose PNG Vello doesn't draw: grey ones. Apple Color Emoji keeps 52 of its glyphs as grey + alpha PNGs
|
||||
//! (💬 and 🗨 among them), and Vello's glyph run asks png for RGBA with a transformation that adds alpha and leaves
|
||||
//! grey as it is, logs "Unsupported `output_color_type`" and skips the glyph: its space was kept and nothing drawn
|
||||
//! (#262). Those glyphs are taken out of the run and drawn here, as images placed the way Vello places a bitmap glyph.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyrender::Glyph;
|
||||
use skrifa::bitmap::{BitmapData, BitmapFormat, Origin};
|
||||
use skrifa::raw::TableProvider;
|
||||
use skrifa::{GlyphId, MetadataProvider, instance::Size};
|
||||
use vello::kurbo::{Affine, Vec2};
|
||||
use vello::peniko::{Blob, FontData, ImageAlphaType, ImageData, ImageFormat};
|
||||
|
||||
thread_local! {
|
||||
/// a font (its data's id and index) with bitmap strikes: its units per em, and whether it's Apple Color Emoji; None for a font with none
|
||||
static FONTS: RefCell<HashMap<(u64, u32), Option<(f32, bool)>>> = RefCell::new(HashMap::new());
|
||||
/// a glyph's picture once decoded (font, glyph, strike), so the same image is drawn each frame
|
||||
static PICTURES: RefCell<HashMap<(u64, u32, u32, u32), Option<ImageData>>> = RefCell::new(HashMap::new());
|
||||
}
|
||||
|
||||
/// A PNG's colour type Vello's glyph run draws: truecolour, with alpha or without (2 and 6); grey and palette ones it skips.
|
||||
fn vello_draws(png: &[u8]) -> bool {
|
||||
png.get(25).is_none_or(|t| matches!(t, 2 | 6))
|
||||
}
|
||||
|
||||
/// A PNG as RGBA8, grey and palette ones expanded.
|
||||
pub(crate) fn rgba(data: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let mut decoder = png::Decoder::new(std::io::Cursor::new(data));
|
||||
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA);
|
||||
let mut reader = decoder.read_info().ok()?;
|
||||
let mut buf = vec![0; reader.output_buffer_size()?];
|
||||
let info = reader.next_frame(&mut buf).ok()?;
|
||||
buf.truncate(info.buffer_size());
|
||||
if info.color_type == png::ColorType::Indexed {
|
||||
return None;
|
||||
}
|
||||
// each pixel's samples as four: grey (1 or 2 samples) spread over the three colours, and alpha the last sample
|
||||
// of an even count, opaque otherwise
|
||||
let n = info.color_type.samples();
|
||||
let mut px = Vec::with_capacity(buf.len() / n * 4);
|
||||
for p in buf.chunks_exact(n) {
|
||||
let a = if n % 2 == 0 { p[n - 1] } else { 255 };
|
||||
px.extend_from_slice(&if n < 3 { [p[0], p[0], p[0], a] } else { [p[0], p[1], p[2], a] });
|
||||
}
|
||||
(px.len() as u64 == u64::from(info.width) * u64::from(info.height) * 4).then_some((info.width, info.height, px))
|
||||
}
|
||||
|
||||
/// The glyphs of a run Vello would skip, each as its picture and where it goes in the run's space, and the rest of the
|
||||
/// run for Vello; None when the run has none (every font without bitmaps, nearly every emoji).
|
||||
pub(crate) fn skipped(font: &FontData, font_size: f32, glyph_transform: Option<Affine>, glyphs: impl Iterator<Item = Glyph> + Clone) -> Option<(Vec<Glyph>, Vec<(ImageData, Affine)>)> {
|
||||
let key = (font.data.id(), font.index);
|
||||
let known = FONTS.with_borrow(|f| f.get(&key).copied());
|
||||
if known == Some(None) {
|
||||
return None;
|
||||
}
|
||||
let face = skrifa::FontRef::from_index(font.data.as_ref(), font.index).ok()?;
|
||||
let strikes = face.bitmap_strikes();
|
||||
let (upem, apple) = match known {
|
||||
Some(Some(k)) => k,
|
||||
_ => {
|
||||
let k = strikes.format().and_then(|format| {
|
||||
let upem = f32::from(face.head().ok()?.units_per_em());
|
||||
let apple = format == BitmapFormat::Sbix && face.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).any(|n| n.chars().eq("AppleColorEmoji".chars()));
|
||||
Some((upem, apple))
|
||||
});
|
||||
FONTS.with(|f| f.borrow_mut().insert(key, k));
|
||||
k?
|
||||
}
|
||||
};
|
||||
let png_of = |g: &Glyph| match strikes.glyph_for_size(Size::new(font_size), GlyphId::new(g.id)) {
|
||||
Some(b) => match b.data {
|
||||
BitmapData::Png(d) if !vello_draws(d) => Some((b, d)),
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
if !glyphs.clone().any(|g| png_of(&g).is_some()) {
|
||||
return None;
|
||||
}
|
||||
let (mut rest, mut ours) = (Vec::new(), Vec::new());
|
||||
for g in glyphs {
|
||||
let Some((b, data)) = png_of(&g) else {
|
||||
rest.push(g);
|
||||
continue;
|
||||
};
|
||||
let pic = PICTURES.with(|p| {
|
||||
p.borrow_mut()
|
||||
.entry((key.0, key.1, g.id, b.ppem_y.to_bits()))
|
||||
.or_insert_with(|| rgba(data).filter(|&(w, h, _)| w == b.width && h == b.height).map(|(width, height, px)| ImageData { data: Blob::new(Arc::new(px)), format: ImageFormat::Rgba8, alpha_type: ImageAlphaType::Alpha, width, height }))
|
||||
.clone()
|
||||
});
|
||||
// one png can't read is left out, as Vello leaves it
|
||||
let Some(pic) = pic else { continue };
|
||||
// Vello's placement of a bitmap glyph (scene.rs, after Skia's): Apple Color Emoji an eighth of the size down
|
||||
let outer = if apple { Vec2::new(0.0, f64::from(font_size) / 8.0) } else { Vec2::new(f64::from(b.bearing_x * font_size / upem), -f64::from(b.bearing_y * font_size / upem)) };
|
||||
let mut at = Affine::translate((f64::from(g.x), f64::from(g.y))) * Affine::translate(outer) * Affine::scale(f64::from(font_size / b.ppem_y)) * Affine::translate((f64::from(b.inner_bearing_x), -f64::from(b.inner_bearing_y)));
|
||||
if matches!(b.placement_origin, Origin::BottomLeft) {
|
||||
at *= Affine::translate((0.0, -f64::from(pic.height)));
|
||||
}
|
||||
if let Some(t) = glyph_transform {
|
||||
at *= t;
|
||||
}
|
||||
ours.push((pic, at));
|
||||
}
|
||||
Some((rest, ours))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// a 2 x 1 PNG of colour type `kind`, 8 bits a channel, its rows given unfiltered
|
||||
fn png_of(kind: png::ColorType, row: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut e = png::Encoder::new(&mut out, 2, 1);
|
||||
e.set_color(kind);
|
||||
e.set_depth(png::BitDepth::Eight);
|
||||
e.write_header().unwrap().write_image_data(row).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grey_png_is_the_one_vello_skips_and_reads_as_rgba() {
|
||||
// #262: 💬 in Apple Color Emoji is grey + alpha
|
||||
let grey = png_of(png::ColorType::GrayscaleAlpha, &[200, 255, 10, 128]);
|
||||
assert!(!vello_draws(&grey));
|
||||
assert_eq!(rgba(&grey), Some((2, 1, vec![200, 200, 200, 255, 10, 10, 10, 128])));
|
||||
let colour = png_of(png::ColorType::Rgba, &[1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
assert!(vello_draws(&colour) && vello_draws(&png_of(png::ColorType::Rgb, &[1, 2, 3, 4, 5, 6])));
|
||||
assert_eq!(rgba(&colour), Some((2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8])));
|
||||
assert_eq!(rgba(&png_of(png::ColorType::Grayscale, &[7, 9])), Some((2, 1, vec![7, 7, 7, 255, 9, 9, 9, 255])));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
//! The passes work as Chrome's do: on premultiplied, sRGB-encoded values (no linearising), blur radii scaled by the
|
||||
//! layer's transform; edges are transparent (CSS's `EdgeMode::None`).
|
||||
|
||||
mod emoji;
|
||||
mod painter;
|
||||
mod passes;
|
||||
mod premul;
|
||||
|
||||
@@ -387,6 +387,14 @@ impl PaintScene for Painter<'_> {
|
||||
self.hash.write_u32(g.y.to_bits());
|
||||
}
|
||||
let (scene, at) = self.top();
|
||||
// the bitmap emoji Vello skips (grey PNGs: 💬, #262) drawn here, the rest of the run by Vello
|
||||
if let Some((rest, ours)) = crate::emoji::skipped(font, font_size, glyph_transform, glyphs.clone()) {
|
||||
VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, rest.into_iter());
|
||||
for (pic, place) in &ours {
|
||||
scene.draw_image(pic, at * transform * *place);
|
||||
}
|
||||
return;
|
||||
}
|
||||
VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, glyphs);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,29 @@ pub fn tag_row_view(t: Res<TagRowTarget>, images: Res<Assets<Image>>, view_box:
|
||||
}
|
||||
}
|
||||
|
||||
/// A camera with a sub view culls by that view. Bevy's update_frusta takes the projection's whole view at the target's
|
||||
/// shape, so with a box wider than the frame (1080 x 389 in a 1080 x 600 frame, the same field of view up and down) a
|
||||
/// mesh inside the box's view and outside the frame's was culled and never drawn: a curved shelf's side cards, where
|
||||
/// the same cards turned the other way reached into the frame's view and drew (#261). After Bevy's own frusta, before
|
||||
/// visibility is checked; a camera whose sub view went gets Bevy's frustum back.
|
||||
pub fn sub_view_frusta(mut ours: Local<bevy::platform::collections::HashSet<Entity>>, mut q: Query<(Entity, &Camera, &GlobalTransform, &Projection, &mut bevy::camera::primitives::Frustum)>) {
|
||||
for (e, c, at, p, mut f) in &mut q {
|
||||
let next = match c.sub_camera_view.as_ref() {
|
||||
Some(v) => {
|
||||
ours.insert(e);
|
||||
let clip_from_world = p.get_clip_from_view_for_sub(v) * at.affine().inverse();
|
||||
bevy::camera::primitives::Frustum(bevy::shape::ViewFrustum::from_clip_from_world_custom_far(&clip_from_world, &at.translation(), &at.back(), p.far()))
|
||||
}
|
||||
None if ours.remove(&e) => p.compute_frustum(at),
|
||||
None => continue,
|
||||
};
|
||||
// written only when it moves, so the frustum reads as changed when it is
|
||||
if (0..6).any(|i| next.half_spaces[i].normal() != f.half_spaces[i].normal() || next.half_spaces[i].d() != f.half_spaces[i].d()) {
|
||||
*f = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -126,6 +149,30 @@ mod tests {
|
||||
assert!(app.world().get::<Camera>(cam).unwrap().sub_camera_view.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wide_box_culls_by_its_own_view() {
|
||||
use bevy::camera::primitives::{Frustum, Sphere};
|
||||
// #261's shapes on this 600 x 600 target: fov 30 up and down, the frame 1.8 wide to 1 high and a box 600 x 216
|
||||
// (1080 x 389's shape); a point 1.7 to the side, 3 ahead, is outside the frame's view (half of it is 1.45
|
||||
// wide there) and inside the box's (2.23)
|
||||
let (mut app, cam, _) = app();
|
||||
app.add_systems(Update, sub_view_frusta.after(tag_row_view));
|
||||
let p = PerspectiveProjection { fov: 30f32.to_radians(), aspect_ratio: 1080.0 / 600.0, ..default() };
|
||||
let whole = Projection::Perspective(p.clone()).compute_frustum(&GlobalTransform::IDENTITY);
|
||||
app.world_mut().entity_mut(cam).insert((Projection::Perspective(p), GlobalTransform::IDENTITY, whole));
|
||||
let card = Sphere { center: bevy::math::Vec3A::new(1.7, 0.0, -3.0), radius: 0.05 };
|
||||
let seen = |app: &App| app.world().get::<Frustum>(cam).unwrap().intersects_sphere(&card, true);
|
||||
app.update();
|
||||
assert!(!seen(&app), "outside the frame's view");
|
||||
app.world_mut().resource_mut::<ViewBox>().0 = Some([0, 100, 600, 216]);
|
||||
app.update();
|
||||
assert!(seen(&app), "inside the box's view");
|
||||
// the box goes: Bevy's frustum again
|
||||
app.world_mut().resource_mut::<ViewBox>().0 = None;
|
||||
app.update();
|
||||
assert!(!seen(&app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cameras_own_viewport_is_left_as_it_is() {
|
||||
let (mut app, _, h) = app();
|
||||
|
||||
Reference in new issue
Block a user