forge
Explore
Log in

Don't you dare go Hollow

Clips are trimmed by dragging their edges

Browse files at this commit

222336b1c3cb96ebf0803502576361e77001d1eaAhmet Kaan GümüşParent: c3b6ce2
  • feat
    • clips are trimmed by dragging their edges
Show full message
✨ feat(timeline): clips are trimmed by dragging their edges

A 6 px strip at each end of a clip box takes the press the body-drag would
otherwise take (gpui `occlude`), so one gesture stays one thing: an edge
trims, the middle still moves the clip to another lane, and both ends still
select and open the clip menu. The box follows the pointer while the button
is down and the engine hears about it once, at the release -- one edit, one
undo step for the whole drag, exactly as an equalizer gesture works.

`Project::trim` clamps rather than refuses: one frame of clip always
survives, an edge never crosses its neighbour on the lane, an in-point never
walks back past the source's first frame, and an out-point never runs past
the file's own last frame -- a clip ending past it is a project that will not
open again. `Project` does not know how long a file is, so `PlaybackSession`
now keeps the frame counts it already computes at every import and fills them
in. Linked halves trim together to one clamped edge, the tightest wall of the
group winning, because a link is one span on however many lanes.

`trim_room` is the same clamp without the mutation: the drag asks it where
the edge may land, so the width drawn is the width the release commits. A
timeline drawn to fit the window has no room past its own last frame, so
while a tail is dragged the bed is drawn out to as far as that tail may go --
without it the last clip could be pulled in and never let back out.
crates/app/src/main.rsmodified+287 -20
@@ -13,12 +13,13 @@ use engine::audio::StreamInfo;
13 use engine::color::ColorParams;13 use engine::color::ColorParams;
14 use engine::eq::{Band, BandKind, EqParams};14 use engine::eq::{Band, BandKind, EqParams};
15 use engine::export::{ExportSettings, Format};15 use engine::export::{ExportSettings, Format};
16-use engine::project::{Lane, LaneKind, Source};16+use engine::project::{Edge, Lane, LaneKind, Source};
17 use engine::scale::FitPolicy;17 use engine::scale::FitPolicy;
18 use engine::{Clip, ExportHandle, Frame, PlaybackSession};18 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
19 use gpui::{19 use gpui::{
20- AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,20+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
21- MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,21+ KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
22+ Point,
22 RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds,23 RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds,
23 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,24 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,
24 };25 };
@@ -216,6 +217,31 @@ struct ClipDrag {
216 idx: usize,217 idx: usize,
217 }218 }
218 219
220+/// A clip edge being dragged: which end of which clip, and the timeline frame
221+/// the pointer has pulled it to. The box on screen is drawn from `to` while this
222+/// is set and the engine hears about it once, at the release
223+/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture,
224+/// exactly as an equalizer drag works.
225+#[derive(Clone, Copy)]
226+struct Trim {
227+ lane: Lane,
228+ idx: usize,
229+ edge: Edge,
230+ /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from
231+ /// it is the width the release commits -- an edge stops under the pointer
232+ /// rather than snapping back after the fact.
233+ to: u32,
234+ /// The dragged clip's group, so its other halves' boxes follow the edge on
235+ /// screen exactly as the engine will move them.
236+ link: Option<u32>,
237+}
238+
239+/// How wide a clip's edge is as a *target*: the strip at each end where a press
240+/// means "make this longer or shorter" instead of "move this to another lane".
241+/// Wide enough to hit, narrow enough that the middle of even a small box is
242+/// still the body.
243+const EDGE_W: f32 = 6.;
244+
219 /// An open clip menu: which clip it was opened on, where it hangs, and whether245 /// An open clip menu: which clip it was opened on, where it hangs, and whether
220 /// it has been turned over to show what that clip *is* instead of what can be246 /// it has been turned over to show what that clip *is* instead of what can be
221 /// done to it. The lane and index are the ones the same click selected, so247 /// done to it. The lane and index are the ones the same click selected, so
@@ -359,6 +385,10 @@ struct Player {
359 /// A drag that started on the ruler. Moves anywhere in the window scrub385 /// A drag that started on the ruler. Moves anywhere in the window scrub
360 /// while it is set; the release commits the exact position.386 /// while it is set; the release commits the exact position.
361 scrubbing: bool,387 scrubbing: bool,
388+ /// A drag that started on a clip's edge, tracked on the root for
389+ /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See
390+ /// [`Trim`].
391+ trim: Option<Trim>,
362 last_scrub: Instant,392 last_scrub: Instant,
363 last_target: u32,393 last_target: u32,
364 /// The running export. While it owns the UI the editor is read-only.394 /// The running export. While it owns the UI the editor is read-only.
@@ -527,6 +557,11 @@ impl Player {
527 self.eos = false;557 self.eos = false;
528 self.done = false;558 self.done = false;
529 self.pending_seek = true;559 self.pending_seek = true;
560+ // An edit moves the indices a drag in flight is holding -- a stroke
561+ // during one is exactly that -- and an edge committed against a moved
562+ // index would trim a clip nobody grabbed. Dropping it is the whole fix:
563+ // nothing has been written yet.
564+ self.trim = None;
530 }565 }
531 566
532 /// What an action does, wherever it was asked for -- a stroke, or the clip567 /// What an action does, wherever it was asked for -- a stroke, or the clip
@@ -1168,6 +1203,135 @@ impl Player {
1168 cx.notify();1203 cx.notify();
1169 }1204 }
1170 1205
1206+ /// Opens the clip menu on the box under the pointer, from the right button
1207+ /// wherever it was pressed on that box -- its middle or one of its edge
1208+ /// strips, which cover the middle's own listener. Selecting first is part of
1209+ /// it: every item acts on the clip the menu names.
1210+ fn open_menu(&mut self, lane: Lane, idx: usize, at: Point<Pixels>, cx: &mut Context<Self>) {
1211+ if self.modal() {
1212+ return;
1213+ }
1214+ self.select((lane, idx), cx);
1215+ self.context_menu = Some(ContextMenu {
1216+ lane,
1217+ idx,
1218+ at,
1219+ details: false,
1220+ });
1221+ cx.notify();
1222+ }
1223+
1224+ /// A press on a clip's edge: the start of the drag that changes how much of
1225+ /// its source it plays. It selects the clip as a press anywhere else on the
1226+ /// box does -- the edge strip covers the box's own listener (`occlude`), so
1227+ /// this is the only one that fires there.
1228+ fn start_trim(&mut self, lane: Lane, idx: usize, edge: Edge, cx: &mut Context<Self>) {
1229+ if self.modal() || self.exporting().is_some() {
1230+ return;
1231+ }
1232+ let Some(clip) = self
1233+ .session
1234+ .as_ref()
1235+ .and_then(|session| session.lane_clips(lane).get(idx).copied())
1236+ else {
1237+ return;
1238+ };
1239+ self.select((lane, idx), cx);
1240+ self.trim = Some(Trim {
1241+ lane,
1242+ idx,
1243+ edge,
1244+ // Where the edge already is: a press that never moves is not an
1245+ // edit, and `Project::trim` refuses exactly that.
1246+ to: match edge {
1247+ Edge::Start => clip.start,
1248+ Edge::End => clip.end(),
1249+ },
1250+ link: clip.link,
1251+ });
1252+ cx.notify();
1253+ }
1254+
1255+ /// Where the pointer has pulled the edge to, clamped to the room the engine
1256+ /// says that edge has. Along the same bed the ruler is measured on and
1257+ /// against the same duration the boxes are drawn to, so the edge tracks the
1258+ /// pointer exactly.
1259+ fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
1260+ let (duration, fps) = (self.drawn_duration(), self.fps);
1261+ let frac = frac_along(x, self.ruler.get());
1262+ let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
1263+ return;
1264+ };
1265+ let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {
1266+ return;
1267+ };
1268+ trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi);
1269+ cx.notify();
1270+ }
1271+
1272+ /// The release: the whole drag reaches the engine as one edit, so it is one
1273+ /// undo step. The selection survives it -- a trim inserts and removes
1274+ /// nothing, so every index a lane had still names the clip it named.
1275+ fn commit_trim(&mut self, cx: &mut Context<Self>) {
1276+ let Some(trim) = self.trim.take() else {
1277+ return;
1278+ };
1279+ let trimmed = self
1280+ .session
1281+ .as_mut()
1282+ .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to));
1283+ if trimmed {
1284+ self.reset_after_reseek();
1285+ }
1286+ cx.notify();
1287+ }
1288+
1289+ /// The clip as the drag is showing it: an edge under the pointer moves its
1290+ /// own box, and the boxes of the halves linked to it, before anything is
1291+ /// committed. Display only -- the project is not touched until the release.
1292+ fn trimmed(&self, lane: Lane, idx: usize, clip: Clip) -> Clip {
1293+ let Some(trim) = self.trim.filter(|t| {
1294+ (t.lane, t.idx) == (lane, idx) || (t.link.is_some() && t.link == clip.link)
1295+ }) else {
1296+ return clip;
1297+ };
1298+ match trim.edge {
1299+ // The in-point follows the head, exactly as `Project::trim` moves
1300+ // it: what stays on screen plays what it always played.
1301+ Edge::Start => Clip {
1302+ in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start))
1303+ .clamp(0, i64::from(clip.out_frame - 1)) as u32,
1304+ start: trim.to,
1305+ ..clip
1306+ },
1307+ Edge::End => Clip {
1308+ out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1),
1309+ ..clip
1310+ },
1311+ }
1312+ }
1313+
1314+ /// How long the timeline is *drawn* as: its own length, and while a tail is
1315+ /// being dragged the furthest that tail may reach. A bed that ends exactly
1316+ /// at the last frame has nowhere to put a pointer that means "longer", so
1317+ /// without this the last clip on the timeline could be pulled in and never
1318+ /// let back out.
1319+ fn drawn_duration(&self) -> f64 {
1320+ let Some(session) = &self.session else {
1321+ return 0.;
1322+ };
1323+ let duration = session.timeline_duration();
1324+ match self.trim {
1325+ Some(trim) if trim.edge == Edge::End => {
1326+ let (_, hi) = session
1327+ .trim_room(trim.lane, trim.idx, trim.edge)
1328+ .unwrap_or((0, 0));
1329+ duration.max(f64::from(hi) / self.fps)
1330+ }
1331+ _ => duration,
1332+ }
1333+ }
1334+
1171 /// The one way a library row reaches the timeline: the Add button and a row1335 /// The one way a library row reaches the timeline: the Add button and a row
1172 /// dragged onto a lane both come here, so there is a single answer to what1336 /// dragged onto a lane both come here, so there is a single answer to what
1173 /// "add this source" does. The whole source goes in at the playhead as one1337 /// "add this source" does. The whole source goes in at the playhead as one
@@ -1690,11 +1854,9 @@ impl Render for Player {
1690 }1854 }
1691 1855
1692 // Read per render, never cached: a delete shortens the timeline and the1856 // Read per render, never cached: a delete shortens the timeline and the
1693- // timecode, the ruler and the clamp below all have to follow it.1857+ // timecode, the ruler and the clamp below all have to follow it -- and
1694- let duration = self1858+ // so does the room a tail being dragged needs to grow into.
1695- .session1859+ let duration = self.drawn_duration();
1696- .as_ref()
1697- .map_or(0., PlaybackSession::timeline_duration);
1698 // The clock keeps running after the last frame (wall time takes over at1860 // The clock keeps running after the last frame (wall time takes over at
1699 // audio EOF) while the picture is frozen, so the timeline the UI shows is1861 // audio EOF) while the picture is frozen, so the timeline the UI shows is
1700 // the clamped one, pinned to the out-point once playback is done.1862 // the clamped one, pinned to the out-point once playback is done.
@@ -1899,6 +2061,17 @@ impl Render for Player {
1899 }2061 }
1900 return;2062 return;
1901 }2063 }
2064+ // A clip edge is 6 px wide and the pointer leaves it on the
2065+ // first drag, so the gesture is tracked here for the same
2066+ // reason -- and it ends here too when the button came up
2067+ // outside the window, still owing its one edit.
2068+ if this.trim.is_some() {
2069+ match event.pressed_button {
2070+ Some(MouseButton::Left) => this.trim_to(event.position.x, cx),
2071+ _ => this.commit_trim(cx),
2072+ }
2073+ return;
2074+ }
1902 if !this.scrubbing {2075 if !this.scrubbing {
1903 return;2076 return;
1904 }2077 }
@@ -1921,6 +2094,13 @@ impl Render for Player {
1921 this.commit_eq(cx);2094 this.commit_eq(cx);
1922 return;2095 return;
1923 }2096 }
2097+ if this.trim.is_some() {
2098+ // The release lands exactly, then the gesture is
2099+ // written once -- one edit, one undo step.
2100+ this.trim_to(event.position.x, cx);
2101+ this.commit_trim(cx);
2102+ return;
2103+ }
1924 if std::mem::take(&mut this.scrubbing) {2104 if std::mem::take(&mut this.scrubbing) {
1925 this.scrub_to(event.position.x, true, cx);2105 this.scrub_to(event.position.x, true, cx);
1926 }2106 }
@@ -3444,7 +3624,7 @@ impl Player {
3444 let (sel, sel_link) = (self.selected, self.selected_link());3624 let (sel, sel_link) = (self.selected, self.selected_link());
3445 let audio = lane.kind == LaneKind::Audio;3625 let audio = lane.kind == LaneKind::Audio;
3446 let tip: SharedString = format!(3626 let tip: SharedString = format!(
3447- "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut",3627+ "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut",
3448 self.keymap.display(ActionId::Select),3628 self.keymap.display(ActionId::Select),
3449 self.keymap.display(ActionId::SelectPrev),3629 self.keymap.display(ActionId::SelectPrev),
3450 self.keymap.display(ActionId::SelectNext),3630 self.keymap.display(ActionId::SelectNext),
@@ -3502,6 +3682,9 @@ impl Player {
3502 }))3682 }))
3503 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))3683 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
3504 .children(clips.iter().enumerate().map(|(i, clip)| {3684 .children(clips.iter().enumerate().map(|(i, clip)| {
3685+ // What a drag on an edge is showing, which is the clip
3686+ // itself while nothing is being dragged.
3687+ let clip = &self.trimmed(lane, i, *clip);
3505 let (start, len) = (3688 let (start, len) = (
3506 f64::from(clip.start) / self.fps,3689 f64::from(clip.start) / self.fps,
3507 f64::from(clip.len()) / self.fps,3690 f64::from(clip.len()) / self.fps,
@@ -3580,19 +3763,44 @@ impl Player {
3580 .on_mouse_down(3763 .on_mouse_down(
3581 MouseButton::Right,3764 MouseButton::Right,
3582 cx.listener(move |this, event: &MouseDownEvent, _, cx| {3765 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3583- if this.modal() {3766+ this.open_menu(lane, i, event.position, cx);
3584- return;
3585- }
3586- this.select((lane, i), cx);
3587- this.context_menu = Some(ContextMenu {
3588- lane,
3589- idx: i,
3590- at: event.position,
3591- details: false,
3592- });
3593- cx.notify();
3594 }),3767 }),
3595 )3768 )
3769+ // The two strips a drag *lengthens* the clip by,
3770+ // one at each end. They occlude the box behind
3771+ // them, which is what keeps one gesture one thing:
3772+ // a press here trims, a press anywhere else on the
3773+ // box still starts the move to another lane.
3774+ .children([Edge::Start, Edge::End].map(|edge| {
3775+ let mut zone = div()
3776+ .absolute()
3777+ .top_0()
3778+ .h_full()
3779+ .w(px(EDGE_W))
3780+ .occlude()
3781+ .cursor(CursorStyle::ResizeLeftRight)
3782+ .hover(|s| s.bg(rgb(ACCENT)))
3783+ .on_mouse_down(
3784+ MouseButton::Left,
3785+ cx.listener(move |this, _: &MouseDownEvent, _, cx| {
3786+ this.start_trim(lane, i, edge, cx);
3787+ }),
3788+ )
3789+ // Occluded, so the box's own right-button
3790+ // listener never fires here: the menu is
3791+ // the same menu, opened by the same call.
3792+ .on_mouse_down(
3793+ MouseButton::Right,
3794+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3795+ this.open_menu(lane, i, event.position, cx);
3796+ }),
3797+ );
3798+ zone = match edge {
3799+ Edge::Start => zone.left_0(),
3800+ Edge::End => zone.right_0(),
3801+ };
3802+ zone
3803+ }))
3596 // Under the label row, never through it.3804 // Under the label row, never through it.
3597 .children(wave.filter(|_| audio).and_then(|wave| {3805 .children(wave.filter(|_| audio).and_then(|wave| {
3598 let inner: AnyElement = match wave {3806 let inner: AnyElement = match wave {
@@ -5179,6 +5387,64 @@ mod tests {
5179 );5387 );
5180 }5388 }
5181 5389
5390+ /// The trim-a-clip path through the doors the edge drag uses:
5391+ /// [`Player::trim_to`] clamps the pointer with `trim_room` and
5392+ /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
5393+ /// of its file, the sound linked to it follows, the head trim moves the
5394+ /// in-point, and one undo takes a whole gesture back.
5395+ ///
5396+ /// The routing *to* these doors -- the 6 px edge strip claiming the press
5397+ /// the clip's own body-drag would otherwise take -- is gpui hitbox
5398+ /// behaviour (`occlude`) and is not reachable without a window.
5399+ #[test]
5400+ fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
5401+ use engine::project::Edge;
5402+
5403+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5404+ session.set_gain(0.0);
5405+ let whole = session.lane_clips(Lane::V1)[0];
5406+ let full = session.timeline_duration();
5407+ assert_eq!(
5408+ session.trim_room(Lane::V1, 0, Edge::End),
5409+ Some((whole.start + 1, whole.end())),
5410+ "the file's own last frame is how far the tail goes"
5411+ );
5412+ assert!(
5413+ !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
5414+ "it already plays all of it"
5415+ );
5416+
5417+ // Pulled in by a third: the timeline ends earlier and the sound with it.
5418+ let shorter = whole.end() - whole.len() / 3;
5419+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
5420+ assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
5421+ assert_eq!(
5422+ session.lane_clips(Lane::A1)[0].end(),
5423+ shorter,
5424+ "the linked sound was trimmed with the picture"
5425+ );
5426+ assert!(session.timeline_duration() < full, "and plays out earlier");
5427+
5428+ // ...and dragged back out, as far as the file goes and no further.
5429+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
5430+ assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the whole take back");
5431+
5432+ // The head takes the in-point with it, so what plays at the new start
5433+ // is source frame 10 rather than source frame 0.
5434+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
5435+ let head = session.lane_clips(Lane::V1)[0];
5436+ assert_eq!((head.start, head.in_frame), (10, 10));
5437+ assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
5438+ assert_eq!(
5439+ session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
5440+ Some(0),
5441+ "and it may be pulled back out to the file's first frame"
5442+ );
5443+
5444+ assert!(session.undo(), "one step for the whole drag");
5445+ assert_eq!(session.lane_clips(Lane::V1)[0], whole);
5446+ }
5447+
5182 /// The move-a-clip-between-tracks path through the door the drop uses5448 /// The move-a-clip-between-tracks path through the door the drop uses
5183 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the5449 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the
5184 /// *picture* comes from the new row afterwards -- which is what "it plays5450 /// *picture* comes from the new row afterwards -- which is what "it plays
@@ -6226,6 +6492,7 @@ fn main() {
6226 streams: HashMap::new(),6492 streams: HashMap::new(),
6227 clipboard: None,6493 clipboard: None,
6228 scrubbing: false,6494 scrubbing: false,
6495+ trim: None,
6229 last_scrub: Instant::now(),6496 last_scrub: Instant::now(),
6230 last_target: 0,6497 last_target: 0,
6231 export: None,6498 export: None,
crates/engine/src/playback.rsmodified+54 -1
@@ -25,7 +25,7 @@ use crate::color::ColorParams;
25 use crate::decode::{DecodeSession, Frame, Worker};25 use crate::decode::{DecodeSession, Frame, Worker};
26 use crate::demux::{Demuxer, VideoMeta};26 use crate::demux::{Demuxer, VideoMeta};
27 use crate::eq::EqParams;27 use crate::eq::EqParams;
28-use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};28+use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span};
29 use crate::scale::{Composer, FitPolicy};29 use crate::scale::{Composer, FitPolicy};
30 30
31 /// How long the feeder waits out a full ring. The ring holds a second, so this31 /// How long the feeder waits out a full ring. The ring holds a second, so this
@@ -122,6 +122,15 @@ pub struct PlaybackSession {
122 /// The edit list. Everything a caller says in seconds is a *timeline*122 /// The edit list. Everything a caller says in seconds is a *timeline*
123 /// position; only this maps it onto the file.123 /// position; only this maps it onto the file.
124 project: Project,124 project: Project,
125+ /// How many frames each source actually holds, indexed exactly as
126+ /// [`Project::sources`] is and grown with it. The project itself does not
127+ /// know -- a clip names a source by index and carries its own range -- and
128+ /// [`Self::trim_clip`] is the one edit that could ask for frames past the
129+ /// end of a file, which is a save that would not open again
130+ /// ([`Self::open_project`] refuses one by name). Append-only for
131+ /// `sources`'s reason: an index handed out stays valid, undone import or
132+ /// not.
133+ counts: Vec<u32>,
125 /// What the current video worker was opened for: where it sits on the134 /// What the current video worker was opened for: where it sits on the
126 /// timeline, how long it runs, and which source frame it started at --135 /// timeline, how long it runs, and which source frame it started at --
127 /// together they rewrite a source frame index into a timeline one. Not a136 /// together they rewrite a source frame index into a timeline one. Not a
@@ -185,6 +194,7 @@ impl PlaybackSession {
185 audio,194 audio,
186 audio_disabled,195 audio_disabled,
187 project,196 project,
197+ counts: vec![meta.frame_count],
188 span,198 span,
189 eos: false,199 eos: false,
190 })200 })
@@ -310,6 +320,7 @@ impl PlaybackSession {
310 audio,320 audio,
311 audio_disabled,321 audio_disabled,
312 project,322 project,
323+ counts,
313 span,324 span,
314 eos: false,325 eos: false,
315 };326 };
@@ -591,6 +602,45 @@ impl PlaybackSession {
591 self.edit(|p| p.move_to_lane(from, idx, to))602 self.edit(|p| p.move_to_lane(from, idx, to))
592 }603 }
593 604
605+ /// Drags one end of that clip to timeline frame `to`, changing how much of
606+ /// its source it plays and nothing else on the lane -- see [`Project::trim`]
607+ /// for the walls it is clamped by, which this fills the source lengths in
608+ /// for. One undo step per call, so a front-end calls it once, at the release
609+ /// of the drag. Reseeks like every other edit, which is what makes the
610+ /// picture (and the sound) follow a new in-point straight away. `false` for
611+ /// a bad index and for an edge already where it was asked to go.
612+ ///
613+ /// A *frame*, where the rest of this type takes seconds: a drag has already
614+ /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
615+ /// answer is in frames -- converting it back through seconds would be a
616+ /// rounding step between the width drawn and the width committed.
617+ pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
618+ // Spelled out rather than through `edit`, whose closure cannot hold a
619+ // second borrow of the session while it has the project.
620+ if !self.project.trim(lane, idx, edge, to, &self.counts) {
621+ return false;
622+ }
623+ let now = self.now();
624+ self.seek(now);
625+ true
626+ }
627+
628+ /// Where that edge may land, `(first, last)` timeline frame inclusive: what
629+ /// a drag clamps the pointer to so the box it draws is the box
630+ /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
631+ pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
632+ self.project.trim_room(lane, idx, edge, &self.counts)
633+ }
634+
635+ /// Records how long a source is, for a source index that may be one
636+ /// `Project::import` just made or one it handed back. See [`Self::counts`].
637+ fn note_frames(&mut self, source: usize, frames: u32) {
638+ if source == self.counts.len() {
639+ self.counts.push(frames);
640+ }
641+ debug_assert_eq!(self.counts.len(), self.project.sources().len());
642+ }
643+
594 /// The clip the picture is coming from at `timeline_secs`: the lane it sits644 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
595 /// on and its index there, by the same topmost-lane-wins rule the decoder645 /// on and its index there, by the same topmost-lane-wins rule the decoder
596 /// follows. `None` over a gap and past the end. What a card that grades646 /// follows. `None` over a gap and past the end. What a card that grades
@@ -729,6 +779,7 @@ impl PlaybackSession {
729 let first = self.first_audio()?;779 let first = self.first_audio()?;
730 audio_matches(&wanted, &first)?;780 audio_matches(&wanted, &first)?;
731 let source = self.project.import(path, stream);781 let source = self.project.import(path, stream);
782+ self.note_frames(source, frames.max(1));
732 let clip = Clip {783 let clip = Clip {
733 start: 0,784 start: 0,
734 in_frame: 0,785 in_frame: 0,
@@ -820,6 +871,7 @@ impl PlaybackSession {
820 871
821 let old_end = self.timeline_duration();872 let old_end = self.timeline_duration();
822 let source = self.project.import(path, 0);873 let source = self.project.import(path, 0);
874+ self.note_frames(source, meta.frame_count);
823 // Refused only for an unknown index, and this one just came from `import`.875 // Refused only for an unknown index, and this one just came from `import`.
824 self.project.append_clip(source, meta.frame_count);876 self.project.append_clip(source, meta.frame_count);
825 // Reseek like any other edit, even though nothing before the playhead877 // Reseek like any other edit, even though nothing before the playhead
@@ -852,6 +904,7 @@ impl PlaybackSession {
852 904
853 let old_end = self.timeline_duration();905 let old_end = self.timeline_duration();
854 let source = self.project.import(path, 0);906 let source = self.project.import(path, 0);
907+ self.note_frames(source, frames);
855 let at = self.project.timeline_frames();908 let at = self.project.timeline_frames();
856 self.project.place(909 self.project.place(
857 Lane::A1,910 Lane::A1,
crates/engine/src/project.rsmodified+254 -0
@@ -212,6 +212,17 @@ impl LaneData {
212 }212 }
213 }213 }
214 214
215+/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
216+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
217+pub enum Edge {
218+ /// Its first timeline frame; moving it changes where in the source the clip
219+ /// starts reading, so the picture behind the edge slides with it.
220+ Start,
221+ /// One past its last timeline frame; moving it only says how much of the
222+ /// source to keep.
223+ End,
224+}
225+
215 /// What a lane holds over one stretch of the timeline: either a placed clip or226 /// What a lane holds over one stretch of the timeline: either a placed clip or
216 /// a gap. Returned already trimmed to the position it was asked about, so a227 /// a gap. Returned already trimmed to the position it was asked about, so a
217 /// caller can hand `len` straight to a decoder (or to a black-frame generator).228 /// caller can hand `len` straight to a decoder (or to a black-frame generator).
@@ -1031,6 +1042,140 @@ impl Project {
1031 true1042 true
1032 }1043 }
1033 1044
1045+ /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
1046+ /// the drag on a clip's end that makes it play more or less of its source.
1047+ /// The rest of the lane stays exactly where it is (nothing ripples), so what
1048+ /// a shortened clip leaves behind is a gap and what a lengthened one takes
1049+ /// is room that was already empty. One snapshot, so a whole drag is one
1050+ /// [`Project::undo`] -- commit once, at the release, rather than per pointer
1051+ /// sample. Changes the timeline->source mapping: the caller must reseek.
1052+ ///
1053+ /// [`Edge::Start`] moves the in-point with it: the frames that stay play
1054+ /// exactly what they played before, which is what makes this a trim and not
1055+ /// a slip.
1056+ ///
1057+ /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
1058+ /// legal means "as far as it goes", and stopping the box there is the
1059+ /// affordance. The walls are: one frame of clip always survives, an edge
1060+ /// never crosses the neighbouring clip on its own lane, an in-point never
1061+ /// walks back past the source's first frame, and an out-point never runs
1062+ /// past `source_frames[clip.source]` -- the caller's table of how long each
1063+ /// source actually is ([`Project`] does not know, and a clip ending past its
1064+ /// file's last frame is a save that will not open again; see
1065+ /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
1066+ /// there may not grow at all.
1067+ ///
1068+ /// Linked clips trim *together*, to one clamped edge: a link is one span on
1069+ /// however many lanes ([`links_are_consistent`]), so a picture trimmed away
1070+ /// from its sound would be a group no save could load. The room is therefore
1071+ /// what every member of the group has -- the tightest wall wins.
1072+ ///
1073+ /// `false`, changing nothing and costing no undo step, for an index that is
1074+ /// not there and for an edge that is already where it was asked to go.
1075+ pub fn trim(
1076+ &mut self,
1077+ lane: Lane,
1078+ idx: usize,
1079+ edge: Edge,
1080+ to: u32,
1081+ source_frames: &[u32],
1082+ ) -> bool {
1083+ let (Some((lo, hi)), Some(clip)) = (
1084+ self.trim_room(lane, idx, edge, source_frames),
1085+ self.lane(lane).get(idx).copied(),
1086+ ) else {
1087+ return false;
1088+ };
1089+ let to = to.clamp(lo, hi);
1090+ let at = match edge {
1091+ Edge::Start => clip.start,
1092+ Edge::End => clip.end(),
1093+ };
1094+ if to == at {
1095+ return false;
1096+ }
1097+ self.snapshot();
1098+ for (l, i) in self.group_of(lane, idx).expect("checked above") {
1099+ let c = &mut self.lanes[l].clips[i];
1100+ match edge {
1101+ Edge::Start => {
1102+ // Non-negative by `lo`, which is what keeps the in-point on
1103+ // the source.
1104+ c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32;
1105+ c.start = to;
1106+ }
1107+ Edge::End => c.out_frame = c.in_frame + (to - c.start),
1108+ }
1109+ debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1110+ }
1111+ true
1112+ }
1113+
1114+ /// How far that edge may travel, `(first, last)` timeline frame inclusive --
1115+ /// the walls [`trim`](Project::trim) clamps to, without moving anything.
1116+ /// What a front-end drawing the box *during* a drag asks, so the live width
1117+ /// is the width the release will commit and an edge stops under the pointer
1118+ /// rather than snapping back. `None` for an index that is not there.
1119+ pub fn trim_room(
1120+ &self,
1121+ lane: Lane,
1122+ idx: usize,
1123+ edge: Edge,
1124+ source_frames: &[u32],
1125+ ) -> Option<(u32, u32)> {
1126+ let (mut lo, mut hi) = (u32::MIN, u32::MAX);
1127+ for (l, i) in self.group_of(lane, idx)? {
1128+ let clips = &self.lanes[l].clips;
1129+ let c = clips[i];
1130+ let (member_lo, member_hi) = match edge {
1131+ Edge::Start => (
1132+ // Back to the source's own first frame, and never over the
1133+ // clip in front of it.
1134+ (c.start - c.in_frame).max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1135+ c.end() - 1,
1136+ ),
1137+ Edge::End => (
1138+ c.start + 1,
1139+ // Out to whatever is left of the source, and never over the
1140+ // clip behind it.
1141+ c.start
1142+ .saturating_add(
1143+ source_frames
1144+ .get(c.source)
1145+ .copied()
1146+ .unwrap_or(c.out_frame)
1147+ .saturating_sub(c.in_frame),
1148+ )
1149+ .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1150+ ),
1151+ };
1152+ lo = lo.max(member_lo);
1153+ hi = hi.min(member_hi);
1154+ }
1155+ // `hi.max(lo)`: for a clip the invariants hold for, the range always
1156+ // contains the edge's own place, and a caller's wrong `source_frames`
1157+ // must not become an empty range (or a panicking `clamp`) here.
1158+ Some((lo, hi.max(lo)))
1159+ }
1160+
1161+ /// The clips that move as one with the clip at `idx` of `lane` -- itself and
1162+ /// whatever carries its link on the other lanes -- as `(lane storage index,
1163+ /// clip index)` pairs. `None` for an index that is not there.
1164+ fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
1165+ let clip = *self.lane(lane).get(idx)?;
1166+ Some(match clip.link {
1167+ Some(link) => self
1168+ .lanes
1169+ .iter()
1170+ .enumerate()
1171+ .filter_map(|(l, data)| {
1172+ Some((l, data.clips.iter().position(|c| c.link == Some(link))?))
1173+ })
1174+ .collect(),
1175+ None => vec![(self.index(lane).expect("the clip was found on it"), idx)],
1176+ })
1177+ }
1178+
1034 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one1179 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
1035 /// new group, pushing everything from there on later by its length in1180 /// new group, pushing everything from there on later by its length in
1036 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip1181 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
@@ -2093,6 +2238,115 @@ mod tests {
2093 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);2238 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
2094 }2239 }
2095 2240
2241+ /// How long `FILE` is, which is what a trim's tail is allowed to reach:
2242+ /// [`three`] cuts up all nine of its frames.
2243+ const SRC: &[u32] = &[9];
2244+
2245+ /// The drag on a clip's tail: it plays less (or more) of its source, nothing
2246+ /// else on the lane moves, and every wall stops the edge rather than
2247+ /// refusing the gesture.
2248+ #[test]
2249+ fn trimming_the_tail_stops_at_every_wall() {
2250+ let mut p = three();
2251+
2252+ // Pulled in: a gap opens behind it and the clip after it stays put.
2253+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2254+ assert_eq!(
2255+ shape(&p)[0],
2256+ vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
2257+ );
2258+ assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
2259+ assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
2260+
2261+ // ...and back out, no further than the clip behind it.
2262+ assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
2263+ assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour");
2264+ assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall");
2265+
2266+ // One frame of clip always survives, however far back the pointer went.
2267+ assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
2268+ assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
2269+
2270+ // The last clip has no neighbour, so what stops it is the file: nine
2271+ // frames is nine frames.
2272+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
2273+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2274+ assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
2275+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
2276+ // A source nobody told us the length of may not grow at all -- an
2277+ // out-point past the end of a file is a save that will not open again.
2278+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
2279+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
2280+ }
2281+
2282+ /// The head pulled in takes the in-point with it -- what stays plays what it
2283+ /// always played -- and stops at the source's own first frame.
2284+ #[test]
2285+ fn trimming_the_head_moves_the_in_point() {
2286+ let mut p = three();
2287+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2288+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front");
2289+ assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
2290+ assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
2291+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
2292+ assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
2293+ // One frame survives here too.
2294+ assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
2295+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
2296+
2297+ // A clip that does not begin at its source's first frame: its head goes
2298+ // back to source frame 0 and not one frame further.
2299+ let mut p = Project::single(FILE, 9);
2300+ assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
2301+ assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
2302+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
2303+ assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
2304+ }
2305+
2306+ /// Linked halves trim as one: a link is one span on however many lanes, so
2307+ /// the sound follows the picture's edge -- and the tightest wall of the two
2308+ /// is what stops both.
2309+ #[test]
2310+ fn linked_halves_trim_together() {
2311+ let mut p = three();
2312+ let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
2313+ assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
2314+
2315+ assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
2316+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
2317+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
2318+ assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it");
2319+ assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
2320+ links_are_consistent(&p.lanes).expect("one id per lane, one span");
2321+
2322+ // Something in the way on the *audio* lane stops the picture's tail as
2323+ // well: the group can only go as far as its tightest member.
2324+ assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
2325+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2326+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
2327+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
2328+ links_are_consistent(&p.lanes).expect("still one span");
2329+ }
2330+
2331+ /// A whole drag is one undo step -- the front-end commits once, at the
2332+ /// release -- and an edge asked to stay where it is costs none at all.
2333+ #[test]
2334+ fn a_trim_is_one_undo_step() {
2335+ let mut p = three();
2336+ let before = shape(&p);
2337+ let history = p.history.len();
2338+
2339+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2340+ assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
2341+ assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
2342+ assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
2343+ assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
2344+ assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
2345+
2346+ assert!(p.undo());
2347+ assert_eq!(shape(&p), before, "both halves back, in one step");
2348+ }
2349+
2096 /// A moved half stays in its group: a link names a span, not a lane, so the2350 /// A moved half stays in its group: a link names a span, not a lane, so the
2097 /// picture on `V2` is still the same take as the sound under it on `A1`.2351 /// picture on `V2` is still the same take as the sound under it on `A1`.
2098 #[test]2352 #[test]
crates/engine/tests/saveload.rsmodified+38 -0
@@ -100,6 +100,44 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() {
100 std::fs::remove_dir_all(&dir).expect("cleanup");100 std::fs::remove_dir_all(&dir).expect("cleanup");
101 }101 }
102 102
103+/// Why a trim's tail stops where the file ends: a clip reaching past the last
104+/// frame of its source is a project that will not open again (`open_project`
105+/// refuses it by name). Pulled in on both ends and then dragged out as far as
106+/// the pointer can ask for, the save still comes back as itself.
107+#[test]
108+fn a_trimmed_timeline_saves_and_opens_again() {
109+ use engine::project::Edge;
110+
111+ let dir = scratch("trim");
112+ let media = copy_in(&dir, "test_av.mp4");
113+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
114+ session.set_gain(0.0);
115+ let whole = session.clip_at(0).expect("one clip");
116+
117+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, whole.end() / 2));
118+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 5));
119+ let path = dir.join("trimmed.edith");
120+ session.save_project(&path).expect("save");
121+ let loaded = PlaybackSession::open_project(&path).expect("a trimmed project opens");
122+ assert_eq!(
123+ loaded.clip_at(0).map(|c| (c.start, c.in_frame, c.out_frame)),
124+ Some((5, 5, whole.end() / 2)),
125+ "the trimmed range is what came back"
126+ );
127+
128+ // A hand that keeps pulling: the tail stops at the file's own last frame,
129+ // and the save of *that* opens too.
130+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, u32::MAX));
131+ assert_eq!(
132+ session.clip_at(0).expect("still one clip").out_frame,
133+ whole.out_frame,
134+ "as far as the file goes and not one frame further"
135+ );
136+ session.save_project(&path).expect("save");
137+ PlaybackSession::open_project(&path).expect("and it still opens");
138+ std::fs::remove_dir_all(&dir).expect("cleanup");
139+}
140+
103 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline141 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline
104 /// with something to lose in every field.142 /// with something to lose in every field.
105 fn edited(dir: &Path) -> PlaybackSession {143 fn edited(dir: &Path) -> PlaybackSession {