mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
codecs: list each Cryptomatte layer once and index streams by name (#10978)
* codecs: list each Cryptomatte layer once and index streams by name layers() cloned the cached stream list for every cryptomatte/<key>/name attribute that named a layer, so many keys naming one layer (in any case or _/- spelling) retained keys x channels strings. Streams are now indexed by normalized layer name in one pass over the channels, each layer's list is moved into the first key that names it, and later keys naming the same layer are skipped (decode resolves a name to its first layer anyway). decode() searched the layer's stream list for every decoded channel; it now builds a stream-name -> slot map once. * address review: compare cryptomatte layer names normalized in decode * address review: prefer exact Cryptomatte layer name * address review: sort cryptomatte keys so layer names are stable * address review: prefer the key with a usable manifest when keys name one cryptomatte layer
This commit is contained in:
1 parent
648d742a50
commit
bbcb4b825a
2 files changed
+124
-39
No files matched your search
@@ -124,25 +124,33 @@ fn parse_manifest(json: &str) -> Vec<(f32, String)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The stream channel names of a layer (`crypto_asset00`, `crypto_asset01`, …, exactly as
|
||||
/// the file spells them), matched leniently: the channel prefix and the `name` attribute
|
||||
/// differ in case or `_`/`-` between renderers (`CryptoAsset` vs `crypto_asset`).
|
||||
fn layer_streams(header: &exr::meta::header::Header, name: &str) -> Vec<String> {
|
||||
let normalize = |s: &str| s.to_ascii_lowercase().replace(['_', '-'], "");
|
||||
let want = normalize(name);
|
||||
let mut found: Vec<(u32, String)> = header
|
||||
.channels
|
||||
.list
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let s = split_stream(&c.name.to_string())?;
|
||||
(!s.coverage).then_some((s.index, s.stream))
|
||||
/// How a layer name compares with a stream's channel prefix: the channel prefix and the `name`
|
||||
/// attribute differ in case or `_`/`-` between renderers (`CryptoAsset` vs `crypto_asset`).
|
||||
fn normalize_layer(s: &str) -> String {
|
||||
s.to_ascii_lowercase().replace(['_', '-'], "")
|
||||
}
|
||||
|
||||
/// The stream channel names of every layer of a header (`crypto_asset00`, `crypto_asset01`, …,
|
||||
/// exactly as the file spells them), keyed by [`normalize_layer`] of their prefix. Built in one
|
||||
/// pass over the channels, so looking up each `cryptomatte/<key>/name` costs no channel scan.
|
||||
fn layer_streams(header: &exr::meta::header::Header) -> std::collections::HashMap<String, Vec<String>> {
|
||||
let mut found: std::collections::HashMap<String, Vec<(u32, String)>> = std::collections::HashMap::new();
|
||||
for c in &header.channels.list {
|
||||
let Some(s) = split_stream(&c.name.to_string()) else { continue };
|
||||
if s.coverage {
|
||||
continue;
|
||||
}
|
||||
let layer = normalize_layer(s.stream.trim_end_matches(|c: char| c.is_ascii_digit()));
|
||||
found.entry(layer).or_default().push((s.index, s.stream));
|
||||
}
|
||||
found
|
||||
.into_iter()
|
||||
.map(|(layer, mut streams)| {
|
||||
streams.sort();
|
||||
streams.dedup();
|
||||
(layer, streams.into_iter().map(|(_, stream)| stream).collect())
|
||||
})
|
||||
.filter(|(_, stream)| normalize(stream.trim_end_matches(|c: char| c.is_ascii_digit())) == want)
|
||||
.collect();
|
||||
found.sort();
|
||||
found.dedup();
|
||||
found.into_iter().map(|(_, stream)| stream).collect()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lists every Cryptomatte layer of the file from the headers alone: what a Cryptomatte
|
||||
@@ -157,41 +165,56 @@ pub(crate) fn layers(bytes: &[u8], limits: &Limits) -> Result<Vec<CryptomatteLay
|
||||
let size = header.layer_size;
|
||||
let (w, h) = (u32::try_from(size.0).unwrap_or(u32::MAX), u32::try_from(size.1).unwrap_or(u32::MAX));
|
||||
limits.check_bytes(w, h, 8)?;
|
||||
// Cache stream lists by resolved layer name: layer_streams() rescans every channel,
|
||||
// and distinct file-controlled keys can all name the same layer, which would turn
|
||||
// channel discovery into O(keys * channels) work and allocate a fresh list each time.
|
||||
let mut streams_for: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
|
||||
for key in cryptomatte_keys(&header.own_attributes.other) {
|
||||
let Some(name) = attribute(&header.own_attributes.other, &key, "name") else { continue };
|
||||
let channels = streams_for.entry(name.clone()).or_insert_with(|| layer_streams(header, name.as_str())).clone();
|
||||
if channels.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let manifest = attribute(&header.own_attributes.other, &key, "manifest")
|
||||
.filter(|m| m.len() <= MANIFEST_CAP)
|
||||
.map(|m| parse_manifest(m.as_str()))
|
||||
.unwrap_or_default();
|
||||
// Every channel's stream, indexed once by layer. Each layer's list is moved into the
|
||||
// first key that names it: file-controlled keys can all name the same layer (in any
|
||||
// case or `_`/`-` spelling), and copying its list for each of them would make the
|
||||
// result grow with keys * channels. A second key naming a listed layer is skipped;
|
||||
// `decode` resolves a name to its first layer anyway.
|
||||
let mut streams_for = layer_streams(header);
|
||||
// A key whose manifest is missing or unparseable only stands in for its layer when no later
|
||||
// key naming it has a usable one.
|
||||
let mut fallback: std::collections::HashMap<String, (String, String)> = std::collections::HashMap::new();
|
||||
let other = &header.own_attributes.other;
|
||||
let mut push = |name: String, key: String, manifest: Vec<_>, channels: Vec<String>| {
|
||||
out.push(CryptomatteLayer {
|
||||
part,
|
||||
name,
|
||||
key: key.clone(),
|
||||
conversion: attribute(&header.own_attributes.other, &key, "conversion"),
|
||||
conversion: attribute(other, &key, "conversion"),
|
||||
manifest,
|
||||
sidecar_manifest: attribute(&header.own_attributes.other, &key, "manif_file"),
|
||||
sidecar_manifest: attribute(other, &key, "manif_file"),
|
||||
key,
|
||||
channels,
|
||||
});
|
||||
};
|
||||
for key in cryptomatte_keys(other) {
|
||||
let Some(name) = attribute(other, &key, "name") else { continue };
|
||||
let norm = normalize_layer(&name);
|
||||
if streams_for.get(&norm).is_none_or(|c| c.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let manifest = attribute(other, &key, "manifest").filter(|m| m.len() <= MANIFEST_CAP).map(|m| parse_manifest(m.as_str())).unwrap_or_default();
|
||||
if manifest.is_empty() {
|
||||
fallback.entry(norm).or_insert((name, key));
|
||||
} else if let Some(channels) = streams_for.remove(&norm) {
|
||||
push(name, key, manifest, channels);
|
||||
}
|
||||
}
|
||||
for (norm, (name, key)) in fallback {
|
||||
if let Some(channels) = streams_for.remove(&norm) {
|
||||
push(name, key, Vec::new(), channels);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| (&a.part, &a.name).cmp(&(&b.part, &b.name)));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every `cryptomatte/<key>/` key of a header, in file order, without duplicates.
|
||||
/// Every `cryptomatte/<key>/` key of a header, sorted, without duplicates.
|
||||
fn cryptomatte_keys(other: &std::collections::HashMap<exr::meta::attribute::Text, exr::meta::attribute::AttributeValue>) -> Vec<String> {
|
||||
let mut keys = Vec::new();
|
||||
// Track seen keys in a set: the attribute names are file-controlled, so membership with
|
||||
// keys.iter().any() is O(n^2) in the number of distinct `cryptomatte/<key>/<field>`
|
||||
// groups. The Vec still records file order; the set only answers "seen before".
|
||||
// groups. The set only answers "seen before"; the result is sorted below.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for name in other.keys() {
|
||||
let full = name.to_string();
|
||||
@@ -201,6 +224,7 @@ fn cryptomatte_keys(other: &std::collections::HashMap<exr::meta::attribute::Text
|
||||
keys.push(key.to_string());
|
||||
}
|
||||
}
|
||||
keys.sort(); // HashMap order varies per call; layer names must stay stable
|
||||
keys
|
||||
}
|
||||
|
||||
@@ -210,9 +234,11 @@ fn cryptomatte_keys(other: &std::collections::HashMap<exr::meta::attribute::Text
|
||||
/// other flat part decoders.
|
||||
pub(crate) fn decode(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result<CryptomatteBuffer, CodecError> {
|
||||
let found = layers(bytes, limits)?;
|
||||
// An exact name wins, so layers whose names only differ after normalising can each be asked for.
|
||||
let layer = found
|
||||
.iter()
|
||||
.find(|l| l.name.eq_ignore_ascii_case(layer_name))
|
||||
.find(|l| l.name == layer_name)
|
||||
.or_else(|| found.iter().find(|l| normalize_layer(&l.name) == normalize_layer(layer_name)))
|
||||
.ok_or_else(|| CodecError::unsupported(F, format!("no Cryptomatte layer named {layer_name}")))?;
|
||||
// Also caps all parts' declared sizes together, like every other flat decode.
|
||||
let meta = super::exr::read_meta(bytes, limits)?;
|
||||
@@ -240,9 +266,12 @@ pub(crate) fn decode(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result<
|
||||
// Two (ID, coverage) ranks per set: rank `slot * 2 + stream.rank`.
|
||||
let mut ids: Vec<Vec<f32>> = vec![Vec::new(); ranks];
|
||||
let mut coverages: Vec<Vec<f32>> = vec![Vec::new(); ranks];
|
||||
// Stream name -> its slot, built once: a linear search per decoded channel is quadratic in
|
||||
// the file's stream count.
|
||||
let slots: std::collections::HashMap<&str, usize> = layer.channels.iter().enumerate().rev().map(|(i, s)| (s.as_str(), i)).collect();
|
||||
for c in &ex_layer.channel_data.list {
|
||||
let Some(stream) = split_stream(&c.name.to_string()) else { continue };
|
||||
let Some(slot) = layer.channels.iter().position(|s| *s == stream.stream) else { continue };
|
||||
let Some(&slot) = slots.get(stream.stream.as_str()) else { continue };
|
||||
let values: Vec<f32> = c.sample_data.values_as_f32().collect();
|
||||
if values.len() != npx {
|
||||
return Err(CodecError::malformed(F, "a Cryptomatte channel is smaller than its layer"));
|
||||
|
||||
@@ -269,3 +269,59 @@ fn hostile_input_never_panics() {
|
||||
let e = cryptomatte_layers(&bytes, &Limits { max_alloc: 8, ..Limits::default() }).unwrap_err();
|
||||
assert!(e.to_string().contains("exceed"), "{e}");
|
||||
}
|
||||
|
||||
/// Many keys naming the same layer (in different spellings) list it once, so the listing
|
||||
/// stays proportional to the channels rather than keys * channels.
|
||||
#[test]
|
||||
fn keys_naming_one_layer_list_it_once() {
|
||||
let (w, h) = (4usize, 4usize);
|
||||
let mk = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h]));
|
||||
let list = vec![mk("crypto_asset00.red", cryptomatte_id("cube")), mk("crypto_asset00.green", 1.0)];
|
||||
let mut attrs = LayerAttributes::named("crypto_asset");
|
||||
let spellings = ["CryptoAsset", "crypto_asset", "Crypto-Asset", "CRYPTO_ASSET", "crypto__asset"];
|
||||
for i in 0..200 {
|
||||
let name = spellings[i % spellings.len()];
|
||||
attrs.other.insert(text(&format!("cryptomatte/k{i:04}/name")), AttributeValue::Text(text(name)));
|
||||
}
|
||||
let layer = Layer::new(
|
||||
(w, h),
|
||||
attrs,
|
||||
Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing },
|
||||
AnyChannels::sort(list.into_iter().collect()),
|
||||
);
|
||||
let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), vec![layer]);
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
image.write().to_buffered(&mut out).expect("synthetic cryptomatte exr writes");
|
||||
let bytes = out.into_inner();
|
||||
let found = cryptomatte_layers(&bytes, &Limits::default()).unwrap();
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].channels, ["crypto_asset00"]);
|
||||
let buf = decode_cryptomatte(&bytes, &found[0].name, &Limits::default()).unwrap();
|
||||
assert_eq!(buf.at(0, 0).len(), 1);
|
||||
}
|
||||
|
||||
/// Of keys naming one layer, the first with a usable manifest lists it, not an earlier one
|
||||
/// whose manifest is missing.
|
||||
#[test]
|
||||
fn a_later_key_with_a_manifest_beats_an_earlier_one_without() {
|
||||
let (w, h) = (4usize, 4usize);
|
||||
let mk = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h]));
|
||||
let list = vec![mk("crypto_asset00.red", cryptomatte_id("cube")), mk("crypto_asset00.green", 1.0)];
|
||||
let mut attrs = LayerAttributes::named("crypto_asset");
|
||||
attrs.other.insert(text("cryptomatte/a/name"), AttributeValue::Text(text("CryptoAsset")));
|
||||
attrs.other.insert(text("cryptomatte/b/name"), AttributeValue::Text(text("crypto_asset")));
|
||||
attrs.other.insert(text("cryptomatte/b/manifest"), AttributeValue::Text(text("{\"cube\":\"3f800000\"}")));
|
||||
let layer = Layer::new(
|
||||
(w, h),
|
||||
attrs,
|
||||
Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing },
|
||||
AnyChannels::sort(list.into_iter().collect()),
|
||||
);
|
||||
let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), vec![layer]);
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
image.write().to_buffered(&mut out).expect("synthetic cryptomatte exr writes");
|
||||
let found = cryptomatte_layers(&out.into_inner(), &Limits::default()).unwrap();
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].key, "b");
|
||||
assert_eq!(found[0].manifest.len(), 1);
|
||||
}
|
||||
Reference in new issue
Block a user