From 3050ac917ec00e2ba7e4386d0ed3258d6928ed3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 02:47:35 +0300 Subject: [PATCH] wip: transform engine scaffolding --- crates/engine/src/lib.rs | 1 + crates/engine/src/project.rs | 112 +++++++++++++++++ crates/engine/src/scale.rs | 218 +++++++++++++++++++++++++++++++++ crates/engine/src/transform.rs | 81 ++++++++++++ 4 files changed, 412 insertions(+) create mode 100644 crates/engine/src/transform.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3af7024..ed75a72 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,7 @@ pub(crate) mod map; mod sweep; pub(crate) mod stretch; pub mod tonemap; +pub mod transform; pub mod waveform; pub use audio::{ diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index b11442d..5c65de2 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -77,6 +77,7 @@ use crate::map::TimelineMap; use std::path::{Path, PathBuf}; use crate::color::ColorParams; +use crate::transform::TransformParams; use crate::eq::EqParams; use crate::limiter::{Limiter, db_to_linear}; use crate::scale::FitPolicy; @@ -413,6 +414,11 @@ pub struct Clip { /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same /// promises: `Copy`, append-only within a session, never dangling. pub color: Option, + /// Index into the project's transform table + /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a + /// clip that plays at its fit policy's own placement. An index for + /// [`Clip::color`]'s reason and with the same promises. + pub transform: Option, /// How this clip's picture meets a project canvas of another shape /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the /// two above: it is one byte with no parameters, so there is nothing for a @@ -757,6 +763,7 @@ pub type Parts = ( Vec<(LaneKind, Vec)>, Vec, Vec, + Vec, ); /// How many undo steps a project keeps. One gesture is one step, so 100 is past @@ -778,6 +785,8 @@ pub struct Project { eq: Vec, /// The same, for [`Clip::color`]. color: Vec, + /// The same, for [`Clip::transform`]. + transform: Vec, /// Snapshots pushed *before* each successful edit; `undo` pops one. The /// whole lane list, so adding a lane undoes as well. Bounded by /// [`HISTORY_CAP`]: at the cap the oldest step goes. @@ -817,6 +826,7 @@ impl Project { link: Some(0), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -827,6 +837,7 @@ impl Project { lanes: LaneData::two_lanes(vec![clip], vec![clip]), eq: Vec::new(), color: Vec::new(), + transform: Vec::new(), history: Vec::new(), next_link: 1, subtitles: Vec::new(), @@ -857,6 +868,7 @@ impl Project { lanes: Vec<(LaneKind, Vec)>, eq: Vec, color: Vec, + transform: Vec, ) -> crate::Result { if let Some(bad) = eq.iter().position(|p| !finite(p)) { return Err(format!("eq {bad} holds a band that is not a finite number").into()); @@ -864,6 +876,9 @@ impl Project { if let Some(bad) = color.iter().position(|p| !color_finite(p)) { return Err(format!("color {bad} holds a value that is not a finite number").into()); } + if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) { + return Err(format!("transform {bad} holds a value that is not a finite number").into()); + } if lanes.is_empty() { return Err("no lanes at all: that is not a project".into()); } @@ -927,6 +942,15 @@ impl Project { ) .into()); } + if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) { + return Err(format!( + "{name} clip at {} names transform {} of {}", + c.start, + c.transform.unwrap_or_default(), + transform.len() + ) + .into()); + } } if !sorted_disjoint(&data.clips) { return Err(format!("the {name} lane is out of order or overlaps itself").into()); @@ -956,6 +980,7 @@ impl Project { lanes, eq, color, + transform, history: Vec::new(), next_link, subtitles: Vec::new(), @@ -1302,6 +1327,8 @@ impl Project { let mut eq = Vec::new(); let mut moved_color = vec![None; self.color.len()]; let mut color = Vec::new(); + let mut moved_transform = vec![None; self.transform.len()]; + let mut transform = Vec::new(); let mut lanes = self.lanes.clone(); for c in lanes.iter_mut().flat_map(|l| &mut l.clips) { let old = c.source; @@ -1335,6 +1362,17 @@ impl Project { } }); } + if let Some(old) = c.transform.map(usize::from) { + c.transform = Some(match moved_transform[old] { + Some(new) => new, + None => { + transform.push(self.transform[old]); + let new = (transform.len() - 1) as u16; + moved_transform[old] = Some(new); + new + } + }); + } } if sources.is_empty() { sources.extend(self.sources.first().cloned()); @@ -1348,6 +1386,7 @@ impl Project { lanes.into_iter().map(|l| (l.kind, l.clips)).collect(), eq, color, + transform, ) } @@ -2192,6 +2231,71 @@ impl Project { true } + /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit + /// policy's own placement (and for an index that is not there) -- what the + /// renderer and the export ask before they place its picture. + pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> { + self.transform + .get(usize::from(self.lane(lane).get(idx)?.transform?)) + } + + /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo + /// step, `false` (and no history) for an index that is not there or a + /// value that is not finite, and equal settings share a table entry. + pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option) -> bool { + self.write_transform(lane, idx, params, true) + } + + /// [`set_transform`](Self::set_transform) without the undo step, for + /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside + /// one drag on a position/scale/rotate/crop control are one undo, not one + /// per pixel. + pub fn set_transform_live( + &mut self, + lane: Lane, + idx: usize, + params: Option, + ) -> bool { + self.write_transform(lane, idx, params, false) + } + + fn write_transform( + &mut self, + lane: Lane, + idx: usize, + params: Option, + snapshot: bool, + ) -> bool { + if idx >= self.lane(lane).len() { + return false; + } + let slot = match params { + None => None, + Some(params) => { + if !transform_finite(¶ms) { + return false; + } + Some(match self.transform.iter().position(|p| *p == params) { + Some(at) => at as u16, + // corner-cut: the 65535th *distinct* transform of one + // session is refused rather than silently aliased, + // exactly as `write_color` refuses the 65535th grade; + // same upgrade path. + None if self.transform.len() >= usize::from(u16::MAX) => return false, + None => { + self.transform.push(params); + (self.transform.len() - 1) as u16 + } + }) + } + }; + if snapshot { + self.snapshot(); + } + self.lane_mut(lane).expect("checked above")[idx].transform = slot; + true + } + /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an /// index that is not there, which is what every clip starts at anyway. pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed { @@ -2658,6 +2762,14 @@ impl Project { self.color_of(lane, idx) } + /// [`composite_color_at`](Self::composite_color_at)'s twin for + /// [`Clip::transform`]: `None` over a gap and for a clip at its fit + /// policy's own placement. + pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> { + let (lane, idx) = self.composite_clip_at(timeline_frame)?; + self.transform_of(lane, idx) + } + /// How the composite meets the project canvas at `timeline_frame`, so the /// picture playback composes and the one an export encodes are placed from /// one answer. `Fit` over a gap, where black is already the canvas. diff --git a/crates/engine/src/scale.rs b/crates/engine/src/scale.rs index 09732db..16269ae 100644 --- a/crates/engine/src/scale.rs +++ b/crates/engine/src/scale.rs @@ -26,6 +26,8 @@ //! chroma-sample bias that no eye finds and that a siting-aware kernel would fix //! in the same place the Lanczos upgrade goes. +use crate::transform::TransformParams; + /// Limited-range black: what an untouched canvas pixel is. pub const BLACK_Y: u8 = 16; /// Neutral chroma: 128 in both planes. @@ -330,6 +332,130 @@ pub fn compose_i420( } } +/// The source rect [`TransformParams`]'s crop fractions cut out of a `src_w` x +/// `src_h` picture, chroma-grid aligned exactly as [`fit_rect`]'s rects are. +/// Fractions are clamped to `0.0..=0.5` a side, so opposing crops can never +/// meet or cross -- the smallest surviving rect is one chroma sample, for +/// [`align`]'s reason. +pub fn crop_rect(src_w: u32, src_h: u32, t: &TransformParams) -> Rect { + if src_w == 0 || src_h == 0 { + return Rect { x: 0, y: 0, w: 0, h: 0 }; + } + let (cl, cr) = (t.crop_l.clamp(0.0, 0.5), t.crop_r.clamp(0.0, 0.5)); + let (ct, cb) = (t.crop_t.clamp(0.0, 0.5), t.crop_b.clamp(0.0, 0.5)); + let x0 = (f64::from(src_w) * f64::from(cl)).round() as u32; + let x1 = (f64::from(src_w) * (1.0 - f64::from(cr))).round() as u32; + let y0 = (f64::from(src_h) * f64::from(ct)).round() as u32; + let y1 = (f64::from(src_h) * (1.0 - f64::from(cb))).round() as u32; + let (x, w) = align(x0.min(src_w), x1.saturating_sub(x0), src_w); + let (y, h) = align(y0.min(src_h), y1.saturating_sub(y0), src_h); + Rect { x, y, w, h } +} + +/// `dst` -- a placement [`fit_rect`] already worked out -- moved by +/// [`TransformParams::pos_x`]/`pos_y` (canvas fractions, about `dst`'s own +/// centre) and resized by `scale` (about that same centre), clamped onto the +/// canvas and chroma-grid aligned like every other rect here. +/// +/// corner-cut: a placement pushed partway off the canvas is clipped at the +/// edge (what [`compose_i420`] already does to any rect), not wrapped or +/// reflected -- there is no picture to draw once it is entirely off, and +/// [`compose_i420`] already refuses that case by returning without a write. +pub fn transformed_dst_rect(dst: Rect, t: &TransformParams, canvas_w: u32, canvas_h: u32) -> Rect { + if dst.is_empty() || canvas_w == 0 || canvas_h == 0 { + return dst; + } + let scale = if t.scale.is_finite() && t.scale > 0.0 { + f64::from(t.scale) + } else { + 1.0 + }; + let new_w = ((f64::from(dst.w) * scale).round() as i64).clamp(1, i64::from(canvas_w)); + let new_h = ((f64::from(dst.h) * scale).round() as i64).clamp(1, i64::from(canvas_h)); + let pos_x = if t.pos_x.is_finite() { f64::from(t.pos_x) } else { 0.0 }; + let pos_y = if t.pos_y.is_finite() { f64::from(t.pos_y) } else { 0.0 }; + let cx = i64::from(dst.x) + i64::from(dst.w) / 2 + (f64::from(canvas_w) * pos_x).round() as i64; + let cy = i64::from(dst.y) + i64::from(dst.h) / 2 + (f64::from(canvas_h) * pos_y).round() as i64; + let x = (cx - new_w / 2).clamp(0, i64::from(canvas_w)) as u32; + let y = (cy - new_h / 2).clamp(0, i64::from(canvas_h)) as u32; + let (x, w) = align(x, new_w as u32, canvas_w); + let (y, h) = align(y, new_h as u32, canvas_h); + Rect { x, y, w, h } +} + +/// Nearest 90-degree step `degrees` renders at: `0` (0deg), `1` (90deg +/// clockwise), `2` (180deg) or `3` (270deg). Continuous rotation is not +/// rendered at all -- see the [`crate::transform`] module docs -- so this is +/// the one lossy step between what a project *stores* and what a frame +/// *shows*. Non-finite folds to `0`. +pub fn nearest_90_steps(degrees: f32) -> u8 { + if !degrees.is_finite() { + return 0; + } + let norm = degrees.rem_euclid(360.0); + ((norm / 90.0).round() as i64).rem_euclid(4) as u8 +} + +/// Rotates a tightly packed I420 frame by `steps` quarter turns clockwise +/// (`steps % 4`; see [`nearest_90_steps`]). `0` and `2` keep the frame's +/// shape, `1` and `3` swap it -- the chroma planes rotate the same way at +/// their own `(w+1)/2` x `(h+1)/2` size, which stays exact because it is +/// exactly the luma size's, swapped the same way. +pub fn rotate_i420_90s( + y: &[u8], + u: &[u8], + v: &[u8], + w: u32, + h: u32, + steps: u8, +) -> (Vec, Vec, Vec, u32, u32) { + let steps = steps % 4; + if steps == 0 || w == 0 || h == 0 { + return (y.to_vec(), u.to_vec(), v.to_vec(), w, h); + } + let (cw, ch) = chroma_dims(w as usize, h as usize); + let (ry, rw, rh) = rotate_plane(y, w as usize, h as usize, steps); + let (ru, ..) = rotate_plane(u, cw, ch, steps); + let (rv, ..) = rotate_plane(v, cw, ch, steps); + (ry, ru, rv, rw as u32, rh as u32) +} + +/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise. +fn rotate_plane(src: &[u8], w: usize, h: usize, steps: u8) -> (Vec, usize, usize) { + match steps { + 1 => { + let (nw, nh) = (h, w); + let mut out = vec![0u8; nw * nh]; + for yp in 0..nh { + for xp in 0..nw { + out[yp * nw + xp] = src[(h - 1 - xp) * w + yp]; + } + } + (out, nw, nh) + } + 2 => { + let mut out = vec![0u8; w * h]; + for yp in 0..h { + for xp in 0..w { + out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)]; + } + } + (out, w, h) + } + 3 => { + let (nw, nh) = (h, w); + let mut out = vec![0u8; nw * nh]; + for yp in 0..nh { + for xp in 0..nw { + out[yp * nw + xp] = src[xp * w + (w - 1 - yp)]; + } + } + (out, nw, nh) + } + _ => unreachable!("steps % 4 is 1, 2 or 3 here"), + } +} + /// One clip's pictures placed on the project canvas: the geometry, plus the /// buffers it composes into so a frame costs no allocation. /// @@ -485,6 +611,98 @@ impl Composer { compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst); (ky, ku, kv, self.width, self.height) } + + /// [`place`](Self::place) with a per-clip [`TransformParams`] applied on + /// top of the fit policy: the source is cropped to [`crop_rect`], rotated + /// by [`rotate_i420_90s`] to [`nearest_90_steps`] of `t.rotate`, fit to the + /// canvas exactly as an untransformed picture is, and the fitted + /// placement is then moved/resized by [`transformed_dst_rect`]. + /// `t.is_identity()` takes the exact [`place`](Self::place) path. + /// + /// corner-cut: unlike `place`, this always allocates its crop and rotate + /// buffers fresh rather than reusing `self`'s -- the grade path already + /// pays the same per-frame cost for a graded clip + /// ([`crate::decode::Render::frame`]'s `graded` copy), so a transformed + /// clip follows that precedent instead of adding a second steady-state + /// buffer budget. Upgrade path if this shows up in a measurement: give + /// `Composer` its own crop/rotate scratch fields, sized once like `crop` + /// and `scaled` already are. + pub fn place_transformed( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + src_w: u32, + src_h: u32, + t: &TransformParams, + ) -> (Vec, Vec, Vec, u32, u32) { + if t.is_identity() { + let (y, u, v, w, h) = self.place(y, u, v, src_w, src_h); + return (y.to_vec(), u.to_vec(), v.to_vec(), w, h); + } + // A pass-through canvas still has a picture to place a transform on; + // treat it as a canvas the exact size of the incoming picture, so a + // transformed clip at the project's own resolution still crops, + // rotates and moves instead of skipping straight through. + let (canvas_w, canvas_h) = if self.width == 0 || self.height == 0 { + (src_w, src_h) + } else { + (self.width, self.height) + }; + + let crop = crop_rect(src_w, src_h, t); + let mut buf = (Vec::new(), Vec::new(), Vec::new()); + let (cy, cu, cv) = if (crop.w, crop.h) == (src_w, src_h) { + (y, u, v) + } else { + crop_i420(&mut buf, y, u, v, src_w as usize, src_h as usize, crop); + (&buf.0[..], &buf.1[..], &buf.2[..]) + }; + + let steps = nearest_90_steps(t.rotate); + let (ry, ru, rv, rw, rh) = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps); + + let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, self.policy); + let (rw_u, rh_u) = (rw as usize, rh as usize); + let (fy, fu, fv) = if (src.w, src.h) == (rw, rh) { + (&ry[..], &ru[..], &rv[..]) + } else { + crop_i420(&mut buf, &ry, &ru, &rv, rw_u, rh_u, src); + (&buf.0[..], &buf.1[..], &buf.2[..]) + }; + + let dst = transformed_dst_rect(dst, t, canvas_w, canvas_h); + let (sw, sh) = (src.w as usize, src.h as usize); + let (dw, dh) = (dst.w as usize, dst.h as usize); + let mut scaled = (Vec::new(), Vec::new(), Vec::new()); + let (py, pu, pv) = if (sw, sh) == (dw, dh) { + (fy, fu, fv) + } else { + let (ccw, cch) = chroma_dims(dw, dh); + scaled.0.resize(dw * dh, 0); + scaled.1.resize(ccw * cch, 0); + scaled.2.resize(ccw * cch, 0); + scale_i420( + fy, fu, fv, sw, sh, &mut scaled.0, &mut scaled.1, &mut scaled.2, dw, dh, + ); + (&scaled.0[..], &scaled.1[..], &scaled.2[..]) + }; + + let (w, h) = (canvas_w as usize, canvas_h as usize); + let mut canvas = black_i420(w, h); + compose_i420( + &mut canvas.0, + &mut canvas.1, + &mut canvas.2, + w, + h, + py, + pu, + pv, + dst, + ); + (canvas.0, canvas.1, canvas.2, canvas_w, canvas_h) + } } /// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused diff --git a/crates/engine/src/transform.rs b/crates/engine/src/transform.rs new file mode 100644 index 0000000..6f1f1fe --- /dev/null +++ b/crates/engine/src/transform.rs @@ -0,0 +1,81 @@ +//! Per-clip position/scale/rotate/crop, applied engine-side on the placed +//! picture so that playback and export land the same pixel from the same +//! numbers -- [`crate::color::ColorParams`]'s twin in every respect but what +//! it moves: a grade changes what a sample *is*, this changes where it *goes*. +//! +//! Plain data with no invariants of its own: out-of-range or non-finite +//! values are clamped where the geometry is built ([`crate::scale::crop_rect`], +//! [`crate::scale::transformed_dst_rect`]), so a deserializer can hand this +//! over unchecked, exactly as [`ColorParams`](crate::color::ColorParams) can. + +/// One clip's placement on the project canvas, on top of whatever +/// [`crate::scale::FitPolicy`] already does. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct TransformParams { + /// Canvas-fraction offset from centred, positive right. `0.0` is + /// identity. + pub pos_x: f32, + /// Canvas-fraction offset from centred, positive down. `0.0` is identity. + pub pos_y: f32, + /// Multiplier on the fit-policy placement size. `1.0` is identity. + pub scale: f32, + /// Degrees, clockwise. Rendered at the nearest 90-degree step + /// ([`crate::scale::rotate_i420_90s`]); the value itself is kept exactly, + /// so a UI that later grows continuous rotation loses nothing already + /// saved. `0.0` is identity. + pub rotate: f32, + /// Fraction of the source cropped off the left, `0.0..0.5`. + pub crop_l: f32, + /// Fraction of the source cropped off the right, `0.0..0.5`. + pub crop_r: f32, + /// Fraction of the source cropped off the top, `0.0..0.5`. + pub crop_t: f32, + /// Fraction of the source cropped off the bottom, `0.0..0.5`. + pub crop_b: f32, +} + +impl Default for TransformParams { + fn default() -> Self { + Self { + pos_x: 0.0, + pos_y: 0.0, + scale: 1.0, + rotate: 0.0, + crop_l: 0.0, + crop_r: 0.0, + crop_t: 0.0, + crop_b: 0.0, + } + } +} + +impl TransformParams { + /// Whether this is the do-nothing setting. Compared exactly, for + /// [`crate::color::ColorParams::is_identity`]'s reason: only a value that + /// is precisely identity is allowed to skip the geometry. + pub fn is_identity(&self) -> bool { + self.pos_x == 0.0 + && self.pos_y == 0.0 + && self.scale == 1.0 + && self.rotate == 0.0 + && self.crop_l == 0.0 + && self.crop_r == 0.0 + && self.crop_t == 0.0 + && self.crop_b == 0.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_is_identity() { + assert!(TransformParams::default().is_identity()); + assert!(!TransformParams { + pos_x: 0.001, + ..TransformParams::default() + } + .is_identity()); + } +}