forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(main): edge trim beside the colour drag on the root carriers

Browse files at this commit

dcd2d0f916bd668e4371efd914ea9d4ede15244bAhmet Kaan GümüşParent: 8d8d880e1fb59d
Both features hang a drag off the root's mouse-move and mouse-up, which is
where they collided. Kept both, in press-target order: equalizer, trim,
colour, scrub. They cannot overlap -- a gesture belongs to whatever was
pressed, and no two of those hitboxes are the same element.
crates/app/src/main.rsmodified+299 -22
@@ -13,12 +13,13 @@ use engine::audio::StreamInfo;
1313 use engine::color::ColorParams;
1414 use engine::eq::{Band, BandKind, EqParams};
1515 use engine::export::{ExportSettings, Format};
16-use engine::project::{Lane, LaneKind, Source};
16+use engine::project::{Edge, Lane, LaneKind, Source};
1717 use engine::scale::FitPolicy;
1818 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
1919 use gpui::{
20- AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,
21- MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,
20+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
21+ KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
22+ Point,
2223 RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds,
2324 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,
2425 };
@@ -216,6 +217,31 @@ struct ClipDrag {
216217 idx: usize,
217218 }
218219
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+
219245 /// An open clip menu: which clip it was opened on, where it hangs, and whether
220246 /// it has been turned over to show what that clip *is* instead of what can be
221247 /// done to it. The lane and index are the ones the same click selected, so
@@ -380,6 +406,10 @@ struct Player {
380406 /// A drag that started on the ruler. Moves anywhere in the window scrub
381407 /// while it is set; the release commits the exact position.
382408 scrubbing: bool,
409+ /// A drag that started on a clip's edge, tracked on the root for
410+ /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See
411+ /// [`Trim`].
412+ trim: Option<Trim>,
383413 last_scrub: Instant,
384414 last_target: u32,
385415 /// The running export. While it owns the UI the editor is read-only.
@@ -569,6 +599,11 @@ impl Player {
569599 self.eos = false;
570600 self.done = false;
571601 self.pending_seek = true;
602+ // An edit moves the indices a drag in flight is holding -- a stroke
603+ // during one is exactly that -- and an edge committed against a moved
604+ // index would trim a clip nobody grabbed. Dropping it is the whole fix:
605+ // nothing has been written yet.
606+ self.trim = None;
572607 }
573608
574609 /// What an action does, wherever it was asked for -- a stroke, or the clip
@@ -1072,7 +1107,7 @@ impl Player {
10721107 _ => false,
10731108 };
10741109 if selected.is_some() && !deleted {
1075- self.notice = Some("NOTHING DELETED — the timeline cannot be emptied".into());
1110+ self.notice = Some("NOTHING DELETED — that clip is no longer there".into());
10761111 }
10771112 if deleted {
10781113 self.reset_after_reseek();
@@ -1092,7 +1127,7 @@ impl Player {
10921127 if session.lift_clip(lane, idx) {
10931128 self.reset_after_reseek();
10941129 } else {
1095- self.notice = Some("NOTHING LIFTED — the timeline cannot be emptied".into());
1130+ self.notice = Some("NOTHING LIFTED — that half is no longer there".into());
10961131 }
10971132 }
10981133 (Some(_), None) => {
@@ -1252,6 +1287,135 @@ impl Player {
12521287 cx.notify();
12531288 }
12541289
1290+ /// Opens the clip menu on the box under the pointer, from the right button
1291+ /// wherever it was pressed on that box -- its middle or one of its edge
1292+ /// strips, which cover the middle's own listener. Selecting first is part of
1293+ /// it: every item acts on the clip the menu names.
1294+ fn open_menu(&mut self, lane: Lane, idx: usize, at: Point<Pixels>, cx: &mut Context<Self>) {
1295+ if self.modal() {
1296+ return;
1297+ }
1298+ self.select((lane, idx), cx);
1299+ self.context_menu = Some(ContextMenu {
1300+ lane,
1301+ idx,
1302+ at,
1303+ details: false,
1304+ });
1305+ cx.notify();
1306+ }
1307+
1308+ /// A press on a clip's edge: the start of the drag that changes how much of
1309+ /// its source it plays. It selects the clip as a press anywhere else on the
1310+ /// box does -- the edge strip covers the box's own listener (`occlude`), so
1311+ /// this is the only one that fires there.
1312+ fn start_trim(&mut self, lane: Lane, idx: usize, edge: Edge, cx: &mut Context<Self>) {
1313+ if self.modal() || self.exporting().is_some() {
1314+ return;
1315+ }
1316+ let Some(clip) = self
1317+ .session
1318+ .as_ref()
1319+ .and_then(|session| session.lane_clips(lane).get(idx).copied())
1320+ else {
1321+ return;
1322+ };
1323+ self.select((lane, idx), cx);
1324+ self.trim = Some(Trim {
1325+ lane,
1326+ idx,
1327+ edge,
1328+ // Where the edge already is: a press that never moves is not an
1329+ // edit, and `Project::trim` refuses exactly that.
1330+ to: match edge {
1331+ Edge::Start => clip.start,
1332+ Edge::End => clip.end(),
1333+ },
1334+ link: clip.link,
1335+ });
1336+ cx.notify();
1337+ }
1338+
1339+ /// Where the pointer has pulled the edge to, clamped to the room the engine
1340+ /// says that edge has. Along the same bed the ruler is measured on and
1341+ /// against the same duration the boxes are drawn to, so the edge tracks the
1342+ /// pointer exactly.
1343+ fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
1344+ let (duration, fps) = (self.drawn_duration(), self.fps);
1345+ let frac = frac_along(x, self.ruler.get());
1346+ let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
1347+ return;
1348+ };
1349+ let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {
1350+ return;
1351+ };
1352+ trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi);
1353+ cx.notify();
1354+ }
1355+
1356+ /// The release: the whole drag reaches the engine as one edit, so it is one
1357+ /// undo step. The selection survives it -- a trim inserts and removes
1358+ /// nothing, so every index a lane had still names the clip it named.
1359+ fn commit_trim(&mut self, cx: &mut Context<Self>) {
1360+ let Some(trim) = self.trim.take() else {
1361+ return;
1362+ };
1363+ let trimmed = self
1364+ .session
1365+ .as_mut()
1366+ .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to));
1367+ if trimmed {
1368+ self.reset_after_reseek();
1369+ }
1370+ cx.notify();
1371+ }
1372+
1373+ /// The clip as the drag is showing it: an edge under the pointer moves its
1374+ /// own box, and the boxes of the halves linked to it, before anything is
1375+ /// committed. Display only -- the project is not touched until the release.
1376+ fn trimmed(&self, lane: Lane, idx: usize, clip: Clip) -> Clip {
1377+ let Some(trim) = self.trim.filter(|t| {
1378+ (t.lane, t.idx) == (lane, idx) || (t.link.is_some() && t.link == clip.link)
1379+ }) else {
1380+ return clip;
1381+ };
1382+ match trim.edge {
1383+ // The in-point follows the head, exactly as `Project::trim` moves
1384+ // it: what stays on screen plays what it always played.
1385+ Edge::Start => Clip {
1386+ in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start))
1387+ .clamp(0, i64::from(clip.out_frame - 1)) as u32,
1388+ start: trim.to,
1389+ ..clip
1390+ },
1391+ Edge::End => Clip {
1392+ out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1),
1393+ ..clip
1394+ },
1395+ }
1396+ }
1397+
1398+ /// How long the timeline is *drawn* as: its own length, and while a tail is
1399+ /// being dragged the furthest that tail may reach. A bed that ends exactly
1400+ /// at the last frame has nowhere to put a pointer that means "longer", so
1401+ /// without this the last clip on the timeline could be pulled in and never
1402+ /// let back out.
1403+ fn drawn_duration(&self) -> f64 {
1404+ let Some(session) = &self.session else {
1405+ return 0.;
1406+ };
1407+ let duration = session.timeline_duration();
1408+ match self.trim {
1409+ Some(trim) if trim.edge == Edge::End => {
1410+ let (_, hi) = session
1411+ .trim_room(trim.lane, trim.idx, trim.edge)
1412+ .unwrap_or((0, 0));
1413+ duration.max(f64::from(hi) / self.fps)
1414+ }
1415+ _ => duration,
1416+ }
1417+ }
1418+
12551419 /// The one way a library row reaches the timeline: the Add button and a row
12561420 /// dragged onto a lane both come here, so there is a single answer to what
12571421 /// "add this source" does. The whole source goes in at the playhead as one
@@ -1693,6 +1857,16 @@ impl Player {
16931857 cx.notify();
16941858 return;
16951859 };
1860+ // An emptied timeline is a timeline; it is simply not a file. Refused by
1861+ // name here rather than written as a project of no frames -- and the
1862+ // engine refuses it again on the worker (`export::start`), so a caller
1863+ // that is not this button cannot get past it either. Two fences on
1864+ // purpose: this one is the one with a keystroke to blame.
1865+ if session.is_empty() {
1866+ self.notice = Some("NOTHING TO EXPORT — the timeline is empty".into());
1867+ cx.notify();
1868+ return;
1869+ }
16961870 session.pause();
16971871 self.export = Some(session.export_to_with(&self.export_path, &settings));
16981872 // The card has been answered; the progress line takes the panel from
@@ -1774,11 +1948,9 @@ impl Render for Player {
17741948 }
17751949
17761950 // Read per render, never cached: a delete shortens the timeline and the
1777- // timecode, the ruler and the clamp below all have to follow it.
1778- let duration = self
1779- .session
1780- .as_ref()
1781- .map_or(0., PlaybackSession::timeline_duration);
1951+ // timecode, the ruler and the clamp below all have to follow it -- and
1952+ // so does the room a tail being dragged needs to grow into.
1953+ let duration = self.drawn_duration();
17821954 // The clock keeps running after the last frame (wall time takes over at
17831955 // audio EOF) while the picture is frozen, so the timeline the UI shows is
17841956 // the clamped one, pinned to the out-point once playback is done.
@@ -1986,6 +2158,17 @@ impl Render for Player {
19862158 }
19872159 return;
19882160 }
2161+ // A clip edge is 6 px wide and the pointer leaves it on the
2162+ // first drag, so the gesture is tracked here for the same
2163+ // reason -- and it ends here too when the button came up
2164+ // outside the window, still owing its one edit.
2165+ if this.trim.is_some() {
2166+ match event.pressed_button {
2167+ Some(MouseButton::Left) => this.trim_to(event.position.x, cx),
2168+ _ => this.commit_trim(cx),
2169+ }
2170+ return;
2171+ }
19892172 // A colour slider is 4 px tall and the pointer leaves it just as
19902173 // fast; every sample is live, so the release owes no write of
19912174 // its own -- what the last sample set is what the clip carries.
@@ -2019,6 +2202,13 @@ impl Render for Player {
20192202 this.commit_eq(cx);
20202203 return;
20212204 }
2205+ if this.trim.is_some() {
2206+ // The release lands exactly, then the gesture is
2207+ // written once -- one edit, one undo step.
2208+ this.trim_to(event.position.x, cx);
2209+ this.commit_trim(cx);
2210+ return;
2211+ }
20222212 if std::mem::take(&mut this.color_dragging) {
20232213 // The release lands exactly where the hand let go, and
20242214 // it is a live write like every other sample: the undo
@@ -3568,7 +3758,7 @@ impl Player {
35683758 let (sel, sel_link) = (self.selected, self.selected_link());
35693759 let audio = lane.kind == LaneKind::Audio;
35703760 let tip: SharedString = format!(
3571- "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut",
3761+ "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut",
35723762 self.keymap.display(ActionId::Select),
35733763 self.keymap.display(ActionId::SelectPrev),
35743764 self.keymap.display(ActionId::SelectNext),
@@ -3626,6 +3816,9 @@ impl Player {
36263816 }))
36273817 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
36283818 .children(clips.iter().enumerate().map(|(i, clip)| {
3819+ // What a drag on an edge is showing, which is the clip
3820+ // itself while nothing is being dragged.
3821+ let clip = &self.trimmed(lane, i, *clip);
36293822 let (start, len) = (
36303823 f64::from(clip.start) / self.fps,
36313824 f64::from(clip.len()) / self.fps,
@@ -3704,19 +3897,44 @@ impl Player {
37043897 .on_mouse_down(
37053898 MouseButton::Right,
37063899 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3707- if this.modal() {
3708- return;
3709- }
3710- this.select((lane, i), cx);
3711- this.context_menu = Some(ContextMenu {
3712- lane,
3713- idx: i,
3714- at: event.position,
3715- details: false,
3716- });
3717- cx.notify();
3900+ this.open_menu(lane, i, event.position, cx);
37183901 }),
37193902 )
3903+ // The two strips a drag *lengthens* the clip by,
3904+ // one at each end. They occlude the box behind
3905+ // them, which is what keeps one gesture one thing:
3906+ // a press here trims, a press anywhere else on the
3907+ // box still starts the move to another lane.
3908+ .children([Edge::Start, Edge::End].map(|edge| {
3909+ let mut zone = div()
3910+ .absolute()
3911+ .top_0()
3912+ .h_full()
3913+ .w(px(EDGE_W))
3914+ .occlude()
3915+ .cursor(CursorStyle::ResizeLeftRight)
3916+ .hover(|s| s.bg(rgb(ACCENT)))
3917+ .on_mouse_down(
3918+ MouseButton::Left,
3919+ cx.listener(move |this, _: &MouseDownEvent, _, cx| {
3920+ this.start_trim(lane, i, edge, cx);
3921+ }),
3922+ )
3923+ // Occluded, so the box's own right-button
3924+ // listener never fires here: the menu is
3925+ // the same menu, opened by the same call.
3926+ .on_mouse_down(
3927+ MouseButton::Right,
3928+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3929+ this.open_menu(lane, i, event.position, cx);
3930+ }),
3931+ );
3932+ zone = match edge {
3933+ Edge::Start => zone.left_0(),
3934+ Edge::End => zone.right_0(),
3935+ };
3936+ zone
3937+ }))
37203938 // Under the label row, never through it.
37213939 .children(wave.filter(|_| audio).and_then(|wave| {
37223940 let inner: AnyElement = match wave {
@@ -5371,6 +5589,64 @@ mod tests {
53715589 );
53725590 }
53735591
5592+ /// The trim-a-clip path through the doors the edge drag uses:
5593+ /// [`Player::trim_to`] clamps the pointer with `trim_room` and
5594+ /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
5595+ /// of its file, the sound linked to it follows, the head trim moves the
5596+ /// in-point, and one undo takes a whole gesture back.
5597+ ///
5598+ /// The routing *to* these doors -- the 6 px edge strip claiming the press
5599+ /// the clip's own body-drag would otherwise take -- is gpui hitbox
5600+ /// behaviour (`occlude`) and is not reachable without a window.
5601+ #[test]
5602+ fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
5603+ use engine::project::Edge;
5604+
5605+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5606+ session.set_gain(0.0);
5607+ let whole = session.lane_clips(Lane::V1)[0];
5608+ let full = session.timeline_duration();
5609+ assert_eq!(
5610+ session.trim_room(Lane::V1, 0, Edge::End),
5611+ Some((whole.start + 1, whole.end())),
5612+ "the file's own last frame is how far the tail goes"
5613+ );
5614+ assert!(
5615+ !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
5616+ "it already plays all of it"
5617+ );
5618+
5619+ // Pulled in by a third: the timeline ends earlier and the sound with it.
5620+ let shorter = whole.end() - whole.len() / 3;
5621+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
5622+ assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
5623+ assert_eq!(
5624+ session.lane_clips(Lane::A1)[0].end(),
5625+ shorter,
5626+ "the linked sound was trimmed with the picture"
5627+ );
5628+ assert!(session.timeline_duration() < full, "and plays out earlier");
5629+
5630+ // ...and dragged back out, as far as the file goes and no further.
5631+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
5632+ assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the whole take back");
5633+
5634+ // The head takes the in-point with it, so what plays at the new start
5635+ // is source frame 10 rather than source frame 0.
5636+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
5637+ let head = session.lane_clips(Lane::V1)[0];
5638+ assert_eq!((head.start, head.in_frame), (10, 10));
5639+ assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
5640+ assert_eq!(
5641+ session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
5642+ Some(0),
5643+ "and it may be pulled back out to the file's first frame"
5644+ );
5645+
5646+ assert!(session.undo(), "one step for the whole drag");
5647+ assert_eq!(session.lane_clips(Lane::V1)[0], whole);
5648+ }
5649+
53745650 /// The move-a-clip-between-tracks path through the door the drop uses
53755651 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the
53765652 /// *picture* comes from the new row afterwards -- which is what "it plays
@@ -6542,6 +6818,7 @@ fn main() {
65426818 streams: HashMap::new(),
65436819 clipboard: None,
65446820 scrubbing: false,
6821+ trim: None,
65456822 last_scrub: Instant::now(),
65466823 last_target: 0,
65476824 export: None,
crates/engine/src/edith.rsmodified+25 -19
@@ -504,9 +504,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
504504 }
505505 }
506506 }
507- if doc.lanes.iter().all(|(_, clips)| clips.is_empty()) {
508- return Err("no clips: an empty timeline is not a project".into());
509- }
507+ // A file whose lanes are all empty *is* a project -- the emptied timeline,
508+ // saved. What it may not be is laneless; [`crate::Project::from_parts`]
509+ // refuses that one, by the name it has there.
510510 Ok(doc)
511511 }
512512
@@ -870,13 +870,10 @@ mod tests {
870870 ] {
871871 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
872872 }
873- // Lanes and nothing on them is not a project.
874- assert_eq!(
875- parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir)
876- .unwrap_err()
877- .to_string(),
878- "no clips: an empty timeline is not a project"
879- );
873+ // Lanes and nothing on them is the emptied timeline, saved: a project.
874+ let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
875+ assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
876+ assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
880877 }
881878
882879 /// One band, spelled the way an eq line spells it.
@@ -1539,19 +1536,28 @@ mod tests {
15391536 }
15401537 }
15411538
1539+ /// The emptied timeline writes and reads back: every lane declared, no clip
1540+ /// on any of them, and the source that gave the project its frame rate still
1541+ /// named. Nothing about the format changes for it -- an empty lane already
1542+ /// had a line of its own.
15421543 #[test]
1543- fn a_project_without_clips_is_not_a_project() {
1544+ fn a_project_without_clips_round_trips() {
15441545 let dir = PathBuf::from("/proj");
1546+ let source = Source {
1547+ path: PathBuf::from("/proj/a.mp4"),
1548+ audio_stream: 0,
1549+ };
1550+ let bytes = flat(&dir, &[source.clone()], &two(Vec::new(), Vec::new()), 0);
1551+ let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
1552+ assert_eq!(back.sources, vec![source]);
1553+ assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
1554+ assert_eq!(back.playhead, 0);
1555+ // Older dialects, where the two lanes are implied rather than declared.
15451556 assert_eq!(
1546- parse(b"edith 1\nsource a.mp4\n", &dir)
1547- .unwrap_err()
1548- .to_string(),
1549- "no clips: an empty timeline is not a project"
1550- );
1551- assert_eq!(
1552- parse(b"edith 1\n", &dir).unwrap_err().to_string(),
1553- "no clips: an empty timeline is not a project"
1557+ parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
1558+ two(Vec::new(), Vec::new())
15541559 );
1560+ assert!(parse(b"edith 1\n", &dir).expect("a project of nothing").sources.is_empty());
15551561 }
15561562
15571563 /// Every truncation of a good file either parses or refuses; none panics.
crates/engine/src/export.rsmodified+11 -0
@@ -165,7 +165,18 @@ pub fn start(
165165 // The rename is the last step and the only one that publishes a file
166166 // under the name the caller asked for; it stays on the same directory,
167167 // so it is atomic.
168+ //
169+ // An emptied timeline is a legal project and an illegal file: no
170+ // picture, no sound, and a muxer that is never created because no coded
171+ // frame arrives. Refused by name here -- before the format is even
172+ // looked at, so an mp4 and a WAV refuse in the same words -- rather than
173+ // left to write a file of no frames that nothing opens. Every caller of
174+ // `start` comes through this, the app's own door
175+ // (`PlaybackSession::is_empty`) being only the first fence.
168176 let written = match settings.format {
177+ _ if project.timeline_frames() == 0 => {
178+ Err("the timeline is empty: there is nothing to export".into())
179+ }
169180 Format::Mp4 => run(&project, &meta, &part, &worker, &settings),
170181 format => run_audio(&project, &meta, &part, &worker, format),
171182 };
crates/engine/src/playback.rsmodified+114 -29
@@ -25,7 +25,7 @@ use crate::color::ColorParams;
2525 use crate::decode::{DecodeSession, Frame, Worker};
2626 use crate::demux::{Demuxer, VideoMeta};
2727 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};
2929 use crate::scale::{Composer, FitPolicy};
3030
3131 /// How long the feeder waits out a full ring. The ring holds a second, so this
@@ -122,13 +122,28 @@ pub struct PlaybackSession {
122122 /// The edit list. Everything a caller says in seconds is a *timeline*
123123 /// position; only this maps it onto the file.
124124 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>,
125134 /// What the current video worker was opened for: where it sits on the
126135 /// timeline, how long it runs, and which source frame it started at --
127136 /// together they rewrite a source frame index into a timeline one. Not a
128137 /// clip index: a `split` cuts the clip under a running worker, and only the
129138 /// mapping survives that. A span with no source is a *gap*, and the worker
130139 /// feeding it emits black frames indexed from zero.
131- span: Span,
140+ ///
141+ /// `None` is the *emptied* timeline -- no clip on any lane, so there is no
142+ /// stretch to be inside of. It is a state, not a failure: the picture is
143+ /// black ([`start_span`](Self::start_span) feeds one black frame for it),
144+ /// the sound is silence, the duration is zero, and placing anything reseeks
145+ /// straight back out of it.
146+ span: Option<Span>,
132147 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
133148 eos: bool,
134149 }
@@ -174,7 +189,7 @@ impl PlaybackSession {
174189 // One clip per lane covering the file, so timeline == source until the
175190 // first edit -- and the range opened above is exactly that clip's.
176191 let project = Project::single(&path, meta.frame_count);
177- let span = project.composite_span_at(0).expect("never empty");
192+ let span = project.composite_span_at(0);
178193 Ok(Self {
179194 meta,
180195 native: (meta.width, meta.height),
@@ -185,6 +200,7 @@ impl PlaybackSession {
185200 audio,
186201 audio_disabled,
187202 project,
203+ counts: vec![meta.frame_count],
188204 span,
189205 eos: false,
190206 })
@@ -290,7 +306,7 @@ impl PlaybackSession {
290306
291307 let playhead = doc.playhead;
292308 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?;
293- let span = project.composite_span_at(0).expect("never empty");
309+ let span = project.composite_span_at(0);
294310 // Last, because it is the one thing here that cannot be taken back: the
295311 // feeder thread outlives the `Audio` value (it holds its own clones) and
296312 // only a session's `drop` retires it, so a refusal above this line would
@@ -310,6 +326,7 @@ impl PlaybackSession {
310326 audio,
311327 audio_disabled,
312328 project,
329+ counts,
313330 span,
314331 eos: false,
315332 };
@@ -370,9 +387,12 @@ impl PlaybackSession {
370387 match self.frames.try_recv() {
371388 Ok(mut frame) => {
372389 // A gap's worker indexes from zero, a decoder's from its in
373- // point: `base` is whichever this span started at.
374- let base = self.span.from.map_or(0, |(_, in_frame)| in_frame);
375- frame.index = self.span.start + frame.index.saturating_sub(base);
390+ // point: `base` is whichever this span started at. An empty
391+ // timeline has no span, and its one black frame is frame 0.
392+ let (start, base) = self
393+ .span
394+ .map_or((0, 0), |s| (s.start, s.from.map_or(0, |(_, i)| i)));
395+ frame.index = start + frame.index.saturating_sub(base);
376396 return Some(frame);
377397 }
378398 Err(TryRecvError::Empty) => return None,
@@ -415,35 +435,47 @@ impl PlaybackSession {
415435 /// than remembered as a clip index, because a `split` while playing cuts the
416436 /// clip under the running worker and only the mapping stays true.
417437 fn next_clip(&mut self) -> bool {
418- let next = self.span.end();
438+ // No span is the emptied timeline: it was played out the moment its one
439+ // black frame went by, and there is no "next" to walk to.
440+ let next = match self.span {
441+ Some(span) => span.end(),
442+ None => return false,
443+ };
419444 let Some(span) = self.project.composite_span_at(next) else {
420445 return false;
421446 };
422447 // We only get here on a disconnect, so the old worker has already
423448 // returned; cancel anyway, so `retire` treats every path alike.
424449 self.worker.cancel();
425- self.start_span(span);
450+ self.start_span(Some(span));
426451 true
427452 }
428453
429454 /// Points the video worker at `span`: a decoder over its source range, or a
430- /// black-frame generator for a gap. The old worker must already have been
431- /// cancelled -- this is the half both `seek` and `next_clip` share.
455+ /// black-frame generator for a gap -- and for `None`, the emptied timeline,
456+ /// which is one frame of black so the viewer shows the nothing that is
457+ /// there rather than the last picture of the clip that was deleted. The old
458+ /// worker must already have been cancelled -- this is the half both `seek`
459+ /// and `next_clip` share.
432460 ///
433461 /// A source that will not open leaves the *span* installed anyway: the
434462 /// timeline still moves, there are simply no more pictures, and the
435463 /// disconnected receiver carries the session on to the next span.
436- fn start_span(&mut self, span: Span) {
437- let opened = match span.from {
464+ fn start_span(&mut self, span: Option<Span>) {
465+ let opened = match span {
438466 // The grade is the composite's at this frame -- the same clip the
439467 // span itself came from -- and it is constant across the span, so
440468 // the worker carries it and every frame it converts wears it.
441- Some((source, in_frame)) => DecodeSession::open_worker(
469+ Some(Span {
470+ start,
471+ len,
472+ from: Some((source, in_frame)),
473+ }) => DecodeSession::open_worker(
442474 &self.project.sources()[source].path,
443475 in_frame,
444- in_frame + span.len,
476+ in_frame + len,
445477 self.project
446- .composite_color_at(span.start)
478+ .composite_color_at(start)
447479 .copied()
448480 .unwrap_or_default(),
449481 // ...and the canvas it is placed on: the project's resolution
@@ -452,15 +484,18 @@ impl PlaybackSession {
452484 Composer::new(
453485 self.meta.width,
454486 self.meta.height,
455- self.project.composite_fit_at(span.start),
487+ self.project.composite_fit_at(start),
456488 ),
457489 )
458490 .map(|(_, stream)| stream)
459- .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),
460- None => Ok(DecodeSession::open_black(
491+ .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")),
492+ // A gap: black for as long as it runs. An emptied timeline has no
493+ // span at all and gets one frame of it -- enough to put black on
494+ // screen, and it ends where the timeline does, at once.
495+ gap => Ok(DecodeSession::open_black(
461496 self.meta.width,
462497 self.meta.height,
463- span.len,
498+ gap.map_or(1, |s| s.len),
464499 )),
465500 };
466501 if let Ok(stream) = opened {
@@ -480,6 +515,14 @@ impl PlaybackSession {
480515 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
481516 }
482517
518+ /// Whether no lane holds anything: the emptied timeline, which plays black
519+ /// and silent and is zero seconds long. A state, not a failure -- but the
520+ /// one a caller with nothing to render (an export) has to refuse by name
521+ /// rather than write a file of no frames.
522+ pub fn is_empty(&self) -> bool {
523+ self.project.timeline_frames() == 0
524+ }
525+
483526 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
484527 /// needs to lay itself out. Selection is the caller's business.
485528 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
@@ -575,8 +618,9 @@ impl PlaybackSession {
575618
576619 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
577620 /// silence on the audio one, and nothing else moves. Reseeks, because what
578- /// the playhead sits on has changed. `false` for a bad index and for the
579- /// lift that would leave the whole timeline empty.
621+ /// the playhead sits on has changed. `false` for a bad index -- the lift of
622+ /// the last placement there is empties the timeline, which is a state
623+ /// ([`is_empty`](Self::is_empty)) and one undo away.
580624 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
581625 self.edit(|p| p.lift(lane, idx))
582626 }
@@ -591,6 +635,45 @@ impl PlaybackSession {
591635 self.edit(|p| p.move_to_lane(from, idx, to))
592636 }
593637
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+
594677 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
595678 /// on and its index there, by the same topmost-lane-wins rule the decoder
596679 /// follows. `None` over a gap and past the end. What a card that grades
@@ -737,6 +820,7 @@ impl PlaybackSession {
737820 let first = self.first_audio()?;
738821 audio_matches(&wanted, &first)?;
739822 let source = self.project.import(path, stream);
823+ self.note_frames(source, frames.max(1));
740824 let clip = Clip {
741825 start: 0,
742826 in_frame: 0,
@@ -793,7 +877,8 @@ impl PlaybackSession {
793877 /// on every lane. Unlike a split this *does* move every following frame, so
794878 /// the session reseeks to wherever the playhead now points.
795879 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
796- /// `false` for a bad index or the last remaining clip.
880+ /// `false` for a bad index; the last remaining clip goes like any other and
881+ /// leaves the timeline empty ([`is_empty`](Self::is_empty)).
797882 ///
798883 /// The lane travels because the index is a lane's own: `V2`'s third clip is
799884 /// not `V1`'s, and a front-end that could only say "the third clip" would
@@ -828,6 +913,7 @@ impl PlaybackSession {
828913
829914 let old_end = self.timeline_duration();
830915 let source = self.project.import(path, 0);
916+ self.note_frames(source, meta.frame_count);
831917 // Refused only for an unknown index, and this one just came from `import`.
832918 self.project.append_clip(source, meta.frame_count);
833919 // Reseek like any other edit, even though nothing before the playhead
@@ -860,6 +946,7 @@ impl PlaybackSession {
860946
861947 let old_end = self.timeline_duration();
862948 let source = self.project.import(path, 0);
949+ self.note_frames(source, frames);
863950 let at = self.project.timeline_frames();
864951 self.project.place(
865952 Lane::A1,
@@ -984,12 +1071,10 @@ impl PlaybackSession {
9841071 // [`retire`](Self::retire), which is what keeps a scrub off the price
9851072 // of a VA-API init.
9861073 self.worker.cancel();
987- // `target` is inside the timeline (never empty), so this always spans;
988- // the span runs from there to the end of whatever it landed in -- a
989- // clip, or a gap, which starts a black-frame worker instead.
990- if let Some(span) = self.project.composite_span_at(target) {
991- self.start_span(span);
992- }
1074+ // The span runs from `target` to the end of whatever it landed in -- a
1075+ // clip, or a gap, which starts a black-frame worker instead. `None` is
1076+ // the emptied timeline, black too, and `start_span` says so.
1077+ self.start_span(self.project.composite_span_at(target));
9931078 self.eos = false;
9941079
9951080 let mut audio_running = false;
crates/engine/src/project.rsmodified+350 -32
@@ -212,6 +212,17 @@ impl LaneData {
212212 }
213213 }
214214
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+
215226 /// What a lane holds over one stretch of the timeline: either a placed clip or
216227 /// a gap. Returned already trimmed to the position it was asked about, so a
217228 /// caller can hand `len` straight to a decoder (or to a black-frame generator).
@@ -299,10 +310,16 @@ impl Project {
299310 /// [`Project::undo`] is `false` until the first edit of the new session.
300311 /// This is the one door untrusted parts come in through, so every invariant
301312 /// every other constructor keeps is checked here, by name and in release:
302- /// every lane empty, an empty clip, a clip naming a source (or an equalizer,
313+ /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
303314 /// or a colour) that is not there, a clip whose end overflows, a lane that is
304315 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
305316 /// below.
317+ ///
318+ /// A project whose lanes are all *empty* is not among them: an emptied
319+ /// timeline is a project like any other -- it plays black and silent, it
320+ /// saves, and it loads back. What a project cannot be is laneless, because
321+ /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
322+ /// handle indexes into.
306323 pub fn from_parts(
307324 sources: Vec<Source>,
308325 lanes: Vec<(LaneKind, Vec<Clip>)>,
@@ -315,8 +332,8 @@ impl Project {
315332 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
316333 return Err(format!("color {bad} holds a value that is not a finite number").into());
317334 }
318- if lanes.iter().all(|(_, clips)| clips.is_empty()) {
319- return Err("every lane is empty: that is not a project".into());
335+ if lanes.is_empty() {
336+ return Err("no lanes at all: that is not a project".into());
320337 }
321338 let lanes: Vec<LaneData> = lanes
322339 .into_iter()
@@ -421,9 +438,8 @@ impl Project {
421438 /// that could not be taken back would be the one edit with no way out.
422439 /// Nothing plays differently until something is placed on it.
423440 ///
424- /// The new lane being empty is fine even though [`Project::from_parts`]
425- /// refuses an all-empty project: the lanes that were there still hold the
426- /// timeline, and "no lane holds anything" is what that door refuses.
441+ /// An empty lane is a lane like any other -- so is a whole project of them
442+ /// ([`Project::from_parts`]); nothing plays until something is placed.
427443 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
428444 self.snapshot();
429445 self.lanes.push(LaneData {
@@ -525,6 +541,11 @@ impl Project {
525541 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
526542 /// and this is the one moment they can go -- the indexes that survive it are
527543 /// only the ones a clip names.
544+ ///
545+ /// One exception, and it is the emptied timeline's: a project no clip plays
546+ /// from still keeps source 0. It is the file a session is scaffolded from --
547+ /// its frame rate is the timeline's and is written nowhere else -- so a save
548+ /// that pruned it would write a project that cannot be loaded back at all.
528549 pub fn without_orphan_sources(&self) -> Parts {
529550 let mut moved = vec![None; self.sources.len()];
530551 let mut sources = Vec::new();
@@ -566,6 +587,9 @@ impl Project {
566587 });
567588 }
568589 }
590+ if sources.is_empty() {
591+ sources.extend(self.sources.first().cloned());
592+ }
569593 (
570594 sources,
571595 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
@@ -1051,6 +1075,145 @@ impl Project {
10511075 true
10521076 }
10531077
1078+ /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
1079+ /// the drag on a clip's end that makes it play more or less of its source.
1080+ /// The rest of the lane stays exactly where it is (nothing ripples), so what
1081+ /// a shortened clip leaves behind is a gap and what a lengthened one takes
1082+ /// is room that was already empty. One snapshot, so a whole drag is one
1083+ /// [`Project::undo`] -- commit once, at the release, rather than per pointer
1084+ /// sample. Changes the timeline->source mapping: the caller must reseek.
1085+ ///
1086+ /// [`Edge::Start`] moves the in-point with it: the frames that stay play
1087+ /// exactly what they played before, which is what makes this a trim and not
1088+ /// a slip.
1089+ ///
1090+ /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
1091+ /// legal means "as far as it goes", and stopping the box there is the
1092+ /// affordance. The walls are: one frame of clip always survives, an edge
1093+ /// never crosses the neighbouring clip on its own lane, an in-point never
1094+ /// walks back past the source's first frame, and an out-point never runs
1095+ /// past `source_frames[clip.source]` -- the caller's table of how long each
1096+ /// source actually is ([`Project`] does not know, and a clip ending past its
1097+ /// file's last frame is a save that will not open again; see
1098+ /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
1099+ /// there may not grow at all.
1100+ ///
1101+ /// Linked clips trim *together*, to one clamped edge: a link is one span on
1102+ /// however many lanes ([`links_are_consistent`]), so a picture trimmed away
1103+ /// from its sound would be a group no save could load. The room is therefore
1104+ /// what every member of the group has -- the tightest wall wins.
1105+ ///
1106+ /// `false`, changing nothing and costing no undo step, for an index that is
1107+ /// not there and for an edge that is already where it was asked to go.
1108+ pub fn trim(
1109+ &mut self,
1110+ lane: Lane,
1111+ idx: usize,
1112+ edge: Edge,
1113+ to: u32,
1114+ source_frames: &[u32],
1115+ ) -> bool {
1116+ let (Some((lo, hi)), Some(clip)) = (
1117+ self.trim_room(lane, idx, edge, source_frames),
1118+ self.lane(lane).get(idx).copied(),
1119+ ) else {
1120+ return false;
1121+ };
1122+ let to = to.clamp(lo, hi);
1123+ let at = match edge {
1124+ Edge::Start => clip.start,
1125+ Edge::End => clip.end(),
1126+ };
1127+ if to == at {
1128+ return false;
1129+ }
1130+ self.snapshot();
1131+ for (l, i) in self.group_of(lane, idx).expect("checked above") {
1132+ let c = &mut self.lanes[l].clips[i];
1133+ match edge {
1134+ Edge::Start => {
1135+ // Non-negative by `lo`, which is what keeps the in-point on
1136+ // the source.
1137+ c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32;
1138+ c.start = to;
1139+ }
1140+ Edge::End => c.out_frame = c.in_frame + (to - c.start),
1141+ }
1142+ debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1143+ }
1144+ true
1145+ }
1146+
1147+ /// How far that edge may travel, `(first, last)` timeline frame inclusive --
1148+ /// the walls [`trim`](Project::trim) clamps to, without moving anything.
1149+ /// What a front-end drawing the box *during* a drag asks, so the live width
1150+ /// is the width the release will commit and an edge stops under the pointer
1151+ /// rather than snapping back. `None` for an index that is not there.
1152+ pub fn trim_room(
1153+ &self,
1154+ lane: Lane,
1155+ idx: usize,
1156+ edge: Edge,
1157+ source_frames: &[u32],
1158+ ) -> Option<(u32, u32)> {
1159+ let (mut lo, mut hi) = (u32::MIN, u32::MAX);
1160+ for (l, i) in self.group_of(lane, idx)? {
1161+ let clips = &self.lanes[l].clips;
1162+ let c = clips[i];
1163+ let (member_lo, member_hi) = match edge {
1164+ Edge::Start => (
1165+ // Back to the source's own first frame, and never over the
1166+ // clip in front of it. Saturating because a clip may hold
1167+ // *more* head than the timeline has room for -- a ripple
1168+ // delete slides a clip back to frame 0 with its in-point
1169+ // wherever the cut left it -- and frame 0 is the other wall.
1170+ c.start
1171+ .saturating_sub(c.in_frame)
1172+ .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1173+ c.end() - 1,
1174+ ),
1175+ Edge::End => (
1176+ c.start + 1,
1177+ // Out to whatever is left of the source, and never over the
1178+ // clip behind it.
1179+ c.start
1180+ .saturating_add(
1181+ source_frames
1182+ .get(c.source)
1183+ .copied()
1184+ .unwrap_or(c.out_frame)
1185+ .saturating_sub(c.in_frame),
1186+ )
1187+ .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1188+ ),
1189+ };
1190+ lo = lo.max(member_lo);
1191+ hi = hi.min(member_hi);
1192+ }
1193+ // `hi.max(lo)`: for a clip the invariants hold for, the range always
1194+ // contains the edge's own place, and a caller's wrong `source_frames`
1195+ // must not become an empty range (or a panicking `clamp`) here.
1196+ Some((lo, hi.max(lo)))
1197+ }
1198+
1199+ /// The clips that move as one with the clip at `idx` of `lane` -- itself and
1200+ /// whatever carries its link on the other lanes -- as `(lane storage index,
1201+ /// clip index)` pairs. `None` for an index that is not there.
1202+ fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
1203+ let clip = *self.lane(lane).get(idx)?;
1204+ Some(match clip.link {
1205+ Some(link) => self
1206+ .lanes
1207+ .iter()
1208+ .enumerate()
1209+ .filter_map(|(l, data)| {
1210+ Some((l, data.clips.iter().position(|c| c.link == Some(link))?))
1211+ })
1212+ .collect(),
1213+ None => vec![(self.index(lane).expect("the clip was found on it"), idx)],
1214+ })
1215+ }
1216+
10541217 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
10551218 /// new group, pushing everything from there on later by its length in
10561219 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
@@ -1128,13 +1291,12 @@ impl Project {
11281291 }
11291292
11301293 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
1131- /// silence, and nothing else moves. Refused for an out-of-range index (which
1132- /// a lane that is not there always is) and for the lift that would leave
1133- /// *every* lane empty -- an empty timeline is the front-end's state, not a
1134- /// project's (see the never-empty invariant).
1294+ /// silence, and nothing else moves. Refused only for an out-of-range index
1295+ /// (which a lane that is not there always is) -- lifting the last placement
1296+ /// there is leaves an *empty* timeline, which is a state the project holds
1297+ /// like any other and an undo brings back.
11351298 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
1136- let placed: usize = self.lanes.iter().map(|l| l.clips.len()).sum();
1137- if idx >= self.lane(lane).len() || placed == 1 {
1299+ if idx >= self.lane(lane).len() {
11381300 return false;
11391301 }
11401302 self.snapshot();
@@ -1144,23 +1306,17 @@ impl Project {
11441306
11451307 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
11461308 /// the hole: everything after slides back by `len`. The rippling delete --
1147- /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an
1148- /// empty range and when it would leave every lane empty.
1309+ /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
1310+ /// empty range; a delete that leaves nothing behind empties the timeline,
1311+ /// which is a state like any other and one undo away.
11491312 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
11501313 if len == 0 {
11511314 return false;
11521315 }
1153- let survivors: usize = self
1154- .lanes
1155- .iter()
1156- .map(|l| {
1157- l.clips
1158- .iter()
1159- .filter(|c| c.start < at || c.end() > at + len)
1160- .count()
1161- })
1162- .sum();
1163- if survivors == 0 {
1316+ // Nothing reaches past `at`: there is nothing to cut and nothing to
1317+ // slide back, and a delete that changes nothing must not cost an undo
1318+ // step (see [`snapshot`](Project::snapshot)).
1319+ if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| c.end() > at) {
11641320 return false;
11651321 }
11661322 self.snapshot();
@@ -1951,7 +2107,11 @@ mod tests {
19512107
19522108 assert!(!p.delete(2), "index past the end");
19532109 assert!(p.delete(1));
1954- assert!(!p.delete(0), "the last remaining clip stays");
2110+ assert!(p.delete(0), "and the last remaining clip goes too");
2111+ assert_eq!(p.clips().len(), 0);
2112+ assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
2113+ assert!(!p.delete(0), "there is nothing left to delete");
2114+ assert!(p.undo(), "one gesture, one undo");
19552115 assert_eq!(p.clips().len(), 1);
19562116 }
19572117
@@ -2002,13 +2162,28 @@ mod tests {
20022162 }
20032163 }
20042164
2165+ /// The timeline is emptiable: the last placement comes off like any other,
2166+ /// the project holds "nothing on any lane" as a state, and one undo per
2167+ /// gesture brings it back.
20052168 #[test]
2006- fn the_last_clip_of_the_last_lane_cannot_be_lifted() {
2169+ fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
20072170 let mut p = Project::single(FILE, 9);
20082171 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
2009- assert!(!p.lift(Lane::V1, 0), "an empty one is not");
2172+ assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
2173+ assert_eq!(p.timeline_frames(), 0);
2174+ assert_eq!(p.composite_span_at(0), None, "nothing to show");
2175+ assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
20102176 assert!(!p.lift(Lane::A1, 0), "index past the end");
2011- assert_eq!(p.timeline_frames(), 9);
2177+ assert!(p.undo(), "and the last lift comes back");
2178+ assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
2179+ // A saved-and-loaded empty timeline is a project like any other, and it
2180+ // still names the file its frame rate came from.
2181+ assert!(p.lift(Lane::V1, 0));
2182+ let (sources, lanes, eq, color) = p.without_orphan_sources();
2183+ assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
2184+ let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads");
2185+ assert_eq!(back.timeline_frames(), 0);
2186+ assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
20122187 }
20132188
20142189 /// What a keyboard selection walks: one answer per lane, gaps included --
@@ -2113,6 +2288,139 @@ mod tests {
21132288 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
21142289 }
21152290
2291+ /// How long `FILE` is, which is what a trim's tail is allowed to reach:
2292+ /// [`three`] cuts up all nine of its frames.
2293+ const SRC: &[u32] = &[9];
2294+
2295+ /// The drag on a clip's tail: it plays less (or more) of its source, nothing
2296+ /// else on the lane moves, and every wall stops the edge rather than
2297+ /// refusing the gesture.
2298+ #[test]
2299+ fn trimming_the_tail_stops_at_every_wall() {
2300+ let mut p = three();
2301+
2302+ // Pulled in: a gap opens behind it and the clip after it stays put.
2303+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2304+ assert_eq!(
2305+ shape(&p)[0],
2306+ vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
2307+ );
2308+ assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
2309+ assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
2310+
2311+ // ...and back out, no further than the clip behind it.
2312+ assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
2313+ assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour");
2314+ assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall");
2315+
2316+ // One frame of clip always survives, however far back the pointer went.
2317+ assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
2318+ assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
2319+
2320+ // The last clip has no neighbour, so what stops it is the file: nine
2321+ // frames is nine frames.
2322+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
2323+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2324+ assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
2325+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
2326+ // A source nobody told us the length of may not grow at all -- an
2327+ // out-point past the end of a file is a save that will not open again.
2328+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
2329+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
2330+ }
2331+
2332+ /// The head pulled in takes the in-point with it -- what stays plays what it
2333+ /// always played -- and stops at the source's own first frame.
2334+ #[test]
2335+ fn trimming_the_head_moves_the_in_point() {
2336+ let mut p = three();
2337+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2338+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front");
2339+ assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
2340+ assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
2341+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
2342+ assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
2343+ // One frame survives here too.
2344+ assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
2345+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
2346+
2347+ // A clip that does not begin at its source's first frame: its head goes
2348+ // back to source frame 0 and not one frame further.
2349+ let mut p = Project::single(FILE, 9);
2350+ assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
2351+ assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
2352+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
2353+ assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
2354+ }
2355+
2356+ /// A clip whose in-point is *past* its own start -- what a ripple delete
2357+ /// leaves, the piece in front of it gone and this one slid back to frame 0
2358+ /// carrying the in-point the cut gave it. Its head has more source behind it
2359+ /// than the timeline has room for, and the timeline's own first frame is the
2360+ /// wall: asking is not an overflow, and the answer is 0.
2361+ #[test]
2362+ fn a_ripple_closed_clip_can_still_be_head_trimmed() {
2363+ let mut p = Project::single(FILE, 9);
2364+ assert!(p.split(5));
2365+ assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
2366+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
2367+
2368+ assert_eq!(
2369+ p.trim_room(Lane::V1, 0, Edge::Start, SRC),
2370+ Some((0, 3)),
2371+ "back to frame 0 at most, and one frame of clip always survives"
2372+ );
2373+ assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
2374+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2375+ assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed");
2376+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
2377+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
2378+ }
2379+
2380+ /// Linked halves trim as one: a link is one span on however many lanes, so
2381+ /// the sound follows the picture's edge -- and the tightest wall of the two
2382+ /// is what stops both.
2383+ #[test]
2384+ fn linked_halves_trim_together() {
2385+ let mut p = three();
2386+ let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
2387+ assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
2388+
2389+ assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
2390+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
2391+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
2392+ assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it");
2393+ assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
2394+ links_are_consistent(&p.lanes).expect("one id per lane, one span");
2395+
2396+ // Something in the way on the *audio* lane stops the picture's tail as
2397+ // well: the group can only go as far as its tightest member.
2398+ assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
2399+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2400+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
2401+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
2402+ links_are_consistent(&p.lanes).expect("still one span");
2403+ }
2404+
2405+ /// A whole drag is one undo step -- the front-end commits once, at the
2406+ /// release -- and an edge asked to stay where it is costs none at all.
2407+ #[test]
2408+ fn a_trim_is_one_undo_step() {
2409+ let mut p = three();
2410+ let before = shape(&p);
2411+ let history = p.history.len();
2412+
2413+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2414+ assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
2415+ assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
2416+ assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
2417+ assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
2418+ assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
2419+
2420+ assert!(p.undo());
2421+ assert_eq!(shape(&p), before, "both halves back, in one step");
2422+ }
2423+
21162424 /// A moved half stays in its group: a link names a span, not a lane, so the
21172425 /// picture on `V2` is still the same take as the sound under it on `A1`.
21182426 #[test]
@@ -2141,7 +2449,16 @@ mod tests {
21412449 assert_eq!(shape(&p)[1], shape(&p)[0]);
21422450 assert_eq!(p.timeline_frames(), 5);
21432451 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
2144- assert!(!p.ripple_delete(0, 100), "and one that empties every lane");
2452+ assert!(p.undo());
2453+ assert_eq!(shape(&p), shape(&three()));
2454+ // One that takes everything is a delete like any other: the timeline
2455+ // empties, and the undo it cost brings it back whole.
2456+ assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
2457+ assert_eq!(p.timeline_frames(), 0);
2458+ assert!(
2459+ !p.ripple_delete(0, 100),
2460+ "and a delete with nothing left to take is not an undo step"
2461+ );
21452462 assert!(p.undo());
21462463 assert_eq!(shape(&p), shape(&three()));
21472464 }
@@ -2628,7 +2945,8 @@ mod tests {
26282945 assert!(p.split(4), "...and is editable from there");
26292946 assert!(p.undo());
26302947
2631- // A lane may be empty; every lane may not, and neither may no lane.
2948+ // A lane may be empty, and so may every lane -- an emptied timeline is a
2949+ // project. No lane at all is not one: there would be nothing to place on.
26322950 assert!(
26332951 Project::from_parts(
26342952 sources.clone(),
@@ -2645,7 +2963,7 @@ mod tests {
26452963 Vec::new(),
26462964 Vec::new(),
26472965 )
2648- .is_err()
2966+ .is_ok()
26492967 );
26502968 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
26512969 let bad: [Vec<Clip>; 5] = [
crates/engine/tests/playback.rsmodified+100 -0
@@ -11,6 +11,7 @@ use std::path::{Path, PathBuf};
1111 use std::thread::sleep;
1212 use std::time::{Duration, Instant};
1313
14+use engine::export::{ExportSettings, Format};
1415 use engine::project::Lane;
1516 use engine::{DecodeSession, Frame, PlaybackSession};
1617
@@ -1122,3 +1123,102 @@ fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
11221123 );
11231124 eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}");
11241125 }
1126+
1127+/// The emptied timeline, end to end: the last clip deletes like any other, what
1128+/// is left plays as black and silence with a duration of zero, it saves and
1129+/// loads back as the project it is, and one undo brings the clip back. Silent
1130+/// fixture, so this runs anywhere.
1131+#[test]
1132+fn an_emptied_timeline_plays_black_saves_loads_and_undoes() {
1133+ let path = asset("test_baseline.mp4");
1134+ let mut session = open(&path);
1135+ let whole = session.timeline_duration();
1136+ assert!(whole > 0.0);
1137+
1138+ // The sole take goes -- picture and sound of it, on every lane at once.
1139+ assert!(
1140+ session.delete_clip(Lane::V1, 0),
1141+ "the last clip deletes like any other"
1142+ );
1143+ assert!(session.is_empty(), "and the timeline is empty");
1144+ assert_eq!(session.timeline_duration(), 0.0);
1145+ assert!(session.clip_spans().is_empty());
1146+ assert_eq!(session.lanes().len(), 2, "the lanes are still there");
1147+
1148+ // It scrubs: every seek lands at zero and shows black rather than the
1149+ // picture of the clip that was deleted.
1150+ for t in [0.0, -1.0, whole, 1e9] {
1151+ session.seek(t);
1152+ assert_eq!(session.now(), 0.0, "seek to {t} on an empty timeline");
1153+ let deadline = Instant::now() + Duration::from_secs(5);
1154+ let mut black = None;
1155+ while black.is_none() && Instant::now() < deadline {
1156+ session.tick();
1157+ black = session.try_frame();
1158+ sleep(Duration::from_millis(4));
1159+ }
1160+ let frame = black.expect("an empty timeline shows one black frame");
1161+ assert_eq!(frame.index, 0);
1162+ assert!(
1163+ frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]),
1164+ "and it is black"
1165+ );
1166+ }
1167+ // It plays: nothing to show, so it is at its end at once, and nothing hangs.
1168+ session.play();
1169+ let mut last_index = None;
1170+ run_for(&mut session, &mut last_index, Duration::from_millis(200));
1171+ assert!(session.is_eos(), "an empty timeline is played out at once");
1172+ session.pause();
1173+
1174+ // Exporting nothing is a refusal in words, not a file of no frames -- and
1175+ // in the *same* words whichever format asked, because the fence sits in
1176+ // `export::start` ahead of the format, not in the mp4 path alone.
1177+ for format in [Format::Mp4, Format::Wav, Format::Flac] {
1178+ let out = std::env::temp_dir().join(format!("ve_nothing_{}", std::process::id()));
1179+ let handle = session.export_to_with(
1180+ &out,
1181+ &ExportSettings {
1182+ format,
1183+ ..ExportSettings::default()
1184+ },
1185+ );
1186+ let deadline = Instant::now() + Duration::from_secs(10);
1187+ let err = loop {
1188+ if let Some(result) = handle.result() {
1189+ break result.expect_err("an empty timeline cannot be exported");
1190+ }
1191+ assert!(Instant::now() < deadline, "{format:?} export never settled");
1192+ sleep(Duration::from_millis(10));
1193+ };
1194+ assert_eq!(
1195+ err.to_string(),
1196+ "the timeline is empty: there is nothing to export",
1197+ "{format:?}"
1198+ );
1199+ assert!(!out.exists(), "{format:?} wrote a file anyway");
1200+ }
1201+
1202+ // It saves and loads back -- still a project, still two lanes, and still
1203+ // naming the file whose frame rate the timeline counts in.
1204+ let dir = std::env::temp_dir().join(format!("ve_empty_{}", std::process::id()));
1205+ let _ = std::fs::remove_dir_all(&dir);
1206+ std::fs::create_dir_all(&dir).expect("scratch dir");
1207+ let project = dir.join("empty.edith");
1208+ session
1209+ .save_project(&project)
1210+ .expect("save an empty timeline");
1211+ let loaded = PlaybackSession::open_project(&project).expect("load it back");
1212+ assert!(loaded.is_empty(), "what came back is the empty timeline");
1213+ assert_eq!(loaded.lanes().len(), 2);
1214+ assert_eq!(loaded.sources().len(), 1, "source 0 is kept, orphan or not");
1215+ assert_eq!(loaded.meta().frame_rate, session.meta().frame_rate);
1216+ drop(loaded);
1217+ let _ = std::fs::remove_dir_all(&dir);
1218+
1219+ // ...and one gesture is one undo: the take comes back whole.
1220+ assert!(session.undo(), "the delete undoes");
1221+ assert!(!session.is_empty());
1222+ assert!((session.timeline_duration() - whole).abs() < 1e-9);
1223+ assert_eq!(session.clip_spans().len(), 1);
1224+}
crates/engine/tests/saveload.rsmodified+38 -0
@@ -100,6 +100,44 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() {
100100 std::fs::remove_dir_all(&dir).expect("cleanup");
101101 }
102102
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+
103141 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline
104142 /// with something to lose in every field.
105143 fn edited(dir: &Path) -> PlaybackSession {