Merge main into IO-2/SHP-5/OUT-2/PRV-2 work
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
//! Auxiliary channels from multi-layer OpenEXR files (depth, object / material IDs, normals,
|
||||
//! Cryptomatte, …) for the 3D Channel effects, read with the pure-Rust `exr` crate.
|
||||
//!
|
||||
//! Every channel of every layer becomes a plane named `layer.channel` (or just `channel` for
|
||||
//! the unnamed layer), placed in the display window (pixels outside a layer's data window are
|
||||
//! 0, or the background depth for depth channels). Cryptomatte manifests come from the
|
||||
//! `cryptomatte/<key>/name` and `cryptomatte/<key>/manifest` header attributes (the published
|
||||
//! Cryptomatte metadata convention: the manifest is a JSON object of name → hex hash).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use effectcraft_raster::AuxChannels;
|
||||
use effectcraft_raster::channels3d::BACKGROUND_DEPTH;
|
||||
|
||||
fn is_depth(name: &str) -> bool {
|
||||
let last = name.rsplit('.').next().unwrap_or(name);
|
||||
last.eq_ignore_ascii_case("z") || name.to_ascii_lowercase().contains("depth")
|
||||
}
|
||||
|
||||
/// Parse a Cryptomatte manifest (`{"name": "hexhash", …}`).
|
||||
pub fn parse_manifest(json: &str) -> Vec<(String, u32)> {
|
||||
let Ok(serde_json::Value::Object(m)) = serde_json::from_str::<serde_json::Value>(json) else { return vec![] };
|
||||
let mut v: Vec<(String, u32)> = m.iter().filter_map(|(k, h)| Some((k.clone(), u32::from_str_radix(h.as_str()?.trim(), 16).ok()?))).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// Read all channels of an EXR file's bytes. `None` when it is not a readable EXR.
|
||||
pub fn read_exr_channels(bytes: &[u8]) -> Option<AuxChannels> {
|
||||
use exr::prelude::*;
|
||||
let img = read().no_deep_data().largest_resolution_level().all_channels().all_layers().all_attributes().from_buffered(std::io::Cursor::new(bytes)).ok()?;
|
||||
let dw = img.attributes.display_window;
|
||||
let (w, h) = (dw.size.0, dw.size.1);
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut aux = AuxChannels::new(w as u32, h as u32, 1.0);
|
||||
let mut crypto: HashMap<String, (Option<String>, Option<String>)> = HashMap::new();
|
||||
let mut collect_meta = |other: &HashMap<Text, AttributeValue>| {
|
||||
for (k, v) in other {
|
||||
let key = k.to_string();
|
||||
let Some(rest) = key.strip_prefix("cryptomatte/") else { continue };
|
||||
let Some((id, field)) = rest.split_once('/') else { continue };
|
||||
let AttributeValue::Text(t) = v else { continue };
|
||||
let e = crypto.entry(id.to_string()).or_default();
|
||||
match field {
|
||||
"name" => e.0 = Some(t.to_string()),
|
||||
"manifest" => e.1 = Some(t.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
};
|
||||
collect_meta(&img.attributes.other);
|
||||
for layer in img.layer_data.iter() {
|
||||
collect_meta(&layer.attributes.other);
|
||||
let prefix = layer.attributes.layer_name.as_ref().map(|t| t.to_string()).filter(|s| !s.is_empty());
|
||||
let (lw, lh) = (layer.size.0, layer.size.1);
|
||||
let pos = layer.attributes.layer_position;
|
||||
let (ox, oy) = (pos.0 as i64 - dw.position.0 as i64, pos.1 as i64 - dw.position.1 as i64);
|
||||
for ch in layer.channel_data.list.iter() {
|
||||
let name = match &prefix {
|
||||
Some(p) => format!("{p}.{}", ch.name),
|
||||
None => ch.name.to_string(),
|
||||
};
|
||||
let fill = if is_depth(&name) { BACKGROUND_DEPTH } else { 0.0 };
|
||||
let mut plane = vec![fill; w * h];
|
||||
let vals: Vec<f32> = ch.sample_data.values_as_f32().collect();
|
||||
if vals.len() < lw * lh {
|
||||
continue;
|
||||
}
|
||||
for y in 0..lh {
|
||||
let ty = y as i64 + oy;
|
||||
if ty < 0 || ty >= h as i64 {
|
||||
continue;
|
||||
}
|
||||
for x in 0..lw {
|
||||
let tx = x as i64 + ox;
|
||||
if tx < 0 || tx >= w as i64 {
|
||||
continue;
|
||||
}
|
||||
plane[ty as usize * w + tx as usize] = vals[y * lw + x];
|
||||
}
|
||||
}
|
||||
aux.channels.push((name, plane));
|
||||
}
|
||||
}
|
||||
for (_, (name, manifest)) in crypto {
|
||||
if let (Some(n), Some(m)) = (name, manifest) {
|
||||
aux.manifests.push((n, parse_manifest(&m)));
|
||||
}
|
||||
}
|
||||
aux.manifests.sort();
|
||||
Some(aux)
|
||||
}
|
||||
|
||||
type Cache = Mutex<Vec<(String, Option<Arc<AuxChannels>>)>>;
|
||||
|
||||
/// Read (and cache, a few files) the channels of the EXR at `path` via `read`.
|
||||
pub(crate) fn cached(path: &str, read: impl FnOnce() -> Option<Arc<[u8]>>) -> Option<Arc<AuxChannels>> {
|
||||
static CACHE: OnceLock<Cache> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(Vec::new()));
|
||||
if let Some(v) = cache.lock().ok().and_then(|c| c.iter().find(|(p, _)| p == path).map(|(_, v)| v.clone())) {
|
||||
return v;
|
||||
}
|
||||
let v = read().and_then(|b| read_exr_channels(&b)).map(Arc::new);
|
||||
if let Ok(mut c) = cache.lock() {
|
||||
if c.len() >= 4 {
|
||||
c.remove(0);
|
||||
}
|
||||
c.push((path.to_string(), v.clone()));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_layered_channels_and_cryptomatte_metadata() {
|
||||
use exr::prelude::*;
|
||||
let (w, h) = (4usize, 2usize);
|
||||
let z: Vec<f32> = (0..w * h).map(|i| i as f32 * 10.0).collect();
|
||||
let id: Vec<f32> = (0..w * h).map(|i| (i % 2) as f32 + 1.0).collect();
|
||||
let r: Vec<f32> = vec![0.5; w * h];
|
||||
let channels = AnyChannels::sort(
|
||||
vec![
|
||||
AnyChannel::new("R", FlatSamples::F32(r)),
|
||||
AnyChannel::new("Z", FlatSamples::F32(z.clone())),
|
||||
AnyChannel::new("ObjectID", FlatSamples::F32(id.clone())),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
let mut layer = Layer::new((w, h), LayerAttributes::named("depth"), Encoding::FAST_LOSSLESS, channels);
|
||||
layer.attributes.other.insert(Text::from("cryptomatte/abc1234/name"), AttributeValue::Text(Text::from("CryptoObject")));
|
||||
layer
|
||||
.attributes
|
||||
.other
|
||||
.insert(Text::from("cryptomatte/abc1234/manifest"), AttributeValue::Text(Text::from(r#"{"bunny":"13851a76","floor":"0a1b2c3d"}"#)));
|
||||
let image = Image::from_layer(layer);
|
||||
let mut bytes = std::io::Cursor::new(Vec::new());
|
||||
image.write().to_buffered(&mut bytes).unwrap();
|
||||
let aux = read_exr_channels(bytes.get_ref()).unwrap();
|
||||
assert_eq!((aux.width, aux.height), (4, 2));
|
||||
assert_eq!(aux.get("depth.Z").unwrap(), z.as_slice());
|
||||
assert_eq!(aux.depth().unwrap(), z.as_slice());
|
||||
assert_eq!(aux.object_id().unwrap(), id.as_slice());
|
||||
assert_eq!(aux.manifests, vec![("CryptoObject".to_string(), vec![("bunny".to_string(), 0x1385_1a76), ("floor".to_string(), 0x0a1b_2c3d)])]);
|
||||
assert!(read_exr_channels(b"not an exr").is_none());
|
||||
}
|
||||
}
|
||||
@@ -14,12 +14,13 @@
|
||||
//! from `effectcraft-psd` and SVG from `effectcraft-svg` (rasterised at any scale).
|
||||
|
||||
mod convert;
|
||||
pub mod exr_channels;
|
||||
mod layered;
|
||||
mod pool;
|
||||
mod probe;
|
||||
|
||||
pub use pool::{DEFAULT_BUDGET, MediaPool, PoolStats};
|
||||
pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_single, sequence_files};
|
||||
pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_model, probe_single, sequence_files};
|
||||
|
||||
/// Errors from probing or decoding footage.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -52,10 +53,16 @@ pub const AUDIO_EXTENSIONS: &[&str] = filmcraft_media::AUDIO_EXTENSIONS;
|
||||
/// File extensions recognised as movies.
|
||||
pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "mkv", "webm"];
|
||||
|
||||
/// File extensions recognised as 3D models (Advanced 3D model layers).
|
||||
pub const MODEL_EXTENSIONS: &[&str] = &["gltf", "glb", "obj"];
|
||||
|
||||
/// Whether `path` has an extension we can import.
|
||||
pub fn is_importable(path: &std::path::Path) -> bool {
|
||||
let ext = ext_of(path);
|
||||
STILL_EXTENSIONS.contains(&ext.as_str()) || AUDIO_EXTENSIONS.contains(&ext.as_str()) || VIDEO_EXTENSIONS.contains(&ext.as_str())
|
||||
MODEL_EXTENSIONS.contains(&ext.as_str())
|
||||
|| STILL_EXTENSIONS.contains(&ext.as_str())
|
||||
|| AUDIO_EXTENSIONS.contains(&ext.as_str())
|
||||
|| VIDEO_EXTENSIONS.contains(&ext.as_str())
|
||||
}
|
||||
|
||||
pub(crate) fn ext_of(path: &std::path::Path) -> String {
|
||||
|
||||
@@ -122,6 +122,8 @@ struct Inner {
|
||||
sources: Mutex<HashMap<Arc<str>, Option<SharedSource>>>,
|
||||
/// In-memory files registered with `add_bytes` (web builds, tests).
|
||||
files: Mutex<HashMap<String, Arc<[u8]>>>,
|
||||
/// Parsed 3D models by path (`None`: failed to load; not retried until `forget`).
|
||||
models: Mutex<HashMap<String, Option<Arc<effectcraft_model::Model>>>>,
|
||||
cache: Mutex<CacheState>,
|
||||
done: Condvar,
|
||||
budget: AtomicU64,
|
||||
@@ -183,6 +185,7 @@ impl MediaPool {
|
||||
inner: Arc::new(Inner {
|
||||
sources: Mutex::default(),
|
||||
files: Mutex::default(),
|
||||
models: Mutex::default(),
|
||||
cache: Mutex::default(),
|
||||
done: Condvar::new(),
|
||||
budget: AtomicU64::new(bytes as u64),
|
||||
@@ -234,6 +237,7 @@ impl MediaPool {
|
||||
/// Forget a file (after it changed on disk, or to retry a file that failed to open).
|
||||
pub fn forget(&self, path: &str) {
|
||||
lock(&self.inner.sources).remove(path);
|
||||
lock(&self.inner.models).remove(path);
|
||||
let mut c = lock(&self.inner.cache);
|
||||
let keys: Vec<Key> = c.lru.map.keys().filter(|k| &*k.path == path).cloned().collect();
|
||||
for k in keys {
|
||||
@@ -305,6 +309,29 @@ impl Inner {
|
||||
self.budget.load(Ordering::Relaxed) as usize
|
||||
}
|
||||
|
||||
/// A 3D model file and its sibling resources (buffers, textures, MTL files), parsed once.
|
||||
fn model(&self, path: &str) -> Option<Arc<effectcraft_model::Model>> {
|
||||
if let Some(m) = lock(&self.models).get(path) {
|
||||
return m.clone();
|
||||
}
|
||||
let loaded = self.read(path).map_err(|e| e.to_string()).and_then(|bytes| {
|
||||
let dir = std::path::Path::new(path).parent().map(|d| d.to_path_buf()).unwrap_or_default();
|
||||
let resolve = |uri: &str| -> Option<Vec<u8>> {
|
||||
let p = dir.join(uri);
|
||||
self.read(&p.to_string_lossy()).ok().map(|b| b.to_vec())
|
||||
};
|
||||
effectcraft_model::load(path, &bytes, &resolve).map_err(|e| e.to_string())
|
||||
});
|
||||
let m = match loaded {
|
||||
Ok(m) => Some(Arc::new(m)),
|
||||
Err(e) => {
|
||||
log::warn!("media: cannot load model {path}: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
lock(&self.models).entry(path.to_string()).or_insert(m).clone()
|
||||
}
|
||||
|
||||
fn read(&self, path: &str) -> Result<Arc<[u8]>> {
|
||||
if let Some(b) = lock(&self.files).get(path) {
|
||||
return Ok(b.clone());
|
||||
@@ -364,7 +391,7 @@ impl Inner {
|
||||
let l = footage.layer.as_ref().map_or(0, |l| 1 + l.index as i64 * 2 + l.layer_size as i64);
|
||||
Loc { key: key(&footage.path, l), media_t: None }
|
||||
}
|
||||
FootageKind::Still | FootageKind::Sequence => Loc { key: key(&footage.path, 0), media_t: None },
|
||||
FootageKind::Still | FootageKind::Sequence | FootageKind::Model => Loc { key: key(&footage.path, 0), media_t: None },
|
||||
FootageKind::Video | FootageKind::Audio => {
|
||||
let rate = footage.frame_rate;
|
||||
let n = Self::frame_count(rate, footage.duration);
|
||||
@@ -459,6 +486,12 @@ impl Inner {
|
||||
}
|
||||
|
||||
impl FootageSource for MediaPool {
|
||||
fn model(&self, _item: ItemId, footage: &Footage) -> Option<Arc<effectcraft_model::Model>> {
|
||||
if footage.missing || footage.kind != FootageKind::Model {
|
||||
return None;
|
||||
}
|
||||
self.inner.model(&footage.path)
|
||||
}
|
||||
fn set_cache_budget(&self, bytes: usize) {
|
||||
self.set_budget(bytes);
|
||||
}
|
||||
@@ -486,6 +519,18 @@ impl FootageSource for MediaPool {
|
||||
crate::layered::rasterize_svg(&bytes, scale).map(Arc::new)
|
||||
}
|
||||
|
||||
fn aux(&self, _item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<effectcraft_raster::AuxChannels>> {
|
||||
if footage.missing || !footage.has_video {
|
||||
return None;
|
||||
}
|
||||
let loc = Inner::locate(footage, t);
|
||||
if loc.media_t.is_some() || !loc.key.path.to_ascii_lowercase().ends_with(".exr") {
|
||||
return None;
|
||||
}
|
||||
let path = loc.key.path.clone();
|
||||
crate::exr_channels::cached(&path, || self.inner.read(&path).ok())
|
||||
}
|
||||
|
||||
fn audio(&self, _item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option<Vec<f32>> {
|
||||
if !footage.has_audio || footage.missing {
|
||||
return None;
|
||||
|
||||
@@ -28,14 +28,54 @@ pub fn probe(path: impl AsRef<Path>) -> Result<Footage> {
|
||||
pub fn probe_single(path: impl AsRef<Path>) -> Result<Footage> {
|
||||
let path = path.as_ref();
|
||||
let bytes = std::fs::read(path).map_err(|e| MediaError::Io(format!("{}: {e}", path.display())))?;
|
||||
if crate::MODEL_EXTENSIONS.contains(&ext_of(path).as_str()) {
|
||||
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
return probe_model(&path.to_string_lossy(), &bytes, &|uri| std::fs::read(dir.join(uri)).ok());
|
||||
}
|
||||
probe_bytes(&path.to_string_lossy(), bytes.into())
|
||||
}
|
||||
|
||||
/// Probe a 3D model (glTF 2.0 / OBJ): a [`FootageKind::Model`] item whose duration is its
|
||||
/// longest animation. `resolve` reads sibling resources.
|
||||
pub fn probe_model(path: &str, bytes: &[u8], resolve: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Footage> {
|
||||
let m = effectcraft_model::load(path, bytes, resolve).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?;
|
||||
let s = m.summary();
|
||||
let dur = s.animations.iter().map(|a| a.1).fold(0.0f64, f64::max);
|
||||
let codec = match effectcraft_model::format_of(path) {
|
||||
Some("obj") => "OBJ",
|
||||
Some("glb") => "GLB",
|
||||
_ => "glTF",
|
||||
};
|
||||
Ok(Footage {
|
||||
path: path.to_string(),
|
||||
kind: FootageKind::Model,
|
||||
width: 0,
|
||||
height: 0,
|
||||
pixel_aspect: 1.0,
|
||||
frame_rate: DEFAULT_SEQUENCE_RATE,
|
||||
native_rate: None,
|
||||
duration: Tick::from_seconds_f64(dur),
|
||||
has_video: false,
|
||||
has_audio: false,
|
||||
alpha: AlphaMode::Straight,
|
||||
premul_color: [0.0; 3],
|
||||
loop_count: 1,
|
||||
codec: format!("{codec} ({} meshes, {} triangles)", s.meshes, s.triangles),
|
||||
missing: false,
|
||||
sequence: Vec::new(),
|
||||
color_profile: None,
|
||||
layer: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Probe in-memory file contents; `path` names the footage (and is stored as `Footage::path`).
|
||||
pub fn probe_bytes(path: &str, bytes: Arc<[u8]>) -> Result<Footage> {
|
||||
if let Some(f) = crate::layered::probe(path, &bytes)? {
|
||||
return Ok(f);
|
||||
}
|
||||
if crate::MODEL_EXTENSIONS.contains(&ext_of(Path::new(path)).as_str()) {
|
||||
return probe_model(path, &bytes, &|_| None);
|
||||
}
|
||||
if let Ok(fmt) = image::guess_format(&bytes) {
|
||||
return probe_still_bytes(path, &bytes, fmt);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user