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.

IX2: a video's fast pass is its keyframes: one for each 4 s, at most 16 spread over the whole, each the sync frame nearest its moment (AVAssetImageGenerator, tolerance unbounded, so nothing between keyframes is decoded), the first its thumbnail; each frame a row with its moment, an item's frames embedded in one batch so it counts once. On 35 of our own videos: 109 frames, all searchable in 0.9 s; "a monk in a dark stone hall" finds MUSPILLI's opening at 153 s. Listing a video's length before its frames is still to do

shinyobjectz32587e0b9dc3
diff --git a/Cargo.lock b/Cargo.lock
index 8577dd51..0ae9c5ce 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15792,8 +15792,10 @@ dependencies = [
"anyhow",
"half",
"objc2 0.6.5",
+ "objc2-av-foundation",
"objc2-core-foundation",
"objc2-core-graphics",
+ "objc2-core-media",
"objc2-core-ml",
"objc2-core-video",
"objc2-foundation 0.3.2",
diff --git a/systems/index/Cargo.toml b/systems/index/Cargo.toml
index 698fbd2e..19876891 100644
--- a/systems/index/Cargo.toml
+++ b/systems/index/Cargo.toml
@@ -29,3 +29,6 @@ objc2-core-ml = { version = "0.3", features = ["MLModel", "MLModelConfiguration"
objc2-core-video = { version = "0.3", features = ["CVPixelBuffer", "CVImageBuffer", "CVBuffer", "CVReturn"] }
objc2-core-graphics = { version = "0.3", features = ["CGImage", "CGColorSpace", "CGContext", "CGBitmapContext"] }
objc2-image-io = { version = "0.3", features = ["CGImageSource", "CGImageDestination", "CGImageProperties"] }
+# a video's keyframes (frames.rs)
+objc2-av-foundation = { version = "0.3", features = ["objc2-core-media", "objc2-core-graphics"] }
+objc2-core-media = "0.3"
diff --git a/systems/index/src/frames.rs b/systems/index/src/frames.rs
new file mode 100644
index 00000000..2d010c07
--- /dev/null
+++ b/systems/index/src/frames.rs
@@ -0,0 +1,96 @@
+//! A video's frames for the fast pass (docs/index.feature IX2): one for each `EVERY` seconds, at most `FRAMES` spread
+//! over the whole video, each the keyframe nearest its moment so nothing between keyframes is decoded. The first is the
+//! video's thumbnail. Each frame is a row with its moment, so a hit says where in the video it is.
+
+use crate::apple::{SIDE, squash, write_jpeg};
+use objc2_av_foundation::{AVAssetImageGenerator, AVURLAsset};
+use objc2_core_foundation::{CFRetained, CGSize};
+use objc2_core_graphics::CGImage;
+use objc2_core_media::{CMTime, kCMTimePositiveInfinity};
+use objc2_core_video::CVPixelBuffer;
+use objc2_foundation::{NSString, NSURL};
+use std::path::Path;
+
+/// seconds of video for each frame, and the most frames a video gives
+pub const EVERY: f64 = 4.0;
+pub const FRAMES: usize = 16;
+
+/// The moments to take: the middle of each stretch, the stretches `EVERY` seconds long, or longer so a long video
+/// gives `FRAMES`. A video whose length can't be read gives its first frame.
+pub fn moments(dur: f64) -> Vec<f64> {
+ if dur.is_nan() || dur <= 0.0 || dur.is_infinite() {
+ return vec![0.0];
+ }
+ let n = ((dur / EVERY).ceil() as usize).clamp(1, FRAMES);
+ let step = dur / n as f64;
+ (0..n).map(|i| step * (i as f64 + 0.5)).collect()
+}
+
+/// A video's frames squashed for the model, each with its moment in seconds, and the size of its small copy
+pub struct Frames {
+ pub px: Vec<(CFRetained<CVPixelBuffer>, f64)>,
+ pub w: u32,
+ pub h: u32,
+}
+
+pub fn video(path: &Path, thumb: Option<&Path>) -> Result<Frames, String> {
+ objc2::rc::autoreleasepool(|_| {
+ let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()));
+ let asset = unsafe { AVURLAsset::URLAssetWithURL_options(&url, None) };
+ let dur = unsafe { asset.duration().seconds() };
+ let generator = unsafe { AVAssetImageGenerator::assetImageGeneratorWithAsset(&asset) };
+ unsafe {
+ generator.setAppliesPreferredTrackTransform(true);
+ generator.setMaximumSize(CGSize::new(SIDE as f64, SIDE as f64));
+ // the nearest keyframe, however far: the fast pass never decodes between keyframes
+ generator.setRequestedTimeToleranceBefore(kCMTimePositiveInfinity);
+ generator.setRequestedTimeToleranceAfter(kCMTimePositiveInfinity);
+ }
+ let mut f = Frames { px: Vec::new(), w: 0, h: 0 };
+ let (mut last, mut why) = (f64::NAN, None);
+ for t in moments(dur) {
+ let want = unsafe { CMTime::with_seconds(t, 600) };
+ let mut got = want;
+ #[allow(deprecated)]
+ let img = match unsafe { generator.copyCGImageAtTime_actualTime_error(want, &mut got) } {
+ Ok(img) => img,
+ Err(e) => {
+ why = Some(e.localizedDescription().to_string());
+ continue;
+ }
+ };
+ let at = unsafe { got.seconds() };
+ // keyframes further apart than the stretches give the same one again
+ if at == last {
+ continue;
+ }
+ last = at;
+ if f.px.is_empty() {
+ (f.w, f.h) = (CGImage::width(Some(&img)) as u32, CGImage::height(Some(&img)) as u32);
+ if let Some(to) = thumb {
+ let _ = write_jpeg(&img, to);
+ }
+ }
+ f.px.push((squash(&img)?, at));
+ }
+ if f.px.is_empty() {
+ return Err(why.unwrap_or_else(|| "no frames in it".into()));
+ }
+ Ok(f)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_frame_for_each_four_seconds_up_to_sixteen_spread_over_the_whole() {
+ assert_eq!(moments(3.0), vec![1.5]);
+ assert_eq!(moments(10.0).len(), 3);
+ let long = moments(3600.0);
+ assert_eq!(long.len(), FRAMES);
+ assert!(long[0] > 100.0 && *long.last().unwrap() > 3400.0);
+ assert_eq!(moments(f64::NAN), vec![0.0]);
+ }
+}
diff --git a/systems/index/src/lib.rs b/systems/index/src/lib.rs
index 1d47a081..4961b2ff 100644
--- a/systems/index/src/lib.rs
+++ b/systems/index/src/lib.rs
@@ -7,6 +7,8 @@
#[cfg(target_vendor = "apple")]
pub mod apple;
pub mod cli;
+#[cfg(target_vendor = "apple")]
+pub mod frames;
pub mod search;
pub mod serve;
pub mod store;
@@ -101,16 +103,17 @@ pub fn list_folder(store: &mut Store, root: &Path, on: &mut dyn FnMut(&Progress)
Ok(l)
}
-/// The fast pass over a source's pictures that wait for it: decoded on every core but two, embedded 32 at a time on
-/// the Neural Engine, each batch's rows written as it finishes. Videos wait for their frames (IX2).
+/// The fast pass over a source's pictures and videos that wait for it: decoded on every core but two (a video as a few
+/// keyframes, frames.rs), embedded about 32 frames at a time on the Neural Engine, each batch's rows written as it
+/// finishes. An item's frames go in one batch, so an item counts as searchable once all of its rows are written.
#[cfg(target_vendor = "apple")]
pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, stop: &std::sync::Arc<std::sync::atomic::AtomicBool>, on: &mut dyn FnMut(&Progress)) -> Result<Progress> {
use std::sync::atomic::Ordering;
use rayon::prelude::*;
const BATCH: usize = 32;
- let all: Vec<store::Pending> = store.pending(source, usize::MAX)?.into_iter().filter(|p| p.kind == "picture").collect();
+ let all: Vec<store::Pending> = store.pending(source, usize::MAX)?;
let base = store.counts(Some(source))?;
- let (tx, rx) = std::sync::mpsc::sync_channel::<Result<apple::Ready, (i64, String)>>(BATCH * 8);
+ let (tx, rx) = std::sync::mpsc::sync_channel::<Result<Vec<apple::Ready>, (i64, String)>>(BATCH * 8);
let thumbs: Vec<PathBuf> = all.iter().map(|p| store.thumb(p.id)).collect();
let threads = std::thread::available_parallelism().map(|n| n.get().saturating_sub(2).max(2)).unwrap_or(4);
let halt = stop.clone();
@@ -121,7 +124,13 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, sto
if halt.load(Ordering::Relaxed) {
return;
}
- let r = apple::picture(Path::new(&p.locator), Some(thumb)).map(|(px, w, h)| apple::Ready { item: p.id, t: 0.0, px, w, h }).map_err(|e| (p.id, e));
+ let file = Path::new(&p.locator);
+ let r = if p.kind == "video" {
+ frames::video(file, Some(thumb)).map(|f| f.px.into_iter().map(|(px, t)| apple::Ready { item: p.id, t, px, w: f.w, h: f.h }).collect())
+ } else {
+ apple::picture(file, Some(thumb)).map(|(px, w, h)| vec![apple::Ready { item: p.id, t: 0.0, px, w, h }])
+ };
+ let r = r.map_err(|e| (p.id, e));
let _ = tx.send(r);
})
})
@@ -129,19 +138,21 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, sto
let started = Instant::now();
let mut last = Instant::now();
let mut prog = Progress { source: source.into(), found: base.found, done: base.done, failed: base.failed, stage: "embedding", ..Progress::default() };
- let mut batch: Vec<apple::Ready> = Vec::with_capacity(BATCH);
- let mut embedded = 0u64;
+ let mut batch: Vec<apple::Ready> = Vec::with_capacity(BATCH + frames::FRAMES);
let flush = |batch: &mut Vec<apple::Ready>, prog: &mut Progress, store: &mut Store| -> Result<()> {
if batch.is_empty() {
return Ok(());
}
let pxs: Vec<&objc2_core_video::CVPixelBuffer> = batch.iter().map(|r| &*r.px).collect();
let vs = model.embed(&pxs).map_err(|e| anyhow::anyhow!(e))?;
- // each picture's row and its size, in one pass
+ // each frame's row and its item's size, in one pass
let (rows, dims): (Vec<(i64, f64, Vec<f32>)>, Vec<(i64, u32, u32)>) = batch.iter().zip(vs).map(|(r, v)| ((r.item, r.t, v), (r.item, r.w, r.h))).unzip();
store.append(MODEL, &rows, &dims)?;
- prog.done += batch.len() as u64;
- prog.newest.extend(batch.iter().map(|r| r.item));
+ // an item's frames sit together: one count and one tile each
+ let mut items: Vec<i64> = batch.iter().map(|r| r.item).collect();
+ items.dedup();
+ prog.done += items.len() as u64;
+ prog.newest.extend(items);
batch.clear();
Ok(())
};
@@ -151,10 +162,9 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, sto
break;
}
match r {
- Ok(ready) => {
- batch.push(ready);
- if batch.len() == BATCH {
- embedded += BATCH as u64;
+ Ok(item) => {
+ batch.extend(item);
+ if batch.len() >= BATCH {
flush(&mut batch, &mut prog, store)?;
}
}
@@ -165,17 +175,16 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, sto
}
if last.elapsed().as_millis() >= 250 {
prog.seconds = started.elapsed().as_secs_f64();
- prog.per_sec = embedded as f64 / prog.seconds.max(1e-3);
+ prog.per_sec = (prog.done - base.done) as f64 / prog.seconds.max(1e-3);
on(&prog);
prog.newest.clear();
last = Instant::now();
}
}
- embedded += batch.len() as u64;
flush(&mut batch, &mut prog, store)?;
let _ = decoder.join();
prog.seconds = started.elapsed().as_secs_f64();
- prog.per_sec = embedded as f64 / prog.seconds.max(1e-3);
+ prog.per_sec = (prog.done - base.done) as f64 / prog.seconds.max(1e-3);
if prog.stage != "stopped" {
prog.stage = "done";
}