diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index b54e2a4..413905c 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -53,6 +53,8 @@ pub enum ActionId { Paste, Cut, Regroup, + Detach, + Group, Select, SelectNext, SelectPrev, @@ -74,7 +76,7 @@ pub enum ActionId { impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 29] = [ + pub const ALL: [ActionId; 31] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -88,6 +90,8 @@ impl ActionId { ActionId::Paste, ActionId::Cut, ActionId::Regroup, + ActionId::Detach, + ActionId::Group, ActionId::Select, ActionId::SelectNext, ActionId::SelectPrev, @@ -122,6 +126,8 @@ impl ActionId { ActionId::Paste => "Paste", ActionId::Cut => "Cut", ActionId::Regroup => "Regroup", + ActionId::Detach => "Detach the sound from the picture", + ActionId::Group => "Group with the clip on another track", ActionId::Select => "Select the clip under the playhead (again for the next lane)", ActionId::SelectNext => "Select the next clip in the lane", ActionId::SelectPrev => "Select the previous clip in the lane", @@ -158,6 +164,8 @@ impl ActionId { ActionId::Paste => "paste", ActionId::Cut => "cut", ActionId::Regroup => "regroup", + ActionId::Detach => "detach", + ActionId::Group => "group", ActionId::Select => "select", ActionId::SelectNext => "select-next", ActionId::SelectPrev => "select-prev", @@ -207,6 +215,8 @@ impl ActionId { ActionId::Resolution => Category::View, ActionId::Cut | ActionId::Regroup + | ActionId::Detach + | ActionId::Group | ActionId::Undo | ActionId::AddVideoLane | ActionId::AddAudioLane => Category::Editing, @@ -453,6 +463,12 @@ impl Keymap { // The two lane keys, on the letters they are named after: both // were free, and neither is next to a key that edits. b(ActionId::Regroup, "g", false), + // The pair that takes a take apart and puts it back: "d" for + // detach was free and is one press like the rest of the clip + // keys, and grouping two clips is the "g" that rejoins a cut one + // lane over -- the chord beside it, so the two read as one idea. + b(ActionId::Detach, "d", false), + b(ActionId::Group, "g", true), // Selection without a pointer. Tab is what a keyboard already // means by "move on to the next thing", and the two brackets // are the pair either side of it in the lane -- shift+tab is @@ -753,7 +769,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 31); + assert_eq!(k.entries().len(), 33); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -769,6 +785,9 @@ mod tests { assert_eq!(k.lookup("v", true), Some(ActionId::Paste)); assert_eq!(k.lookup("c", false), Some(ActionId::Cut)); assert_eq!(k.lookup("g", false), Some(ActionId::Regroup)); + // The take apart / put back pair beside it. + assert_eq!(k.lookup("d", false), Some(ActionId::Detach)); + assert_eq!(k.lookup("g", true), Some(ActionId::Group)); // The keyboard's way onto a clip, and the pair that walks the lane. assert_eq!(k.lookup("tab", false), Some(ActionId::Select)); assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext)); @@ -977,7 +996,7 @@ mod tests { assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 29); + assert_eq!(ActionId::ALL.len(), 31); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index dd805e2..f39f421 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 @@ -285,11 +311,13 @@ impl RowItem { /// action a stroke already reaches -- the menu is a second way *to* the actions /// and never a second version of them -- so both the label and the hint come /// out of the keymap registry and the two can never disagree. -const MENU_ITEMS: [ActionId; 8] = [ +const MENU_ITEMS: [ActionId; 10] = [ ActionId::Cut, ActionId::Delete, ActionId::Lift, ActionId::Regroup, + ActionId::Detach, + ActionId::Group, ActionId::Equalizer, ActionId::Color, ActionId::Fit, @@ -349,16 +377,37 @@ const COLOR_BANDS: [(&str, f32, f32); 4] = [ ("Tint (cool–warm)", -1., 1.), ]; -/// A press of a nudge key or button: a fortieth of a band's range, so a slider -/// crosses it in forty presses and every stop is a number the file can write. +/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it +/// in forty presses and every stop is a number the file can write. A drag lands +/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard +/// cannot reach two different sets of values. const COLOR_STEP: f32 = 0.05; -/// The card's width: a slider row is a label, two buttons, the bar and the -/// value, and the longest label has to fit beside all four without truncating -/// (measured against "Tint (cool–warm)" at 460). +/// The card's width: a slider row is a label, the bar and the value, and the +/// longest label has to fit beside all three without truncating (measured +/// against "Tint (cool–warm)"). const COLOR_W: f32 = 460.; -/// How much of a slider row the bar itself gets. -const COLOR_BAR_W: f32 = 140.; +/// How much of a slider row the bar itself gets -- what a drag is read against, +/// so it takes the width the two nudge buttons used to. +const COLOR_BAR_W: f32 = 240.; + +/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin: +/// fine enough to see a grade tilt, coarse enough that a subsampled count is +/// not noise. +const HIST_BINS: usize = 64; + +/// How many pixels of a frame the histogram reads. The stride is +/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a +/// thousandth of the frame and walks across columns rather than down one. +const HIST_SAMPLES: usize = 8_192; + +/// The histogram box. Shorter than the equalizer's curve because four slider +/// rows stand under it and the card still has to fit a 360 px window. +const HIST_H: f32 = 96.; + +/// What each channel's line is drawn in, in `[r, g, b]` order -- the channel it +/// counts, lightened enough to read on the dark box. +const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0]; struct Player { /// The timeline, once there is one. A run with no file opens without it and @@ -416,6 +465,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. @@ -483,9 +536,24 @@ struct Player { /// there. `None` when it is closed, which is the only place that state /// lives: the grade itself is the project's. color_open: Option<(Lane, usize)>, - /// Which of the card's four sliders the arrow keys and the buttons move. - /// The card's own focus, since nothing in it takes gpui's (ledger:182). + /// Which of the card's four sliders the arrow keys and a drag move. The + /// card's own focus, since nothing in it takes gpui's (ledger:182). color_band: usize, + /// A slider is being dragged. Tracked on the root like `scrubbing` and the + /// equalizer's drag, for the same reason: a 4 px bar is left by the pointer + /// on the first move and its own listeners then stop firing. + color_dragging: bool, + /// Each slider's box, recorded at prepaint: a mouse listener is handed the + /// window position only, so this is what a press and a drag are read against + /// ([`frac_along`]). One per band, because the press picks the row it landed + /// on and the drag then belongs to that row's range. + color_bars: [Rc>>; COLOR_BANDS.len()], + /// The frame on screen counted into `HIST_BINS` bins per channel -- the + /// *graded* frame, because the grade is applied in the decode worker and + /// what arrives here is already through it. Refilled by every pumped frame, + /// which is what makes the colour card's graph move as a slider is dragged: + /// each live write reseeks, and the reseek's frame is the next count. + histogram: [[u32; HIST_BINS]; 3], /// The action whose row is waiting for a stroke. The next key that is /// neither escape nor a lone modifier becomes the whole of what reaches it. rebinding: Option, @@ -552,6 +620,12 @@ impl Player { }); let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra) .expect("frame buffer sized width*height*4"); + // Counted here rather than under `color_open`, because the card + // opens on a frame that was pumped before it: gating this on the + // card would leave its graph flat until something reseeked. A + // thousandth of the pixels, against a conversion that just touched + // all of them. + self.histogram = histogram(buf.as_raw()); let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)])); if let Some(old) = self.image.replace(next) { // Every RenderImage gets a fresh id and its own atlas tile: @@ -584,6 +658,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 @@ -606,6 +685,8 @@ impl Player { ActionId::Paste => self.paste(cx), ActionId::Cut => self.cut(cx), ActionId::Regroup => self.regroup(cx), + ActionId::Detach => self.detach(cx), + ActionId::Group => self.group(cx), ActionId::Select => self.select_under_playhead(cx), ActionId::SelectNext => self.select_step(true, cx), ActionId::SelectPrev => self.select_step(false, cx), @@ -775,6 +856,7 @@ impl Player { Some(clip) => { self.color_open = Some(clip); self.color_band = 0; + self.color_dragging = false; // One card at a time, the rule both the others already follow. self.keys_open = false; self.export_open = false; @@ -801,6 +883,14 @@ impl Player { /// frame on screen repaints through the new grade; this only owes the flags /// that reseek clears. fn set_color(&mut self, params: ColorParams, cx: &mut Context) { + self.write_color(params, false, cx); + } + + /// Both writes: `live` is the one that takes no undo step, which is what + /// every sample *inside* a drag goes through + /// (`PlaybackSession::set_color_live`). Either way the engine reseeks, so + /// the picture -- and the histogram counted off it -- is regraded at once. + fn write_color(&mut self, params: ColorParams, live: bool, cx: &mut Context) { let Some((lane, idx)) = self.color_open else { return; }; @@ -808,7 +898,11 @@ impl Player { return; }; let grade = Some(params).filter(|p| !p.is_identity()); - if session.set_color(lane, idx, grade) { + let took = match live { + true => session.set_color_live(lane, idx, grade), + false => session.set_color(lane, idx, grade), + }; + if took { self.reset_after_reseek(); } cx.notify(); @@ -824,6 +918,35 @@ impl Player { self.set_color(params, cx); } + /// Where the pointer sits along a slider, as that band's value: the left end + /// of the bar is the bottom of its range and the right end the top. Called + /// on every pointer sample, so the grade -- and the picture, and the + /// histogram over it -- moves under the hand. + /// + /// `first` is the press: it takes the undo step the whole gesture rolls back + /// to, and every sample after it is live. That is why it writes even when + /// the value did not change -- without that snapshot the rest of the drag + /// would be unundoable. + /// + /// Values land on the [`COLOR_STEP`] grid the keys use, which also bounds + /// one drag to forty-odd entries in the project's colour table. + /// + /// ponytail: one reseek per step crossed, up to ~40 for a bar-wide sweep. If + /// that ever stutters, the throttle is [`scrub_due`]'s, which the ruler drag + /// already uses for the same cost. + fn drag_color(&mut self, x: Pixels, first: bool, cx: &mut Context) { + let (_, low, high) = COLOR_BANDS[self.color_band]; + let along = frac_along(x, self.color_bars[self.color_band].get()); + let value = color_snap(low + along * (high - low)).clamp(low, high); + let mut params = self.color_params(); + let at = band_mut(&mut params, self.color_band); + if *at == value && !first { + return; + } + *at = value; + self.write_color(params, !first, cx); + } + /// Whether a card owns the window. While one does the timeline under it is /// out of reach, so a right-click there opens no menu -- the same rule the /// key handler and the drop target already follow. @@ -1022,6 +1145,63 @@ impl Player { cx.notify(); } + /// Takes the selected clip out of its group, so the picture and the sound + /// under it are edited apart from here on: each half selects, moves, trims + /// and is removed alone, and both draw outlined instead of tinted. The + /// selection stays -- the half that was clicked is still the half in hand. + fn detach(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + match (&mut self.session, self.selected) { + (Some(session), Some((lane, idx))) => { + if !session.ungroup(lane, idx) { + self.notice = + Some("NOTHING DETACHED — that clip is not grouped with another".into()); + } + } + (Some(_), None) => { + self.notice = Some("NOTHING DETACHED — click the take to take apart first".into()) + } + (None, _) => {} + } + cx.notify(); + } + + /// Puts the selected clip back in a group with the clip covering exactly the + /// same frames on another track -- the way back from [`Player::detach`], and + /// the way to group a picture with sound it was never opened with. The + /// partner is not clicked because there is nothing to choose: a group id + /// names one span, so only a clip covering these very frames could join it, + /// and the engine words what to do when none does. + fn group(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let partner = match (&self.session, self.selected) { + (Some(session), Some((lane, idx))) => span_partner(session, lane, idx), + _ => None, + }; + match (&mut self.session, self.selected, partner) { + (Some(session), Some((lane, idx)), Some((other, o_idx))) => { + if let Err(e) = session.group(lane, idx, other, o_idx) { + self.notice = Some(format!("NOT GROUPED — {e}").into()); + } + } + (Some(_), Some(_), None) => { + self.notice = Some( + "NOTHING TO GROUP WITH — no clip on another track covers exactly these frames" + .into(), + ) + } + (Some(_), None, _) => { + self.notice = Some("NOTHING GROUPED — click one of the halves first".into()) + } + (None, ..) => {} + } + cx.notify(); + } + /// Drops the selected clip and closes the hole: a whole take goes, both /// lanes of it, and everything after it moves up. A half with no take under /// it in the video lane -- what a lift leaves behind -- has nothing to @@ -1045,7 +1225,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(); @@ -1065,7 +1245,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) => { @@ -1225,6 +1405,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 @@ -1732,6 +2041,25 @@ 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; + } + // The format row can be refused *after* it was picked -- mp4 is the + // default and an audio-only timeline (or a second audio lane) is one + // edit away -- so the button asks again rather than starting a worker + // that will only settle with the same refusal minutes later. + if let (Format::Mp4, Some(why)) = (self.format, mp4_refusal(session)) { + self.notice = Some(format!("NOT EXPORTED — {why}").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 @@ -1813,11 +2141,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. @@ -1954,7 +2280,10 @@ impl Render for Player { // the keys menu still lists them. if this.color_open.is_some() { match color_key(key) { - Some(ColorKey::Close) => this.color_open = None, + Some(ColorKey::Close) => { + this.color_open = None; + this.color_dragging = false; + } Some(ColorKey::Band(step)) => { this.color_band = (this.color_band + step) % COLOR_BANDS.len(); } @@ -2027,6 +2356,28 @@ 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. + if this.color_dragging { + if event.pressed_button == Some(MouseButton::Left) { + this.drag_color(event.position.x, false, cx); + } else { + this.color_dragging = false; + } + return; + } if !this.scrubbing { return; } @@ -2049,6 +2400,20 @@ 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 + // step the gesture rolls back to was the press's. + this.drag_color(event.position.x, false, cx); + return; + } if std::mem::take(&mut this.scrubbing) { this.scrub_to(event.position.x, true, cx); } @@ -3238,14 +3603,17 @@ impl Player { ) } - /// The colour card: a row per control, each showing where in its range it - /// stands and carrying the pair of buttons that move it -- the same move the - /// arrow keys make, because a control only the pointer can reach is not one - /// everyone can reach. Same scrim, surface and row shape as the other two - /// cards, and the same plain divs, so the root keeps the keyboard. + /// The colour card: the graded frame's histogram over a row per control, + /// each row a bar the pointer drags straight to a value -- no stepper + /// buttons, because a slider is a thing to pull, and the arrow keys still + /// move the same value for anyone not using a pointer. Same scrim, surface + /// and row shape as the other two cards, and the same plain divs, so the + /// root keeps the keyboard. /// /// The values are read from the project every render: what is drawn is what - /// the decoder is grading with, never a copy that could drift from it. + /// the decoder is grading with, never a copy that could drift from it. The + /// graph above them is counted off the frame that came *back* through that + /// grade ([`histogram`]), so pulling exposure tilts it while the hand moves. fn color_card(&self, cx: &mut Context) -> Option { let (lane, idx) = self.color_open?; let params = self.color_params(); @@ -3257,26 +3625,6 @@ impl Player { let value = *band_mut(&mut read, i); let frac = ((value - low) / (high - low)).clamp(0., 1.); let picked = i == self.color_band; - // Both buttons of a row do what the arrows do, so there is one - // rule for what a press is worth and one place it is clamped. - let step = |name: &'static str, steps: f32| { - div() - .id((name, i)) - .w(px(CONTROL_H)) - .h(px(CONTROL_H)) - .flex() - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.color_band = i; - this.nudge_color(steps, cx); - })) - .child(if steps < 0. { "–" } else { "+" }) - }; div() .id(("color-row", i)) .flex() @@ -3293,22 +3641,43 @@ impl Player { cx.notify(); })) .child(div().flex_1().min_w(px(0.)).truncate().child(label)) - .child(step("color-down", -1.)) .child( + // The bar is 4 px to look at and a whole row to hit + // (WCAG 2.5.8), the same split the ruler makes between + // what is drawn and what is grabbed. The press is + // already the first sample of the drag, so a plain click + // sets the value it landed on. div() + .id(("color-bar", i)) + .relative() .w(px(COLOR_BAR_W)) - .h(px(4.)) - .rounded(px(2.)) - .bg(rgb(CHROME)) + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.color_band = i; + this.color_dragging = true; + this.drag_color(event.position.x, true, cx); + }), + ) + .child(bounds_probe(self.color_bars[i].clone())) .child( div() - .h_full() - .w(relative(frac)) + .w_full() + .h(px(4.)) .rounded(px(2.)) - .bg(rgb(ACCENT)), + .bg(rgb(CHROME)) + .child( + div() + .h_full() + .w(relative(frac)) + .rounded(px(2.)) + .bg(rgb(ACCENT)), + ), ), ) - .child(step("color-up", 1.)) .child( div() .w(px(44.)) @@ -3349,7 +3718,22 @@ impl Player { .px(px(6.)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child("↑↓ picks a slider, ←→ moves it, r resets — esc closes"), + .child( + "drag a bar, or ↑↓ picks one and ←→ moves it, r resets — esc closes", + ), + ) + // The frame as it is being graded, over the controls + // grading it: the three lines are what the picture is + // made of, and every sample of a drag reseeks, so they + // move with the bar under the hand. + .child( + div() + .flex_none() + .h(px(HIST_H)) + .rounded(px(3.)) + .bg(rgb(HOVER_DIM)) + .relative() + .child(hist_curves(self.histogram)), ) .children(rows) .child( @@ -3757,7 +4141,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), @@ -3815,6 +4199,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, @@ -3893,19 +4280,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 { @@ -4249,6 +4661,10 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool // at an edge of this clip. Whether those two halves were ever one take // is the engine's question, and it words that refusal itself. ActionId::Regroup => playhead == clip.start || playhead == clip.end(), + // Nothing to take apart in a clip that names no group at all. Whether + // the group it names still has another half is the engine's question, + // like the regroup above, and it words that refusal itself. + ActionId::Detach => clip.link.is_some(), _ => true, } } @@ -4706,7 +5122,19 @@ fn is_bare_modifier(key: &str) -> bool { /// timeline whose sound is spread over more than one audio lane is refused by /// the engine (`export::run`). Said on the row, before a destination has been /// picked, rather than after the write has started. +/// +/// An audio-only timeline is the other one: every frame of it is a gap, so the +/// mp4 would be a black picture over the sound. The engine refuses it too +/// (`export::start`); this is what greys the row before a destination has been +/// picked. fn mp4_refusal(session: &PlaybackSession) -> Option { + let picture = session + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); + if !picture { + return Some("no picture — an mp4 would be black; export WAV or FLAC".to_string()); + } let lanes = session .lanes() .into_iter() @@ -4760,20 +5188,57 @@ fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool { let Some(clip) = session.lane_clips(lane).get(idx) else { return false; }; - match (lane.kind, lane.ord) { - (_, 1..) => false, - (LaneKind::Video, _) => true, - // The sound of a take, only while the take is still there: its group is - // carried by a clip on some other lane. - (LaneKind::Audio, _) => session + let paired = || { + session .lanes() .into_iter() .filter(|&other| other != lane) .flat_map(|other| session.lane_clips(other)) - .any(|o| o.link.is_some() && o.link == clip.link), + .any(|o| o.link.is_some() && o.link == clip.link) + }; + match (lane.kind, lane.ord) { + (_, 1..) => false, + // The picture of a take -- unless the take has been taken apart: a + // detached picture (a group id no other lane carries, which is also what + // a lift of the sound leaves) is a half like the sound is, and a ripple + // under it would drag away the very half it was detached from. A clip in + // no group at all is not a half but a placement, and on `V1` a placement + // is the take there is. + (LaneKind::Video, _) => clip.link.is_none() || paired(), + // The sound of a take, only while the take is still there: its group is + // carried by a clip on some other lane. + (LaneKind::Audio, _) => paired(), } } +/// The clip a Group would pair this one with: the first clip on another track, +/// in the order the lanes are drawn, covering exactly the same frames and not in +/// this clip's group already. Exactly the same frames because that is all a +/// group id can mean (engine `links_are_consistent`), which is what leaves +/// nothing for a second click to choose. `None` when no track has one, and the +/// notice says so. +fn span_partner(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> { + let clip = *session.lane_clips(lane).get(idx)?; + let matches = |other: Lane| { + let i = session.lane_clips(other).iter().position(|c| { + (c.start, c.end()) == (clip.start, clip.end()) + && !(c.link.is_some() && c.link == clip.link) + })?; + Some((other, i)) + }; + // Sound before picture (and picture before sound): "group this" means the + // other half of the take, and a project whose audio lane was added after a + // second video one has that half *after* the layer in storage order -- which + // is the order the lanes come in. A same-kind lane is still groupable (V1 + // and V2 may be one take), but only where no opposite one covers the span. + let (opposite, same): (Vec, Vec) = session + .lanes() + .into_iter() + .filter(|&other| other != lane) + .partition(|other| other.kind != lane.kind); + opposite.into_iter().chain(same).find_map(matches) +} + /// Whether a click marks this clip: the clip that was clicked always, and the /// other lane's clip of the same group with it. A clip whose group has no other /// half -- what a lift leaves behind -- marks only itself, which is what makes a @@ -4996,6 +5461,73 @@ fn frac_down(y: Pixels, bounds: Bounds) -> f32 { ((y - bounds.top()) / bounds.size.height).clamp(0., 1.) } +/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the +/// pointer stops where the arrow keys do and "0.35" on screen is the number the +/// file writes rather than a rounding of one. +fn color_snap(value: f32) -> f32 { + (value / COLOR_STEP).round() * COLOR_STEP +} + +/// How the frame on screen is spread across the tone range: `HIST_BINS` counts +/// per channel, read off the BGRA the decoder handed over -- which is the +/// *graded* picture, because the grade is folded into the conversion +/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye +/// is looking at, and moving a slider moves it. +/// +/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn +/// from eight thousand samples is the same shape, at a thousandth of the reads. +fn histogram(bgra: &[u8]) -> [[u32; HIST_BINS]; 3] { + let pixels = bgra.len() / 4; + let stride = (pixels / HIST_SAMPLES).max(1); + let mut bins = [[0u32; HIST_BINS]; 3]; + for p in (0..pixels).step_by(stride) { + let px = &bgra[p * 4..]; + // BGRA on the wire, `[r, g, b]` in the bins: the graph names channels + // the way a person does. + for (channel, value) in [px[2], px[1], px[0]].into_iter().enumerate() { + bins[channel][usize::from(value) * HIST_BINS / 256] += 1; + } + } + bins +} + +/// The three counts drawn as three lines across the box, tallest bin to the top. +/// +/// Square root, not linear: a shot with a big flat area (a night sky, a title +/// card) puts one bin so far above the rest that a linear graph is a single +/// spike beside a flat line, and the tilt a grade puts in the rest is exactly +/// what the card is for. +fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + // Shared across the channels, so their relative weight is readable; + // never zero, so an unpumped (all-zero) histogram is a flat line + // rather than a division by nothing. + let top = bins.iter().flatten().copied().max().unwrap_or(0).max(1) as f32; + for (channel, counts) in bins.iter().enumerate() { + let mut path = PathBuilder::stroke(px(1.5)); + for (bin, &count) in counts.iter().enumerate() { + let at = point( + o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32), + o.y + s.height * (1. - (count as f32 / top).sqrt()), + ); + match bin { + 0 => path.move_to(at), + _ => path.line_to(at), + } + } + if let Ok(path) = path.build() { + window.paint_path(path, rgb(HIST_INK[channel])); + } + } + }, + ) + .absolute() + .size_full() +} + /// The cascade's frequency response, drawn as one line across the graph. /// /// Every point comes from `EqParams::response_db`, which reads the very @@ -5101,17 +5633,18 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { use super::{ - ACCENT, CONTROL_H, Clip, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, - EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, + ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH, + EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS, + Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, - WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, envelope, eq_x, - eq_y, export_path, export_settings, format_line, frac_along, frac_down, frame_at, - is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, menu_at, mp4_refusal, - normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, - source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, whole_take, - width_frac, window_title, + WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap, + envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down, + frame_at, histogram, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, + menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due, + show_label, source_frames, source_tint, span_partner, start_frac, timecode, unseen_paths, + unseen_sources, whole_take, width_frac, window_title, }; use super::{file_name, file_uri, library_rows}; @@ -5207,6 +5740,57 @@ mod tests { assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90); } + /// The window opened on a song and nothing else -- the launch argument, the + /// drop on an empty window and the Import button all end in the same + /// `PlaybackSession::open`. The library lists it placeable, the lane door + /// the Add button and a drag share puts it on `A1`, and the one format that + /// needs a picture says so on its own row instead of failing at the end of + /// an export. + #[test] + fn a_song_opens_the_window_by_itself() { + let mut session = + PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline"); + session.set_gain(0.0); + // The source's own path, which is the canonical one a row carries. + let path = session.sources()[0].path.clone(); + assert!(session.lane_clips(Lane::V1).is_empty(), "no picture"); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + + // The library row: probed like any other source, and not greyed -- + // `unusable` is what the panel dims a row with. + let streams = HashMap::from([( + path.clone(), + engine::AudioSession::probe_streams(&path).expect("probe the song"), + )]); + let rate = streams[&path] + .iter() + .find(|s| s.index == session.sources()[0].audio_stream) + .map(|s| (s.sample_rate, s.channels)); + let frames = source_frames(lane_clips(&session), session.sources(), &path); + let rows = library_rows(session.sources(), &streams, rate, |_| frames); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].name, "test_tone.mp3"); + assert_eq!(rows[0].unusable, None, "the row is placeable"); + assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps"); + + // ...and it places, on the audio lane, through the door `insert_source` + // uses: a second copy of the song at the playhead. + session.seek(1.0); + assert!( + session + .place_stream_at(1.0, &path, 0, frames, Some(Lane::A1)) + .expect("its own file is on this timeline") + ); + assert_eq!(session.lane_clips(Lane::A1).len(), 2); + assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); + + // The mp4 row carries the reason rather than the format's detail line. + assert_eq!( + mp4_refusal(&session).as_deref(), + Some("no picture — an mp4 would be black; export WAV or FLAC") + ); + } + fn info( index: usize, rate: u32, @@ -5360,6 +5944,16 @@ mod tests { assert!(applicable(&clip, v1, ActionId::Regroup, 30)); assert!(applicable(&clip, v1, ActionId::Regroup, 90)); assert!(!applicable(&clip, v1, ActionId::Regroup, 60)); + // Detach is the clip's own business: nothing to take apart in one that + // names no group, and whether the group still has another half is the + // engine's question. Group is offered on every clip, for that reason. + assert!(!applicable(&clip, v1, ActionId::Detach, 0)); + let grouped = Clip { + link: Some(3), + ..clip + }; + assert!(applicable(&grouped, v1, ActionId::Detach, 60)); + assert!(applicable(&clip, a1, ActionId::Group, 0)); // The equalizer is the one item the *lane* decides: it filters samples, // and a video clip has none of its own. Never the playhead's business. assert!(applicable(&clip, a1, ActionId::Equalizer, 0)); @@ -5401,6 +5995,114 @@ mod tests { } } + /// What the Detach and Group items do to a real timeline: a music video's + /// sound comes off its picture, Delete on the loose half takes that half + /// only, undo puts both back, and Group makes the two one take again -- + /// whole-take delete and all. + #[test] + fn a_detached_half_is_removed_alone_and_groups_again() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + assert!(whole_take(&session, Lane::V1, 0), "one take to start with"); + assert!(whole_take(&session, Lane::A1, 0)); + let frames = session.lane_clips(Lane::V1)[0].len(); + + // Detach audio: neither half is a whole take any more, so Delete on + // either leaves the other exactly where it is. + assert!(session.ungroup(Lane::V1, 0)); + assert!( + !whole_take(&session, Lane::A1, 0), + "the sound is a half now" + ); + assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture"); + assert!(session.lift_clip(Lane::A1, 0)); + assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went"); + assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed"); + assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed"); + + // One undo per edit, the removal then the detach. + assert!(session.undo()); + assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back"); + assert!(session.undo()); + assert!(whole_take(&session, Lane::A1, 0), "one take again"); + + // Group: the partner is the clip covering these very frames on the + // other track, which is what the item hands the engine. + assert!(session.ungroup(Lane::V1, 0)); + assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); + session + .group(Lane::V1, 0, Lane::A1, 0) + .expect("both halves still cover the same frames"); + assert!( + whole_take(&session, Lane::A1, 0), + "a take that ripples again" + ); + assert_eq!( + span_partner(&session, Lane::V1, 0), + None, + "and nothing left on another track to group with" + ); + } + + /// Which clip Group reaches when more than one covers the span: the sound, + /// whatever order the lanes are stored in. A project file may hold them in + /// any order -- a video layer *before* the audio lane among them -- and + /// "group this" means the other half of the take, never the layer above it. + #[test] + fn group_reaches_the_sound_before_a_video_layer_over_it() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let v2 = session.add_lane(LaneKind::Video); + let path = session.sources()[0].path.clone(); + let frames = source_frames(lane_clips(&session), session.sources(), &path); + assert!( + session + .place_stream_at(0.0, &path, 0, frames, Some(v2)) + .expect("its own file is on this timeline"), + "a layer covering the same frames as the take" + ); + + // Saved and loaded back with the lanes in the order a hand-written + // project may hold them: the sound last, behind the layer. + let dir = std::env::temp_dir().join(format!("ve_group_{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a scratch directory"); + let file = dir.join("lanes.edith"); + session.save_project(&file).expect("save the project"); + let text = std::fs::read_to_string(&file).expect("read it back"); + let (sound, rest): (Vec<&str>, Vec<&str>) = + text.lines().partition(|l| l.starts_with("audio ")); + std::fs::write( + &file, + format!("{}\n{}\n", rest.join("\n"), sound.join("\n")), + ) + .expect("write the reordered project"); + let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands"); + std::fs::remove_dir_all(&dir).ok(); + assert_eq!( + session.lanes(), + vec![Lane::V1, v2, Lane::A1], + "the sound is the last lane there" + ); + + // Detached, so Group has a choice to get wrong: the layer covers these + // frames too, and it is the lane the walk meets first. + assert!(session.ungroup(Lane::V1, 0)); + // Group on the picture reaches the sound, not that layer. + assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); + session + .group(Lane::V1, 0, Lane::A1, 0) + .expect("the two halves cover the same frames"); + // ...and a lane of its own kind is still groupable, once the sound is + // spoken for: two video lanes may be one take. + assert_eq!( + span_partner(&session, Lane::V1, 0), + Some((v2, 0)), + "the layer is what is left to group with" + ); + } + /// The refusal path, end to end against the real files: an incompatible /// import changes nothing, and the library mirrors `sources()` 1:1, so a /// refused file cannot leave a row behind. @@ -5538,6 +6240,64 @@ mod tests { assert!(session.remove_source(&second, 0).is_err()); } + /// 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 @@ -6071,6 +6831,130 @@ mod tests { assert!(KEYS_ROW_H >= HIT_MIN); } + /// A colour slider is dragged straight to a value, so where the pointer + /// lands and where the bar then paints have to be the same place: this is + /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill. + #[test] + fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() { + // A bar as laid out, somewhere that is not the window's origin -- a + // mapping that forgot the offset would pass at zero. + let bar = Bounds { + origin: point(px(180.), px(240.)), + size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)), + }; + for &(label, low, high) in &COLOR_BANDS { + // The ends are the ends: the left of the bar is the bottom of the + // range and the right is the top, so a slider can be pulled to + // either without hunting for the last pixel. + let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low)); + assert_eq!(at(180.), low, "{label} left end"); + assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end"); + // Off either end clamps rather than running past the range. + assert_eq!(at(-4000.), low, "{label} off the left"); + assert_eq!(at(9999.), high, "{label} off the right"); + + for step in 0..=48 { + let along = step as f32 / 48.; + let value = at(180. + along * COLOR_BAR_W); + // Every stop is one the keyboard can also reach, which is what + // keeps "0.35" the number the file writes. + let steps = value / COLOR_STEP; + assert!( + (steps - steps.round()).abs() < 1e-3, + "{label}: {value} is off the {COLOR_STEP} grid" + ); + assert!( + (low..=high).contains(&value), + "{label}: {value} outside {low}..{high}" + ); + // What the row paints from that value is where the pointer was, + // to within the half step the snap costs. + let painted = (value - low) / (high - low); + let slack = COLOR_STEP / (high - low) / 2. + 1e-4; + assert!( + (painted - along).abs() <= slack, + "{label}: pressed at {along}, paints at {painted}" + ); + } + } + + // The same shape as the other two cards, so it fits where they do: the + // graph, four rows and the reset button inside a 360 px window. + let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.); + let rows = COLOR_BANDS.len() as f32 * KEYS_ROW_H; + assert!( + title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360., + "card too tall" + ); + assert!(COLOR_W <= 640., "card too wide"); + // The label still has room beside the bar and the readout, which is + // what the buttons coming off the row bought. + let row = COLOR_W - padding - 12. - 2. * 8. - COLOR_BAR_W - 44.; + assert!(row >= LABEL_MIN_W, "no room left for a label: {row}px"); + // What is dragged is the whole row's height, not the 4 px the bar is + // drawn as (WCAG 2.5.8) -- the same split the ruler makes. + assert!(KEYS_ROW_H >= HIT_MIN); + } + + /// The graph over the sliders is the frame the grade already went through, + /// so it has to count what is actually in those bytes -- BGRA on the wire, + /// red-green-blue in the bins. + #[test] + fn the_histogram_counts_the_frame_it_is_handed() { + // Half pure red, half mid grey: two known values, in two known bins. + let (w, h) = (64usize, 64usize); + let mut frame = Vec::with_capacity(w * h * 4); + for _ in 0..h { + for col in 0..w { + match col < w / 2 { + true => frame.extend_from_slice(&[0, 0, 255, 255]), + false => frame.extend_from_slice(&[128, 128, 128, 255]), + } + } + } + let bins = histogram(&frame); + let half = (w * h / 2) as u32; + // 64 bins over 256 codes: 255 is the last bin, 128 the middle one, 0 the + // first. + assert_eq!(bins[0][63], half, "the red half tops the red channel"); + assert_eq!(bins[0][32], half, "and the grey half sits mid red"); + for channel in [1, 2] { + assert_eq!(bins[channel][0], half, "no green or blue in the red half"); + assert_eq!(bins[channel][32], half); + assert_eq!(bins[channel][63], 0); + } + // Nothing is counted twice and nothing is dropped: this frame is small + // enough to be read whole. + for channel in bins { + assert_eq!(channel.iter().sum::(), (w * h) as u32); + } + + // A grade shifts it, which is the whole point of drawing it: the same + // frame darkened lands in lower bins. + let darker: Vec = frame.iter().map(|b| b / 2).collect(); + let bins = histogram(&darker); + assert_eq!(bins[0][31], half, "255 -> 127"); + assert_eq!(bins[0][16], half, "128 -> 64"); + + // A real frame is subsampled: a 1080p one is read every 253rd pixel, so + // the shape costs a thousandth of the reads and still counts thousands. + let big = vec![200u8; 1920 * 1080 * 4]; + let bins = histogram(&big); + let counted = bins[0].iter().sum::(); + let pixels = 1920 * 1080usize; + let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32; + assert_eq!(counted, expected, "every strided pixel counted, once"); + assert!( + (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted), + "{counted} samples is not the budget" + ); + assert_eq!(bins[0][200 * HIST_BINS / 256], counted, "all in one bin"); + + // An empty buffer is a flat graph rather than a panic: the card is open + // before the first frame is pumped. + assert_eq!(histogram(&[]), [[0; HIST_BINS]; 3]); + } + /// Mute and level are one control with two states, and the whole point is /// that mute keeps the level: the user gets back what they had, not 100%. #[test] @@ -6586,6 +7470,7 @@ fn main() { streams: HashMap::new(), clipboard: None, scrubbing: false, + trim: None, last_scrub: Instant::now(), last_target: 0, export: None, @@ -6604,6 +7489,11 @@ fn main() { eq_graph: Rc::default(), color_open: None, color_band: 0, + color_dragging: false, + color_bars: std::array::from_fn(|_| Rc::default()), + // Empty until the first frame is pumped, which draws as a + // flat line rather than as a shape nothing measured. + histogram: [[0; HIST_BINS]; 3], // What an export is until someone says otherwise: the // bitrate the picture asks for. quality: Quality::Auto, 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..c85eda6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -31,7 +31,7 @@ use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; -use crate::project::Project; +use crate::project::{LaneKind, Project}; use crate::scale::Composer; /// Progress is reported in permille: an atomic integer the render loop can read @@ -165,7 +165,28 @@ 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. + // + // An audio-only timeline is the other legal project no mp4 can be made + // of: every frame of it is a gap, so the file would be black picture + // over the sound -- minutes of encoding for a video of nothing. Refused + // by name, with the two formats that *are* that timeline, rather than + // written; the app says the same on the format row before a destination + // is even picked (`mp4_refusal`). let written = match settings.format { + _ if project.timeline_frames() == 0 => { + Err("the timeline is empty: there is nothing to export".into()) + } + Format::Mp4 if !has_picture(&project) => Err("the timeline has no picture: \ + an mp4 would be black. Export WAV or FLAC, which are the sound itself" + .into()), Format::Mp4 => run(&project, &meta, &part, &worker, &settings), format => run_audio(&project, &meta, &part, &worker, format), }; @@ -182,6 +203,17 @@ pub fn start( ExportHandle { shared } } +/// Whether any video lane holds anything at all -- what tells an audio-only +/// timeline from one that merely opens on a gap. Asked of the *lanes* rather +/// than of the sources, because a project may name a video file no clip plays +/// from any more. +fn has_picture(project: &Project) -> bool { + project + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) +} + fn settle(shared: &Shared, result: crate::Result<()>) { *shared.outcome.lock().unwrap() = Some(result); // Published last: a caller that sees the flag is guaranteed the outcome. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 40e914e..7c26cb1 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -23,15 +23,29 @@ use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; use crate::decode::{DecodeSession, Frame, Worker}; -use crate::demux::{Demuxer, VideoMeta}; +use crate::demux::{Codec, 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 /// only has to be short next to that; it costs one wakeup per 10 ms of audio. const RING_FULL_WAIT: Duration = Duration::from_millis(10); +/// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- +/// nothing was shot on it, so it is the canvas a *later* import meets rather +/// than a description of the song. H.264 because it is the one codec that +/// decodes without the plugin, 30 fps because a rounded-up audio length is what +/// the frame count means and a whole number of frames per second keeps it +/// honest; both are what a video imported onto such a timeline is held to +/// ([`matches_timeline`]). +/// +/// ponytail: a 25 fps video refused by an audio-only timeline it could have +/// defined is the ceiling here. Upgrade path is adopting the first *picture's* +/// rate and codec on import, which means retiming every audio clip already +/// placed in frames. +const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); + /// The output half of a session: the device, plus what the feeder has handed it. /// Cloned into the feeder thread; every field that matters is shared. #[derive(Clone)] @@ -122,13 +136,29 @@ 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 -- with the single exception `sources` itself has, + /// [`Self::remove_source`], which takes the same entry out of both. + 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, } @@ -138,16 +168,12 @@ impl PlaybackSession { /// a file we cannot hear is still a file we can watch. pub fn open(path: impl AsRef) -> crate::Result { let path = path.as_ref().to_path_buf(); - // A timeline is scaffolded from source 0's picture -- its size, its - // frame rate, its clock. A song has none of that, so it joins a - // timeline (`import`) rather than starting one, and saying so beats - // failing in the demuxer's words. + // A timeline is normally scaffolded from source 0's picture -- its size, + // its frame rate, its clock. A song has none of that, so it scaffolds + // the *canvas* instead and its own sound keeps the clock: an audio-only + // project is a project like any other, it simply plays black. if crate::is_audio(&path) { - return Err(format!( - "{} has no picture: open a video first, then import it onto the audio lane", - path.display() - ) - .into()); + return Self::open_audio_only(&path); } // `open_worker` rather than `open` purely for the worker handle: the // field has to exist from the start for the first seek to use it. @@ -174,7 +200,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 +211,79 @@ impl PlaybackSession { audio, audio_disabled, project, + counts: vec![meta.frame_count], + span, + eos: false, + }) + } + + /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its + /// own: one clip on `A1`, nothing on the video lane, and a picture that is + /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as + /// the song runs. Its own sound keeps the clock, exactly as a video's does. + /// + /// Refused when the file has no sound to time it by: a source with neither a + /// picture nor a playable length is not a timeline, and that is what + /// [`audio_frames`] answers -- the *device* is a different question, and a + /// machine without one opens this like any other session, silently. + fn open_audio_only(path: &Path) -> crate::Result { + let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; + let meta = VideoMeta { + width, + height, + frame_rate, + // Rounded up to whole frames, which is the only frame count a + // source with no picture has -- the same length `import_audio` + // gives a song joining a timeline of video. The demuxer's words are + // named with the file, since this is the door a file that is not + // really audio at all comes to. + frame_count: audio_frames(path, frame_rate) + .map_err(|e| format!("{}: {e}", path.display()))?, + codec: Codec::H264, + }; + let (audio, audio_disabled) = open_audio(path, 0); + // Through `from_parts` rather than `Project::single`, which is the + // *video* open's pair of grouped clips: here there is no picture to + // group the sound with, so the video lane starts empty. + let clip = Clip { + start: 0, + in_frame: 0, + out_frame: meta.frame_count, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + }; + let project = Project::from_parts( + vec![Source::new(path, 0)], + vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])], + Vec::new(), + Vec::new(), + )?; + // Every frame of this timeline is a gap, since no video lane covers + // anything: `composite_span_at` says so and the black worker + // `start_span` would open is opened here instead, for the reason `open` + // opens its decoder inline -- the field has to exist for the first seek. + let span = project.composite_span_at(0); + let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len)); + Ok(Self { + meta, + native: (width, height), + frames: stream.frames, + worker: stream.worker, + retired: Vec::new(), + // The song keeps the clock, as a video's own sound does -- and wall + // time keeps it on a machine with no device, where the picture + // (black) still has to move at some rate. + clock: PlaybackClock::new(match audio { + Some(_) => ClockSource::Audio, + None => ClockSource::Wall, + }), + audio, + audio_disabled, + project, + counts: vec![meta.frame_count], span, eos: false, }) @@ -223,14 +322,33 @@ impl PlaybackSession { // Ungraded, and superseded before a frame of it is shown: the `seek` at // the end of this function reopens the playhead's span through // `start_span`, which is where a saved grade reaches the picture. - let (mut meta, stream) = DecodeSession::open_worker( - &first.path, - 0, - u32::MAX, - ColorParams::default(), - Composer::passthrough(), - ) - .map_err(|e| format!("source {}: {e}", first.path.display()))?; + // ...unless it has no picture to open: a project whose source 0 is a + // song scaffolds the canvas the same way a fresh audio-only open does + // ([`open_audio_only`](Self::open_audio_only)), and the placeholder + // black stream is superseded by the `seek` at the end of this function + // like every other worker opened here. + let (mut meta, stream) = match crate::is_audio(&first.path) { + true => { + let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; + let meta = VideoMeta { + width, + height, + frame_rate, + frame_count: audio_frames(&first.path, frame_rate) + .map_err(|e| format!("source {}: {e}", first.path.display()))?, + codec: Codec::H264, + }; + (meta, DecodeSession::open_black(width, height, 1)) + } + false => DecodeSession::open_worker( + &first.path, + 0, + u32::MAX, + ColorParams::default(), + Composer::passthrough(), + ) + .map_err(|e| format!("source {}: {e}", first.path.display()))?, + }; // The project's own resolution, which is source 0's picture unless the // file says otherwise -- every dialect before v7 had no way to say it, // and that default is exactly what those projects meant. @@ -290,7 +408,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 +428,7 @@ impl PlaybackSession { audio, audio_disabled, project, + counts, span, eos: false, }; @@ -370,9 +489,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 +537,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 +586,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 +617,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)> { @@ -552,6 +697,21 @@ impl PlaybackSession { .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate)) } + /// Takes that clip out of its group, so its picture and its sound are edited + /// apart from here on. Metadata only like a cut -- no reseek -- and one undo + /// step. `false` for a bad index and for a clip that is not grouped with + /// anything, which is already detached. + pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool { + self.project.ungroup(lane, idx) + } + + /// Puts two clips covering the same frames back into one group: the regroup + /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo + /// step, and the error says why when it refuses. + pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> { + self.project.group(a, a_idx, b, b_idx) + } + /// What the clip at `idx` of `lane` is equalized with, or `None` for one /// that plays flat -- what a card shows before it lets anyone drag a band. pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> { @@ -575,8 +735,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 +752,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 @@ -624,6 +824,14 @@ impl PlaybackSession { self.edit(|p| p.set_color(lane, idx, params)) } + /// The same grade and the same reseek without the undo step + /// ([`Project::set_color_live`]): what the samples inside one slider drag go + /// through, so the frame regrades under the hand and the whole gesture is + /// still a single `z`. + pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option) -> bool { + self.edit(|p| p.set_color_live(lane, idx, params)) + } + /// The project's resolution: what every clip is composed onto, what the /// window is sized to and what an export writes -- *not* any one file's. /// It starts as source 0's picture, which is what a project meant before it @@ -729,6 +937,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, @@ -782,6 +991,14 @@ impl PlaybackSession { .position(|s| *s == wanted) .ok_or_else(|| format!("{} is not on this timeline", path.display()))?; self.project.remove_source(idx)?; + // The one thing that shortens the source list, so the one place + // [`Self::counts`] shortens with it: left behind, the gone file's length + // would become the wall a *surviving* source is trimmed against + // ([`trim_room`](Self::trim_room)) and the next import would land its + // count one index late. + if idx < self.counts.len() { + self.counts.remove(idx); + } let now = self.now(); self.seek(now); Ok(()) @@ -808,7 +1025,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 @@ -843,6 +1061,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 @@ -875,6 +1094,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, @@ -999,12 +1219,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; @@ -1318,7 +1536,59 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 { #[cfg(test)] mod tests { - use super::secs_to_frame; + use super::{Edge, Lane, PlaybackSession, secs_to_frame}; + use std::path::PathBuf; + + fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) + } + + /// The seam between the two lists a source index reaches: dropping a file + /// from the library shortens `sources`, and `counts` -- the frame length + /// per source, which is what a trim is walled by -- has to lose the same + /// entry. Left behind, the dead file's length would wall the survivor. + #[test] + fn removing_a_source_takes_its_frame_count_with_it() { + // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale + // count cannot pass for the right one. + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let (long, short) = (session.counts[0], session.counts[1]); + assert!(long > short, "{long} vs {short}"); + + // Clear source 0's take, then take the file itself out: av2's clip is + // the only one left and it is source 0 now. + assert!(session.delete_clip(Lane::V1, 0)); + session + .remove_source(&asset("test_av.mp4"), 0) + .expect("nothing plays it any more"); + assert_eq!(session.counts, vec![short], "the dead length went with it"); + assert_eq!(session.sources().len(), session.counts.len()); + + // The wall is the surviving file's own length, not the gone one's: a + // whole-file clip cannot be dragged out any further at all. + let clip = session.lane_clips(Lane::V1)[0]; + assert_eq!(clip.len(), short, "av2's take, whole"); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::End), + Some((clip.start + 1, clip.end())) + ); + assert!( + !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30), + "past the file's last frame is refused, by ITS length" + ); + + // ...and the next import still lines the two lists up, which is the + // alignment `note_frames` asserts on. + session + .import(&asset("test_av.mp4")) + .expect("it may come back"); + assert_eq!(session.counts, vec![short, long]); + assert_eq!(session.sources().len(), session.counts.len()); + } #[test] fn boundary_seconds_round_trip_to_their_own_frame() { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index e5ca906..231d989 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 { @@ -579,6 +595,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(); @@ -620,6 +641,9 @@ impl Project { }); } } + if sources.is_empty() { + sources.extend(self.sources.first().cloned()); + } ( sources, lanes.into_iter().map(|l| (l.kind, l.clips)).collect(), @@ -687,6 +711,24 @@ impl Project { /// (and no history) for an index that is not there or a value that is not /// finite, and equal settings share a table entry. pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option) -> bool { + self.write_color(lane, idx, params, true) + } + + /// [`set_color`](Self::set_color) without the undo step: the samples *inside* + /// one pointer drag, whose first write (a plain `set_color`) already took the + /// snapshot the gesture rolls back to. A drag across a slider is one undo, + /// not one per pixel -- and undoing it lands where the hand picked it up. + pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option) -> bool { + self.write_color(lane, idx, params, false) + } + + fn write_color( + &mut self, + lane: Lane, + idx: usize, + params: Option, + snapshot: bool, + ) -> bool { if idx >= self.lane(lane).len() { return false; } @@ -709,7 +751,9 @@ impl Project { }) } }; - self.snapshot(); + if snapshot { + self.snapshot(); + } self.lane_mut(lane).expect("checked above")[idx].color = slot; true } @@ -1012,6 +1056,115 @@ impl Project { true } + /// Take the clip at `idx` of `lane` out of its group: every clip carrying + /// its id -- on however many lanes -- is handed an id of its own, so from + /// here on each half moves, trims and is deleted alone. The music video + /// whose sound is to be cut against its picture starts here. + /// + /// An id of its own rather than none at all: a half no other lane is grouped + /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal + /// (see [`links_are_consistent`]), and it is what a front-end already draws + /// as detached. `None` would instead say "was never part of a take", which + /// is what a one-lane [`place`](Project::place) means. + /// + /// Metadata only, like a [`split`](Project::split): no mapping changes, so + /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts + /// the group back. Refused (`false`, nothing changed) for an index that is + /// not there, a clip in no group at all, and one whose group has no other + /// half -- that one is already detached, and a refusal must not cost an undo + /// step. + pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool { + let Some(id) = self.lane(lane).get(idx).and_then(|c| c.link) else { + return false; + }; + let members = self + .lanes + .iter() + .flat_map(|l| &l.clips) + .filter(|c| c.link == Some(id)) + .count(); + if members < 2 { + return false; + } + self.snapshot(); + // Drawn before the walk: `new_link` takes the whole project, and the + // walk holds the lanes. + let mut fresh = (0..members).map(|_| self.new_link()).collect::>(); + for data in &mut self.lanes { + for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) { + c.link = fresh.pop(); + } + } + debug_assert!(links_are_consistent(&self.lanes).is_ok()); + true + } + + /// Put two clips on two lanes into one group, so what moves one moves the + /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and + /// how a picture is regrouped with sound it was never opened with. Whatever + /// either of them was grouped with comes along: those clips cover this same + /// span already, so the result is one group and not two overlapping ones. + /// + /// Same frames or nothing: a group id names **one span** on however many + /// lanes ([`links_are_consistent`] refuses to load anything else), so two + /// clips that do not cover the same frames cannot be one take, and the + /// refusal says which bounds to trim to. Kinds are *not* checked: a take may + /// run on `V1` and `V2` at once, and picture-with-sound is the case people + /// mean, not the rule. + /// + /// Metadata only, one snapshot. The error says what is wrong, because + /// `false` would not: a bad index, one lane twice (a group is at most one + /// clip per lane), spans that disagree, and a pair that is already one take + /// -- nothing changes, and none of them costs an undo step. + pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> { + if a == b { + return Err(format!( + "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}", + a.label() + ) + .into()); + } + let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result { + p.lane(lane) + .get(idx) + .copied() + .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into()) + }; + let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?); + if (x.start, x.end()) != (y.start, y.end()) { + return Err(format!( + "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first", + a.label(), + x.start, + x.end(), + b.label(), + y.start, + y.end() + ) + .into()); + } + if x.link.is_some() && x.link == y.link { + return Err("those two are one take already".into()); + } + self.snapshot(); + let id = self.new_link(); + // Every clip either of them was grouped with, by the same rule: all of + // them cover this span, so one id over the lot stays consistent. + let old = [x.link, y.link]; + for data in &mut self.lanes { + for c in data.clips.iter_mut().filter(|c| c.link.is_some()) { + if old.contains(&c.link) { + c.link = Some(id); + } + } + } + // And the two themselves, which a `place` may have left in no group. + self.lane_mut(a).expect("read above")[a_idx].link = Some(id); + self.lane_mut(b).expect("read above")[b_idx].link = Some(id); + debug_assert!(links_are_consistent(&self.lanes).is_ok()); + Ok(()) + } + /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it /// lands on and leaving every other clip exactly where it is -- the /// per-lane paste. Anything already there is trimmed away (and split in two @@ -1085,6 +1238,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 @@ -1162,13 +1454,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(); @@ -1178,23 +1469,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(); @@ -1719,6 +2004,103 @@ mod tests { ); } + /// The music video's own path: the take comes apart into halves that carry + /// ids of their own, one undo puts it back, and two clips over the same + /// frames become one take again by hand. + #[test] + fn a_take_comes_apart_and_goes_back_together() { + let mut p = Project::single(FILE, 9); + let one = p.clips()[0].link.expect("a fresh project is one take"); + assert_eq!(p.lane(Lane::A1)[0].link, Some(one)); + + // A third lane in the same group -- and the merge case with it: a + // placement is in no group, and grouping it in leaves *one* group. + let v2 = p.add_lane(LaneKind::Video); + assert!(p.place(v2, 0, clip(0, 0, 9, 0))); + assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group"); + p.group(Lane::V1, 0, v2, 0) + .expect("the same frames, one lane over"); + let id = p.clips()[0].link.expect("still a group"); + assert!( + p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)), + "one id over the three, not two groups sharing a span" + ); + links_are_consistent(&p.lanes).expect("one id, one span"); + + // Detached by the sound: every half of the group, not only the two. + assert!(p.ungroup(Lane::A1, 0)); + let ids: Vec> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect(); + assert!( + ids.iter().all(Option::is_some), + "a half keeps an id of its own" + ); + assert!( + ids.iter() + .enumerate() + .all(|(i, a)| ids[..i].iter().all(|b| a != b)), + "and no two halves are the same group any more: {ids:?}" + ); + links_are_consistent(&p.lanes).expect("a lone id is legal"); + + // One snapshot for the whole detach. + assert!(p.undo()); + assert!( + p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)), + "one undo puts the whole group back" + ); + + // And back together by hand: the two the pointer named, and only them. + assert!(p.ungroup(Lane::V1, 0)); + p.group(Lane::V1, 0, Lane::A1, 0) + .expect("both cover [0, 9)"); + assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link); + assert_ne!( + p.lane(v2)[0].link, + p.lane(Lane::V1)[0].link, + "the third half stayed detached" + ); + links_are_consistent(&p.lanes).expect("one id, one span"); + } + + /// What a group may not be, and what a detach has nothing to take apart -- + /// none of which may cost an undo step. + #[test] + fn a_group_is_one_span_and_one_clip_per_lane() { + let mut p = three(); + let before = shape(&p); + let why = |r: crate::Result<()>| r.expect_err("refused").to_string(); + + assert!( + why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"), + "two clips of one lane are never one take" + ); + assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1")); + let spans = why(p.group(Lane::V1, 0, Lane::A1, 1)); + assert!( + spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"), + "{spans}" + ); + assert!( + spans.contains("trim them to matching bounds first"), + "{spans}" + ); + assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already")); + + // A half nothing else is grouped with is already detached, a placement + // is in no group at all, and an index that is not there has nothing to + // detach either. + assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0))); + assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group"); + assert!(p.lift(Lane::A1, 0)); + assert!(!p.ungroup(Lane::V1, 0), "its group has no other half"); + assert!(!p.ungroup(Lane::V1, 9), "no clip there"); + + // Two undos, one per edit: not one of the refusals pushed a snapshot. + assert!(p.undo()); + assert!(p.undo()); + assert_eq!(shape(&p), before); + } + #[test] fn split_refused_at_zero_boundary_end_and_in_a_gap() { let mut p = three(); @@ -1985,7 +2367,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); } @@ -2036,13 +2422,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 -- @@ -2147,6 +2548,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] @@ -2175,7 +2709,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())); } @@ -2649,6 +3192,42 @@ mod tests { ); } + /// A slider drag is one gesture: the press snapshots, every sample after it + /// only regrades, and the single undo lands on what the clip was *before* + /// the hand touched it -- not one step back down the drag. + #[test] + fn a_whole_colour_drag_undoes_in_one_step() { + let mut p = three(); + assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press"); + for n in 2..=8 { + assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample"); + } + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8))); + assert!(p.undo()); + assert!( + p.color_of(Lane::V1, 0).is_none(), + "one undo is the whole gesture, back to ungraded" + ); + + // The live write refuses what the snapshotting one refuses, and a + // refusal still costs no history either way. + assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1)))); + assert!(!p.set_color_live( + Lane::V1, + 0, + Some(ColorParams { + contrast: f32::NAN, + ..grade_at(1) + }) + )); + assert!(p.undo()); + assert_eq!( + p.lane(Lane::V1).len(), + 2, + "the next step back is the split before the drag: no sample pushed one" + ); + } + /// The colour table is append-only within a session, exactly as the eq one /// is -- and a save is where an undone grade goes. #[test] @@ -2707,7 +3286,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(), @@ -2724,7 +3304,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/audio_files.rs b/crates/engine/tests/audio_files.rs index 6b180b2..c68c113 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -1,7 +1,8 @@ //! Standalone audio files as sources: every container we claim to read decodes -//! to the same tone, a song joins a timeline of video on the audio lane, and -//! the three things it cannot do -- start a timeline, play on the video lane, -//! be copied into an mp4 -- are refusals that say so. +//! to the same tone, a song joins a timeline of video on the audio lane, a song +//! *is* a timeline on its own (canvas scaffolded, picture black, sound exported) +//! and the two things it cannot do -- play on the video lane, be copied into an +//! mp4 -- are refusals that say so. //! //! ```text //! cargo test -p engine --release --test audio_files @@ -9,6 +10,7 @@ use std::path::{Path, PathBuf}; +use engine::export::{ExportSettings, Format}; use engine::project::Lane; use engine::{AudioSession, Clip, PlaybackSession}; @@ -154,13 +156,178 @@ fn a_rate_the_device_cannot_mix_is_refused_at_the_door() { assert_eq!(session.lane_clips(Lane::A1).len(), 1); } +/// A song *is* a timeline: it scaffolds the canvas a video would have defined, +/// its own length is the timeline's, the video lane starts empty and the picture +/// is the black of an uncovered canvas. #[test] -fn a_song_cannot_be_a_timeline_of_its_own() { - let e = refusal(PlaybackSession::open(asset("test_tone.mp3"))); +fn a_song_is_a_timeline_of_its_own() { + let mut session = open(asset("test_tone.mp3")); + let meta = *session.meta(); + assert_eq!( + (meta.width, meta.height), + (1920, 1080), + "the default canvas" + ); + assert_eq!(meta.frame_rate, 30.0); + // 3 s of tone at 30 fps, rounded up: the only frame count a file with no + // picture has, and it is the timeline's length too. + assert_eq!(meta.frame_count, 90); + assert!((session.timeline_duration() - 3.0).abs() < 0.05); + assert!(!session.is_empty(), "a song is not an empty timeline"); assert!( - e.ends_with("has no picture: open a video first, then import it onto the audio lane"), - "{e}" + session.lane_clips(Lane::V1).is_empty(), + "no picture anywhere" + ); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + let clip = session.lane_clips(Lane::A1)[0]; + assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90)); + assert_eq!(session.sources().len(), 1); + + // And it shows black rather than nothing: the whole timeline is a gap, so + // the black worker feeds it at the canvas size. + session.seek(1.0); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let frame = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + assert!(std::time::Instant::now() < deadline, "no frame at 1 s"); + std::thread::sleep(std::time::Duration::from_millis(10)); + }; + assert_eq!((frame.width, frame.height), (1920, 1080)); + assert_eq!(frame.index, 30, "the gap is indexed in timeline frames"); + assert!( + frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]), + "the picture over a song is black" + ); +} + +/// A file that is neither a picture nor a sound this engine can play is not a +/// timeline: refused at the door, in the words of whatever refused it. +#[test] +fn a_file_with_no_picture_and_no_sound_is_still_refused() { + let dir = std::env::temp_dir().join(format!("ve_audio_bad_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let fake = dir.join("not_really.mp3"); + std::fs::write(&fake, b"this is not an mp3").expect("write"); + let e = refusal(PlaybackSession::open(&fake)); + assert!(e.starts_with(&fake.display().to_string()), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The whole audio-only round trip a user makes: open a song, place a second +/// one, save, reopen, export the sound -- and be told, by name, that the one +/// format that needs a picture cannot have one. +#[test] +fn an_audio_only_project_saves_reloads_and_exports_its_sound() { + let dir = std::env::temp_dir().join(format!("ve_audio_only_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + + let mut session = open(asset("test_tone.mp3")); + // A second song joins it, the same way one joins a timeline of video: no + // picture is needed for the import to have something to hold it to. + session + .import(&asset("test_tone.flac")) + .expect("a song joins a song"); + assert_eq!(session.lane_clips(Lane::A1).len(), 2); + assert!(session.lane_clips(Lane::V1).is_empty()); + assert!((session.timeline_duration() - 6.0).abs() < 0.1); + + // mp4 is refused by name, before a byte is written; WAV writes the sound. + let mp4 = dir.join("song.mp4"); + let e = wait(&session.export_to_with( + &mp4, + &ExportSettings { + format: Format::Mp4, + ..ExportSettings::default() + }, + )) + .expect_err("an audio-only timeline is not an mp4"); + assert_eq!( + e.to_string(), + "the timeline has no picture: an mp4 would be black. \ + Export WAV or FLAC, which are the sound itself" + ); + assert!(!mp4.exists(), "the refusal wrote a file anyway"); + + let wav = dir.join("song.wav"); + wait(&session.export_to_with( + &wav, + &ExportSettings { + format: Format::Wav, + ..ExportSettings::default() + }, + )) + .expect("wav export of an audio-only timeline"); + let (rate, channels, samples) = decode(&wav); + assert_eq!((rate, channels), (44100, 2)); + let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels); + assert!((secs - 6.0).abs() < 0.1, "{secs:.3} s of exported audio"); + let peak = samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs())); + assert!(peak > 0.05, "the export is silent: peak {peak}"); + + // Saved and reopened: an .edith naming nothing but songs loads. + let project = dir.join("songs.edith"); + let before = ( + session.lane_spans_by_source(Lane::A1), + session.sources().to_vec(), + session.timeline_duration(), + ); + session.save_project(&project).expect("save"); + drop(session); + let reloaded = PlaybackSession::open_project(&project).expect("reload an audio-only project"); + reloaded.set_gain(0.0); + assert_eq!( + ( + reloaded.lane_spans_by_source(Lane::A1), + reloaded.sources().to_vec(), + reloaded.timeline_duration() + ), + before ); + assert_eq!(reloaded.meta().frame_rate, 30.0, "the canvas came back"); + assert_eq!( + (reloaded.meta().width, reloaded.meta().height), + (1920, 1080) + ); + assert!(reloaded.lane_clips(Lane::V1).is_empty()); + drop(reloaded); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The other half of the door: a *video* joining a timeline a song scaffolded. +/// It is held to the canvas the song set (H.264, 30 fps), so a matching file +/// brings its picture in -- and the timeline stops being audio-only, mp4 export +/// included. +#[test] +fn a_video_joins_a_timeline_a_song_started() { + let mut session = open(asset("test_tone.mp3")); + session + .import(&asset("test_av.mp4")) + .expect("30 fps H.264 matches the audio-only canvas"); + assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); + assert_eq!(session.lane_clips(Lane::A1).len(), 2); + // And a file at another rate is refused in the timeline's own words rather + // than silently retiming the song already on the lane. + let e = refusal(session.import(&asset("test_tone_48k.wav"))); + assert_eq!( + e, + "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" + ); +} + +/// Blocks until the export settles, whichever way it settled. +fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + loop { + if let Some(result) = handle.result() { + return result; + } + assert!(std::time::Instant::now() < deadline, "export never settled"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } } /// The export copies AAC packets and has no encoder, so a timeline carrying an 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 {