diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 773097e..50e3bf0 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -13,12 +13,13 @@ use engine::audio::StreamInfo; use engine::color::ColorParams; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; -use engine::project::{Lane, LaneKind, Source}; +use engine::project::{Edge, Lane, LaneKind, Source}; use engine::scale::FitPolicy; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ - AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent, - MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point, + AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, + KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, + Point, RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size, }; @@ -216,6 +217,31 @@ struct ClipDrag { idx: usize, } +/// A clip edge being dragged: which end of which clip, and the timeline frame +/// the pointer has pulled it to. The box on screen is drawn from `to` while this +/// is set and the engine hears about it once, at the release +/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture, +/// exactly as an equalizer drag works. +#[derive(Clone, Copy)] +struct Trim { + lane: Lane, + idx: usize, + edge: Edge, + /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from + /// it is the width the release commits -- an edge stops under the pointer + /// rather than snapping back after the fact. + to: u32, + /// The dragged clip's group, so its other halves' boxes follow the edge on + /// screen exactly as the engine will move them. + link: Option, +} + +/// How wide a clip's edge is as a *target*: the strip at each end where a press +/// means "make this longer or shorter" instead of "move this to another lane". +/// Wide enough to hit, narrow enough that the middle of even a small box is +/// still the body. +const EDGE_W: f32 = 6.; + /// An open clip menu: which clip it was opened on, where it hangs, and whether /// it has been turned over to show what that clip *is* instead of what can be /// done to it. The lane and index are the ones the same click selected, so @@ -380,6 +406,10 @@ struct Player { /// A drag that started on the ruler. Moves anywhere in the window scrub /// while it is set; the release commits the exact position. scrubbing: bool, + /// A drag that started on a clip's edge, tracked on the root for + /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See + /// [`Trim`]. + trim: Option, last_scrub: Instant, last_target: u32, /// The running export. While it owns the UI the editor is read-only. @@ -569,6 +599,11 @@ impl Player { self.eos = false; self.done = false; self.pending_seek = true; + // An edit moves the indices a drag in flight is holding -- a stroke + // during one is exactly that -- and an edge committed against a moved + // index would trim a clip nobody grabbed. Dropping it is the whole fix: + // nothing has been written yet. + self.trim = None; } /// What an action does, wherever it was asked for -- a stroke, or the clip @@ -1072,7 +1107,7 @@ impl Player { _ => false, }; if selected.is_some() && !deleted { - self.notice = Some("NOTHING DELETED — the timeline cannot be emptied".into()); + self.notice = Some("NOTHING DELETED — that clip is no longer there".into()); } if deleted { self.reset_after_reseek(); @@ -1092,7 +1127,7 @@ impl Player { if session.lift_clip(lane, idx) { self.reset_after_reseek(); } else { - self.notice = Some("NOTHING LIFTED — the timeline cannot be emptied".into()); + self.notice = Some("NOTHING LIFTED — that half is no longer there".into()); } } (Some(_), None) => { @@ -1252,6 +1287,135 @@ impl Player { cx.notify(); } + /// Opens the clip menu on the box under the pointer, from the right button + /// wherever it was pressed on that box -- its middle or one of its edge + /// strips, which cover the middle's own listener. Selecting first is part of + /// it: every item acts on the clip the menu names. + fn open_menu(&mut self, lane: Lane, idx: usize, at: Point, cx: &mut Context) { + if self.modal() { + return; + } + self.select((lane, idx), cx); + self.context_menu = Some(ContextMenu { + lane, + idx, + at, + details: false, + }); + cx.notify(); + } + + /// A press on a clip's edge: the start of the drag that changes how much of + /// its source it plays. It selects the clip as a press anywhere else on the + /// box does -- the edge strip covers the box's own listener (`occlude`), so + /// this is the only one that fires there. + fn start_trim(&mut self, lane: Lane, idx: usize, edge: Edge, cx: &mut Context) { + if self.modal() || self.exporting().is_some() { + return; + } + let Some(clip) = self + .session + .as_ref() + .and_then(|session| session.lane_clips(lane).get(idx).copied()) + else { + return; + }; + self.select((lane, idx), cx); + self.trim = Some(Trim { + lane, + idx, + edge, + // Where the edge already is: a press that never moves is not an + // edit, and `Project::trim` refuses exactly that. + to: match edge { + Edge::Start => clip.start, + Edge::End => clip.end(), + }, + link: clip.link, + }); + cx.notify(); + } + + /// Where the pointer has pulled the edge to, clamped to the room the engine + /// says that edge has. Along the same bed the ruler is measured on and + /// against the same duration the boxes are drawn to, so the edge tracks the + /// pointer exactly. + fn trim_to(&mut self, x: Pixels, cx: &mut Context) { + let (duration, fps) = (self.drawn_duration(), self.fps); + let frac = frac_along(x, self.ruler.get()); + let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { + return; + }; + let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { + return; + }; + trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi); + cx.notify(); + } + + /// The release: the whole drag reaches the engine as one edit, so it is one + /// undo step. The selection survives it -- a trim inserts and removes + /// nothing, so every index a lane had still names the clip it named. + fn commit_trim(&mut self, cx: &mut Context) { + let Some(trim) = self.trim.take() else { + return; + }; + let trimmed = self + .session + .as_mut() + .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to)); + if trimmed { + self.reset_after_reseek(); + } + cx.notify(); + } + + /// The clip as the drag is showing it: an edge under the pointer moves its + /// own box, and the boxes of the halves linked to it, before anything is + /// committed. Display only -- the project is not touched until the release. + fn trimmed(&self, lane: Lane, idx: usize, clip: Clip) -> Clip { + let Some(trim) = self.trim.filter(|t| { + (t.lane, t.idx) == (lane, idx) || (t.link.is_some() && t.link == clip.link) + }) else { + return clip; + }; + match trim.edge { + // The in-point follows the head, exactly as `Project::trim` moves + // it: what stays on screen plays what it always played. + Edge::Start => Clip { + in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start)) + .clamp(0, i64::from(clip.out_frame - 1)) as u32, + start: trim.to, + ..clip + }, + Edge::End => Clip { + out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1), + ..clip + }, + } + } + + /// How long the timeline is *drawn* as: its own length, and while a tail is + /// being dragged the furthest that tail may reach. A bed that ends exactly + /// at the last frame has nowhere to put a pointer that means "longer", so + /// without this the last clip on the timeline could be pulled in and never + /// let back out. + fn drawn_duration(&self) -> f64 { + let Some(session) = &self.session else { + return 0.; + }; + let duration = session.timeline_duration(); + match self.trim { + Some(trim) if trim.edge == Edge::End => { + let (_, hi) = session + .trim_room(trim.lane, trim.idx, trim.edge) + .unwrap_or((0, 0)); + duration.max(f64::from(hi) / self.fps) + } + _ => duration, + } + } + /// The one way a library row reaches the timeline: the Add button and a row /// dragged onto a lane both come here, so there is a single answer to what /// "add this source" does. The whole source goes in at the playhead as one @@ -1693,6 +1857,16 @@ impl Player { cx.notify(); return; }; + // An emptied timeline is a timeline; it is simply not a file. Refused by + // name here rather than written as a project of no frames -- and the + // engine refuses it again on the worker (`export::start`), so a caller + // that is not this button cannot get past it either. Two fences on + // purpose: this one is the one with a keystroke to blame. + if session.is_empty() { + self.notice = Some("NOTHING TO EXPORT — the timeline is empty".into()); + cx.notify(); + return; + } session.pause(); self.export = Some(session.export_to_with(&self.export_path, &settings)); // The card has been answered; the progress line takes the panel from @@ -1774,11 +1948,9 @@ impl Render for Player { } // Read per render, never cached: a delete shortens the timeline and the - // timecode, the ruler and the clamp below all have to follow it. - let duration = self - .session - .as_ref() - .map_or(0., PlaybackSession::timeline_duration); + // timecode, the ruler and the clamp below all have to follow it -- and + // so does the room a tail being dragged needs to grow into. + let duration = self.drawn_duration(); // The clock keeps running after the last frame (wall time takes over at // audio EOF) while the picture is frozen, so the timeline the UI shows is // the clamped one, pinned to the out-point once playback is done. @@ -1986,6 +2158,17 @@ impl Render for Player { } return; } + // A clip edge is 6 px wide and the pointer leaves it on the + // first drag, so the gesture is tracked here for the same + // reason -- and it ends here too when the button came up + // outside the window, still owing its one edit. + if this.trim.is_some() { + match event.pressed_button { + Some(MouseButton::Left) => this.trim_to(event.position.x, cx), + _ => this.commit_trim(cx), + } + return; + } // A colour slider is 4 px tall and the pointer leaves it just as // fast; every sample is live, so the release owes no write of // its own -- what the last sample set is what the clip carries. @@ -2019,6 +2202,13 @@ impl Render for Player { this.commit_eq(cx); return; } + if this.trim.is_some() { + // The release lands exactly, then the gesture is + // written once -- one edit, one undo step. + this.trim_to(event.position.x, cx); + this.commit_trim(cx); + return; + } if std::mem::take(&mut this.color_dragging) { // The release lands exactly where the hand let go, and // it is a live write like every other sample: the undo @@ -3568,7 +3758,7 @@ impl Player { let (sel, sel_link) = (self.selected, self.selected_link()); let audio = lane.kind == LaneKind::Audio; let tip: SharedString = format!( - "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut", + "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut", self.keymap.display(ActionId::Select), self.keymap.display(ActionId::SelectPrev), self.keymap.display(ActionId::SelectNext), @@ -3626,6 +3816,9 @@ impl Player { })) .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) .children(clips.iter().enumerate().map(|(i, clip)| { + // What a drag on an edge is showing, which is the clip + // itself while nothing is being dragged. + let clip = &self.trimmed(lane, i, *clip); let (start, len) = ( f64::from(clip.start) / self.fps, f64::from(clip.len()) / self.fps, @@ -3704,19 +3897,44 @@ impl Player { .on_mouse_down( MouseButton::Right, cx.listener(move |this, event: &MouseDownEvent, _, cx| { - if this.modal() { - return; - } - this.select((lane, i), cx); - this.context_menu = Some(ContextMenu { - lane, - idx: i, - at: event.position, - details: false, - }); - cx.notify(); + this.open_menu(lane, i, event.position, cx); }), ) + // The two strips a drag *lengthens* the clip by, + // one at each end. They occlude the box behind + // them, which is what keeps one gesture one thing: + // a press here trims, a press anywhere else on the + // box still starts the move to another lane. + .children([Edge::Start, Edge::End].map(|edge| { + let mut zone = div() + .absolute() + .top_0() + .h_full() + .w(px(EDGE_W)) + .occlude() + .cursor(CursorStyle::ResizeLeftRight) + .hover(|s| s.bg(rgb(ACCENT))) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _: &MouseDownEvent, _, cx| { + this.start_trim(lane, i, edge, cx); + }), + ) + // Occluded, so the box's own right-button + // listener never fires here: the menu is + // the same menu, opened by the same call. + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.open_menu(lane, i, event.position, cx); + }), + ); + zone = match edge { + Edge::Start => zone.left_0(), + Edge::End => zone.right_0(), + }; + zone + })) // Under the label row, never through it. .children(wave.filter(|_| audio).and_then(|wave| { let inner: AnyElement = match wave { @@ -5371,6 +5589,64 @@ mod tests { ); } + /// The trim-a-clip path through the doors the edge drag uses: + /// [`Player::trim_to`] clamps the pointer with `trim_room` and + /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less + /// of its file, the sound linked to it follows, the head trim moves the + /// in-point, and one undo takes a whole gesture back. + /// + /// The routing *to* these doors -- the 6 px edge strip claiming the press + /// the clip's own body-drag would otherwise take -- is gpui hitbox + /// behaviour (`occlude`) and is not reachable without a window. + #[test] + fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() { + use engine::project::Edge; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let whole = session.lane_clips(Lane::V1)[0]; + let full = session.timeline_duration(); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::End), + Some((whole.start + 1, whole.end())), + "the file's own last frame is how far the tail goes" + ); + assert!( + !session.trim_clip(Lane::V1, 0, Edge::End, 9_999), + "it already plays all of it" + ); + + // Pulled in by a third: the timeline ends earlier and the sound with it. + let shorter = whole.end() - whole.len() / 3; + assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter)); + assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter); + assert_eq!( + session.lane_clips(Lane::A1)[0].end(), + shorter, + "the linked sound was trimmed with the picture" + ); + assert!(session.timeline_duration() < full, "and plays out earlier"); + + // ...and dragged back out, as far as the file goes and no further. + assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999)); + assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the whole take back"); + + // The head takes the in-point with it, so what plays at the new start + // is source frame 10 rather than source frame 0. + assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10)); + let head = session.lane_clips(Lane::V1)[0]; + assert_eq!((head.start, head.in_frame), (10, 10)); + assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too"); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0), + Some(0), + "and it may be pulled back out to the file's first frame" + ); + + assert!(session.undo(), "one step for the whole drag"); + assert_eq!(session.lane_clips(Lane::V1)[0], whole); + } + /// The move-a-clip-between-tracks path through the door the drop uses /// ([`Player::move_clip`] calls exactly this): the clip changes row, the /// *picture* comes from the new row afterwards -- which is what "it plays @@ -6542,6 +6818,7 @@ fn main() { streams: HashMap::new(), clipboard: None, scrubbing: false, + trim: None, last_scrub: Instant::now(), last_target: 0, export: None, diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 947bee0..0e5208c 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -504,9 +504,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } } } - if doc.lanes.iter().all(|(_, clips)| clips.is_empty()) { - return Err("no clips: an empty timeline is not a project".into()); - } + // A file whose lanes are all empty *is* a project -- the emptied timeline, + // saved. What it may not be is laneless; [`crate::Project::from_parts`] + // refuses that one, by the name it has there. Ok(doc) } @@ -870,13 +870,10 @@ mod tests { ] { assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want); } - // Lanes and nothing on them is not a project. - assert_eq!( - parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir) - .unwrap_err() - .to_string(), - "no clips: an empty timeline is not a project" - ); + // Lanes and nothing on them is the emptied timeline, saved: a project. + let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse"); + assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty())); + assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip"); } /// One band, spelled the way an eq line spells it. @@ -1539,19 +1536,28 @@ mod tests { } } + /// The emptied timeline writes and reads back: every lane declared, no clip + /// on any of them, and the source that gave the project its frame rate still + /// named. Nothing about the format changes for it -- an empty lane already + /// had a line of its own. #[test] - fn a_project_without_clips_is_not_a_project() { + fn a_project_without_clips_round_trips() { let dir = PathBuf::from("/proj"); + let source = Source { + path: PathBuf::from("/proj/a.mp4"), + audio_stream: 0, + }; + let bytes = flat(&dir, &[source.clone()], &two(Vec::new(), Vec::new()), 0); + let back = parse(&bytes, &dir).expect("an emptied timeline is a project"); + assert_eq!(back.sources, vec![source]); + assert_eq!(back.lanes, two(Vec::new(), Vec::new())); + assert_eq!(back.playhead, 0); + // Older dialects, where the two lanes are implied rather than declared. assert_eq!( - parse(b"edith 1\nsource a.mp4\n", &dir) - .unwrap_err() - .to_string(), - "no clips: an empty timeline is not a project" - ); - assert_eq!( - parse(b"edith 1\n", &dir).unwrap_err().to_string(), - "no clips: an empty timeline is not a project" + parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes, + two(Vec::new(), Vec::new()) ); + assert!(parse(b"edith 1\n", &dir).expect("a project of nothing").sources.is_empty()); } /// Every truncation of a good file either parses or refuses; none panics. diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 62a343f..b626490 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -165,7 +165,18 @@ pub fn start( // The rename is the last step and the only one that publishes a file // under the name the caller asked for; it stays on the same directory, // so it is atomic. + // + // An emptied timeline is a legal project and an illegal file: no + // picture, no sound, and a muxer that is never created because no coded + // frame arrives. Refused by name here -- before the format is even + // looked at, so an mp4 and a WAV refuse in the same words -- rather than + // left to write a file of no frames that nothing opens. Every caller of + // `start` comes through this, the app's own door + // (`PlaybackSession::is_empty`) being only the first fence. let written = match settings.format { + _ if project.timeline_frames() == 0 => { + Err("the timeline is empty: there is nothing to export".into()) + } Format::Mp4 => run(&project, &meta, &part, &worker, &settings), format => run_audio(&project, &meta, &part, &worker, format), }; diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index ff0ec66..c0a5423 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -25,7 +25,7 @@ use crate::color::ColorParams; use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Demuxer, VideoMeta}; use crate::eq::EqParams; -use crate::project::{Clip, Lane, LaneKind, Project, Source, Span}; +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span}; use crate::scale::{Composer, FitPolicy}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -122,13 +122,28 @@ pub struct PlaybackSession { /// The edit list. Everything a caller says in seconds is a *timeline* /// position; only this maps it onto the file. project: Project, + /// How many frames each source actually holds, indexed exactly as + /// [`Project::sources`] is and grown with it. The project itself does not + /// know -- a clip names a source by index and carries its own range -- and + /// [`Self::trim_clip`] is the one edit that could ask for frames past the + /// end of a file, which is a save that would not open again + /// ([`Self::open_project`] refuses one by name). Append-only for + /// `sources`'s reason: an index handed out stays valid, undone import or + /// not. + counts: Vec, /// What the current video worker was opened for: where it sits on the /// timeline, how long it runs, and which source frame it started at -- /// together they rewrite a source frame index into a timeline one. Not a /// clip index: a `split` cuts the clip under a running worker, and only the /// mapping survives that. A span with no source is a *gap*, and the worker /// feeding it emits black frames indexed from zero. - span: Span, + /// + /// `None` is the *emptied* timeline -- no clip on any lane, so there is no + /// stretch to be inside of. It is a state, not a failure: the picture is + /// black ([`start_span`](Self::start_span) feeds one black frame for it), + /// the sound is silence, the duration is zero, and placing anything reseeks + /// straight back out of it. + span: Option, /// The last clip has been played out; see [`PlaybackSession::is_eos`]. eos: bool, } @@ -174,7 +189,7 @@ impl PlaybackSession { // One clip per lane covering the file, so timeline == source until the // first edit -- and the range opened above is exactly that clip's. let project = Project::single(&path, meta.frame_count); - let span = project.composite_span_at(0).expect("never empty"); + let span = project.composite_span_at(0); Ok(Self { meta, native: (meta.width, meta.height), @@ -185,6 +200,7 @@ impl PlaybackSession { audio, audio_disabled, project, + counts: vec![meta.frame_count], span, eos: false, }) @@ -290,7 +306,7 @@ impl PlaybackSession { let playhead = doc.playhead; let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?; - let span = project.composite_span_at(0).expect("never empty"); + let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and // only a session's `drop` retires it, so a refusal above this line would @@ -310,6 +326,7 @@ impl PlaybackSession { audio, audio_disabled, project, + counts, span, eos: false, }; @@ -370,9 +387,12 @@ impl PlaybackSession { match self.frames.try_recv() { Ok(mut frame) => { // A gap's worker indexes from zero, a decoder's from its in - // point: `base` is whichever this span started at. - let base = self.span.from.map_or(0, |(_, in_frame)| in_frame); - frame.index = self.span.start + frame.index.saturating_sub(base); + // point: `base` is whichever this span started at. An empty + // timeline has no span, and its one black frame is frame 0. + let (start, base) = self + .span + .map_or((0, 0), |s| (s.start, s.from.map_or(0, |(_, i)| i))); + frame.index = start + frame.index.saturating_sub(base); return Some(frame); } Err(TryRecvError::Empty) => return None, @@ -415,35 +435,47 @@ impl PlaybackSession { /// than remembered as a clip index, because a `split` while playing cuts the /// clip under the running worker and only the mapping stays true. fn next_clip(&mut self) -> bool { - let next = self.span.end(); + // No span is the emptied timeline: it was played out the moment its one + // black frame went by, and there is no "next" to walk to. + let next = match self.span { + Some(span) => span.end(), + None => return false, + }; let Some(span) = self.project.composite_span_at(next) else { return false; }; // We only get here on a disconnect, so the old worker has already // returned; cancel anyway, so `retire` treats every path alike. self.worker.cancel(); - self.start_span(span); + self.start_span(Some(span)); true } /// Points the video worker at `span`: a decoder over its source range, or a - /// black-frame generator for a gap. The old worker must already have been - /// cancelled -- this is the half both `seek` and `next_clip` share. + /// black-frame generator for a gap -- and for `None`, the emptied timeline, + /// which is one frame of black so the viewer shows the nothing that is + /// there rather than the last picture of the clip that was deleted. The old + /// worker must already have been cancelled -- this is the half both `seek` + /// and `next_clip` share. /// /// A source that will not open leaves the *span* installed anyway: the /// timeline still moves, there are simply no more pictures, and the /// disconnected receiver carries the session on to the next span. - fn start_span(&mut self, span: Span) { - let opened = match span.from { + fn start_span(&mut self, span: Option) { + let opened = match span { // The grade is the composite's at this frame -- the same clip the // span itself came from -- and it is constant across the span, so // the worker carries it and every frame it converts wears it. - Some((source, in_frame)) => DecodeSession::open_worker( + Some(Span { + start, + len, + from: Some((source, in_frame)), + }) => DecodeSession::open_worker( &self.project.sources()[source].path, in_frame, - in_frame + span.len, + in_frame + len, self.project - .composite_color_at(span.start) + .composite_color_at(start) .copied() .unwrap_or_default(), // ...and the canvas it is placed on: the project's resolution @@ -452,15 +484,18 @@ impl PlaybackSession { Composer::new( self.meta.width, self.meta.height, - self.project.composite_fit_at(span.start), + self.project.composite_fit_at(start), ), ) .map(|(_, stream)| stream) - .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)), - None => Ok(DecodeSession::open_black( + .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")), + // A gap: black for as long as it runs. An emptied timeline has no + // span at all and gets one frame of it -- enough to put black on + // screen, and it ends where the timeline does, at once. + gap => Ok(DecodeSession::open_black( self.meta.width, self.meta.height, - span.len, + gap.map_or(1, |s| s.len), )), }; if let Ok(stream) = opened { @@ -480,6 +515,14 @@ impl PlaybackSession { f64::from(self.project.timeline_frames()) / self.meta.frame_rate } + /// Whether no lane holds anything: the emptied timeline, which plays black + /// and silent and is zero seconds long. A state, not a failure -- but the + /// one a caller with nothing to render (an export) has to refuse by name + /// rather than write a file of no frames. + pub fn is_empty(&self) -> bool { + self.project.timeline_frames() == 0 + } + /// `(start, len)` per clip in timeline seconds, in order: what a clips lane /// needs to lay itself out. Selection is the caller's business. pub fn clip_spans(&self) -> Vec<(f64, f64)> { @@ -575,8 +618,9 @@ impl PlaybackSession { /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, /// silence on the audio one, and nothing else moves. Reseeks, because what - /// the playhead sits on has changed. `false` for a bad index and for the - /// lift that would leave the whole timeline empty. + /// the playhead sits on has changed. `false` for a bad index -- the lift of + /// the last placement there is empties the timeline, which is a state + /// ([`is_empty`](Self::is_empty)) and one undo away. pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { self.edit(|p| p.lift(lane, idx)) } @@ -591,6 +635,45 @@ impl PlaybackSession { self.edit(|p| p.move_to_lane(from, idx, to)) } + /// Drags one end of that clip to timeline frame `to`, changing how much of + /// its source it plays and nothing else on the lane -- see [`Project::trim`] + /// for the walls it is clamped by, which this fills the source lengths in + /// for. One undo step per call, so a front-end calls it once, at the release + /// of the drag. Reseeks like every other edit, which is what makes the + /// picture (and the sound) follow a new in-point straight away. `false` for + /// a bad index and for an edge already where it was asked to go. + /// + /// A *frame*, where the rest of this type takes seconds: a drag has already + /// asked [`trim_room`](Self::trim_room) where the edge may land, and that + /// answer is in frames -- converting it back through seconds would be a + /// rounding step between the width drawn and the width committed. + pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool { + // Spelled out rather than through `edit`, whose closure cannot hold a + // second borrow of the session while it has the project. + if !self.project.trim(lane, idx, edge, to, &self.counts) { + return false; + } + let now = self.now(); + self.seek(now); + true + } + + /// Where that edge may land, `(first, last)` timeline frame inclusive: what + /// a drag clamps the pointer to so the box it draws is the box + /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index. + pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> { + self.project.trim_room(lane, idx, edge, &self.counts) + } + + /// Records how long a source is, for a source index that may be one + /// `Project::import` just made or one it handed back. See [`Self::counts`]. + fn note_frames(&mut self, source: usize, frames: u32) { + if source == self.counts.len() { + self.counts.push(frames); + } + debug_assert_eq!(self.counts.len(), self.project.sources().len()); + } + /// The clip the picture is coming from at `timeline_secs`: the lane it sits /// on and its index there, by the same topmost-lane-wins rule the decoder /// follows. `None` over a gap and past the end. What a card that grades @@ -737,6 +820,7 @@ impl PlaybackSession { let first = self.first_audio()?; audio_matches(&wanted, &first)?; let source = self.project.import(path, stream); + self.note_frames(source, frames.max(1)); let clip = Clip { start: 0, in_frame: 0, @@ -793,7 +877,8 @@ impl PlaybackSession { /// on every lane. Unlike a split this *does* move every following frame, so /// the session reseeks to wherever the playhead now points. /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead. - /// `false` for a bad index or the last remaining clip. + /// `false` for a bad index; the last remaining clip goes like any other and + /// leaves the timeline empty ([`is_empty`](Self::is_empty)). /// /// The lane travels because the index is a lane's own: `V2`'s third clip is /// not `V1`'s, and a front-end that could only say "the third clip" would @@ -828,6 +913,7 @@ impl PlaybackSession { let old_end = self.timeline_duration(); let source = self.project.import(path, 0); + self.note_frames(source, meta.frame_count); // Refused only for an unknown index, and this one just came from `import`. self.project.append_clip(source, meta.frame_count); // Reseek like any other edit, even though nothing before the playhead @@ -860,6 +946,7 @@ impl PlaybackSession { let old_end = self.timeline_duration(); let source = self.project.import(path, 0); + self.note_frames(source, frames); let at = self.project.timeline_frames(); self.project.place( Lane::A1, @@ -984,12 +1071,10 @@ impl PlaybackSession { // [`retire`](Self::retire), which is what keeps a scrub off the price // of a VA-API init. self.worker.cancel(); - // `target` is inside the timeline (never empty), so this always spans; - // the span runs from there to the end of whatever it landed in -- a - // clip, or a gap, which starts a black-frame worker instead. - if let Some(span) = self.project.composite_span_at(target) { - self.start_span(span); - } + // The span runs from `target` to the end of whatever it landed in -- a + // clip, or a gap, which starts a black-frame worker instead. `None` is + // the emptied timeline, black too, and `start_span` says so. + self.start_span(self.project.composite_span_at(target)); self.eos = false; let mut audio_running = false; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 5fb2ce9..9752f56 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -212,6 +212,17 @@ impl LaneData { } } +/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Edge { + /// Its first timeline frame; moving it changes where in the source the clip + /// starts reading, so the picture behind the edge slides with it. + Start, + /// One past its last timeline frame; moving it only says how much of the + /// source to keep. + End, +} + /// What a lane holds over one stretch of the timeline: either a placed clip or /// a gap. Returned already trimmed to the position it was asked about, so a /// caller can hand `len` straight to a decoder (or to a black-frame generator). @@ -299,10 +310,16 @@ impl Project { /// [`Project::undo`] is `false` until the first edit of the new session. /// This is the one door untrusted parts come in through, so every invariant /// every other constructor keeps is checked here, by name and in release: - /// every lane empty, an empty clip, a clip naming a source (or an equalizer, + /// no lanes at all, an empty clip, a clip naming a source (or an equalizer, /// or a colour) that is not there, a clip whose end overflows, a lane that is /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`] /// below. + /// + /// A project whose lanes are all *empty* is not among them: an emptied + /// timeline is a project like any other -- it plays black and silent, it + /// saves, and it loads back. What a project cannot be is laneless, because + /// [`Project::lanes`] is what a front-end lays out and what every `Lane` + /// handle indexes into. pub fn from_parts( sources: Vec, lanes: Vec<(LaneKind, Vec)>, @@ -315,8 +332,8 @@ impl Project { if let Some(bad) = color.iter().position(|p| !color_finite(p)) { return Err(format!("color {bad} holds a value that is not a finite number").into()); } - if lanes.iter().all(|(_, clips)| clips.is_empty()) { - return Err("every lane is empty: that is not a project".into()); + if lanes.is_empty() { + return Err("no lanes at all: that is not a project".into()); } let lanes: Vec = lanes .into_iter() @@ -421,9 +438,8 @@ impl Project { /// that could not be taken back would be the one edit with no way out. /// Nothing plays differently until something is placed on it. /// - /// The new lane being empty is fine even though [`Project::from_parts`] - /// refuses an all-empty project: the lanes that were there still hold the - /// timeline, and "no lane holds anything" is what that door refuses. + /// An empty lane is a lane like any other -- so is a whole project of them + /// ([`Project::from_parts`]); nothing plays until something is placed. pub fn add_lane(&mut self, kind: LaneKind) -> Lane { self.snapshot(); self.lanes.push(LaneData { @@ -525,6 +541,11 @@ impl Project { /// [`set_color`](Project::set_color) leaves settings nothing plays behind, /// and this is the one moment they can go -- the indexes that survive it are /// only the ones a clip names. + /// + /// One exception, and it is the emptied timeline's: a project no clip plays + /// from still keeps source 0. It is the file a session is scaffolded from -- + /// its frame rate is the timeline's and is written nowhere else -- so a save + /// that pruned it would write a project that cannot be loaded back at all. pub fn without_orphan_sources(&self) -> Parts { let mut moved = vec![None; self.sources.len()]; let mut sources = Vec::new(); @@ -566,6 +587,9 @@ impl Project { }); } } + if sources.is_empty() { + sources.extend(self.sources.first().cloned()); + } ( sources, lanes.into_iter().map(|l| (l.kind, l.clips)).collect(), @@ -1051,6 +1075,145 @@ impl Project { true } + /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` -- + /// the drag on a clip's end that makes it play more or less of its source. + /// The rest of the lane stays exactly where it is (nothing ripples), so what + /// a shortened clip leaves behind is a gap and what a lengthened one takes + /// is room that was already empty. One snapshot, so a whole drag is one + /// [`Project::undo`] -- commit once, at the release, rather than per pointer + /// sample. Changes the timeline->source mapping: the caller must reseek. + /// + /// [`Edge::Start`] moves the in-point with it: the frames that stay play + /// exactly what they played before, which is what makes this a trim and not + /// a slip. + /// + /// `to` is **clamped**, never refused -- a hand pulling an edge past what is + /// legal means "as far as it goes", and stopping the box there is the + /// affordance. The walls are: one frame of clip always survives, an edge + /// never crosses the neighbouring clip on its own lane, an in-point never + /// walks back past the source's first frame, and an out-point never runs + /// past `source_frames[clip.source]` -- the caller's table of how long each + /// source actually is ([`Project`] does not know, and a clip ending past its + /// file's last frame is a save that will not open again; see + /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry + /// there may not grow at all. + /// + /// Linked clips trim *together*, to one clamped edge: a link is one span on + /// however many lanes ([`links_are_consistent`]), so a picture trimmed away + /// from its sound would be a group no save could load. The room is therefore + /// what every member of the group has -- the tightest wall wins. + /// + /// `false`, changing nothing and costing no undo step, for an index that is + /// not there and for an edge that is already where it was asked to go. + pub fn trim( + &mut self, + lane: Lane, + idx: usize, + edge: Edge, + to: u32, + source_frames: &[u32], + ) -> bool { + let (Some((lo, hi)), Some(clip)) = ( + self.trim_room(lane, idx, edge, source_frames), + self.lane(lane).get(idx).copied(), + ) else { + return false; + }; + let to = to.clamp(lo, hi); + let at = match edge { + Edge::Start => clip.start, + Edge::End => clip.end(), + }; + if to == at { + return false; + } + self.snapshot(); + for (l, i) in self.group_of(lane, idx).expect("checked above") { + let c = &mut self.lanes[l].clips[i]; + match edge { + Edge::Start => { + // Non-negative by `lo`, which is what keeps the in-point on + // the source. + c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32; + c.start = to; + } + Edge::End => c.out_frame = c.in_frame + (to - c.start), + } + debug_assert!(sorted_disjoint(&self.lanes[l].clips)); + } + true + } + + /// How far that edge may travel, `(first, last)` timeline frame inclusive -- + /// the walls [`trim`](Project::trim) clamps to, without moving anything. + /// What a front-end drawing the box *during* a drag asks, so the live width + /// is the width the release will commit and an edge stops under the pointer + /// rather than snapping back. `None` for an index that is not there. + pub fn trim_room( + &self, + lane: Lane, + idx: usize, + edge: Edge, + source_frames: &[u32], + ) -> Option<(u32, u32)> { + let (mut lo, mut hi) = (u32::MIN, u32::MAX); + for (l, i) in self.group_of(lane, idx)? { + let clips = &self.lanes[l].clips; + let c = clips[i]; + let (member_lo, member_hi) = match edge { + Edge::Start => ( + // Back to the source's own first frame, and never over the + // clip in front of it. Saturating because a clip may hold + // *more* head than the timeline has room for -- a ripple + // delete slides a clip back to frame 0 with its in-point + // wherever the cut left it -- and frame 0 is the other wall. + c.start + .saturating_sub(c.in_frame) + .max(i.checked_sub(1).map_or(0, |p| clips[p].end())), + c.end() - 1, + ), + Edge::End => ( + c.start + 1, + // Out to whatever is left of the source, and never over the + // clip behind it. + c.start + .saturating_add( + source_frames + .get(c.source) + .copied() + .unwrap_or(c.out_frame) + .saturating_sub(c.in_frame), + ) + .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)), + ), + }; + lo = lo.max(member_lo); + hi = hi.min(member_hi); + } + // `hi.max(lo)`: for a clip the invariants hold for, the range always + // contains the edge's own place, and a caller's wrong `source_frames` + // must not become an empty range (or a panicking `clamp`) here. + Some((lo, hi.max(lo))) + } + + /// The clips that move as one with the clip at `idx` of `lane` -- itself and + /// whatever carries its link on the other lanes -- as `(lane storage index, + /// clip index)` pairs. `None` for an index that is not there. + fn group_of(&self, lane: Lane, idx: usize) -> Option> { + let clip = *self.lane(lane).get(idx)?; + Some(match clip.link { + Some(link) => self + .lanes + .iter() + .enumerate() + .filter_map(|(l, data)| { + Some((l, data.clips.iter().position(|c| c.link == Some(link))?)) + }) + .collect(), + None => vec![(self.index(lane).expect("the clip was found on it"), idx)], + }) + } + /// Insert `clip` into the first lane of each kind at `timeline_frame` as one /// new group, pushing everything from there on later by its length in /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip @@ -1128,13 +1291,12 @@ impl Project { } /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or - /// silence, and nothing else moves. Refused for an out-of-range index (which - /// a lane that is not there always is) and for the lift that would leave - /// *every* lane empty -- an empty timeline is the front-end's state, not a - /// project's (see the never-empty invariant). + /// silence, and nothing else moves. Refused only for an out-of-range index + /// (which a lane that is not there always is) -- lifting the last placement + /// there is leaves an *empty* timeline, which is a state the project holds + /// like any other and an undo brings back. pub fn lift(&mut self, lane: Lane, idx: usize) -> bool { - let placed: usize = self.lanes.iter().map(|l| l.clips.len()).sum(); - if idx >= self.lane(lane).len() || placed == 1 { + if idx >= self.lane(lane).len() { return false; } self.snapshot(); @@ -1144,23 +1306,17 @@ impl Project { /// Cut the timeline frames `[at, at + len)` out of *every* lane and close /// the hole: everything after slides back by `len`. The rippling delete -- - /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an - /// empty range and when it would leave every lane empty. + /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an + /// empty range; a delete that leaves nothing behind empties the timeline, + /// which is a state like any other and one undo away. pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool { if len == 0 { return false; } - let survivors: usize = self - .lanes - .iter() - .map(|l| { - l.clips - .iter() - .filter(|c| c.start < at || c.end() > at + len) - .count() - }) - .sum(); - if survivors == 0 { + // Nothing reaches past `at`: there is nothing to cut and nothing to + // slide back, and a delete that changes nothing must not cost an undo + // step (see [`snapshot`](Project::snapshot)). + if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| c.end() > at) { return false; } self.snapshot(); @@ -1951,7 +2107,11 @@ mod tests { assert!(!p.delete(2), "index past the end"); assert!(p.delete(1)); - assert!(!p.delete(0), "the last remaining clip stays"); + assert!(p.delete(0), "and the last remaining clip goes too"); + assert_eq!(p.clips().len(), 0); + assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable"); + assert!(!p.delete(0), "there is nothing left to delete"); + assert!(p.undo(), "one gesture, one undo"); assert_eq!(p.clips().len(), 1); } @@ -2002,13 +2162,28 @@ mod tests { } } + /// The timeline is emptiable: the last placement comes off like any other, + /// the project holds "nothing on any lane" as a state, and one undo per + /// gesture brings it back. #[test] - fn the_last_clip_of_the_last_lane_cannot_be_lifted() { + fn the_last_clip_of_the_last_lane_lifts_and_undoes() { let mut p = Project::single(FILE, 9); assert!(p.lift(Lane::A1, 0), "a silent timeline is fine"); - assert!(!p.lift(Lane::V1, 0), "an empty one is not"); + assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too"); + assert_eq!(p.timeline_frames(), 0); + assert_eq!(p.composite_span_at(0), None, "nothing to show"); + assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list"); assert!(!p.lift(Lane::A1, 0), "index past the end"); - assert_eq!(p.timeline_frames(), 9); + assert!(p.undo(), "and the last lift comes back"); + assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]); + // A saved-and-loaded empty timeline is a project like any other, and it + // still names the file its frame rate came from. + assert!(p.lift(Lane::V1, 0)); + let (sources, lanes, eq, color) = p.without_orphan_sources(); + assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline"); + let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads"); + assert_eq!(back.timeline_frames(), 0); + assert_eq!(back.lanes().len(), 2, "and it kept its lanes"); } /// What a keyboard selection walks: one answer per lane, gaps included -- @@ -2113,6 +2288,139 @@ mod tests { assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]); } + /// How long `FILE` is, which is what a trim's tail is allowed to reach: + /// [`three`] cuts up all nine of its frames. + const SRC: &[u32] = &[9]; + + /// The drag on a clip's tail: it plays less (or more) of its source, nothing + /// else on the lane moves, and every wall stops the edge rather than + /// refusing the gesture. + #[test] + fn trimming_the_tail_stops_at_every_wall() { + let mut p = three(); + + // Pulled in: a gap opens behind it and the clip after it stays put. + assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC)); + assert_eq!( + shape(&p)[0], + vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)] + ); + assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing"); + assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap"); + + // ...and back out, no further than the clip behind it. + assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC)); + assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour"); + assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall"); + + // One frame of clip always survives, however far back the pointer went. + assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC)); + assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0)); + + // The last clip has no neighbour, so what stops it is the file: nine + // frames is nine frames. + assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC)); + assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC)); + assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take"); + assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further"); + // A source nobody told us the length of may not grow at all -- an + // out-point past the end of a file is a save that will not open again. + assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[])); + assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown"); + } + + /// The head pulled in takes the in-point with it -- what stays plays what it + /// always played -- and stops at the source's own first frame. + #[test] + fn trimming_the_head_moves_the_in_point() { + let mut p = three(); + assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); + assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front"); + assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2"); + assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap"); + assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again"); + assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0)); + // One frame survives here too. + assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC)); + assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0)); + + // A clip that does not begin at its source's first frame: its head goes + // back to source frame 0 and not one frame further. + let mut p = Project::single(FILE, 9); + assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0))); + assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it"); + assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC)); + assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left"); + } + + /// A clip whose in-point is *past* its own start -- what a ripple delete + /// leaves, the piece in front of it gone and this one slid back to frame 0 + /// carrying the in-point the cut gave it. Its head has more source behind it + /// than the timeline has room for, and the timeline's own first frame is the + /// wall: asking is not an overflow, and the answer is 0. + #[test] + fn a_ripple_closed_clip_can_still_be_head_trimmed() { + let mut p = Project::single(FILE, 9); + assert!(p.split(5)); + assert!(p.delete_in(Lane::V1, 0), "the first piece goes"); + assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5"); + + assert_eq!( + p.trim_room(Lane::V1, 0, Edge::Start, SRC), + Some((0, 3)), + "back to frame 0 at most, and one frame of clip always survives" + ); + assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there"); + assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); + assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed"); + assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out"); + assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]); + } + + /// Linked halves trim as one: a link is one span on however many lanes, so + /// the sound follows the picture's edge -- and the tightest wall of the two + /// is what stops both. + #[test] + fn linked_halves_trim_together() { + let mut p = three(); + let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids"); + assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped"); + + assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC)); + assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0)); + assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed"); + assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it"); + assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows"); + links_are_consistent(&p.lanes).expect("one id per lane, one span"); + + // Something in the way on the *audio* lane stops the picture's tail as + // well: the group can only go as far as its tightest member. + assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0))); + assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC)); + assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip"); + assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0)); + links_are_consistent(&p.lanes).expect("still one span"); + } + + /// A whole drag is one undo step -- the front-end commits once, at the + /// release -- and an edge asked to stay where it is costs none at all. + #[test] + fn a_trim_is_one_undo_step() { + let mut p = three(); + let before = shape(&p); + let history = p.history.len(); + + assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC)); + assert_eq!(p.history.len(), history + 1, "one snapshot per gesture"); + assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there"); + assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip"); + assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC)); + assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing"); + + assert!(p.undo()); + assert_eq!(shape(&p), before, "both halves back, in one step"); + } + /// A moved half stays in its group: a link names a span, not a lane, so the /// picture on `V2` is still the same take as the sound under it on `A1`. #[test] @@ -2141,7 +2449,16 @@ mod tests { assert_eq!(shape(&p)[1], shape(&p)[0]); assert_eq!(p.timeline_frames(), 5); assert!(!p.ripple_delete(0, 0), "an empty range is not a delete"); - assert!(!p.ripple_delete(0, 100), "and one that empties every lane"); + assert!(p.undo()); + assert_eq!(shape(&p), shape(&three())); + // One that takes everything is a delete like any other: the timeline + // empties, and the undo it cost brings it back whole. + assert!(p.ripple_delete(0, 100), "the timeline is emptiable"); + assert_eq!(p.timeline_frames(), 0); + assert!( + !p.ripple_delete(0, 100), + "and a delete with nothing left to take is not an undo step" + ); assert!(p.undo()); assert_eq!(shape(&p), shape(&three())); } @@ -2628,7 +2945,8 @@ mod tests { assert!(p.split(4), "...and is editable from there"); assert!(p.undo()); - // A lane may be empty; every lane may not, and neither may no lane. + // A lane may be empty, and so may every lane -- an emptied timeline is a + // project. No lane at all is not one: there would be nothing to place on. assert!( Project::from_parts( sources.clone(), @@ -2645,7 +2963,7 @@ mod tests { Vec::new(), Vec::new(), ) - .is_err() + .is_ok() ); assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err()); let bad: [Vec; 5] = [ diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index d4c7ff1..81c64f7 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -11,6 +11,7 @@ use std::path::{Path, PathBuf}; use std::thread::sleep; use std::time::{Duration, Instant}; +use engine::export::{ExportSettings, Format}; use engine::project::Lane; use engine::{DecodeSession, Frame, PlaybackSession}; @@ -1122,3 +1123,102 @@ fn an_audio_gap_is_silent_and_the_clock_keeps_counting() { ); eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}"); } + +/// The emptied timeline, end to end: the last clip deletes like any other, what +/// is left plays as black and silence with a duration of zero, it saves and +/// loads back as the project it is, and one undo brings the clip back. Silent +/// fixture, so this runs anywhere. +#[test] +fn an_emptied_timeline_plays_black_saves_loads_and_undoes() { + let path = asset("test_baseline.mp4"); + let mut session = open(&path); + let whole = session.timeline_duration(); + assert!(whole > 0.0); + + // The sole take goes -- picture and sound of it, on every lane at once. + assert!( + session.delete_clip(Lane::V1, 0), + "the last clip deletes like any other" + ); + assert!(session.is_empty(), "and the timeline is empty"); + assert_eq!(session.timeline_duration(), 0.0); + assert!(session.clip_spans().is_empty()); + assert_eq!(session.lanes().len(), 2, "the lanes are still there"); + + // It scrubs: every seek lands at zero and shows black rather than the + // picture of the clip that was deleted. + for t in [0.0, -1.0, whole, 1e9] { + session.seek(t); + assert_eq!(session.now(), 0.0, "seek to {t} on an empty timeline"); + let deadline = Instant::now() + Duration::from_secs(5); + let mut black = None; + while black.is_none() && Instant::now() < deadline { + session.tick(); + black = session.try_frame(); + sleep(Duration::from_millis(4)); + } + let frame = black.expect("an empty timeline shows one black frame"); + assert_eq!(frame.index, 0); + assert!( + frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]), + "and it is black" + ); + } + // It plays: nothing to show, so it is at its end at once, and nothing hangs. + session.play(); + let mut last_index = None; + run_for(&mut session, &mut last_index, Duration::from_millis(200)); + assert!(session.is_eos(), "an empty timeline is played out at once"); + session.pause(); + + // Exporting nothing is a refusal in words, not a file of no frames -- and + // in the *same* words whichever format asked, because the fence sits in + // `export::start` ahead of the format, not in the mp4 path alone. + for format in [Format::Mp4, Format::Wav, Format::Flac] { + let out = std::env::temp_dir().join(format!("ve_nothing_{}", std::process::id())); + let handle = session.export_to_with( + &out, + &ExportSettings { + format, + ..ExportSettings::default() + }, + ); + let deadline = Instant::now() + Duration::from_secs(10); + let err = loop { + if let Some(result) = handle.result() { + break result.expect_err("an empty timeline cannot be exported"); + } + assert!(Instant::now() < deadline, "{format:?} export never settled"); + sleep(Duration::from_millis(10)); + }; + assert_eq!( + err.to_string(), + "the timeline is empty: there is nothing to export", + "{format:?}" + ); + assert!(!out.exists(), "{format:?} wrote a file anyway"); + } + + // It saves and loads back -- still a project, still two lanes, and still + // naming the file whose frame rate the timeline counts in. + let dir = std::env::temp_dir().join(format!("ve_empty_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let project = dir.join("empty.edith"); + session + .save_project(&project) + .expect("save an empty timeline"); + let loaded = PlaybackSession::open_project(&project).expect("load it back"); + assert!(loaded.is_empty(), "what came back is the empty timeline"); + assert_eq!(loaded.lanes().len(), 2); + assert_eq!(loaded.sources().len(), 1, "source 0 is kept, orphan or not"); + assert_eq!(loaded.meta().frame_rate, session.meta().frame_rate); + drop(loaded); + let _ = std::fs::remove_dir_all(&dir); + + // ...and one gesture is one undo: the take comes back whole. + assert!(session.undo(), "the delete undoes"); + assert!(!session.is_empty()); + assert!((session.timeline_duration() - whole).abs() < 1e-9); + assert_eq!(session.clip_spans().len(), 1); +} diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 308e03e..eb828ab 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -100,6 +100,44 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() { std::fs::remove_dir_all(&dir).expect("cleanup"); } +/// Why a trim's tail stops where the file ends: a clip reaching past the last +/// frame of its source is a project that will not open again (`open_project` +/// refuses it by name). Pulled in on both ends and then dragged out as far as +/// the pointer can ask for, the save still comes back as itself. +#[test] +fn a_trimmed_timeline_saves_and_opens_again() { + use engine::project::Edge; + + let dir = scratch("trim"); + let media = copy_in(&dir, "test_av.mp4"); + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + let whole = session.clip_at(0).expect("one clip"); + + assert!(session.trim_clip(Lane::V1, 0, Edge::End, whole.end() / 2)); + assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 5)); + let path = dir.join("trimmed.edith"); + session.save_project(&path).expect("save"); + let loaded = PlaybackSession::open_project(&path).expect("a trimmed project opens"); + assert_eq!( + loaded.clip_at(0).map(|c| (c.start, c.in_frame, c.out_frame)), + Some((5, 5, whole.end() / 2)), + "the trimmed range is what came back" + ); + + // A hand that keeps pulling: the tail stops at the file's own last frame, + // and the save of *that* opens too. + assert!(session.trim_clip(Lane::V1, 0, Edge::End, u32::MAX)); + assert_eq!( + session.clip_at(0).expect("still one clip").out_frame, + whole.out_frame, + "as far as the file goes and not one frame further" + ); + session.save_project(&path).expect("save"); + PlaybackSession::open_project(&path).expect("and it still opens"); + std::fs::remove_dir_all(&dir).expect("cleanup"); +} + /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline /// with something to lose in every field. fn edited(dir: &Path) -> PlaybackSession {