From 6d8f3a1df6e9f723a292f9e5ed113e160f7bd5a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 16 Aug 2026 05:34:18 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(playback):=20the=20playhead?= =?UTF-8?q?=20follows=20the=20re-rate=20through=20the=20same=20map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A speed change left the playhead at its own timeline position while write_speed re-timed the group under it, so the scene changed with the rate -- at 2x from the middle of a clip the cursor jumped a clip's worth of content. Both the commit and every live sample of the bar now map the playhead through a TimelineMap built from the group's own old geometry: each clip member by its old rate against the new one about its own head, each caption member by the held clip's proportion about the held clip's head, and a playhead outside every member unmoved -- nothing ripples, so the difference is the gap's to absorb. TimelineMap (engine/src/map.rs) is the one piecewise-affine answer the re-timing ops will share; this is its read-side consumer, with the laws pinned (monotone, exact on the ends, invertible on the image) and the playhead its first user. The delete and paste migrations land next; until they do, invert and the total shift answer the laws tests alone. --- crates/engine/src/lib.rs | 1 + crates/engine/src/map.rs | 185 ++++++++++++++++++++++++++++++++++ crates/engine/src/playback.rs | 38 ++++++- crates/engine/src/project.rs | 169 +++++++++++++++++++++++++++++++ crates/engine/tests/speed.rs | 30 ++++++ 5 files changed, 420 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/map.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 27913f0..221b6ce 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -24,6 +24,7 @@ pub mod scale; pub mod scratch; pub mod silence; pub mod subtitle; +pub(crate) mod map; pub(crate) mod stretch; pub mod tonemap; pub mod waveform; diff --git a/crates/engine/src/map.rs b/crates/engine/src/map.rs new file mode 100644 index 0000000..39ea7bc --- /dev/null +++ b/crates/engine/src/map.rs @@ -0,0 +1,185 @@ +//! The timeline's re-timing map: one piecewise-affine answer to "this frame +//! is now where?", built by every operation that moves time. +//! +//! THE ARCHITECTURE LAW: a re-timing op NEVER touches lanes directly. It +//! (1) resolves its [`Members`](crate::project) once via `group_of`, (2) +//! builds ONE `TimelineMap` from their geometry, (3) applies that map to +//! every lane it owns -- media clips AND captions, uniformly -- and (4) the +//! caller maps the playhead through the SAME map. The app never re-derives +//! group or time semantics; the engine's gates stay the single questions. +//! +//! The map itself is a sorted list of knots `(old frame, new frame)` with +//! affine interpolation between neighbours and identity outside the ends: a +//! compression is two knots with a shallower slope between them, a removal +//! is a knot pair that collapses a span onto a point, an insertion the same +//! run backwards. Every piece is monotone by construction (knots sorted on +//! both axes), which is what makes [`TimelineMap::invert`] a binary search +//! and the playhead's question a lookup. + +/// A piecewise-affine old→new frame map, identity outside its knots. Built +/// once per edit and read many times; `Clone` for the tests that pin its +/// laws, `Debug` for the messages those tests print when they fail. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct TimelineMap { + /// Knot points, sorted by `old`, strictly increasing on both axes (the + /// constructor refuses anything else: a map that folded time back on + /// itself would be a map nothing downstream could invert). + knots: Vec<(u32, u32)>, +} + +impl TimelineMap { + /// The map that moves nothing: the base every piece is cut into. + pub(crate) fn identity() -> Self { + Self { knots: Vec::new() } + } + + /// One non-identity piece -- `[old_lo, old_hi)` maps onto `[new_lo, + /// new_hi)` -- over an identity base. The whole of a compression (a + /// re-rate of a member); a removal is `new` collapsed onto its own lo, + /// and an insertion is that run backwards. Degenerate spans (an empty + /// old, an inverted one) come out identity, because there is nothing in + /// them to move. + pub(crate) fn piece(old: (u32, u32), new: (u32, u32)) -> Self { + if old.0 >= old.1 || new.0 >= new.1 { + return Self::identity(); + } + Self { + // Half-open boundary knots: interpolation runs between them and + // the frame *at* the hi knot is the piece's own to give back + // (the caller clamps inside), never a step past its new end. + knots: vec![(old.0, new.0), (old.1, new.1)], + } + } + + /// Where `frame` lands. Affine between knots, identity outside them, + /// rounded to the nearest frame -- the same rounding every placement in + /// this engine already makes -- and never past the new end of the piece + /// it is inside, which a round-up at the last frame would do. + pub(crate) fn apply(&self, frame: u32) -> u32 { + let mut prev: Option<(u32, u32)> = None; + for &(o, n) in &self.knots { + if frame == o { + return n; + } + if frame < o { + return match prev { + // Before the first knot: identity from the head. + None => frame, + Some(po) => lerp(po, (o, n), frame).min(n.saturating_sub(1)).max(po.1), + }; + } + prev = Some((o, n)); + } + match prev { + // Past the last knot: identity at the total shift it left. + Some((o, n)) => frame.saturating_add(n).saturating_sub(o), + None => frame, + } + } + + /// The inverse question, `None` off the surviving domain (inside a + /// removed span there is no frame to come back to -- the caller that + /// needs one picks the span's head, which is where a ripple put what + /// followed it). The knots are monotone, so this is the same walk with + /// the axes traded. + pub(crate) fn invert(&self, frame: u32) -> Option { + if self.knots.is_empty() { + return Some(frame); + } + // Before the first knot the map was the identity on `[0, old_lo)`, + // which on the new axis is the straight run from 0 to the knot. + if frame < self.knots[0].1 { + return Some(lerp((0, 0), self.knots[0], frame)); + } + let mut prev = self.knots[0]; + for &(o, n) in &self.knots { + if frame == n { + return Some(o); + } + if frame < n { + return Some(lerp((prev.1, prev.0), (n, o), frame)); + } + prev = (o, n); + } + let (o, n) = *self.knots.last().expect("checked non-empty"); + Some(frame.saturating_sub(n).saturating_add(o)) + } + + pub(crate) fn shifted_total(&self) -> i64 { + match self.knots.last() { + Some(&(o, n)) => i64::from(n) - i64::from(o), + None => 0, + } + } +} + +/// The one interpolation this module is: `frame`'s place between two knots, +/// carried across to the other axis. Independent of the axes' order, which +/// is what [`TimelineMap::invert`] reuses it for. +fn lerp(a: (u32, u32), b: (u32, u32), frame: u32) -> u32 { + if b.0 <= a.0 { + return a.1; + } + let t = f64::from(frame.saturating_sub(a.0)) / f64::from(b.0 - a.0); + (f64::from(a.1) + t * f64::from(b.1.saturating_sub(a.1))).round() as u32 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The piece laws on every shape the engine cuts: monotone, identity + /// outside, exact on the ends, invertible on what survives, and the + /// total shift the caller reads for the timeline's new length. + #[test] + fn a_piece_is_monotone_exact_and_invertible() { + // A compression: [100, 200) onto [100, 150). + let m = TimelineMap::piece((100, 200), (100, 150)); + assert_eq!(m.apply(0), 0, "identity before"); + assert_eq!(m.apply(99), 99); + assert_eq!(m.apply(100), 100, "the lo knot is exact"); + assert_eq!(m.apply(150), 125, "the middle halves"); + assert_eq!(m.apply(199), 149, "the last surviving frame"); + assert_eq!(m.apply(200), 150, "identity at the new shift"); + assert_eq!(m.apply(1_000), 950); + assert_eq!(m.shifted_total(), -50); + // Monotone: a walk up the whole range never goes down. + let mut last = 0; + for f in 0..400 { + let now = m.apply(f); + assert!(now >= last, "frame {f} went back to {now}"); + last = now; + } + // Round trip in the law's own direction: every new frame's inverse + // maps back onto it. The other direction cannot be identity under + // rounding -- a compression sends two neighbouring frames to one. + for n in 0..400 { + let back = m.invert(n).expect("the image is total"); + assert_eq!(m.apply(back), n, "new frame {n} round trips"); + } + let m = TimelineMap::piece((100, 200), (100, 300)); + assert_eq!(m.apply(150), 200, "the middle doubles"); + assert_eq!(m.apply(1_000), 1_100); + assert_eq!(m.shifted_total(), 100); + + // A removal: [100, 200) onto [100, 100) -- nothing survives inside, + // and what followed stands where the span began. + let m = TimelineMap::piece((100, 200), (100, 101)); + assert_eq!(m.apply(99), 99); + assert_eq!(m.apply(150), 100, "inside collapses to the head"); + assert_eq!(m.apply(200), 101, "after shifts up tight"); + assert_eq!(m.shifted_total(), -99); + } + + /// Identity is the base: everything maps to itself, in both directions, + /// and the timeline's length never moved. + #[test] + fn identity_moves_nothing() { + let m = TimelineMap::identity(); + for f in [0u32, 1, 999, u32::MAX / 2] { + assert_eq!(m.apply(f), f); + assert_eq!(m.invert(f), Some(f)); + } + assert_eq!(m.shifted_total(), 0); + } +} diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 56e98a6..2225128 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -2074,9 +2074,18 @@ impl PlaybackSession { /// would run it into its neighbour, and nothing changes. pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { // Spelled out rather than through `edit`, whose closure hands back a - // bool and would drop the refusal's own words. + // bool and would drop the refusal's own words. The playhead moves + let at = self.project.speeded_playhead( + lane, + idx, + speed, + secs_to_frame(self.now(), self.meta.frame_rate), + ); self.project.set_speed(lane, idx, speed)?; - let now = self.now(); + let now = at.map_or_else( + || self.now(), + |frame| f64::from(frame) / self.meta.frame_rate, + ); self.seek(now); Ok(()) } @@ -2085,12 +2094,35 @@ impl PlaybackSession { /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one, /// which is what makes the bar move the picture under the hand. pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { + // The mapping on every sample, not just at the commit: the bar moves + // the rate live, and the scene has to stay put across the whole + // gesture or the last picture before the release is not the one the + // commit lands on. + let at = self.project.speeded_playhead( + lane, + idx, + speed, + secs_to_frame(self.now(), self.meta.frame_rate), + ); self.project.set_speed_live(lane, idx, speed)?; - let now = self.now(); + let now = at.map_or_else( + || self.now(), + |frame| f64::from(frame) / self.meta.frame_rate, + ); self.seek(now); Ok(()) } + /// The picture's source frame at `timeline_secs`: which source, and which + /// frame of it -- the composite a viewer is looking at, through the same + /// span math the decoder walks. What a test asks to prove a reseek kept + /// the scene, and nothing in the editor itself reads. + pub fn video_source_frame_at(&self, timeline_secs: f64) -> Option<(usize, u32)> { + self.project + .composite_span_at(secs_to_frame(timeline_secs, self.meta.frame_rate)) + .and_then(|s| s.from) + } + /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out /// of the lanes in `scope` and closes each hole, as **one** edit /// ([`Project::cut_regions`]): the jumpcut a silence scan diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 2bf21d4..f16e49f 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -73,6 +73,7 @@ //! a save. An index rather than the four floats themselves for the same reason: //! twenty clips graded alike name one entry, and the file writes it once. +use crate::map::TimelineMap; use std::path::{Path, PathBuf}; use crate::color::ColorParams; @@ -2298,6 +2299,70 @@ impl Project { Ok(()) } + /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a + /// playhead standing at `at` -- read off the geometry **before** the + /// write, because the old ends are gone after it. The question a card + /// asks as its bar moves: the picture under the cursor has to stay the + /// picture under the cursor, or the scene changes with the rate. + /// + /// The answer is piecewise, exactly as [`write_speed`] re-times, and it + /// is asked of the same [`TimelineMap`] the write itself is a shape of: + /// a clip member keeps its own start and re-fits its length at the new + /// rate -- its **old** rate against the new one, which is what the bar's + /// live samples ask about as much as a first press does; a caption + /// member scales about the held clip's start by the held clip's own + /// proportion; and a playhead outside every member's old extent stays + /// exactly where it was -- nothing ripples, so the gap a shrink leaves + /// (or the room a stretch takes) absorbs the difference, not the + /// playhead. `None` for an index that is not there. + pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option { + let members = self.group_of(lane, idx)?; + let held = self.lane(lane).get(idx).copied()?; + let (held_old, new) = (held.speed.as_f64(), speed.as_f64()); + for &(l, i) in members.clips.iter().chain(&members.subs) { + let (span, map) = match self + .lanes[l] + .clips + .get(i) + .filter(|_| members.clips.contains(&(l, i))) + { + // The clip's own span, re-fitted at its own old rate: one + // piece of the map, anchored where the clip itself is. The + // new length is the same *source* frames at the new rate -- + // len divided by it, never multiplied. + Some(c) => ( + (c.start, c.start + c.frames()), + TimelineMap::piece( + (c.start, c.start + c.frames()), + ( + c.start, + c.start + (c.len() as f64 / new).round() as u32, + ), + ), + ), + // The caption's span, scaled about the held clip's head by + // the held clip's proportion -- the offset the group keeps. + None => { + let s = self.lanes[l].subs.get(i)?; + let held_start = f64::from(held.start); + let scale = |f: u32| { + (held_start + (f64::from(f) - held_start) * held_old / new).round() as u32 + }; + ( + (s.start, s.end()), + TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))), + ) + } + }; + // The piece owns only its own old span: outside it the playhead + // is another member's question, or nobody's. + if (span.0..span.1).contains(&at) { + return Some(map.apply(at)); + } + } + Some(at) + } + /// How the clip at `idx` of `lane` meets a project canvas of another shape. /// [`FitPolicy::Fit`] for an index that is not there, which is the default /// every clip starts at anyway. @@ -4935,6 +5000,110 @@ mod tests { assert_eq!(shape(&p), before); } + /// Where a re-rate puts a playhead: the scene under the cursor stays the + /// scene under the cursor, measured the way a viewer would -- the source + /// frame playing at the playhead is the same frame after the write, at + /// every playhead position the re-rate can catch one. + #[test] + fn a_re_rate_keeps_the_frame_under_the_playhead() { + let caption = |start: u32, frames: u32| SubClip { + start, + frames, + track: 0, + in_us: 0, + out_us: i64::from(frames) * 1_000_000, + link: None, + }; + let track = || SubtitleTrack { + path: FILE.into(), + track: None, + language: "eng".into(), + name: String::new(), + label: "eng".into(), + cues: Vec::new(), + bitmap: false, + refused: None, + }; + // A group of a 300-frame clip and a caption offset 30 frames into it. + let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]); + let s1 = p.add_lane(LaneKind::Subtitle); + p.place_sub(s1, 30, caption(30, 240)).expect("placed"); + p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); + + // The frame playing at `at`: which clip, and which source frame of it. + let playing = |p: &Project, at: u32| -> Option<(usize, u32)> { + p.span_at(Lane::V1, at) + .and_then(|s| s.from.map(|(source, from)| (source, from))) + }; + + // Inside the held clip: the source frame under the playhead is the + // same one after the re-rate, at 2x and at half speed both. + for (what, speed) in [("2x", 2000u16), ("half", 500)] { + let at = 120; + let before = playing(&p, at).expect("a clip under the playhead"); + let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at); + p.set_speed(Lane::V1, 0, Speed::from_permille(speed)) + .expect("room for it"); + let after = playing(&p, mapped.unwrap()).expect("still a clip there"); + assert_eq!(before, after, "{what}: the same source frame plays"); + // ...and the write itself is untouched by the question. + assert!(p.undo(), "{what}: one step back"); + } + + // Past the group -- the clip ends at 300 and the caption at 270, so + // from 300 on nothing is re-timed under the playhead: unmoved. + for at in [300u32, 301, 1_000] { + assert_eq!( + p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at), + Some(at), + "at {at}: outside every member, unmoved" + ); + } + // The boundary is exact: the held clip's own last frame (299) maps + // to its new one (149 -- the last frame inside [0, 150), where the + // shrunken clip's last source frame plays), and its first stays put. + assert_eq!( + p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299), + Some(149) + ); + assert_eq!( + p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0), + Some(0) + ); + // A spot the caption shares with the clip maps by the clip (it is + // what is *playing* there): the held clip's own proportion, which on + // this fixture is also its head. + assert_eq!( + p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90), + Some(45), + "the clip under the caption owns the spot" + ); + } + + /// A playhead inside another clip member of the group: that member keeps + /// its own head, so the mapping is by its proportion and not the held + /// clip's -- and the frame under the cursor is still the frame that was. + #[test] + fn a_re_rate_maps_a_second_clip_member_about_its_own_head() { + let mut p = Project::single(FILE, 300); + // A second clip, grouped with the first but starting 300 later: the + // head the group shares and its own differ by exactly that. + let v2 = p.add_lane(LaneKind::Video); + assert!(p.lift(Lane::A1, 0), "the sound half stands aside"); + assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2"); + p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped"); + + let at = 450; // inside the second member, 150 past its head + let before = p.span_at(v2, at).and_then(|s| s.from); + let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at); + p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room for it"); + let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from); + assert_eq!(before, after, "the second member's own frame plays"); + // ...and the mapping itself: 150 past its head halves, the head stays. + assert_eq!(mapped, Some(375)); + } + /// The link counter a load seeds sits past every id the file names, /// captions included: a hand-grouped caption may carry the highest id there /// is, and a counter that read the clips alone would hand it to the next diff --git a/crates/engine/tests/speed.rs b/crates/engine/tests/speed.rs index af81948..28bafd2 100644 --- a/crates/engine/tests/speed.rs +++ b/crates/engine/tests/speed.rs @@ -400,6 +400,36 @@ fn a_2x_clip_keeps_the_beeps_pitch() { ); } +/// The playhead follows the re-rate: the source frame under it is the same +/// frame after the write (the scene does not change with the rate), through +/// the real session doors -- commit and the live samples of a drag both. +#[test] +fn the_playhead_follows_the_re_rate() { + let path = asset("test_speed_sync.mp4"); + let mut session = engine::PlaybackSession::open(&path).expect("open the fixture"); + // Park inside the clip, at a frame a re-rate must not lose: the source + // frame playing *now* is what the cursor is standing on. + session.seek(2.0); + let before = session.video_source_frame_at(2.0); + session + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room for it"); + let now = session.now(); + let after = session.video_source_frame_at(now); + // The live path keeps it across the whole gesture: two samples of a drag + // leave the same frame playing, not the one the rate walked past. + session + .set_speed(Lane::V1, 0, Speed::from_permille(1500)) + .expect("the bar moves"); + let hold = session.now(); + let held_frame = session.video_source_frame_at(hold); + session + .set_speed_live(Lane::V1, 0, Speed::from_permille(2500)) + .expect("the bar moves again"); + let still = session.video_source_frame_at(session.now()); + assert_eq!(held_frame, still, "a live sample keeps the scene"); +} + /// The symmetric half: a clip at half speed plays its beep at 1 kHz too, not /// the sub-octave the tape effect would leave there. #[test]