Skip to content

armgit / raea

Public Imported from GitHub
0

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

raea song builds and runs off Apple (fixes #43). raea-sys-vision compiled modules that use Core ML and Apple Vision on every platform. depth and object are now Apple-only, and AppleVision with its text_lines moved into apple_vision.rs. The Vision trait and the portable helpers stay in vision.rs, and image becomes a dependency everywhere. raea-sys-layout's motion module (pure Rust) is no longer gated. raea-perceive gates the eyes, vad, track and hands commands to Apple, and read-lines and faces to builds that have a backend. Footage's store and content_hash (beats --store) move out of the Apple-only ingest module into store.rs. Off Apple, song and beats decode in process with the soft backend (Symphonia), since a Windows install has no ffmpeg: on a 163 s mp3 the map matches the ffmpeg backend's (264 beats, the same sections; strengths within 0.003). Models live in raea_io_home::models(): %LOCALAPPDATA%\raea\models on Windows, which has no HOME, and ~/.local/share/raea-models elsewhere as before. raea-perceive is found as raea-perceive.exe on Windows (io/assets perceive_bin, and the CLI's native.ts, whose PATH lookup now splits on the platform's delimiter). raea-perceive checks for Linux and Windows except opus's C build, which the soft backend brings and only a native toolchain compiles. The release doesn't ship raea-perceive for Windows or Linux yet

shinyobjectz3fcd4e56f375
diff --git a/Cargo.lock b/Cargo.lock
index 0f18cc46..cadb47f3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15490,6 +15490,7 @@ dependencies = [
"deep_filter",
"ndarray 0.15.6",
"ort",
+ "raea-io-home",
"raea-io-media",
"raea-sys-vision",
"serde_json",
diff --git a/apps/tools/src/song.rs b/apps/tools/src/song.rs
index 0569389c..91d00659 100644
--- a/apps/tools/src/song.rs
+++ b/apps/tools/src/song.rs
@@ -59,8 +59,8 @@ pub fn song(args: &[String]) -> R<String> {
return Err("song: the map is made by raea-perceive, which isn't installed beside raea. Update raea (`curl -fsSL https://raea.io/install | sh`: releases ship it in ~/.raea/bin), or from a checkout `cargo build --release -p raea-perceive`, or point RAEA_PERCEIVE at one".into());
}
// its beat model (Beat This!, MIT): an install keeps it in share/raea/models; raea-perceive reads it from
- // ~/.local/share/raea-models
- let model = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models/beat-this/beat_this_small0.onnx");
+ // raea_io_home::models() (~/.local/share/raea-models; %LOCALAPPDATA%\raea\models on Windows)
+ let model = raea_io_home::models().join("beat-this/beat_this_small0.onnx");
if !model.is_file() {
let shipped = raea_io_home::home().join("models/beat-this/beat_this_small0.onnx");
if !shipped.is_file() || std::fs::create_dir_all(model.parent().unwrap()).and_then(|_| std::fs::copy(&shipped, &model)).is_err() {
diff --git a/engine/cli/src/native.ts b/engine/cli/src/native.ts
index c98b8def..ce9d3a8b 100644
--- a/engine/cli/src/native.ts
+++ b/engine/cli/src/native.ts
@@ -6,7 +6,7 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { basename, dirname, extname } from "node:path";
+import { basename, delimiter, dirname, extname } from "node:path";
import { brandKit } from "./brand";
import { readSite, stylesOf } from "./scrape";
import { wordsOf } from "./heard";
@@ -211,9 +211,11 @@ function cut(a: { take: string; lines: string[]; spans: number[][]; keep: Clip[]
/** raea-perceive, as `raea song` finds it (runtime/react/src/runtime/page/src/faces.rs perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */
function perceive(): string {
// raea's path (a bare name, as a test may pass, is found on PATH)
- const self = raea.includes("/") ? raea : (process.env.PATH ?? "").split(":").map((d) => `${d}/${raea}`).find((p) => existsSync(p)) ?? raea;
- const beside = existsSync(self) ? `${dirname(realpathSync(self))}/raea-perceive` : "";
- return process.env.RAEA_PERCEIVE || (existsSync(beside) ? beside : "raea-perceive");
+ const self = raea.includes("/") ? raea : (process.env.PATH ?? "").split(delimiter).map((d) => `${d}/${raea}`).find((p) => existsSync(p)) ?? raea;
+ // raea-perceive.exe on Windows (#43)
+ const name = process.platform === "win32" ? "raea-perceive.exe" : "raea-perceive";
+ const beside = existsSync(self) ? `${dirname(realpathSync(self))}/${name}` : "";
+ return process.env.RAEA_PERCEIVE || (existsSync(beside) ? beside : name);
}
/** `raea frame`'s host step: how a take fits the edit's shape, from where its face is at a moment (raea-perceive's
diff --git a/io/assets/src/lib.rs b/io/assets/src/lib.rs
index 5ed5d452..bbaafbd7 100644
--- a/io/assets/src/lib.rs
+++ b/io/assets/src/lib.rs
@@ -268,9 +268,11 @@ pub fn matchmove_params(p: &J) -> Result<J, String> {
/// raea-perceive (EdgeTAM tracking, face tracks): $RAEA_PERCEIVE, else the first found beside this raea (an install's
/// ~/.raea/bin, which the release fills), in the checkout's release build or on PATH.
pub fn perceive_bin() -> PathBuf {
- let beside = std::env::current_exe().ok().and_then(|e| e.canonicalize().ok()).and_then(|e| Some(e.parent()?.join("raea-perceive")));
- let found = beside.into_iter().chain([PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/release/raea-perceive"))]).chain(std::env::var_os("PATH").iter().flat_map(std::env::split_paths).map(|d| d.join("raea-perceive"))).find(|p| p.is_file());
- std::env::var_os("RAEA_PERCEIVE").filter(|v| !v.is_empty()).map(PathBuf::from).or(found).unwrap_or_else(|| "raea-perceive".into())
+ // raea-perceive.exe on Windows (#43)
+ const NAME: &str = if cfg!(windows) { "raea-perceive.exe" } else { "raea-perceive" };
+ let beside = std::env::current_exe().ok().and_then(|e| e.canonicalize().ok()).and_then(|e| Some(e.parent()?.join(NAME)));
+ let found = beside.into_iter().chain([PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/release")).join(NAME)]).chain(std::env::var_os("PATH").iter().flat_map(std::env::split_paths).map(|d| d.join(NAME))).find(|p| p.is_file());
+ std::env::var_os("RAEA_PERCEIVE").filter(|v| !v.is_empty()).map(PathBuf::from).or(found).unwrap_or_else(|| NAME.into())
}
/// A file's SHA-256, streamed.
diff --git a/io/home/src/lib.rs b/io/home/src/lib.rs
index 0bc188af..2f8462dd 100644
--- a/io/home/src/lib.rs
+++ b/io/home/src/lib.rs
@@ -43,6 +43,17 @@ fn drive(s: &str) -> Option<&str> {
s.strip_prefix(r"\\?\").filter(|r| r.as_bytes().get(1) == Some(&b':'))
}
+/// Where raea's models are kept (Beat This!, Demucs, TransNet, Silero, the Core ML ones): ~/.local/share/raea-models on
+/// the Mac and Linux, %LOCALAPPDATA%\raea\models on Windows, which has no HOME (#43). Relative when neither is set.
+pub fn models() -> std::path::PathBuf {
+ use std::path::PathBuf;
+ let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
+ match var("LOCALAPPDATA").filter(|_| cfg!(windows)) {
+ Some(d) => d.join("raea").join("models"),
+ None => var("HOME").unwrap_or_default().join(".local/share/raea-models"),
+ }
+}
+
/// raea's per-user cache folder: ~/Library/Caches/raea on macOS, $XDG_CACHE_HOME/raea (~/.cache/raea by default)
/// elsewhere on Unix, %LOCALAPPDATA%\raea\cache on Windows. None when that platform's home isn't set.
pub fn caches() -> Option<std::path::PathBuf> {
diff --git a/systems/footage/src/ingest/mod.rs b/systems/footage/src/ingest/mod.rs
index df4cbb58..f90696cb 100644
--- a/systems/footage/src/ingest/mod.rs
+++ b/systems/footage/src/ingest/mod.rs
@@ -274,28 +274,8 @@ pub struct Manifest {
/// What ingest writes and in what shape; bumped when a step's output changes, which makes every clip run again.
pub const INGEST_VERSION: u32 = 1;
-/// The default store: $RAEA_INGEST, else ~/.cache/raea-ingest.
-pub fn store() -> std::path::PathBuf {
- std::env::var_os("RAEA_INGEST")
- .map(std::path::PathBuf::from)
- .unwrap_or_else(|| std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".cache/raea-ingest"))
-}
-
-pub fn content_hash(path: &Path) -> Result<String, String> {
- use sha2::{Digest, Sha256};
- use std::io::Read;
- let mut f = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
- let mut h = Sha256::new();
- let mut buf = vec![0u8; 1 << 20];
- loop {
- let n = f.read(&mut buf).map_err(|e| e.to_string())?;
- if n == 0 {
- break;
- }
- h.update(&buf[..n]);
- }
- Ok(format!("{:x}", h.finalize()))
-}
+// (the store and a clip's content hash, store.rs, here as before)
+pub use crate::store::{content_hash, store};
/// Ingest a clip once: facts (with what's heard) and the performance when a face is on camera, into `store/<hash>/`; a
/// step whose output is already there for this version is skipped.
diff --git a/systems/footage/src/lib.rs b/systems/footage/src/lib.rs
index 3d249995..deae031d 100644
--- a/systems/footage/src/lib.rs
+++ b/systems/footage/src/lib.rs
@@ -4,6 +4,7 @@
#[cfg(target_vendor = "apple")]
pub mod ingest;
pub mod shots;
+pub mod store;
pub mod performance;
#[cfg(target_vendor = "apple")]
pub mod cuts;
diff --git a/systems/footage/src/store.rs b/systems/footage/src/store.rs
new file mode 100644
index 00000000..557f9065
--- /dev/null
+++ b/systems/footage/src/store.rs
@@ -0,0 +1,27 @@
+//! Where ingest keeps a clip's tracks: the store, and the content hash a clip's folder is named by (on every platform: a
+//! song's beats and speech spans are kept there too).
+
+use std::path::Path;
+
+/// The default store: $RAEA_INGEST, else ~/.cache/raea-ingest.
+pub fn store() -> std::path::PathBuf {
+ std::env::var_os("RAEA_INGEST")
+ .map(std::path::PathBuf::from)
+ .unwrap_or_else(|| std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".cache/raea-ingest"))
+}
+
+pub fn content_hash(path: &Path) -> Result<String, String> {
+ use sha2::{Digest, Sha256};
+ use std::io::Read;
+ let mut f = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
+ let mut h = Sha256::new();
+ let mut buf = vec![0u8; 1 << 20];
+ loop {
+ let n = f.read(&mut buf).map_err(|e| e.to_string())?;
+ if n == 0 {
+ break;
+ }
+ h.update(&buf[..n]);
+ }
+ Ok(format!("{:x}", h.finalize()))
+}
diff --git a/systems/layout/src/lib.rs b/systems/layout/src/lib.rs
index 57a4bffc..6ce6551c 100644
--- a/systems/layout/src/lib.rs
+++ b/systems/layout/src/lib.rs
@@ -5,5 +5,4 @@ pub mod layout;
pub mod coach;
pub mod legible;
pub mod framing;
-#[cfg(target_vendor = "apple")]
pub mod motion;
diff --git a/systems/song/Cargo.toml b/systems/song/Cargo.toml
index 050dda2a..cef5a9ab 100644
--- a/systems/song/Cargo.toml
+++ b/systems/song/Cargo.toml
@@ -13,6 +13,8 @@ denoise = ["dep:deep_filter", "dep:ndarray"]
# frames come from the media plane (VideoToolbox on Apple, ffmpeg or the software decoders elsewhere)
raea-io-media = { path = "../../io/media", default-features = false, features = ["apple"] }
raea-sys-vision = { path = "../vision" }
+# where its models are kept (raea_io_home::models)
+raea-io-home = { path = "../../io/home" }
serde_json = "1"
# TransNetV2 (MIT) through its ONNX export, the same ort pin and prebuilt runtime as ugc-embed
ort = "=2.0.0-rc.13"
diff --git a/systems/song/src/beatthis.rs b/systems/song/src/beatthis.rs
index 1dc8143a..9321be47 100644
--- a/systems/song/src/beatthis.rs
+++ b/systems/song/src/beatthis.rs
@@ -21,7 +21,7 @@ const CHUNK: usize = 1500;
const BORDER: usize = 6;
pub fn model_path() -> PathBuf {
- PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models/beat-this/beat_this_small0.onnx")
+ raea_io_home::models().join("beat-this/beat_this_small0.onnx")
}
pub fn fft(re: &mut [f64], im: &mut [f64]) {
diff --git a/systems/song/src/stems.rs b/systems/song/src/stems.rs
index 34fc76ae..3325aefd 100644
--- a/systems/song/src/stems.rs
+++ b/systems/song/src/stems.rs
@@ -19,7 +19,7 @@ const HOP: usize = 1024;
const FQ: usize = NFFT / 2;
pub fn model_path() -> PathBuf {
- PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models/htdemucs/htdemucs_core.onnx")
+ raea_io_home::models().join("htdemucs/htdemucs_core.onnx")
}
fn fft(re: &mut [f64], im: &mut [f64], inverse: bool) {
diff --git a/systems/song/src/transnet.rs b/systems/song/src/transnet.rs
index 6bf012ee..ff0c8004 100644
--- a/systems/song/src/transnet.rs
+++ b/systems/song/src/transnet.rs
@@ -9,7 +9,7 @@ use ort::session::Session;
use ort::value::Tensor;
pub fn model_path() -> PathBuf {
- PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models/transnetv2/transnetv2.onnx")
+ raea_io_home::models().join("transnetv2/transnetv2.onnx")
}
pub struct TransNet(Session);
diff --git a/systems/song/src/vad.rs b/systems/song/src/vad.rs
index 322c01ad..cc645514 100644
--- a/systems/song/src/vad.rs
+++ b/systems/song/src/vad.rs
@@ -14,7 +14,7 @@ const WIN: usize = 512;
const CTX: usize = 64;
pub fn model_path() -> PathBuf {
- PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models/silero-vad/silero_vad.onnx")
+ raea_io_home::models().join("silero-vad/silero_vad.onnx")
}
pub struct Vad(Session);
diff --git a/systems/vision/Cargo.toml b/systems/vision/Cargo.toml
index 9ec6b3b8..09518df4 100644
--- a/systems/vision/Cargo.toml
+++ b/systems/vision/Cargo.toml
@@ -12,6 +12,8 @@ raea-io-media = { path = "../../io/media", default-features = false, features =
raea-sys-layout = { path = "../layout" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+# the layout reader's grey copy (vision.rs grey), on every platform
+image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
[target.'cfg(target_vendor = "apple")'.dependencies]
objc2 = "0.6"
@@ -21,4 +23,3 @@ objc2-core-video = { version = "0.3", features = ["CVPixelBuffer", "CVImageBuffe
objc2-core-foundation = "0.3"
objc2-core-graphics = { version = "0.3", features = ["CGImage", "CGColorSpace", "CGDataProvider"] }
objc2-vision = { version = "0.3", features = ["VNRequestHandler", "VNRequest", "VNDetectFaceRectanglesRequest", "VNGeneratePersonSegmentationRequest", "VNRecognizeTextRequest", "VNDetectRectanglesRequest", "VNClassifyImageRequest", "VNDetectHumanRectanglesRequest", "VNGenerateAttentionBasedSaliencyImageRequest", "VNCalculateImageAestheticsScoresRequest", "VNGenerateImageFeaturePrintRequest", "VNGenerateOpticalFlowRequest", "VNTargetedImageRequest", "VNObservation", "VNTypes", "VNStatefulRequest", "objc2-core-video", "objc2-core-image", "objc2-core-graphics"] }
-image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
diff --git a/systems/vision/src/apple_vision.rs b/systems/vision/src/apple_vision.rs
new file mode 100644
index 00000000..513bb1ce
--- /dev/null
+++ b/systems/vision/src/apple_vision.rs
@@ -0,0 +1,296 @@
+//! Apple Vision behind the Vision trait (vision.rs): its requests through objc2, with the settings Perception.swift uses.
+
+use objc2::rc::Retained;
+use objc2::AnyThread;
+use objc2_core_video::{
+ CVPixelBufferGetBaseAddress, CVPixelBufferGetBytesPerRow, CVPixelBufferGetHeight, CVPixelBufferGetWidth, CVPixelBufferLockBaseAddress,
+ CVPixelBufferLockFlags, CVPixelBufferUnlockBaseAddress,
+};
+use objc2_foundation::{NSArray, NSDictionary};
+use objc2_vision::{
+ VNCalculateImageAestheticsScoresRequest, VNClassifyImageRequest, VNDetectFaceRectanglesRequest, VNDetectHumanRectanglesRequest,
+ VNGenerateAttentionBasedSaliencyImageRequest, VNGenerateImageFeaturePrintRequest, VNDetectRectanglesRequest, VNGeneratePersonSegmentationRequest,
+ VNGeneratePersonSegmentationRequestQualityLevel, VNImageRequestHandler, VNRecognizeTextRequest, VNRequest, VNRequestTextRecognitionLevel,
+};
+
+use raea_sys_layout::layout::Rect;
+
+use crate::vision::{People, Read, Seen, Vision};
+
+fn r2(x: f64) -> f64 {
+ (x * 100.0).round() / 100.0
+}
+
+/// A box as the Swift's facts round it (two decimals).
+fn rounded_box(r: Rect) -> [f64; 4] {
+ [r2(r.x), r2(r.y), r2(r.w), r2(r.h)]
+}
+
+/// RGBA8 as an sRGB CGImage, as the Swift hands Vision a decoded picture.
+fn cg_image(rgba: &[u8], w: usize, h: usize) -> Result<objc2_core_foundation::CFRetained<objc2_core_graphics::CGImage>, String> {
+ use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGDataProvider, CGImage, CGImageAlphaInfo, kCGColorSpaceSRGB};
+ let data = objc2_core_foundation::CFData::from_bytes(rgba);
+ let provider = CGDataProvider::with_cf_data(Some(&data)).ok_or("no data provider")?;
+ let space = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB })).ok_or("no sRGB")?;
+ unsafe {
+ CGImage::new(w, h, 8, 32, w * 4, Some(&space), CGBitmapInfo(CGImageAlphaInfo::NoneSkipLast.0), Some(&provider), std::ptr::null(), false,
+ CGColorRenderingIntent::RenderingIntentDefault)
+ }
+ .ok_or_else(|| "CGImageCreate failed".to_string())
+}
+
+pub struct AppleVision {
+ /// the person mask's quality: balanced for layout, fast for the live coach
+ pub quality: VNGeneratePersonSegmentationRequestQualityLevel,
+}
+
+impl Default for AppleVision {
+ fn default() -> Self {
+ AppleVision { quality: VNGeneratePersonSegmentationRequestQualityLevel::Balanced }
+ }
+}
+
+/// Vision's box (origin bottom left) as one from the top left.
+fn rect(b: objc2_core_foundation::CGRect) -> Rect {
+ Rect::new(b.origin.x, 1.0 - (b.origin.y + b.size.height), b.size.width, b.size.height)
+}
+
+impl Vision for AppleVision {
+ fn see(&self, rgba: &[u8], pw: usize, ph: usize) -> Result<Seen, String> {
+ let image = cg_image(rgba, pw, ph)?;
+ let (w, h) = (pw as f64, ph as f64);
+ let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
+ let faces = unsafe { VNDetectFaceRectanglesRequest::new() };
+ let text = VNRecognizeTextRequest::new();
+ text.setRecognitionLevel(VNRequestTextRecognitionLevel::Fast);
+ text.setUsesLanguageCorrection(false);
+ let person = unsafe { VNGeneratePersonSegmentationRequest::new() };
+ unsafe { person.setQualityLevel(self.quality) };
+ let rects = unsafe { VNDetectRectanglesRequest::new() };
+ unsafe {
+ rects.setMaximumObservations(8);
+ rects.setMinimumSize(0.08);
+ rects.setMinimumAspectRatio(0.2);
+ rects.setQuadratureTolerance(20.0); // screens shown at an angle are quads, not rectangles
+ }
+ let classify = unsafe { VNClassifyImageRequest::new() };
+ // one request at a time, as the Swift performs them
+ let requests: [&VNRequest; 5] = [&faces, &text, &person, &rects, &classify];
+ for r in requests {
+ let _ = handler.performRequests_error(&NSArray::from_slice(&[r]));
+ }
+ let mut seen = Seen::default();
+ if let Some(rs) = unsafe { faces.results() } {
+ seen.faces = rs.iter().map(|o| rect(unsafe { o.boundingBox() })).filter(|r| r.area() > 0.0015).collect();
+ }
+ if let Some(rs) = text.results() {
+ for o in rs.iter() {
+ let Some(top) = o.topCandidates(1).firstObject() else { continue };
+ if top.confidence() <= 0.3 {
+ continue;
+ }
+ let (tl, tr) = (unsafe { o.topLeft() }, unsafe { o.topRight() });
+ let tilt = ((tr.y - tl.y) * h).atan2((tr.x - tl.x) * w).abs().to_degrees();
+ if tilt < 2.5 {
+ seen.lines.push((rect(unsafe { o.boundingBox() }), top.string().to_string()));
+ }
+ }
+ }
+ if let Some(rs) = unsafe { rects.results() } {
+ seen.rects = rs.iter().map(|o| rect(unsafe { o.boundingBox() })).collect();
+ }
+ if let Some(rs) = unsafe { classify.results() } {
+ seen.screenshot = rs.iter().any(|o| unsafe { o.identifier() }.to_string() == "screenshot" && unsafe { o.confidence() } >= 0.3);
+ }
+ if let Some(m) = unsafe { person.results() }.and_then(|r| r.firstObject()) {
+ let buf: Retained<_> = unsafe { m.pixelBuffer() };
+ unsafe { CVPixelBufferLockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
+ let (mw, mh, row) = (CVPixelBufferGetWidth(&buf), CVPixelBufferGetHeight(&buf), CVPixelBufferGetBytesPerRow(&buf));
+ let base = CVPixelBufferGetBaseAddress(&buf) as *const u8;
+ if !base.is_null() {
+ seen.mask = (0..mh).flat_map(|y| (0..mw).map(move |x| unsafe { *base.add(y * row + x) })).collect();
+ (seen.mw, seen.mh) = (mw, mh);
+ }
+ unsafe { CVPixelBufferUnlockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
+ }
+ Ok(seen)
+ }
+
+ fn attention(&self, rgba: &[u8], w: usize, h: usize) -> Result<Option<(Vec<f32>, usize, usize)>, String> {
+ let image = cg_image(rgba, w, h)?;
+ let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
+ let req = unsafe { VNGenerateAttentionBasedSaliencyImageRequest::new() };
+ let _ = handler.performRequests_error(&NSArray::from_slice(&[&*req as &VNRequest]));
+ let Some(o) = unsafe { req.results() }.and_then(|r| r.firstObject()) else { return Ok(None) };
+ let buf: Retained<_> = unsafe { o.pixelBuffer() };
+ unsafe { CVPixelBufferLockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
+ let (mw, mh, row) = (CVPixelBufferGetWidth(&buf), CVPixelBufferGetHeight(&buf), CVPixelBufferGetBytesPerRow(&buf));
+ let base = CVPixelBufferGetBaseAddress(&buf) as *const u8;
+ let map = if base.is_null() {
+ None
+ } else {
+ // one float a pixel (OneComponent32Float)
+ Some((0..mh).flat_map(|y| (0..mw).map(move |x| unsafe { *(base.add(y * row) as *const f32).add(x) })).collect::<Vec<f32>>())
+ };
+ unsafe { CVPixelBufferUnlockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
+ Ok(map.map(|m| (m, mw, mh)))
+ }
+
+ fn room(&self, rgba: &[u8], w: usize, h: usize) -> Result<Option<Vec<f32>>, String> {
+ let p = self.people(rgba, w, h, false)?;
+ let mut masked = rgba.to_vec();
+ if p.mw > 0 {
+ // the mask scaled to the frame (bilinear at pixel centres), the person blended to black
+ let m = |x: f64, y: f64| -> f64 {
+ let (fx, fy) = ((x + 0.5) * p.mw as f64 / w as f64 - 0.5, (y + 0.5) * p.mh as f64 / h as f64 - 0.5);
+ let (x0, y0) = (fx.floor().max(0.0) as usize, fy.floor().max(0.0) as usize);
+ let (x1, y1) = ((x0 + 1).min(p.mw - 1), (y0 + 1).min(p.mh - 1));
+ let (tx, ty) = ((fx - x0 as f64).clamp(0.0, 1.0), (fy - y0 as f64).clamp(0.0, 1.0));
+ let at = |x: usize, y: usize| p.mask[y * p.mw + x] as f64 / 255.0;
+ (at(x0, y0) * (1.0 - tx) + at(x1, y0) * tx) * (1.0 - ty) + (at(x0, y1) * (1.0 - tx) + at(x1, y1) * tx) * ty
+ };
+ for y in 0..h {
+ for x in 0..w {
+ let k = 1.0 - m(x as f64, y as f64);
+ let o = (y * w + x) * 4;
+ for c in 0..3 {
+ masked[o + c] = (masked[o + c] as f64 * k).round() as u8;
+ }
+ }
+ }
+ }
+ let image = cg_image(&masked, w, h)?;
+ let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
+ let print = unsafe { VNGenerateImageFeaturePrintRequest::new() };
+ let _ = handler.performRequests_error(&NSArray::from_slice(&[&*print as &VNRequest]));
+ let Some(fp) = unsafe { print.results() }.and_then(|r| r.firstObject()) else { return Ok(None) };
+ let n = unsafe { fp.elementCount() };
+ let data = unsafe { fp.data() };
+ let bytes = data.to_vec();
+ if bytes.len() < n * 4 {
+ return Ok(None);
+ }
+ Ok(Some((0..n).map(|i| (f32::from_le_bytes([bytes[i * 4], bytes[i * 4 + 1], bytes[i * 4 + 2], bytes[i * 4 + 3]]) * 1000.0).round() / 1000.0).collect()))
+ }
+
+ fn people(&self, rgba: &[u8], w: usize, h: usize, fast: bool) -> Result<People, String> {
+ let image = cg_image(rgba, w, h)?;
+ let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
+ let faces = unsafe { VNDetectFaceRectanglesRequest::new() };
+ let person = unsafe { VNGeneratePersonSegmentationRequest::new() };
+ unsafe {
+ person.setQualityLevel(if fast { VNGeneratePersonSegmentationRequestQualityLevel::Fast } else { VNGeneratePersonSegmentationRequestQualityLevel::Balanced })
+ };
+ for r in [&*faces as &VNRequest, &*person as &VNRequest] {
+ let _ = handler.performRequests_error(&NSArray::from_slice(&[r]));
+ }
+ let mut out = People::default();
+ let found: Vec<(Rect, f32)> = unsafe { faces.results() }
+ .map(|r| r.iter().map(|o| (rect(unsafe { o.boundingBox() }), unsafe { o.confidence() })).filter(|(r, _)| r.area() > 0.0015).collect())
+ .unwrap_or_default();
+ out.face_conf = found.iter().map(|f| f.1).collect();
+ out.faces = found.into_iter().map(|f| f.0).collect();
+ if let Some(m) = unsafe { person.results() }.and_then(|r| r.firstObject()) {
+ let buf: Retained<_> = unsafe { m.pixelBuffer() };
+ unsafe { CVPixelBufferLockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
+ let (mw, mh, row) = (CVPixelBufferGetWidth(&buf), CVPixelBufferGetHeight(&buf), CVPixelBufferGetBytesPerRow(&buf));
+ let base = CVPixelBufferGetBaseAddress(&buf) as *const u8;
+ if !base.is_null() {
+ out.mask = (0..mh).flat_map(|y| (0..mw).map(move |x| unsafe { *base.add(y * row + x) })).collect();
+ (out.mw, out.mh) = (mw, mh);
+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);
+ for y in 0..mh {
+ for x in 0..mw {
+ if out.mask[y * mw + x] > 127 {
+ (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));
+ }
+ }
+ }
+ if x0 != usize::MAX {
+ out.person = Some(Rect::new(x0 as f64 / mw as f64, y0 as f64 / mh as f64, (x1 - x0 + 1) as f64 / mw as f64, (y1 - y0 + 1) as f64 / mh as f64));
+ }
+ }
+ unsafe { CVPixelBufferUnlockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
+ }
+ Ok(out)
+ }
+
+ fn read(&self, rgba: &[u8], w: usize, h: usize, ocr: bool) -> Result<Read, String> {
+ let image = cg_image(rgba, w, h)?;
+ let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
+ let faces = unsafe { VNDetectFaceRectanglesRequest::new() };
+ let bodies = unsafe { VNDetectHumanRectanglesRequest::new() };
+ let attention = unsafe { VNGenerateAttentionBasedSaliencyImageRequest::new() };
+ let classify = unsafe { VNClassifyImageRequest::new() };
+ let aesthetics = unsafe { VNCalculateImageAestheticsScoresRequest::new() };
+ // one at a time: a request the device can't run mustn't take the others with it
+ let requests: [&VNRequest; 5] = [&faces, &bodies, &attention, &classify, &aesthetics];
+ for r in requests {
+ let _ = handler.performRequests_error(&NSArray::from_slice(&[r]));
+ }
+ let mut out = Read { framing: "no people".into(), ..Default::default() };
+ let found: Vec<Rect> = unsafe { faces.results() }.map(|r| r.iter().map(|o| rect(unsafe { o.boundingBox() })).collect()).unwrap_or_default();
+ out.faces = found.len();
+ if let Some(biggest) = found.iter().map(|f| f.h).fold(None::<f64>, |b, v| Some(b.map_or(v, |b| b.max(v)))) {
+ out.framing = if biggest >= 0.22 { "close-up" } else if biggest >= 0.09 { "medium" } else { "wide" }.into();
+ } else if unsafe { bodies.results() }.is_some_and(|r| r.count() > 0) {
+ out.framing = "wide".into();
+ }
+ if let Some(objs) = unsafe { attention.results() }.and_then(|r| r.firstObject()).and_then(|o| unsafe { o.salientObjects() }) {
+ // Swift's max(by:): the first of the most confident
+ let best = objs.iter().fold(None::<Retained<objc2_vision::VNRectangleObservation>>, |b, o| match b {
+ Some(b) if unsafe { b.confidence() } >= unsafe { o.confidence() } => Some(b),
+ _ => Some(o),
+ });
+ out.subject = best.map(|o| rounded_box(rect(unsafe { o.boundingBox() })));
+ }
+ out.look = unsafe { aesthetics.results() }.and_then(|r| r.firstObject()).map(|o| r2(unsafe { o.overallScore() } as f64));
+ if let Some(rs) = unsafe { classify.results() } {
+ out.scene = rs.iter().filter(|o| unsafe { o.confidence() } >= 0.3).take(4).map(|o| unsafe { o.identifier() }.to_string().replace('_', " ")).collect();
+ }
+ if ocr {
+ let text = VNRecognizeTextRequest::new();
+ text.setRecognitionLevel(VNRequestTextRecognitionLevel::Accurate);
+ text.setUsesLanguageCorrection(true);
+ text.setMinimumTextHeight(0.015);
+ let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
+ let _ = handler.performRequests_error(&NSArray::from_slice(&[&*text as &VNRequest]));
+ if let Some(rs) = text.results() {
+ for o in rs.iter() {
+ let Some(c) = o.topCandidates(1).firstObject() else { continue };
+ if c.confidence() < 0.4 {
+ continue;
+ }
+ let t = c.string().to_string().trim().to_string();
+ if t.chars().filter(|ch| ch.is_alphanumeric()).count() >= 2 {
+ out.words.push((t, rounded_box(rect(unsafe { o.boundingBox() }))));
+ }
+ }
+ }
+ }
+ Ok(out)
+ }
+}
+
+/// Every line of text Apple Vision reads accurately in a frame (docs/goal.feature J1), with its confidence and its box (0..1
+/// of the frame, from the top left, unrounded): no language correction (captions aren't prose), lines at least 1.5% of
+/// the frame high.
+pub fn text_lines(rgba: &[u8], w: usize, h: usize) -> Result<Vec<(String, f32, [f64; 4])>, String> {
+ let image = cg_image(rgba, w, h)?;
+ let text = VNRecognizeTextRequest::new();
+ text.setRecognitionLevel(VNRequestTextRecognitionLevel::Accurate);
+ text.setUsesLanguageCorrection(false);
+ text.setMinimumTextHeight(0.015);
+ let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
+ let _ = handler.performRequests_error(&NSArray::from_slice(&[&*text as &VNRequest]));
+ let mut out = Vec::new();
+ if let Some(rs) = text.results() {
+ for o in rs.iter() {
+ let Some(c) = o.topCandidates(1).firstObject() else { continue };
+ let r = rect(unsafe { o.boundingBox() });
+ out.push((c.string().to_string(), c.confidence(), [r.x, r.y, r.w, r.h]));
+ }
+ }
+ Ok(out)
+}
+
diff --git a/systems/vision/src/lib.rs b/systems/vision/src/lib.rs
index d3399cbc..ca940808 100644
--- a/systems/vision/src/lib.rs
+++ b/systems/vision/src/lib.rs
@@ -11,11 +11,15 @@ pub mod face;
pub mod hands;
#[cfg(target_vendor = "apple")]
pub mod hair;
+#[cfg(target_vendor = "apple")]
pub mod depth;
+#[cfg(target_vendor = "apple")]
pub mod object;
#[cfg(target_vendor = "apple")]
pub mod flow;
pub mod vision;
+#[cfg(target_vendor = "apple")]
+mod apple_vision;
pub mod textread;
pub mod camera;
#[cfg(target_vendor = "apple")]
diff --git a/systems/vision/src/textread.rs b/systems/vision/src/textread.rs
index eb2b1dd7..e067393a 100644
--- a/systems/vision/src/textread.rs
+++ b/systems/vision/src/textread.rs
@@ -4,6 +4,7 @@
//! its text, its first and last frame, and its median box. The rows read can then be set against the rows an edit
//! wrote (what J1 is graded on: our own renders, whose true rows are known).
+#[cfg(target_vendor = "apple")]
use std::path::Path;
/// Frames a line may go unread inside a row before the row ends (a word Vision drops for a frame or two).
diff --git a/systems/vision/src/vision.rs b/systems/vision/src/vision.rs
index 8f9233db..2aad4ae4 100644
--- a/systems/vision/src/vision.rs
+++ b/systems/vision/src/vision.rs
@@ -1,19 +1,7 @@
//! What Apple Vision sees in a frame, behind one trait (docs/goal.feature A3): faces, text lines, rectangles, the person
//! mask and whether the picture is a screenshot. AppleVision runs Vision's requests through objc2 with the settings
-//! Perception.swift uses; another implementation (models elsewhere) can stand in on other platforms.
-
-use objc2::rc::Retained;
-use objc2::AnyThread;
-use objc2_core_video::{
- CVPixelBufferGetBaseAddress, CVPixelBufferGetBytesPerRow, CVPixelBufferGetHeight, CVPixelBufferGetWidth, CVPixelBufferLockBaseAddress,
- CVPixelBufferLockFlags, CVPixelBufferUnlockBaseAddress,
-};
-use objc2_foundation::{NSArray, NSDictionary};
-use objc2_vision::{
- VNCalculateImageAestheticsScoresRequest, VNClassifyImageRequest, VNDetectFaceRectanglesRequest, VNDetectHumanRectanglesRequest,
- VNGenerateAttentionBasedSaliencyImageRequest, VNGenerateImageFeaturePrintRequest, VNDetectRectanglesRequest, VNGeneratePersonSegmentationRequest,
- VNGeneratePersonSegmentationRequestQualityLevel, VNImageRequestHandler, VNRecognizeTextRequest, VNRequest, VNRequestTextRecognitionLevel,
-};
+//! Perception.swift uses (apple_vision.rs); another implementation (raea-sys-perceive's portable models) stands in on
+//! other platforms.
use raea_sys_layout::layout::Rect;
@@ -78,282 +66,9 @@ pub struct Read {
pub words: Vec<(String, [f64; 4])>,
}
-fn r2(x: f64) -> f64 {
- (x * 100.0).round() / 100.0
-}
-
-/// A box as the Swift's facts round it (two decimals).
-fn rounded_box(r: Rect) -> [f64; 4] {
- [r2(r.x), r2(r.y), r2(r.w), r2(r.h)]
-}
-
-/// RGBA8 as an sRGB CGImage, as the Swift hands Vision a decoded picture.
-fn cg_image(rgba: &[u8], w: usize, h: usize) -> Result<objc2_core_foundation::CFRetained<objc2_core_graphics::CGImage>, String> {
- use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGDataProvider, CGImage, CGImageAlphaInfo, kCGColorSpaceSRGB};
- let data = objc2_core_foundation::CFData::from_bytes(rgba);
- let provider = CGDataProvider::with_cf_data(Some(&data)).ok_or("no data provider")?;
- let space = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB })).ok_or("no sRGB")?;
- unsafe {
- CGImage::new(w, h, 8, 32, w * 4, Some(&space), CGBitmapInfo(CGImageAlphaInfo::NoneSkipLast.0), Some(&provider), std::ptr::null(), false,
- CGColorRenderingIntent::RenderingIntentDefault)
- }
- .ok_or_else(|| "CGImageCreate failed".to_string())
-}
-
-pub struct AppleVision {
- /// the person mask's quality: balanced for layout, fast for the live coach
- pub quality: VNGeneratePersonSegmentationRequestQualityLevel,
-}
-
-impl Default for AppleVision {
- fn default() -> Self {
- AppleVision { quality: VNGeneratePersonSegmentationRequestQualityLevel::Balanced }
- }
-}
-
-/// Vision's box (origin bottom left) as one from the top left.
-fn rect(b: objc2_core_foundation::CGRect) -> Rect {
- Rect::new(b.origin.x, 1.0 - (b.origin.y + b.size.height), b.size.width, b.size.height)
-}
-
-impl Vision for AppleVision {
- fn see(&self, rgba: &[u8], pw: usize, ph: usize) -> Result<Seen, String> {
- let image = cg_image(rgba, pw, ph)?;
- let (w, h) = (pw as f64, ph as f64);
- let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
- let faces = unsafe { VNDetectFaceRectanglesRequest::new() };
- let text = VNRecognizeTextRequest::new();
- text.setRecognitionLevel(VNRequestTextRecognitionLevel::Fast);
- text.setUsesLanguageCorrection(false);
- let person = unsafe { VNGeneratePersonSegmentationRequest::new() };
- unsafe { person.setQualityLevel(self.quality) };
- let rects = unsafe { VNDetectRectanglesRequest::new() };
- unsafe {
- rects.setMaximumObservations(8);
- rects.setMinimumSize(0.08);
- rects.setMinimumAspectRatio(0.2);
- rects.setQuadratureTolerance(20.0); // screens shown at an angle are quads, not rectangles
- }
- let classify = unsafe { VNClassifyImageRequest::new() };
- // one request at a time, as the Swift performs them
- let requests: [&VNRequest; 5] = [&faces, &text, &person, &rects, &classify];
- for r in requests {
- let _ = handler.performRequests_error(&NSArray::from_slice(&[r]));
- }
- let mut seen = Seen::default();
- if let Some(rs) = unsafe { faces.results() } {
- seen.faces = rs.iter().map(|o| rect(unsafe { o.boundingBox() })).filter(|r| r.area() > 0.0015).collect();
- }
- if let Some(rs) = text.results() {
- for o in rs.iter() {
- let Some(top) = o.topCandidates(1).firstObject() else { continue };
- if top.confidence() <= 0.3 {
- continue;
- }
- let (tl, tr) = (unsafe { o.topLeft() }, unsafe { o.topRight() });
- let tilt = ((tr.y - tl.y) * h).atan2((tr.x - tl.x) * w).abs().to_degrees();
- if tilt < 2.5 {
- seen.lines.push((rect(unsafe { o.boundingBox() }), top.string().to_string()));
- }
- }
- }
- if let Some(rs) = unsafe { rects.results() } {
- seen.rects = rs.iter().map(|o| rect(unsafe { o.boundingBox() })).collect();
- }
- if let Some(rs) = unsafe { classify.results() } {
- seen.screenshot = rs.iter().any(|o| unsafe { o.identifier() }.to_string() == "screenshot" && unsafe { o.confidence() } >= 0.3);
- }
- if let Some(m) = unsafe { person.results() }.and_then(|r| r.firstObject()) {
- let buf: Retained<_> = unsafe { m.pixelBuffer() };
- unsafe { CVPixelBufferLockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
- let (mw, mh, row) = (CVPixelBufferGetWidth(&buf), CVPixelBufferGetHeight(&buf), CVPixelBufferGetBytesPerRow(&buf));
- let base = CVPixelBufferGetBaseAddress(&buf) as *const u8;
- if !base.is_null() {
- seen.mask = (0..mh).flat_map(|y| (0..mw).map(move |x| unsafe { *base.add(y * row + x) })).collect();
- (seen.mw, seen.mh) = (mw, mh);
- }
- unsafe { CVPixelBufferUnlockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
- }
- Ok(seen)
- }
-
- fn attention(&self, rgba: &[u8], w: usize, h: usize) -> Result<Option<(Vec<f32>, usize, usize)>, String> {
- let image = cg_image(rgba, w, h)?;
- let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
- let req = unsafe { VNGenerateAttentionBasedSaliencyImageRequest::new() };
- let _ = handler.performRequests_error(&NSArray::from_slice(&[&*req as &VNRequest]));
- let Some(o) = unsafe { req.results() }.and_then(|r| r.firstObject()) else { return Ok(None) };
- let buf: Retained<_> = unsafe { o.pixelBuffer() };
- unsafe { CVPixelBufferLockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
- let (mw, mh, row) = (CVPixelBufferGetWidth(&buf), CVPixelBufferGetHeight(&buf), CVPixelBufferGetBytesPerRow(&buf));
- let base = CVPixelBufferGetBaseAddress(&buf) as *const u8;
- let map = if base.is_null() {
- None
- } else {
- // one float a pixel (OneComponent32Float)
- Some((0..mh).flat_map(|y| (0..mw).map(move |x| unsafe { *(base.add(y * row) as *const f32).add(x) })).collect::<Vec<f32>>())
- };
- unsafe { CVPixelBufferUnlockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
- Ok(map.map(|m| (m, mw, mh)))
- }
-
- fn room(&self, rgba: &[u8], w: usize, h: usize) -> Result<Option<Vec<f32>>, String> {
- let p = self.people(rgba, w, h, false)?;
- let mut masked = rgba.to_vec();
- if p.mw > 0 {
- // the mask scaled to the frame (bilinear at pixel centres), the person blended to black
- let m = |x: f64, y: f64| -> f64 {
- let (fx, fy) = ((x + 0.5) * p.mw as f64 / w as f64 - 0.5, (y + 0.5) * p.mh as f64 / h as f64 - 0.5);
- let (x0, y0) = (fx.floor().max(0.0) as usize, fy.floor().max(0.0) as usize);
- let (x1, y1) = ((x0 + 1).min(p.mw - 1), (y0 + 1).min(p.mh - 1));
- let (tx, ty) = ((fx - x0 as f64).clamp(0.0, 1.0), (fy - y0 as f64).clamp(0.0, 1.0));
- let at = |x: usize, y: usize| p.mask[y * p.mw + x] as f64 / 255.0;
- (at(x0, y0) * (1.0 - tx) + at(x1, y0) * tx) * (1.0 - ty) + (at(x0, y1) * (1.0 - tx) + at(x1, y1) * tx) * ty
- };
- for y in 0..h {
- for x in 0..w {
- let k = 1.0 - m(x as f64, y as f64);
- let o = (y * w + x) * 4;
- for c in 0..3 {
- masked[o + c] = (masked[o + c] as f64 * k).round() as u8;
- }
- }
- }
- }
- let image = cg_image(&masked, w, h)?;
- let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
- let print = unsafe { VNGenerateImageFeaturePrintRequest::new() };
- let _ = handler.performRequests_error(&NSArray::from_slice(&[&*print as &VNRequest]));
- let Some(fp) = unsafe { print.results() }.and_then(|r| r.firstObject()) else { return Ok(None) };
- let n = unsafe { fp.elementCount() };
- let data = unsafe { fp.data() };
- let bytes = data.to_vec();
- if bytes.len() < n * 4 {
- return Ok(None);
- }
- Ok(Some((0..n).map(|i| (f32::from_le_bytes([bytes[i * 4], bytes[i * 4 + 1], bytes[i * 4 + 2], bytes[i * 4 + 3]]) * 1000.0).round() / 1000.0).collect()))
- }
-
- fn people(&self, rgba: &[u8], w: usize, h: usize, fast: bool) -> Result<People, String> {
- let image = cg_image(rgba, w, h)?;
- let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
- let faces = unsafe { VNDetectFaceRectanglesRequest::new() };
- let person = unsafe { VNGeneratePersonSegmentationRequest::new() };
- unsafe {
- person.setQualityLevel(if fast { VNGeneratePersonSegmentationRequestQualityLevel::Fast } else { VNGeneratePersonSegmentationRequestQualityLevel::Balanced })
- };
- for r in [&*faces as &VNRequest, &*person as &VNRequest] {
- let _ = handler.performRequests_error(&NSArray::from_slice(&[r]));
- }
- let mut out = People::default();
- let found: Vec<(Rect, f32)> = unsafe { faces.results() }
- .map(|r| r.iter().map(|o| (rect(unsafe { o.boundingBox() }), unsafe { o.confidence() })).filter(|(r, _)| r.area() > 0.0015).collect())
- .unwrap_or_default();
- out.face_conf = found.iter().map(|f| f.1).collect();
- out.faces = found.into_iter().map(|f| f.0).collect();
- if let Some(m) = unsafe { person.results() }.and_then(|r| r.firstObject()) {
- let buf: Retained<_> = unsafe { m.pixelBuffer() };
- unsafe { CVPixelBufferLockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
- let (mw, mh, row) = (CVPixelBufferGetWidth(&buf), CVPixelBufferGetHeight(&buf), CVPixelBufferGetBytesPerRow(&buf));
- let base = CVPixelBufferGetBaseAddress(&buf) as *const u8;
- if !base.is_null() {
- out.mask = (0..mh).flat_map(|y| (0..mw).map(move |x| unsafe { *base.add(y * row + x) })).collect();
- (out.mw, out.mh) = (mw, mh);
- let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);
- for y in 0..mh {
- for x in 0..mw {
- if out.mask[y * mw + x] > 127 {
- (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));
- }
- }
- }
- if x0 != usize::MAX {
- out.person = Some(Rect::new(x0 as f64 / mw as f64, y0 as f64 / mh as f64, (x1 - x0 + 1) as f64 / mw as f64, (y1 - y0 + 1) as f64 / mh as f64));
- }
- }
- unsafe { CVPixelBufferUnlockBaseAddress(&buf, CVPixelBufferLockFlags::ReadOnly) };
- }
- Ok(out)
- }
-
- fn read(&self, rgba: &[u8], w: usize, h: usize, ocr: bool) -> Result<Read, String> {
- let image = cg_image(rgba, w, h)?;
- let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
- let faces = unsafe { VNDetectFaceRectanglesRequest::new() };
- let bodies = unsafe { VNDetectHumanRectanglesRequest::new() };
- let attention = unsafe { VNGenerateAttentionBasedSaliencyImageRequest::new() };
- let classify = unsafe { VNClassifyImageRequest::new() };
- let aesthetics = unsafe { VNCalculateImageAestheticsScoresRequest::new() };
- // one at a time: a request the device can't run mustn't take the others with it
- let requests: [&VNRequest; 5] = [&faces, &bodies, &attention, &classify, &aesthetics];
- for r in requests {
- let _ = handler.performRequests_error(&NSArray::from_slice(&[r]));
- }
- let mut out = Read { framing: "no people".into(), ..Default::default() };
- let found: Vec<Rect> = unsafe { faces.results() }.map(|r| r.iter().map(|o| rect(unsafe { o.boundingBox() })).collect()).unwrap_or_default();
- out.faces = found.len();
- if let Some(biggest) = found.iter().map(|f| f.h).fold(None::<f64>, |b, v| Some(b.map_or(v, |b| b.max(v)))) {
- out.framing = if biggest >= 0.22 { "close-up" } else if biggest >= 0.09 { "medium" } else { "wide" }.into();
- } else if unsafe { bodies.results() }.is_some_and(|r| r.count() > 0) {
- out.framing = "wide".into();
- }
- if let Some(objs) = unsafe { attention.results() }.and_then(|r| r.firstObject()).and_then(|o| unsafe { o.salientObjects() }) {
- // Swift's max(by:): the first of the most confident
- let best = objs.iter().fold(None::<Retained<objc2_vision::VNRectangleObservation>>, |b, o| match b {
- Some(b) if unsafe { b.confidence() } >= unsafe { o.confidence() } => Some(b),
- _ => Some(o),
- });
- out.subject = best.map(|o| rounded_box(rect(unsafe { o.boundingBox() })));
- }
- out.look = unsafe { aesthetics.results() }.and_then(|r| r.firstObject()).map(|o| r2(unsafe { o.overallScore() } as f64));
- if let Some(rs) = unsafe { classify.results() } {
- out.scene = rs.iter().filter(|o| unsafe { o.confidence() } >= 0.3).take(4).map(|o| unsafe { o.identifier() }.to_string().replace('_', " ")).collect();
- }
- if ocr {
- let text = VNRecognizeTextRequest::new();
- text.setRecognitionLevel(VNRequestTextRecognitionLevel::Accurate);
- text.setUsesLanguageCorrection(true);
- text.setMinimumTextHeight(0.015);
- let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
- let _ = handler.performRequests_error(&NSArray::from_slice(&[&*text as &VNRequest]));
- if let Some(rs) = text.results() {
- for o in rs.iter() {
- let Some(c) = o.topCandidates(1).firstObject() else { continue };
- if c.confidence() < 0.4 {
- continue;
- }
- let t = c.string().to_string().trim().to_string();
- if t.chars().filter(|ch| ch.is_alphanumeric()).count() >= 2 {
- out.words.push((t, rounded_box(rect(unsafe { o.boundingBox() }))));
- }
- }
- }
- }
- Ok(out)
- }
-}
-
-/// Every line of text Apple Vision reads accurately in a frame (docs/goal.feature J1), with its confidence and its box (0..1
-/// of the frame, from the top left, unrounded): no language correction (captions aren't prose), lines at least 1.5% of
-/// the frame high.
-pub fn text_lines(rgba: &[u8], w: usize, h: usize) -> Result<Vec<(String, f32, [f64; 4])>, String> {
- let image = cg_image(rgba, w, h)?;
- let text = VNRecognizeTextRequest::new();
- text.setRecognitionLevel(VNRequestTextRecognitionLevel::Accurate);
- text.setUsesLanguageCorrection(false);
- text.setMinimumTextHeight(0.015);
- let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
- let _ = handler.performRequests_error(&NSArray::from_slice(&[&*text as &VNRequest]));
- let mut out = Vec::new();
- if let Some(rs) = text.results() {
- for o in rs.iter() {
- let Some(c) = o.topCandidates(1).firstObject() else { continue };
- let r = rect(unsafe { o.boundingBox() });
- out.push((c.string().to_string(), c.confidence(), [r.x, r.y, r.w, r.h]));
- }
- }
- Ok(out)
-}
+// Apple Vision's implementation (apple_vision.rs), named here as before
+#[cfg(target_vendor = "apple")]
+pub use crate::apple_vision::{AppleVision, text_lines};
/// The layout reader's grey copy: the picture 240 px wide, luma, averaged down then sampled bilinearly.
pub fn grey(rgba: &[u8], w: usize, h: usize) -> raea_sys_layout::layout::Grey {
diff --git a/tools/perceive/Cargo.toml b/tools/perceive/Cargo.toml
index 2a2d976e..880cfdcc 100644
--- a/tools/perceive/Cargo.toml
+++ b/tools/perceive/Cargo.toml
@@ -14,13 +14,13 @@ vision-portable = ["raea-sys-perceive/vision-portable"]
[dependencies]
# frames come from the media plane (VideoToolbox on Apple, ffmpeg or the software decoders elsewhere)
-raea-io-media = { path = "../../io/media", default-features = false, features = ["apple"] }
+# soft-audio: a song's sound decoded in process off Apple (Symphonia), where an install has no ffmpeg (#43)
+raea-io-media = { path = "../../io/media", default-features = false, features = ["apple", "soft-audio"] }
raea-sys-layout = { path = "../../systems/layout" }
raea-sys-vision = { path = "../../systems/vision" }
raea-sys-song = { path = "../../systems/song" }
raea-sys-perceive = { path = "../../systems/perceive" }
raea-sys-footage = { path = "../../systems/footage" }
serde_json = "1"
-
-[target.'cfg(target_vendor = "apple")'.dependencies]
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
+
diff --git a/tools/perceive/src/more.rs b/tools/perceive/src/more.rs
index 4becb748..66edb29a 100644
--- a/tools/perceive/src/more.rs
+++ b/tools/perceive/src/more.rs
@@ -5,6 +5,8 @@ use super::*;
pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Result<(), String> {
match args.first().map(String::as_str) {
+ // (with a backend: Vision on Apple, or the ocr-portable feature)
+ #[cfg(any(target_vendor = "apple", feature = "ocr-portable"))]
Some("read-lines") => {
// --backend apple (Vision, the default on Apple) | ocrs (portable, the ocr-portable feature)
let backend = flag("--backend").unwrap_or_else(|| if cfg!(target_vendor = "apple") { "apple".into() } else { "ocrs".into() });
@@ -24,6 +26,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
}
Ok(())
}
+ #[cfg(target_vendor = "apple")]
Some("eyes") => {
// eyes IMG...: a line per picture with the largest face's eyes, their midpoint in shares of the picture
// from the top left, or null with no face: where <Video framing="face"> holds them (sdk/react
@@ -50,6 +53,8 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
}
Ok(())
}
+ // (with a backend: Vision on Apple, or the face-portable feature)
+ #[cfg(any(target_vendor = "apple", feature = "face-portable"))]
Some("faces") => {
// --backend apple (Vision, the default on Apple) | yunet (portable, the face-portable feature)
let backend = flag("--backend").unwrap_or_else(|| if cfg!(target_vendor = "apple") { "apple".into() } else { "yunet".into() });
@@ -174,6 +179,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
println!("{}", json!({"samples": mix[0].len(), "rtf": t.elapsed().as_secs_f64() / (mix[0].len() as f64 / 44_100.0)}));
Ok(())
}
+ #[cfg(target_vendor = "apple")]
Some("vad") => {
// Silero VAD v5: speech spans of a file's sound (a .f32 file is raw 16 kHz mono)
let path = std::path::Path::new(args.get(1).ok_or("vad FILE [--store DIR]")?);
@@ -181,8 +187,8 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
let j = raea_sys_song::vad::file(path, &backend)?;
// --store DIR (or $RAEA_INGEST): kept as vad.json beside the source's other ingest tracks
if args.iter().any(|a| a == "--store") || std::env::var_os("RAEA_INGEST").is_some() {
- let store = flag("--store").map(std::path::PathBuf::from).unwrap_or_else(raea_sys_footage::ingest::store);
- let dir = store.join(&raea_sys_footage::ingest::content_hash(path)?[..16]);
+ let store = flag("--store").map(std::path::PathBuf::from).unwrap_or_else(raea_sys_footage::store::store);
+ let dir = store.join(&raea_sys_footage::store::content_hash(path)?[..16]);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
std::fs::write(dir.join("vad.json"), j.to_string()).map_err(|e| e.to_string())?;
}
@@ -192,7 +198,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
Some("beats") => {
// Beat This! small: beats and downbeats of a file's sound; --spect OUT.f32 also writes the log-mel frames
let path = std::path::Path::new(args.get(1).ok_or("beats FILE [--store DIR] [--spect OUT.f32] [--pcm OUT.f32]")?);
- let backend = flag("--backend").unwrap_or_else(|| if cfg!(target_vendor = "apple") { "apple".into() } else { "ffmpeg".into() });
+ let backend = flag("--backend").unwrap_or_else(sound_backend);
if let Some(out) = flag("--pcm") {
let x = raea_sys_song::beatthis::pcm(path, &backend)?;
std::fs::write(&out, x.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).map_err(|e| e.to_string())?;
@@ -205,8 +211,8 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
let j = raea_sys_song::beatthis::file(path, &backend)?;
// --store DIR (or $RAEA_INGEST): kept as beats.json beside the source's other ingest tracks
if args.iter().any(|a| a == "--store") || std::env::var_os("RAEA_INGEST").is_some() {
- let store = flag("--store").map(std::path::PathBuf::from).unwrap_or_else(raea_sys_footage::ingest::store);
- let dir = store.join(&raea_sys_footage::ingest::content_hash(path)?[..16]);
+ let store = flag("--store").map(std::path::PathBuf::from).unwrap_or_else(raea_sys_footage::store::store);
+ let dir = store.join(&raea_sys_footage::store::content_hash(path)?[..16]);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
std::fs::write(dir.join("beats.json"), j.to_string()).map_err(|e| e.to_string())?;
}
@@ -217,7 +223,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
// the song's energy map (raea_sys_song::song): sections from the file's [Section] markers when it
// has them (--srt, a .srt beside it, or its own timed-text stream), else from novelty
let path = std::path::Path::new(args.get(1).ok_or("song FILE [--srt S.srt] [-o OUT.json]")?);
- let backend = flag("--backend").unwrap_or_else(|| if cfg!(target_vendor = "apple") { "apple".into() } else { "ffmpeg".into() });
+ let backend = flag("--backend").unwrap_or_else(sound_backend);
let srt = flag("--srt").map(std::path::PathBuf::from);
let j = raea_sys_song::song::file(path, &backend, srt.as_deref())?;
match flag("-o") {
@@ -279,6 +285,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
let _ = child.wait();
Ok(())
}
+ #[cfg(target_vendor = "apple")]
Some("track") => {
// an object tracked through frames from a box on the first (EdgeTAM): a matte per frame at the
// frame's own size, OUTDIR/<frame's name>.png (255 on the object), and a JSON line each with its box
@@ -303,6 +310,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
}
Ok(())
}
+ #[cfg(target_vendor = "apple")]
Some("hands") => {
let m = raea_sys_vision::hands::models()?;
for path in &args[1..] {
@@ -350,3 +358,9 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
_ => Err("usage: raea-perceive ingest CLIP [--store DIR] | beats FILE | vad FILE | analyze | sound | cuts | transnet | samples VIDEO [--backend B] | bounds | layout | coach | camera | performance ... (the module comment lists every command)".into()),
}
}
+
+/// Where a song's sound is decoded by default: AVFoundation on Apple, else in process (the soft backend: Symphonia), since
+/// an install elsewhere has no ffmpeg (#43); `--backend ffmpeg` reads what Symphonia doesn't
+fn sound_backend() -> String {
+ if cfg!(target_vendor = "apple") { "apple" } else { "soft" }.into()
+}