forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(main): library row menu meets the edge-trim source lengths

Browse files at this commit

5f60e190e0532bc35236ebef1856d165ba403cb2Ahmet Kaan GümüşParent: 97d941eca3d7de
Both sides appended a test at the same place in the app suite; both kept.

Seam: `PlaybackSession::counts` (the per-source frame lengths a trim is
walled by) is indexed exactly as `sources` is, and `remove_source` is the
one thing that shortens that list -- so it takes the matching count out
too. Left behind, the gone file's length walled the survivor and the next
import landed its count one index late, tripping `note_frames`'s
alignment assert.
crates/app/src/keymap.rsmodified+22 -3
@@ -53,6 +53,8 @@ pub enum ActionId {
5353 Paste,
5454 Cut,
5555 Regroup,
56+ Detach,
57+ Group,
5658 Select,
5759 SelectNext,
5860 SelectPrev,
@@ -74,7 +76,7 @@ pub enum ActionId {
7476 impl ActionId {
7577 /// Display order everywhere -- the editor lists them in it and
7678 /// [`Keymap::defaults`] binds them in it.
77- pub const ALL: [ActionId; 29] = [
79+ pub const ALL: [ActionId; 31] = [
7880 ActionId::Play,
7981 ActionId::StepBack,
8082 ActionId::StepForward,
@@ -88,6 +90,8 @@ impl ActionId {
8890 ActionId::Paste,
8991 ActionId::Cut,
9092 ActionId::Regroup,
93+ ActionId::Detach,
94+ ActionId::Group,
9195 ActionId::Select,
9296 ActionId::SelectNext,
9397 ActionId::SelectPrev,
@@ -122,6 +126,8 @@ impl ActionId {
122126 ActionId::Paste => "Paste",
123127 ActionId::Cut => "Cut",
124128 ActionId::Regroup => "Regroup",
129+ ActionId::Detach => "Detach the sound from the picture",
130+ ActionId::Group => "Group with the clip on another track",
125131 ActionId::Select => "Select the clip under the playhead (again for the next lane)",
126132 ActionId::SelectNext => "Select the next clip in the lane",
127133 ActionId::SelectPrev => "Select the previous clip in the lane",
@@ -158,6 +164,8 @@ impl ActionId {
158164 ActionId::Paste => "paste",
159165 ActionId::Cut => "cut",
160166 ActionId::Regroup => "regroup",
167+ ActionId::Detach => "detach",
168+ ActionId::Group => "group",
161169 ActionId::Select => "select",
162170 ActionId::SelectNext => "select-next",
163171 ActionId::SelectPrev => "select-prev",
@@ -207,6 +215,8 @@ impl ActionId {
207215 ActionId::Resolution => Category::View,
208216 ActionId::Cut
209217 | ActionId::Regroup
218+ | ActionId::Detach
219+ | ActionId::Group
210220 | ActionId::Undo
211221 | ActionId::AddVideoLane
212222 | ActionId::AddAudioLane => Category::Editing,
@@ -453,6 +463,12 @@ impl Keymap {
453463 // The two lane keys, on the letters they are named after: both
454464 // were free, and neither is next to a key that edits.
455465 b(ActionId::Regroup, "g", false),
466+ // The pair that takes a take apart and puts it back: "d" for
467+ // detach was free and is one press like the rest of the clip
468+ // keys, and grouping two clips is the "g" that rejoins a cut one
469+ // lane over -- the chord beside it, so the two read as one idea.
470+ b(ActionId::Detach, "d", false),
471+ b(ActionId::Group, "g", true),
456472 // Selection without a pointer. Tab is what a keyboard already
457473 // means by "move on to the next thing", and the two brackets
458474 // are the pair either side of it in the lane -- shift+tab is
@@ -753,7 +769,7 @@ mod tests {
753769 #[test]
754770 fn every_default_stroke_reaches_its_action() {
755771 let k = Keymap::defaults();
756- assert_eq!(k.entries().len(), 31);
772+ assert_eq!(k.entries().len(), 33);
757773 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
758774 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
759775 // ends of the timeline.
@@ -769,6 +785,9 @@ mod tests {
769785 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
770786 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));
771787 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
788+ // The take apart / put back pair beside it.
789+ assert_eq!(k.lookup("d", false), Some(ActionId::Detach));
790+ assert_eq!(k.lookup("g", true), Some(ActionId::Group));
772791 // The keyboard's way onto a clip, and the pair that walks the lane.
773792 assert_eq!(k.lookup("tab", false), Some(ActionId::Select));
774793 assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext));
@@ -977,7 +996,7 @@ mod tests {
977996 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
978997 // The label is the editor's column, and never the file's word for it.
979998 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
980- assert_eq!(ActionId::ALL.len(), 29);
999+ assert_eq!(ActionId::ALL.len(), 31);
9811000 }
9821001
9831002 #[test]
crates/app/src/main.rsmodified+974 -84
@@ -13,12 +13,13 @@ use engine::audio::StreamInfo;
1313 use engine::color::ColorParams;
1414 use engine::eq::{Band, BandKind, EqParams};
1515 use engine::export::{ExportSettings, Format};
16-use engine::project::{Lane, LaneKind, Source};
16+use engine::project::{Edge, Lane, LaneKind, Source};
1717 use engine::scale::FitPolicy;
1818 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
1919 use gpui::{
20- AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,
21- MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,
20+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
21+ KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
22+ Point,
2223 RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds,
2324 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,
2425 };
@@ -216,6 +217,31 @@ struct ClipDrag {
216217 idx: usize,
217218 }
218219
220+/// A clip edge being dragged: which end of which clip, and the timeline frame
221+/// the pointer has pulled it to. The box on screen is drawn from `to` while this
222+/// is set and the engine hears about it once, at the release
223+/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture,
224+/// exactly as an equalizer drag works.
225+#[derive(Clone, Copy)]
226+struct Trim {
227+ lane: Lane,
228+ idx: usize,
229+ edge: Edge,
230+ /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from
231+ /// it is the width the release commits -- an edge stops under the pointer
232+ /// rather than snapping back after the fact.
233+ to: u32,
234+ /// The dragged clip's group, so its other halves' boxes follow the edge on
235+ /// screen exactly as the engine will move them.
236+ link: Option<u32>,
237+}
238+
239+/// How wide a clip's edge is as a *target*: the strip at each end where a press
240+/// means "make this longer or shorter" instead of "move this to another lane".
241+/// Wide enough to hit, narrow enough that the middle of even a small box is
242+/// still the body.
243+const EDGE_W: f32 = 6.;
244+
219245 /// An open clip menu: which clip it was opened on, where it hangs, and whether
220246 /// it has been turned over to show what that clip *is* instead of what can be
221247 /// done to it. The lane and index are the ones the same click selected, so
@@ -285,11 +311,13 @@ impl RowItem {
285311 /// action a stroke already reaches -- the menu is a second way *to* the actions
286312 /// and never a second version of them -- so both the label and the hint come
287313 /// out of the keymap registry and the two can never disagree.
288-const MENU_ITEMS: [ActionId; 8] = [
314+const MENU_ITEMS: [ActionId; 10] = [
289315 ActionId::Cut,
290316 ActionId::Delete,
291317 ActionId::Lift,
292318 ActionId::Regroup,
319+ ActionId::Detach,
320+ ActionId::Group,
293321 ActionId::Equalizer,
294322 ActionId::Color,
295323 ActionId::Fit,
@@ -349,16 +377,37 @@ const COLOR_BANDS: [(&str, f32, f32); 4] = [
349377 ("Tint (cool–warm)", -1., 1.),
350378 ];
351379
352-/// A press of a nudge key or button: a fortieth of a band's range, so a slider
353-/// crosses it in forty presses and every stop is a number the file can write.
380+/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it
381+/// in forty presses and every stop is a number the file can write. A drag lands
382+/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard
383+/// cannot reach two different sets of values.
354384 const COLOR_STEP: f32 = 0.05;
355385
356-/// The card's width: a slider row is a label, two buttons, the bar and the
357-/// value, and the longest label has to fit beside all four without truncating
358-/// (measured against "Tint (cool–warm)" at 460).
386+/// The card's width: a slider row is a label, the bar and the value, and the
387+/// longest label has to fit beside all three without truncating (measured
388+/// against "Tint (cool–warm)").
359389 const COLOR_W: f32 = 460.;
360-/// How much of a slider row the bar itself gets.
361-const COLOR_BAR_W: f32 = 140.;
390+/// How much of a slider row the bar itself gets -- what a drag is read against,
391+/// so it takes the width the two nudge buttons used to.
392+const COLOR_BAR_W: f32 = 240.;
393+
394+/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin:
395+/// fine enough to see a grade tilt, coarse enough that a subsampled count is
396+/// not noise.
397+const HIST_BINS: usize = 64;
398+
399+/// How many pixels of a frame the histogram reads. The stride is
400+/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a
401+/// thousandth of the frame and walks across columns rather than down one.
402+const HIST_SAMPLES: usize = 8_192;
403+
404+/// The histogram box. Shorter than the equalizer's curve because four slider
405+/// rows stand under it and the card still has to fit a 360 px window.
406+const HIST_H: f32 = 96.;
407+
408+/// What each channel's line is drawn in, in `[r, g, b]` order -- the channel it
409+/// counts, lightened enough to read on the dark box.
410+const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];
362411
363412 struct Player {
364413 /// The timeline, once there is one. A run with no file opens without it and
@@ -416,6 +465,10 @@ struct Player {
416465 /// A drag that started on the ruler. Moves anywhere in the window scrub
417466 /// while it is set; the release commits the exact position.
418467 scrubbing: bool,
468+ /// A drag that started on a clip's edge, tracked on the root for
469+ /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See
470+ /// [`Trim`].
471+ trim: Option<Trim>,
419472 last_scrub: Instant,
420473 last_target: u32,
421474 /// The running export. While it owns the UI the editor is read-only.
@@ -483,9 +536,24 @@ struct Player {
483536 /// there. `None` when it is closed, which is the only place that state
484537 /// lives: the grade itself is the project's.
485538 color_open: Option<(Lane, usize)>,
486- /// Which of the card's four sliders the arrow keys and the buttons move.
487- /// The card's own focus, since nothing in it takes gpui's (ledger:182).
539+ /// Which of the card's four sliders the arrow keys and a drag move. The
540+ /// card's own focus, since nothing in it takes gpui's (ledger:182).
488541 color_band: usize,
542+ /// A slider is being dragged. Tracked on the root like `scrubbing` and the
543+ /// equalizer's drag, for the same reason: a 4 px bar is left by the pointer
544+ /// on the first move and its own listeners then stop firing.
545+ color_dragging: bool,
546+ /// Each slider's box, recorded at prepaint: a mouse listener is handed the
547+ /// window position only, so this is what a press and a drag are read against
548+ /// ([`frac_along`]). One per band, because the press picks the row it landed
549+ /// on and the drag then belongs to that row's range.
550+ color_bars: [Rc<Cell<Bounds<Pixels>>>; COLOR_BANDS.len()],
551+ /// The frame on screen counted into `HIST_BINS` bins per channel -- the
552+ /// *graded* frame, because the grade is applied in the decode worker and
553+ /// what arrives here is already through it. Refilled by every pumped frame,
554+ /// which is what makes the colour card's graph move as a slider is dragged:
555+ /// each live write reseeks, and the reseek's frame is the next count.
556+ histogram: [[u32; HIST_BINS]; 3],
489557 /// The action whose row is waiting for a stroke. The next key that is
490558 /// neither escape nor a lone modifier becomes the whole of what reaches it.
491559 rebinding: Option<ActionId>,
@@ -552,6 +620,12 @@ impl Player {
552620 });
553621 let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
554622 .expect("frame buffer sized width*height*4");
623+ // Counted here rather than under `color_open`, because the card
624+ // opens on a frame that was pumped before it: gating this on the
625+ // card would leave its graph flat until something reseeked. A
626+ // thousandth of the pixels, against a conversion that just touched
627+ // all of them.
628+ self.histogram = histogram(buf.as_raw());
555629 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
556630 if let Some(old) = self.image.replace(next) {
557631 // Every RenderImage gets a fresh id and its own atlas tile:
@@ -584,6 +658,11 @@ impl Player {
584658 self.eos = false;
585659 self.done = false;
586660 self.pending_seek = true;
661+ // An edit moves the indices a drag in flight is holding -- a stroke
662+ // during one is exactly that -- and an edge committed against a moved
663+ // index would trim a clip nobody grabbed. Dropping it is the whole fix:
664+ // nothing has been written yet.
665+ self.trim = None;
587666 }
588667
589668 /// What an action does, wherever it was asked for -- a stroke, or the clip
@@ -606,6 +685,8 @@ impl Player {
606685 ActionId::Paste => self.paste(cx),
607686 ActionId::Cut => self.cut(cx),
608687 ActionId::Regroup => self.regroup(cx),
688+ ActionId::Detach => self.detach(cx),
689+ ActionId::Group => self.group(cx),
609690 ActionId::Select => self.select_under_playhead(cx),
610691 ActionId::SelectNext => self.select_step(true, cx),
611692 ActionId::SelectPrev => self.select_step(false, cx),
@@ -775,6 +856,7 @@ impl Player {
775856 Some(clip) => {
776857 self.color_open = Some(clip);
777858 self.color_band = 0;
859+ self.color_dragging = false;
778860 // One card at a time, the rule both the others already follow.
779861 self.keys_open = false;
780862 self.export_open = false;
@@ -801,6 +883,14 @@ impl Player {
801883 /// frame on screen repaints through the new grade; this only owes the flags
802884 /// that reseek clears.
803885 fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
886+ self.write_color(params, false, cx);
887+ }
888+
889+ /// Both writes: `live` is the one that takes no undo step, which is what
890+ /// every sample *inside* a drag goes through
891+ /// (`PlaybackSession::set_color_live`). Either way the engine reseeks, so
892+ /// the picture -- and the histogram counted off it -- is regraded at once.
893+ fn write_color(&mut self, params: ColorParams, live: bool, cx: &mut Context<Self>) {
804894 let Some((lane, idx)) = self.color_open else {
805895 return;
806896 };
@@ -808,7 +898,11 @@ impl Player {
808898 return;
809899 };
810900 let grade = Some(params).filter(|p| !p.is_identity());
811- if session.set_color(lane, idx, grade) {
901+ let took = match live {
902+ true => session.set_color_live(lane, idx, grade),
903+ false => session.set_color(lane, idx, grade),
904+ };
905+ if took {
812906 self.reset_after_reseek();
813907 }
814908 cx.notify();
@@ -824,6 +918,35 @@ impl Player {
824918 self.set_color(params, cx);
825919 }
826920
921+ /// Where the pointer sits along a slider, as that band's value: the left end
922+ /// of the bar is the bottom of its range and the right end the top. Called
923+ /// on every pointer sample, so the grade -- and the picture, and the
924+ /// histogram over it -- moves under the hand.
925+ ///
926+ /// `first` is the press: it takes the undo step the whole gesture rolls back
927+ /// to, and every sample after it is live. That is why it writes even when
928+ /// the value did not change -- without that snapshot the rest of the drag
929+ /// would be unundoable.
930+ ///
931+ /// Values land on the [`COLOR_STEP`] grid the keys use, which also bounds
932+ /// one drag to forty-odd entries in the project's colour table.
933+ ///
934+ /// ponytail: one reseek per step crossed, up to ~40 for a bar-wide sweep. If
935+ /// that ever stutters, the throttle is [`scrub_due`]'s, which the ruler drag
936+ /// already uses for the same cost.
937+ fn drag_color(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
938+ let (_, low, high) = COLOR_BANDS[self.color_band];
939+ let along = frac_along(x, self.color_bars[self.color_band].get());
940+ let value = color_snap(low + along * (high - low)).clamp(low, high);
941+ let mut params = self.color_params();
942+ let at = band_mut(&mut params, self.color_band);
943+ if *at == value && !first {
944+ return;
945+ }
946+ *at = value;
947+ self.write_color(params, !first, cx);
948+ }
949+
827950 /// Whether a card owns the window. While one does the timeline under it is
828951 /// out of reach, so a right-click there opens no menu -- the same rule the
829952 /// key handler and the drop target already follow.
@@ -1022,6 +1145,63 @@ impl Player {
10221145 cx.notify();
10231146 }
10241147
1148+ /// Takes the selected clip out of its group, so the picture and the sound
1149+ /// under it are edited apart from here on: each half selects, moves, trims
1150+ /// and is removed alone, and both draw outlined instead of tinted. The
1151+ /// selection stays -- the half that was clicked is still the half in hand.
1152+ fn detach(&mut self, cx: &mut Context<Self>) {
1153+ if self.exporting().is_some() {
1154+ return;
1155+ }
1156+ match (&mut self.session, self.selected) {
1157+ (Some(session), Some((lane, idx))) => {
1158+ if !session.ungroup(lane, idx) {
1159+ self.notice =
1160+ Some("NOTHING DETACHED — that clip is not grouped with another".into());
1161+ }
1162+ }
1163+ (Some(_), None) => {
1164+ self.notice = Some("NOTHING DETACHED — click the take to take apart first".into())
1165+ }
1166+ (None, _) => {}
1167+ }
1168+ cx.notify();
1169+ }
1170+
1171+ /// Puts the selected clip back in a group with the clip covering exactly the
1172+ /// same frames on another track -- the way back from [`Player::detach`], and
1173+ /// the way to group a picture with sound it was never opened with. The
1174+ /// partner is not clicked because there is nothing to choose: a group id
1175+ /// names one span, so only a clip covering these very frames could join it,
1176+ /// and the engine words what to do when none does.
1177+ fn group(&mut self, cx: &mut Context<Self>) {
1178+ if self.exporting().is_some() {
1179+ return;
1180+ }
1181+ let partner = match (&self.session, self.selected) {
1182+ (Some(session), Some((lane, idx))) => span_partner(session, lane, idx),
1183+ _ => None,
1184+ };
1185+ match (&mut self.session, self.selected, partner) {
1186+ (Some(session), Some((lane, idx)), Some((other, o_idx))) => {
1187+ if let Err(e) = session.group(lane, idx, other, o_idx) {
1188+ self.notice = Some(format!("NOT GROUPED — {e}").into());
1189+ }
1190+ }
1191+ (Some(_), Some(_), None) => {
1192+ self.notice = Some(
1193+ "NOTHING TO GROUP WITH — no clip on another track covers exactly these frames"
1194+ .into(),
1195+ )
1196+ }
1197+ (Some(_), None, _) => {
1198+ self.notice = Some("NOTHING GROUPED — click one of the halves first".into())
1199+ }
1200+ (None, ..) => {}
1201+ }
1202+ cx.notify();
1203+ }
1204+
10251205 /// Drops the selected clip and closes the hole: a whole take goes, both
10261206 /// lanes of it, and everything after it moves up. A half with no take under
10271207 /// it in the video lane -- what a lift leaves behind -- has nothing to
@@ -1045,7 +1225,7 @@ impl Player {
10451225 _ => false,
10461226 };
10471227 if selected.is_some() && !deleted {
1048- self.notice = Some("NOTHING DELETED — the timeline cannot be emptied".into());
1228+ self.notice = Some("NOTHING DELETED — that clip is no longer there".into());
10491229 }
10501230 if deleted {
10511231 self.reset_after_reseek();
@@ -1065,7 +1245,7 @@ impl Player {
10651245 if session.lift_clip(lane, idx) {
10661246 self.reset_after_reseek();
10671247 } else {
1068- self.notice = Some("NOTHING LIFTED — the timeline cannot be emptied".into());
1248+ self.notice = Some("NOTHING LIFTED — that half is no longer there".into());
10691249 }
10701250 }
10711251 (Some(_), None) => {
@@ -1225,6 +1405,135 @@ impl Player {
12251405 cx.notify();
12261406 }
12271407
1408+ /// Opens the clip menu on the box under the pointer, from the right button
1409+ /// wherever it was pressed on that box -- its middle or one of its edge
1410+ /// strips, which cover the middle's own listener. Selecting first is part of
1411+ /// it: every item acts on the clip the menu names.
1412+ fn open_menu(&mut self, lane: Lane, idx: usize, at: Point<Pixels>, cx: &mut Context<Self>) {
1413+ if self.modal() {
1414+ return;
1415+ }
1416+ self.select((lane, idx), cx);
1417+ self.context_menu = Some(ContextMenu {
1418+ lane,
1419+ idx,
1420+ at,
1421+ details: false,
1422+ });
1423+ cx.notify();
1424+ }
1425+
1426+ /// A press on a clip's edge: the start of the drag that changes how much of
1427+ /// its source it plays. It selects the clip as a press anywhere else on the
1428+ /// box does -- the edge strip covers the box's own listener (`occlude`), so
1429+ /// this is the only one that fires there.
1430+ fn start_trim(&mut self, lane: Lane, idx: usize, edge: Edge, cx: &mut Context<Self>) {
1431+ if self.modal() || self.exporting().is_some() {
1432+ return;
1433+ }
1434+ let Some(clip) = self
1435+ .session
1436+ .as_ref()
1437+ .and_then(|session| session.lane_clips(lane).get(idx).copied())
1438+ else {
1439+ return;
1440+ };
1441+ self.select((lane, idx), cx);
1442+ self.trim = Some(Trim {
1443+ lane,
1444+ idx,
1445+ edge,
1446+ // Where the edge already is: a press that never moves is not an
1447+ // edit, and `Project::trim` refuses exactly that.
1448+ to: match edge {
1449+ Edge::Start => clip.start,
1450+ Edge::End => clip.end(),
1451+ },
1452+ link: clip.link,
1453+ });
1454+ cx.notify();
1455+ }
1456+
1457+ /// Where the pointer has pulled the edge to, clamped to the room the engine
1458+ /// says that edge has. Along the same bed the ruler is measured on and
1459+ /// against the same duration the boxes are drawn to, so the edge tracks the
1460+ /// pointer exactly.
1461+ fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
1462+ let (duration, fps) = (self.drawn_duration(), self.fps);
1463+ let frac = frac_along(x, self.ruler.get());
1464+ let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
1465+ return;
1466+ };
1467+ let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {
1468+ return;
1469+ };
1470+ trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi);
1471+ cx.notify();
1472+ }
1473+
1474+ /// The release: the whole drag reaches the engine as one edit, so it is one
1475+ /// undo step. The selection survives it -- a trim inserts and removes
1476+ /// nothing, so every index a lane had still names the clip it named.
1477+ fn commit_trim(&mut self, cx: &mut Context<Self>) {
1478+ let Some(trim) = self.trim.take() else {
1479+ return;
1480+ };
1481+ let trimmed = self
1482+ .session
1483+ .as_mut()
1484+ .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to));
1485+ if trimmed {
1486+ self.reset_after_reseek();
1487+ }
1488+ cx.notify();
1489+ }
1490+
1491+ /// The clip as the drag is showing it: an edge under the pointer moves its
1492+ /// own box, and the boxes of the halves linked to it, before anything is
1493+ /// committed. Display only -- the project is not touched until the release.
1494+ fn trimmed(&self, lane: Lane, idx: usize, clip: Clip) -> Clip {
1495+ let Some(trim) = self.trim.filter(|t| {
1496+ (t.lane, t.idx) == (lane, idx) || (t.link.is_some() && t.link == clip.link)
1497+ }) else {
1498+ return clip;
1499+ };
1500+ match trim.edge {
1501+ // The in-point follows the head, exactly as `Project::trim` moves
1502+ // it: what stays on screen plays what it always played.
1503+ Edge::Start => Clip {
1504+ in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start))
1505+ .clamp(0, i64::from(clip.out_frame - 1)) as u32,
1506+ start: trim.to,
1507+ ..clip
1508+ },
1509+ Edge::End => Clip {
1510+ out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1),
1511+ ..clip
1512+ },
1513+ }
1514+ }
1515+
1516+ /// How long the timeline is *drawn* as: its own length, and while a tail is
1517+ /// being dragged the furthest that tail may reach. A bed that ends exactly
1518+ /// at the last frame has nowhere to put a pointer that means "longer", so
1519+ /// without this the last clip on the timeline could be pulled in and never
1520+ /// let back out.
1521+ fn drawn_duration(&self) -> f64 {
1522+ let Some(session) = &self.session else {
1523+ return 0.;
1524+ };
1525+ let duration = session.timeline_duration();
1526+ match self.trim {
1527+ Some(trim) if trim.edge == Edge::End => {
1528+ let (_, hi) = session
1529+ .trim_room(trim.lane, trim.idx, trim.edge)
1530+ .unwrap_or((0, 0));
1531+ duration.max(f64::from(hi) / self.fps)
1532+ }
1533+ _ => duration,
1534+ }
1535+ }
1536+
12281537 /// The one way a library row reaches the timeline: the Add button and a row
12291538 /// dragged onto a lane both come here, so there is a single answer to what
12301539 /// "add this source" does. The whole source goes in at the playhead as one
@@ -1732,6 +2041,25 @@ impl Player {
17322041 cx.notify();
17332042 return;
17342043 };
2044+ // An emptied timeline is a timeline; it is simply not a file. Refused by
2045+ // name here rather than written as a project of no frames -- and the
2046+ // engine refuses it again on the worker (`export::start`), so a caller
2047+ // that is not this button cannot get past it either. Two fences on
2048+ // purpose: this one is the one with a keystroke to blame.
2049+ if session.is_empty() {
2050+ self.notice = Some("NOTHING TO EXPORT — the timeline is empty".into());
2051+ cx.notify();
2052+ return;
2053+ }
2054+ // The format row can be refused *after* it was picked -- mp4 is the
2055+ // default and an audio-only timeline (or a second audio lane) is one
2056+ // edit away -- so the button asks again rather than starting a worker
2057+ // that will only settle with the same refusal minutes later.
2058+ if let (Format::Mp4, Some(why)) = (self.format, mp4_refusal(session)) {
2059+ self.notice = Some(format!("NOT EXPORTED — {why}").into());
2060+ cx.notify();
2061+ return;
2062+ }
17352063 session.pause();
17362064 self.export = Some(session.export_to_with(&self.export_path, &settings));
17372065 // The card has been answered; the progress line takes the panel from
@@ -1813,11 +2141,9 @@ impl Render for Player {
18132141 }
18142142
18152143 // Read per render, never cached: a delete shortens the timeline and the
1816- // timecode, the ruler and the clamp below all have to follow it.
1817- let duration = self
1818- .session
1819- .as_ref()
1820- .map_or(0., PlaybackSession::timeline_duration);
2144+ // timecode, the ruler and the clamp below all have to follow it -- and
2145+ // so does the room a tail being dragged needs to grow into.
2146+ let duration = self.drawn_duration();
18212147 // The clock keeps running after the last frame (wall time takes over at
18222148 // audio EOF) while the picture is frozen, so the timeline the UI shows is
18232149 // the clamped one, pinned to the out-point once playback is done.
@@ -1954,7 +2280,10 @@ impl Render for Player {
19542280 // the keys menu still lists them.
19552281 if this.color_open.is_some() {
19562282 match color_key(key) {
1957- Some(ColorKey::Close) => this.color_open = None,
2283+ Some(ColorKey::Close) => {
2284+ this.color_open = None;
2285+ this.color_dragging = false;
2286+ }
19582287 Some(ColorKey::Band(step)) => {
19592288 this.color_band = (this.color_band + step) % COLOR_BANDS.len();
19602289 }
@@ -2027,6 +2356,28 @@ impl Render for Player {
20272356 }
20282357 return;
20292358 }
2359+ // A clip edge is 6 px wide and the pointer leaves it on the
2360+ // first drag, so the gesture is tracked here for the same
2361+ // reason -- and it ends here too when the button came up
2362+ // outside the window, still owing its one edit.
2363+ if this.trim.is_some() {
2364+ match event.pressed_button {
2365+ Some(MouseButton::Left) => this.trim_to(event.position.x, cx),
2366+ _ => this.commit_trim(cx),
2367+ }
2368+ return;
2369+ }
2370+ // A colour slider is 4 px tall and the pointer leaves it just as
2371+ // fast; every sample is live, so the release owes no write of
2372+ // its own -- what the last sample set is what the clip carries.
2373+ if this.color_dragging {
2374+ if event.pressed_button == Some(MouseButton::Left) {
2375+ this.drag_color(event.position.x, false, cx);
2376+ } else {
2377+ this.color_dragging = false;
2378+ }
2379+ return;
2380+ }
20302381 if !this.scrubbing {
20312382 return;
20322383 }
@@ -2049,6 +2400,20 @@ impl Render for Player {
20492400 this.commit_eq(cx);
20502401 return;
20512402 }
2403+ if this.trim.is_some() {
2404+ // The release lands exactly, then the gesture is
2405+ // written once -- one edit, one undo step.
2406+ this.trim_to(event.position.x, cx);
2407+ this.commit_trim(cx);
2408+ return;
2409+ }
2410+ if std::mem::take(&mut this.color_dragging) {
2411+ // The release lands exactly where the hand let go, and
2412+ // it is a live write like every other sample: the undo
2413+ // step the gesture rolls back to was the press's.
2414+ this.drag_color(event.position.x, false, cx);
2415+ return;
2416+ }
20522417 if std::mem::take(&mut this.scrubbing) {
20532418 this.scrub_to(event.position.x, true, cx);
20542419 }
@@ -3238,14 +3603,17 @@ impl Player {
32383603 )
32393604 }
32403605
3241- /// The colour card: a row per control, each showing where in its range it
3242- /// stands and carrying the pair of buttons that move it -- the same move the
3243- /// arrow keys make, because a control only the pointer can reach is not one
3244- /// everyone can reach. Same scrim, surface and row shape as the other two
3245- /// cards, and the same plain divs, so the root keeps the keyboard.
3606+ /// The colour card: the graded frame's histogram over a row per control,
3607+ /// each row a bar the pointer drags straight to a value -- no stepper
3608+ /// buttons, because a slider is a thing to pull, and the arrow keys still
3609+ /// move the same value for anyone not using a pointer. Same scrim, surface
3610+ /// and row shape as the other two cards, and the same plain divs, so the
3611+ /// root keeps the keyboard.
32463612 ///
32473613 /// The values are read from the project every render: what is drawn is what
3248- /// the decoder is grading with, never a copy that could drift from it.
3614+ /// the decoder is grading with, never a copy that could drift from it. The
3615+ /// graph above them is counted off the frame that came *back* through that
3616+ /// grade ([`histogram`]), so pulling exposure tilts it while the hand moves.
32493617 fn color_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
32503618 let (lane, idx) = self.color_open?;
32513619 let params = self.color_params();
@@ -3257,26 +3625,6 @@ impl Player {
32573625 let value = *band_mut(&mut read, i);
32583626 let frac = ((value - low) / (high - low)).clamp(0., 1.);
32593627 let picked = i == self.color_band;
3260- // Both buttons of a row do what the arrows do, so there is one
3261- // rule for what a press is worth and one place it is clamped.
3262- let step = |name: &'static str, steps: f32| {
3263- div()
3264- .id((name, i))
3265- .w(px(CONTROL_H))
3266- .h(px(CONTROL_H))
3267- .flex()
3268- .items_center()
3269- .justify_center()
3270- .rounded(px(3.))
3271- .bg(rgb(CHROME))
3272- .cursor_pointer()
3273- .hover(|s| s.bg(rgb(HOVER)))
3274- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
3275- this.color_band = i;
3276- this.nudge_color(steps, cx);
3277- }))
3278- .child(if steps < 0. { "–" } else { "+" })
3279- };
32803628 div()
32813629 .id(("color-row", i))
32823630 .flex()
@@ -3293,22 +3641,43 @@ impl Player {
32933641 cx.notify();
32943642 }))
32953643 .child(div().flex_1().min_w(px(0.)).truncate().child(label))
3296- .child(step("color-down", -1.))
32973644 .child(
3645+ // The bar is 4 px to look at and a whole row to hit
3646+ // (WCAG 2.5.8), the same split the ruler makes between
3647+ // what is drawn and what is grabbed. The press is
3648+ // already the first sample of the drag, so a plain click
3649+ // sets the value it landed on.
32983650 div()
3651+ .id(("color-bar", i))
3652+ .relative()
32993653 .w(px(COLOR_BAR_W))
3300- .h(px(4.))
3301- .rounded(px(2.))
3302- .bg(rgb(CHROME))
3654+ .h(px(KEYS_ROW_H))
3655+ .flex()
3656+ .items_center()
3657+ .on_mouse_down(
3658+ MouseButton::Left,
3659+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3660+ this.color_band = i;
3661+ this.color_dragging = true;
3662+ this.drag_color(event.position.x, true, cx);
3663+ }),
3664+ )
3665+ .child(bounds_probe(self.color_bars[i].clone()))
33033666 .child(
33043667 div()
3305- .h_full()
3306- .w(relative(frac))
3668+ .w_full()
3669+ .h(px(4.))
33073670 .rounded(px(2.))
3308- .bg(rgb(ACCENT)),
3671+ .bg(rgb(CHROME))
3672+ .child(
3673+ div()
3674+ .h_full()
3675+ .w(relative(frac))
3676+ .rounded(px(2.))
3677+ .bg(rgb(ACCENT)),
3678+ ),
33093679 ),
33103680 )
3311- .child(step("color-up", 1.))
33123681 .child(
33133682 div()
33143683 .w(px(44.))
@@ -3349,7 +3718,22 @@ impl Player {
33493718 .px(px(6.))
33503719 .text_size(px(11.))
33513720 .text_color(rgb(INK_DIM))
3352- .child("↑↓ picks a slider, ←→ moves it, r resets — esc closes"),
3721+ .child(
3722+ "drag a bar, or ↑↓ picks one and ←→ moves it, r resets — esc closes",
3723+ ),
3724+ )
3725+ // The frame as it is being graded, over the controls
3726+ // grading it: the three lines are what the picture is
3727+ // made of, and every sample of a drag reseeks, so they
3728+ // move with the bar under the hand.
3729+ .child(
3730+ div()
3731+ .flex_none()
3732+ .h(px(HIST_H))
3733+ .rounded(px(3.))
3734+ .bg(rgb(HOVER_DIM))
3735+ .relative()
3736+ .child(hist_curves(self.histogram)),
33533737 )
33543738 .children(rows)
33553739 .child(
@@ -3757,7 +4141,7 @@ impl Player {
37574141 let (sel, sel_link) = (self.selected, self.selected_link());
37584142 let audio = lane.kind == LaneKind::Audio;
37594143 let tip: SharedString = format!(
3760- "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut",
4144+ "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut",
37614145 self.keymap.display(ActionId::Select),
37624146 self.keymap.display(ActionId::SelectPrev),
37634147 self.keymap.display(ActionId::SelectNext),
@@ -3815,6 +4199,9 @@ impl Player {
38154199 }))
38164200 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
38174201 .children(clips.iter().enumerate().map(|(i, clip)| {
4202+ // What a drag on an edge is showing, which is the clip
4203+ // itself while nothing is being dragged.
4204+ let clip = &self.trimmed(lane, i, *clip);
38184205 let (start, len) = (
38194206 f64::from(clip.start) / self.fps,
38204207 f64::from(clip.len()) / self.fps,
@@ -3893,19 +4280,44 @@ impl Player {
38934280 .on_mouse_down(
38944281 MouseButton::Right,
38954282 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3896- if this.modal() {
3897- return;
3898- }
3899- this.select((lane, i), cx);
3900- this.context_menu = Some(ContextMenu {
3901- lane,
3902- idx: i,
3903- at: event.position,
3904- details: false,
3905- });
3906- cx.notify();
4283+ this.open_menu(lane, i, event.position, cx);
39074284 }),
39084285 )
4286+ // The two strips a drag *lengthens* the clip by,
4287+ // one at each end. They occlude the box behind
4288+ // them, which is what keeps one gesture one thing:
4289+ // a press here trims, a press anywhere else on the
4290+ // box still starts the move to another lane.
4291+ .children([Edge::Start, Edge::End].map(|edge| {
4292+ let mut zone = div()
4293+ .absolute()
4294+ .top_0()
4295+ .h_full()
4296+ .w(px(EDGE_W))
4297+ .occlude()
4298+ .cursor(CursorStyle::ResizeLeftRight)
4299+ .hover(|s| s.bg(rgb(ACCENT)))
4300+ .on_mouse_down(
4301+ MouseButton::Left,
4302+ cx.listener(move |this, _: &MouseDownEvent, _, cx| {
4303+ this.start_trim(lane, i, edge, cx);
4304+ }),
4305+ )
4306+ // Occluded, so the box's own right-button
4307+ // listener never fires here: the menu is
4308+ // the same menu, opened by the same call.
4309+ .on_mouse_down(
4310+ MouseButton::Right,
4311+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
4312+ this.open_menu(lane, i, event.position, cx);
4313+ }),
4314+ );
4315+ zone = match edge {
4316+ Edge::Start => zone.left_0(),
4317+ Edge::End => zone.right_0(),
4318+ };
4319+ zone
4320+ }))
39094321 // Under the label row, never through it.
39104322 .children(wave.filter(|_| audio).and_then(|wave| {
39114323 let inner: AnyElement = match wave {
@@ -4249,6 +4661,10 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool
42494661 // at an edge of this clip. Whether those two halves were ever one take
42504662 // is the engine's question, and it words that refusal itself.
42514663 ActionId::Regroup => playhead == clip.start || playhead == clip.end(),
4664+ // Nothing to take apart in a clip that names no group at all. Whether
4665+ // the group it names still has another half is the engine's question,
4666+ // like the regroup above, and it words that refusal itself.
4667+ ActionId::Detach => clip.link.is_some(),
42524668 _ => true,
42534669 }
42544670 }
@@ -4706,7 +5122,19 @@ fn is_bare_modifier(key: &str) -> bool {
47065122 /// timeline whose sound is spread over more than one audio lane is refused by
47075123 /// the engine (`export::run`). Said on the row, before a destination has been
47085124 /// picked, rather than after the write has started.
5125+///
5126+/// An audio-only timeline is the other one: every frame of it is a gap, so the
5127+/// mp4 would be a black picture over the sound. The engine refuses it too
5128+/// (`export::start`); this is what greys the row before a destination has been
5129+/// picked.
47095130 fn mp4_refusal(session: &PlaybackSession) -> Option<String> {
5131+ let picture = session
5132+ .lanes()
5133+ .into_iter()
5134+ .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
5135+ if !picture {
5136+ return Some("no picture — an mp4 would be black; export WAV or FLAC".to_string());
5137+ }
47105138 let lanes = session
47115139 .lanes()
47125140 .into_iter()
@@ -4760,20 +5188,57 @@ fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool {
47605188 let Some(clip) = session.lane_clips(lane).get(idx) else {
47615189 return false;
47625190 };
4763- match (lane.kind, lane.ord) {
4764- (_, 1..) => false,
4765- (LaneKind::Video, _) => true,
4766- // The sound of a take, only while the take is still there: its group is
4767- // carried by a clip on some other lane.
4768- (LaneKind::Audio, _) => session
5191+ let paired = || {
5192+ session
47695193 .lanes()
47705194 .into_iter()
47715195 .filter(|&other| other != lane)
47725196 .flat_map(|other| session.lane_clips(other))
4773- .any(|o| o.link.is_some() && o.link == clip.link),
5197+ .any(|o| o.link.is_some() && o.link == clip.link)
5198+ };
5199+ match (lane.kind, lane.ord) {
5200+ (_, 1..) => false,
5201+ // The picture of a take -- unless the take has been taken apart: a
5202+ // detached picture (a group id no other lane carries, which is also what
5203+ // a lift of the sound leaves) is a half like the sound is, and a ripple
5204+ // under it would drag away the very half it was detached from. A clip in
5205+ // no group at all is not a half but a placement, and on `V1` a placement
5206+ // is the take there is.
5207+ (LaneKind::Video, _) => clip.link.is_none() || paired(),
5208+ // The sound of a take, only while the take is still there: its group is
5209+ // carried by a clip on some other lane.
5210+ (LaneKind::Audio, _) => paired(),
47745211 }
47755212 }
47765213
5214+/// The clip a Group would pair this one with: the first clip on another track,
5215+/// in the order the lanes are drawn, covering exactly the same frames and not in
5216+/// this clip's group already. Exactly the same frames because that is all a
5217+/// group id can mean (engine `links_are_consistent`), which is what leaves
5218+/// nothing for a second click to choose. `None` when no track has one, and the
5219+/// notice says so.
5220+fn span_partner(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> {
5221+ let clip = *session.lane_clips(lane).get(idx)?;
5222+ let matches = |other: Lane| {
5223+ let i = session.lane_clips(other).iter().position(|c| {
5224+ (c.start, c.end()) == (clip.start, clip.end())
5225+ && !(c.link.is_some() && c.link == clip.link)
5226+ })?;
5227+ Some((other, i))
5228+ };
5229+ // Sound before picture (and picture before sound): "group this" means the
5230+ // other half of the take, and a project whose audio lane was added after a
5231+ // second video one has that half *after* the layer in storage order -- which
5232+ // is the order the lanes come in. A same-kind lane is still groupable (V1
5233+ // and V2 may be one take), but only where no opposite one covers the span.
5234+ let (opposite, same): (Vec<Lane>, Vec<Lane>) = session
5235+ .lanes()
5236+ .into_iter()
5237+ .filter(|&other| other != lane)
5238+ .partition(|other| other.kind != lane.kind);
5239+ opposite.into_iter().chain(same).find_map(matches)
5240+}
5241+
47775242 /// Whether a click marks this clip: the clip that was clicked always, and the
47785243 /// other lane's clip of the same group with it. A clip whose group has no other
47795244 /// 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<Pixels>) -> f32 {
49965461 ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
49975462 }
49985463
5464+/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the
5465+/// pointer stops where the arrow keys do and "0.35" on screen is the number the
5466+/// file writes rather than a rounding of one.
5467+fn color_snap(value: f32) -> f32 {
5468+ (value / COLOR_STEP).round() * COLOR_STEP
5469+}
5470+
5471+/// How the frame on screen is spread across the tone range: `HIST_BINS` counts
5472+/// per channel, read off the BGRA the decoder handed over -- which is the
5473+/// *graded* picture, because the grade is folded into the conversion
5474+/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye
5475+/// is looking at, and moving a slider moves it.
5476+///
5477+/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn
5478+/// from eight thousand samples is the same shape, at a thousandth of the reads.
5479+fn histogram(bgra: &[u8]) -> [[u32; HIST_BINS]; 3] {
5480+ let pixels = bgra.len() / 4;
5481+ let stride = (pixels / HIST_SAMPLES).max(1);
5482+ let mut bins = [[0u32; HIST_BINS]; 3];
5483+ for p in (0..pixels).step_by(stride) {
5484+ let px = &bgra[p * 4..];
5485+ // BGRA on the wire, `[r, g, b]` in the bins: the graph names channels
5486+ // the way a person does.
5487+ for (channel, value) in [px[2], px[1], px[0]].into_iter().enumerate() {
5488+ bins[channel][usize::from(value) * HIST_BINS / 256] += 1;
5489+ }
5490+ }
5491+ bins
5492+}
5493+
5494+/// The three counts drawn as three lines across the box, tallest bin to the top.
5495+///
5496+/// Square root, not linear: a shot with a big flat area (a night sky, a title
5497+/// card) puts one bin so far above the rest that a linear graph is a single
5498+/// spike beside a flat line, and the tilt a grade puts in the rest is exactly
5499+/// what the card is for.
5500+fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement {
5501+ canvas(
5502+ |_, _, _| (),
5503+ move |bounds, _, window, _| {
5504+ let (o, s) = (bounds.origin, bounds.size);
5505+ // Shared across the channels, so their relative weight is readable;
5506+ // never zero, so an unpumped (all-zero) histogram is a flat line
5507+ // rather than a division by nothing.
5508+ let top = bins.iter().flatten().copied().max().unwrap_or(0).max(1) as f32;
5509+ for (channel, counts) in bins.iter().enumerate() {
5510+ let mut path = PathBuilder::stroke(px(1.5));
5511+ for (bin, &count) in counts.iter().enumerate() {
5512+ let at = point(
5513+ o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32),
5514+ o.y + s.height * (1. - (count as f32 / top).sqrt()),
5515+ );
5516+ match bin {
5517+ 0 => path.move_to(at),
5518+ _ => path.line_to(at),
5519+ }
5520+ }
5521+ if let Ok(path) = path.build() {
5522+ window.paint_path(path, rgb(HIST_INK[channel]));
5523+ }
5524+ }
5525+ },
5526+ )
5527+ .absolute()
5528+ .size_full()
5529+}
5530+
49995531 /// The cascade's frequency response, drawn as one line across the graph.
50005532 ///
50015533 /// Every point comes from `EqParams::response_db`, which reads the very
@@ -5101,17 +5633,18 @@ fn timecode(t: f64, fps: f64) -> String {
51015633 #[cfg(test)]
51025634 mod tests {
51035635 use super::{
5104- ACCENT, CONTROL_H, Clip, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,
5105- EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM,
5636+ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH,
5637+ EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS,
5638+ Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM,
51065639 KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,
51075640 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,
51085641 RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,
5109- WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, envelope, eq_x,
5110- eq_y, export_path, export_settings, format_line, frac_along, frac_down, frame_at,
5111- is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, menu_at, mp4_refusal,
5112- normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,
5113- source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, whole_take,
5114- width_frac, window_title,
5642+ WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap,
5643+ envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down,
5644+ frame_at, histogram, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked,
5645+ menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due,
5646+ show_label, source_frames, source_tint, span_partner, start_frac, timecode, unseen_paths,
5647+ unseen_sources, whole_take, width_frac, window_title,
51155648 };
51165649 use super::{file_name, file_uri, library_rows};
51175650
@@ -5207,6 +5740,57 @@ mod tests {
52075740 assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90);
52085741 }
52095742
5743+ /// The window opened on a song and nothing else -- the launch argument, the
5744+ /// drop on an empty window and the Import button all end in the same
5745+ /// `PlaybackSession::open`. The library lists it placeable, the lane door
5746+ /// the Add button and a drag share puts it on `A1`, and the one format that
5747+ /// needs a picture says so on its own row instead of failing at the end of
5748+ /// an export.
5749+ #[test]
5750+ fn a_song_opens_the_window_by_itself() {
5751+ let mut session =
5752+ PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline");
5753+ session.set_gain(0.0);
5754+ // The source's own path, which is the canonical one a row carries.
5755+ let path = session.sources()[0].path.clone();
5756+ assert!(session.lane_clips(Lane::V1).is_empty(), "no picture");
5757+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
5758+
5759+ // The library row: probed like any other source, and not greyed --
5760+ // `unusable` is what the panel dims a row with.
5761+ let streams = HashMap::from([(
5762+ path.clone(),
5763+ engine::AudioSession::probe_streams(&path).expect("probe the song"),
5764+ )]);
5765+ let rate = streams[&path]
5766+ .iter()
5767+ .find(|s| s.index == session.sources()[0].audio_stream)
5768+ .map(|s| (s.sample_rate, s.channels));
5769+ let frames = source_frames(lane_clips(&session), session.sources(), &path);
5770+ let rows = library_rows(session.sources(), &streams, rate, |_| frames);
5771+ assert_eq!(rows.len(), 1);
5772+ assert_eq!(rows[0].name, "test_tone.mp3");
5773+ assert_eq!(rows[0].unusable, None, "the row is placeable");
5774+ assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps");
5775+
5776+ // ...and it places, on the audio lane, through the door `insert_source`
5777+ // uses: a second copy of the song at the playhead.
5778+ session.seek(1.0);
5779+ assert!(
5780+ session
5781+ .place_stream_at(1.0, &path, 0, frames, Some(Lane::A1))
5782+ .expect("its own file is on this timeline")
5783+ );
5784+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
5785+ assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
5786+
5787+ // The mp4 row carries the reason rather than the format's detail line.
5788+ assert_eq!(
5789+ mp4_refusal(&session).as_deref(),
5790+ Some("no picture — an mp4 would be black; export WAV or FLAC")
5791+ );
5792+ }
5793+
52105794 fn info(
52115795 index: usize,
52125796 rate: u32,
@@ -5360,6 +5944,16 @@ mod tests {
53605944 assert!(applicable(&clip, v1, ActionId::Regroup, 30));
53615945 assert!(applicable(&clip, v1, ActionId::Regroup, 90));
53625946 assert!(!applicable(&clip, v1, ActionId::Regroup, 60));
5947+ // Detach is the clip's own business: nothing to take apart in one that
5948+ // names no group, and whether the group still has another half is the
5949+ // engine's question. Group is offered on every clip, for that reason.
5950+ assert!(!applicable(&clip, v1, ActionId::Detach, 0));
5951+ let grouped = Clip {
5952+ link: Some(3),
5953+ ..clip
5954+ };
5955+ assert!(applicable(&grouped, v1, ActionId::Detach, 60));
5956+ assert!(applicable(&clip, a1, ActionId::Group, 0));
53635957 // The equalizer is the one item the *lane* decides: it filters samples,
53645958 // and a video clip has none of its own. Never the playhead's business.
53655959 assert!(applicable(&clip, a1, ActionId::Equalizer, 0));
@@ -5401,6 +5995,114 @@ mod tests {
54015995 }
54025996 }
54035997
5998+ /// What the Detach and Group items do to a real timeline: a music video's
5999+ /// sound comes off its picture, Delete on the loose half takes that half
6000+ /// only, undo puts both back, and Group makes the two one take again --
6001+ /// whole-take delete and all.
6002+ #[test]
6003+ fn a_detached_half_is_removed_alone_and_groups_again() {
6004+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
6005+ session.set_gain(0.0);
6006+ assert!(whole_take(&session, Lane::V1, 0), "one take to start with");
6007+ assert!(whole_take(&session, Lane::A1, 0));
6008+ let frames = session.lane_clips(Lane::V1)[0].len();
6009+
6010+ // Detach audio: neither half is a whole take any more, so Delete on
6011+ // either leaves the other exactly where it is.
6012+ assert!(session.ungroup(Lane::V1, 0));
6013+ assert!(
6014+ !whole_take(&session, Lane::A1, 0),
6015+ "the sound is a half now"
6016+ );
6017+ assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture");
6018+ assert!(session.lift_clip(Lane::A1, 0));
6019+ assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went");
6020+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed");
6021+ assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed");
6022+
6023+ // One undo per edit, the removal then the detach.
6024+ assert!(session.undo());
6025+ assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back");
6026+ assert!(session.undo());
6027+ assert!(whole_take(&session, Lane::A1, 0), "one take again");
6028+
6029+ // Group: the partner is the clip covering these very frames on the
6030+ // other track, which is what the item hands the engine.
6031+ assert!(session.ungroup(Lane::V1, 0));
6032+ assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
6033+ session
6034+ .group(Lane::V1, 0, Lane::A1, 0)
6035+ .expect("both halves still cover the same frames");
6036+ assert!(
6037+ whole_take(&session, Lane::A1, 0),
6038+ "a take that ripples again"
6039+ );
6040+ assert_eq!(
6041+ span_partner(&session, Lane::V1, 0),
6042+ None,
6043+ "and nothing left on another track to group with"
6044+ );
6045+ }
6046+
6047+ /// Which clip Group reaches when more than one covers the span: the sound,
6048+ /// whatever order the lanes are stored in. A project file may hold them in
6049+ /// any order -- a video layer *before* the audio lane among them -- and
6050+ /// "group this" means the other half of the take, never the layer above it.
6051+ #[test]
6052+ fn group_reaches_the_sound_before_a_video_layer_over_it() {
6053+ use engine::project::LaneKind;
6054+
6055+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
6056+ session.set_gain(0.0);
6057+ let v2 = session.add_lane(LaneKind::Video);
6058+ let path = session.sources()[0].path.clone();
6059+ let frames = source_frames(lane_clips(&session), session.sources(), &path);
6060+ assert!(
6061+ session
6062+ .place_stream_at(0.0, &path, 0, frames, Some(v2))
6063+ .expect("its own file is on this timeline"),
6064+ "a layer covering the same frames as the take"
6065+ );
6066+
6067+ // Saved and loaded back with the lanes in the order a hand-written
6068+ // project may hold them: the sound last, behind the layer.
6069+ let dir = std::env::temp_dir().join(format!("ve_group_{}", std::process::id()));
6070+ std::fs::create_dir_all(&dir).expect("a scratch directory");
6071+ let file = dir.join("lanes.edith");
6072+ session.save_project(&file).expect("save the project");
6073+ let text = std::fs::read_to_string(&file).expect("read it back");
6074+ let (sound, rest): (Vec<&str>, Vec<&str>) =
6075+ text.lines().partition(|l| l.starts_with("audio "));
6076+ std::fs::write(
6077+ &file,
6078+ format!("{}\n{}\n", rest.join("\n"), sound.join("\n")),
6079+ )
6080+ .expect("write the reordered project");
6081+ let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands");
6082+ std::fs::remove_dir_all(&dir).ok();
6083+ assert_eq!(
6084+ session.lanes(),
6085+ vec![Lane::V1, v2, Lane::A1],
6086+ "the sound is the last lane there"
6087+ );
6088+
6089+ // Detached, so Group has a choice to get wrong: the layer covers these
6090+ // frames too, and it is the lane the walk meets first.
6091+ assert!(session.ungroup(Lane::V1, 0));
6092+ // Group on the picture reaches the sound, not that layer.
6093+ assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
6094+ session
6095+ .group(Lane::V1, 0, Lane::A1, 0)
6096+ .expect("the two halves cover the same frames");
6097+ // ...and a lane of its own kind is still groupable, once the sound is
6098+ // spoken for: two video lanes may be one take.
6099+ assert_eq!(
6100+ span_partner(&session, Lane::V1, 0),
6101+ Some((v2, 0)),
6102+ "the layer is what is left to group with"
6103+ );
6104+ }
6105+
54046106 /// The refusal path, end to end against the real files: an incompatible
54056107 /// import changes nothing, and the library mirrors `sources()` 1:1, so a
54066108 /// refused file cannot leave a row behind.
@@ -5538,6 +6240,64 @@ mod tests {
55386240 assert!(session.remove_source(&second, 0).is_err());
55396241 }
55406242
6243+ /// The trim-a-clip path through the doors the edge drag uses:
6244+ /// [`Player::trim_to`] clamps the pointer with `trim_room` and
6245+ /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
6246+ /// of its file, the sound linked to it follows, the head trim moves the
6247+ /// in-point, and one undo takes a whole gesture back.
6248+ ///
6249+ /// The routing *to* these doors -- the 6 px edge strip claiming the press
6250+ /// the clip's own body-drag would otherwise take -- is gpui hitbox
6251+ /// behaviour (`occlude`) and is not reachable without a window.
6252+ #[test]
6253+ fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
6254+ use engine::project::Edge;
6255+
6256+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
6257+ session.set_gain(0.0);
6258+ let whole = session.lane_clips(Lane::V1)[0];
6259+ let full = session.timeline_duration();
6260+ assert_eq!(
6261+ session.trim_room(Lane::V1, 0, Edge::End),
6262+ Some((whole.start + 1, whole.end())),
6263+ "the file's own last frame is how far the tail goes"
6264+ );
6265+ assert!(
6266+ !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
6267+ "it already plays all of it"
6268+ );
6269+
6270+ // Pulled in by a third: the timeline ends earlier and the sound with it.
6271+ let shorter = whole.end() - whole.len() / 3;
6272+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
6273+ assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
6274+ assert_eq!(
6275+ session.lane_clips(Lane::A1)[0].end(),
6276+ shorter,
6277+ "the linked sound was trimmed with the picture"
6278+ );
6279+ assert!(session.timeline_duration() < full, "and plays out earlier");
6280+
6281+ // ...and dragged back out, as far as the file goes and no further.
6282+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
6283+ assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the whole take back");
6284+
6285+ // The head takes the in-point with it, so what plays at the new start
6286+ // is source frame 10 rather than source frame 0.
6287+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
6288+ let head = session.lane_clips(Lane::V1)[0];
6289+ assert_eq!((head.start, head.in_frame), (10, 10));
6290+ assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
6291+ assert_eq!(
6292+ session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
6293+ Some(0),
6294+ "and it may be pulled back out to the file's first frame"
6295+ );
6296+
6297+ assert!(session.undo(), "one step for the whole drag");
6298+ assert_eq!(session.lane_clips(Lane::V1)[0], whole);
6299+ }
6300+
55416301 /// The move-a-clip-between-tracks path through the door the drop uses
55426302 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the
55436303 /// *picture* comes from the new row afterwards -- which is what "it plays
@@ -6071,6 +6831,130 @@ mod tests {
60716831 assert!(KEYS_ROW_H >= HIT_MIN);
60726832 }
60736833
6834+ /// A colour slider is dragged straight to a value, so where the pointer
6835+ /// lands and where the bar then paints have to be the same place: this is
6836+ /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.
6837+ #[test]
6838+ fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() {
6839+ // A bar as laid out, somewhere that is not the window's origin -- a
6840+ // mapping that forgot the offset would pass at zero.
6841+ let bar = Bounds {
6842+ origin: point(px(180.), px(240.)),
6843+ size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
6844+ };
6845+ for &(label, low, high) in &COLOR_BANDS {
6846+ // The ends are the ends: the left of the bar is the bottom of the
6847+ // range and the right is the top, so a slider can be pulled to
6848+ // either without hunting for the last pixel.
6849+ let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low));
6850+ assert_eq!(at(180.), low, "{label} left end");
6851+ assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end");
6852+ // Off either end clamps rather than running past the range.
6853+ assert_eq!(at(-4000.), low, "{label} off the left");
6854+ assert_eq!(at(9999.), high, "{label} off the right");
6855+
6856+ for step in 0..=48 {
6857+ let along = step as f32 / 48.;
6858+ let value = at(180. + along * COLOR_BAR_W);
6859+ // Every stop is one the keyboard can also reach, which is what
6860+ // keeps "0.35" the number the file writes.
6861+ let steps = value / COLOR_STEP;
6862+ assert!(
6863+ (steps - steps.round()).abs() < 1e-3,
6864+ "{label}: {value} is off the {COLOR_STEP} grid"
6865+ );
6866+ assert!(
6867+ (low..=high).contains(&value),
6868+ "{label}: {value} outside {low}..{high}"
6869+ );
6870+ // What the row paints from that value is where the pointer was,
6871+ // to within the half step the snap costs.
6872+ let painted = (value - low) / (high - low);
6873+ let slack = COLOR_STEP / (high - low) / 2. + 1e-4;
6874+ assert!(
6875+ (painted - along).abs() <= slack,
6876+ "{label}: pressed at {along}, paints at {painted}"
6877+ );
6878+ }
6879+ }
6880+
6881+ // The same shape as the other two cards, so it fits where they do: the
6882+ // graph, four rows and the reset button inside a 360 px window.
6883+ let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.);
6884+ let rows = COLOR_BANDS.len() as f32 * KEYS_ROW_H;
6885+ assert!(
6886+ title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360.,
6887+ "card too tall"
6888+ );
6889+ assert!(COLOR_W <= 640., "card too wide");
6890+ // The label still has room beside the bar and the readout, which is
6891+ // what the buttons coming off the row bought.
6892+ let row = COLOR_W - padding - 12. - 2. * 8. - COLOR_BAR_W - 44.;
6893+ assert!(row >= LABEL_MIN_W, "no room left for a label: {row}px");
6894+ // What is dragged is the whole row's height, not the 4 px the bar is
6895+ // drawn as (WCAG 2.5.8) -- the same split the ruler makes.
6896+ assert!(KEYS_ROW_H >= HIT_MIN);
6897+ }
6898+
6899+ /// The graph over the sliders is the frame the grade already went through,
6900+ /// so it has to count what is actually in those bytes -- BGRA on the wire,
6901+ /// red-green-blue in the bins.
6902+ #[test]
6903+ fn the_histogram_counts_the_frame_it_is_handed() {
6904+ // Half pure red, half mid grey: two known values, in two known bins.
6905+ let (w, h) = (64usize, 64usize);
6906+ let mut frame = Vec::with_capacity(w * h * 4);
6907+ for _ in 0..h {
6908+ for col in 0..w {
6909+ match col < w / 2 {
6910+ true => frame.extend_from_slice(&[0, 0, 255, 255]),
6911+ false => frame.extend_from_slice(&[128, 128, 128, 255]),
6912+ }
6913+ }
6914+ }
6915+ let bins = histogram(&frame);
6916+ let half = (w * h / 2) as u32;
6917+ // 64 bins over 256 codes: 255 is the last bin, 128 the middle one, 0 the
6918+ // first.
6919+ assert_eq!(bins[0][63], half, "the red half tops the red channel");
6920+ assert_eq!(bins[0][32], half, "and the grey half sits mid red");
6921+ for channel in [1, 2] {
6922+ assert_eq!(bins[channel][0], half, "no green or blue in the red half");
6923+ assert_eq!(bins[channel][32], half);
6924+ assert_eq!(bins[channel][63], 0);
6925+ }
6926+ // Nothing is counted twice and nothing is dropped: this frame is small
6927+ // enough to be read whole.
6928+ for channel in bins {
6929+ assert_eq!(channel.iter().sum::<u32>(), (w * h) as u32);
6930+ }
6931+
6932+ // A grade shifts it, which is the whole point of drawing it: the same
6933+ // frame darkened lands in lower bins.
6934+ let darker: Vec<u8> = frame.iter().map(|b| b / 2).collect();
6935+ let bins = histogram(&darker);
6936+ assert_eq!(bins[0][31], half, "255 -> 127");
6937+ assert_eq!(bins[0][16], half, "128 -> 64");
6938+
6939+ // A real frame is subsampled: a 1080p one is read every 253rd pixel, so
6940+ // the shape costs a thousandth of the reads and still counts thousands.
6941+ let big = vec![200u8; 1920 * 1080 * 4];
6942+ let bins = histogram(&big);
6943+ let counted = bins[0].iter().sum::<u32>();
6944+ let pixels = 1920 * 1080usize;
6945+ let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32;
6946+ assert_eq!(counted, expected, "every strided pixel counted, once");
6947+ assert!(
6948+ (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted),
6949+ "{counted} samples is not the budget"
6950+ );
6951+ assert_eq!(bins[0][200 * HIST_BINS / 256], counted, "all in one bin");
6952+
6953+ // An empty buffer is a flat graph rather than a panic: the card is open
6954+ // before the first frame is pumped.
6955+ assert_eq!(histogram(&[]), [[0; HIST_BINS]; 3]);
6956+ }
6957+
60746958 /// Mute and level are one control with two states, and the whole point is
60756959 /// that mute keeps the level: the user gets back what they had, not 100%.
60766960 #[test]
@@ -6586,6 +7470,7 @@ fn main() {
65867470 streams: HashMap::new(),
65877471 clipboard: None,
65887472 scrubbing: false,
7473+ trim: None,
65897474 last_scrub: Instant::now(),
65907475 last_target: 0,
65917476 export: None,
@@ -6604,6 +7489,11 @@ fn main() {
66047489 eq_graph: Rc::default(),
66057490 color_open: None,
66067491 color_band: 0,
7492+ color_dragging: false,
7493+ color_bars: std::array::from_fn(|_| Rc::default()),
7494+ // Empty until the first frame is pumped, which draws as a
7495+ // flat line rather than as a shape nothing measured.
7496+ histogram: [[0; HIST_BINS]; 3],
66077497 // What an export is until someone says otherwise: the
66087498 // bitrate the picture asks for.
66097499 quality: Quality::Auto,
crates/engine/src/edith.rsmodified+25 -19
@@ -504,9 +504,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
504504 }
505505 }
506506 }
507- if doc.lanes.iter().all(|(_, clips)| clips.is_empty()) {
508- return Err("no clips: an empty timeline is not a project".into());
509- }
507+ // A file whose lanes are all empty *is* a project -- the emptied timeline,
508+ // saved. What it may not be is laneless; [`crate::Project::from_parts`]
509+ // refuses that one, by the name it has there.
510510 Ok(doc)
511511 }
512512
@@ -870,13 +870,10 @@ mod tests {
870870 ] {
871871 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
872872 }
873- // Lanes and nothing on them is not a project.
874- assert_eq!(
875- parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir)
876- .unwrap_err()
877- .to_string(),
878- "no clips: an empty timeline is not a project"
879- );
873+ // Lanes and nothing on them is the emptied timeline, saved: a project.
874+ let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
875+ assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
876+ assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
880877 }
881878
882879 /// One band, spelled the way an eq line spells it.
@@ -1539,19 +1536,28 @@ mod tests {
15391536 }
15401537 }
15411538
1539+ /// The emptied timeline writes and reads back: every lane declared, no clip
1540+ /// on any of them, and the source that gave the project its frame rate still
1541+ /// named. Nothing about the format changes for it -- an empty lane already
1542+ /// had a line of its own.
15421543 #[test]
1543- fn a_project_without_clips_is_not_a_project() {
1544+ fn a_project_without_clips_round_trips() {
15441545 let dir = PathBuf::from("/proj");
1546+ let source = Source {
1547+ path: PathBuf::from("/proj/a.mp4"),
1548+ audio_stream: 0,
1549+ };
1550+ let bytes = flat(&dir, &[source.clone()], &two(Vec::new(), Vec::new()), 0);
1551+ let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
1552+ assert_eq!(back.sources, vec![source]);
1553+ assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
1554+ assert_eq!(back.playhead, 0);
1555+ // Older dialects, where the two lanes are implied rather than declared.
15451556 assert_eq!(
1546- parse(b"edith 1\nsource a.mp4\n", &dir)
1547- .unwrap_err()
1548- .to_string(),
1549- "no clips: an empty timeline is not a project"
1550- );
1551- assert_eq!(
1552- parse(b"edith 1\n", &dir).unwrap_err().to_string(),
1553- "no clips: an empty timeline is not a project"
1557+ parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
1558+ two(Vec::new(), Vec::new())
15541559 );
1560+ assert!(parse(b"edith 1\n", &dir).expect("a project of nothing").sources.is_empty());
15551561 }
15561562
15571563 /// Every truncation of a good file either parses or refuses; none panics.
crates/engine/src/export.rsmodified+33 -1
@@ -31,7 +31,7 @@ use crate::audio::{AudioMeta, AudioSession};
3131 use crate::demux::{Demuxer, VideoMeta};
3232 use crate::hw::{HwEncoder, HwSession};
3333 use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
34-use crate::project::Project;
34+use crate::project::{LaneKind, Project};
3535 use crate::scale::Composer;
3636
3737 /// Progress is reported in permille: an atomic integer the render loop can read
@@ -165,7 +165,28 @@ pub fn start(
165165 // The rename is the last step and the only one that publishes a file
166166 // under the name the caller asked for; it stays on the same directory,
167167 // so it is atomic.
168+ //
169+ // An emptied timeline is a legal project and an illegal file: no
170+ // picture, no sound, and a muxer that is never created because no coded
171+ // frame arrives. Refused by name here -- before the format is even
172+ // looked at, so an mp4 and a WAV refuse in the same words -- rather than
173+ // left to write a file of no frames that nothing opens. Every caller of
174+ // `start` comes through this, the app's own door
175+ // (`PlaybackSession::is_empty`) being only the first fence.
176+ //
177+ // An audio-only timeline is the other legal project no mp4 can be made
178+ // of: every frame of it is a gap, so the file would be black picture
179+ // over the sound -- minutes of encoding for a video of nothing. Refused
180+ // by name, with the two formats that *are* that timeline, rather than
181+ // written; the app says the same on the format row before a destination
182+ // is even picked (`mp4_refusal`).
168183 let written = match settings.format {
184+ _ if project.timeline_frames() == 0 => {
185+ Err("the timeline is empty: there is nothing to export".into())
186+ }
187+ Format::Mp4 if !has_picture(&project) => Err("the timeline has no picture: \
188+ an mp4 would be black. Export WAV or FLAC, which are the sound itself"
189+ .into()),
169190 Format::Mp4 => run(&project, &meta, &part, &worker, &settings),
170191 format => run_audio(&project, &meta, &part, &worker, format),
171192 };
@@ -182,6 +203,17 @@ pub fn start(
182203 ExportHandle { shared }
183204 }
184205
206+/// Whether any video lane holds anything at all -- what tells an audio-only
207+/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
208+/// than of the sources, because a project may name a video file no clip plays
209+/// from any more.
210+fn has_picture(project: &Project) -> bool {
211+ project
212+ .lanes()
213+ .into_iter()
214+ .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
215+}
216+
185217 fn settle(shared: &Shared, result: crate::Result<()>) {
186218 *shared.outcome.lock().unwrap() = Some(result);
187219 // Published last: a caller that sees the flag is guaranteed the outcome.
crates/engine/src/playback.rsmodified+318 -48
@@ -23,15 +23,29 @@ use crate::audio::{AudioChunk, AudioSession};
2323 use crate::clock::{ClockSource, PlaybackClock};
2424 use crate::color::ColorParams;
2525 use crate::decode::{DecodeSession, Frame, Worker};
26-use crate::demux::{Demuxer, VideoMeta};
26+use crate::demux::{Codec, Demuxer, VideoMeta};
2727 use crate::eq::EqParams;
28-use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};
28+use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span};
2929 use crate::scale::{Composer, FitPolicy};
3030
3131 /// How long the feeder waits out a full ring. The ring holds a second, so this
3232 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
3333 const RING_FULL_WAIT: Duration = Duration::from_millis(10);
3434
35+/// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
36+/// nothing was shot on it, so it is the canvas a *later* import meets rather
37+/// than a description of the song. H.264 because it is the one codec that
38+/// decodes without the plugin, 30 fps because a rounded-up audio length is what
39+/// the frame count means and a whole number of frames per second keeps it
40+/// honest; both are what a video imported onto such a timeline is held to
41+/// ([`matches_timeline`]).
42+///
43+/// ponytail: a 25 fps video refused by an audio-only timeline it could have
44+/// defined is the ceiling here. Upgrade path is adopting the first *picture's*
45+/// rate and codec on import, which means retiming every audio clip already
46+/// placed in frames.
47+const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);
48+
3549 /// The output half of a session: the device, plus what the feeder has handed it.
3650 /// Cloned into the feeder thread; every field that matters is shared.
3751 #[derive(Clone)]
@@ -122,13 +136,29 @@ pub struct PlaybackSession {
122136 /// The edit list. Everything a caller says in seconds is a *timeline*
123137 /// position; only this maps it onto the file.
124138 project: Project,
139+ /// How many frames each source actually holds, indexed exactly as
140+ /// [`Project::sources`] is and grown with it. The project itself does not
141+ /// know -- a clip names a source by index and carries its own range -- and
142+ /// [`Self::trim_clip`] is the one edit that could ask for frames past the
143+ /// end of a file, which is a save that would not open again
144+ /// ([`Self::open_project`] refuses one by name). Append-only for
145+ /// `sources`'s reason: an index handed out stays valid, undone import or
146+ /// not -- with the single exception `sources` itself has,
147+ /// [`Self::remove_source`], which takes the same entry out of both.
148+ counts: Vec<u32>,
125149 /// What the current video worker was opened for: where it sits on the
126150 /// timeline, how long it runs, and which source frame it started at --
127151 /// together they rewrite a source frame index into a timeline one. Not a
128152 /// clip index: a `split` cuts the clip under a running worker, and only the
129153 /// mapping survives that. A span with no source is a *gap*, and the worker
130154 /// feeding it emits black frames indexed from zero.
131- span: Span,
155+ ///
156+ /// `None` is the *emptied* timeline -- no clip on any lane, so there is no
157+ /// stretch to be inside of. It is a state, not a failure: the picture is
158+ /// black ([`start_span`](Self::start_span) feeds one black frame for it),
159+ /// the sound is silence, the duration is zero, and placing anything reseeks
160+ /// straight back out of it.
161+ span: Option<Span>,
132162 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
133163 eos: bool,
134164 }
@@ -138,16 +168,12 @@ impl PlaybackSession {
138168 /// a file we cannot hear is still a file we can watch.
139169 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
140170 let path = path.as_ref().to_path_buf();
141- // A timeline is scaffolded from source 0's picture -- its size, its
142- // frame rate, its clock. A song has none of that, so it joins a
143- // timeline (`import`) rather than starting one, and saying so beats
144- // failing in the demuxer's words.
171+ // A timeline is normally scaffolded from source 0's picture -- its size,
172+ // its frame rate, its clock. A song has none of that, so it scaffolds
173+ // the *canvas* instead and its own sound keeps the clock: an audio-only
174+ // project is a project like any other, it simply plays black.
145175 if crate::is_audio(&path) {
146- return Err(format!(
147- "{} has no picture: open a video first, then import it onto the audio lane",
148- path.display()
149- )
150- .into());
176+ return Self::open_audio_only(&path);
151177 }
152178 // `open_worker` rather than `open` purely for the worker handle: the
153179 // field has to exist from the start for the first seek to use it.
@@ -174,7 +200,7 @@ impl PlaybackSession {
174200 // One clip per lane covering the file, so timeline == source until the
175201 // first edit -- and the range opened above is exactly that clip's.
176202 let project = Project::single(&path, meta.frame_count);
177- let span = project.composite_span_at(0).expect("never empty");
203+ let span = project.composite_span_at(0);
178204 Ok(Self {
179205 meta,
180206 native: (meta.width, meta.height),
@@ -185,6 +211,79 @@ impl PlaybackSession {
185211 audio,
186212 audio_disabled,
187213 project,
214+ counts: vec![meta.frame_count],
215+ span,
216+ eos: false,
217+ })
218+ }
219+
220+ /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its
221+ /// own: one clip on `A1`, nothing on the video lane, and a picture that is
222+ /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as
223+ /// the song runs. Its own sound keeps the clock, exactly as a video's does.
224+ ///
225+ /// Refused when the file has no sound to time it by: a source with neither a
226+ /// picture nor a playable length is not a timeline, and that is what
227+ /// [`audio_frames`] answers -- the *device* is a different question, and a
228+ /// machine without one opens this like any other session, silently.
229+ fn open_audio_only(path: &Path) -> crate::Result<Self> {
230+ let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
231+ let meta = VideoMeta {
232+ width,
233+ height,
234+ frame_rate,
235+ // Rounded up to whole frames, which is the only frame count a
236+ // source with no picture has -- the same length `import_audio`
237+ // gives a song joining a timeline of video. The demuxer's words are
238+ // named with the file, since this is the door a file that is not
239+ // really audio at all comes to.
240+ frame_count: audio_frames(path, frame_rate)
241+ .map_err(|e| format!("{}: {e}", path.display()))?,
242+ codec: Codec::H264,
243+ };
244+ let (audio, audio_disabled) = open_audio(path, 0);
245+ // Through `from_parts` rather than `Project::single`, which is the
246+ // *video* open's pair of grouped clips: here there is no picture to
247+ // group the sound with, so the video lane starts empty.
248+ let clip = Clip {
249+ start: 0,
250+ in_frame: 0,
251+ out_frame: meta.frame_count,
252+ source: 0,
253+ link: None,
254+ eq: None,
255+ color: None,
256+ fit: FitPolicy::default(),
257+ };
258+ let project = Project::from_parts(
259+ vec![Source::new(path, 0)],
260+ vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])],
261+ Vec::new(),
262+ Vec::new(),
263+ )?;
264+ // Every frame of this timeline is a gap, since no video lane covers
265+ // anything: `composite_span_at` says so and the black worker
266+ // `start_span` would open is opened here instead, for the reason `open`
267+ // opens its decoder inline -- the field has to exist for the first seek.
268+ let span = project.composite_span_at(0);
269+ let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len));
270+ Ok(Self {
271+ meta,
272+ native: (width, height),
273+ frames: stream.frames,
274+ worker: stream.worker,
275+ retired: Vec::new(),
276+ // The song keeps the clock, as a video's own sound does -- and wall
277+ // time keeps it on a machine with no device, where the picture
278+ // (black) still has to move at some rate.
279+ clock: PlaybackClock::new(match audio {
280+ Some(_) => ClockSource::Audio,
281+ None => ClockSource::Wall,
282+ }),
283+ audio,
284+ audio_disabled,
285+ project,
286+ counts: vec![meta.frame_count],
188287 span,
189288 eos: false,
190289 })
@@ -223,14 +322,33 @@ impl PlaybackSession {
223322 // Ungraded, and superseded before a frame of it is shown: the `seek` at
224323 // the end of this function reopens the playhead's span through
225324 // `start_span`, which is where a saved grade reaches the picture.
226- let (mut meta, stream) = DecodeSession::open_worker(
227- &first.path,
228- 0,
229- u32::MAX,
230- ColorParams::default(),
231- Composer::passthrough(),
232- )
233- .map_err(|e| format!("source {}: {e}", first.path.display()))?;
325+ // ...unless it has no picture to open: a project whose source 0 is a
326+ // song scaffolds the canvas the same way a fresh audio-only open does
327+ // ([`open_audio_only`](Self::open_audio_only)), and the placeholder
328+ // black stream is superseded by the `seek` at the end of this function
329+ // like every other worker opened here.
330+ let (mut meta, stream) = match crate::is_audio(&first.path) {
331+ true => {
332+ let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
333+ let meta = VideoMeta {
334+ width,
335+ height,
336+ frame_rate,
337+ frame_count: audio_frames(&first.path, frame_rate)
338+ .map_err(|e| format!("source {}: {e}", first.path.display()))?,
339+ codec: Codec::H264,
340+ };
341+ (meta, DecodeSession::open_black(width, height, 1))
342+ }
343+ false => DecodeSession::open_worker(
344+ &first.path,
345+ 0,
346+ u32::MAX,
347+ ColorParams::default(),
348+ Composer::passthrough(),
349+ )
350+ .map_err(|e| format!("source {}: {e}", first.path.display()))?,
351+ };
234352 // The project's own resolution, which is source 0's picture unless the
235353 // file says otherwise -- every dialect before v7 had no way to say it,
236354 // and that default is exactly what those projects meant.
@@ -290,7 +408,7 @@ impl PlaybackSession {
290408
291409 let playhead = doc.playhead;
292410 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?;
293- let span = project.composite_span_at(0).expect("never empty");
411+ let span = project.composite_span_at(0);
294412 // Last, because it is the one thing here that cannot be taken back: the
295413 // feeder thread outlives the `Audio` value (it holds its own clones) and
296414 // only a session's `drop` retires it, so a refusal above this line would
@@ -310,6 +428,7 @@ impl PlaybackSession {
310428 audio,
311429 audio_disabled,
312430 project,
431+ counts,
313432 span,
314433 eos: false,
315434 };
@@ -370,9 +489,12 @@ impl PlaybackSession {
370489 match self.frames.try_recv() {
371490 Ok(mut frame) => {
372491 // A gap's worker indexes from zero, a decoder's from its in
373- // point: `base` is whichever this span started at.
374- let base = self.span.from.map_or(0, |(_, in_frame)| in_frame);
375- frame.index = self.span.start + frame.index.saturating_sub(base);
492+ // point: `base` is whichever this span started at. An empty
493+ // timeline has no span, and its one black frame is frame 0.
494+ let (start, base) = self
495+ .span
496+ .map_or((0, 0), |s| (s.start, s.from.map_or(0, |(_, i)| i)));
497+ frame.index = start + frame.index.saturating_sub(base);
376498 return Some(frame);
377499 }
378500 Err(TryRecvError::Empty) => return None,
@@ -415,35 +537,47 @@ impl PlaybackSession {
415537 /// than remembered as a clip index, because a `split` while playing cuts the
416538 /// clip under the running worker and only the mapping stays true.
417539 fn next_clip(&mut self) -> bool {
418- let next = self.span.end();
540+ // No span is the emptied timeline: it was played out the moment its one
541+ // black frame went by, and there is no "next" to walk to.
542+ let next = match self.span {
543+ Some(span) => span.end(),
544+ None => return false,
545+ };
419546 let Some(span) = self.project.composite_span_at(next) else {
420547 return false;
421548 };
422549 // We only get here on a disconnect, so the old worker has already
423550 // returned; cancel anyway, so `retire` treats every path alike.
424551 self.worker.cancel();
425- self.start_span(span);
552+ self.start_span(Some(span));
426553 true
427554 }
428555
429556 /// Points the video worker at `span`: a decoder over its source range, or a
430- /// black-frame generator for a gap. The old worker must already have been
431- /// cancelled -- this is the half both `seek` and `next_clip` share.
557+ /// black-frame generator for a gap -- and for `None`, the emptied timeline,
558+ /// which is one frame of black so the viewer shows the nothing that is
559+ /// there rather than the last picture of the clip that was deleted. The old
560+ /// worker must already have been cancelled -- this is the half both `seek`
561+ /// and `next_clip` share.
432562 ///
433563 /// A source that will not open leaves the *span* installed anyway: the
434564 /// timeline still moves, there are simply no more pictures, and the
435565 /// disconnected receiver carries the session on to the next span.
436- fn start_span(&mut self, span: Span) {
437- let opened = match span.from {
566+ fn start_span(&mut self, span: Option<Span>) {
567+ let opened = match span {
438568 // The grade is the composite's at this frame -- the same clip the
439569 // span itself came from -- and it is constant across the span, so
440570 // the worker carries it and every frame it converts wears it.
441- Some((source, in_frame)) => DecodeSession::open_worker(
571+ Some(Span {
572+ start,
573+ len,
574+ from: Some((source, in_frame)),
575+ }) => DecodeSession::open_worker(
442576 &self.project.sources()[source].path,
443577 in_frame,
444- in_frame + span.len,
578+ in_frame + len,
445579 self.project
446- .composite_color_at(span.start)
580+ .composite_color_at(start)
447581 .copied()
448582 .unwrap_or_default(),
449583 // ...and the canvas it is placed on: the project's resolution
@@ -452,15 +586,18 @@ impl PlaybackSession {
452586 Composer::new(
453587 self.meta.width,
454588 self.meta.height,
455- self.project.composite_fit_at(span.start),
589+ self.project.composite_fit_at(start),
456590 ),
457591 )
458592 .map(|(_, stream)| stream)
459- .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),
460- None => Ok(DecodeSession::open_black(
593+ .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")),
594+ // A gap: black for as long as it runs. An emptied timeline has no
595+ // span at all and gets one frame of it -- enough to put black on
596+ // screen, and it ends where the timeline does, at once.
597+ gap => Ok(DecodeSession::open_black(
461598 self.meta.width,
462599 self.meta.height,
463- span.len,
600+ gap.map_or(1, |s| s.len),
464601 )),
465602 };
466603 if let Ok(stream) = opened {
@@ -480,6 +617,14 @@ impl PlaybackSession {
480617 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
481618 }
482619
620+ /// Whether no lane holds anything: the emptied timeline, which plays black
621+ /// and silent and is zero seconds long. A state, not a failure -- but the
622+ /// one a caller with nothing to render (an export) has to refuse by name
623+ /// rather than write a file of no frames.
624+ pub fn is_empty(&self) -> bool {
625+ self.project.timeline_frames() == 0
626+ }
627+
483628 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
484629 /// needs to lay itself out. Selection is the caller's business.
485630 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
@@ -552,6 +697,21 @@ impl PlaybackSession {
552697 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
553698 }
554699
700+ /// Takes that clip out of its group, so its picture and its sound are edited
701+ /// apart from here on. Metadata only like a cut -- no reseek -- and one undo
702+ /// step. `false` for a bad index and for a clip that is not grouped with
703+ /// anything, which is already detached.
704+ pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
705+ self.project.ungroup(lane, idx)
706+ }
707+
708+ /// Puts two clips covering the same frames back into one group: the regroup
709+ /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo
710+ /// step, and the error says why when it refuses.
711+ pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
712+ self.project.group(a, a_idx, b, b_idx)
713+ }
714+
555715 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
556716 /// that plays flat -- what a card shows before it lets anyone drag a band.
557717 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
@@ -575,8 +735,9 @@ impl PlaybackSession {
575735
576736 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
577737 /// silence on the audio one, and nothing else moves. Reseeks, because what
578- /// the playhead sits on has changed. `false` for a bad index and for the
579- /// lift that would leave the whole timeline empty.
738+ /// the playhead sits on has changed. `false` for a bad index -- the lift of
739+ /// the last placement there is empties the timeline, which is a state
740+ /// ([`is_empty`](Self::is_empty)) and one undo away.
580741 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
581742 self.edit(|p| p.lift(lane, idx))
582743 }
@@ -591,6 +752,45 @@ impl PlaybackSession {
591752 self.edit(|p| p.move_to_lane(from, idx, to))
592753 }
593754
755+ /// Drags one end of that clip to timeline frame `to`, changing how much of
756+ /// its source it plays and nothing else on the lane -- see [`Project::trim`]
757+ /// for the walls it is clamped by, which this fills the source lengths in
758+ /// for. One undo step per call, so a front-end calls it once, at the release
759+ /// of the drag. Reseeks like every other edit, which is what makes the
760+ /// picture (and the sound) follow a new in-point straight away. `false` for
761+ /// a bad index and for an edge already where it was asked to go.
762+ ///
763+ /// A *frame*, where the rest of this type takes seconds: a drag has already
764+ /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
765+ /// answer is in frames -- converting it back through seconds would be a
766+ /// rounding step between the width drawn and the width committed.
767+ pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
768+ // Spelled out rather than through `edit`, whose closure cannot hold a
769+ // second borrow of the session while it has the project.
770+ if !self.project.trim(lane, idx, edge, to, &self.counts) {
771+ return false;
772+ }
773+ let now = self.now();
774+ self.seek(now);
775+ true
776+ }
777+
778+ /// Where that edge may land, `(first, last)` timeline frame inclusive: what
779+ /// a drag clamps the pointer to so the box it draws is the box
780+ /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
781+ pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
782+ self.project.trim_room(lane, idx, edge, &self.counts)
783+ }
784+
785+ /// Records how long a source is, for a source index that may be one
786+ /// `Project::import` just made or one it handed back. See [`Self::counts`].
787+ fn note_frames(&mut self, source: usize, frames: u32) {
788+ if source == self.counts.len() {
789+ self.counts.push(frames);
790+ }
791+ debug_assert_eq!(self.counts.len(), self.project.sources().len());
792+ }
793+
594794 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
595795 /// on and its index there, by the same topmost-lane-wins rule the decoder
596796 /// follows. `None` over a gap and past the end. What a card that grades
@@ -624,6 +824,14 @@ impl PlaybackSession {
624824 self.edit(|p| p.set_color(lane, idx, params))
625825 }
626826
827+ /// The same grade and the same reseek without the undo step
828+ /// ([`Project::set_color_live`]): what the samples inside one slider drag go
829+ /// through, so the frame regrades under the hand and the whole gesture is
830+ /// still a single `z`.
831+ pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
832+ self.edit(|p| p.set_color_live(lane, idx, params))
833+ }
834+
627835 /// The project's resolution: what every clip is composed onto, what the
628836 /// window is sized to and what an export writes -- *not* any one file's.
629837 /// It starts as source 0's picture, which is what a project meant before it
@@ -729,6 +937,7 @@ impl PlaybackSession {
729937 let first = self.first_audio()?;
730938 audio_matches(&wanted, &first)?;
731939 let source = self.project.import(path, stream);
940+ self.note_frames(source, frames.max(1));
732941 let clip = Clip {
733942 start: 0,
734943 in_frame: 0,
@@ -782,6 +991,14 @@ impl PlaybackSession {
782991 .position(|s| *s == wanted)
783992 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
784993 self.project.remove_source(idx)?;
994+ // The one thing that shortens the source list, so the one place
995+ // [`Self::counts`] shortens with it: left behind, the gone file's length
996+ // would become the wall a *surviving* source is trimmed against
997+ // ([`trim_room`](Self::trim_room)) and the next import would land its
998+ // count one index late.
999+ if idx < self.counts.len() {
1000+ self.counts.remove(idx);
1001+ }
7851002 let now = self.now();
7861003 self.seek(now);
7871004 Ok(())
@@ -808,7 +1025,8 @@ impl PlaybackSession {
8081025 /// on every lane. Unlike a split this *does* move every following frame, so
8091026 /// the session reseeks to wherever the playhead now points.
8101027 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
811- /// `false` for a bad index or the last remaining clip.
1028+ /// `false` for a bad index; the last remaining clip goes like any other and
1029+ /// leaves the timeline empty ([`is_empty`](Self::is_empty)).
8121030 ///
8131031 /// The lane travels because the index is a lane's own: `V2`'s third clip is
8141032 /// not `V1`'s, and a front-end that could only say "the third clip" would
@@ -843,6 +1061,7 @@ impl PlaybackSession {
8431061
8441062 let old_end = self.timeline_duration();
8451063 let source = self.project.import(path, 0);
1064+ self.note_frames(source, meta.frame_count);
8461065 // Refused only for an unknown index, and this one just came from `import`.
8471066 self.project.append_clip(source, meta.frame_count);
8481067 // Reseek like any other edit, even though nothing before the playhead
@@ -875,6 +1094,7 @@ impl PlaybackSession {
8751094
8761095 let old_end = self.timeline_duration();
8771096 let source = self.project.import(path, 0);
1097+ self.note_frames(source, frames);
8781098 let at = self.project.timeline_frames();
8791099 self.project.place(
8801100 Lane::A1,
@@ -999,12 +1219,10 @@ impl PlaybackSession {
9991219 // [`retire`](Self::retire), which is what keeps a scrub off the price
10001220 // of a VA-API init.
10011221 self.worker.cancel();
1002- // `target` is inside the timeline (never empty), so this always spans;
1003- // the span runs from there to the end of whatever it landed in -- a
1004- // clip, or a gap, which starts a black-frame worker instead.
1005- if let Some(span) = self.project.composite_span_at(target) {
1006- self.start_span(span);
1007- }
1222+ // The span runs from `target` to the end of whatever it landed in -- a
1223+ // clip, or a gap, which starts a black-frame worker instead. `None` is
1224+ // the emptied timeline, black too, and `start_span` says so.
1225+ self.start_span(self.project.composite_span_at(target));
10081226 self.eos = false;
10091227
10101228 let mut audio_running = false;
@@ -1318,7 +1536,59 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 {
13181536
13191537 #[cfg(test)]
13201538 mod tests {
1321- use super::secs_to_frame;
1539+ use super::{Edge, Lane, PlaybackSession, secs_to_frame};
1540+ use std::path::PathBuf;
1541+
1542+ fn asset(name: &str) -> PathBuf {
1543+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1544+ .join("../../assets")
1545+ .join(name)
1546+ }
1547+
1548+ /// The seam between the two lists a source index reaches: dropping a file
1549+ /// from the library shortens `sources`, and `counts` -- the frame length
1550+ /// per source, which is what a trim is walled by -- has to lose the same
1551+ /// entry. Left behind, the dead file's length would wall the survivor.
1552+ #[test]
1553+ fn removing_a_source_takes_its_frame_count_with_it() {
1554+ // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale
1555+ // count cannot pass for the right one.
1556+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1557+ session.set_gain(0.0);
1558+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
1559+ let (long, short) = (session.counts[0], session.counts[1]);
1560+ assert!(long > short, "{long} vs {short}");
1561+
1562+ // Clear source 0's take, then take the file itself out: av2's clip is
1563+ // the only one left and it is source 0 now.
1564+ assert!(session.delete_clip(Lane::V1, 0));
1565+ session
1566+ .remove_source(&asset("test_av.mp4"), 0)
1567+ .expect("nothing plays it any more");
1568+ assert_eq!(session.counts, vec![short], "the dead length went with it");
1569+ assert_eq!(session.sources().len(), session.counts.len());
1570+
1571+ // The wall is the surviving file's own length, not the gone one's: a
1572+ // whole-file clip cannot be dragged out any further at all.
1573+ let clip = session.lane_clips(Lane::V1)[0];
1574+ assert_eq!(clip.len(), short, "av2's take, whole");
1575+ assert_eq!(
1576+ session.trim_room(Lane::V1, 0, Edge::End),
1577+ Some((clip.start + 1, clip.end()))
1578+ );
1579+ assert!(
1580+ !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30),
1581+ "past the file's last frame is refused, by ITS length"
1582+ );
1583+
1584+ // ...and the next import still lines the two lists up, which is the
1585+ // alignment `note_frames` asserts on.
1586+ session
1587+ .import(&asset("test_av.mp4"))
1588+ .expect("it may come back");
1589+ assert_eq!(session.counts, vec![short, long]);
1590+ assert_eq!(session.sources().len(), session.counts.len());
1591+ }
13221592
13231593 #[test]
13241594 fn boundary_seconds_round_trip_to_their_own_frame() {
crates/engine/src/project.rsmodified+613 -33
@@ -212,6 +212,17 @@ impl LaneData {
212212 }
213213 }
214214
215+/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
216+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
217+pub enum Edge {
218+ /// Its first timeline frame; moving it changes where in the source the clip
219+ /// starts reading, so the picture behind the edge slides with it.
220+ Start,
221+ /// One past its last timeline frame; moving it only says how much of the
222+ /// source to keep.
223+ End,
224+}
225+
215226 /// What a lane holds over one stretch of the timeline: either a placed clip or
216227 /// a gap. Returned already trimmed to the position it was asked about, so a
217228 /// caller can hand `len` straight to a decoder (or to a black-frame generator).
@@ -299,10 +310,16 @@ impl Project {
299310 /// [`Project::undo`] is `false` until the first edit of the new session.
300311 /// This is the one door untrusted parts come in through, so every invariant
301312 /// every other constructor keeps is checked here, by name and in release:
302- /// every lane empty, an empty clip, a clip naming a source (or an equalizer,
313+ /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
303314 /// or a colour) that is not there, a clip whose end overflows, a lane that is
304315 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
305316 /// below.
317+ ///
318+ /// A project whose lanes are all *empty* is not among them: an emptied
319+ /// timeline is a project like any other -- it plays black and silent, it
320+ /// saves, and it loads back. What a project cannot be is laneless, because
321+ /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
322+ /// handle indexes into.
306323 pub fn from_parts(
307324 sources: Vec<Source>,
308325 lanes: Vec<(LaneKind, Vec<Clip>)>,
@@ -315,8 +332,8 @@ impl Project {
315332 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
316333 return Err(format!("color {bad} holds a value that is not a finite number").into());
317334 }
318- if lanes.iter().all(|(_, clips)| clips.is_empty()) {
319- return Err("every lane is empty: that is not a project".into());
335+ if lanes.is_empty() {
336+ return Err("no lanes at all: that is not a project".into());
320337 }
321338 let lanes: Vec<LaneData> = lanes
322339 .into_iter()
@@ -421,9 +438,8 @@ impl Project {
421438 /// that could not be taken back would be the one edit with no way out.
422439 /// Nothing plays differently until something is placed on it.
423440 ///
424- /// The new lane being empty is fine even though [`Project::from_parts`]
425- /// refuses an all-empty project: the lanes that were there still hold the
426- /// timeline, and "no lane holds anything" is what that door refuses.
441+ /// An empty lane is a lane like any other -- so is a whole project of them
442+ /// ([`Project::from_parts`]); nothing plays until something is placed.
427443 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
428444 self.snapshot();
429445 self.lanes.push(LaneData {
@@ -579,6 +595,11 @@ impl Project {
579595 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
580596 /// and this is the one moment they can go -- the indexes that survive it are
581597 /// only the ones a clip names.
598+ ///
599+ /// One exception, and it is the emptied timeline's: a project no clip plays
600+ /// from still keeps source 0. It is the file a session is scaffolded from --
601+ /// its frame rate is the timeline's and is written nowhere else -- so a save
602+ /// that pruned it would write a project that cannot be loaded back at all.
582603 pub fn without_orphan_sources(&self) -> Parts {
583604 let mut moved = vec![None; self.sources.len()];
584605 let mut sources = Vec::new();
@@ -620,6 +641,9 @@ impl Project {
620641 });
621642 }
622643 }
644+ if sources.is_empty() {
645+ sources.extend(self.sources.first().cloned());
646+ }
623647 (
624648 sources,
625649 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
@@ -687,6 +711,24 @@ impl Project {
687711 /// (and no history) for an index that is not there or a value that is not
688712 /// finite, and equal settings share a table entry.
689713 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
714+ self.write_color(lane, idx, params, true)
715+ }
716+
717+ /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
718+ /// one pointer drag, whose first write (a plain `set_color`) already took the
719+ /// snapshot the gesture rolls back to. A drag across a slider is one undo,
720+ /// not one per pixel -- and undoing it lands where the hand picked it up.
721+ pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
722+ self.write_color(lane, idx, params, false)
723+ }
724+
725+ fn write_color(
726+ &mut self,
727+ lane: Lane,
728+ idx: usize,
729+ params: Option<ColorParams>,
730+ snapshot: bool,
731+ ) -> bool {
690732 if idx >= self.lane(lane).len() {
691733 return false;
692734 }
@@ -709,7 +751,9 @@ impl Project {
709751 })
710752 }
711753 };
712- self.snapshot();
754+ if snapshot {
755+ self.snapshot();
756+ }
713757 self.lane_mut(lane).expect("checked above")[idx].color = slot;
714758 true
715759 }
@@ -1012,6 +1056,115 @@ impl Project {
10121056 true
10131057 }
10141058
1059+ /// Take the clip at `idx` of `lane` out of its group: every clip carrying
1060+ /// its id -- on however many lanes -- is handed an id of its own, so from
1061+ /// here on each half moves, trims and is deleted alone. The music video
1062+ /// whose sound is to be cut against its picture starts here.
1063+ ///
1064+ /// An id of its own rather than none at all: a half no other lane is grouped
1065+ /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
1066+ /// (see [`links_are_consistent`]), and it is what a front-end already draws
1067+ /// as detached. `None` would instead say "was never part of a take", which
1068+ /// is what a one-lane [`place`](Project::place) means.
1069+ ///
1070+ /// Metadata only, like a [`split`](Project::split): no mapping changes, so
1071+ /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
1072+ /// the group back. Refused (`false`, nothing changed) for an index that is
1073+ /// not there, a clip in no group at all, and one whose group has no other
1074+ /// half -- that one is already detached, and a refusal must not cost an undo
1075+ /// step.
1076+ pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
1077+ let Some(id) = self.lane(lane).get(idx).and_then(|c| c.link) else {
1078+ return false;
1079+ };
1080+ let members = self
1081+ .lanes
1082+ .iter()
1083+ .flat_map(|l| &l.clips)
1084+ .filter(|c| c.link == Some(id))
1085+ .count();
1086+ if members < 2 {
1087+ return false;
1088+ }
1089+ self.snapshot();
1090+ // Drawn before the walk: `new_link` takes the whole project, and the
1091+ // walk holds the lanes.
1092+ let mut fresh = (0..members).map(|_| self.new_link()).collect::<Vec<_>>();
1093+ for data in &mut self.lanes {
1094+ for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
1095+ c.link = fresh.pop();
1096+ }
1097+ }
1098+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
1099+ true
1100+ }
1101+
1102+ /// Put two clips on two lanes into one group, so what moves one moves the
1103+ /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
1104+ /// how a picture is regrouped with sound it was never opened with. Whatever
1105+ /// either of them was grouped with comes along: those clips cover this same
1106+ /// span already, so the result is one group and not two overlapping ones.
1107+ ///
1108+ /// Same frames or nothing: a group id names **one span** on however many
1109+ /// lanes ([`links_are_consistent`] refuses to load anything else), so two
1110+ /// clips that do not cover the same frames cannot be one take, and the
1111+ /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
1112+ /// run on `V1` and `V2` at once, and picture-with-sound is the case people
1113+ /// mean, not the rule.
1114+ ///
1115+ /// Metadata only, one snapshot. The error says what is wrong, because
1116+ /// `false` would not: a bad index, one lane twice (a group is at most one
1117+ /// clip per lane), spans that disagree, and a pair that is already one take
1118+ /// -- nothing changes, and none of them costs an undo step.
1119+ pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
1120+ if a == b {
1121+ return Err(format!(
1122+ "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
1123+ a.label()
1124+ )
1125+ .into());
1126+ }
1127+ let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
1128+ p.lane(lane)
1129+ .get(idx)
1130+ .copied()
1131+ .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
1132+ };
1133+ let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
1134+ if (x.start, x.end()) != (y.start, y.end()) {
1135+ return Err(format!(
1136+ "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
1137+ a.label(),
1138+ x.start,
1139+ x.end(),
1140+ b.label(),
1141+ y.start,
1142+ y.end()
1143+ )
1144+ .into());
1145+ }
1146+ if x.link.is_some() && x.link == y.link {
1147+ return Err("those two are one take already".into());
1148+ }
1149+ self.snapshot();
1150+ let id = self.new_link();
1151+ // Every clip either of them was grouped with, by the same rule: all of
1152+ // them cover this span, so one id over the lot stays consistent.
1153+ let old = [x.link, y.link];
1154+ for data in &mut self.lanes {
1155+ for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
1156+ if old.contains(&c.link) {
1157+ c.link = Some(id);
1158+ }
1159+ }
1160+ }
1161+ // And the two themselves, which a `place` may have left in no group.
1162+ self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
1163+ self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
1164+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
1165+ Ok(())
1166+ }
1167+
10151168 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
10161169 /// lands on and leaving every other clip exactly where it is -- the
10171170 /// per-lane paste. Anything already there is trimmed away (and split in two
@@ -1085,6 +1238,145 @@ impl Project {
10851238 true
10861239 }
10871240
1241+ /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
1242+ /// the drag on a clip's end that makes it play more or less of its source.
1243+ /// The rest of the lane stays exactly where it is (nothing ripples), so what
1244+ /// a shortened clip leaves behind is a gap and what a lengthened one takes
1245+ /// is room that was already empty. One snapshot, so a whole drag is one
1246+ /// [`Project::undo`] -- commit once, at the release, rather than per pointer
1247+ /// sample. Changes the timeline->source mapping: the caller must reseek.
1248+ ///
1249+ /// [`Edge::Start`] moves the in-point with it: the frames that stay play
1250+ /// exactly what they played before, which is what makes this a trim and not
1251+ /// a slip.
1252+ ///
1253+ /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
1254+ /// legal means "as far as it goes", and stopping the box there is the
1255+ /// affordance. The walls are: one frame of clip always survives, an edge
1256+ /// never crosses the neighbouring clip on its own lane, an in-point never
1257+ /// walks back past the source's first frame, and an out-point never runs
1258+ /// past `source_frames[clip.source]` -- the caller's table of how long each
1259+ /// source actually is ([`Project`] does not know, and a clip ending past its
1260+ /// file's last frame is a save that will not open again; see
1261+ /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
1262+ /// there may not grow at all.
1263+ ///
1264+ /// Linked clips trim *together*, to one clamped edge: a link is one span on
1265+ /// however many lanes ([`links_are_consistent`]), so a picture trimmed away
1266+ /// from its sound would be a group no save could load. The room is therefore
1267+ /// what every member of the group has -- the tightest wall wins.
1268+ ///
1269+ /// `false`, changing nothing and costing no undo step, for an index that is
1270+ /// not there and for an edge that is already where it was asked to go.
1271+ pub fn trim(
1272+ &mut self,
1273+ lane: Lane,
1274+ idx: usize,
1275+ edge: Edge,
1276+ to: u32,
1277+ source_frames: &[u32],
1278+ ) -> bool {
1279+ let (Some((lo, hi)), Some(clip)) = (
1280+ self.trim_room(lane, idx, edge, source_frames),
1281+ self.lane(lane).get(idx).copied(),
1282+ ) else {
1283+ return false;
1284+ };
1285+ let to = to.clamp(lo, hi);
1286+ let at = match edge {
1287+ Edge::Start => clip.start,
1288+ Edge::End => clip.end(),
1289+ };
1290+ if to == at {
1291+ return false;
1292+ }
1293+ self.snapshot();
1294+ for (l, i) in self.group_of(lane, idx).expect("checked above") {
1295+ let c = &mut self.lanes[l].clips[i];
1296+ match edge {
1297+ Edge::Start => {
1298+ // Non-negative by `lo`, which is what keeps the in-point on
1299+ // the source.
1300+ c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32;
1301+ c.start = to;
1302+ }
1303+ Edge::End => c.out_frame = c.in_frame + (to - c.start),
1304+ }
1305+ debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1306+ }
1307+ true
1308+ }
1309+
1310+ /// How far that edge may travel, `(first, last)` timeline frame inclusive --
1311+ /// the walls [`trim`](Project::trim) clamps to, without moving anything.
1312+ /// What a front-end drawing the box *during* a drag asks, so the live width
1313+ /// is the width the release will commit and an edge stops under the pointer
1314+ /// rather than snapping back. `None` for an index that is not there.
1315+ pub fn trim_room(
1316+ &self,
1317+ lane: Lane,
1318+ idx: usize,
1319+ edge: Edge,
1320+ source_frames: &[u32],
1321+ ) -> Option<(u32, u32)> {
1322+ let (mut lo, mut hi) = (u32::MIN, u32::MAX);
1323+ for (l, i) in self.group_of(lane, idx)? {
1324+ let clips = &self.lanes[l].clips;
1325+ let c = clips[i];
1326+ let (member_lo, member_hi) = match edge {
1327+ Edge::Start => (
1328+ // Back to the source's own first frame, and never over the
1329+ // clip in front of it. Saturating because a clip may hold
1330+ // *more* head than the timeline has room for -- a ripple
1331+ // delete slides a clip back to frame 0 with its in-point
1332+ // wherever the cut left it -- and frame 0 is the other wall.
1333+ c.start
1334+ .saturating_sub(c.in_frame)
1335+ .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1336+ c.end() - 1,
1337+ ),
1338+ Edge::End => (
1339+ c.start + 1,
1340+ // Out to whatever is left of the source, and never over the
1341+ // clip behind it.
1342+ c.start
1343+ .saturating_add(
1344+ source_frames
1345+ .get(c.source)
1346+ .copied()
1347+ .unwrap_or(c.out_frame)
1348+ .saturating_sub(c.in_frame),
1349+ )
1350+ .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1351+ ),
1352+ };
1353+ lo = lo.max(member_lo);
1354+ hi = hi.min(member_hi);
1355+ }
1356+ // `hi.max(lo)`: for a clip the invariants hold for, the range always
1357+ // contains the edge's own place, and a caller's wrong `source_frames`
1358+ // must not become an empty range (or a panicking `clamp`) here.
1359+ Some((lo, hi.max(lo)))
1360+ }
1361+
1362+ /// The clips that move as one with the clip at `idx` of `lane` -- itself and
1363+ /// whatever carries its link on the other lanes -- as `(lane storage index,
1364+ /// clip index)` pairs. `None` for an index that is not there.
1365+ fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
1366+ let clip = *self.lane(lane).get(idx)?;
1367+ Some(match clip.link {
1368+ Some(link) => self
1369+ .lanes
1370+ .iter()
1371+ .enumerate()
1372+ .filter_map(|(l, data)| {
1373+ Some((l, data.clips.iter().position(|c| c.link == Some(link))?))
1374+ })
1375+ .collect(),
1376+ None => vec![(self.index(lane).expect("the clip was found on it"), idx)],
1377+ })
1378+ }
1379+
10881380 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
10891381 /// new group, pushing everything from there on later by its length in
10901382 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
@@ -1162,13 +1454,12 @@ impl Project {
11621454 }
11631455
11641456 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
1165- /// silence, and nothing else moves. Refused for an out-of-range index (which
1166- /// a lane that is not there always is) and for the lift that would leave
1167- /// *every* lane empty -- an empty timeline is the front-end's state, not a
1168- /// project's (see the never-empty invariant).
1457+ /// silence, and nothing else moves. Refused only for an out-of-range index
1458+ /// (which a lane that is not there always is) -- lifting the last placement
1459+ /// there is leaves an *empty* timeline, which is a state the project holds
1460+ /// like any other and an undo brings back.
11691461 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
1170- let placed: usize = self.lanes.iter().map(|l| l.clips.len()).sum();
1171- if idx >= self.lane(lane).len() || placed == 1 {
1462+ if idx >= self.lane(lane).len() {
11721463 return false;
11731464 }
11741465 self.snapshot();
@@ -1178,23 +1469,17 @@ impl Project {
11781469
11791470 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
11801471 /// the hole: everything after slides back by `len`. The rippling delete --
1181- /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an
1182- /// empty range and when it would leave every lane empty.
1472+ /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
1473+ /// empty range; a delete that leaves nothing behind empties the timeline,
1474+ /// which is a state like any other and one undo away.
11831475 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
11841476 if len == 0 {
11851477 return false;
11861478 }
1187- let survivors: usize = self
1188- .lanes
1189- .iter()
1190- .map(|l| {
1191- l.clips
1192- .iter()
1193- .filter(|c| c.start < at || c.end() > at + len)
1194- .count()
1195- })
1196- .sum();
1197- if survivors == 0 {
1479+ // Nothing reaches past `at`: there is nothing to cut and nothing to
1480+ // slide back, and a delete that changes nothing must not cost an undo
1481+ // step (see [`snapshot`](Project::snapshot)).
1482+ if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| c.end() > at) {
11981483 return false;
11991484 }
12001485 self.snapshot();
@@ -1719,6 +2004,103 @@ mod tests {
17192004 );
17202005 }
17212006
2007+ /// The music video's own path: the take comes apart into halves that carry
2008+ /// ids of their own, one undo puts it back, and two clips over the same
2009+ /// frames become one take again by hand.
2010+ #[test]
2011+ fn a_take_comes_apart_and_goes_back_together() {
2012+ let mut p = Project::single(FILE, 9);
2013+ let one = p.clips()[0].link.expect("a fresh project is one take");
2014+ assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
2015+
2016+ // A third lane in the same group -- and the merge case with it: a
2017+ // placement is in no group, and grouping it in leaves *one* group.
2018+ let v2 = p.add_lane(LaneKind::Video);
2019+ assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
2020+ assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
2021+ p.group(Lane::V1, 0, v2, 0)
2022+ .expect("the same frames, one lane over");
2023+ let id = p.clips()[0].link.expect("still a group");
2024+ assert!(
2025+ p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
2026+ "one id over the three, not two groups sharing a span"
2027+ );
2028+ links_are_consistent(&p.lanes).expect("one id, one span");
2029+
2030+ // Detached by the sound: every half of the group, not only the two.
2031+ assert!(p.ungroup(Lane::A1, 0));
2032+ let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
2033+ assert!(
2034+ ids.iter().all(Option::is_some),
2035+ "a half keeps an id of its own"
2036+ );
2037+ assert!(
2038+ ids.iter()
2039+ .enumerate()
2040+ .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
2041+ "and no two halves are the same group any more: {ids:?}"
2042+ );
2043+ links_are_consistent(&p.lanes).expect("a lone id is legal");
2044+
2045+ // One snapshot for the whole detach.
2046+ assert!(p.undo());
2047+ assert!(
2048+ p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
2049+ "one undo puts the whole group back"
2050+ );
2051+
2052+ // And back together by hand: the two the pointer named, and only them.
2053+ assert!(p.ungroup(Lane::V1, 0));
2054+ p.group(Lane::V1, 0, Lane::A1, 0)
2055+ .expect("both cover [0, 9)");
2056+ assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
2057+ assert_ne!(
2058+ p.lane(v2)[0].link,
2059+ p.lane(Lane::V1)[0].link,
2060+ "the third half stayed detached"
2061+ );
2062+ links_are_consistent(&p.lanes).expect("one id, one span");
2063+ }
2064+
2065+ /// What a group may not be, and what a detach has nothing to take apart --
2066+ /// none of which may cost an undo step.
2067+ #[test]
2068+ fn a_group_is_one_span_and_one_clip_per_lane() {
2069+ let mut p = three();
2070+ let before = shape(&p);
2071+ let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
2072+
2073+ assert!(
2074+ why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
2075+ "two clips of one lane are never one take"
2076+ );
2077+ assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
2078+ let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
2079+ assert!(
2080+ spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
2081+ "{spans}"
2082+ );
2083+ assert!(
2084+ spans.contains("trim them to matching bounds first"),
2085+ "{spans}"
2086+ );
2087+ assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
2088+
2089+ // A half nothing else is grouped with is already detached, a placement
2090+ // is in no group at all, and an index that is not there has nothing to
2091+ // detach either.
2092+ assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
2093+ assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
2094+ assert!(p.lift(Lane::A1, 0));
2095+ assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
2096+ assert!(!p.ungroup(Lane::V1, 9), "no clip there");
2097+
2098+ // Two undos, one per edit: not one of the refusals pushed a snapshot.
2099+ assert!(p.undo());
2100+ assert!(p.undo());
2101+ assert_eq!(shape(&p), before);
2102+ }
2103+
17222104 #[test]
17232105 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
17242106 let mut p = three();
@@ -1985,7 +2367,11 @@ mod tests {
19852367
19862368 assert!(!p.delete(2), "index past the end");
19872369 assert!(p.delete(1));
1988- assert!(!p.delete(0), "the last remaining clip stays");
2370+ assert!(p.delete(0), "and the last remaining clip goes too");
2371+ assert_eq!(p.clips().len(), 0);
2372+ assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
2373+ assert!(!p.delete(0), "there is nothing left to delete");
2374+ assert!(p.undo(), "one gesture, one undo");
19892375 assert_eq!(p.clips().len(), 1);
19902376 }
19912377
@@ -2036,13 +2422,28 @@ mod tests {
20362422 }
20372423 }
20382424
2425+ /// The timeline is emptiable: the last placement comes off like any other,
2426+ /// the project holds "nothing on any lane" as a state, and one undo per
2427+ /// gesture brings it back.
20392428 #[test]
2040- fn the_last_clip_of_the_last_lane_cannot_be_lifted() {
2429+ fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
20412430 let mut p = Project::single(FILE, 9);
20422431 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
2043- assert!(!p.lift(Lane::V1, 0), "an empty one is not");
2432+ assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
2433+ assert_eq!(p.timeline_frames(), 0);
2434+ assert_eq!(p.composite_span_at(0), None, "nothing to show");
2435+ assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
20442436 assert!(!p.lift(Lane::A1, 0), "index past the end");
2045- assert_eq!(p.timeline_frames(), 9);
2437+ assert!(p.undo(), "and the last lift comes back");
2438+ assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
2439+ // A saved-and-loaded empty timeline is a project like any other, and it
2440+ // still names the file its frame rate came from.
2441+ assert!(p.lift(Lane::V1, 0));
2442+ let (sources, lanes, eq, color) = p.without_orphan_sources();
2443+ assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
2444+ let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads");
2445+ assert_eq!(back.timeline_frames(), 0);
2446+ assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
20462447 }
20472448
20482449 /// What a keyboard selection walks: one answer per lane, gaps included --
@@ -2147,6 +2548,139 @@ mod tests {
21472548 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
21482549 }
21492550
2551+ /// How long `FILE` is, which is what a trim's tail is allowed to reach:
2552+ /// [`three`] cuts up all nine of its frames.
2553+ const SRC: &[u32] = &[9];
2554+
2555+ /// The drag on a clip's tail: it plays less (or more) of its source, nothing
2556+ /// else on the lane moves, and every wall stops the edge rather than
2557+ /// refusing the gesture.
2558+ #[test]
2559+ fn trimming_the_tail_stops_at_every_wall() {
2560+ let mut p = three();
2561+
2562+ // Pulled in: a gap opens behind it and the clip after it stays put.
2563+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2564+ assert_eq!(
2565+ shape(&p)[0],
2566+ vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
2567+ );
2568+ assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
2569+ assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
2570+
2571+ // ...and back out, no further than the clip behind it.
2572+ assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
2573+ assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour");
2574+ assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall");
2575+
2576+ // One frame of clip always survives, however far back the pointer went.
2577+ assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
2578+ assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
2579+
2580+ // The last clip has no neighbour, so what stops it is the file: nine
2581+ // frames is nine frames.
2582+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
2583+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2584+ assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
2585+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
2586+ // A source nobody told us the length of may not grow at all -- an
2587+ // out-point past the end of a file is a save that will not open again.
2588+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
2589+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
2590+ }
2591+
2592+ /// The head pulled in takes the in-point with it -- what stays plays what it
2593+ /// always played -- and stops at the source's own first frame.
2594+ #[test]
2595+ fn trimming_the_head_moves_the_in_point() {
2596+ let mut p = three();
2597+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2598+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front");
2599+ assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
2600+ assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
2601+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
2602+ assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
2603+ // One frame survives here too.
2604+ assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
2605+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
2606+
2607+ // A clip that does not begin at its source's first frame: its head goes
2608+ // back to source frame 0 and not one frame further.
2609+ let mut p = Project::single(FILE, 9);
2610+ assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
2611+ assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
2612+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
2613+ assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
2614+ }
2615+
2616+ /// A clip whose in-point is *past* its own start -- what a ripple delete
2617+ /// leaves, the piece in front of it gone and this one slid back to frame 0
2618+ /// carrying the in-point the cut gave it. Its head has more source behind it
2619+ /// than the timeline has room for, and the timeline's own first frame is the
2620+ /// wall: asking is not an overflow, and the answer is 0.
2621+ #[test]
2622+ fn a_ripple_closed_clip_can_still_be_head_trimmed() {
2623+ let mut p = Project::single(FILE, 9);
2624+ assert!(p.split(5));
2625+ assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
2626+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
2627+
2628+ assert_eq!(
2629+ p.trim_room(Lane::V1, 0, Edge::Start, SRC),
2630+ Some((0, 3)),
2631+ "back to frame 0 at most, and one frame of clip always survives"
2632+ );
2633+ assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
2634+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2635+ assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed");
2636+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
2637+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
2638+ }
2639+
2640+ /// Linked halves trim as one: a link is one span on however many lanes, so
2641+ /// the sound follows the picture's edge -- and the tightest wall of the two
2642+ /// is what stops both.
2643+ #[test]
2644+ fn linked_halves_trim_together() {
2645+ let mut p = three();
2646+ let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
2647+ assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
2648+
2649+ assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
2650+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
2651+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
2652+ assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it");
2653+ assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
2654+ links_are_consistent(&p.lanes).expect("one id per lane, one span");
2655+
2656+ // Something in the way on the *audio* lane stops the picture's tail as
2657+ // well: the group can only go as far as its tightest member.
2658+ assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
2659+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2660+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
2661+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
2662+ links_are_consistent(&p.lanes).expect("still one span");
2663+ }
2664+
2665+ /// A whole drag is one undo step -- the front-end commits once, at the
2666+ /// release -- and an edge asked to stay where it is costs none at all.
2667+ #[test]
2668+ fn a_trim_is_one_undo_step() {
2669+ let mut p = three();
2670+ let before = shape(&p);
2671+ let history = p.history.len();
2672+
2673+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2674+ assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
2675+ assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
2676+ assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
2677+ assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
2678+ assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
2679+
2680+ assert!(p.undo());
2681+ assert_eq!(shape(&p), before, "both halves back, in one step");
2682+ }
2683+
21502684 /// A moved half stays in its group: a link names a span, not a lane, so the
21512685 /// picture on `V2` is still the same take as the sound under it on `A1`.
21522686 #[test]
@@ -2175,7 +2709,16 @@ mod tests {
21752709 assert_eq!(shape(&p)[1], shape(&p)[0]);
21762710 assert_eq!(p.timeline_frames(), 5);
21772711 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
2178- assert!(!p.ripple_delete(0, 100), "and one that empties every lane");
2712+ assert!(p.undo());
2713+ assert_eq!(shape(&p), shape(&three()));
2714+ // One that takes everything is a delete like any other: the timeline
2715+ // empties, and the undo it cost brings it back whole.
2716+ assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
2717+ assert_eq!(p.timeline_frames(), 0);
2718+ assert!(
2719+ !p.ripple_delete(0, 100),
2720+ "and a delete with nothing left to take is not an undo step"
2721+ );
21792722 assert!(p.undo());
21802723 assert_eq!(shape(&p), shape(&three()));
21812724 }
@@ -2649,6 +3192,42 @@ mod tests {
26493192 );
26503193 }
26513194
3195+ /// A slider drag is one gesture: the press snapshots, every sample after it
3196+ /// only regrades, and the single undo lands on what the clip was *before*
3197+ /// the hand touched it -- not one step back down the drag.
3198+ #[test]
3199+ fn a_whole_colour_drag_undoes_in_one_step() {
3200+ let mut p = three();
3201+ assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
3202+ for n in 2..=8 {
3203+ assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
3204+ }
3205+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
3206+ assert!(p.undo());
3207+ assert!(
3208+ p.color_of(Lane::V1, 0).is_none(),
3209+ "one undo is the whole gesture, back to ungraded"
3210+ );
3211+
3212+ // The live write refuses what the snapshotting one refuses, and a
3213+ // refusal still costs no history either way.
3214+ assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
3215+ assert!(!p.set_color_live(
3216+ Lane::V1,
3217+ 0,
3218+ Some(ColorParams {
3219+ contrast: f32::NAN,
3220+ ..grade_at(1)
3221+ })
3222+ ));
3223+ assert!(p.undo());
3224+ assert_eq!(
3225+ p.lane(Lane::V1).len(),
3226+ 2,
3227+ "the next step back is the split before the drag: no sample pushed one"
3228+ );
3229+ }
3230+
26523231 /// The colour table is append-only within a session, exactly as the eq one
26533232 /// is -- and a save is where an undone grade goes.
26543233 #[test]
@@ -2707,7 +3286,8 @@ mod tests {
27073286 assert!(p.split(4), "...and is editable from there");
27083287 assert!(p.undo());
27093288
2710- // A lane may be empty; every lane may not, and neither may no lane.
3289+ // A lane may be empty, and so may every lane -- an emptied timeline is a
3290+ // project. No lane at all is not one: there would be nothing to place on.
27113291 assert!(
27123292 Project::from_parts(
27133293 sources.clone(),
@@ -2724,7 +3304,7 @@ mod tests {
27243304 Vec::new(),
27253305 Vec::new(),
27263306 )
2727- .is_err()
3307+ .is_ok()
27283308 );
27293309 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
27303310 let bad: [Vec<Clip>; 5] = [
crates/engine/tests/audio_files.rsmodified+174 -7
@@ -1,7 +1,8 @@
11 //! Standalone audio files as sources: every container we claim to read decodes
2-//! to the same tone, a song joins a timeline of video on the audio lane, and
3-//! the three things it cannot do -- start a timeline, play on the video lane,
4-//! be copied into an mp4 -- are refusals that say so.
2+//! to the same tone, a song joins a timeline of video on the audio lane, a song
3+//! *is* a timeline on its own (canvas scaffolded, picture black, sound exported)
4+//! and the two things it cannot do -- play on the video lane, be copied into an
5+//! mp4 -- are refusals that say so.
56 //!
67 //! ```text
78 //! cargo test -p engine --release --test audio_files
@@ -9,6 +10,7 @@
910
1011 use std::path::{Path, PathBuf};
1112
13+use engine::export::{ExportSettings, Format};
1214 use engine::project::Lane;
1315 use engine::{AudioSession, Clip, PlaybackSession};
1416
@@ -154,13 +156,178 @@ fn a_rate_the_device_cannot_mix_is_refused_at_the_door() {
154156 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
155157 }
156158
159+/// A song *is* a timeline: it scaffolds the canvas a video would have defined,
160+/// its own length is the timeline's, the video lane starts empty and the picture
161+/// is the black of an uncovered canvas.
157162 #[test]
158-fn a_song_cannot_be_a_timeline_of_its_own() {
159- let e = refusal(PlaybackSession::open(asset("test_tone.mp3")));
163+fn a_song_is_a_timeline_of_its_own() {
164+ let mut session = open(asset("test_tone.mp3"));
165+ let meta = *session.meta();
166+ assert_eq!(
167+ (meta.width, meta.height),
168+ (1920, 1080),
169+ "the default canvas"
170+ );
171+ assert_eq!(meta.frame_rate, 30.0);
172+ // 3 s of tone at 30 fps, rounded up: the only frame count a file with no
173+ // picture has, and it is the timeline's length too.
174+ assert_eq!(meta.frame_count, 90);
175+ assert!((session.timeline_duration() - 3.0).abs() < 0.05);
176+ assert!(!session.is_empty(), "a song is not an empty timeline");
160177 assert!(
161- e.ends_with("has no picture: open a video first, then import it onto the audio lane"),
162- "{e}"
178+ session.lane_clips(Lane::V1).is_empty(),
179+ "no picture anywhere"
180+ );
181+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
182+ let clip = session.lane_clips(Lane::A1)[0];
183+ assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90));
184+ assert_eq!(session.sources().len(), 1);
185+
186+ // And it shows black rather than nothing: the whole timeline is a gap, so
187+ // the black worker feeds it at the canvas size.
188+ session.seek(1.0);
189+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
190+ let frame = loop {
191+ if let Some(frame) = session.try_frame() {
192+ break frame;
193+ }
194+ assert!(std::time::Instant::now() < deadline, "no frame at 1 s");
195+ std::thread::sleep(std::time::Duration::from_millis(10));
196+ };
197+ assert_eq!((frame.width, frame.height), (1920, 1080));
198+ assert_eq!(frame.index, 30, "the gap is indexed in timeline frames");
199+ assert!(
200+ frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]),
201+ "the picture over a song is black"
202+ );
203+}
204+
205+/// A file that is neither a picture nor a sound this engine can play is not a
206+/// timeline: refused at the door, in the words of whatever refused it.
207+#[test]
208+fn a_file_with_no_picture_and_no_sound_is_still_refused() {
209+ let dir = std::env::temp_dir().join(format!("ve_audio_bad_{}", std::process::id()));
210+ let _ = std::fs::remove_dir_all(&dir);
211+ std::fs::create_dir_all(&dir).expect("scratch dir");
212+ let fake = dir.join("not_really.mp3");
213+ std::fs::write(&fake, b"this is not an mp3").expect("write");
214+ let e = refusal(PlaybackSession::open(&fake));
215+ assert!(e.starts_with(&fake.display().to_string()), "{e}");
216+ let _ = std::fs::remove_dir_all(&dir);
217+}
218+
219+/// The whole audio-only round trip a user makes: open a song, place a second
220+/// one, save, reopen, export the sound -- and be told, by name, that the one
221+/// format that needs a picture cannot have one.
222+#[test]
223+fn an_audio_only_project_saves_reloads_and_exports_its_sound() {
224+ let dir = std::env::temp_dir().join(format!("ve_audio_only_{}", std::process::id()));
225+ let _ = std::fs::remove_dir_all(&dir);
226+ std::fs::create_dir_all(&dir).expect("scratch dir");
227+
228+ let mut session = open(asset("test_tone.mp3"));
229+ // A second song joins it, the same way one joins a timeline of video: no
230+ // picture is needed for the import to have something to hold it to.
231+ session
232+ .import(&asset("test_tone.flac"))
233+ .expect("a song joins a song");
234+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
235+ assert!(session.lane_clips(Lane::V1).is_empty());
236+ assert!((session.timeline_duration() - 6.0).abs() < 0.1);
237+
238+ // mp4 is refused by name, before a byte is written; WAV writes the sound.
239+ let mp4 = dir.join("song.mp4");
240+ let e = wait(&session.export_to_with(
241+ &mp4,
242+ &ExportSettings {
243+ format: Format::Mp4,
244+ ..ExportSettings::default()
245+ },
246+ ))
247+ .expect_err("an audio-only timeline is not an mp4");
248+ assert_eq!(
249+ e.to_string(),
250+ "the timeline has no picture: an mp4 would be black. \
251+ Export WAV or FLAC, which are the sound itself"
252+ );
253+ assert!(!mp4.exists(), "the refusal wrote a file anyway");
254+
255+ let wav = dir.join("song.wav");
256+ wait(&session.export_to_with(
257+ &wav,
258+ &ExportSettings {
259+ format: Format::Wav,
260+ ..ExportSettings::default()
261+ },
262+ ))
263+ .expect("wav export of an audio-only timeline");
264+ let (rate, channels, samples) = decode(&wav);
265+ assert_eq!((rate, channels), (44100, 2));
266+ let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
267+ assert!((secs - 6.0).abs() < 0.1, "{secs:.3} s of exported audio");
268+ let peak = samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs()));
269+ assert!(peak > 0.05, "the export is silent: peak {peak}");
270+
271+ // Saved and reopened: an .edith naming nothing but songs loads.
272+ let project = dir.join("songs.edith");
273+ let before = (
274+ session.lane_spans_by_source(Lane::A1),
275+ session.sources().to_vec(),
276+ session.timeline_duration(),
277+ );
278+ session.save_project(&project).expect("save");
279+ drop(session);
280+ let reloaded = PlaybackSession::open_project(&project).expect("reload an audio-only project");
281+ reloaded.set_gain(0.0);
282+ assert_eq!(
283+ (
284+ reloaded.lane_spans_by_source(Lane::A1),
285+ reloaded.sources().to_vec(),
286+ reloaded.timeline_duration()
287+ ),
288+ before
163289 );
290+ assert_eq!(reloaded.meta().frame_rate, 30.0, "the canvas came back");
291+ assert_eq!(
292+ (reloaded.meta().width, reloaded.meta().height),
293+ (1920, 1080)
294+ );
295+ assert!(reloaded.lane_clips(Lane::V1).is_empty());
296+ drop(reloaded);
297+ let _ = std::fs::remove_dir_all(&dir);
298+}
299+
300+/// The other half of the door: a *video* joining a timeline a song scaffolded.
301+/// It is held to the canvas the song set (H.264, 30 fps), so a matching file
302+/// brings its picture in -- and the timeline stops being audio-only, mp4 export
303+/// included.
304+#[test]
305+fn a_video_joins_a_timeline_a_song_started() {
306+ let mut session = open(asset("test_tone.mp3"));
307+ session
308+ .import(&asset("test_av.mp4"))
309+ .expect("30 fps H.264 matches the audio-only canvas");
310+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");
311+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
312+ // And a file at another rate is refused in the timeline's own words rather
313+ // than silently retiming the song already on the lane.
314+ let e = refusal(session.import(&asset("test_tone_48k.wav")));
315+ assert_eq!(
316+ e,
317+ "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"
318+ );
319+}
320+
321+/// Blocks until the export settles, whichever way it settled.
322+fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
323+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
324+ loop {
325+ if let Some(result) = handle.result() {
326+ return result;
327+ }
328+ assert!(std::time::Instant::now() < deadline, "export never settled");
329+ std::thread::sleep(std::time::Duration::from_millis(20));
330+ }
164331 }
165332
166333 /// The export copies AAC packets and has no encoder, so a timeline carrying an
crates/engine/tests/playback.rsmodified+100 -0
@@ -11,6 +11,7 @@ use std::path::{Path, PathBuf};
1111 use std::thread::sleep;
1212 use std::time::{Duration, Instant};
1313
14+use engine::export::{ExportSettings, Format};
1415 use engine::project::Lane;
1516 use engine::{DecodeSession, Frame, PlaybackSession};
1617
@@ -1122,3 +1123,102 @@ fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
11221123 );
11231124 eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}");
11241125 }
1126+
1127+/// The emptied timeline, end to end: the last clip deletes like any other, what
1128+/// is left plays as black and silence with a duration of zero, it saves and
1129+/// loads back as the project it is, and one undo brings the clip back. Silent
1130+/// fixture, so this runs anywhere.
1131+#[test]
1132+fn an_emptied_timeline_plays_black_saves_loads_and_undoes() {
1133+ let path = asset("test_baseline.mp4");
1134+ let mut session = open(&path);
1135+ let whole = session.timeline_duration();
1136+ assert!(whole > 0.0);
1137+
1138+ // The sole take goes -- picture and sound of it, on every lane at once.
1139+ assert!(
1140+ session.delete_clip(Lane::V1, 0),
1141+ "the last clip deletes like any other"
1142+ );
1143+ assert!(session.is_empty(), "and the timeline is empty");
1144+ assert_eq!(session.timeline_duration(), 0.0);
1145+ assert!(session.clip_spans().is_empty());
1146+ assert_eq!(session.lanes().len(), 2, "the lanes are still there");
1147+
1148+ // It scrubs: every seek lands at zero and shows black rather than the
1149+ // picture of the clip that was deleted.
1150+ for t in [0.0, -1.0, whole, 1e9] {
1151+ session.seek(t);
1152+ assert_eq!(session.now(), 0.0, "seek to {t} on an empty timeline");
1153+ let deadline = Instant::now() + Duration::from_secs(5);
1154+ let mut black = None;
1155+ while black.is_none() && Instant::now() < deadline {
1156+ session.tick();
1157+ black = session.try_frame();
1158+ sleep(Duration::from_millis(4));
1159+ }
1160+ let frame = black.expect("an empty timeline shows one black frame");
1161+ assert_eq!(frame.index, 0);
1162+ assert!(
1163+ frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]),
1164+ "and it is black"
1165+ );
1166+ }
1167+ // It plays: nothing to show, so it is at its end at once, and nothing hangs.
1168+ session.play();
1169+ let mut last_index = None;
1170+ run_for(&mut session, &mut last_index, Duration::from_millis(200));
1171+ assert!(session.is_eos(), "an empty timeline is played out at once");
1172+ session.pause();
1173+
1174+ // Exporting nothing is a refusal in words, not a file of no frames -- and
1175+ // in the *same* words whichever format asked, because the fence sits in
1176+ // `export::start` ahead of the format, not in the mp4 path alone.
1177+ for format in [Format::Mp4, Format::Wav, Format::Flac] {
1178+ let out = std::env::temp_dir().join(format!("ve_nothing_{}", std::process::id()));
1179+ let handle = session.export_to_with(
1180+ &out,
1181+ &ExportSettings {
1182+ format,
1183+ ..ExportSettings::default()
1184+ },
1185+ );
1186+ let deadline = Instant::now() + Duration::from_secs(10);
1187+ let err = loop {
1188+ if let Some(result) = handle.result() {
1189+ break result.expect_err("an empty timeline cannot be exported");
1190+ }
1191+ assert!(Instant::now() < deadline, "{format:?} export never settled");
1192+ sleep(Duration::from_millis(10));
1193+ };
1194+ assert_eq!(
1195+ err.to_string(),
1196+ "the timeline is empty: there is nothing to export",
1197+ "{format:?}"
1198+ );
1199+ assert!(!out.exists(), "{format:?} wrote a file anyway");
1200+ }
1201+
1202+ // It saves and loads back -- still a project, still two lanes, and still
1203+ // naming the file whose frame rate the timeline counts in.
1204+ let dir = std::env::temp_dir().join(format!("ve_empty_{}", std::process::id()));
1205+ let _ = std::fs::remove_dir_all(&dir);
1206+ std::fs::create_dir_all(&dir).expect("scratch dir");
1207+ let project = dir.join("empty.edith");
1208+ session
1209+ .save_project(&project)
1210+ .expect("save an empty timeline");
1211+ let loaded = PlaybackSession::open_project(&project).expect("load it back");
1212+ assert!(loaded.is_empty(), "what came back is the empty timeline");
1213+ assert_eq!(loaded.lanes().len(), 2);
1214+ assert_eq!(loaded.sources().len(), 1, "source 0 is kept, orphan or not");
1215+ assert_eq!(loaded.meta().frame_rate, session.meta().frame_rate);
1216+ drop(loaded);
1217+ let _ = std::fs::remove_dir_all(&dir);
1218+
1219+ // ...and one gesture is one undo: the take comes back whole.
1220+ assert!(session.undo(), "the delete undoes");
1221+ assert!(!session.is_empty());
1222+ assert!((session.timeline_duration() - whole).abs() < 1e-9);
1223+ assert_eq!(session.clip_spans().len(), 1);
1224+}
crates/engine/tests/saveload.rsmodified+38 -0
@@ -100,6 +100,44 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() {
100100 std::fs::remove_dir_all(&dir).expect("cleanup");
101101 }
102102
103+/// Why a trim's tail stops where the file ends: a clip reaching past the last
104+/// frame of its source is a project that will not open again (`open_project`
105+/// refuses it by name). Pulled in on both ends and then dragged out as far as
106+/// the pointer can ask for, the save still comes back as itself.
107+#[test]
108+fn a_trimmed_timeline_saves_and_opens_again() {
109+ use engine::project::Edge;
110+
111+ let dir = scratch("trim");
112+ let media = copy_in(&dir, "test_av.mp4");
113+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
114+ session.set_gain(0.0);
115+ let whole = session.clip_at(0).expect("one clip");
116+
117+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, whole.end() / 2));
118+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 5));
119+ let path = dir.join("trimmed.edith");
120+ session.save_project(&path).expect("save");
121+ let loaded = PlaybackSession::open_project(&path).expect("a trimmed project opens");
122+ assert_eq!(
123+ loaded.clip_at(0).map(|c| (c.start, c.in_frame, c.out_frame)),
124+ Some((5, 5, whole.end() / 2)),
125+ "the trimmed range is what came back"
126+ );
127+
128+ // A hand that keeps pulling: the tail stops at the file's own last frame,
129+ // and the save of *that* opens too.
130+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, u32::MAX));
131+ assert_eq!(
132+ session.clip_at(0).expect("still one clip").out_frame,
133+ whole.out_frame,
134+ "as far as the file goes and not one frame further"
135+ );
136+ session.save_project(&path).expect("save");
137+ PlaybackSession::open_project(&path).expect("and it still opens");
138+ std::fs::remove_dir_all(&dir).expect("cleanup");
139+}
140+
103141 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline
104142 /// with something to lose in every field.
105143 fn edited(dir: &Path) -> PlaybackSession {