forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-a908d3dc90d179d74'

Browse files at this commit

e1fb59d564d70d37a7e6e32f4c946228988fbf37Ahmet Kaan GümüşParent: 2dd4b74affa0a3
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
@@ -1700,11 +1864,9 @@ impl Render for Player {
1700 }1864 }
1701 1865
1702 // Read per render, never cached: a delete shortens the timeline and the1866 // Read per render, never cached: a delete shortens the timeline and the
1703- // timecode, the ruler and the clamp below all have to follow it.1867+ // timecode, the ruler and the clamp below all have to follow it -- and
1704- let duration = self1868+ // so does the room a tail being dragged needs to grow into.
1705- .session1869+ let duration = self.drawn_duration();
1706- .as_ref()
1707- .map_or(0., PlaybackSession::timeline_duration);
1708 // The clock keeps running after the last frame (wall time takes over at1870 // The clock keeps running after the last frame (wall time takes over at
1709 // audio EOF) while the picture is frozen, so the timeline the UI shows is1871 // audio EOF) while the picture is frozen, so the timeline the UI shows is
1710 // the clamped one, pinned to the out-point once playback is done.1872 // the clamped one, pinned to the out-point once playback is done.
@@ -1909,6 +2071,17 @@ impl Render for Player {
1909 }2071 }
1910 return;2072 return;
1911 }2073 }
2074+ // A clip edge is 6 px wide and the pointer leaves it on the
2075+ // first drag, so the gesture is tracked here for the same
2076+ // reason -- and it ends here too when the button came up
2077+ // outside the window, still owing its one edit.
2078+ if this.trim.is_some() {
2079+ match event.pressed_button {
2080+ Some(MouseButton::Left) => this.trim_to(event.position.x, cx),
2081+ _ => this.commit_trim(cx),
2082+ }
2083+ return;
2084+ }
1912 if !this.scrubbing {2085 if !this.scrubbing {
1913 return;2086 return;
1914 }2087 }
@@ -1931,6 +2104,13 @@ impl Render for Player {
1931 this.commit_eq(cx);2104 this.commit_eq(cx);
1932 return;2105 return;
1933 }2106 }
2107+ if this.trim.is_some() {
2108+ // The release lands exactly, then the gesture is
2109+ // written once -- one edit, one undo step.
2110+ this.trim_to(event.position.x, cx);
2111+ this.commit_trim(cx);
2112+ return;
2113+ }
1934 if std::mem::take(&mut this.scrubbing) {2114 if std::mem::take(&mut this.scrubbing) {
1935 this.scrub_to(event.position.x, true, cx);2115 this.scrub_to(event.position.x, true, cx);
1936 }2116 }
@@ -3454,7 +3634,7 @@ impl Player {
3454 let (sel, sel_link) = (self.selected, self.selected_link());3634 let (sel, sel_link) = (self.selected, self.selected_link());
3455 let audio = lane.kind == LaneKind::Audio;3635 let audio = lane.kind == LaneKind::Audio;
3456 let tip: SharedString = format!(3636 let tip: SharedString = format!(
3457- "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut",3637+ "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut",
3458 self.keymap.display(ActionId::Select),3638 self.keymap.display(ActionId::Select),
3459 self.keymap.display(ActionId::SelectPrev),3639 self.keymap.display(ActionId::SelectPrev),
3460 self.keymap.display(ActionId::SelectNext),3640 self.keymap.display(ActionId::SelectNext),
@@ -3512,6 +3692,9 @@ impl Player {
3512 }))3692 }))
3513 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))3693 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
3514 .children(clips.iter().enumerate().map(|(i, clip)| {3694 .children(clips.iter().enumerate().map(|(i, clip)| {
3695+ // What a drag on an edge is showing, which is the clip
3696+ // itself while nothing is being dragged.
3697+ let clip = &self.trimmed(lane, i, *clip);
3515 let (start, len) = (3698 let (start, len) = (
3516 f64::from(clip.start) / self.fps,3699 f64::from(clip.start) / self.fps,
3517 f64::from(clip.len()) / self.fps,3700 f64::from(clip.len()) / self.fps,
@@ -3590,19 +3773,44 @@ impl Player {
3590 .on_mouse_down(3773 .on_mouse_down(
3591 MouseButton::Right,3774 MouseButton::Right,
3592 cx.listener(move |this, event: &MouseDownEvent, _, cx| {3775 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3593- if this.modal() {3776+ this.open_menu(lane, i, event.position, cx);
3594- return;
3595- }
3596- this.select((lane, i), cx);
3597- this.context_menu = Some(ContextMenu {
3598- lane,
3599- idx: i,
3600- at: event.position,
3601- details: false,
3602- });
3603- cx.notify();
3604 }),3777 }),
3605 )3778 )
3779+ // The two strips a drag *lengthens* the clip by,
3780+ // one at each end. They occlude the box behind
3781+ // them, which is what keeps one gesture one thing:
3782+ // a press here trims, a press anywhere else on the
3783+ // box still starts the move to another lane.
3784+ .children([Edge::Start, Edge::End].map(|edge| {
3785+ let mut zone = div()
3786+ .absolute()
3787+ .top_0()
3788+ .h_full()
3789+ .w(px(EDGE_W))
3790+ .occlude()
3791+ .cursor(CursorStyle::ResizeLeftRight)
3792+ .hover(|s| s.bg(rgb(ACCENT)))
3793+ .on_mouse_down(
3794+ MouseButton::Left,
3795+ cx.listener(move |this, _: &MouseDownEvent, _, cx| {
3796+ this.start_trim(lane, i, edge, cx);
3797+ }),
3798+ )
3799+ // Occluded, so the box's own right-button
3800+ // listener never fires here: the menu is
3801+ // the same menu, opened by the same call.
3802+ .on_mouse_down(
3803+ MouseButton::Right,
3804+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3805+ this.open_menu(lane, i, event.position, cx);
3806+ }),
3807+ );
3808+ zone = match edge {
3809+ Edge::Start => zone.left_0(),
3810+ Edge::End => zone.right_0(),
3811+ };
3812+ zone
3813+ }))
3606 // Under the label row, never through it.3814 // Under the label row, never through it.
3607 .children(wave.filter(|_| audio).and_then(|wave| {3815 .children(wave.filter(|_| audio).and_then(|wave| {
3608 let inner: AnyElement = match wave {3816 let inner: AnyElement = match wave {
@@ -5189,6 +5397,64 @@ mod tests {
5189 );5397 );
5190 }5398 }
5191 5399
5400+ /// The trim-a-clip path through the doors the edge drag uses:
5401+ /// [`Player::trim_to`] clamps the pointer with `trim_room` and
5402+ /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
5403+ /// of its file, the sound linked to it follows, the head trim moves the
5404+ /// in-point, and one undo takes a whole gesture back.
5405+ ///
5406+ /// The routing *to* these doors -- the 6 px edge strip claiming the press
5407+ /// the clip's own body-drag would otherwise take -- is gpui hitbox
5408+ /// behaviour (`occlude`) and is not reachable without a window.
5409+ #[test]
5410+ fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
5411+ use engine::project::Edge;
5412+
5413+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5414+ session.set_gain(0.0);
5415+ let whole = session.lane_clips(Lane::V1)[0];
5416+ let full = session.timeline_duration();
5417+ assert_eq!(
5418+ session.trim_room(Lane::V1, 0, Edge::End),
5419+ Some((whole.start + 1, whole.end())),
5420+ "the file's own last frame is how far the tail goes"
5421+ );
5422+ assert!(
5423+ !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
5424+ "it already plays all of it"
5425+ );
5426+
5427+ // Pulled in by a third: the timeline ends earlier and the sound with it.
5428+ let shorter = whole.end() - whole.len() / 3;
5429+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
5430+ assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
5431+ assert_eq!(
5432+ session.lane_clips(Lane::A1)[0].end(),
5433+ shorter,
5434+ "the linked sound was trimmed with the picture"
5435+ );
5436+ assert!(session.timeline_duration() < full, "and plays out earlier");
5437+
5438+ // ...and dragged back out, as far as the file goes and no further.
5439+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
5440+ assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the whole take back");
5441+
5442+ // The head takes the in-point with it, so what plays at the new start
5443+ // is source frame 10 rather than source frame 0.
5444+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
5445+ let head = session.lane_clips(Lane::V1)[0];
5446+ assert_eq!((head.start, head.in_frame), (10, 10));
5447+ assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
5448+ assert_eq!(
5449+ session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
5450+ Some(0),
5451+ "and it may be pulled back out to the file's first frame"
5452+ );
5453+
5454+ assert!(session.undo(), "one step for the whole drag");
5455+ assert_eq!(session.lane_clips(Lane::V1)[0], whole);
5456+ }
5457+
5192 /// The move-a-clip-between-tracks path through the door the drop uses5458 /// The move-a-clip-between-tracks path through the door the drop uses
5193 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the5459 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the
5194 /// *picture* comes from the new row afterwards -- which is what "it plays5460 /// *picture* comes from the new row afterwards -- which is what "it plays
@@ -6236,6 +6502,7 @@ fn main() {
6236 streams: HashMap::new(),6502 streams: HashMap::new(),
6237 clipboard: None,6503 clipboard: None,
6238 scrubbing: false,6504 scrubbing: false,
6505+ trim: None,
6239 last_scrub: Instant::now(),6506 last_scrub: Instant::now(),
6240 last_target: 0,6507 last_target: 0,
6241 export: None,6508 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
@@ -191,6 +200,7 @@ impl PlaybackSession {
191 audio,200 audio,
192 audio_disabled,201 audio_disabled,
193 project,202 project,
203+ counts: vec![meta.frame_count],
194 span,204 span,
195 eos: false,205 eos: false,
196 })206 })
@@ -316,6 +326,7 @@ impl PlaybackSession {
316 audio,326 audio,
317 audio_disabled,327 audio_disabled,
318 project,328 project,
329+ counts,
319 span,330 span,
320 eos: false,331 eos: false,
321 };332 };
@@ -624,6 +635,45 @@ impl PlaybackSession {
624 self.edit(|p| p.move_to_lane(from, idx, to))635 self.edit(|p| p.move_to_lane(from, idx, to))
625 }636 }
626 637
638+ /// Drags one end of that clip to timeline frame `to`, changing how much of
639+ /// its source it plays and nothing else on the lane -- see [`Project::trim`]
640+ /// for the walls it is clamped by, which this fills the source lengths in
641+ /// for. One undo step per call, so a front-end calls it once, at the release
642+ /// of the drag. Reseeks like every other edit, which is what makes the
643+ /// picture (and the sound) follow a new in-point straight away. `false` for
644+ /// a bad index and for an edge already where it was asked to go.
645+ ///
646+ /// A *frame*, where the rest of this type takes seconds: a drag has already
647+ /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
648+ /// answer is in frames -- converting it back through seconds would be a
649+ /// rounding step between the width drawn and the width committed.
650+ pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
651+ // Spelled out rather than through `edit`, whose closure cannot hold a
652+ // second borrow of the session while it has the project.
653+ if !self.project.trim(lane, idx, edge, to, &self.counts) {
654+ return false;
655+ }
656+ let now = self.now();
657+ self.seek(now);
658+ true
659+ }
660+
661+ /// Where that edge may land, `(first, last)` timeline frame inclusive: what
662+ /// a drag clamps the pointer to so the box it draws is the box
663+ /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
664+ pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
665+ self.project.trim_room(lane, idx, edge, &self.counts)
666+ }
667+
668+ /// Records how long a source is, for a source index that may be one
669+ /// `Project::import` just made or one it handed back. See [`Self::counts`].
670+ fn note_frames(&mut self, source: usize, frames: u32) {
671+ if source == self.counts.len() {
672+ self.counts.push(frames);
673+ }
674+ debug_assert_eq!(self.counts.len(), self.project.sources().len());
675+ }
676+
627 /// The clip the picture is coming from at `timeline_secs`: the lane it sits677 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
628 /// on and its index there, by the same topmost-lane-wins rule the decoder678 /// on and its index there, by the same topmost-lane-wins rule the decoder
629 /// follows. `None` over a gap and past the end. What a card that grades679 /// follows. `None` over a gap and past the end. What a card that grades
@@ -762,6 +812,7 @@ impl PlaybackSession {
762 let first = self.first_audio()?;812 let first = self.first_audio()?;
763 audio_matches(&wanted, &first)?;813 audio_matches(&wanted, &first)?;
764 let source = self.project.import(path, stream);814 let source = self.project.import(path, stream);
815+ self.note_frames(source, frames.max(1));
765 let clip = Clip {816 let clip = Clip {
766 start: 0,817 start: 0,
767 in_frame: 0,818 in_frame: 0,
@@ -854,6 +905,7 @@ impl PlaybackSession {
854 905
855 let old_end = self.timeline_duration();906 let old_end = self.timeline_duration();
856 let source = self.project.import(path, 0);907 let source = self.project.import(path, 0);
908+ self.note_frames(source, meta.frame_count);
857 // Refused only for an unknown index, and this one just came from `import`.909 // Refused only for an unknown index, and this one just came from `import`.
858 self.project.append_clip(source, meta.frame_count);910 self.project.append_clip(source, meta.frame_count);
859 // Reseek like any other edit, even though nothing before the playhead911 // Reseek like any other edit, even though nothing before the playhead
@@ -886,6 +938,7 @@ impl PlaybackSession {
886 938
887 let old_end = self.timeline_duration();939 let old_end = self.timeline_duration();
888 let source = self.project.import(path, 0);940 let source = self.project.import(path, 0);
941+ self.note_frames(source, frames);
889 let at = self.project.timeline_frames();942 let at = self.project.timeline_frames();
890 self.project.place(943 self.project.place(
891 Lane::A1,944 Lane::A1,
crates/engine/src/project.rsmodified+283 -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).
@@ -1044,6 +1055,145 @@ impl Project {
1044 true1055 true
1045 }1056 }
1046 1057
1058+ /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
1059+ /// the drag on a clip's end that makes it play more or less of its source.
1060+ /// The rest of the lane stays exactly where it is (nothing ripples), so what
1061+ /// a shortened clip leaves behind is a gap and what a lengthened one takes
1062+ /// is room that was already empty. One snapshot, so a whole drag is one
1063+ /// [`Project::undo`] -- commit once, at the release, rather than per pointer
1064+ /// sample. Changes the timeline->source mapping: the caller must reseek.
1065+ ///
1066+ /// [`Edge::Start`] moves the in-point with it: the frames that stay play
1067+ /// exactly what they played before, which is what makes this a trim and not
1068+ /// a slip.
1069+ ///
1070+ /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
1071+ /// legal means "as far as it goes", and stopping the box there is the
1072+ /// affordance. The walls are: one frame of clip always survives, an edge
1073+ /// never crosses the neighbouring clip on its own lane, an in-point never
1074+ /// walks back past the source's first frame, and an out-point never runs
1075+ /// past `source_frames[clip.source]` -- the caller's table of how long each
1076+ /// source actually is ([`Project`] does not know, and a clip ending past its
1077+ /// file's last frame is a save that will not open again; see
1078+ /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
1079+ /// there may not grow at all.
1080+ ///
1081+ /// Linked clips trim *together*, to one clamped edge: a link is one span on
1082+ /// however many lanes ([`links_are_consistent`]), so a picture trimmed away
1083+ /// from its sound would be a group no save could load. The room is therefore
1084+ /// what every member of the group has -- the tightest wall wins.
1085+ ///
1086+ /// `false`, changing nothing and costing no undo step, for an index that is
1087+ /// not there and for an edge that is already where it was asked to go.
1088+ pub fn trim(
1089+ &mut self,
1090+ lane: Lane,
1091+ idx: usize,
1092+ edge: Edge,
1093+ to: u32,
1094+ source_frames: &[u32],
1095+ ) -> bool {
1096+ let (Some((lo, hi)), Some(clip)) = (
1097+ self.trim_room(lane, idx, edge, source_frames),
1098+ self.lane(lane).get(idx).copied(),
1099+ ) else {
1100+ return false;
1101+ };
1102+ let to = to.clamp(lo, hi);
1103+ let at = match edge {
1104+ Edge::Start => clip.start,
1105+ Edge::End => clip.end(),
1106+ };
1107+ if to == at {
1108+ return false;
1109+ }
1110+ self.snapshot();
1111+ for (l, i) in self.group_of(lane, idx).expect("checked above") {
1112+ let c = &mut self.lanes[l].clips[i];
1113+ match edge {
1114+ Edge::Start => {
1115+ // Non-negative by `lo`, which is what keeps the in-point on
1116+ // the source.
1117+ c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32;
1118+ c.start = to;
1119+ }
1120+ Edge::End => c.out_frame = c.in_frame + (to - c.start),
1121+ }
1122+ debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1123+ }
1124+ true
1125+ }
1126+
1127+ /// How far that edge may travel, `(first, last)` timeline frame inclusive --
1128+ /// the walls [`trim`](Project::trim) clamps to, without moving anything.
1129+ /// What a front-end drawing the box *during* a drag asks, so the live width
1130+ /// is the width the release will commit and an edge stops under the pointer
1131+ /// rather than snapping back. `None` for an index that is not there.
1132+ pub fn trim_room(
1133+ &self,
1134+ lane: Lane,
1135+ idx: usize,
1136+ edge: Edge,
1137+ source_frames: &[u32],
1138+ ) -> Option<(u32, u32)> {
1139+ let (mut lo, mut hi) = (u32::MIN, u32::MAX);
1140+ for (l, i) in self.group_of(lane, idx)? {
1141+ let clips = &self.lanes[l].clips;
1142+ let c = clips[i];
1143+ let (member_lo, member_hi) = match edge {
1144+ Edge::Start => (
1145+ // Back to the source's own first frame, and never over the
1146+ // clip in front of it. Saturating because a clip may hold
1147+ // *more* head than the timeline has room for -- a ripple
1148+ // delete slides a clip back to frame 0 with its in-point
1149+ // wherever the cut left it -- and frame 0 is the other wall.
1150+ c.start
1151+ .saturating_sub(c.in_frame)
1152+ .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1153+ c.end() - 1,
1154+ ),
1155+ Edge::End => (
1156+ c.start + 1,
1157+ // Out to whatever is left of the source, and never over the
1158+ // clip behind it.
1159+ c.start
1160+ .saturating_add(
1161+ source_frames
1162+ .get(c.source)
1163+ .copied()
1164+ .unwrap_or(c.out_frame)
1165+ .saturating_sub(c.in_frame),
1166+ )
1167+ .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1168+ ),
1169+ };
1170+ lo = lo.max(member_lo);
1171+ hi = hi.min(member_hi);
1172+ }
1173+ // `hi.max(lo)`: for a clip the invariants hold for, the range always
1174+ // contains the edge's own place, and a caller's wrong `source_frames`
1175+ // must not become an empty range (or a panicking `clamp`) here.
1176+ Some((lo, hi.max(lo)))
1177+ }
1178+
1179+ /// The clips that move as one with the clip at `idx` of `lane` -- itself and
1180+ /// whatever carries its link on the other lanes -- as `(lane storage index,
1181+ /// clip index)` pairs. `None` for an index that is not there.
1182+ fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
1183+ let clip = *self.lane(lane).get(idx)?;
1184+ Some(match clip.link {
1185+ Some(link) => self
1186+ .lanes
1187+ .iter()
1188+ .enumerate()
1189+ .filter_map(|(l, data)| {
1190+ Some((l, data.clips.iter().position(|c| c.link == Some(link))?))
1191+ })
1192+ .collect(),
1193+ None => vec![(self.index(lane).expect("the clip was found on it"), idx)],
1194+ })
1195+ }
1196+
1047 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one1197 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
1048 /// new group, pushing everything from there on later by its length in1198 /// new group, pushing everything from there on later by its length in
1049 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip1199 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
@@ -2118,6 +2268,139 @@ mod tests {
2118 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);2268 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
2119 }2269 }
2120 2270
2271+ /// How long `FILE` is, which is what a trim's tail is allowed to reach:
2272+ /// [`three`] cuts up all nine of its frames.
2273+ const SRC: &[u32] = &[9];
2274+
2275+ /// The drag on a clip's tail: it plays less (or more) of its source, nothing
2276+ /// else on the lane moves, and every wall stops the edge rather than
2277+ /// refusing the gesture.
2278+ #[test]
2279+ fn trimming_the_tail_stops_at_every_wall() {
2280+ let mut p = three();
2281+
2282+ // Pulled in: a gap opens behind it and the clip after it stays put.
2283+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2284+ assert_eq!(
2285+ shape(&p)[0],
2286+ vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
2287+ );
2288+ assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
2289+ assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
2290+
2291+ // ...and back out, no further than the clip behind it.
2292+ assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
2293+ assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour");
2294+ assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall");
2295+
2296+ // One frame of clip always survives, however far back the pointer went.
2297+ assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
2298+ assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
2299+
2300+ // The last clip has no neighbour, so what stops it is the file: nine
2301+ // frames is nine frames.
2302+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
2303+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2304+ assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
2305+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
2306+ // A source nobody told us the length of may not grow at all -- an
2307+ // out-point past the end of a file is a save that will not open again.
2308+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
2309+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
2310+ }
2311+
2312+ /// The head pulled in takes the in-point with it -- what stays plays what it
2313+ /// always played -- and stops at the source's own first frame.
2314+ #[test]
2315+ fn trimming_the_head_moves_the_in_point() {
2316+ let mut p = three();
2317+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2318+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front");
2319+ assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
2320+ assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
2321+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
2322+ assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
2323+ // One frame survives here too.
2324+ assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
2325+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
2326+
2327+ // A clip that does not begin at its source's first frame: its head goes
2328+ // back to source frame 0 and not one frame further.
2329+ let mut p = Project::single(FILE, 9);
2330+ assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
2331+ assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
2332+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
2333+ assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
2334+ }
2335+
2336+ /// A clip whose in-point is *past* its own start -- what a ripple delete
2337+ /// leaves, the piece in front of it gone and this one slid back to frame 0
2338+ /// carrying the in-point the cut gave it. Its head has more source behind it
2339+ /// than the timeline has room for, and the timeline's own first frame is the
2340+ /// wall: asking is not an overflow, and the answer is 0.
2341+ #[test]
2342+ fn a_ripple_closed_clip_can_still_be_head_trimmed() {
2343+ let mut p = Project::single(FILE, 9);
2344+ assert!(p.split(5));
2345+ assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
2346+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
2347+
2348+ assert_eq!(
2349+ p.trim_room(Lane::V1, 0, Edge::Start, SRC),
2350+ Some((0, 3)),
2351+ "back to frame 0 at most, and one frame of clip always survives"
2352+ );
2353+ assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
2354+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2355+ assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed");
2356+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
2357+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
2358+ }
2359+
2360+ /// Linked halves trim as one: a link is one span on however many lanes, so
2361+ /// the sound follows the picture's edge -- and the tightest wall of the two
2362+ /// is what stops both.
2363+ #[test]
2364+ fn linked_halves_trim_together() {
2365+ let mut p = three();
2366+ let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
2367+ assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
2368+
2369+ assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
2370+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
2371+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
2372+ assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it");
2373+ assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
2374+ links_are_consistent(&p.lanes).expect("one id per lane, one span");
2375+
2376+ // Something in the way on the *audio* lane stops the picture's tail as
2377+ // well: the group can only go as far as its tightest member.
2378+ assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
2379+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2380+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
2381+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
2382+ links_are_consistent(&p.lanes).expect("still one span");
2383+ }
2384+
2385+ /// A whole drag is one undo step -- the front-end commits once, at the
2386+ /// release -- and an edge asked to stay where it is costs none at all.
2387+ #[test]
2388+ fn a_trim_is_one_undo_step() {
2389+ let mut p = three();
2390+ let before = shape(&p);
2391+ let history = p.history.len();
2392+
2393+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2394+ assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
2395+ assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
2396+ assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
2397+ assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
2398+ assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
2399+
2400+ assert!(p.undo());
2401+ assert_eq!(shape(&p), before, "both halves back, in one step");
2402+ }
2403+
2121 /// A moved half stays in its group: a link names a span, not a lane, so the2404 /// A moved half stays in its group: a link names a span, not a lane, so the
2122 /// picture on `V2` is still the same take as the sound under it on `A1`.2405 /// picture on `V2` is still the same take as the sound under it on `A1`.
2123 #[test]2406 #[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 {