From 5d0bfe7869e7518fd686c1b2678752579021e032 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 17 Nov 2026 17:00:29 +0100 Subject: [PATCH] Caching: memory is let go only where it frees memory, Purge keeps nothing decoding meanwhile, and regions read the rows they show (#3750 review) - Cryptomatte planes: a plane a render holds is not offered for its gone channels, and the entry limit holds while renders hold every plane. - Footage frames and whole stills held elsewhere are not offered to the memory accountant. - Purge (clear frames) makes decodes in flight stale: their frames are not kept or joined. - Plane store: a size refusal of a merged decode is not handed to a request that fits alone; slimming a shared set and copies for the disk cache take memory fallibly, and planes the disk cache can't take are not copied. - Disk cache: the plane encoder's scratch is taken fallibly; no memory skips the entry. - Region of interest: rows follow the projected transform of a 2D layer under a 3D parent, and a frame of another size than its footage is read whole. - The box filter's work bound is checked without a wall clock. --- crates/effects/src/channel3d.rs | 46 ++++++-- crates/effects/src/channel3d/tests.rs | 4 +- crates/gpu/src/fx_depth/matte_cache.rs | 26 ++++- crates/gpu/src/tests/fx_depth.rs | 33 ++++++ crates/media/src/exr_planes.rs | 143 ++++++++++++++++++------ crates/media/src/exr_planes/tests.rs | 132 ++++++++++++++++++++++ crates/media/src/pool.rs | 111 ++++++++++++++++-- crates/render/src/disk_cache.rs | 81 +++++++++++--- crates/render/src/pipeline.rs | 9 +- crates/render/src/tests/footage_size.rs | 44 ++++++++ 10 files changed, 550 insertions(+), 79 deletions(-) diff --git a/crates/effects/src/channel3d.rs b/crates/effects/src/channel3d.rs index b2d821cb4..c83e0caf5 100644 --- a/crates/effects/src/channel3d.rs +++ b/crates/effects/src/channel3d.rs @@ -728,27 +728,49 @@ fn crypto_box(src: CryptoPlane, s: f64) -> CryptoPlane { crypto_box_within(src, s, MAX_BOX_PIXELS) } -/// [`crypto_box`] with a result of at most `max_out` pixels. The filter's work, a visit of every -/// layer pixel, is bounded by the source's size alone, which is in memory already: a 16K source -/// at half resolution is filtered, not looked up nearest-neighbour. -fn crypto_box_within(src: CryptoPlane, s: f64, max_out: usize) -> CryptoPlane { - if !(src.scale.is_finite() && src.scale > 0.0) { - return src; +/// The sizes of a box filter of a source plane to a render scale. +struct BoxSize { + /// Layer pixels per output pixel. + k: f64, + /// The layer's width in pixels. + lw: usize, + /// The layer's height in pixels. + lh: usize, + /// The result's width in pixels. + dw: usize, + /// The result's height in pixels. + dh: usize, +} + +/// [`BoxSize`] of a filter of a `width` × `height` source at `scale` to render scale `s` whose +/// result has at most `max_out` pixels, or `None` where the plane stays unscaled. The filter +/// visits every layer pixel and may visit at most four per source pixel, so a footage item +/// claiming a far larger size than its file is left unscaled. +fn box_size(width: u32, height: u32, scale: f64, s: f64, max_out: usize) -> Option { + if !(scale.is_finite() && scale > 0.0) { + return None; } // (layer pixels per output pixel; a whole number when it is one within rounding, so a // third resolution averages exactly three by three pixels) let k = 1.0 / s; let k = if (k - k.round()).abs() < 1e-9 * k { k.round() } else { k }; - let (lw, lh) = ((src.width as f64 / src.scale).ceil(), (src.height as f64 / src.scale).ceil()); + let (lw, lh) = ((width as f64 / scale).ceil(), (height as f64 / scale).ceil()); let (dw, dh) = ((lw / k * (1.0 - 1e-12)).ceil(), (lh / k * (1.0 - 1e-12)).ceil()); - // (the filter visits every layer pixel: at most four per source pixel; a footage item - // claiming a far larger size than its file is left unscaled) - let work = (src.width as usize).saturating_mul(src.height as usize).saturating_mul(4); + let work = (width as usize).saturating_mul(height as usize).saturating_mul(4); let fits = |v: f64| v.is_finite() && v >= 0.0 && v <= work as f64; if !(fits(lw) && fits(lh) && fits(dw) && fits(dh)) || (dw * dh) as usize > work.min(max_out) || (lw * lh) as usize > work { - return src; + return None; } - let (lw, lh, dw, dh) = (lw as usize, lh as usize, dw as usize, dh as usize); + Some(BoxSize { k, lw: lw as usize, lh: lh as usize, dw: dw as usize, dh: dh as usize }) +} + +/// [`crypto_box`] with a result of at most `max_out` pixels. The filter's work, a visit of every +/// layer pixel, is bounded by the source's size alone, which is in memory already: a 16K source +/// at half resolution is filtered, not looked up nearest-neighbour. +fn crypto_box_within(src: CryptoPlane, s: f64, max_out: usize) -> CryptoPlane { + let Some(BoxSize { k, lw, lh, dw, dh }) = box_size(src.width, src.height, src.scale, s, max_out) else { + return src; + }; let ch = src.output.channels(); let n = dw.saturating_mul(dh).saturating_mul(ch); let mut data = Vec::new(); diff --git a/crates/effects/src/channel3d/tests.rs b/crates/effects/src/channel3d/tests.rs index c1aba5265..7dae546b6 100644 --- a/crates/effects/src/channel3d/tests.rs +++ b/crates/effects/src/channel3d/tests.rs @@ -397,10 +397,10 @@ fn box_filter_survives_hostile_scales() { // A layer claiming 1000 × its file's size at a tiny render scale: few output pixels, but the // filter would visit 6.3e7 layer pixels; left unscaled, at once. tiny.scale = 1e-3; - let t = std::time::Instant::now(); let p = crypto_plane(&tiny, "CryptoObject", &[crypto_hash("cube")], CryptoOutput::Matte, 1e-3); assert_eq!(p.data.len(), 9 * 7); - assert!(t.elapsed() < std::time::Duration::from_secs(1)); + assert!(box_size(9, 7, 1e-3, 1e-3, MAX_BOX_PIXELS).is_none(), "the filter's work is refused, not done"); + assert!(box_size(9, 7, 1.0, 0.5, MAX_BOX_PIXELS).is_some(), "an ordinary half resolution is filtered"); } /// #3301 review: a source whose layer has more pixels than a filtered plane may have (a 16K diff --git a/crates/gpu/src/fx_depth/matte_cache.rs b/crates/gpu/src/fx_depth/matte_cache.rs index 28dc200d3..76bdd6dc3 100644 --- a/crates/gpu/src/fx_depth/matte_cache.rs +++ b/crates/gpu/src/fx_depth/matte_cache.rs @@ -107,13 +107,20 @@ fn plane_within(a: &Arc, layer: &str, sel: &[u32], output: CryptoOu if bytes > max_bytes && (budget == usize::MAX || bytes > budget) { return made; } - c.entries.push(Entry { aux: Arc::downgrade(a), key, plane: made.clone(), used: memory::tick(), cost_us }); + c.entries.push(Entry { aux: Arc::downgrade(a), key: key.clone(), plane: made.clone(), used: memory::tick(), cost_us }); loop { let total: usize = c.entries.iter().map(|e| e.plane.bytes()).fold(0, usize::saturating_add); if c.entries.len() <= 1 || (c.entries.len() <= MAX_ENTRIES && total <= max_bytes) { break; } - let Some(i) = oldest(&c) else { break }; + let Some(i) = oldest(&c) else { + // Renders hold every plane kept: the new one is handed out, not kept, so the + // cache never stays over its limits once they let go. + if let Some(i) = c.entries.iter().position(|e| e.of(a) && e.key == key) { + c.entries.swap_remove(i); + } + return made; + }; c.entries.swap_remove(i); } } @@ -121,13 +128,14 @@ fn plane_within(a: &Arc, layer: &str, sel: &[u32], output: CryptoOu made } -/// The entry to drop next: one whose channels are gone, else the least recently used of those -/// no render holds now (dropping one in use would free nothing yet). +/// The entry to drop next, of those no render holds now (dropping one in use would free nothing +/// yet): one whose channels are gone, else the least recently used. fn oldest(c: &Cache) -> Option { + let free = |e: &Entry| Arc::strong_count(&e.plane) == 1; c.entries .iter() - .position(Entry::gone) - .or_else(|| c.entries.iter().enumerate().filter(|(_, e)| Arc::strong_count(&e.plane) == 1).min_by_key(|(_, e)| e.used).map(|(i, _)| i)) + .position(|e| e.gone() && free(e)) + .or_else(|| c.entries.iter().enumerate().filter(|(_, e)| free(e)).min_by_key(|(_, e)| e.used).map(|(i, _)| i)) } /// The planes in the common memory budget. @@ -165,6 +173,12 @@ pub(crate) fn made() -> u64 { lock().made } +/// Whether `p` is kept (tests). +#[cfg(test)] +pub(crate) fn keeps(p: &Arc) -> bool { + lock().entries.iter().any(|e| Arc::ptr_eq(&e.plane, p)) +} + /// Planes kept now (tests). #[cfg(test)] pub(crate) fn kept() -> usize { diff --git a/crates/gpu/src/tests/fx_depth.rs b/crates/gpu/src/tests/fx_depth.rs index 9e53d10a3..d562d5917 100644 --- a/crates/gpu/src/tests/fx_depth.rs +++ b/crates/gpu/src/tests/fx_depth.rs @@ -412,6 +412,39 @@ fn a_plane_over_the_byte_limit_is_kept_only_under_a_budget() { assert!(Arc::ptr_eq(&first, &again), "a budget that holds it: kept"); } +/// #3750 review: a plane a render still holds is not offered to the memory accountant, even +/// once its frame's channels are gone (dropping it would free nothing while the render holds it). +#[test] +fn a_held_plane_of_gone_channels_is_not_offered() { + use crate::fx_depth::matte_cache; + use effectcraft_effects::CryptoOutput; + crate::tests::hold_gpu_lock(); + let gone = Arc::new(aux_scene(70, 44, 1.0)); + let held = matte_cache::plane(&gone, "CryptoObject", &[crypto_hash("beta")], CryptoOutput::Matte, 1.0); + drop(gone); + let holder = matte_cache::holder(); + // (everything nobody holds goes; at most as many rounds as planes kept) + for _ in 0..=matte_cache::kept() { + if holder.drop_oldest() == 0 { + break; + } + } + assert!(matte_cache::keeps(&held), "the held plane was offered and dropped"); +} + +/// #3750 review: when renders hold every plane kept, a new plane is handed out but not kept, so +/// the cache never stays over its entry limit (32) once they let go. +#[test] +fn the_entry_limit_holds_while_renders_hold_every_plane() { + use crate::fx_depth::matte_cache; + use effectcraft_effects::CryptoOutput; + crate::tests::hold_gpu_lock(); + let a = Arc::new(aux_scene(70, 44, 1.0)); + let held: Vec<_> = (0..40u32).map(|i| matte_cache::plane_held_to(&a, "CryptoObject", &[i], CryptoOutput::Matte, usize::MAX, usize::MAX)).collect(); + assert!(matte_cache::kept() <= 32, "{} planes kept", matte_cache::kept()); + drop(held); +} + #[test] fn extractor() { case("ec.3d.extractor", &[("red", Value::Str("Z".into())), ("green", Value::Str("UV.U".into())), ("whitePoint", n(1000.0))]); diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index bf261491b..21d47ead1 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -235,6 +235,12 @@ impl Flight { self.take(CLAIMED) } + /// The decode asked for more than `want` (other requests added to it): a refusal for its + /// size may not hold for `want` alone. + fn asks_beyond(&self, index: &ExrIndex, want: &Want) -> bool { + !asks_at_least(index, want, &self.state().want) + } + fn claimed(&self) -> bool { self.phase.load(std::sync::atomic::Ordering::SeqCst) == CLAIMED } @@ -545,6 +551,8 @@ impl PlaneStore { // Not all it asks for: ask again (the next decode reads what is missing). Waited::Got(Ok(_)) => Step::Again { retry: false }, Waited::Got(Err(Refused::Cancelled | Refused::Forgotten | Refused::Stopped)) => Step::Again { retry: true }, + // Too large with what other requests added to it: this request alone may fit. + Waited::Got(Err(Refused::TooLarge(_))) if flight.asks_beyond(index, want) => Step::Again { retry: true }, Waited::Got(Err(e)) => Step::Done(Err(e)), Waited::Cancelled => Step::Done(Err(Refused::Cancelled)), // A copy, kept nowhere. @@ -569,13 +577,16 @@ impl PlaneStore { Step::Done(Ok(b)) } Ok(_) | Err(Refused::Forgotten | Refused::Stopped) => Step::Again { retry: true }, + // (as a waiter: this request alone may fit) + Err(Refused::TooLarge(_)) if flight.asks_beyond(index, want) => Step::Again { retry: true }, Err(e) => Step::Done(Err(e)), } } /// Keep only the channels `keep` of the planes `b` of `path` (a picture converted: the pool /// keeps the picture, its planes would be a second copy of it); nothing when none is left. - /// The set is trimmed in place when nobody else holds it, else the kept planes are copied. + /// The set is trimmed in place when nobody else holds it, else the kept planes are copied; + /// when the system can't give the memory for that copy, the set stays as it was. pub(crate) fn keep_only(&self, path: &str, b: Arc, keep: &BTreeSet) { if b.ids.iter().all(|id| keep.contains(id)) { return; @@ -589,24 +600,38 @@ impl PlaneStore { e.bytes = 0; } st.held.retain(|(p, h)| !(p == path && Arc::ptr_eq(h, &b))); - let slim = match Arc::try_unwrap(b) { - Ok(mut owned) => { - let mut aux = Arc::try_unwrap(owned.aux).unwrap_or_else(|shared| AuxChannels::clone(&shared)); - let channels = std::mem::take(&mut aux.channels); - aux.channels = owned.ids.iter().zip(channels).filter(|(id, _)| keep.contains(id)).map(|(_, c)| c).collect(); - owned.ids.retain(|id| keep.contains(id)); - aux.listed = owned.index.channels.iter().map(|c| c.name.clone()).collect(); - owned.aux = Arc::new(aux); - owned - } - Err(shared) => { - let mut aux = AuxChannels::new(shared.aux.width, shared.aux.height, shared.aux.scale); - aux.manifests = shared.aux.manifests.clone(); - aux.aliases = shared.aux.aliases.clone(); - aux.listed = shared.index.channels.iter().map(|c| c.name.clone()).collect(); - aux.channels = shared.ids.iter().zip(&shared.aux.channels).filter(|(id, _)| keep.contains(id)).map(|(_, c)| c.clone()).collect(); - let ids = shared.ids.iter().copied().filter(|id| keep.contains(id)).collect(); - Batch { index: shared.index.clone(), ids, all: shared.all, aux: Arc::new(aux), file: shared.file.clone() } + let slimmed = match Arc::try_unwrap(b) { + Ok(mut owned) => match Arc::try_unwrap(owned.aux) { + Ok(mut aux) => { + let channels = std::mem::take(&mut aux.channels); + aux.channels = owned.ids.iter().zip(channels).filter(|(id, _)| keep.contains(id)).map(|(_, c)| c).collect(); + owned.ids.retain(|id| keep.contains(id)); + aux.listed = owned.index.channels.iter().map(|c| c.name.clone()).collect(); + owned.aux = Arc::new(aux); + Ok(owned) + } + Err(shared_aux) => { + owned.aux = shared_aux; + match slim_copy(path, &owned, keep) { + Some(slim) => Ok(slim), + None => Err(Arc::new(owned)), + } + } + }, + Err(shared) => slim_copy(path, &shared, keep).ok_or(shared), + }; + let slim = match slimmed { + Ok(slim) => slim, + // (no memory for the copy: the set stays as it was) + Err(whole) => { + if let Some(e) = st.entries.get_mut(at) { + e.bytes = whole.bytes(); + e.batch = Some(whole.clone()); + } + if held { + st.held.push_back((path.to_string(), whole)); + } + return; } }; if slim.ids.is_empty() { @@ -801,6 +826,38 @@ impl PlaneStore { } } +/// The channels `keep` of `b` (of `path`) in a set of their own, the planes copied; `None` when +/// the system can't give the memory for a copy. +fn slim_copy(path: &str, b: &Batch, keep: &BTreeSet) -> Option { + #[cfg(test)] + if COPIES_REFUSED.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|p| p == path) { + return None; + } + let _ = path; + let mut aux = AuxChannels::new(b.aux.width, b.aux.height, b.aux.scale); + aux.manifests = b.aux.manifests.clone(); + aux.aliases = b.aux.aliases.clone(); + aux.listed = b.index.channels.iter().map(|c| c.name.clone()).collect(); + for (id, (name, plane)) in b.ids.iter().zip(&b.aux.channels) { + if keep.contains(id) { + let mut copy = Vec::new(); + copy.try_reserve_exact(plane.len()).ok()?; + copy.extend_from_slice(plane); + aux.channels.push((name.clone(), copy)); + } + } + let ids = b.ids.iter().copied().filter(|id| keep.contains(id)).collect(); + Some(Batch { index: b.index.clone(), ids, all: b.all, aux: Arc::new(aux), file: b.file.clone() }) +} + +/// One path per plane copied for the disk cache (tests). +#[cfg(test)] +pub(crate) static DISK_COPIES: Mutex> = Mutex::new(Vec::new()); + +/// Paths whose planes [`slim_copy`] finds no memory for (tests). +#[cfg(test)] +pub(crate) static COPIES_REFUSED: Mutex> = Mutex::new(Vec::new()); + /// This thread may not wait for planes: a decode thread (#3270: a decode doesn't depend on the /// requests waiting for it; an owner on a frame worker queues its decode on these threads, and /// a decode thread waiting for it could starve that queue), or one running a store decode. @@ -1015,22 +1072,38 @@ fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option()); + if let Some(d) = disk.as_ref().filter(|d| d.accepts_writes() && plane_bytes as u64 <= d.limit_bytes()) { let mut files = effectcraft_render::reads::ReadFiles::default(); files.add(batch.file.clone()); if let Some(entry) = effectcraft_render::disk_cache::EntryFiles::of(&files, None) { - // (copies, each owned by its write: a queued write never keeps the store's set) - let planes: Vec<(u128, String, Vec)> = to_read - .par_iter() + // The planes read now that the disk cache doesn't hold yet. + let fresh: Vec<(u128, &String, &Vec)> = to_read + .iter() .filter_map(|id| { let (name, plane) = batch.aux.channels.get(batch.ids.binary_search(id).ok()?)?; - Some((key(name), name.clone(), plane.clone())) + let k = key(name); + (!d.contains(effectcraft_render::disk_cache::Kind::Plane, k)).then_some((k, name, plane)) }) .collect(); // (only planes that cost more to decode again than to read back, #3301) - let bytes = planes.iter().map(|(_, _, p)| p.len().saturating_mul(std::mem::size_of::())).fold(0, usize::saturating_add); - let took_us = read_took; - if d.pays_off(bytes, took_us) { + let bytes = fresh.iter().map(|(_, _, p)| p.len().saturating_mul(std::mem::size_of::())).fold(0, usize::saturating_add); + if !fresh.is_empty() && d.pays_off(bytes, read_took) { + // (copies, each owned by its write: a queued write never keeps the store's set; + // a plane the system can't give the memory for is left out) + let planes: Vec<(u128, String, Vec)> = fresh + .par_iter() + .filter_map(|(k, name, plane)| { + let mut copy = Vec::new(); + copy.try_reserve_exact(plane.len()).ok()?; + copy.extend_from_slice(plane); + #[cfg(test)] + DISK_COPIES.lock().unwrap_or_else(PoisonError::into_inner).push(path.to_string()); + Some((*k, (*name).clone(), copy)) + }) + .collect(); d.put_planes(w as u32, h as u32, planes, &entry, since); } } @@ -1230,16 +1303,22 @@ fn picture_fits(path: &str, index: &ExrIndex) -> Result<(), String> { Err(format!("its {w}×{h} OpenEXR picture needs {:.1} GB of memory, more than the {:.1} GB one file may use", gb(need), gb(most))) } -/// The picture of the OpenEXR at `path` (as [`picture`]) of only the display rows `rows`: those -/// rows are read (with 1-line chunks exactly those lines, else the chunks holding them) and -/// converted, the others stay empty (#3271: a region of interest). Read for this request alone, -/// not kept in the store or on disk (the pool keeps the picture under a key naming the rows). -pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i64, i64)) -> Picture { +/// The picture of the OpenEXR at `path` (as [`picture`]) of only the display rows `rows` of the +/// footage's `nominal` size: those rows are read (with 1-line chunks exactly those lines, else +/// the chunks holding them) and converted, the others stay empty (#3271: a region of interest). +/// Read for this request alone, not kept in the store or on disk (the pool keeps the picture +/// under a key naming the rows). A file of another size than `nominal` (a sequence frame larger +/// than the first) is shown scaled, so its rows are not those: it is read whole. +pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i64, i64), nominal: (u32, u32)) -> Picture { let (index, opened) = match exr_index::get_opened(path, source) { Ok(ix) => ix, Err(IndexError::Unsupported(why)) => return Picture::Done(Err(why.to_string())), Err(_) => return Picture::Legacy, }; + if index.size() != (nominal.0 as usize, nominal.1 as usize) { + drop(opened); + return picture(path, source, op, None); + } if let Err(why) = picture_fits(path, &index) { return Picture::Done(Err(why)); } diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index 02f99a2c1..7a97ca592 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -868,6 +868,63 @@ fn a_picture_too_large_with_its_channels_is_read_alone() { assert_eq!(d.last().map(|d| d.channels.len()), Some(4), "{d:?}"); } +/// #3750 review: two requests that each fit under the read's limit, merged into one decode that +/// doesn't, each get their planes: a refusal for the merged size is not handed to a request +/// whose own planes fit (they are read again for it alone). +#[test] +fn a_merged_decode_too_large_leaves_each_request_that_fits_its_planes() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3750-merged-too-large.exr"; + let source = ExrSource::Bytes(bytes); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture: BTreeSet = index.picture_ids().into_iter().collect(); + let first = Want { all: false, ids: picture.clone() }; + // (10 passes: with the picture's 4 planes 14, over the limit of 12) + let passes: BTreeSet = (0..index.channels.len()).filter(|i| !picture.contains(i)).take(10).collect(); + let second = Want { all: false, ids: passes.clone() }; + set_cap(path, 12 * SIZE.0 * SIZE.1 * 4); + // Before the first request's decode reads: the second request joins it. + let (tx, rx) = std::sync::mpsc::channel(); + let joined = Arc::new(std::sync::atomic::AtomicBool::new(false)); + { + let (store, source, index, second, joined) = (store.clone(), source.clone(), index.clone(), second.clone(), joined.clone()); + let hook: Hook = Arc::new(move |_: &str| { + if joined.swap(true, Ordering::SeqCst) { + return; + } + let (s, src, idx, want, tx) = (store.clone(), source.clone(), index.clone(), second.clone(), tx.clone()); + std::thread::spawn(move || { + let _ = tx.send(s.get(path, &src, &idx, &want, Use::Other).map(|b| b.ids.clone())); + }); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while std::time::Instant::now() < until { + let merged = store + .lock() + .entries + .iter() + .find(|e| e.path == path) + .and_then(|e| e.flight.clone()) + .is_some_and(|f| second.ids.iter().all(|id| f.state().want.ids.contains(id))); + if merged { + break; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + }); + set_before_read(path, Some(hook)); + } + let got_first = store.get(path, &source, &index, &first, Use::Other).map(|b| b.ids.clone()); + let got_second = rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + set_before_read(path, None); + assert!(joined.load(Ordering::SeqCst)); + assert!(decodes_of(path).first().is_some_and(|d| d.channels.len() == 14), "merged first: {:?}", decodes_of(path)); + let got_first = got_first.expect("the picture alone fits"); + let got_second = got_second.expect("the passes alone fit"); + assert!(picture.iter().all(|id| got_first.contains(id)), "{got_first:?}"); + assert!(passes.iter().all(|id| got_second.contains(id)), "{got_second:?}"); +} + /// #474: at most CACHE_FILES entries are kept, however small. #[test] fn the_store_keeps_a_bounded_number_of_files() { @@ -1105,7 +1162,17 @@ fn decoded_planes_are_kept_on_disk_and_read_back_exactly() { dc.flush(); pool.forget(&f.path); pool.aux(ItemId(1), &f, Tick::ZERO).unwrap(); + // #3750 review: a disk cache too small for one plane gets no copies of the planes at all. + dc.flush(); + dc.set_max_bytes(1024); + let small = dir.join("crypto_0002.exr"); + std::fs::write(&small, multipart()).unwrap(); + let g = crate::probe(&small).unwrap(); + pool.aux(ItemId(2), &g, Tick::ZERO).unwrap(); set_disk_cache(None); + let copies = DISK_COPIES.lock().unwrap().iter().filter(|p| **p == g.path).count(); + assert_eq!(copies, 0, "no plane copied for a cache it can't go in"); + assert!(DISK_COPIES.lock().unwrap().iter().any(|p| *p == f.path), "copied while it could"); let from_disk: Vec = decodes_of(&f.path).iter().map(|d| d.from_disk).collect(); assert_eq!(from_disk, [false, false, true, false]); let _ = std::fs::remove_dir_all(&dir); @@ -1518,6 +1585,71 @@ fn the_picture_planes_are_not_kept_beside_the_picture() { forget(path); } +/// #3750 review: slimming a set someone else still holds copies the planes it keeps; when the +/// system can't give the memory for the copy, the set stays as it was (nothing aborts). +#[test] +fn a_shared_set_stays_whole_when_its_copy_finds_no_memory() { + let bytes: Arc<[u8]> = write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", true), ("Z", false)], (16, 8), Compression::ZIP1)], (16, 8)).into(); + let path = "/3750-slim-no-memory.exr"; + let source = ExrSource::Bytes(bytes); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let all = Want { all: true, ids: index.picture_ids().into_iter().collect() }; + let whole = store.get(path, &source, &index, &all, Use::Other).unwrap(); + let z: BTreeSet = index.aux_ids().into_iter().collect(); + COPIES_REFUSED.lock().unwrap().push(path.to_string()); + // (`whole` is still held here: the planes kept would be copied) + store.keep_only(path, whole.clone(), &z); + COPIES_REFUSED.lock().unwrap().retain(|p| p != path); + let kept = store.lock().entries.iter().find(|e| e.path == path).and_then(|e| e.batch.clone()); + assert!(kept.is_some_and(|k| Arc::ptr_eq(&k, &whole)), "the whole set is kept"); + // With memory for the copy: the kept channel alone. + store.keep_only(path, whole.clone(), &z); + assert_eq!(store.kept(path).map(|(n, _)| n), Some(vec!["Z".to_string()])); +} + +/// #3750 review: a frame of another size than its footage's (a sequence frame larger than the +/// first, shown scaled) is read whole under a region of interest, so the region shows what the +/// whole frame shows; the region's rows are of the footage's size, not of that frame. +#[test] +fn a_frame_of_another_size_is_read_whole_under_a_region() { + use effectcraft_project::{Comp, ItemKind, LayerSource, Project, build}; + use effectcraft_render::{RenderOpts, Renderer}; + use effectcraft_time::FrameRate; + struct Whole<'a>(&'a crate::MediaPool); + impl FootageSource for Whole<'_> { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + self.0.frame(item, f, t) + } + fn frame_with(&self, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { + self.0.frame_with(item, f, t, size, float) + } + } + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3750-roi-other-size.exr"; + let fresh = || { + let pool = crate::MediaPool::new(); + pool.add_bytes(path, bytes.clone()); + pool + }; + // (the footage's size is half the file's: a later, larger frame) + let mut f = crate::probe_bytes(path, bytes.clone()).unwrap(); + f.width = SIZE.0 as u32 / 2; + f.height = SIZE.1 as u32 / 2; + let mut p = Project::default(); + let comp = Comp::new(96, 96, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + let cid = p.add_item("Comp", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let fid = p.add_item("plate", effectcraft_color::Label::Aqua, None, ItemKind::Footage(f)); + let l = build::layer(&mut p, &comp, "plate", LayerSource::Footage { item: fid }, (SIZE.0 as u32 / 2, SIZE.1 as u32 / 2), None); + p.comp_mut(cid).unwrap().layers = vec![l].into(); + let opts = RenderOpts { roi: Some([30.0, 40.0, 30.0, 8.0]), ..Default::default() }; + let whole = Renderer::new(&p, &Whole(&fresh()), opts).comp_frame(cid, Tick::ZERO); + let before = decodes_of(path).len(); + let rows = Renderer::new(&p, &fresh(), opts).comp_frame(cid, Tick::ZERO); + assert_eq!(bits(&rows), bits(&whole)); + assert!(decodes_of(path).get(before..).unwrap_or_default().iter().all(|d| d.stats.lines == SIZE.1), "read whole"); +} + /// #3271 review (#3301): a remembered failure belongs to the file as it was. A file that was /// unreadable and is then replaced on disk (no Reload Footage: the new index comes from its new /// stamp) is read again, not refused with the old file's failure. diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index c20e546d2..1b5792bc0 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -71,6 +71,14 @@ enum Pixels { } impl Pixels { + /// Nobody but the cache holds the pixels: dropping them frees their memory. + fn unshared(&self) -> bool { + match self { + Pixels::F32(img) => Arc::strong_count(img) == 1, + Pixels::Q8(f) => Arc::strong_count(f) == 1, + } + } + fn bytes(&self) -> usize { match self { Pixels::F32(img) => img.data.len() * std::mem::size_of::(), @@ -199,13 +207,17 @@ impl Lru { } } } - /// The least recently used frame it may drop (the newest always stays) and its last use. + /// The least recently used frame it may drop and its last use: not the newest (it always + /// stays) and not one whose pixels someone else holds (dropping it would free nothing yet). fn oldest(&self) -> Option<(&Key, u64)> { if self.map.len() <= 1 { return None; } - let (_, k) = self.order.first_key_value()?; - Some((k, self.map.get(k)?.used)) + let newest = self.order.last_key_value().map(|(s, _)| *s); + self.order.iter().filter(|(s, _)| Some(**s) != newest).find_map(|(_, k)| { + let e = self.map.get(k)?; + e.img.unshared().then_some((k, e.used)) + }) } /// Drop the least recently used frame it may drop; the bytes freed. fn drop_oldest(&mut self) -> usize { @@ -335,6 +347,14 @@ impl CacheState { self.forgotten.insert(path.into(), self.generation); } + /// Note that every file was let go (Purge): whatever a request or decode that started before + /// makes is stale, and none of them is joined. + fn forgot_all(&mut self) { + self.generation = self.generation.saturating_add(1); + self.forgotten.clear(); + self.stale_before = self.generation; + } + /// The whole still `key` decoded recently, with the files it was decoded from, if it is /// still kept. fn recent(&mut self, key: &Key) -> Option<(Arc, Arc)> { @@ -378,6 +398,12 @@ impl CacheState { self.lru.bytes.saturating_add(self.lru.spare_bytes()).saturating_add(self.recent_bytes()) } + /// The oldest whole still in [`CacheState::recent`] that nobody else holds (dropping one in + /// use would free nothing yet). + fn oldest_recent(&self) -> Option { + self.recent.iter().position(|r| Arc::strong_count(&r.img) == 1) + } + /// The bytes of the whole stills [`CacheState::recent`] holds. fn recent_bytes(&self) -> usize { self.recent.iter().map(|r| r.bytes).sum() @@ -796,6 +822,8 @@ impl MediaPool { c.lru = Lru::default(); c.recent.clear(); c.last.clear(); + // (a decode in flight keeps nothing, and later requests don't join it) + c.forgot_all(); c.forgets = c.forgets.wrapping_add(1); drop(c); // Decoded GIFs sit outside the frame budget; Purge frees them too. @@ -1639,7 +1667,9 @@ impl Inner { use crate::exr_planes::Picture; let extra = lock(&self.aux_footage).plan(&footage.path); let picture = match loc.key.rows { - Some(rows) if extra.is_none() => crate::exr_planes::picture_rows(path, &self.exr_source(path), op, rows), + Some(rows) if extra.is_none() => { + crate::exr_planes::picture_rows(path, &self.exr_source(path), op, rows, (footage.width, footage.height)) + } _ => crate::exr_planes::picture(path, &self.exr_source(path), op, extra.as_ref()), }; match picture { @@ -1749,7 +1779,7 @@ impl effectcraft_render::memory::MemoryHolder for Inner { } let frame = c.lru.oldest().and_then(|(k, _)| c.lru.map.get(k)).map(|e| Candidate { used: e.used, bytes: e.bytes, cost_us: e.cost_us, protected: false }); - let still = c.recent.front().map(|r| Candidate { used: r.used, bytes: r.bytes.max(1), cost_us: 0, protected: false }); + let still = c.oldest_recent().and_then(|i| c.recent.get(i)).map(|r| Candidate { used: r.used, bytes: r.bytes.max(1), cost_us: 0, protected: false }); match (frame, still) { (Some(f), Some(s)) => Some(if s.used < f.used { s } else { f }), (f, s) => f.or(s), @@ -1761,10 +1791,11 @@ impl effectcraft_render::memory::MemoryHolder for Inner { return c.lru.drop_spare(); } let frame = c.lru.oldest().map(|(_, t)| t); - let still = c.recent.front().map(|r| r.used); - match (frame, still) { - (Some(f), Some(s)) if s < f => c.recent.pop_front().map_or(0, |r| r.bytes.max(1)), - (None, Some(_)) => c.recent.pop_front().map_or(0, |r| r.bytes.max(1)), + let at = c.oldest_recent(); + let still = at.and_then(|i| c.recent.get(i)).map(|r| r.used); + match (frame, still, at) { + (Some(f), Some(s), Some(i)) if s < f => c.recent.remove(i).map_or(0, |r| r.bytes.max(1)), + (None, Some(_), Some(i)) => c.recent.remove(i).map_or(0, |r| r.bytes.max(1)), _ => c.lru.drop_oldest(), } } @@ -2183,6 +2214,35 @@ mod tests { assert_eq!(holder.drop_oldest(), px + 64, "then the oldest frame"); } + /// #3750 review: a frame or whole still whose pixels someone else holds is not offered to the + /// accountant (dropping it would free nothing yet): what goes is what nobody else holds. + #[test] + fn frames_and_stills_held_elsewhere_are_not_offered() { + let pool = MediaPool::unregistered(usize::MAX); + let holder = pool.memory_holder(); + let px = 256 * std::mem::size_of::(); + let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), rows: None, q8: false }; + let held = Arc::new(Image::new(16, 16)); + let held_still = Arc::new(Image::new(8, 8)); + { + let mut c = lock(&pool.inner.cache); + c.lru.insert(k(0), Pixels::F32(held.clone()), Arc::default(), usize::MAX); + c.lru.insert(k(1), Pixels::F32(Arc::new(Image::new(16, 16))), Arc::default(), usize::MAX); + c.lru.insert(k(2), Pixels::F32(Arc::new(Image::new(16, 16))), Arc::default(), usize::MAX); + // (two whole stills, older than every frame: the held one first) + let stamp = c.lru.clock; + c.recent.push_back(Recent { key: k(8), img: held_still.clone(), files: Arc::default(), bytes: 64 * 16, stamp, used: 0 }); + c.recent.push_back(Recent { key: k(9), img: Arc::new(Image::new(4, 4)), files: Arc::default(), bytes: 16 * 16, stamp, used: 0 }); + } + assert_eq!(holder.drop_oldest(), 16 * 16, "the still nobody holds"); + assert_eq!(holder.drop_oldest(), px + 64, "the oldest frame nobody holds"); + assert!(holder.oldest().is_none(), "the rest is held elsewhere, or the newest frame"); + let c = lock(&pool.inner.cache); + assert!(c.lru.map.contains_key(&k(0)) && c.recent.iter().any(|r| Arc::ptr_eq(&r.img, &held_still))); + drop(c); + drop((held, held_still)); + } + /// A frame kept as 8-bit levels is its own entry beside the float one, counted at 4 bytes /// a pixel. #[test] @@ -2657,6 +2717,39 @@ mod tests { *lock(&pool.inner.gate) = None; } + /// #3750 review: a decode running when the frames are cleared (Purge) keeps nothing: its + /// frame doesn't come back into the cache after Purge emptied it. + #[test] + fn a_decode_running_across_purge_keeps_nothing() { + let pool = MediaPool::new(); + let f = plate(&pool, "/purge.exr"); + let started = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let go = Arc::new(std::sync::atomic::AtomicBool::new(false)); + { + let (started, go) = (started.clone(), go.clone()); + // The decode waits (2 s at most) until the frames were cleared, then decodes the file. + *lock(&pool.inner.gate) = Some(Arc::new(move || { + started.store(true, Ordering::SeqCst); + let until = std::time::Instant::now() + std::time::Duration::from_secs(2); + while !go.load(Ordering::SeqCst) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + None + })); + } + std::thread::scope(|s| { + let decoding = s.spawn(|| pool.frame_at(&f, Tick::ZERO)); + while !started.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + pool.clear_frames(); + go.store(true, Ordering::SeqCst); + assert!(decoding.join().unwrap().is_ok(), "the request still gets its picture"); + }); + *lock(&pool.inner.gate) = None; + assert_eq!(pool.stats().frames, 0, "nothing kept after Purge"); + } + /// Forgotten paths are remembered per path and boundedly: past [`MAX_FORGOTTEN`], everything /// that started before counts as stale. #[test] diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 50b472305..03c104427 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -126,7 +126,7 @@ const FORMAT_F16_FILES: u8 = 3; /// Layer entries: their source files ([`EntryFiles`]), then the buffer. The format before it /// (0, without files) reads as a miss and is deleted. const FORMAT_LAYER_FILES: u8 = 4; -/// Plane entries: their source file ([`EntryFiles`]), then one named plane ([`encode_plane`]). +/// Plane entries: their source file ([`EntryFiles`]), then one named plane ([`encode_plane_after`]). /// (5, several `f32` planes per entry, reads as a miss and is deleted.) const FORMAT_PLANES_FILES: u8 = 6; @@ -357,7 +357,16 @@ impl Payload { Payload::FrameF16(w, h, rgba, files) => one(key, &|| with_files(&files, encode_frame_f16(w, h, &rgba))), Payload::Planes(w, h, planes, files) => { for (key, name, plane) in planes { - one(key, &|| with_files(&files, encode_plane(w, h, &name, &plane))); + if cache.contains(kind, key) { + continue; + } + let mut entry = Vec::new(); + files.encode(&mut entry); + // (no memory for the encoder just now: the entry isn't written, and the + // plane is decoded from its file next time) + if let Some(entry) = encode_plane_after(entry, w, h, &name, &plane) { + cache.write_format(kind, key, format, &entry); + } } } Payload::Lz4(raw) => one(key, &|| lz4_flex::compress_prepend_size(&raw)), @@ -1736,6 +1745,10 @@ fn decompress_checked(p: &[u8], expected: Option) -> Option> { /// `n` copies of `v`, or `None` when the system can't give the memory: a cache entry read back /// then counts as a miss. fn zeroed(n: usize, v: T) -> Option> { + #[cfg(test)] + if n.saturating_mul(std::mem::size_of::()) > NO_MEMORY_OVER.with(std::cell::Cell::get) { + return None; + } let mut out = Vec::new(); out.try_reserve_exact(n).ok()?; out.resize(n, v); @@ -1795,13 +1808,20 @@ fn decode_frame_f16(p: &[u8]) -> Option { Some(FrameF16 { width: w, height: h, rgba }) } -/// A plane entry's pixels (`plane`, named `name`, of `w` x `h`): width, height, the name -/// (length and UTF-8 bytes) and the sample type, then the samples' bytes shuffled into byte -/// planes (the first bytes of all samples, then the second...), LZ4-compressed. Type 1: half -/// floats, when every value is one exactly (a half channel: half the bytes); type 2: `f32` -/// (bit-exact: Cryptomatte IDs are float bit patterns). +/// [`encode_plane_after`] alone (tests). +#[cfg(test)] fn encode_plane(w: u32, h: u32, name: &str, plane: &[f32]) -> Vec { - let mut out = Vec::with_capacity(64); + encode_plane_after(Vec::new(), w, h, name, plane).unwrap_or_default() +} + +/// A plane entry's pixels (`plane`, named `name`, of `w` x `h`) appended to `out` (the entry's +/// source files): width, height, the name (length and UTF-8 bytes) and the sample type, then the +/// samples' bytes shuffled into byte planes (the first bytes of all samples, then the +/// second...), LZ4-compressed. Type 1: half floats, when every value is one exactly (a half +/// channel: half the bytes); type 2: `f32` (bit-exact: Cryptomatte IDs are float bit patterns). +/// The scratch memory and the result are taken fallibly: `None` when the system can't give them. +fn encode_plane_after(mut out: Vec, w: u32, h: u32, name: &str, plane: &[f32]) -> Option> { + out.try_reserve(64).ok()?; out.extend_from_slice(&w.to_le_bytes()); out.extend_from_slice(&h.to_le_bytes()); let name = name.as_bytes(); @@ -1809,14 +1829,14 @@ fn encode_plane(w: u32, h: u32, name: &str, plane: &[f32]) -> Vec { out.extend_from_slice(&(len as u16).to_le_bytes()); out.extend_from_slice(name.get(..len).unwrap_or_default()); let n = plane.len(); - let mut halves = vec![half::f16::ZERO; n]; + let mut halves = zeroed(n, half::f16::ZERO)?; half::slice::HalfFloatSliceExt::convert_from_f32_slice(halves.as_mut_slice(), plane); // (NaNs stay `f32`: their payloads must come back as they were) let exact = halves.iter().zip(plane).all(|(h, v)| !v.is_nan() && h.to_f32().to_bits() == v.to_bits()); // Shuffled straight from the samples' bits into byte planes. let shuffled = if exact { out.push(1); - let mut s = vec![0u8; n.saturating_mul(2)]; + let mut s = zeroed(n.checked_mul(2)?, 0u8)?; let (lo, hi) = s.split_at_mut(n); for ((l, hb), x) in lo.iter_mut().zip(hi.iter_mut()).zip(&halves) { [*l, *hb] = x.to_bits().to_le_bytes(); @@ -1825,7 +1845,7 @@ fn encode_plane(w: u32, h: u32, name: &str, plane: &[f32]) -> Vec { } else { drop(halves); out.push(2); - let mut s = vec![0u8; n.saturating_mul(4)]; + let mut s = zeroed(n.checked_mul(4)?, 0u8)?; let (b0, rest) = s.split_at_mut(n); let (b1, rest) = rest.split_at_mut(n); let (b2, b3) = rest.split_at_mut(n); @@ -1834,11 +1854,25 @@ fn encode_plane(w: u32, h: u32, name: &str, plane: &[f32]) -> Vec { } s }; - out.extend_from_slice(&lz4_flex::compress_prepend_size(&shuffled)); - out + // (as `lz4_flex::compress_prepend_size`: the size, then the block) + let most = lz4_flex::block::get_maximum_output_size(shuffled.len()); + out.try_reserve_exact(most.checked_add(4)?).ok()?; + out.extend_from_slice(&u32::try_from(shuffled.len()).ok()?.to_le_bytes()); + let at = out.len(); + out.resize(at.checked_add(most)?, 0); + let len = lz4_flex::block::compress_into(&shuffled, out.get_mut(at..)?).ok()?; + out.truncate(at.saturating_add(len)); + Some(out) } -/// The name and plane of a plane entry's pixels ([`encode_plane`]) of `expect` (width, height); +/// Allocations [`zeroed`] refuses on this thread: those over this many bytes (tests: memory the +/// system can't give). +#[cfg(test)] +thread_local! { + static NO_MEMORY_OVER: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; +} + +/// The name and plane of a plane entry's pixels ([`encode_plane_after`]) of `expect` (width, height); /// `None` when damaged or of another size. fn decode_plane(p: &[u8], expect: (u32, u32)) -> Option<(String, Vec)> { let u32_at = |at: usize| Some(u32::from_le_bytes(p.get(at..at + 4)?.try_into().ok()?)); @@ -2361,6 +2395,25 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// #3750 review: a plane write whose encoder can't get its scratch memory (the half or + /// shuffled buffer of a 16K plane) writes no entry and goes on, instead of aborting; with the + /// memory it is written. + #[test] + fn a_plane_write_without_memory_for_its_encoder_is_skipped() { + let dir = tmpdir("planes-no-memory"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (files, _) = plane_source(&dir.join("src")); + let job = |key: u128| Payload::Planes(16, 8, vec![(key, "A.R".to_string(), vec![0.5f32; 128])], files.clone()); + // (this thread's allocations through the encoder's scratch over 64 bytes are refused) + NO_MEMORY_OVER.with(|c| c.set(64)); + job(1).write(&dc, Kind::Plane, 1, FORMAT_PLANES_FILES); + NO_MEMORY_OVER.with(|c| c.set(usize::MAX)); + assert!(!dc.contains(Kind::Plane, 1), "no entry without the encoder's memory"); + job(2).write(&dc, Kind::Plane, 2, FORMAT_PLANES_FILES); + assert!(dc.get_plane(2, 16, 8).is_some(), "written with it"); + let _ = std::fs::remove_dir_all(&dir); + } + /// #3271: a queued plane write owns its planes, counts them for the memory accountant (all /// of them, not a share of the store's set) and frees them when the accountant drops it; /// frames stay. 69 channels are queued without loss, each written as an entry of its own diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 36e08878a..b695c108e 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -1259,10 +1259,12 @@ impl<'a> Renderer<'a> { if comp_reads_pixels(ctx) || !self.footage.reads_rows(f, ctx.source_time(layer)) { return None; } - let inv = ctx.world_matrix(layer).inverse()?; + // (the transform the compositor places the 2D layer with: a 3D parent's matrix projected + // to the comp's plane) + let inv = ctx.layer_to_comp(layer).0.inverse()?; let ys: Vec = [[roi[0], roi[1]], [roi[0] + roi[2], roi[1]], [roi[0], roi[1] + roi[3]], [roi[0] + roi[2], roi[1] + roi[3]]] .iter() - .map(|p| inv.apply(effectcraft_geom::vec3(p[0], p[1], 0.0)).y) + .map(|p| inv.apply(effectcraft_geom::vec2(p[0], p[1])).y) .collect(); let (lo, hi) = ys.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(*y), hi.max(*y))); if !lo.is_finite() || !hi.is_finite() { @@ -1273,8 +1275,7 @@ impl<'a> Renderer<'a> { // pixels are 1/scale footage rows), plus the region's rounding to output pixels: one // output pixel is `k / scale` footage rows, `k` the footage rows per comp pixel. let s = self.opts.scale.max(1e-3); - let k = - [effectcraft_geom::vec3(1.0, 0.0, 0.0), effectcraft_geom::vec3(0.0, 1.0, 0.0)].iter().map(|v| inv.apply_vec(*v).length()).fold(1.0f64, f64::max); + let k = [effectcraft_geom::vec2(1.0, 0.0), effectcraft_geom::vec2(0.0, 1.0)].iter().map(|v| inv.apply_vec(*v).length()).fold(1.0f64, f64::max); if !k.is_finite() { return None; } diff --git a/crates/render/src/tests/footage_size.rs b/crates/render/src/tests/footage_size.rs index 1346609b7..5dd31363a 100644 --- a/crates/render/src/tests/footage_size.rs +++ b/crates/render/src/tests/footage_size.rs @@ -225,6 +225,50 @@ fn a_footage_layer_read_by_rows_is_not_the_shared_picture() { assert!(whole_layer.footage_rows(&ctx, &comp.layers[0], f).is_none(), "whole layer: the whole frame"); } +/// #3750 review: a 2D footage layer under a 3D parent (a null turned 60° about X) is placed by +/// its world matrix projected to the comp's plane, which halves its height: the comp's rows 0..10 +/// show its rows 0..20, and those are read (inverting the unprojected matrix gave rows 0..5). +#[test] +fn rows_under_a_3d_parent_follow_the_projected_layer() { + struct Rows; + impl FootageSource for Rows { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + Clip { sizes: None }.frame(item, f, t) + } + fn frame_rows(&self, item: ItemId, f: &Footage, t: Tick, _: Option<(u32, u32)>, _: crate::FloatCurve, _: (i64, i64)) -> Option> { + Clip { sizes: None }.frame(item, f, t) + } + fn reads_rows(&self, _: &Footage, _: Tick) -> bool { + true + } + } + use effectcraft_keyframe::Value; + let (mut p, cid) = project(BitDepth::Bpc32, false); + let Some(LayerSource::Footage { item }) = p.comp(cid).map(|c| c.layers[0].source.clone()) else { panic!("footage layer") }; + if let Some(ItemKind::Footage(f)) = p.item_mut(item).map(|it| &mut it.kind) { + f.kind = FootageKind::Still; + f.path = "/still.exr".into(); + } + let comp = p.comp(cid).unwrap().clone(); + let mut null = build::layer(&mut p, &comp, "Null", LayerSource::Null, (100, 100), None); + null.switches.three_d = true; + null.props.prop_mut("transform/anchor").unwrap().value = Value::Vec3([0.0, 0.0, 0.0]); + null.props.prop_mut("transform/position").unwrap().value = Value::Vec3([0.0, 0.0, 0.0]); + null.props.prop_mut("transform/rotationX").unwrap().value = Value::Scalar(60.0); + let mut l = comp.layers[0].clone(); + // (the layer's own transform is the identity: its anchor at its position) + l.props.prop_mut("transform/position").unwrap().value = Value::Vec3([48.0, 27.0, 0.0]); + l.props.prop_mut("transform/anchor").unwrap().value = Value::Vec3([48.0, 27.0, 0.0]); + l.parent = Some(null.id); + p.comp_mut(cid).unwrap().layers = vec![l, null].into(); + let comp = p.comp(cid).unwrap(); + let ctx = crate::EvalCtx::new(&p, cid, comp, Tick::ZERO); + let region = Renderer::new(&p, &Rows, RenderOpts { roi: Some([0.0, 0.0, 96.0, 10.0]), ..Default::default() }); + let Some(ItemKind::Footage(f)) = p.item(item).map(|it| &it.kind) else { panic!("footage") }; + let rows = region.footage_rows(&ctx, &comp.layers[0], f).expect("read by rows"); + assert!(rows.0 == 0 && rows.1 >= 20, "rows 0..20 and the warp's reach: {rows:?}"); +} + /// #3271 review: a render's channel reads (an effect's EXR channels) are called off with the /// render like its frame reads: they run under the render's cancel flag (a decode stops between /// batches), and once it is set they don't start.