diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index a5acefe..bfcec58 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -625,6 +625,7 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -998,6 +999,7 @@ fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() { link: Some(1), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -1631,6 +1633,7 @@ fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { link: None, eq: None, color: None, + transform: None, fit: Default::default(), speed: Default::default(), }; diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs index 4768d88..6e1435d 100644 --- a/crates/app/src/tests/layout.rs +++ b/crates/app/src/tests/layout.rs @@ -811,6 +811,7 @@ fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::Fit, speed: Speed::NORMAL, }; diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs index ec7e696..3e95f4e 100644 --- a/crates/app/src/tests/view.rs +++ b/crates/app/src/tests/view.rs @@ -157,6 +157,7 @@ fn the_marks_are_every_lane_the_playhead_and_the_start() { link, eq: None, color: None, + transform: None, fit: Default::default(), speed: Default::default(), }; diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 887afeb..f0760a8 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -17,6 +17,7 @@ use crate::hw::HwSession; use crate::project::Speed; use crate::scale::Composer; use crate::tonemap::{self, ToneMapper}; +use crate::transform::TransformParams; /// One decoded picture, ready to hand to a renderer. pub struct Frame { @@ -176,6 +177,7 @@ struct SpanCmd { start: u32, end: u32, color: ColorParams, + transform: TransformParams, canvas: Composer, tone: tonemap::Preset, /// The clip's own playback speed ([`crate::project::Clip::speed`]), for @@ -308,6 +310,7 @@ impl Worker { start: u32, end: u32, color: ColorParams, + transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, @@ -331,6 +334,7 @@ impl Worker { start, end, color, + transform, canvas, tone, speed, @@ -433,6 +437,9 @@ impl DecodeSession { start_frame, end_frame, ColorParams::default(), + // No clip, no transform either: the file-level API hands back the + // pictures the file holds, untouched. + TransformParams::default(), // No project, no canvas: the file-level API hands back the // pictures the file holds, at the size it holds them. Composer::passthrough(), @@ -512,6 +519,7 @@ impl DecodeSession { start_frame: u32, len: u32, color: ColorParams, + transform: TransformParams, canvas: Composer, ) -> crate::Result { let still = Still::open(path)?; @@ -538,6 +546,7 @@ impl DecodeSession { // the project is watching. let first = Render::new( color, + transform, ColorDescription::default(), canvas, tonemap::Preset::default(), @@ -610,6 +619,7 @@ impl DecodeSession { start_frame: u32, end_frame: u32, color: ColorParams, + transform: TransformParams, canvas: Composer, tone: tonemap::Preset, ) -> crate::Result<(VideoMeta, FrameStream)> { @@ -650,6 +660,7 @@ impl DecodeSession { start_frame, end_frame, color, + transform, canvas, tone, // A file-level open has no clip and no speed to skip frames @@ -677,6 +688,7 @@ impl DecodeSession { start_frame: u32, end_frame: u32, color: ColorParams, + transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, @@ -687,6 +699,7 @@ impl DecodeSession { start_frame, end_frame, color, + transform, canvas, tone, speed, @@ -710,6 +723,7 @@ fn span_worker( start_frame: u32, end_frame: u32, color: ColorParams, + transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, @@ -740,6 +754,7 @@ fn span_worker( start: start_frame, end: end_frame, color, + transform, canvas, tone, speed, @@ -919,6 +934,7 @@ fn run_span( start, end, color, + transform, canvas, tone, speed, @@ -947,7 +963,7 @@ fn run_span( // The stream's own colour and peak brightness: properties of the stream, so // neither can change while one range decodes -- but the grade, the canvas // and the rendition are the *span's*, so this is built per span. - let mut render = Render::new(color, opened.meta.color, canvas, tone, opened.peak); + let mut render = Render::new(color, transform, opened.meta.color, canvas, tone, opened.peak); if let Some(reused) = opened.position_hw(path, start) { // Cancelled during the init (or the seek): leave without decoding. if abort.hit() { @@ -1007,6 +1023,9 @@ fn run_span( /// project resolution, byte for byte and allocation for allocation. struct Render { color: ColorParams, + /// This clip's placement, on top of whatever the canvas's own fit policy + /// already does ([`crate::scale::Composer::place_transformed`]). + transform: TransformParams, /// What the source's samples mean -- the stream's own matrix and range, /// which is what the conversion below is done in rather than the BT.601 it /// used to assume of every file. @@ -1021,6 +1040,10 @@ struct Render { /// across the worker's whole range. Empty unless the clip needs one: it is /// tone-mapped in place, graded in place, or both. graded: (Vec, Vec, Vec), + /// Where [`Composer::place_transformed`]'s owned picture lands, so a + /// transformed frame's planes live as long as `self` -- matching what + /// [`Composer::place`] already hands back by borrowing `self.canvas`. + placed: (Vec, Vec, Vec), } /// What [`Render::frame`] converts a tone-mapped picture in: the tone map's @@ -1038,6 +1061,7 @@ impl Render { /// reference rendition reads (see [`tonemap::Preset`]). fn new( color: ColorParams, + transform: TransformParams, desc: ColorDescription, canvas: Composer, preset: tonemap::Preset, @@ -1045,6 +1069,7 @@ impl Render { ) -> Self { Self { color, + transform, desc, canvas, // corner-cut: the ceiling is that the map reads limited-range codes @@ -1058,6 +1083,7 @@ impl Render { Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)), }, graded: (Vec::new(), Vec::new(), Vec::new()), + placed: (Vec::new(), Vec::new(), Vec::new()), } } @@ -1071,6 +1097,12 @@ impl Render { height: u32, ) -> Frame { let passthrough = self.canvas.is_passthrough(width, height); + // A transform still has a picture to place even where the canvas + // itself would hand this size back untouched -- moving, scaling, + // rotating or cropping a passthrough-sized clip is still a placement, + // and must not be silently dropped by the fused conversion below. + let transform_active = !self.transform.is_identity(); + let skip_placement = passthrough && !transform_active; // Everything that has to happen to the samples before the canvas sees // them, on one copy: the tone map (HDR streams only) and, unless the // conversion below can fuse it, the grade. An SDR stream that is either @@ -1080,7 +1112,8 @@ impl Render { // picture a viewer is shown, so its brightness and saturation mean what // they say in the SDR the tone map just produced, not in the 10-stop // HDR the file was in. - let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity()) + let (y, u, v, desc) = if self.tone.is_some() + || (!skip_placement && !self.color.is_identity()) { let (gy, gu, gv) = &mut self.graded; gy.clear(); @@ -1104,7 +1137,7 @@ impl Render { } else { (y, u, v, self.desc) }; - if passthrough { + if skip_placement { return Frame { index, width, @@ -1120,7 +1153,15 @@ impl Render { ), }; } - let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height); + let (y, u, v, width, height) = if transform_active { + let (py, pu, pv, w, h) = self + .canvas + .place_transformed(y, u, v, width, height, &self.transform); + self.placed = (py, pu, pv); + (&self.placed.0[..], &self.placed.1[..], &self.placed.2[..], w, h) + } else { + self.canvas.place(y, u, v, width, height) + }; Frame { index, width, @@ -1384,6 +1425,7 @@ mod tests { 0, u32::MAX, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), Speed::NORMAL, @@ -1405,6 +1447,7 @@ mod tests { 0, u32::MAX, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), ) @@ -1453,6 +1496,7 @@ mod tests { 0, u32::MAX, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), Speed::NORMAL, @@ -1536,6 +1580,7 @@ mod tests { 0, u32::MAX, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), ) diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 1edc073..37ef4de 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -16,9 +16,10 @@ //! subtitle 3 test_av.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk //! color 0.1:1.2:0.9:-0.3 -//! video 1 0 0 120 0 0 0 0 fit 1000 0 0 -//! audio 1 0 0 120 0 0 0 - fit 1000 30 30 -//! video 2 120 0 120 1 - - - fill 2000 0 0 +//! transform 0.1:-0.1:1.5:90.0:0.0:0.0:0.0:0.0 +//! video 1 0 0 120 0 0 0 0 fit 1000 0 0 0 - +//! audio 1 0 0 120 0 0 0 - fit 1000 30 30 0 - +//! video 2 120 0 120 1 - - - fill 2000 0 0 0 0 //! audio 2 //! sub 1 0 60 0 500000 1500000 //! sub 2 @@ -109,8 +110,16 @@ //! ([`crate::color::ColorParams`]), named by position exactly as an eq line is //! -- the first colour line is color 0 -- printed and refused by the same rules. //! +//! A transform line is `transform ::::: +//! ::` ([`crate::transform::TransformParams`]), named by +//! position exactly as an eq or a colour line is -- the first transform line is +//! transform 0 -- printed and refused by the same rules: how a clip's picture +//! sits, is sized, is turned and is trimmed on the canvas, on top of whatever +//! its fit policy already placed. +//! //! A lane line is ` -//! `: which lane the clip is on -- its kind and its 1-based number +//! `: +//! which lane the clip is on -- its kind and its 1-based number //! among the lanes of that kind, the [`crate::project::Lane::label`] a header //! column shows -- then where the clip sits on the timeline, the half-open //! source range it plays, the file it plays from, its group id, the eq line it @@ -120,9 +129,12 @@ //! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip //! nobody has speeded), and finally its ramp up from silence and ramp down to //! it, in timeline frames ([`crate::project::Clip::fade_in`], -//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded), and -//! finally its cross-dissolve into whatever abuts its end -//! ([`crate::project::Clip::transition_out`], `0` for a hard cut). +//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded), its +//! cross-dissolve into whatever abuts its end +//! ([`crate::project::Clip::transition_out`], `0` for a hard cut), and last of +//! all the transform line it is placed, sized, turned and cropped by, on top +//! of everything its fit policy already did (`-` for a clip left at its fit +//! policy's own spot, [`crate::project::Clip::transform`]). //! Timeline placement is //! explicit, so a *gap* is simply a stretch no line covers -- there is nothing //! to write for one, and nothing that can disagree about its length. The `` @@ -148,7 +160,11 @@ //! track 3 of a two-track palette is refused here, as a clip naming a source //! that is not there is. //! -//! **Version 17** was this without the clip's two fade fields: such a project +//! **Version 19** was this without the clip's transform field: such a project +//! places no clip anywhere but its fit policy's own spot, which is what `-` +//! still means. **Version 18** was that without the clip's transition field: +//! such a project dissolves no clip into its neighbor, which is what `0` still +//! means. **Version 17** was this without the clip's two fade fields: such a project //! holds no clip anyone has faded, which is what a `0 0` pair still means. //! **Version 15** was this without the caption's group field: such a project //! holds captions no hand ever grouped, which is every caption there could be. @@ -187,7 +203,7 @@ //! nothing, and an older one plays everything at real time, and an older one //! mixes flat, and an older one shows no subtitles, and an older one is shown //! in the reference rendition, and an older one places none of the words it -//! names -- and saving any of them writes v18. An older +//! names -- and saving any of them writes v20. An older //! reader refuses a newer file by name. //! //! Text because an edit list is a few integers and a path, and a path is @@ -220,10 +236,12 @@ use crate::limiter::Limiter; use crate::project::{Clip, Lane, LaneKind, Source, Speed, SubClip}; use crate::scale::FitPolicy; use crate::subtitle::SubtitleTrack; +use crate::transform::TransformParams; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 19"; +const MAGIC: &[u8] = b"edith 20"; +const MAGIC_V19: &[u8] = b"edith 19"; const MAGIC_V18: &[u8] = b"edith 18"; const MAGIC_V17: &[u8] = b"edith 17"; const MAGIC_V16: &[u8] = b"edith 16"; @@ -265,6 +283,9 @@ pub struct Document { /// The colour table [`Clip::color`] indexes into, in file order. Empty for /// every dialect before v6. pub color: Vec, + /// The transform table [`Clip::transform`] indexes into, in file order. + /// Empty for every dialect before v20. + pub transform: Vec, /// The project's own picture size. `None` for every dialect before v7 and /// for a v7 file that leaves it out, which both mean "source 0's picture". pub resolution: Option<(u32, u32)>, @@ -333,6 +354,7 @@ pub fn save( subtitles: &[SubtitleTrack], eq: &[EqParams], color: &[ColorParams], + transform: &[TransformParams], resolution: (u32, u32), fps: Option, tone: crate::tonemap::Preset, @@ -354,8 +376,8 @@ pub fn save( let result = std::fs::File::create(&part) .and_then(|mut f| { f.write_all(&emit( - &dir, sources, lanes, gains, subs, subtitles, eq, color, resolution, fps, tone, - proxy, auto_proxy, encoder, limiter, sample_rate, playhead, + &dir, sources, lanes, gains, subs, subtitles, eq, color, transform, resolution, + fps, tone, proxy, auto_proxy, encoder, limiter, sample_rate, playhead, ))?; f.sync_all() }) @@ -396,6 +418,7 @@ fn emit( subtitles: &[SubtitleTrack], eq: &[EqParams], color: &[ColorParams], + transform: &[TransformParams], resolution: (u32, u32), fps: Option, tone: crate::tonemap::Preset, @@ -504,6 +527,16 @@ fn emit( .as_bytes(), ); } + // ...and the transform table, for the same reason and by the same rules. + for p in transform { + out.extend_from_slice( + format!( + "transform {:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}\n", + p.pos_x, p.pos_y, p.scale, p.rotate, p.crop_l, p.crop_r, p.crop_t, p.crop_b + ) + .as_bytes(), + ); + } // Lane by lane rather than interleaved by time: a lane reads as a list, the // parser gets its sortedness check for free from the order it is in, and // the lanes come back out in the order they are displayed in. @@ -556,9 +589,10 @@ fn emit( let link = c.link.map_or("-".to_string(), |l| l.to_string()); let eq = c.eq.map_or("-".to_string(), |e| e.to_string()); let color = c.color.map_or("-".to_string(), |e| e.to_string()); + let transform = c.transform.map_or("-".to_string(), |e| e.to_string()); out.extend_from_slice( format!( - "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {} {} {} {}\n", + "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {} {} {} {} {transform}\n", c.start, c.in_frame, c.out_frame, @@ -610,8 +644,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries a per-clip cross-dissolve into its successor... - let v19 = first == MAGIC; + // The one that carries a per-clip transform (position/scale/rotate/crop)... + let v20 = first == MAGIC; + // ...the one that carries a per-clip cross-dissolve into its successor... + let v19 = v20 || first == MAGIC_V19; // ...the one that carries a per-clip fade envelope... let v18 = v19 || first == MAGIC_V18; // ...the one that carries an explicit sound rate... @@ -668,6 +704,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // Nothing before v5 equalizes anything, and nothing before v6 grades. eq: Vec::new(), color: Vec::new(), + // Nothing before v20 places any clip anywhere but its fit policy's own + // spot: the identity transform is what leaving a clip's index out + // still means. + transform: Vec::new(), // Nothing before v7 has a resolution of its own: source 0's picture is // what those projects were, and `None` is how the loader is told so. resolution: None, @@ -972,6 +1012,30 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { tint: float(parts[3], n)?, }); } + b"transform" if v20 => { + if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { + return Err(format!("line {n}: transform after a clip").into()); + } + let f = fields(rest, 1, "transform", n)?; + let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect(); + if parts.len() != 8 { + return Err(format!( + "line {n}: transform wants 8 fields, found {}", + parts.len() + ) + .into()); + } + doc.transform.push(TransformParams { + pos_x: float(parts[0], n)?, + pos_y: float(parts[1], n)?, + scale: float(parts[2], n)?, + rotate: float(parts[3], n)?, + crop_l: float(parts[4], n)?, + crop_r: float(parts[5], n)?, + crop_t: float(parts[6], n)?, + crop_b: float(parts[7], n)?, + }); + } // v1: one lane, no placement, no groups. Every clip becomes one // grouped video+audio pair laid where the queue reached, which is // what the file always meant. @@ -989,6 +1053,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { link: Some(doc.lanes[0].1.len() as u32), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }, @@ -1100,16 +1165,18 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { if numbered && rest.is_empty() { continue; } - // v18 grew the two fade fields, v19 the transition one, v8 - // the speed one, v7 the fit one, v6 the colour one and v5 the - // eq one; every older dialect ends at the link. + // v20 grew the transform field, v18 the two fade fields, v19 + // the transition one, v8 the speed one, v7 the fit one, v6 + // the colour one and v5 the eq one; every older dialect ends + // at the link. let want = 5 + usize::from(v5) + usize::from(v6) + usize::from(v7) + usize::from(v8) + 2 * usize::from(v18) - + usize::from(v19); + + usize::from(v19) + + usize::from(v20); let f = fields(rest, want, "clip", n)?; let in_frame = number(f[1], n)?; let out_frame = number(f[2], n)?; @@ -1134,6 +1201,12 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { }, eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?, color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?, + transform: table_index( + f.get(12).copied(), + doc.transform.len(), + "transform", + n, + )?, fit: fit_policy(f.get(7).copied(), n)?, speed, }, @@ -1462,6 +1535,7 @@ mod tests { &[], eq, color, + &[], resolution, None, crate::tonemap::Preset::default(), @@ -1510,6 +1584,7 @@ mod tests { &tracks, &[], &[], + &[], (1280, 720), None, crate::tonemap::Preset::default(), @@ -1545,7 +1620,7 @@ mod tests { video 1 0 0 30 0 - - - fit 1000\n"; let old = parse(v9, &dir).expect("v9 still loads"); assert_eq!(old.subtitles, Vec::new()); - assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 19\n")); + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 20\n")); // ...and the line itself is not a v9 line: a dialect may not be mixed. let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) .unwrap_err() @@ -1591,6 +1666,7 @@ mod tests { &[subtitle("/proj/subs.srt", None)], &[], &[], + &[], (1280, 720), None, crate::tonemap::Preset::default(), @@ -1643,6 +1719,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, crate::tonemap::Preset::default(), @@ -1707,6 +1784,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, crate::tonemap::Preset::default(), @@ -1773,6 +1851,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, crate::tonemap::Preset::default(), @@ -1846,6 +1925,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, crate::tonemap::Preset::default(), @@ -1912,6 +1992,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, preset, @@ -1965,6 +2046,7 @@ mod tests { link, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, } @@ -2016,10 +2098,10 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 20\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000 0 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0\n\ - audio 1 0 0 30 0 0 - - fit 1000 0 0 0\n", + video 1 0 0 30 0 0 - - fit 1000 0 0 0 -\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0 -\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0 0 -\n", "the file under the project directory is written relative to it, \ each with the audio stream it plays" ); @@ -2053,9 +2135,9 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 4 - - fit 1000 0 0 0\naudio 1\n\ - video 2 40 0 10 0 - - - fit 1000 0 0 0\naudio 2 0 0 30 0 4 - - fit 1000 0 0 0\n", + "edith 20\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 4 - - fit 1000 0 0 0 -\naudio 1\n\ + video 2 40 0 10 0 - - - fit 1000 0 0 0 -\naudio 2 0 0 30 0 4 - - fit 1000 0 0 0 -\n", "an empty lane is a line of its own; everything else is its clips" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2173,12 +2255,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 20\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ - video 1 0 0 30 0 0 0 - fit 1000 0 0 0\nvideo 1 30 10 20 0 - 1 - fit 1000 0 0 0\n\ - audio 1 0 0 30 0 0 0 - fit 1000 0 0 0\naudio 1 30 0 10 0 - 2 - fit 1000 0 0 0\n", + video 1 0 0 30 0 0 0 - fit 1000 0 0 0 -\nvideo 1 30 10 20 0 - 1 - fit 1000 0 0 0 -\n\ + audio 1 0 0 30 0 0 0 - fit 1000 0 0 0 -\naudio 1 30 0 10 0 - 2 - fit 1000 0 0 0 -\n", "the table comes before the clips, and a clip names a line of it" ); @@ -2289,12 +2371,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 20\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ - video 1 0 0 30 0 0 - 0 fit 1000 0 0 0\nvideo 1 30 10 20 0 - - 1 fit 1000 0 0 0\n\ - audio 1 0 0 30 0 0 - 0 fit 1000 0 0 0\naudio 1 30 0 10 0 - - 2 fit 1000 0 0 0\n", + video 1 0 0 30 0 0 - 0 fit 1000 0 0 0 -\nvideo 1 30 10 20 0 - - 1 fit 1000 0 0 0 -\n\ + audio 1 0 0 30 0 0 - 0 fit 1000 0 0 0 -\naudio 1 30 0 10 0 - - 2 fit 1000 0 0 0 -\n", "the table comes before the clips, and a clip names a line of it" ); @@ -2354,9 +2436,9 @@ mod tests { (1280, 720), old.playhead )), - "edith 19\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 20\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ - video 1 0 0 30 0 0 0 - fit 1000 0 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0\n" + video 1 0 0 30 0 0 0 - fit 1000 0 0 0 -\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0 -\n" ); } @@ -2379,6 +2461,7 @@ mod tests { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::from_permille(permille), }; @@ -2395,9 +2478,9 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 2000 0 0 0\nvideo 1 15 30 40 0 - - - fit 250 0 0 0\n\ - audio 1 0 0 30 0 - - - fit 2000 0 0 0\n", + "edith 20\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 2000 0 0 0 -\nvideo 1 15 30 40 0 - - - fit 250 0 0 0 -\n\ + audio 1 0 0 30 0 - - - fit 2000 0 0 0 -\n", "the rate is the clip line's last field, in thousandths" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2424,8 +2507,8 @@ mod tests { (1280, 720), old.playhead )), - "edith 19\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000 0 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0\n" + "edith 20\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 0 - - fit 1000 0 0 0 -\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0 -\n" ); // A rate outside what the editor can set is a corrupt line, by name. let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n"; @@ -2465,6 +2548,7 @@ mod tests { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -2472,8 +2556,8 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000 5 7 0\n", + "edith 20\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 5 7 0 -\n", "the fades are the clip line's last two fields" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2515,6 +2599,7 @@ mod tests { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -2522,8 +2607,8 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000 0 0 9\n", + "edith 20\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 9 -\n", "the dissolve is the clip line's own last field" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2533,6 +2618,164 @@ mod tests { ); } + /// A v19 file is a v20 one that places no clip anywhere but its fit + /// policy's own spot: it loads with every clip's [`Clip::transform`] at + /// `None`, which is what a v19 file's missing field still means. + #[test] + fn a_v19_file_loads_untransformed() { + let dir = PathBuf::from("/proj"); + // The v19 dialect: twelve clip fields, the last the transition -- no + // transform field after it at all, not even a `-`. + let v19 = b"edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n"; + let old = parse(v19, &dir).expect("v19 parses"); + assert!(old.transform.is_empty(), "nothing before v20 has a table"); + assert!( + old.lanes + .iter() + .flat_map(|(_, clips)| clips) + .all(|c| c.transform.is_none()), + "nothing before v20 had a placement to name" + ); + } + + /// [`colours_round_trip_bit_exactly_and_are_shared`]'s twin: two clips + /// sharing one transform table entry write it once, and both bytes and + /// values come back bit-exact. + #[test] + fn transforms_round_trip_bit_exactly_and_are_shared() { + let dir = PathBuf::from("/proj"); + let sources = vec![source("/proj/a.mp4", 0)]; + let transform = vec![ + TransformParams { + pos_x: 0.1, + pos_y: -0.2, + scale: 1.5, + rotate: 90.0, + crop_l: 0.1, + crop_r: 0.0, + crop_t: 0.0, + crop_b: 0.05, + }, + // The awkward ones again: all 24 mantissa bits, an exponential + // spelling, a subnormal and a negative zero -- and the identity, + // which is a setting like any other. + TransformParams { + pos_x: -0.000_000_1, + pos_y: 16_777_215.0, + scale: f32::MIN_POSITIVE / 3.0, + rotate: -0.0, + crop_l: 0.0, + crop_r: 0.0, + crop_t: 0.0, + crop_b: 0.0, + }, + TransformParams::default(), + ]; + // Two clips share entry 0, so it is written once; one clip is untransformed. + let lanes = two( + vec![ + Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, + transform: Some(0), + fit: FitPolicy::default(), + speed: Speed::NORMAL, + ..clip(0, 0, 30, 0, Some(0)) + }, + Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, + transform: Some(1), + fit: FitPolicy::default(), + speed: Speed::NORMAL, + ..clip(30, 10, 20, 0, None) + }, + ], + vec![ + Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, + transform: Some(0), + fit: FitPolicy::default(), + speed: Speed::NORMAL, + ..clip(0, 0, 30, 0, Some(0)) + }, + Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, + transform: Some(2), + fit: FitPolicy::default(), + speed: Speed::NORMAL, + ..clip(30, 0, 10, 0, None) + }, + ], + ); + let bytes = super::emit( + &dir, + &sources, + &lanes, + &[], + &[], + &[], + &[], + &[], + &transform, + (1280, 720), + None, + crate::tonemap::Preset::default(), + false, + true, + crate::export::EncoderSeat::default(), + Limiter::default(), + None, + 0, + ); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 20\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + transform 0.1:-0.2:1.5:90.0:0.1:0.0:0.0:0.05\n\ + transform -1e-7:16777215.0:3.918315e-39:-0.0:0.0:0.0:0.0:0.0\n\ + transform 0.0:0.0:1.0:0.0:0.0:0.0:0.0:0.0\n\ + video 1 0 0 30 0 0 - - fit 1000 0 0 0 0\nvideo 1 30 10 20 0 - - - fit 1000 0 0 0 1\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0 0 0\naudio 1 30 0 10 0 - - - fit 1000 0 0 0 2\n", + "the table comes before the clips, and a clip names a line of it" + ); + + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.lanes, lanes, "every clip keeps the transform it named"); + for (i, (got, want)) in back.transform.iter().zip(&transform).enumerate() { + assert_eq!( + ( + got.pos_x.to_bits(), + got.pos_y.to_bits(), + got.scale.to_bits(), + got.rotate.to_bits(), + got.crop_l.to_bits(), + got.crop_r.to_bits(), + got.crop_t.to_bits(), + got.crop_b.to_bits(), + ), + ( + want.pos_x.to_bits(), + want.pos_y.to_bits(), + want.scale.to_bits(), + want.rotate.to_bits(), + want.crop_l.to_bits(), + want.crop_r.to_bits(), + want.crop_t.to_bits(), + want.crop_b.to_bits(), + ), + "transform {i} came back as other bits" + ); + } + assert_eq!(back.transform.len(), 3); + } + /// The whole of the v9 bump, the speed test's twin: the mix a project was /// left at -- every track's own volume and the master limiter -- plus the /// rate it was cut at, all written, all read back as the very numbers, and @@ -2561,6 +2804,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), Some(23.976023976023978), crate::tonemap::Preset::default(), @@ -2573,10 +2817,10 @@ mod tests { ); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + "edith 20\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ limiter -1.5 on\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n\ - audio 2 0 0 30 0 - - - fit 1000 0 0 0\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0 -\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 -\n\ + audio 2 0 0 30 0 - - - fit 1000 0 0 0 -\n\ gain audio 1 3.0\ngain audio 2 -6.5\n", "the mix is lines of its own, the gains after the lanes they name" ); @@ -2605,8 +2849,8 @@ mod tests { (1280, 720), old.playhead )), - "edith 19\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n" + "edith 20\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0 -\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 -\n" ); // Each of the three refuses by name, on its own line. @@ -2769,10 +3013,10 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 19\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 20\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000 0 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0\n\ - audio 1 0 0 30 0 0 - - fit 1000 0 0 0\n" + video 1 0 0 30 0 0 - - fit 1000 0 0 0 -\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0 -\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0 0 -\n" ); // An empty lane's line is still the whole of that lane, eq or no eq. let empty = parse( @@ -2822,10 +3066,10 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 19\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 20\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000 0 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0\n\ - audio 1 0 0 30 0 0 - - fit 1000 0 0 0\n", + video 1 0 0 30 0 0 - - fit 1000 0 0 0 -\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0 -\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0 0 -\n", "a re-saved v2 project differs only by its version, the lane \ numbers, the streams it always meant and an equalizer it has none of" ); @@ -2854,7 +3098,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 19\n")); + assert!(v5.starts_with(b"edith 20\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -2950,6 +3194,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, crate::tonemap::Preset::default(), @@ -2964,8 +3209,8 @@ mod tests { let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 19\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n" + "edith 20\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0 -\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 -\n" ); // Loading rejoins the *given* directory, so the file is reached by the // way the project was opened -- the same file, through the link, still @@ -3009,10 +3254,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 20\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 21\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 20"); + assert_eq!(err, "line 1: unsupported version 21"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index ca8b1aa..0d93514 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -82,6 +82,7 @@ use crate::project::{Lane, LaneKind, Project, Rate}; use crate::scale::{blend_i420, Composer}; use crate::subtitle::{Cue, SubtitleTrack}; use crate::tonemap::{self, ToneMapper}; +use crate::transform::TransformParams; /// Progress is reported in permille: an atomic integer the render loop can read /// without a lock, fine enough for any progress bar. @@ -1098,8 +1099,10 @@ struct Dissolve<'a> { mapper: Option<&'a ToneMapper>, remap: Option<(Matrix, Matrix)>, grade: Option, + transform: TransformParams, canvas: Composer, graded: (Vec, Vec, Vec), + transformed: (Vec, Vec, Vec), } /// The track's cues where the *exported* timeline puts them, which is the only @@ -1658,6 +1661,14 @@ impl CopyPlan { { return None; } + // A moved, scaled, rotated or cropped clip is a different picture + // than the source's own packets, exactly as a grade is. + if project + .composite_transform_at(span.start) + .is_some_and(|params| !params.is_identity()) + { + return None; + } let path = &entries.get(source)?.path; if sources.get(source)?.is_none() { if !crate::demux::is_matroska(path) { @@ -2553,6 +2564,9 @@ fn run( && project .composite_color_at(span.start) .is_none_or(|params| params.is_identity()) + && project + .composite_transform_at(span.start) + .is_none_or(|params| params.is_identity()) && dissolve.is_none(); let want = untouched.then(|| encoder.dma_want(meta)).flatten(); // Opened at the file's own frame, which is the only place the @@ -2582,7 +2596,12 @@ fn run( // is touched. Scratch outside the frame loop: it is refilled per frame // and its allocation survives the whole span. let grade = project.composite_color_at(span.start).copied(); + let transform = project + .composite_transform_at(span.start) + .copied() + .unwrap_or_default(); let mut graded = (Vec::new(), Vec::new(), Vec::new()); + let mut transformed = (Vec::new(), Vec::new(), Vec::new()); // ...and the canvas it is placed on, which is where a source of another // resolution becomes a picture at the project's. The same `Composer` // playback composes with, given the same policy, so an export is what @@ -2611,12 +2630,17 @@ fn run( mapper: b_mapper, remap: b_remap, grade: project.composite_color_at(b_start).copied(), + transform: project + .composite_transform_at(b_start) + .copied() + .unwrap_or_default(), canvas: Composer::new( meta.width, meta.height, project.composite_fit_at(b_start), ), graded: (Vec::new(), Vec::new(), Vec::new()), + transformed: (Vec::new(), Vec::new(), Vec::new()), }) }) .transpose()?; @@ -2704,9 +2728,11 @@ fn run( width, height, grade, + transform, remap, mapper, &mut graded, + &mut transformed, &mut canvas, )), }; @@ -2734,8 +2760,9 @@ fn run( } Some(Frame::Pixels(by, bu, bv, bw, bh)) => { let (by, bu, bv, _, _) = place_picture( - by, bu, bv, bw, bh, d.grade, d.remap, d.mapper, - &mut d.graded, &mut d.canvas, + by, bu, bv, bw, bh, d.grade, d.transform, d.remap, + d.mapper, &mut d.graded, &mut d.transformed, + &mut d.canvas, ); let idx_in_window = done_here + r - d.tail_start; let t = dissolve_weight(idx_in_window, d.window); @@ -2870,9 +2897,11 @@ fn place_picture<'a>( width: u32, height: u32, grade: Option, + transform: TransformParams, remap: Option<(Matrix, Matrix)>, mapper: Option<&ToneMapper>, graded: &'a mut (Vec, Vec, Vec), + transformed: &'a mut (Vec, Vec, Vec), canvas: &'a mut Composer, ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { // The planes are borrowed from the decoder (and `Black::picture` hands the @@ -2907,7 +2936,13 @@ fn place_picture<'a>( }; // Grade first, place second: the grade is the clip's own pixels and the // bars around them are not the clip (see `scale::Composer`). - canvas.place(y, u, v, width, height) + if transform.is_identity() { + canvas.place(y, u, v, width, height) + } else { + let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform); + *transformed = (py, pu, pv); + (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h) + } } /// Which matrix pair a span's samples are rewritten by on the way into a file 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/playback.rs b/crates/engine/src/playback.rs index 653bfec..bbf43e1 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -28,6 +28,7 @@ use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip}; use crate::scale::{Composer, FitPolicy}; +use crate::transform::TransformParams; /// How long the feeder waits out a full ring. The ring holds a second, so this /// only has to be short next to that; it costs one wakeup per 10 ms of audio. @@ -553,6 +554,7 @@ impl PlaybackSession { 0, u32::MAX, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), // The default rendition: a file just opened is a project nobody has // picked one for, exactly as it is a project nobody has graded. @@ -624,6 +626,7 @@ impl PlaybackSession { vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())], Vec::new(), Vec::new(), + Vec::new(), )?; // Onto the emptied mapping: black picture, silence, zero duration. session.seek(0.); @@ -672,6 +675,7 @@ impl PlaybackSession { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -680,6 +684,7 @@ impl PlaybackSession { vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])], Vec::new(), Vec::new(), + Vec::new(), )?; // Every frame of this timeline is a gap, since no video lane covers // anything: `composite_span_at` says so and the black worker @@ -759,6 +764,7 @@ impl PlaybackSession { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -769,6 +775,7 @@ impl PlaybackSession { vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())], Vec::new(), Vec::new(), + Vec::new(), )?; let span = project.composite_span_at(0); // The placeholder the first seek supersedes, opened here for `open`'s @@ -778,6 +785,7 @@ impl PlaybackSession { 0, span.map_or(1, |s| s.len), ColorParams::default(), + TransformParams::default(), Composer::passthrough(), )?; Ok(Self { @@ -911,6 +919,7 @@ impl PlaybackSession { 0, 1, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), )?; (meta, stream) @@ -920,6 +929,7 @@ impl PlaybackSession { 0, u32::MAX, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), // The saved rendition, from the document rather than from the // project (which is built below): this placeholder is what the @@ -1060,7 +1070,8 @@ impl PlaybackSession { // whole to reach one track: a film whose project names many of its // tracks is one walk here rather than one per row. let subtitles = crate::subtitle::open_all(&doc.subtitles); - let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? + let project = + Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)? .with_mix(&doc.gains, doc.limiter) .with_tone(doc.tone) // The palette before what is placed on it: a caption names a row of @@ -1353,7 +1364,7 @@ impl PlaybackSession { if self.project.sources().is_empty() { return Err("this project names no file: there is nothing to save".into()); } - let (sources, lanes, eq, color) = self.project.without_orphan_sources(); + let (sources, lanes, eq, color, transform) = self.project.without_orphan_sources(); let playhead = secs_to_frame(self.now(), self.meta.frame_rate) .min(self.project.timeline_frames().saturating_sub(1)); crate::edith::save( @@ -1373,6 +1384,7 @@ impl PlaybackSession { self.project.subtitles(), &eq, &color, + &transform, (self.meta.width, self.meta.height), // ...and the rate it was cut at, which nothing else in the file // says: a timeline of stills and songs used to come back at @@ -1697,6 +1709,10 @@ impl PlaybackSession { .composite_color_at(start) .copied() .unwrap_or_default(), + self.project + .composite_transform_at(start) + .copied() + .unwrap_or_default(), Composer::new( self.meta.width, self.meta.height, @@ -1740,6 +1756,11 @@ impl PlaybackSession { .composite_color_at(start) .copied() .unwrap_or_default(); + let transform = self + .project + .composite_transform_at(start) + .copied() + .unwrap_or_default(); // ...and the canvas it is placed on: the project's resolution // and this clip's own fit policy, constant across the span for // the reason the grade is. Built where it is handed over rather @@ -1778,6 +1799,7 @@ impl PlaybackSession { start_frame, end_frame, color, + transform, canvas(), tone, decode_speed, @@ -1792,6 +1814,7 @@ impl PlaybackSession { start_frame, end_frame, color, + transform, canvas(), tone, decode_speed, @@ -2839,6 +2862,7 @@ impl PlaybackSession { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -3721,6 +3745,7 @@ fn matches_timeline( 0, 0, ColorParams::default(), + TransformParams::default(), Composer::passthrough(), // A zero-length range decodes nothing, so no table is built and the // rendition cannot matter here. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 2464391..1b57300 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 @@ -856,6 +862,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 @@ -877,6 +884,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. @@ -923,6 +932,7 @@ impl Project { link: Some(0), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -933,6 +943,7 @@ impl Project { lanes: LaneData::two_lanes(vec![clip], vec![clip]), eq: Vec::new(), color: Vec::new(), + transform: Vec::new(), history: Vec::new(), redo: Vec::new(), next_link: 1, @@ -964,6 +975,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()); @@ -971,6 +983,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()); } @@ -1034,6 +1049,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()); @@ -1063,6 +1087,7 @@ impl Project { lanes, eq, color, + transform, history: Vec::new(), redo: Vec::new(), next_link, @@ -1306,6 +1331,7 @@ impl Project { link: Some(self.new_link()), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -1413,6 +1439,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; @@ -1446,6 +1474,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()); @@ -1459,6 +1498,7 @@ impl Project { lanes.into_iter().map(|l| (l.kind, l.clips)).collect(), eq, color, + transform, ) } @@ -2303,6 +2343,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 { @@ -2870,6 +2975,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. @@ -4504,6 +4617,7 @@ impl Project { lanes: self.lanes.clone(), eq: self.eq.clone(), color: self.color.clone(), + transform: self.transform.clone(), history: Vec::new(), redo: Vec::new(), next_link: self.next_link, @@ -4845,6 +4959,20 @@ fn color_finite(p: &ColorParams) -> bool { && p.tint.is_finite() } +/// The same for a transform: [`crate::scale`] clamps a non-finite value to +/// identity at read time, but a value that cannot round-trip has no business +/// reaching the model. +fn transform_finite(p: &TransformParams) -> bool { + p.pos_x.is_finite() + && p.pos_y.is_finite() + && p.scale.is_finite() + && p.rotate.is_finite() + && p.crop_l.is_finite() + && p.crop_r.is_finite() + && p.crop_t.is_finite() + && p.crop_b.is_finite() +} + fn sorted_disjoint(clips: &[Clip]) -> bool { clips.iter().all(|c| c.out_frame > c.in_frame) && clips.windows(2).all(|w| w[0].end() <= w[1].start) @@ -5197,6 +5325,7 @@ mod tests { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, } @@ -5224,6 +5353,15 @@ mod tests { } } + /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s + /// twin for the transform table. + fn transform_at(n: u32) -> TransformParams { + TransformParams { + pos_x: f64::from(n) as f32 * 0.05, + ..Default::default() + } + } + /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`]. fn two(video: Vec, audio: Vec) -> Vec<(LaneKind, Vec)> { vec![(LaneKind::Video, video), (LaneKind::Audio, audio)] @@ -6642,6 +6780,9 @@ mod tests { /// 52 bytes of fields, but the struct's own alignment is 8 (from the /// `usize` source and the 8-byte `Option` link), so an odd number of /// words after it pads out to the next multiple of 8: 56 bytes total. + /// The transform index is a third `Option`, same reason as the eq and + /// colour ones before it -- it lands in bytes already spent on padding, so + /// the struct still costs 56. /// This is the assert that says so: a clip that grows a word grows every /// undo snapshot and every clipboard copy with it. #[test] @@ -6667,6 +6808,7 @@ mod tests { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::Fit, speed: Speed::NORMAL, }; @@ -6775,6 +6917,7 @@ mod tests { two(vec![c], vec![c]), Vec::new(), Vec::new(), + Vec::new(), ) .expect("valid parts") }; @@ -6913,9 +7056,9 @@ mod tests { // A saved-and-loaded empty timeline is a project like any other, and it // still names the file its frame rate came from. assert!(p.lift(Lane::V1, 0)); - let (sources, lanes, eq, color) = p.without_orphan_sources(); + let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline"); - let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads"); + let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads"); assert_eq!(back.timeline_frames(), 0); assert_eq!(back.lanes().len(), 2, "and it kept its lanes"); } @@ -7089,7 +7232,7 @@ mod tests { (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]), (LaneKind::Audio, vec![clip(0, 0, 3, 0)]), ]; - let mut p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts"); + let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts"); let before = shape(&p); // Into the gap, exactly where it was let go -- nothing else moves. @@ -7652,7 +7795,7 @@ mod tests { // Import a second file, undo it: source 1 is now an orphan. let mut p = two_sources(); assert!(p.undo()); - let (sources, lanes, eq, color) = p.without_orphan_sources(); + let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone"); assert!(eq.is_empty(), "and a project with no equalizer writes none"); assert!(color.is_empty(), "nor a colour it never graded with"); @@ -7668,7 +7811,7 @@ mod tests { assert_eq!(p.import(FILE2, 0), 1); assert_eq!(p.import("/nonexistent/c.mp4", 0), 2); assert!(p.append_clip(2, 4)); - let (sources, lanes, eq, color) = p.without_orphan_sources(); + let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); assert_eq!( sources, vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)] @@ -7678,7 +7821,7 @@ mod tests { [0, 1] ); // ...and what comes out is loadable, with the same timeline. - let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts"); + let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts"); assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); assert_eq!(reloaded.sources().len(), 2); } @@ -7729,8 +7872,8 @@ mod tests { ); // What is left is a project that still loads, which is the whole point // of renumbering rather than leaving a hole. - let (sources, lanes, eq, color) = p.without_orphan_sources(); - Project::from_parts(sources, lanes, eq, color).expect("from_parts"); + let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); + Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts"); } /// The two edges of a removal: it retires the undo stack (the corner-cut on @@ -7836,7 +7979,7 @@ mod tests { assert!(p.undo(), "back to the first setting"); assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1))); - let (_, lanes, eq, _) = p.without_orphan_sources(); + let (_, lanes, eq, _, _) = p.without_orphan_sources(); assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written"); assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers"); assert_eq!(lanes[0].1[1].eq, None); @@ -7844,7 +7987,7 @@ mod tests { // One curve on three clips is one entry: settings that are equal share. assert!(p.set_eq(Lane::V1, 1, Some(band_at(1)))); assert!(p.set_eq(Lane::A1, 2, Some(band_at(1)))); - let (_, lanes, eq, _) = p.without_orphan_sources(); + let (_, lanes, eq, _, _) = p.without_orphan_sources(); assert_eq!(eq.len(), 1, "equal settings share their entry"); assert_eq!(lanes[1].1[2].eq, Some(0)); reloads(&p, "an equalizer that outlived an undo"); @@ -7969,7 +8112,7 @@ mod tests { assert!(p.undo(), "back to the first grade"); assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1))); - let (_, lanes, _, color) = p.without_orphan_sources(); + let (_, lanes, _, color, _) = p.without_orphan_sources(); assert_eq!( color, vec![grade_at(1)], @@ -7981,36 +8124,157 @@ mod tests { // One grade on three clips is one entry: settings that are equal share. assert!(p.set_color(Lane::V1, 1, Some(grade_at(1)))); assert!(p.set_color(Lane::A1, 2, Some(grade_at(1)))); - let (_, lanes, _, color) = p.without_orphan_sources(); + let (_, lanes, _, color, _) = p.without_orphan_sources(); assert_eq!(color.len(), 1, "equal grades share their entry"); assert_eq!(lanes[1].1[2].color, Some(0)); reloads(&p, "a colour that outlived an undo"); // An equalizer and a grade on one clip are two independent tables. assert!(p.set_eq(Lane::V1, 0, Some(band_at(3)))); - let (_, lanes, eq, color) = p.without_orphan_sources(); + let (_, lanes, eq, color, _) = p.without_orphan_sources(); assert_eq!((eq.len(), color.len()), (1, 1)); assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0))); } + /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a + /// placement is the clip's, through every edit that copies one. + #[test] + fn a_transform_follows_the_clip_through_split_copy_and_undo() { + let mut p = three(); + assert!( + p.transform_of(Lane::V1, 0).is_none(), + "a fresh clip is untransformed" + ); + assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2)))); + assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); + assert!( + p.transform_of(Lane::A1, 0).is_none(), + "one clip, not the lane below" + ); + assert!( + p.color_of(Lane::V1, 0).is_none(), + "and a placement is not a grade" + ); + + // Cutting a transformed clip must not transform half of it: both + // halves inherit. + assert!(p.split(1)); + assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); + assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2))); + assert!( + p.transform_of(Lane::V1, 2).is_none(), + "the clip after it is untransformed" + ); + + // A clipboard copy carries it -- onto another lane, at that. + let copied = p.lane(Lane::V1)[1]; + assert!(p.place(Lane::A1, 20, copied)); + assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2))); + assert!(p.undo()); + assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off"); + + // ...and a change to one is one undo step, in both directions. + assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5)))); + assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5))); + assert!(p.undo()); + assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); + assert!( + p.set_transform(Lane::V1, 0, None), + "and taking it off is an edit" + ); + assert!(p.transform_of(Lane::V1, 0).is_none()); + assert!(p.undo()); + assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); + + // Two refusals, neither of which costs an undo step. + let nan = TransformParams { + scale: f32::NAN, + ..transform_at(1) + }; + assert!( + !p.set_transform(Lane::V1, 99, Some(transform_at(1))), + "no clip there" + ); + assert!( + !p.set_transform(Lane::V1, 0, Some(nan)), + "not a finite value" + ); + assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); + assert!(p.undo()); + assert_eq!( + p.lane(Lane::V1).len(), + 3, + "one step back is before the split" + ); + assert!(p.undo()); + assert!( + p.transform_of(Lane::V1, 0).is_none(), + "and the next is before the placement: the refusals pushed none" + ); + } + + /// The transform table is append-only within a session, exactly as the eq + /// and colour ones are -- and a save is where an undone placement goes. + #[test] + fn an_undone_transform_is_pruned_when_the_project_is_saved() { + let mut p = three(); + assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1)))); + assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2)))); + assert!(p.undo(), "back to the first placement"); + assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1))); + + let (_, lanes, _, _, transform) = p.without_orphan_sources(); + assert_eq!( + transform, + vec![transform_at(1)], + "what nothing plays is not written" + ); + assert_eq!( + lanes[0].1[0].transform, + Some(0), + "and the survivor renumbers" + ); + assert_eq!(lanes[0].1[1].transform, None); + + // One placement on three clips is one entry: settings that are equal + // share. + assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1)))); + assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1)))); + let (_, lanes, _, _, transform) = p.without_orphan_sources(); + assert_eq!(transform.len(), 1, "equal placements share their entry"); + assert_eq!(lanes[1].1[2].transform, Some(0)); + reloads(&p, "a transform that outlived an undo"); + + // A grade and a placement on one clip are two independent tables. + assert!(p.set_color(Lane::V1, 0, Some(grade_at(3)))); + let (_, lanes, _, color, transform) = p.without_orphan_sources(); + assert_eq!((color.len(), transform.len()), (1, 1)); + assert_eq!( + (lanes[0].1[0].color, lanes[0].1[0].transform), + (Some(0), Some(0)) + ); + } + /// Not a claim about correctness but about cost: a clip is copied on every /// paste, every undo snapshot and every lane clone, so its size is worth /// knowing. The eq index fit the padding a `Copy` clip already had; the - /// colour one did not, and the struct grew a word. + /// colour one did not, and the struct grew a word. The transform index is + /// a third `Option`, and it fits the padding the fit policy and the + /// transition byte already left behind, so the struct did not grow again. #[test] fn a_clip_is_still_a_small_copy() { assert_eq!( std::mem::size_of::(), 56, - "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition" + "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition, still 56 with the transform index" ); } #[test] fn from_parts_has_no_history_and_checks_the_invariants() { - let (sources, lanes, eq, color) = three().without_orphan_sources(); + let (sources, lanes, eq, color, _transform) = three().without_orphan_sources(); let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone()); - let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone()) + let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new()) .expect("valid parts"); assert_eq!(p.clips(), three().clips()); assert!(!p.undo(), "a loaded project has nothing to undo"); @@ -8025,6 +8289,7 @@ mod tests { two(video.clone(), Vec::new()), Vec::new(), Vec::new(), + Vec::new(), ) .is_ok() ); @@ -8034,10 +8299,11 @@ mod tests { two(Vec::new(), Vec::new()), Vec::new(), Vec::new(), + Vec::new(), ) .is_ok() ); - assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err()); + assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err()); let bad: [Vec; 5] = [ vec![clip(0, 0, 3, 1)], // source that is not there vec![clip(0, 3, 3, 0)], // empty clip @@ -8052,6 +8318,7 @@ mod tests { two(clips.clone(), Vec::new()), Vec::new(), Vec::new(), + Vec::new(), ) .is_err(), "{clips:?}" @@ -8062,6 +8329,7 @@ mod tests { two(video.clone(), clips.clone()), Vec::new(), Vec::new(), + Vec::new(), ) .is_err() ); @@ -8076,6 +8344,7 @@ mod tests { ], Vec::new(), Vec::new(), + Vec::new(), ) .is_err() ); @@ -8097,6 +8366,7 @@ mod tests { two(eqd(0), Vec::new()), Vec::new(), Vec::new(), + Vec::new(), ) .is_err() ); @@ -8108,6 +8378,7 @@ mod tests { two(eqd(0), Vec::new()), vec![nan], Vec::new(), + Vec::new(), ) .is_err() ); @@ -8116,6 +8387,7 @@ mod tests { two(eqd(0), Vec::new()), vec![band_at(1)], Vec::new(), + Vec::new(), ) .expect("an eq the table holds"); assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1))); @@ -8138,6 +8410,7 @@ mod tests { two(graded(0), Vec::new()), Vec::new(), Vec::new(), + Vec::new(), ) .is_err(), "a colour index no entry answers" @@ -8151,6 +8424,7 @@ mod tests { tint: f32::NAN, ..grade_at(1) }], + Vec::new(), ) .is_err(), "a value the file format could not have written" @@ -8160,12 +8434,13 @@ mod tests { two(graded(0), Vec::new()), Vec::new(), vec![grade_at(1)], + Vec::new(), ) .expect("a colour the table holds"); assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1))); // Group ids survive a load, and the next split gets a fresh one. - let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts"); + let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts"); assert!(p.split(4)); assert!(p.clips().iter().all(|c| c.link.is_some())); } @@ -8194,13 +8469,14 @@ mod tests { link: Some(link), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; // The door: a doubled id inside one lane, refused by name. let err = |video: Vec, audio: Vec| { - Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new()) + Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new()) .expect_err("refused") .to_string() }; @@ -8235,14 +8511,15 @@ mod tests { two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]), Vec::new(), Vec::new(), + Vec::new(), ); assert!(apart.is_ok(), "offsets within one group load: {apart:?}"); // A one-sided link is *not* an error: it is what a lift leaves behind. let mut p = Project::single(FILE, 9); assert!(p.lift(Lane::A1, 0)); - let (sources, lanes, eq, color) = p.clone().without_orphan_sources(); + let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources(); assert!( - Project::from_parts(sources, lanes, eq, color).is_ok(), + Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(), "a lifted lane's project has to load again" ); @@ -8637,8 +8914,8 @@ mod tests { /// handed back to the constructor a load goes through -- every lane of them, /// and the reloaded timeline has to be the same lanes in the same order. fn reloads(p: &Project, what: &str) { - let (sources, lanes, eq, color) = p.clone().without_orphan_sources(); - match Project::from_parts(sources, lanes, eq, color) { + let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources(); + match Project::from_parts(sources, lanes, eq, color, transform) { Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes), Ok(back) => { assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed"); @@ -8674,6 +8951,22 @@ mod tests { .collect() }; assert_eq!(colors(&back), colors(p), "{what}: the colours changed"); + // ...and the transform table, by the same claim again. + let transforms = |p: &Project| -> Vec>> { + p.lanes() + .into_iter() + .map(|l| { + (0..p.lane(l).len()) + .map(|i| p.transform_of(l, i).copied()) + .collect() + }) + .collect() + }; + assert_eq!( + transforms(&back), + transforms(p), + "{what}: the transforms changed" + ); } } } @@ -8888,12 +9181,12 @@ mod tests { invariants_hold(&p, "V2 over V1"); // A save writes that order and a load takes it back. - let (sources, lanes, eq, color) = p.without_orphan_sources(); + let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); assert_eq!( lanes.iter().map(|(k, _)| *k).collect::>(), [LaneKind::Video, LaneKind::Video, LaneKind::Audio] ); - let back = Project::from_parts(sources, lanes, eq, color).expect("three lanes load"); + let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load"); assert_eq!(back.lanes(), p.lanes()); assert_eq!(shape(&back), shape(&p), "the same lane is still on top"); @@ -8974,6 +9267,7 @@ mod tests { link: Some(link), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -9024,7 +9318,7 @@ mod tests { let v2 = p.add_lane(LaneKind::Video); assert!(p.place(v2, 4, clip(0, 20, 32, 0))); let a2 = p.add_lane(LaneKind::Audio); - let (sources, lanes, eq, color) = p.without_orphan_sources(); + let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); assert_eq!( lanes.iter().map(|(k, _)| *k).collect::>(), [ @@ -9038,7 +9332,7 @@ mod tests { assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written"); assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane"); // ...and all four load again as the same four. - let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load"); + let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load"); assert_eq!(back.lanes(), p.lanes()); assert_eq!(back.lane(a2), p.lane(a2)); @@ -9131,7 +9425,7 @@ mod tests { (LaneKind::Video, vec![clip(10, 5, 15, 1)]), (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), ]; - let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts"); + let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts"); assert_eq!( p.composite_spans_from(0), vec![ @@ -9176,7 +9470,7 @@ mod tests { (LaneKind::Video, vec![clip(10, 0, 10, 1)]), (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), ]; - let p = Project::from_parts(sources, holed, vec![], vec![]).expect("valid parts"); + let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts"); assert_eq!( p.composite_spans_from(0), vec![ @@ -9224,7 +9518,7 @@ mod tests { (LaneKind::Audio, vec![clip(15, 0, 15, 1)]), (LaneKind::Audio, Vec::new()), ]; - let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts"); + let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts"); let lists = p.audio_segments_from(0, FPS); assert_eq!(lists.len(), 2, "the empty lane is not mixed in"); assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged"); @@ -9241,6 +9535,7 @@ mod tests { ], vec![], vec![], + Vec::new(), ) .expect("valid parts"); assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]); diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index eb30564..a565b7d 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -497,6 +497,7 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result bool) -> crate::Result 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) + } } /// Per-byte lerp of two same-sized I420 frames: `out = a + (b - a) * t`, on @@ -1134,4 +1352,151 @@ mod tests { let (y1, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 1.0); assert_eq!(y1, b.0); } + + /// The crop fractions cut a rect out of a 100x100 source at the very + /// pixels the maths says, chroma-grid aligned like every other rect here. + #[test] + fn crop_rect_math() { + let t = TransformParams { + crop_l: 0.1, + crop_r: 0.2, + crop_t: 0.0, + crop_b: 0.0, + ..Default::default() + }; + assert_eq!( + crop_rect(100, 100, &t), + Rect { x: 10, y: 0, w: 70, h: 100 }, + "10% off the left, 20% off the right, nothing off top or bottom" + ); + // Opposing crops clamp to 0.5 a side rather than meeting or crossing. + let extreme = TransformParams { + crop_l: 0.9, + crop_r: 0.9, + ..Default::default() + }; + let r = crop_rect(100, 100, &extreme); + assert!(r.w >= 2, "the smallest surviving rect is one chroma sample"); + // A zero-sized source has nothing to crop. + assert_eq!(crop_rect(0, 100, &TransformParams::default()), Rect { x: 0, y: 0, w: 0, h: 0 }); + } + + /// A placement moved by `pos_x`/`pos_y` (canvas fractions about its own + /// centre) and resized by `scale`, both about that same centre. + #[test] + fn transformed_dst_rect_at_pos_and_scale() { + let dst = Rect { x: 0, y: 0, w: 100, h: 100 }; + // Moved a quarter of the canvas to the right, untouched vertically. + let moved = TransformParams { + pos_x: 0.25, + ..Default::default() + }; + assert_eq!( + transformed_dst_rect(dst, &moved, 200, 200), + Rect { x: 50, y: 0, w: 100, h: 100 }, + "25% of a 200-wide canvas is 50 pixels, about the placement's own centre" + ); + // Doubled in place: the centre stays, the box fills the canvas. + let grown = TransformParams { + scale: 2.0, + ..Default::default() + }; + assert_eq!( + transformed_dst_rect(dst, &grown, 200, 200), + Rect { x: 0, y: 0, w: 200, h: 200 }, + "a 100x100 box doubled about its own centre on a 200x200 canvas fills it" + ); + } + + /// [`nearest_90_steps`] rounds to the closest quarter turn and folds a + /// non-finite value to the identity. + #[test] + fn nearest_90_steps_rounds_and_wraps() { + assert_eq!(nearest_90_steps(0.0), 0); + assert_eq!(nearest_90_steps(89.0), 1); + assert_eq!(nearest_90_steps(91.0), 1); + assert_eq!(nearest_90_steps(180.0), 2); + assert_eq!(nearest_90_steps(-90.0), 3); + assert_eq!(nearest_90_steps(360.0 + 90.0), 1); + assert_eq!(nearest_90_steps(f32::NAN), 0); + } + + /// A marked corner pixel lands where a clockwise quarter turn puts it: + /// top-left to top-right at 90 degrees, to bottom-right at 180, to + /// bottom-left at 270 -- and the plane's own shape swaps at 90 and 270 + /// and stays put at 180. + #[test] + fn rotate_i420_90s_places_a_marked_pixel() { + let (w, h) = (4usize, 3usize); + let mut y = vec![0u8; w * h]; + y[0] = 99; // (x=0, y=0), the top-left corner. + let (u, v) = (vec![128u8; 2 * 2], vec![128u8; 2 * 2]); + + let mark_at = |plane: &[u8], w: u32, x: u32, y: u32| plane[(y * w + x) as usize]; + + let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 1); + assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 90 degrees"); + assert_eq!(mark_at(&ry, rw, rw - 1, 0), 99, "top-left moves to top-right"); + + let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 2); + assert_eq!((rw, rh), (w as u32, h as u32), "dims stay put at 180 degrees"); + assert_eq!( + mark_at(&ry, rw, rw - 1, rh - 1), + 99, + "top-left moves to bottom-right" + ); + + let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 3); + assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 270 degrees"); + assert_eq!( + mark_at(&ry, rw, 0, rh - 1), + 99, + "top-left moves to bottom-left" + ); + + // Zero steps, and four of them, are both the identity. + let (ry, ru, rv, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 0); + assert_eq!((ry, ru, rv, rw, rh), (y.clone(), u.clone(), v.clone(), w as u32, h as u32)); + let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 4); + assert_eq!((ry, rw, rh), (y, w as u32, h as u32), "four quarter turns is the identity"); + } + + /// [`Composer::place_transformed`] at compose level: a picture placed with + /// a `pos_x` offset lands its marked pixel shifted by exactly that many + /// canvas pixels, with black everywhere else. + #[test] + fn place_transformed_shifts_a_marked_pixel() { + let (src_w, src_h) = (64u32, 64u32); + let (y, u, v) = ( + vec![200u8; (src_w * src_h) as usize], + vec![NEUTRAL_C; ((src_w / 2) * (src_h / 2)) as usize], + vec![NEUTRAL_C; ((src_w / 2) * (src_h / 2)) as usize], + ); + let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit); + // Identity: a pass-through-shaped placement, fills the whole canvas. + let (iy, _, _, iw, ih) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default()); + assert_eq!((iw, ih), (src_w, src_h)); + assert!(iy.iter().all(|&p| p == 200), "identity fills the canvas"); + + // Moved a quarter of the canvas to the right: the left half is black, + // the right half (minus the strip pushed off the edge) is the picture. + let moved = TransformParams { + pos_x: 0.25, + ..Default::default() + }; + let (my, _, _, mw, mh) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &moved); + assert_eq!((mw, mh), (src_w, src_h), "canvas size never changes"); + let shift = (f64::from(src_w) * 0.25).round() as usize; + for row in 0..mh as usize { + let r = &my[row * mw as usize..][..mw as usize]; + assert!( + r[..shift].iter().all(|&p| p == BLACK_Y), + "row {row}: black ahead of the shifted picture" + ); + assert!( + r[shift..].iter().all(|&p| p == 200), + "row {row}: the picture fills the rest, shifted right" + ); + } + } } diff --git a/crates/engine/src/silence.rs b/crates/engine/src/silence.rs index b2ae6b5..273bf50 100644 --- a/crates/engine/src/silence.rs +++ b/crates/engine/src/silence.rs @@ -305,6 +305,7 @@ mod tests { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed, } diff --git a/crates/engine/src/sweep.rs b/crates/engine/src/sweep.rs index 12c8c2f..1e48a0a 100644 --- a/crates/engine/src/sweep.rs +++ b/crates/engine/src/sweep.rs @@ -76,6 +76,7 @@ fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::Fit, speed: Speed::NORMAL, } 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()); + } +} diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 8ccfa79..af6a2ee 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -73,6 +73,7 @@ fn mixed_project() -> Project { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }; Project::from_parts( vec![ @@ -98,12 +99,14 @@ fn mixed_project() -> Project { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }], ), (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]), ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a two-source project with a hole in the audio lane") } @@ -345,6 +348,7 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }; // Two seconds of each at the project's own 30 fps: a still has no length of // its own and the song is longer than what is placed. @@ -356,6 +360,7 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a still under a song"); // The project's own picture size and rate: the still decides the one and @@ -412,6 +417,7 @@ fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }; let four = || { Project::from_parts( @@ -425,7 +431,8 @@ fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { ], Vec::new(), Vec::new(), - ) + Vec::new(), + ) .expect("one second on four audio tracks") }; let write = |project: Project, name: &str| { @@ -651,6 +658,7 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }], ), ( @@ -668,11 +676,13 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }], ), ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a still under a song"); let meta = engine::VideoMeta { @@ -726,6 +736,7 @@ fn a_silent_clip_exports_as_silence_over_its_own_span() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }; let project = Project::from_parts( vec![ @@ -739,6 +750,7 @@ fn a_silent_clip_exports_as_silence_over_its_own_span() { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a project whose middle take is silent"); @@ -821,10 +833,12 @@ fn a_51_ac3_source_round_trips_through_a_wav() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }], )], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a one-source AC-3 project"); let video = engine::demux::Demuxer::open(&source).expect("open the fixture").0; @@ -1140,10 +1154,12 @@ fn a_mono_timeline_exports_as_dual_mono_ogg() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }], )], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a one-source mono project"); diff --git a/crates/engine/tests/eq_audio.rs b/crates/engine/tests/eq_audio.rs index 5c654bb..cb513ff 100644 --- a/crates/engine/tests/eq_audio.rs +++ b/crates/engine/tests/eq_audio.rs @@ -66,6 +66,7 @@ fn clip(start: u32, source: usize, frames: u32) -> Clip { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, } } @@ -80,6 +81,7 @@ fn project(audio: Vec) -> Project { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a one-source project") } @@ -245,6 +247,7 @@ fn a_lane_is_equalized_before_the_mix_and_never_after_it() { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a two-audio-lane project"); assert_eq!(p.audio_lanes().len(), 2, "both lanes hold something"); diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 69cb986..58bfe76 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -244,6 +244,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { link: Some(source as u32), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -259,6 +260,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a two-source project"); // The project's own resolution, which is neither source's: this is the @@ -329,6 +331,7 @@ fn exports_the_audio_stream_the_timeline_plays() { link: Some(0), eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -346,6 +349,7 @@ fn exports_the_audio_stream_the_timeline_plays() { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a one-source project on stream 1"); let out = out_path("stream1"); diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs index c412caf..06f3008 100644 --- a/crates/engine/tests/lanes.rs +++ b/crates/engine/tests/lanes.rs @@ -245,6 +245,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; @@ -257,6 +258,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { ], vec![], vec![], + vec![], ) .expect("valid parts"); assert_eq!( @@ -309,14 +311,15 @@ fn two_audio_lanes_are_summed() { link: None, eq: None, color: None, + transform: None, fit: FitPolicy::default(), speed: Speed::NORMAL, }; let a2 = project.add_lane(LaneKind::Audio); assert!(project.place(a2, TOP_IN, doubled), "place the second lane"); - let (sources, lanes, eq, color) = project.without_orphan_sources(); + let (sources, lanes, eq, color, transform) = project.without_orphan_sources(); assert_eq!(lanes.len(), 3, "V1, A1 and the new A2"); - let project = Project::from_parts(sources, lanes, eq, color).expect("valid parts"); + let project = Project::from_parts(sources, lanes, eq, color, transform).expect("valid parts"); let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap(); let wav = |name: &str, project: Project| { @@ -507,6 +510,7 @@ fn a_subtitle_lane_is_a_peer_and_every_media_path_refuses_it() { vec![(LaneKind::Subtitle, vec![clip])], Vec::new(), Vec::new(), + Vec::new(), ) .expect_err("a file may not name one either"); assert!( diff --git a/crates/engine/tests/opus_export.rs b/crates/engine/tests/opus_export.rs index dc450fa..23147b0 100644 --- a/crates/engine/tests/opus_export.rs +++ b/crates/engine/tests/opus_export.rs @@ -92,6 +92,7 @@ fn project(video: &Path, sound: &Path, sound_in: u32) -> Project { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }; // The sound is source **0** on purpose: the timeline takes its rate and its // width from the first source that has any, so a project whose first source @@ -109,6 +110,7 @@ fn project(video: &Path, sound: &Path, sound_in: u32) -> Project { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a picture lane and an audio lane") } @@ -436,6 +438,7 @@ fn a_copied_picture_names_the_sound_it_was_written_with() { color: None, fit: FitPolicy::default(), speed: Speed::NORMAL, + transform: None, }; // The sound is source 0, for the reason [`project`] gives: the timeline // takes its rate and its width from the first source that has any. @@ -447,6 +450,7 @@ fn a_copied_picture_names_the_sound_it_was_written_with() { ], Vec::new(), Vec::new(), + Vec::new(), ) .expect("a picture lane and an audio lane"); let out = out_path("copy_line"); diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs index 0b034d4..4e4bf43 100644 --- a/crates/engine/tests/silence.rs +++ b/crates/engine/tests/silence.rs @@ -36,8 +36,8 @@ fn fixture() -> Project { /// is one no save could load: this is that check, through the same door a load /// takes. fn loadable(project: &Project) { - let (sources, lanes, eq, color) = project.without_orphan_sources(); - Project::from_parts(sources, lanes, eq, color).expect("the lanes still load"); + let (sources, lanes, eq, color, transform) = project.without_orphan_sources(); + Project::from_parts(sources, lanes, eq, color, transform).expect("the lanes still load"); } fn spans(project: &Project) -> (Vec<(u32, u32)>, Vec<(u32, u32)>) { @@ -150,6 +150,7 @@ fn speed_mode_refuses_a_clip_that_laps_over_a_silence() { color: None, fit: Default::default(), speed: Speed::NORMAL, + transform: None, }; assert!(p.place(lane, 40, broll)); let before = spans(&p); @@ -188,6 +189,7 @@ fn whole(source: usize, frames: u32) -> Clip { color: None, fit: Default::default(), speed: Speed::NORMAL, + transform: None, } } @@ -370,7 +372,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { // same dialect it always was -- no wire change went with this feature. let dir = Scratch::dir("edith-silence"); let file = dir.join("cut.edith"); - let (sources, lanes, eq, color) = p.without_orphan_sources(); + let (sources, lanes, eq, color, transform) = p.without_orphan_sources(); engine::edith::save( &file, &sources, @@ -380,6 +382,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { p.subtitles(), &eq, &color, + &transform, (1920, 1080), None, p.tone(),