forge
Explore
Log in

Don't you dare go Hollow

🔀 merge: origin/main into the choice-list branch

Browse files at this commit

edf0cd92ee3edc5bd6f6874cf3919f9a632892d3Ahmet Kaan GümüşParent: d8cd150680220d
One conflict, both sides adding to the same test-module `use`: kept every name.

13 changed files +1849 -372

crates/app/src/keymap.rsmodified+41 -5
@@ -78,13 +78,14 @@ pub enum ActionId {
78 Speed,78 Speed,
79 Silence,79 Silence,
80 Mix,80 Mix,
81+ ToggleSnap,
81 CancelExport,82 CancelExport,
82 }83 }
83 84
84 impl ActionId {85 impl ActionId {
85 /// Display order everywhere -- the editor lists them in it and86 /// Display order everywhere -- the editor lists them in it and
86 /// [`Keymap::defaults`] binds them in it.87 /// [`Keymap::defaults`] binds them in it.
87- pub const ALL: [ActionId; 39] = [88+ pub const ALL: [ActionId; 40] = [
88 ActionId::Play,89 ActionId::Play,
89 ActionId::StepBack,90 ActionId::StepBack,
90 ActionId::StepForward,91 ActionId::StepForward,
@@ -123,6 +124,7 @@ impl ActionId {
123 ActionId::Speed,124 ActionId::Speed,
124 ActionId::Silence,125 ActionId::Silence,
125 ActionId::Mix,126 ActionId::Mix,
127+ ActionId::ToggleSnap,
126 ActionId::CancelExport,128 ActionId::CancelExport,
127 ];129 ];
128 130
@@ -167,6 +169,7 @@ impl ActionId {
167 ActionId::Speed => "Speed (tape)…",169 ActionId::Speed => "Speed (tape)…",
168 ActionId::Silence => "Silences: cut or speed up…",170 ActionId::Silence => "Silences: cut or speed up…",
169 ActionId::Mix => "Mix: track volumes and the limiter…",171 ActionId::Mix => "Mix: track volumes and the limiter…",
172+ ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",
170 ActionId::CancelExport => "Cancel export",173 ActionId::CancelExport => "Cancel export",
171 }174 }
172 }175 }
@@ -213,6 +216,7 @@ impl ActionId {
213 ActionId::Speed => "speed",216 ActionId::Speed => "speed",
214 ActionId::Silence => "silence",217 ActionId::Silence => "silence",
215 ActionId::Mix => "mix",218 ActionId::Mix => "mix",
219+ ActionId::ToggleSnap => "toggle-snap",
216 ActionId::CancelExport => "cancel-export",220 ActionId::CancelExport => "cancel-export",
217 }221 }
218 }222 }
@@ -265,6 +269,9 @@ impl ActionId {
265 | ActionId::AddVideoLane269 | ActionId::AddVideoLane
266 | ActionId::AddAudioLane270 | ActionId::AddAudioLane
267 | ActionId::RemoveVideoLane271 | ActionId::RemoveVideoLane
272+ // Not a view setting despite being a pointer aid: it decides where
273+ // a drag actually lands, which is an edit and not a magnification.
274+ | ActionId::ToggleSnap
268 | ActionId::RemoveAudioLane => Category::Editing,275 | ActionId::RemoveAudioLane => Category::Editing,
269 ActionId::ToggleMute276 ActionId::ToggleMute
270 | ActionId::VolumeUp277 | ActionId::VolumeUp
@@ -326,7 +333,7 @@ pub struct Fixed {
326 pub category: Category,333 pub category: Category,
327 }334 }
328 335
329-pub const FIXED: [Fixed; 21] = [336+pub const FIXED: [Fixed; 26] = [
330 // Not a chord at all but a way of pressing one, and the only place the337 // Not a chord at all but a way of pressing one, and the only place the
331 // editor can say so: holding a key that moves a *value* runs it, and338 // editor can say so: holding a key that moves a *value* runs it, and
332 // holding anything else still does what one press did.339 // holding anything else still does what one press did.
@@ -394,7 +401,7 @@ pub const FIXED: [Fixed; 21] = [
394 // its own: a band nothing but a drag can reach is a band half the users of401 // its own: a band nothing but a drag can reach is a band half the users of
395 // this editor cannot move at all. Card-local, so none of them is bindable.402 // this editor cannot move at all. Card-local, so none of them is bindable.
396 Fixed {403 Fixed {
397- chord: "1–5",404+ chord: "1–9, 0",
398 label: "Pick an equalizer band",405 label: "Pick an equalizer band",
399 category: Category::Audio,406 category: Category::Audio,
400 },407 },
@@ -408,6 +415,31 @@ pub const FIXED: [Fixed; 21] = [
408 label: "Lower the picked band 1 dB",415 label: "Lower the picked band 1 dB",
409 category: Category::Audio,416 category: Category::Audio,
410 },417 },
418+ Fixed {
419+ chord: "← / →",
420+ label: "Move the picked band down or up in frequency",
421+ category: Category::Audio,
422+ },
423+ Fixed {
424+ chord: "shift ← / →",
425+ label: "Widen or narrow the picked band (its Q)",
426+ category: Category::Audio,
427+ },
428+ Fixed {
429+ chord: "a",
430+ label: "Add an equalizer band beside the picked one",
431+ category: Category::Audio,
432+ },
433+ Fixed {
434+ chord: "x",
435+ label: "Remove the picked equalizer band",
436+ category: Category::Audio,
437+ },
438+ Fixed {
439+ chord: "f",
440+ label: "Flatten the picked band (double-click does the same)",
441+ category: Category::Audio,
442+ },
411 Fixed {443 Fixed {
412 chord: "r",444 chord: "r",
413 label: "Flatten every band",445 label: "Flatten every band",
@@ -645,6 +677,9 @@ impl Keymap {
645 // machine's volume and not the project's -- two things one key677 // machine's volume and not the project's -- two things one key
646 // must not mean.678 // must not mean.
647 b(ActionId::Mix, "f", false),679 b(ActionId::Mix, "f", false),
680+ // The snap takes "n", which is what every other editor toggles
681+ // it with: free here, and nowhere near the two keys that delete.
682+ b(ActionId::ToggleSnap, "n", false),
648 b(ActionId::CancelExport, "escape", false),683 b(ActionId::CancelExport, "escape", false),
649 ],684 ],
650 }685 }
@@ -907,7 +942,7 @@ mod tests {
907 #[test]942 #[test]
908 fn every_default_stroke_reaches_its_action() {943 fn every_default_stroke_reaches_its_action() {
909 let k = Keymap::defaults();944 let k = Keymap::defaults();
910- assert_eq!(k.entries().len(), 41);945+ assert_eq!(k.entries().len(), 42);
911 assert_eq!(k.lookup("space", false), Some(ActionId::Play));946 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
912 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two947 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
913 // ends of the timeline.948 // ends of the timeline.
@@ -1141,7 +1176,8 @@ mod tests {
1141 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1176 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1142 // The label is the editor's column, and never the file's word for it.1177 // The label is the editor's column, and never the file's word for it.
1143 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1178 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1144- assert_eq!(ActionId::ALL.len(), 39);1179+ assert_eq!(ActionId::ALL.len(), 40);
1180+ assert_eq!(k.display(ActionId::ToggleSnap), "n");
1145 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");1181 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1146 }1182 }
1147 1183
crates/app/src/main.rsmodified+1287 -217
@@ -19,11 +19,11 @@ use engine::project::{Edge, Lane, LaneKind, Source, Speed};
19 use engine::scale::FitPolicy;19 use engine::scale::FitPolicy;
20 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};20 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
21 use gpui::{21 use gpui::{
22- AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,22+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,
23- KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,23+ FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
24- Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign,24+ PathBuilder, Pixels, Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size,
25- TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px,25+ Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img,
26- relative, rgb, rgba, size,26+ point, prelude::*, px, relative, rgb, rgba, size,
27 };27 };
28 28
29 /// Editor chrome: three grays and one accent, all darker than the picture so the29 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -85,6 +85,13 @@ const WAVE_BPS: u32 = 40;
85 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,85 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
86 /// and a path with a point per pixel is a path per repaint.86 /// and a path with a point per pixel is a path per repaint.
87 const WAVE_COL: f32 = 2.;87 const WAVE_COL: f32 = 2.;
88+/// The most columns one envelope is ever built from. A waveform is drawn into
89+/// the slice of its box that is on the bed ([`visible_slice`]), and a bed is a
90+/// screen wide, so nothing on screen ever reaches this -- it is the backstop for
91+/// a box laid out wider than any screen, whose path would otherwise cost a point
92+/// per two pixels of a width nobody can see and stall the repaint that was
93+/// meant to draw the wave.
94+const WAVE_COLS_MAX: usize = 4096;
88 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px95 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
89 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.96 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.
90 const HIT_MIN: f32 = 24.;97 const HIT_MIN: f32 = 24.;
@@ -281,6 +288,13 @@ struct AssetDrag(PathBuf, usize);
281 struct ClipDrag {288 struct ClipDrag {
282 lane: Lane,289 lane: Lane,
283 idx: usize,290 idx: usize,
291+ /// The clip that was picked up, so the drop can find it again: gpui freezes
292+ /// the payload for the whole gesture, and an edit made *during* one -- a
293+ /// stroke deletes, undoes or pastes, none of which a drag blocks -- ripples
294+ /// the indices under it. The index alone would then name a different take at
295+ /// the release, and the drag would move a clip nobody touched (see
296+ /// [`live_idx`]).
297+ clip: Clip,
284 }298 }
285 299
286 /// A clip edge being dragged: which end of which clip, and the timeline frame300 /// A clip edge being dragged: which end of which clip, and the timeline frame
@@ -601,6 +615,36 @@ const EQ_FREQ_HIGH: f32 = 20_000.;
601 /// and short enough that the card still fits a 360 px window.615 /// and short enough that the card still fits a 360 px window.
602 const EQ_GRAPH_H: f32 = 132.;616 const EQ_GRAPH_H: f32 = 132.;
603 617
618+/// How wide the equalizer card is allowed to get. It is the one card that is a
619+/// *graph*: every pixel across is frequency resolution, and at the 320 px the
620+/// other cards use, a third of an octave was a couple of pixels. Past this the
621+/// curve stops gaining anything and the card starts reading as a wall.
622+const EQ_W_MAX: f32 = 720.;
623+
624+/// The gap the card leaves either side of it, so it reads as a card on a scrim
625+/// rather than as a second window: it takes the width it can get inside that.
626+const EQ_W_MARGIN: f32 = 32.;
627+
628+/// How many bands one clip's equalizer may carry from this card. Ten because
629+/// the keyboard picks a band with a digit and a keyboard has ten of them --
630+/// past that a band would be reachable by pointer only. The engine itself caps
631+/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more
632+/// and this card will draw and edit every one it finds.
633+const EQ_BANDS_MAX: usize = 10;
634+
635+/// One press of the frequency keys, as a factor: a sixth of an octave, so a
636+/// band walks the whole axis in about sixty presses and still lands close
637+/// enough to a named frequency to aim at one.
638+const EQ_FREQ_STEP: f32 = 1.122_462;
639+
640+/// One press of the Q keys, as a factor, and the range they move in. Below the
641+/// bottom a peak is barely a peak any more; above the top it is a whistle on
642+/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside
643+/// them, so nothing a file carries has to be dragged into range first.
644+const EQ_Q_STEP: f32 = 1.25;
645+const EQ_Q_LOW: f32 = 0.3;
646+const EQ_Q_HIGH: f32 = 12.;
647+
604 /// How many points the curve is drawn from. One per ~3 px across the card:648 /// How many points the curve is drawn from. One per ~3 px across the card:
605 /// past that the line is smooth and the extra biquad evaluations are wasted.649 /// past that the line is smooth and the extra biquad evaluations are wasted.
606 const EQ_CURVE_STEPS: usize = 96;650 const EQ_CURVE_STEPS: usize = 96;
@@ -649,6 +693,11 @@ const EQ_SPECTRUM_INK: u32 = 0x7f95ad66;
649 /// its weight: it is what makes a boost read as a hill rather than as a wire.693 /// its weight: it is what makes a boost read as a hill rather than as a wire.
650 const EQ_FILL_INK: u32 = 0x4a9eff26;694 const EQ_FILL_INK: u32 = 0x4a9eff26;
651 695
696+/// One band's own response, drawn under the sum: a dim thread per band, so a
697+/// boost pushed against a cut can be *seen* as two bands rather than as the
698+/// flat line their total makes.
699+const EQ_BELL_INK: u32 = 0x4a9eff66;
700+
652 /// The colour card's four controls, in the order it lists them: what each is701 /// The colour card's four controls, in the order it lists them: what each is
653 /// called and the range it moves in. The order is `ColorParams`' own, which is702 /// called and the range it moves in. The order is `ColorParams`' own, which is
654 /// what [`color_band`] indexes.703 /// what [`color_band`] indexes.
@@ -826,6 +875,16 @@ struct Player {
826 /// the value being dragged, and stale between drags, which costs nothing --875 /// the value being dragged, and stale between drags, which costs nothing --
827 /// no drag starts without a press on the box it moves.876 /// no drag starts without a press on the box it moves.
828 grab: u32,877 grab: u32,
878+ /// Whether a drag or a trim is pulled onto the edges near it. On by
879+ /// default, because clips meeting exactly is what a timeline is for, and off
880+ /// by one stroke ([`ActionId::ToggleSnap`]) for the frame-by-frame placement
881+ /// no magnet may take away.
882+ snap: bool,
883+ /// The frame the live gesture is about to land on, or `None` while it is
884+ /// over open bed: the line every lane draws so the snap is seen before it
885+ /// happens rather than discovered after the release. Stale between gestures,
886+ /// which costs nothing -- it is drawn only while one is live.
887+ snap_cue: Option<u32>,
829 last_scrub: Instant,888 last_scrub: Instant,
830 last_target: u32,889 last_target: u32,
831 /// The running export. While it owns the UI the editor is read-only.890 /// The running export. While it owns the UI the editor is read-only.
@@ -1169,12 +1228,26 @@ impl Player {
1169 ActionId::Speed => self.open_speed(cx),1228 ActionId::Speed => self.open_speed(cx),
1170 ActionId::Silence => self.open_silence(cx),1229 ActionId::Silence => self.open_silence(cx),
1171 ActionId::Mix => self.open_mix(None, cx),1230 ActionId::Mix => self.open_mix(None, cx),
1231+ ActionId::ToggleSnap => self.toggle_snap(cx),
1172 // Nothing to cancel while nothing is exporting; the export guard in1232 // Nothing to cancel while nothing is exporting; the export guard in
1173 // the key handler is what answers this one while there is.1233 // the key handler is what answers this one while there is.
1174 ActionId::CancelExport => {}1234 ActionId::CancelExport => {}
1175 }1235 }
1176 }1236 }
1177 1237
1238+ /// The magnet off and on again, in words: a snap that stops working
1239+ /// silently reads as a bug, and one that starts working silently reads as
1240+ /// one too. The line goes with it -- nothing is being promised any more.
1241+ fn toggle_snap(&mut self, cx: &mut Context<Self>) {
1242+ self.snap = !self.snap;
1243+ self.snap_cue = None;
1244+ self.notice = Some(match self.snap {
1245+ true => "SNAP ON — drags land on clip edges, the playhead and the start".into(),
1246+ false => "SNAP OFF — drags land exactly where the hand leaves them".into(),
1247+ });
1248+ cx.notify();
1249+ }
1250+
1178 /// Whether the editor can be asked for `action` right now, and why not when1251 /// Whether the editor can be asked for `action` right now, and why not when
1179 /// it cannot. `on` is the clip the question is about -- the one a clip menu1252 /// it cannot. `on` is the clip the question is about -- the one a clip menu
1180 /// was opened on -- and `None` asks about the marked clip instead, which is1253 /// was opened on -- and `None` asks about the marked clip instead, which is
@@ -1192,6 +1265,12 @@ impl Player {
1192 action,1265 action,
1193 Ctx {1266 Ctx {
1194 clip,1267 clip,
1268+ image: clip.is_some_and(|(clip, _)| {
1269+ session
1270+ .sources()
1271+ .get(clip.source)
1272+ .is_some_and(|s| engine::is_image(&s.path))
1273+ }),
1195 playhead: frame_at(session.now(), self.fps),1274 playhead: frame_at(session.now(), self.fps),
1196 timeline: true,1275 timeline: true,
1197 clipboard: self.clipboard.is_some(),1276 clipboard: self.clipboard.is_some(),
@@ -2101,41 +2180,78 @@ impl Player {
2101 cx.notify();2180 cx.notify();
2102 }2181 }
2103 2182
2104- /// Moves one band and says whether anything changed. Live only: the write2183+ /// Changes the picked band in place and says whether anything moved. Every
2105- /// is [`commit_eq`](Player::commit_eq)'s.2184+ /// edit of a band goes through here -- the drag, each key, each stepper
2106- fn set_band(&mut self, band: usize, gain_db: f32) -> bool {2185+ /// button -- so the card has exactly one place that clamps a band into what
2107- let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);2186+ /// the graph can draw, and no caller has to remember the limits.
2108- match self.eq_params.bands.get_mut(band) {2187+ fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
2109- Some(b) if b.gain_db != gain_db => {2188+ let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
2110- b.gain_db = gain_db;2189+ return false;
2111- true2190+ };
2112- }2191+ let was = *band;
2113- _ => false,2192+ change(band);
2193+ band.freq_hz = band.freq_hz.clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH);
2194+ band.gain_db = band.gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
2195+ band.q = band.q.clamp(EQ_Q_LOW, EQ_Q_HIGH);
2196+ *band != was
2197+ }
2198+
2199+ /// The keyboard's and the buttons' version of a drag: one step on the picked
2200+ /// band, committed straight away -- neither has a release to wait for.
2201+ fn nudge_band(&mut self, change: impl FnOnce(&mut Band), cx: &mut Context<Self>) {
2202+ if self.set_band(change) {
2203+ self.commit_eq(cx);
2114 }2204 }
2115 }2205 }
2116 2206
2117- /// The keyboard's version of a drag: one step on the picked band, committed2207+ /// Where the pointer sits in the graph, as the picked band's frequency and
2118- /// straight away -- a keystroke has no release to wait for.2208+ /// gain: across is the frequency axis and down is the gain one, so the
2119- fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) {2209+ /// handle follows the hand both ways rather than sliding up a rail. Called
2120- let gain = self2210+ /// on every pointer sample, so the curve bends under it; the write is the
2121- .eq_params2211+ /// release's ([`commit_eq`](Player::commit_eq)).
2122- .bands2212+ fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
2123- .get(self.eq_band)2213+ let bounds = self.eq_graph.get();
2124- .map_or(0., |b| b.gain_db);2214+ let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT;
2125- if self.set_band(self.eq_band, gain + by) {2215+ let freq = eq_freq(frac_along(at.x, bounds));
2126- self.commit_eq(cx);2216+ if self.set_band(|b| {
2217+ b.gain_db = gain;
2218+ b.freq_hz = freq;
2219+ }) {
2220+ cx.notify();
2221+ }
2222+ }
2223+
2224+ /// A band added beside the picked one, at the frequency with the most room
2225+ /// around it ([`inserted_band`]), and picked so the next keystroke moves the
2226+ /// band that was just made. Refused rather than silently ignored at the cap.
2227+ fn add_band(&mut self, cx: &mut Context<Self>) {
2228+ if self.eq_params.bands.len() >= EQ_BANDS_MAX {
2229+ self.notice = Some(
2230+ format!(
2231+ "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead"
2232+ )
2233+ .into(),
2234+ );
2235+ cx.notify();
2236+ return;
2127 }2237 }
2238+ let band = inserted_band(&self.eq_params.bands, self.eq_band);
2239+ self.eq_band = (self.eq_band + 1).min(self.eq_params.bands.len());
2240+ self.eq_params.bands.insert(self.eq_band, band);
2241+ self.commit_eq(cx);
2128 }2242 }
2129 2243
2130- /// Where the pointer sits down the graph, as a gain on the picked band: the2244+ /// Takes the picked band out. The last one stays: an equalizer of no bands
2131- /// middle is flat and the top and bottom edges are the limit either way.2245+ /// is a card with nothing to edit, and flattening is what "off" means here.
2132- /// Called on every pointer sample, so the curve bends under the hand; the2246+ fn remove_band(&mut self, cx: &mut Context<Self>) {
2133- /// write is the release's ([`commit_eq`](Player::commit_eq)).2247+ if self.eq_params.bands.len() <= 1 {
2134- fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) {2248+ self.notice = Some("LAST BAND — flatten it instead (r), or close the card".into());
2135- let gain = (0.5 - frac_down(y, self.eq_graph.get())) * 2. * EQ_GAIN_LIMIT;
2136- if self.set_band(self.eq_band, gain) {
2137 cx.notify();2249 cx.notify();
2250+ return;
2138 }2251 }
2252+ self.eq_params.bands.remove(self.eq_band);
2253+ self.eq_band = self.eq_band.min(self.eq_params.bands.len() - 1);
2254+ self.commit_eq(cx);
2139 }2255 }
2140 2256
2141 /// Which band a press on the graph grabs: the nearest one along the2257 /// Which band a press on the graph grabs: the nearest one along the
@@ -2535,8 +2651,8 @@ impl Player {
2535 if self.exporting().is_some() {2651 if self.exporting().is_some() {
2536 return;2652 return;
2537 }2653 }
2538- let (Some(start), Some(was)) = (2654+ let (Some((start, _)), Some(was)) = (
2539- self.drop_frame(from, idx, to, x),2655+ self.drop_frame(from, idx, x),
2540 self.session2656 self.session
2541 .as_ref()2657 .as_ref()
2542 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),2658 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),
@@ -2598,26 +2714,70 @@ impl Player {
2598 /// the scroll clamp pins the bed's right edge to the duration, and the2714 /// the scroll clamp pins the bed's right edge to the duration, and the
2599 /// pointer has no pixel past it. The upgrade is to let the scroll clamp2715 /// pointer has no pixel past it. The upgrade is to let the scroll clamp
2600 /// leave a screen of empty bed after the end, the way every NLE does.2716 /// leave a screen of empty bed after the end, the way every NLE does.
2601- fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> {2717+ fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> {
2602- let session = self.session.as_ref()?;2718+ let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?;
2603- let clip = session.lane_clips(from).get(idx).copied()?;
2604 let raw = self.frame_under(x).saturating_sub(self.grab);2719 let raw = self.frame_under(x).saturating_sub(self.grab);
2605- // The edges worth landing on: both ends of every clip already on the2720+ let marks = self.snap_targets(Some((from, idx)));
2606- // lane it is being let go over, the playhead, and the head of the2721+ Some(self.snap_to(raw, clip.frames(), &marks))
2607- // timeline. Never the group's own boxes -- a clip does not snap to2722+ }
2608- // where it already is.2723+
2609- let mut marks: Vec<u32> = session2724+ /// Which index the clip in the hand is at *now*: [`live_idx`] against the
2610- .lane_clips(to)2725+ /// lane the drag named, since a stroke during the gesture moves the indices
2611- .iter()2726+ /// gpui froze into the payload. Both halves of a drag ask it -- the line
2612- .enumerate()2727+ /// drawn in flight and the drop that commits -- so the promise and the
2613- .filter(|&(i, c)| {2728+ /// landing are made about one clip.
2614- (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link)2729+ fn dragged(&self, drag: &ClipDrag) -> Option<usize> {
2615- })2730+ let session = self.session.as_ref()?;
2616- .flat_map(|(_, c)| [c.start, c.end()])2731+ live_idx(session.lane_clips(drag.lane), drag.idx, drag.clip)
2617- .collect();2732+ }
2618- marks.push(frame_at(session.now(), self.fps));2733+
2619- marks.push(0);2734+ /// The line while the clip is still in the hand: the very answer
2620- Some(snapped(raw, clip.frames(), self.snap_frames(), &marks))2735+ /// [`Player::drop_frame`] will commit, worked out on every move of the drag,
2736+ /// so what the eye was promised is where the release puts it. A pointer that
2737+ /// has wandered off the bed promises nothing.
2738+ fn preview_drop(&mut self, from: Lane, idx: usize, x: Pixels, cx: &mut Context<Self>) {
2739+ let cue = self.drop_frame(from, idx, x).and_then(|(_, cue)| cue);
2740+ self.set_cue(cue, x, cx);
2741+ }
2742+
2743+ /// The same line for a library row on its way to a lane: it goes down at
2744+ /// the frame it is let go on ([`Player::insert_source`]), so that frame is
2745+ /// what snaps and what is drawn. No length to snap by -- the file's own is
2746+ /// not known until the engine has placed it -- so only its head lands.
2747+ fn preview_place(&mut self, x: Pixels, cx: &mut Context<Self>) {
2748+ let marks = self.snap_targets(None);
2749+ let cue = self.snap_to(self.frame_under(x), 0, &marks).1;
2750+ self.set_cue(cue, x, cx);
2751+ }
2752+
2753+ /// Sets the line, or takes it away, and repaints only when it moved: a
2754+ /// pointer dragged off the bed (up to the library, say) is not promising a
2755+ /// landing any more.
2756+ fn set_cue(&mut self, cue: Option<u32>, x: Pixels, cx: &mut Context<Self>) {
2757+ let bed = self.ruler.get();
2758+ let cue = cue.filter(|_| x >= bed.left() && x <= bed.right());
2759+ if cue != self.snap_cue {
2760+ self.snap_cue = cue;
2761+ cx.notify();
2762+ }
2763+ }
2764+
2765+ /// Every edge this timeline offers a gesture: [`snap_marks`] over all of its
2766+ /// lanes, so a clip meets a take one track over as readily as one beside it.
2767+ fn snap_targets(&self, skip: Option<(Lane, usize)>) -> Vec<u32> {
2768+ let Some(session) = &self.session else {
2769+ return Vec::new();
2770+ };
2771+ let lanes = session.lanes();
2772+ let clips: Vec<&[Clip]> = lanes.iter().map(|&lane| session.lane_clips(lane)).collect();
2773+ let skip = skip.and_then(|(lane, idx)| Some((lanes.iter().position(|&l| l == lane)?, idx)));
2774+ snap_marks(&clips, skip, frame_at(session.now(), self.fps))
2775+ }
2776+
2777+ /// Where a gesture at `raw` lands and the mark that pulled it there, with
2778+ /// the switch honoured: snapping off, nothing moves and no line is drawn.
2779+ fn snap_to(&self, raw: u32, len: u32, marks: &[u32]) -> (u32, Option<u32>) {
2780+ snap_cue(self.snap, raw, len, self.snap_frames(), marks)
2621 }2781 }
2622 2782
2623 /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's2783 /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's
@@ -2681,14 +2841,25 @@ impl Player {
2681 /// against the same duration the boxes are drawn to, so the edge tracks the2841 /// against the same duration the boxes are drawn to, so the edge tracks the
2682 /// pointer exactly.2842 /// pointer exactly.
2683 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {2843 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
2684- let at = self.frame_under(x);2844+ let Some(trim) = self.trim else {
2685- let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
2686 return;2845 return;
2687 };2846 };
2688- let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {2847+ // The edge is pulled onto the same marks a whole clip is, by itself:
2848+ // there is no other end travelling with it, so it snaps at length zero.
2849+ let marks = self.snap_targets(Some((trim.lane, trim.idx)));
2850+ let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks);
2851+ let Some((lo, hi)) = self
2852+ .session
2853+ .as_ref()
2854+ .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge))
2855+ else {
2689 return;2856 return;
2690 };2857 };
2691- trim.to = at.clamp(lo, hi);2858+ let to = at.clamp(lo, hi);
2859+ // The line only stands where the edge actually stopped: a mark the
2860+ // engine's own room clamped away was never reached.
2861+ self.set_cue(cue.filter(|_| to == at), x, cx);
2862+ self.trim = Some(Trim { to, ..trim });
2692 cx.notify();2863 cx.notify();
2693 }2864 }
2694 2865
@@ -2730,39 +2901,13 @@ impl Player {
2730 }) else {2901 }) else {
2731 return clip;2902 return clip;
2732 };2903 };
2733- match trim.edge {2904+ let still = self.session.as_ref().is_some_and(|session| {
2734- // A still grows forward from source frame 0 instead, exactly as2905+ session
2735- // `Project::trim` writes it: with the in-point clamped at 0 the box2906+ .sources()
2736- // below would slide left rather than stretch, and the release would2907+ .get(clip.source)
2737- // then commit a wider clip than the drag drew.2908+ .is_some_and(|s| engine::is_image(&s.path))
2738- Edge::Start2909+ });
2739- if self.session.as_ref().is_some_and(|session| {2910+ trimmed_clip(clip, trim.edge, trim.to, still)
2740- session
2741- .sources()
2742- .get(clip.source)
2743- .is_some_and(|s| engine::is_image(&s.path))
2744- }) =>
2745- {
2746- Clip {
2747- in_frame: 0,
2748- out_frame: clip.end().saturating_sub(trim.to).max(1),
2749- start: trim.to,
2750- ..clip
2751- }
2752- }
2753- // The in-point follows the head, exactly as `Project::trim` moves
2754- // it: what stays on screen plays what it always played.
2755- Edge::Start => Clip {
2756- in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start))
2757- .clamp(0, i64::from(clip.out_frame - 1)) as u32,
2758- start: trim.to,
2759- ..clip
2760- },
2761- Edge::End => Clip {
2762- out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1),
2763- ..clip
2764- },
2765- }
2766 }2911 }
2767 2912
2768 /// How long the timeline is *drawn* as: its own length, and while a tail is2913 /// How long the timeline is *drawn* as: its own length, and while a tail is
@@ -2770,6 +2915,15 @@ impl Player {
2770 /// at the last frame has nowhere to put a pointer that means "longer", so2915 /// at the last frame has nowhere to put a pointer that means "longer", so
2771 /// without this the last clip on the timeline could be pulled in and never2916 /// without this the last clip on the timeline could be pulled in and never
2772 /// let back out.2917 /// let back out.
2918+ ///
2919+ /// Scroll room only, now that a second is an absolute number of pixels
2920+ /// ([`Scale`]): the extra length loosens [`View::settled`]'s clamp, which is
2921+ /// where the pixels past the last frame come from, and moves no box by a
2922+ /// pixel. It is still the *only* headroom at the tail -- zoomed in against
2923+ /// the end, that clamp pins the bed's right edge to the duration and an
2924+ /// End-trim of the last clip would have nowhere to be dragged to. What it
2925+ /// must not do is be read as a length anyone is told: the timecode reads
2926+ /// `PlaybackSession::timeline_duration` for exactly that reason.
2773 fn drawn_duration(&self) -> f64 {2927 fn drawn_duration(&self) -> f64 {
2774 let Some(session) = &self.session else {2928 let Some(session) = &self.session else {
2775 return 0.;2929 return 0.;
@@ -3800,31 +3954,55 @@ impl Render for Player {
3800 // cannot move at all, and every one of them is listed in the3954 // cannot move at all, and every one of them is listed in the
3801 // keys menu (keymap.rs `FIXED`) rather than being a secret.3955 // keys menu (keymap.rs `FIXED`) rather than being a secret.
3802 if this.eq_open.is_some() {3956 if this.eq_open.is_some() {
3957+ // Shift makes the two horizontal keys Q instead of
3958+ // frequency: both are the *width* of the same hump, so they
3959+ // sit on the same axis rather than on two keys nobody would
3960+ // guess. Wider is a lower Q, which is why left widens.
3961+ let shift = event.keystroke.modifiers.shift;
3803 if key == ESCAPE {3962 if key == ESCAPE {
3804 // Nothing to undo: every change is already at the clip,3963 // Nothing to undo: every change is already at the clip,
3805 // and undo is undo's own key.3964 // and undo is undo's own key.
3806 this.eq_open = None;3965 this.eq_open = None;
3807 this.eq_dragging = false;3966 this.eq_dragging = false;
3808 } else if key == "up" {3967 } else if key == "up" {
3809- this.nudge_band(EQ_STEP, cx);3968+ this.nudge_band(|b| b.gain_db += EQ_STEP, cx);
3810 } else if key == "down" {3969 } else if key == "down" {
3811- this.nudge_band(-EQ_STEP, cx);3970+ this.nudge_band(|b| b.gain_db -= EQ_STEP, cx);
3971+ } else if key == "left" && shift {
3972+ this.nudge_band(|b| b.q /= EQ_Q_STEP, cx);
3973+ } else if key == "right" && shift {
3974+ this.nudge_band(|b| b.q *= EQ_Q_STEP, cx);
3975+ } else if key == "left" {
3976+ this.nudge_band(|b| b.freq_hz /= EQ_FREQ_STEP, cx);
3977+ } else if key == "right" {
3978+ this.nudge_band(|b| b.freq_hz *= EQ_FREQ_STEP, cx);
3812 } else if key == "r" {3979 } else if key == "r" {
3813 for band in &mut this.eq_params.bands {3980 for band in &mut this.eq_params.bands {
3814 band.gain_db = 0.;3981 band.gain_db = 0.;
3815 }3982 }
3816 this.commit_eq(cx);3983 this.commit_eq(cx);
3984+ } else if key == "f" {
3985+ // This one band back to flat, which is the undo of one
3986+ // hand movement -- `r` is the undo of the whole card.
3987+ this.nudge_band(|b| b.gain_db = 0., cx);
3988+ } else if key == "a" {
3989+ this.add_band(cx);
3990+ } else if key == "x" {
3991+ this.remove_band(cx);
3817 } else if key == "s" {3992 } else if key == "s" {
3818 // The analyser off and on. Nothing is committed: it is3993 // The analyser off and on. Nothing is committed: it is
3819 // what the card *shows*, so it survives no further than3994 // what the card *shows*, so it survives no further than
3820 // this window.3995 // this window.
3821 this.eq_spectrum = !this.eq_spectrum;3996 this.eq_spectrum = !this.eq_spectrum;
3822 } else if let Ok(digit) = key.parse::<usize>() {3997 } else if let Ok(digit) = key.parse::<usize>() {
3823- // 1-based, as the rows are numbered on screen; a digit3998+ // As the keys are laid out: 1-9 then 0 for the tenth,
3824- // past the last band picks nothing rather than panics.3999+ // which is the cap ([`EQ_BANDS_MAX`]). A digit past the
3825- if let Some(band) = digit.checked_sub(1)4000+ // last band picks nothing rather than panics.
3826- && band < this.eq_params.bands.len()4001+ let band = match digit {
3827- {4002+ 0 => EQ_BANDS_MAX - 1,
4003+ n => n - 1,
4004+ };
4005+ if band < this.eq_params.bands.len() {
3828 this.eq_band = band;4006 this.eq_band = band;
3829 }4007 }
3830 }4008 }
@@ -3966,6 +4144,26 @@ impl Render for Player {
3966 }4144 }
3967 }4145 }
3968 }))4146 }))
4147+ // A drop event carries no path of its own -- gpui only tells the
4148+ // target that something landed -- so the line that promises where
4149+ // it will land is fed by the drag's own moves, which do carry the
4150+ // pointer (gpui div.rs:282). On the root, because a drag crosses
4151+ // the window: it starts on a clip or on a library row and ends over
4152+ // a lane, and only an ancestor of both hears all of it.
4153+ .on_drag_move(cx.listener(|this, event: &DragMoveEvent<ClipDrag>, _, cx| {
4154+ // The clip the payload named, wherever an edit mid-drag has
4155+ // since put it ([`Player::dragged`]): the line has to promise a
4156+ // landing for the take actually in the hand.
4157+ let drag = *event.drag(cx);
4158+ if let Some(idx) = this.dragged(&drag) {
4159+ this.preview_drop(drag.lane, idx, event.event.position.x, cx);
4160+ }
4161+ }))
4162+ .on_drag_move(
4163+ cx.listener(|this, event: &DragMoveEvent<AssetDrag>, _, cx| {
4164+ this.preview_place(event.event.position.x, cx);
4165+ }),
4166+ )
3969 // Scrubbing is tracked on the root because the pointer leaves the4167 // Scrubbing is tracked on the root because the pointer leaves the
3970 // 6 px ruler on the first drag and its own listeners then stop4168 // 6 px ruler on the first drag and its own listeners then stop
3971 // firing; the root's hitbox is the whole window.4169 // firing; the root's hitbox is the whole window.
@@ -3974,7 +4172,7 @@ impl Render for Player {
3974 // the equalizer drag is tracked here for the ruler's reason.4172 // the equalizer drag is tracked here for the ruler's reason.
3975 if this.eq_dragging {4173 if this.eq_dragging {
3976 if event.pressed_button == Some(MouseButton::Left) {4174 if event.pressed_button == Some(MouseButton::Left) {
3977- this.drag_band(event.position.y, cx);4175+ this.drag_band(event.position, cx);
3978 } else {4176 } else {
3979 // Released outside the window: the up below never came,4177 // Released outside the window: the up below never came,
3980 // so this is where the gesture ends -- and it still owes4178 // so this is where the gesture ends -- and it still owes
@@ -4044,7 +4242,7 @@ impl Render for Player {
4044 if std::mem::take(&mut this.eq_dragging) {4242 if std::mem::take(&mut this.eq_dragging) {
4045 // The release lands exactly, then the gesture is written4243 // The release lands exactly, then the gesture is written
4046 // once -- the append-only table's whole reason.4244 // once -- the append-only table's whole reason.
4047- this.drag_band(event.position.y, cx);4245+ this.drag_band(event.position, cx);
4048 this.commit_eq(cx);4246 this.commit_eq(cx);
4049 return;4247 return;
4050 }4248 }
@@ -4146,7 +4344,7 @@ impl Render for Player {
4146 // column, and only one of the two is ever up.4344 // column, and only one of the two is ever up.
4147 .children(self.keys_overlay(cx))4345 .children(self.keys_overlay(cx))
4148 .children(self.export_card(window.viewport_size(), cx))4346 .children(self.export_card(window.viewport_size(), cx))
4149- .children(self.eq_card(cx))4347+ .children(self.eq_card(window.viewport_size(), cx))
4150 .children(self.color_card(cx))4348 .children(self.color_card(cx))
4151 .children(self.speed_card(cx))4349 .children(self.speed_card(cx))
4152 .children(self.silence_card(cx))4350 .children(self.silence_card(cx))
@@ -4737,6 +4935,25 @@ impl Player {
4737 live,4935 live,
4738 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),4936 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),
4739 ))4937 ))
4938+ // The magnet, beside the zoom for the zoom's own reason: it
4939+ // changes nothing on the timeline, it changes how the hand
4940+ // meets it. The label is the state, as the volume's is --
4941+ // a toggle that looks the same either way says nothing.
4942+ .child(control(
4943+ "snap",
4944+ None,
4945+ if self.snap { "Snap" } else { "No snap" },
4946+ format!(
4947+ "{} — {}",
4948+ key(ActionId::ToggleSnap),
4949+ match self.snap {
4950+ true => "drags and trims land on clip edges, the playhead and the start",
4951+ false => "drags and trims land exactly where the hand leaves them",
4952+ }
4953+ ),
4954+ live,
4955+ cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)),
4956+ ))
4740 // Import is not here: it belongs to the media list it adds4957 // Import is not here: it belongs to the media list it adds
4741 // to, and two doors into one action is a question about4958 // to, and two doors into one action is a question about
4742 // which one is the real one.4959 // which one is the real one.
@@ -4809,10 +5026,20 @@ impl Player {
4809 .gap(px(12.))5026 .gap(px(12.))
4810 // Fixed width and one line: changing digits must not push5027 // Fixed width and one line: changing digits must not push
4811 // the row around, nor wrap and change its height.5028 // the row around, nor wrap and change its height.
5029+ // The timeline's own length, never the drawn one: a tail
5030+ // being dragged inflates the bed to the room that edge has
5031+ // ([`Player::drawn_duration`]), and for a still that room is
5032+ // ten minutes -- a total that jumped to 10:00:00 the moment
5033+ // a picture's edge was pressed, and back on release.
4812 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(5034 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(
4813 "{} / {}",5035 "{} / {}",
4814 timecode(position, self.fps),5036 timecode(position, self.fps),
4815- timecode(duration, self.fps)5037+ timecode(
5038+ self.session
5039+ .as_ref()
5040+ .map_or(0., PlaybackSession::timeline_duration),
5041+ self.fps
5042+ )
4816 )))5043 )))
4817 .child(5044 .child(
4818 div()5045 div()
@@ -5592,20 +5819,28 @@ impl Player {
5592 }5819 }
5593 5820
5594 /// The equalizer of one audio clip: its frequency response drawn as a5821 /// The equalizer of one audio clip: its frequency response drawn as a
5595- /// curve, a handle per band sitting on it, and a row that flattens them5822+ /// curve, a handle per band sitting on it, each band's own bell under the
5596- /// all. The curve is the clip's actual filter (`EqParams::response_db`5823+ /// sum, and a row that reads and moves the picked band's three numbers. The
5597- /// reads the coefficients the samples go through), and it is redrawn on5824+ /// curve is the clip's actual filter (`EqParams::response_db` reads the
5598- /// every pointer sample of a drag, so the shape bends under the hand.5825+ /// coefficients the samples go through), and it is redrawn on every pointer
5826+ /// sample of a drag, so the shape bends under the hand.
5599 ///5827 ///
5600- /// The same scrim and width as the other two cards, and the same plain divs5828+ /// Wider than the other cards and wider still on a bigger window
5601- /// -- nothing here takes focus, so the root keeps the keyboard and the5829+ /// ([`eq_card_w`]): every pixel across is frequency resolution, which none
5602- /// card's own strokes (`1`–`5`, up, down, `r`) reach it.5830+ /// of the row-shaped cards have any use for. The same scrim and the same
5831+ /// plain divs -- nothing here takes focus, so the root keeps the keyboard
5832+ /// and the card's own strokes (a digit, the arrows, `a`, `x`, `f`, `r`,
5833+ /// `s`) reach it.
5603 ///5834 ///
5604 /// Every change is written at the clip as it is made5835 /// Every change is written at the clip as it is made
5605 /// ([`Player::commit_eq`]), so what the card shows is always what is5836 /// ([`Player::commit_eq`]), so what the card shows is always what is
5606 /// playing: there is no OK button to forget, and closing it changes5837 /// playing: there is no OK button to forget, and closing it changes
5607 /// nothing. What takes a curve back off is undo, like every other edit.5838 /// nothing. What takes a curve back off is undo, like every other edit.
5608- fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {5839+ fn eq_card(
5840+ &self,
5841+ viewport: Size<Pixels>,
5842+ cx: &mut Context<Self>,
5843+ ) -> Option<impl IntoElement> {
5609 let (lane, idx) = self.eq_open?;5844 let (lane, idx) = self.eq_open?;
5610 // The rate the engine filters this timeline at, so the drawn curve is5845 // The rate the engine filters this timeline at, so the drawn curve is
5611 // the one those coefficients make -- near the top of the axis a 44.1 kHz5846 // the one those coefficients make -- near the top of the axis a 44.1 kHz
@@ -5659,13 +5894,20 @@ impl Player {
5659 .bg(rgb(HOVER_DIM))5894 .bg(rgb(HOVER_DIM))
5660 .cursor_pointer()5895 .cursor_pointer()
5661 // The press picks the band under it *and* is already the first5896 // The press picks the band under it *and* is already the first
5662- // sample of the drag, so a plain click sets a value.5897+ // sample of the drag, so a plain click sets a value. A second click
5898+ // takes that band back to flat instead: the gesture that undoes one
5899+ // handle, with no modifier to remember.
5663 .on_mouse_down(5900 .on_mouse_down(
5664 MouseButton::Left,5901 MouseButton::Left,
5665 cx.listener(|this, event: &MouseDownEvent, _, cx| {5902 cx.listener(|this, event: &MouseDownEvent, _, cx| {
5666 this.eq_band = this.nearest_band(event.position.x);5903 this.eq_band = this.nearest_band(event.position.x);
5904+ if event.click_count >= 2 {
5905+ this.eq_dragging = false;
5906+ this.nudge_band(|b| b.gain_db = 0., cx);
5907+ return;
5908+ }
5667 this.eq_dragging = true;5909 this.eq_dragging = true;
5668- this.drag_band(event.position.y, cx);5910+ this.drag_band(event.position, cx);
5669 }),5911 }),
5670 )5912 )
5671 .child(bounds_probe(self.eq_graph.clone()))5913 .child(bounds_probe(self.eq_graph.clone()))
@@ -5757,7 +5999,7 @@ impl Player {
5757 })5999 })
5758 .child(6000 .child(
5759 div()6001 div()
5760- .w(px(KEYS_W))6002+ .w(px(eq_card_w(f32::from(viewport.width))))
5761 .flex()6003 .flex()
5762 .flex_col()6004 .flex_col()
5763 .gap(px(2.))6005 .gap(px(2.))
@@ -5778,28 +6020,15 @@ impl Player {
5778 .text_size(px(11.))6020 .text_size(px(11.))
5779 .text_color(rgb(INK_DIM))6021 .text_color(rgb(INK_DIM))
5780 .child(self.notice.clone().unwrap_or_else(|| {6022 .child(self.notice.clone().unwrap_or_else(|| {
5781- "drag the curve, or 1–5 then up/down — s hides the spectrum, esc closes".into()6023+ "drag a handle, or a digit picks a band — ←→ moves it, ↑↓ its gain, shift+←→ its width; a adds, x removes, f flattens it, r all, s spectrum, esc closes".into()
5782 })),6024 })),
5783 )6025 )
5784 .child(graph)6026 .child(graph)
5785- // Which band the keyboard is holding and what it is set6027+ // Which band the keyboard is holding and every number it
5786- // to: the curve shows the sum, and a band pushed against6028+ // is set to, each with the pair of buttons that moves it:
5787- // one pulling the other way is not readable off it.6029+ // the curve shows the sum, and a band pushed against one
5788- .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(6030+ // pulling the other way is not readable off it.
5789- match picked {6031+ .child(self.eq_numbers(picked, cx))
5790- // Q as well as the two the curve shows: it is
5791- // how wide the hump under the handle is, and
5792- // nothing else on the card says so.
5793- Some(band) => format!(
5794- "{} {} {:+.1} dB — Q {:.2}",
5795- self.eq_band + 1,
5796- band_label(band),
5797- band.gain_db,
5798- band.q
5799- ),
5800- None => "no bands".into(),
5801- },
5802- ))
5803 .child(6032 .child(
5804 div()6033 div()
5805 .mt(px(4.))6034 .mt(px(4.))
@@ -5823,7 +6052,45 @@ impl Player {
5823 }6052 }
5824 this.commit_eq(cx);6053 this.commit_eq(cx);
5825 }))6054 }))
5826- .child("Flatten"),6055+ .child("Flatten all"),
6056+ )
6057+ // The two that change how many bands there are.
6058+ // The engine takes any cascade -- the count was
6059+ // only ever fixed because this card had no way
6060+ // to say otherwise.
6061+ .child(
6062+ div()
6063+ .id("eq-add")
6064+ .flex()
6065+ .flex_1()
6066+ .h(px(CONTROL_H))
6067+ .items_center()
6068+ .justify_center()
6069+ .rounded(px(3.))
6070+ .bg(rgb(CHROME))
6071+ .cursor_pointer()
6072+ .hover(|s| s.bg(rgb(HOVER)))
6073+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
6074+ this.add_band(cx)
6075+ }))
6076+ .child("Add band"),
6077+ )
6078+ .child(
6079+ div()
6080+ .id("eq-remove")
6081+ .flex()
6082+ .flex_1()
6083+ .h(px(CONTROL_H))
6084+ .items_center()
6085+ .justify_center()
6086+ .rounded(px(3.))
6087+ .bg(rgb(CHROME))
6088+ .cursor_pointer()
6089+ .hover(|s| s.bg(rgb(HOVER)))
6090+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
6091+ this.remove_band(cx)
6092+ }))
6093+ .child("Remove band"),
5827 )6094 )
5828 // The analyser's switch, next to the one other6095 // The analyser's switch, next to the one other
5829 // button the card has: `s` does the same, and a6096 // button the card has: `s` does the same, and a
@@ -5858,6 +6125,103 @@ impl Player {
5858 )6125 )
5859 }6126 }
5860 6127
6128+ /// The picked band's three numbers -- where it sits, how far it pushes and
6129+ /// how wide it is -- each beside the pair of buttons that moves it. The
6130+ /// arrows do the same three things, but a value only a key can change is a
6131+ /// value a hand on the pointer cannot reach at all, which is the same reason
6132+ /// [`Player::mbps_steppers`] exists.
6133+ fn eq_numbers(&self, picked: Option<&Band>, cx: &mut Context<Self>) -> impl IntoElement {
6134+ let row = div()
6135+ .flex_none()
6136+ .flex()
6137+ .items_center()
6138+ .gap(px(10.))
6139+ .px(px(6.))
6140+ .text_size(px(11.));
6141+ let Some(band) = picked.copied() else {
6142+ return row.child("no bands — a adds one");
6143+ };
6144+ let step = |id: &'static str,
6145+ label: &'static str,
6146+ change: fn(&mut Band),
6147+ cx: &mut Context<Self>| {
6148+ div()
6149+ .id(id)
6150+ .flex()
6151+ .w(px(HIT_MIN))
6152+ .h(px(HIT_MIN))
6153+ .items_center()
6154+ .justify_center()
6155+ .rounded(px(3.))
6156+ .bg(rgb(CHROME))
6157+ .cursor_pointer()
6158+ .hover(|s| s.bg(rgb(HOVER)))
6159+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
6160+ this.nudge_band(change, cx)
6161+ }))
6162+ .child(label)
6163+ };
6164+ let number = |value: String,
6165+ ids: (&'static str, &'static str),
6166+ by: (fn(&mut Band), fn(&mut Band)),
6167+ cx: &mut Context<Self>| {
6168+ div()
6169+ .flex()
6170+ .items_center()
6171+ .gap(px(4.))
6172+ .child(div().child(value))
6173+ .child(step(ids.0, "−", by.0, cx))
6174+ .child(step(ids.1, "+", by.1, cx))
6175+ };
6176+ row.child(format!(
6177+ "Band {} of {}",
6178+ self.eq_band + 1,
6179+ self.eq_params.bands.len()
6180+ ))
6181+ .child(number(
6182+ band_label(&band),
6183+ ("eq-freq-down", "eq-freq-up"),
6184+ (
6185+ |b| b.freq_hz /= EQ_FREQ_STEP,
6186+ |b| b.freq_hz *= EQ_FREQ_STEP,
6187+ ),
6188+ cx,
6189+ ))
6190+ .child(number(
6191+ format!("{:+.1} dB", band.gain_db),
6192+ ("eq-gain-down", "eq-gain-up"),
6193+ (|b| b.gain_db -= EQ_STEP, |b| b.gain_db += EQ_STEP),
6194+ cx,
6195+ ))
6196+ // Q is width, so its buttons are labelled by what they *do* to the
6197+ // hump rather than by which way the number goes: a wider band is a
6198+ // smaller Q, and nobody should have to know that to use the card.
6199+ .child(number(
6200+ format!("Q {:.2}", band.q),
6201+ ("eq-q-wider", "eq-q-narrower"),
6202+ (|b| b.q /= EQ_Q_STEP, |b| b.q *= EQ_Q_STEP),
6203+ cx,
6204+ ))
6205+ .child(
6206+ div()
6207+ .id("eq-flat-band")
6208+ .flex()
6209+ .h(px(HIT_MIN))
6210+ .px(px(8.))
6211+ .items_center()
6212+ .rounded(px(3.))
6213+ .bg(rgb(CHROME))
6214+ .cursor_pointer()
6215+ .hover(|s| s.bg(rgb(HOVER)))
6216+ .on_click(
6217+ cx.listener(|this, _: &ClickEvent, _, cx| {
6218+ this.nudge_band(|b| b.gain_db = 0., cx)
6219+ }),
6220+ )
6221+ .child("Flatten this"),
6222+ )
6223+ }
6224+
5861 /// The colour card: the graded frame's histogram over a row per control,6225 /// The colour card: the graded frame's histogram over a row per control,
5862 /// each row a bar the pointer drags straight to a value -- no stepper6226 /// each row a bar the pointer drags straight to a value -- no stepper
5863 /// buttons, because a slider is a thing to pull, and the arrow keys still6227 /// buttons, because a slider is a thing to pull, and the arrow keys still
@@ -6752,6 +7116,15 @@ impl Player {
6752 // dims a row with -- and a row that takes no click says *why*7116 // dims a row with -- and a row that takes no click says *why*
6753 // rather than printing a stroke that would do nothing.7117 // rather than printing a stroke that would do nothing.
6754 let refusal = self.enable(action, Some((menu.lane, menu.idx)));7118 let refusal = self.enable(action, Some((menu.lane, menu.idx)));
7119+ // A grade on a waveform, an equalizer on a picture, a silence
7120+ // scan on a still: things that do not exist for what was
7121+ // right-clicked, so the menu is the list of what this clip can
7122+ // do rather than the registry with most of it struck through.
7123+ // The state refusals below stay, dimmed and saying why -- the
7124+ // next click of the playhead lights them.
7125+ if !refusal.listed() {
7126+ continue;
7127+ }
6755 let enabled = refusal.yes();7128 let enabled = refusal.yes();
6756 // The one item that is not about this clip says so, and says it7129 // The one item that is not about this clip says so, and says it
6757 // here rather than in the registry: the stroke is global too,7130 // here rather than in the registry: the stroke is global too,
@@ -7052,6 +7425,19 @@ impl Player {
7052 // it, so all of them move together when it does. No bed width is needed7425 // it, so all of them move together when it does. No bed width is needed
7053 // to place them any more -- a second is so many pixels wherever it is.7426 // to place them any more -- a second is so many pixels wherever it is.
7054 let scale = self.scale;7427 let scale = self.scale;
7428+ // How much bed there is to be seen on, measured off the ruler's own
7429+ // probe like every other question about it: what a box draws *inside*
7430+ // itself is clipped to this ([`visible_slice`]), because a box at a deep
7431+ // zoom is far wider than the strip it is being watched through.
7432+ let bed = f32::from(self.ruler.get().size.width);
7433+ // Where the snap line stands, in the same pixels every box is placed
7434+ // through -- and only while a gesture is actually live: gpui drops a
7435+ // drag without telling anyone, so this asks whether one is in flight
7436+ // (`App::has_active_drag`) rather than remembering that one was.
7437+ let cue = self
7438+ .snap_cue
7439+ .filter(|_| self.trim.is_some() || cx.has_active_drag())
7440+ .map(|frame| scale.px_at(f64::from(frame) / self.fps));
7055 let clips = self7441 let clips = self
7056 .session7442 .session
7057 .as_ref()7443 .as_ref()
@@ -7198,7 +7584,12 @@ impl Player {
7198 // the window, which took it from the release that fired7584 // the window, which took it from the release that fired
7199 // this (gpui window.rs:3602).7585 // this (gpui window.rs:3602).
7200 .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| {7586 .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| {
7201- let at = this.frame_under(window.mouse_position().x);7587+ // Onto the edges near it, exactly as a clip carried by
7588+ // hand lands: the line drawn while it was in flight is
7589+ // the frame it goes down on.
7590+ let x = window.mouse_position().x;
7591+ let marks = this.snap_targets(None);
7592+ let (at, _) = this.snap_to(this.frame_under(x), 0, &marks);
7202 this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx)7593 this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx)
7203 }))7594 }))
7204 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))7595 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
@@ -7207,10 +7598,21 @@ impl Player {
7207 // to -- its own included, which is the drag that moves a7598 // to -- its own included, which is the drag that moves a
7208 // take along its track.7599 // take along its track.
7209 .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| {7600 .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| {
7210- this.move_clip(drag.lane, drag.idx, lane, window.mouse_position().x, cx)7601+ // Against the lane as it is *now* ([`Player::dragged`]),
7602+ // and then snapped by `move_clip` like any other drop:
7603+ // which clip is being moved and where it lands are two
7604+ // questions, and this is the first one.
7605+ let Some(idx) = this.dragged(drag) else {
7606+ return;
7607+ };
7608+ this.move_clip(drag.lane, idx, lane, window.mouse_position().x, cx)
7211 }))7609 }))
7212 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))7610 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
7213 .children(clips.iter().enumerate().map(|(i, clip)| {7611 .children(clips.iter().enumerate().map(|(i, clip)| {
7612+ // The clip as the lane holds it, for the drag payload:
7613+ // what a drop looks itself up by has to be the placed
7614+ // clip, never the preview an edge drag is drawing.
7615+ let placed = *clip;
7214 // What a drag on an edge is showing, which is the clip7616 // What a drag on an edge is showing, which is the clip
7215 // itself while nothing is being dragged.7617 // itself while nothing is being dragged.
7216 let clip = &self.trimmed(lane, i, *clip);7618 let clip = &self.trimmed(lane, i, *clip);
@@ -7236,15 +7638,30 @@ impl Player {
7236 .unwrap_or(clip.source),7638 .unwrap_or(clip.source),
7237 );7639 );
7238 let width = scale.width_px(len);7640 let width = scale.width_px(len);
7641+ let left = scale.px_at(start);
7642+ // The slice of this box that is on the bed: where its
7643+ // name, its badge and its waveform go, so none of the
7644+ // three is drawn out at a zoomed-in box's own edges.
7645+ let (vis_x, vis_w) = visible_slice(left, width, bed);
7239 let label = sources.get(clip.source).map(|s| file_name(&s.path));7646 let label = sources.get(clip.source).map(|s| file_name(&s.path));
7240 let wave = sources7647 let wave = sources
7241 .get(clip.source)7648 .get(clip.source)
7242 .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))7649 .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
7243 .cloned();7650 .cloned();
7244- let (from, to) = (7651+ // The source seconds that slice plays -- not the clip's
7245- f64::from(clip.in_frame) / self.fps,7652+ // whole range: the envelope is drawn for the part of the
7246- f64::from(clip.out_frame) / self.fps,7653+ // box that can be seen, at the resolution of the pixels
7247- );7654+ // it actually has, and never one column per two pixels
7655+ // of a box millions of pixels wide.
7656+ let along = |x: f32| match width > 0. {
7657+ true => {
7658+ f64::from(clip.in_frame)
7659+ + f64::from(clip.out_frame - clip.in_frame)
7660+ * f64::from(x / width)
7661+ }
7662+ false => f64::from(clip.in_frame),
7663+ };
7664+ let (from, to) = (along(vis_x) / self.fps, along(vis_x + vis_w) / self.fps);
7248 let tip = tip.clone();7665 let tip = tip.clone();
7249 // What the pointer carries on the way to another lane:7666 // What the pointer carries on the way to another lane:
7250 // the file the box is showing, the same ghost a library7667 // the file the box is showing, the same ghost a library
@@ -7267,7 +7684,7 @@ impl Player {
7267 // off the left edge: the bed clips what hangs out7684 // off the left edge: the bed clips what hangs out
7268 // of it, so a half-visible clip is drawn as the7685 // of it, so a half-visible clip is drawn as the
7269 // half of itself that is on screen.7686 // half of itself that is on screen.
7270- .left(px(scale.px_at(start)))7687+ .left(px(left))
7271 .w(px(width))7688 .w(px(width))
7272 .overflow_hidden()7689 .overflow_hidden()
7273 .rounded(px(3.))7690 .rounded(px(3.))
@@ -7288,9 +7705,14 @@ impl Player {
7288 // starts the drag still selects, so picking a clip7705 // starts the drag still selects, so picking a clip
7289 // up and putting it back down where it was is7706 // up and putting it back down where it was is
7290 // exactly a click.7707 // exactly a click.
7291- .on_drag(ClipDrag { lane, idx: i }, move |_, _, _, cx| {7708+ .on_drag(
7292- cx.new(|_| Tip(ghost.clone()))7709+ ClipDrag {
7293- })7710+ lane,
7711+ idx: i,
7712+ clip: placed,
7713+ },
7714+ move |_, _, _, cx| cx.new(|_| Tip(ghost.clone())),
7715+ )
7294 .on_mouse_down(7716 .on_mouse_down(
7295 MouseButton::Left,7717 MouseButton::Left,
7296 cx.listener(move |this, event: &MouseDownEvent, _, cx| {7718 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
@@ -7349,7 +7771,7 @@ impl Player {
7349 zone7771 zone
7350 }))7772 }))
7351 // Under the label row, never through it.7773 // Under the label row, never through it.
7352- .children(wave.filter(|_| audio).and_then(|wave| {7774+ .children(wave.filter(|_| audio && vis_w > 0.).and_then(|wave| {
7353 let inner: AnyElement = match wave {7775 let inner: AnyElement = match wave {
7354 Wave::Peaks(peaks) => {7776 Wave::Peaks(peaks) => {
7355 waveform(peaks, from, to).into_any_element()7777 waveform(peaks, from, to).into_any_element()
@@ -7385,8 +7807,8 @@ impl Player {
7385 Some(7807 Some(
7386 div()7808 div()
7387 .absolute()7809 .absolute()
7388- .left_0()7810+ .left(px(vis_x))
7389- .right_0()7811+ .w(px(vis_w))
7390 .top(px(LABEL_H))7812 .top(px(LABEL_H))
7391 .bottom_0()7813 .bottom_0()
7392 .child(inner),7814 .child(inner),
@@ -7397,24 +7819,44 @@ impl Player {
7397 // cannot say whether a short clip is a trim or a7819 // cannot say whether a short clip is a trim or a
7398 // clip at 4x, and that is the difference between a7820 // clip at 4x, and that is the difference between a
7399 // cut and a re-time.7821 // cut and a re-time.
7400- .when(!clip.speed.is_normal(), |d| {7822+ // Against the right edge of what is *visible* of the
7823+ // box, not of the box: zoomed in, the box's own
7824+ // right edge is off the screen and the badge with
7825+ // it, which is a clip that stops saying it is
7826+ // speeded exactly when it is being looked at
7827+ // closely.
7828+ .when(!clip.speed.is_normal() && vis_w > 0., |d| {
7401 d.child(7829 d.child(
7402 div()7830 div()
7403 .absolute()7831 .absolute()
7404 .top_0()7832 .top_0()
7405- .right_0()7833+ .left(px(vis_x))
7406- .px(px(3.))7834+ .w(px(vis_w))
7407- .rounded(px(3.))7835+ .flex()
7408- .bg(rgb(ACCENT))7836+ .justify_end()
7409- .text_size(px(9.))7837+ .overflow_hidden()
7410- .text_color(rgb(SURFACE))7838+ .child(
7411- .child(format!("{}", clip.speed)),7839+ div()
7840+ .flex_none()
7841+ .px(px(3.))
7842+ .rounded(px(3.))
7843+ .bg(rgb(ACCENT))
7844+ .text_size(px(9.))
7845+ .text_color(rgb(SURFACE))
7846+ .child(format!("{}", clip.speed)),
7847+ ),
7412 )7848 )
7413 })7849 })
7414- .when_some(label.filter(|_| show_label(width)), |d, label| {7850+ // ...and the name sits at the left edge of the same
7851+ // slice, for the same reason: a box scrolled half
7852+ // off names itself on the half that is on screen.
7853+ .when_some(label.filter(|_| show_label(vis_w)), |d, label| {
7415 d.child(7854 d.child(
7416 div()7855 div()
7417- .relative()7856+ .absolute()
7857+ .top_0()
7858+ .left(px(vis_x))
7859+ .w(px(vis_w))
7418 .h(px(LABEL_H))7860 .h(px(LABEL_H))
7419 .px(px(4.))7861 .px(px(4.))
7420 .truncate()7862 .truncate()
@@ -7442,6 +7884,20 @@ impl Player {
7442 .bg(rgba(0x4a9effaa))7884 .bg(rgba(0x4a9effaa))
7443 }),7885 }),
7444 )7886 )
7887+ // What the gesture in flight is about to land on, drawn on
7888+ // every lane so a clip lining up with a take one track over
7889+ // can be seen to line up with it. Under the playhead's line
7890+ // and in another colour, since the two mean different
7891+ // things and often stand on the same pixel.
7892+ .children(cue.map(|x| {
7893+ div()
7894+ .absolute()
7895+ .top_0()
7896+ .h_full()
7897+ .left(px(x))
7898+ .w(px(1.))
7899+ .bg(rgb(INK))
7900+ }))
7445 // Last, so it is over the clips: the same fraction in both7901 // Last, so it is over the clips: the same fraction in both
7446 // lanes, which is the playhead being one line.7902 // lanes, which is the playhead being one line.
7447 .child(7903 .child(
@@ -7666,6 +8122,36 @@ fn eq_x(freq_hz: f32) -> f32 {
7666 ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)8122 ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)
7667 }8123 }
7668 8124
8125+/// The frequency at a fraction across the graph -- [`eq_x`] backwards, which is
8126+/// how a drag and the curve's own sample points read one. Clamped to the axis
8127+/// either way, so a pointer that leaves the box stops at 20 Hz or 20 kHz.
8128+fn eq_freq(along: f32) -> f32 {
8129+ EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along.clamp(0., 1.))
8130+}
8131+
8132+/// The band an "add" makes: a flat peak half way -- in octaves, which is what
8133+/// the log axis draws -- between the picked band and whatever sits above it, so
8134+/// a new band lands in the gap on screen rather than on top of its neighbour.
8135+/// Above the topmost band the gap is the rest of the axis.
8136+fn inserted_band(bands: &[Band], after: usize) -> Band {
8137+ let below = bands.get(after).map_or(1000., |b| b.freq_hz);
8138+ let above = bands
8139+ .iter()
8140+ .map(|b| b.freq_hz)
8141+ .filter(|f| *f > below)
8142+ .min_by(f32::total_cmp)
8143+ .unwrap_or(EQ_FREQ_HIGH);
8144+ Band {
8145+ freq_hz: (below * above).sqrt().clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH),
8146+ gain_db: 0.,
8147+ // A shade narrower than the flat-shelf 0.707 the defaults use: a band
8148+ // someone asked for is a band they mean to aim, and a wide one aimed at
8149+ // 300 Hz is really a band at everything.
8150+ q: 1.,
8151+ kind: BandKind::Peak,
8152+ }
8153+}
8154+
7669 /// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,8155 /// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,
7670 /// so a cut reads as a dip below the line it is a cut from. The inverse of8156 /// so a cut reads as a dip below the line it is a cut from. The inverse of
7671 /// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a8157 /// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a
@@ -7675,14 +8161,24 @@ fn eq_y(gain_db: f32) -> f32 {
7675 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.8161 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.
7676 }8162 }
7677 8163
8164+/// A frequency as the card writes it. Two decimals of a kHz at most, with the
8165+/// zeroes trimmed, so "1 kHz" stays "1 kHz" and a band nudged off it reads as
8166+/// 1.12 kHz rather than as the same "1 kHz" it was before the keystroke -- a
8167+/// number that does not move under an edit is worse than no number.
8168+fn eq_freq_label(freq_hz: f32) -> String {
8169+ if freq_hz < 1000. {
8170+ return format!("{freq_hz:.0} Hz");
8171+ }
8172+ let khz = format!("{:.2}", freq_hz / 1000.);
8173+ let khz = khz.trim_end_matches('0').trim_end_matches('.');
8174+ format!("{khz} kHz")
8175+}
8176+
7678 /// What a band row calls itself: the corner or centre frequency, and for a8177 /// What a band row calls itself: the corner or centre frequency, and for a
7679 /// shelf the fact that it tilts everything past it -- which is the difference8178 /// shelf the fact that it tilts everything past it -- which is the difference
7680 /// between "12 kHz" moving the last octave and moving one band inside it.8179 /// between "12 kHz" moving the last octave and moving one band inside it.
7681 fn band_label(band: &Band) -> String {8180 fn band_label(band: &Band) -> String {
7682- let freq = match band.freq_hz >= 1000. {8181+ let freq = eq_freq_label(band.freq_hz);
7683- true => format!("{:.0} kHz", band.freq_hz / 1000.),
7684- false => format!("{:.0} Hz", band.freq_hz),
7685- };
7686 match band.kind {8182 match band.kind {
7687 BandKind::LowShelf => format!("{freq} low shelf"),8183 BandKind::LowShelf => format!("{freq} low shelf"),
7688 BandKind::HighShelf => format!("{freq} high shelf"),8184 BandKind::HighShelf => format!("{freq} high shelf"),
@@ -7694,9 +8190,11 @@ fn band_label(band: &Band) -> String {
7694 /// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at8190 /// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at
7695 /// -- an audio clip has no picture, so a grade is not a thing that exists for8191 /// -- an audio clip has no picture, so a grade is not a thing that exists for
7696 /// it, whatever the editor does next -- and `No` is about the state of this8192 /// it, whatever the editor does next -- and `No` is about the state of this
7697-/// moment, which the next click of the playhead can change. Both dim their row8193+/// moment, which the next click of the playhead can change. The clip menu
7698-/// today; a menu that wants to leave the class refusals out and keep the state8194+/// leaves the class refusals *out* and dims the state ones ([`Enable::listed`]);
7699-/// ones has only to match on which of the two it got.8195+/// the actions card, which is the whole registry laid out, dims both with their
8196+/// reason -- an action missing from the one surface that lists everything would
8197+/// read as an action that does not exist.
7700 #[derive(Clone, Copy, PartialEq, Eq, Debug)]8198 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
7701 enum Enable {8199 enum Enable {
7702 Yes,8200 Yes,
@@ -7710,6 +8208,13 @@ impl Enable {
7710 self == Enable::Yes8208 self == Enable::Yes
7711 }8209 }
7712 8210
8211+ /// Whether a menu *about this clip* draws the row at all: a class refusal
8212+ /// is a thing that does not exist for what was clicked, and a row nothing
8213+ /// the user does could ever light is noise between the ones they came for.
8214+ fn listed(self) -> bool {
8215+ !matches!(self, Enable::Hidden(_))
8216+ }
8217+
7713 /// What the row says instead of its stroke, if it says anything.8218 /// What the row says instead of its stroke, if it says anything.
7714 fn why(self) -> Option<&'static str> {8219 fn why(self) -> Option<&'static str> {
7715 match self {8220 match self {
@@ -7730,6 +8235,10 @@ struct Ctx {
7730 /// and the clip-relative answers stand aside: those actions find their own8235 /// and the clip-relative answers stand aside: those actions find their own
7731 /// clip under the playhead and word their own refusal.8236 /// clip under the playhead and word their own refusal.
7732 clip: Option<(Clip, Lane)>,8237 clip: Option<(Clip, Lane)>,
8238+ /// The clip plays a still ([`engine::is_image`]), which has no sound to
8239+ /// reach at all -- not the lane's business, because a still sits on a video
8240+ /// lane exactly like a take whose sound is one lane down.
8241+ image: bool,
7733 playhead: u32,8242 playhead: u32,
7734 /// A timeline is open.8243 /// A timeline is open.
7735 timeline: bool,8244 timeline: bool,
@@ -7769,6 +8278,11 @@ fn enable(action: ActionId, ctx: Ctx) -> Enable {
7769 Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"),8278 Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"),
7770 _ => Enable::Yes,8279 _ => Enable::Yes,
7771 },8280 },
8281+ // The scan reads samples, and a still has none -- ever, unlike a video
8282+ // clip whose sound may be one lane down or simply silent. Exactly what
8283+ // `unscannable` says after the fact, said before the row is drawn so
8284+ // there is no row left to click.
8285+ ActionId::Silence if ctx.image => Enable::Hidden("this clip is a still"),
7772 // -- state: true of this clip now, and the next playhead click or the8286 // -- state: true of this clip now, and the next playhead click or the
7773 // next selection changes the answer. Splits this clip only from inside8287 // next selection changes the answer. Splits this clip only from inside
7774 // it: at either edge there is nothing to split off -- and, on a speeded8288 // it: at either edge there is nothing to split off -- and, on a speeded
@@ -8037,6 +8551,15 @@ fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<Str
8037 })8551 })
8038 }8552 }
8039 8553
8554+/// How wide the equalizer card is drawn in a window this wide: all of it bar a
8555+/// margin, up to [`EQ_W_MAX`]. The card is a graph, and a graph of twenty
8556+/// thousand hertz on 320 px spends four pixels on the octave below middle C --
8557+/// so it takes the room a big window has and stays inside a small one. Floored
8558+/// at the other cards' width, which is the last size the rows still read at.
8559+fn eq_card_w(window_w: f32) -> f32 {
8560+ (window_w - EQ_W_MARGIN).clamp(KEYS_W, EQ_W_MAX)
8561+}
8562+
8040 /// What the media list is given of the window. A share of it, so a narrow8563 /// What the media list is given of the window. A share of it, so a narrow
8041 /// window gives the panel less rather than giving the picture nothing, floored8564 /// window gives the panel less rather than giving the picture nothing, floored
8042 /// where a name stops being readable and capped at a third of the window --8565 /// where a name stops being readable and capped at a third of the window --
@@ -8965,6 +9488,97 @@ fn show_label(w: f32) -> bool {
8965 w >= LABEL_MIN_W9488 w >= LABEL_MIN_W
8966 }9489 }
8967 9490
9491+/// The clip a trim is *showing*, worked out the way `Project::trim` will write
9492+/// it: the timeline room the edge leaves is turned into source frames by the one
9493+/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from
9494+/// that. The preview and the commit are then the same arithmetic -- a box let go
9495+/// of stays where the hand left it at every rate. Assigning the timeline count
9496+/// straight to the source field, as this used to, drew a speeded clip's tail
9497+/// moving at the wrong rate (it snapped on release) and drew a *head* trim
9498+/// moving the clip's other edge, since the length it implied was not the length
9499+/// the release would commit.
9500+///
9501+/// A still grows forward from source frame 0 instead: every frame of it is the
9502+/// same picture, so there is no earlier one for an in-point to walk back to.
9503+///
9504+/// Room too narrow to hold one source frame is the edit the engine refuses, and
9505+/// the box is drawn unchanged rather than as something that will not be
9506+/// committed.
9507+fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip {
9508+ // An edge that has not moved is not an edit, and `Project::trim` refuses it
9509+ // as one: the press that starts a drag must draw the clip it pressed, not a
9510+ // clip a rounding narrower.
9511+ if to
9512+ == match edge {
9513+ Edge::Start => clip.start,
9514+ Edge::End => clip.end(),
9515+ }
9516+ {
9517+ return clip;
9518+ }
9519+ match edge {
9520+ Edge::Start => {
9521+ // What survives is measured from the *end* -- the frames that stay
9522+ // play what they always played, which is what makes this a trim.
9523+ let Some(keep) = clip.speed.fit(clip.end().saturating_sub(to)) else {
9524+ return clip;
9525+ };
9526+ match still {
9527+ true => Clip {
9528+ in_frame: 0,
9529+ out_frame: keep,
9530+ start: to,
9531+ ..clip
9532+ },
9533+ false => Clip {
9534+ in_frame: clip.out_frame - keep.min(clip.out_frame),
9535+ start: to,
9536+ ..clip
9537+ },
9538+ }
9539+ }
9540+ Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) {
9541+ Some(keep) => Clip {
9542+ out_frame: clip.in_frame + keep,
9543+ ..clip
9544+ },
9545+ None => clip,
9546+ },
9547+ }
9548+}
9549+
9550+/// Which index on its own lane a dragged clip is at *now*: the one it was picked
9551+/// up at while nothing has moved, and wherever the clip itself has slid to when
9552+/// an edit during the drag rippled the lane's indices -- a delete, an undo or a
9553+/// paste from a stroke, none of which gpui's frozen drag payload hears about.
9554+/// `None` when the clip is gone altogether, and then the drop is not an edit at
9555+/// all: moving whatever slid into its place is the one thing the hand did not
9556+/// ask for. A lane's clips are disjoint and sorted, so at most one of them can
9557+/// be the clip that was picked up.
9558+fn live_idx(clips: &[Clip], idx: usize, clip: Clip) -> Option<usize> {
9559+ match clips.get(idx) {
9560+ Some(&at) if at == clip => Some(idx),
9561+ _ => clips.iter().position(|&c| c == clip),
9562+ }
9563+}
9564+
9565+/// The part of a clip's box that is on the bed, in the box's own pixels:
9566+/// `(left, width)` of its intersection with the visible strip. Everything drawn
9567+/// *inside* a box -- its waveform, its name, its speed badge -- is placed in
9568+/// here rather than at the box's own edges, which at a deep zoom sit thousands
9569+/// of pixels off either side of the screen: a label out there is a label nobody
9570+/// can read, and a waveform out there is a path with a point per two pixels of a
9571+/// width nobody can see. A bed that has not been measured yet answers with the
9572+/// whole box, which is what was drawn before there was a bed to clip to.
9573+fn visible_slice(left: f32, width: f32, bed: f32) -> (f32, f32) {
9574+ if bed <= 0. {
9575+ return (0., width);
9576+ }
9577+ let from = (-left).clamp(0., width);
9578+ let to = (bed - left).clamp(from, width);
9579+ (from, to - from)
9580+}
9581+
8968 /// Scales an envelope to its own loudest sample, so a quietly mastered source9582 /// Scales an envelope to its own loudest sample, so a quietly mastered source
8969 /// still draws as a shape. The fixtures peak around an eighth of full scale, and9583 /// still draws as a shape. The fixtures peak around an eighth of full scale, and
8970 /// an eighth of a 30 px lane is a flat line -- which says "silent" about a file9584 /// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
@@ -8989,7 +9603,7 @@ fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f3
8989 if peaks.is_empty() || w <= 0. || h <= 0. {9603 if peaks.is_empty() || w <= 0. || h <= 0. {
8990 return Vec::new();9604 return Vec::new();
8991 }9605 }
8992- let cols = (w / WAVE_COL).ceil().max(1.) as usize;9606+ let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX);
8993 let mid = h / 2.;9607 let mid = h / 2.;
8994 (0..=cols)9608 (0..=cols)
8995 .map(|col| {9609 .map(|col| {
@@ -9242,6 +9856,56 @@ fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
9242 best.map_or(raw, |(_, start)| start)9856 best.map_or(raw, |(_, start)| start)
9243 }9857 }
9244 9858
9859+/// The edges worth landing on, off *every* lane: both ends of every clip on the
9860+/// timeline, less `skip` -- the clip being dragged, which does not snap to where
9861+/// it already is -- and less the other halves of its group, which travel with
9862+/// it. `skip` is a lane's place in `lanes` and an index into it. The playhead
9863+/// and the head of the timeline go on the end: a clip meets the cursor and the
9864+/// start of the show as readily as it meets another take.
9865+///
9866+/// All lanes rather than the one being dropped on, because a cut is made across
9867+/// the timeline: a title on V2 lines up with the shot under it, and a sound
9868+/// effect lines up with the frame it belongs to.
9869+fn snap_marks(lanes: &[&[Clip]], skip: Option<(usize, usize)>, playhead: u32) -> Vec<u32> {
9870+ let link = skip
9871+ .and_then(|(lane, idx)| lanes.get(lane)?.get(idx))
9872+ .and_then(|clip| clip.link);
9873+ let mut marks: Vec<u32> = lanes
9874+ .iter()
9875+ .enumerate()
9876+ .flat_map(|(lane, clips)| {
9877+ clips
9878+ .iter()
9879+ .enumerate()
9880+ .filter(move |&(idx, clip)| {
9881+ Some((lane, idx)) != skip && !(link.is_some() && clip.link == link)
9882+ })
9883+ .flat_map(|(_, clip)| [clip.start, clip.end()])
9884+ })
9885+ .collect();
9886+ marks.push(playhead);
9887+ marks.push(0);
9888+ marks
9889+}
9890+
9891+/// [`snapped`], and the mark that pulled it there -- the line the bed draws
9892+/// while the hand is still moving. `None` when nothing was near enough: a line
9893+/// standing over open bed would promise a landing that is not going to happen.
9894+/// The head is read before the tail, exactly as [`snapped`] prefers it.
9895+///
9896+/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and
9897+/// draws no line at all, which is the whole point of being able to turn it off.
9898+fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option<u32>) {
9899+ if !on {
9900+ return (raw, None);
9901+ }
9902+ let start = snapped(raw, len, tol, marks);
9903+ let mark = [start, start.saturating_add(len)]
9904+ .into_iter()
9905+ .find(|mark| marks.contains(mark));
9906+ (start, mark)
9907+}
9908+
9245 /// Where down an element a pointer sits, 0..1 from the top: the vertical twin9909 /// Where down an element a pointer sits, 0..1 from the top: the vertical twin
9246 /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An9910 /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
9247 /// element that was never painted reads as its middle -- flat, the one answer9911 /// element that was never painted reads as its middle -- flat, the one answer
@@ -9445,11 +10109,15 @@ fn eq_spectrum_curve(levels: Vec<f32>) -> impl IntoElement {
9445 .size_full()10109 .size_full()
9446 }10110 }
9447 10111
9448-/// The cascade's frequency response, drawn as one line across the graph.10112+/// The cascade's frequency response, drawn as one line across the graph, with
10113+/// each band's own response threaded dimly under it.
9449 ///10114 ///
9450 /// Every point comes from `EqParams::response_db`, which reads the very10115 /// Every point comes from `EqParams::response_db`, which reads the very
9451 /// coefficients the samples are filtered through: the curve cannot drift from10116 /// coefficients the samples are filtered through: the curve cannot drift from
9452-/// what is heard, because there is no second copy of the maths.10117+/// what is heard, because there is no second copy of the maths. A single band's
10118+/// thread is that same call on a cascade of one, so the two cannot disagree
10119+/// either -- and it is what makes a boost sitting inside a cut visible at all,
10120+/// where the sum alone would draw a flat line and say nothing.
9453 ///10121 ///
9454 /// ponytail: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the10122 /// ponytail: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the
9455 /// curve then rides the edge of the box; upgrade = a wider dB axis with the10123 /// curve then rides the edge of the box; upgrade = a wider dB axis with the
@@ -9459,16 +10127,37 @@ fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement {
9459 |_, _, _| (),10127 |_, _, _| (),
9460 move |bounds, _, window, _| {10128 move |bounds, _, window, _| {
9461 let (o, s) = (bounds.origin, bounds.size);10129 let (o, s) = (bounds.origin, bounds.size);
9462- let points: Vec<_> = (0..=EQ_CURVE_STEPS)10130+ let line = |of: &EqParams| -> Vec<_> {
9463- .map(|step| {10131+ (0..=EQ_CURVE_STEPS)
9464- let along = step as f32 / EQ_CURVE_STEPS as f32;10132+ .map(|step| {
9465- let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along);10133+ let along = step as f32 / EQ_CURVE_STEPS as f32;
9466- point(10134+ point(
9467- o.x + s.width * along,10135+ o.x + s.width * along,
9468- o.y + s.height * eq_y(params.response_db(freq, sample_rate)),10136+ o.y + s.height
9469- )10137+ * eq_y(of.response_db(eq_freq(along), sample_rate)),
10138+ )
10139+ })
10140+ .collect()
10141+ };
10142+ // One thread per band, first, so the sum is drawn over them.
10143+ for band in &params.bands {
10144+ let mut bell = PathBuilder::stroke(px(1.));
10145+ for (step, at) in line(&EqParams {
10146+ bands: vec![*band],
9470 })10147 })
9471- .collect();10148+ .into_iter()
10149+ .enumerate()
10150+ {
10151+ match step {
10152+ 0 => bell.move_to(at),
10153+ _ => bell.line_to(at),
10154+ }
10155+ }
10156+ if let Ok(bell) = bell.build() {
10157+ window.paint_path(bell, rgba(EQ_BELL_INK));
10158+ }
10159+ }
10160+ let points = line(&params);
9472 // The area between the curve and 0 dB, closed along that line: a10161 // The area between the curve and 0 dB, closed along that line: a
9473 // boost and a cut wind opposite ways around it, which is exactly10162 // boost and a cut wind opposite ways around it, which is exactly
9474 // what makes both of them fill and the flat parts stay empty.10163 // what makes both of them fill and the flat parts stay empty.
@@ -9570,28 +10259,32 @@ fn timecode(t: f64, fps: f64) -> String {
9570 #[cfg(test)]10259 #[cfg(test)]
9571 mod tests {10260 mod tests {
9572 use super::{10261 use super::{
9573- ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx,10262+ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, EQ_BANDS_MAX,
9574- EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,10263+ EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H,
9575- EQ_SPECTRUM_DB, EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,10264+ EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE,
10265+ EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,
9576 Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,10266 Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,
9577 INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,10267 INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
9578 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,10268 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,
9579 MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,10269 MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,
9580 SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,10270 SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,
9581- Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, band_label, bitrate_refusal,10271+ Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label,
9582- can_add, cancels_export, clipboard_after_remove, color_snap, containers, enable, envelope,10272+ bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, containers,
9583- eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key,10273+ enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,
10274+ estimated_mb, export_path, export_settings, format_key,
9584 format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram,10275 format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram,
9585- is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at, next_container,10276+ inserted_band, is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at,
10277+ next_container,
9586 normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due,10278 normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due,
9587- show_label, silence_rate, snapped, source_tint, span_partner, speed_at, summary_head,10279+ show_label, silence_rate, snap_cue, snap_marks, snapped, source_tint, span_partner,
9588- summary_tail, timecode, transport, unseen_paths, unseen_sources, whole_take, window_title,10280+ speed_at, summary_head, summary_tail, timecode, transport, unseen_paths, unseen_sources,
10281+ whole_take, window_title,
9589 };10282 };
9590 use super::{10283 use super::{
9591- Choice, FITS, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, Scale, View, ZOOM_MAX_SECONDS,10284+ Choice, Edge, FITS, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, Scale, View,
9592- ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, fit_choices, library_rows, next_fit,10285+ ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, fit_choices,
9593- next_resolution, px_along, repeats, resolution_choices, resolution_ladder, span_label,10286+ library_rows, live_idx, next_fit, next_resolution, px_along, repeats, resolution_choices,
9594- unscannable,10287+ resolution_ladder, span_label, trimmed_clip, unscannable, visible_slice,
9595 };10288 };
9596 10289
9597 /// What the file manager is handed: the parts a path keeps as they are, and10290 /// What the file manager is handed: the parts a path keeps as they are, and
@@ -9954,37 +10647,121 @@ mod tests {
9954 // clip wherever the playhead is, dimmed on a waveform.10647 // clip wherever the playhead is, dimmed on a waveform.
9955 assert!(offered(&clip, v1, ActionId::Color, 0));10648 assert!(offered(&clip, v1, ActionId::Color, 0));
9956 assert!(!offered(&clip, a1, ActionId::Color, 60));10649 assert!(!offered(&clip, a1, ActionId::Color, 60));
9957- // The two kinds of no, which is what the row can be told apart by: a10650+ // The two kinds of no, which is what the row is told apart by: a grade
9958- // grade on a waveform is a *class* answer -- an audio clip has no10651+ // on a waveform is a *class* answer -- an audio clip has no picture and
9959- // picture and never will, so a menu may leave the item out -- where a10652+ // never will, so the menu leaves the item out entirely -- where a cut at
9960- // cut at the clip's edge is this moment's answer and the next click of10653+ // the clip's edge is this moment's answer and the next click of the
9961- // the playhead changes it, so that one is dimmed and stays.10654+ // playhead changes it, so that one is drawn, dimmed, and says why.
9962- assert!(matches!(10655+ //
9963- on(&clip, a1, ActionId::Color, 60),10656+ // What the menu draws for a clip of each kind, in order: the render
9964- Enable::Hidden(_)10657+ // loop's `continue`, as a list.
9965- ));10658+ let menu = |lane, image, playhead| {
9966- assert!(matches!(10659+ MENU_ITEMS
9967- on(&clip, a1, ActionId::Fit, 60),10660+ .into_iter()
9968- Enable::Hidden(_)10661+ .filter(|&action| {
9969- ));10662+ enable(
9970- assert!(matches!(10663+ action,
9971- on(&clip, v1, ActionId::Equalizer, 60),10664+ Ctx {
9972- Enable::Hidden(_)10665+ clip: Some((clip, lane)),
9973- ));10666+ image,
10667+ playhead,
10668+ timeline: true,
10669+ ..Ctx::default()
10670+ },
10671+ )
10672+ .listed()
10673+ })
10674+ .collect::<Vec<_>>()
10675+ };
10676+ // Sound: no grade and no fit policy, and the equalizer that is the
10677+ // whole reason an audio clip has a menu of its own.
10678+ let sound = menu(a1, false, 60);
10679+ assert!(!sound.contains(&ActionId::Color), "{sound:?}");
10680+ assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
10681+ assert!(sound.contains(&ActionId::Equalizer));
10682+ assert!(sound.contains(&ActionId::Silence));
10683+ // Picture: the mirror of it. The sound of a take is the audio lane's,
10684+ // clip for clip, so the equalizer is not this clip's business -- but the
10685+ // silence scan is, because it opens on the half it is grouped with.
10686+ let picture = menu(v1, false, 60);
10687+ assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
10688+ assert!(picture.contains(&ActionId::Color));
10689+ assert!(picture.contains(&ActionId::Fit));
10690+ assert!(picture.contains(&ActionId::Silence));
10691+ // A still: picture with no sound anywhere, ever. Graded, fitted and
10692+ // re-timed like any other clip (a speed reaches a still through the same
10693+ // rewrite), scanned like none.
10694+ let still = menu(v1, true, 60);
10695+ assert!(!still.contains(&ActionId::Silence), "{still:?}");
10696+ assert!(!still.contains(&ActionId::Equalizer), "{still:?}");
10697+ assert!(still.contains(&ActionId::Color));
10698+ assert!(still.contains(&ActionId::Fit));
10699+ assert!(still.contains(&ActionId::Speed));
10700+ // ...and the state refusals are on all three, dimmed rather than gone:
10701+ // at 30 the playhead is on this clip's head, where a cut has nothing to
10702+ // split off -- a row the next click of the playhead lights.
10703+ for rows in [menu(a1, false, 30), menu(v1, false, 30), menu(v1, true, 30)] {
10704+ assert!(rows.contains(&ActionId::Cut), "{rows:?}");
10705+ assert!(rows.contains(&ActionId::Detach), "{rows:?}");
10706+ }
10707+ // The actions card is the other half of the rule: it lists the whole
10708+ // registry, so a class refusal is dimmed there with its reason and never
10709+ // dropped -- an action missing from the one surface that lists
10710+ // everything would read as an action that does not exist.
10711+ let listed: Vec<ActionId> = keys_rows()
10712+ .into_iter()
10713+ .filter_map(|r| match r {
10714+ KeyRow::Act(action) => Some(action),
10715+ _ => None,
10716+ })
10717+ .collect();
10718+ for (lane, action) in [
10719+ (a1, ActionId::Color),
10720+ (a1, ActionId::Fit),
10721+ (v1, ActionId::Equalizer),
10722+ ] {
10723+ assert!(matches!(on(&clip, lane, action, 60), Enable::Hidden(_)));
10724+ assert!(listed.contains(&action), "{action:?} left the actions card");
10725+ assert!(on(&clip, lane, action, 60).why().is_some());
10726+ }
9974 assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_)));10727 assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_)));
9975 assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_)));10728 assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_)));
9976 assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_)));10729 assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_)));
9977 // Every refusal says something, and says it short enough to sit in the10730 // Every refusal says something, and says it short enough to sit in the
9978- // menu's right-hand column beside a label.10731+ // menu's right-hand column beside a label -- the still's included, which
10732+ // the card dims with while the menu leaves the row out.
9979 for action in MENU_ITEMS {10733 for action in MENU_ITEMS {
9980- for lane in [v1, a1] {10734+ for (lane, image) in [(v1, false), (a1, false), (v1, true)] {
9981 for playhead in [0, 30, 60, 90] {10735 for playhead in [0, 30, 60, 90] {
9982- if let Some(why) = on(&clip, lane, action, playhead).why() {10736+ let refusal = enable(
10737+ action,
10738+ Ctx {
10739+ clip: Some((clip, lane)),
10740+ image,
10741+ playhead,
10742+ timeline: true,
10743+ ..Ctx::default()
10744+ },
10745+ );
10746+ if let Some(why) = refusal.why() {
9983 assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}");10747 assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}");
9984 }10748 }
9985 }10749 }
9986 }10750 }
9987 }10751 }
10752+ assert!(matches!(
10753+ enable(
10754+ ActionId::Silence,
10755+ Ctx {
10756+ clip: Some((clip, v1)),
10757+ image: true,
10758+ playhead: 60,
10759+ timeline: true,
10760+ ..Ctx::default()
10761+ }
10762+ ),
10763+ Enable::Hidden(_)
10764+ ));
9988 // The editor as a whole, which is how the actions card asks: with no10765 // The editor as a whole, which is how the actions card asks: with no
9989 // timeline nothing is offered, an export leaves only its own cancel,10766 // timeline nothing is offered, an export leaves only its own cancel,
9990 // and the three that act on the marked clip say so when none is.10767 // and the three that act on the marked clip say so when none is.
@@ -10090,6 +10867,10 @@ mod tests {
10090 "{action:?} is reachable by keyboard only"10867 "{action:?} is reachable by keyboard only"
10091 );10868 );
10092 }10869 }
10870+ // The snap has a door of its own as well as its row on the card: the
10871+ // button beside the zoom, which says which way it is set as well as
10872+ // setting it.
10873+ assert!(element("snap"), "no snap button beside the zoom");
10093 // And the card is a door the pointer can open: the panel's own button.10874 // And the card is a door the pointer can open: the panel's own button.
10094 assert!(element("keys"), "no way to open the actions card");10875 assert!(element("keys"), "no way to open the actions card");
10095 // The card-local strokes have the same rule, and each of them is a thing10876 // The card-local strokes have the same rule, and each of them is a thing
@@ -10231,11 +11012,12 @@ mod tests {
10231 // Silent like the engine suite: this opens the real device.11012 // Silent like the engine suite: this opens the real device.
10232 session.set_gain(0.0);11013 session.set_gain(0.0);
10233 assert_eq!(session.sources().len(), 1);11014 assert_eq!(session.sources().len(), 1);
10234- // 640x360 would join now (the project canvas places it); this file is11015+ // 640x360 joins now (the project canvas places it), and so does a file
10235- // also silent, and a silent file cannot join a timeline with sound.11016+ // with no sound (it plays silence over its span). What is left is one
11017+ // output device: a mono track cannot join a stereo timeline.
10236 let refusal = session11018 let refusal = session
10237- .import(&asset("test_mismatch.mp4"))11019+ .import(&asset("test_ac3.mp4"))
10238- .expect_err("a silent file must not join a timeline with audio")11020+ .expect_err("a mono track must not join a stereo timeline")
10239 .to_string();11021 .to_string();
10240 assert!(refusal.contains("audio"), "refusal must name it: {refusal}");11022 assert!(refusal.contains("audio"), "refusal must name it: {refusal}");
10241 assert_eq!(session.sources().len(), 1, "a refusal added a row");11023 assert_eq!(session.sources().len(), 1, "a refusal added a row");
@@ -10772,6 +11554,62 @@ mod tests {
10772 assert_eq!(snapped(2, 40, 4, &marks), 0);11554 assert_eq!(snapped(2, 40, 4, &marks), 0);
10773 }11555 }
10774 11556
11557+ /// Where those edges come from: every lane, not the one being dropped on --
11558+ /// and never the clip in the hand or the half of it one track down.
11559+ #[test]
11560+ fn the_marks_are_every_lane_the_playhead_and_the_start() {
11561+ let clip = |start: u32, frames: u32, link| Clip {
11562+ start,
11563+ in_frame: 0,
11564+ out_frame: frames,
11565+ source: 0,
11566+ link,
11567+ eq: None,
11568+ color: None,
11569+ fit: Default::default(),
11570+ speed: Default::default(),
11571+ };
11572+ // A grouped take across two lanes at 100..160, and a lone one on the
11573+ // audio lane at 400..430.
11574+ let video = [clip(100, 60, Some(7))];
11575+ let audio = [clip(100, 60, Some(7)), clip(400, 30, None)];
11576+ let lanes: [&[Clip]; 2] = [&video, &audio];
11577+
11578+ // Nothing in the hand: both lanes' edges, the playhead, and 0.
11579+ let mut all = snap_marks(&lanes, None, 300);
11580+ all.sort_unstable();
11581+ assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]);
11582+
11583+ // The video half in the hand: its own edges are gone, and so are its
11584+ // group's on the other lane -- both boxes travel with the drag. The
11585+ // lone audio clip is still a target, which is the whole point: a take
11586+ // being carried on V1 lands flush with a sound on A1.
11587+ let mut carried = snap_marks(&lanes, Some((0, 0)), 300);
11588+ carried.sort_unstable();
11589+ assert_eq!(carried, [0, 300, 400, 430]);
11590+
11591+ // An index that names no clip skips nothing and still answers.
11592+ assert_eq!(snap_marks(&[], Some((3, 9)), 0), [0, 0]);
11593+ }
11594+
11595+ /// The line the bed draws, and the switch that turns the whole thing off.
11596+ #[test]
11597+ fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() {
11598+ let marks = [100, 160, 300, 0];
11599+ // Pulled by the tail: the clip lands at 60 and the line stands on the
11600+ // edge its *tail* met, 100 -- not on the head it happens to have.
11601+ assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100)));
11602+ // Pulled by the head: line and landing are the same frame.
11603+ assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160)));
11604+ // A trim carries no length, so only its own edge lands.
11605+ assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300)));
11606+ // Open bed: nothing moves and nothing is drawn.
11607+ assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None));
11608+ // Switched off, a gesture that would have snapped lands raw and draws
11609+ // no line -- the frame-by-frame placement the toggle is for.
11610+ assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));
11611+ }
11612+
10775 #[test]11613 #[test]
10776 fn timecode_counts_frames_inside_the_second() {11614 fn timecode_counts_frames_inside_the_second() {
10777 assert_eq!(timecode(0., 30.), "00:00:00:00");11615 assert_eq!(timecode(0., 30.), "00:00:00:00");
@@ -11352,6 +12190,9 @@ mod tests {
11352 "12 kHz high shelf"12190 "12 kHz high shelf"
11353 ]12191 ]
11354 );12192 );
12193+ // A band moved off a round number reads as where it *is*: a keystroke
12194+ // that changes the filter and not the number on the card is a keystroke
12195+ // nobody can aim.
11355 assert_eq!(12196 assert_eq!(
11356 band_label(&Band {12197 band_label(&Band {
11357 freq_hz: 2600.,12198 freq_hz: 2600.,
@@ -11359,23 +12200,38 @@ mod tests {
11359 q: 1.,12200 q: 1.,
11360 kind: BandKind::Peak12201 kind: BandKind::Peak
11361 }),12202 }),
11362- "3 kHz",12203+ "2.6 kHz"
11363- "rounded, because a band label is not a measurement"12204+ );
12205+ assert_eq!(eq_freq_label(1122.), "1.12 kHz");
12206+ assert_eq!(eq_freq_label(12000.), "12 kHz", "no zeroes to read past");
12207+ assert_eq!(eq_freq_label(80.), "80 Hz");
12208+
12209+ // The card fits the smallest window and takes the room a bigger one has
12210+ // -- it is a graph, and the width *is* the frequency resolution.
12211+ assert!(eq_card_w(640.) <= 640. - 24., "card too wide for 640");
12212+ assert!(eq_card_w(1280.) > eq_card_w(640.), "card ignores the window");
12213+ assert_eq!(eq_card_w(1920.), EQ_W_MAX, "card grows without end");
12214+ assert!(eq_card_w(320.) >= KEYS_W, "card narrower than a row of text");
12215+ // At the smallest window the graph is still a graph: three across for
12216+ // one down, so an octave is wide enough to put a handle in.
12217+ assert!(
12218+ eq_card_w(640.) - 24. >= 3. * EQ_GRAPH_H,
12219+ "graph too square to aim at"
11364 );12220 );
11365 12221
11366 // The same shape as the other two cards, so it fits where they do: the12222 // The same shape as the other two cards, so it fits where they do: the
11367 // graph stands where the export card's rows do, and is shorter than12223 // graph stands where the export card's rows do, and is shorter than
11368- // they are.12224+ // they are. The numbers row is a row of buttons now, so it is one of
11369- let (title, status, readout, gaps, padding) = (17., 28., 17., 4. * 2., 24.);12225+ // those tall rather than one line of text.
12226+ let (title, status, gaps, padding) = (17., 28., 4. * 2., 24.);
11370 assert!(12227 assert!(
11371- title + status + EQ_GRAPH_H + readout + gaps + padding + CONTROL_H <= 360.,12228+ title + status + EQ_GRAPH_H + HIT_MIN + gaps + padding + CONTROL_H <= 360.,
11372 "card too tall"12229 "card too tall"
11373 );12230 );
11374 assert!(12231 assert!(
11375 EQ_GRAPH_H <= EXPORT_ROWS_H,12232 EQ_GRAPH_H <= EXPORT_ROWS_H,
11376 "graph taller than a card of rows"12233 "graph taller than a card of rows"
11377 );12234 );
11378- assert!(KEYS_W <= 640., "card too wide");
11379 // What is dragged is the whole graph -- the handle is a 10 px dot, but12235 // What is dragged is the whole graph -- the handle is a 10 px dot, but
11380 // a press anywhere in the box takes the band nearest it -- so WCAG12236 // a press anywhere in the box takes the band nearest it -- so WCAG
11381 // 2.5.8 is satisfied by the box, which is far past the minimum.12237 // 2.5.8 is satisfied by the box, which is far past the minimum.
@@ -11387,6 +12243,83 @@ mod tests {
11387 assert!(KEYS_ROW_H >= HIT_MIN);12243 assert!(KEYS_ROW_H >= HIT_MIN);
11388 }12244 }
11389 12245
12246+ /// Editing a band, which is what the card is *for*: the pointer reads a
12247+ /// frequency off the axis the same way the axis draws one, a new band lands
12248+ /// in the gap beside the picked one rather than on top of it, and every band
12249+ /// the card will hold has a digit that picks it.
12250+ #[test]
12251+ fn a_band_can_be_moved_added_and_reached() {
12252+ use engine::eq::{Band, BandKind, EqParams};
12253+ // Across the graph and back: a drag sets the frequency the handle is
12254+ // then drawn at, so the two mappings have to be one another's inverse or
12255+ // the handle walks away from the pointer.
12256+ for freq in [20., 80., 250., 1000., 4000., 12000., 20000.] {
12257+ let read = eq_freq(eq_x(freq));
12258+ assert!(
12259+ (read / freq - 1.).abs() < 1e-3,
12260+ "{freq} Hz read back as {read}"
12261+ );
12262+ }
12263+ // Off the box either end stops at the axis, never past it.
12264+ assert_eq!(eq_freq(-1.), EQ_FREQ_LOW);
12265+ assert_eq!(eq_freq(2.), EQ_FREQ_HIGH);
12266+
12267+ // A step of the frequency keys is a real move on screen -- a keystroke
12268+ // that changes nothing visible is a keystroke that reads as broken --
12269+ // and small enough to aim with.
12270+ let step = eq_x(1000. * EQ_FREQ_STEP) - eq_x(1000.);
12271+ assert!(step > 0.01 && step < 0.06, "frequency key steps {step}");
12272+
12273+ // A new band lands between the picked one and the next one up, in
12274+ // octaves: 250 Hz and 1 kHz put it at 500, which is a gap on screen.
12275+ let bands = EqParams::default_layout().bands;
12276+ let added = inserted_band(&bands, 1);
12277+ assert!((added.freq_hz - 500.).abs() < 1., "landed at {added:?}");
12278+ assert_eq!(added.gain_db, 0., "a new band changes nothing until moved");
12279+ assert_eq!(added.kind, BandKind::Peak, "a new band is not a shelf");
12280+ assert!(eq_x(added.freq_hz) - eq_x(bands[1].freq_hz) > 0.1);
12281+ // Above the topmost band the gap is the rest of the axis, and the band
12282+ // still lands on it rather than off the end.
12283+ let top = inserted_band(&bands, bands.len() - 1);
12284+ assert!(
12285+ top.freq_hz > bands[4].freq_hz && top.freq_hz <= EQ_FREQ_HIGH,
12286+ "landed at {top:?}"
12287+ );
12288+ // Bands out of frequency order (a drag may cross two over) still get a
12289+ // sane neighbour: the next one *up*, not the next one along the list.
12290+ let crossed = vec![
12291+ Band {
12292+ freq_hz: 4000.,
12293+ gain_db: 0.,
12294+ q: 1.,
12295+ kind: BandKind::Peak,
12296+ },
12297+ Band {
12298+ freq_hz: 100.,
12299+ gain_db: 0.,
12300+ q: 1.,
12301+ kind: BandKind::Peak,
12302+ },
12303+ ];
12304+ let between = inserted_band(&crossed, 1);
12305+ assert!(
12306+ (between.freq_hz - 632.).abs() < 2.,
12307+ "landed at {between:?}, not between 100 and 4000"
12308+ );
12309+
12310+ // Every band the card will hold is one digit away: the keyboard has ten
12311+ // digits, which is exactly why the cap is what it is.
12312+ assert!(
12313+ EQ_BANDS_MAX <= 10,
12314+ "a band past the tenth has no key that picks it"
12315+ );
12316+ assert!(EQ_BANDS_MAX > EqParams::default_layout().bands.len());
12317+ // The Q range holds the default, so a file's band never opens out of
12318+ // range and needs dragging back in before it can be edited.
12319+ assert!((EQ_Q_LOW..=EQ_Q_HIGH).contains(&0.707));
12320+ assert!(EQ_Q_STEP > 1.);
12321+ }
12322+
11390 /// The analyser drawn behind the curve: a tone has to land on its own12323 /// The analyser drawn behind the curve: a tone has to land on its own
11391 /// frequency, or the backdrop is a decoration rather than a reading of what12324 /// frequency, or the backdrop is a decoration rather than a reading of what
11392 /// is playing -- and someone shaping a band against it would be aiming at12325 /// is playing -- and someone shaping a band against it would be aiming at
@@ -12479,6 +13412,141 @@ mod tests {
12479 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());13412 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
12480 }13413 }
12481 13414
13415+ /// A box laid out wider than any screen -- a long clip at a deep zoom -- is
13416+ /// still one screen's worth of columns: the path a repaint has to build is
13417+ /// bounded by what can be seen, not by what the layout says the box is.
13418+ /// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points
13419+ /// per frame, and the repaint that stalls on it is the waveform that
13420+ /// "disappeared".
13421+ #[test]
13422+ fn an_envelope_never_costs_more_points_than_a_screen_can_show() {
13423+ let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect();
13424+ // The width a 5 s clip is laid out at when the bed shows 8 frames of it.
13425+ let huge = 5. * 30. / 8. * 1200.;
13426+ let cols = envelope(&peaks, 0., 5., huge, 30.);
13427+ assert!(
13428+ cols.len() <= WAVE_COLS_MAX + 1,
13429+ "{} columns for a {huge} px box",
13430+ cols.len()
13431+ );
13432+ // ...and the slice actually painted is the part of the box on the bed,
13433+ // which is where that width stops mattering: a column per two visible
13434+ // pixels, at every zoom.
13435+ let (x, w) = visible_slice(-huge / 2., huge, 1200.);
13436+ assert_eq!((x, w), (huge / 2., 1200.));
13437+ assert_eq!(envelope(&peaks, 0., 5., w, 30.).len(), 601);
13438+ // A box entirely off the bed has no slice, and one that has never been
13439+ // measured is drawn whole -- what was drawn before there was a bed.
13440+ assert_eq!(visible_slice(2000., 500., 1200.), (0., 0.));
13441+ assert_eq!(visible_slice(-3000., 500., 1200.), (500., 0.));
13442+ assert_eq!(visible_slice(-40., 500., 0.), (0., 500.));
13443+ // Half on, at either edge.
13444+ assert_eq!(visible_slice(-100., 500., 1200.), (100., 400.));
13445+ assert_eq!(visible_slice(1000., 500., 1200.), (0., 200.));
13446+ }
13447+
13448+ /// The box a trim draws is the box its release commits, at every speed. The
13449+ /// preview used to hand the *timeline* frame count to a source-frame field:
13450+ /// at 2x a tail moved twice as fast as the pointer and snapped back on
13451+ /// release, and a head drag moved the clip's other edge.
13452+ #[test]
13453+ fn a_trim_preview_lands_where_the_release_commits() {
13454+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
13455+ session.set_gain(0.0);
13456+ for permille in SPEED_PRESETS {
13457+ // Live, so the loop owes it no undo step: the speeds are the axis
13458+ // this walks, and the trims below are what is undone.
13459+ session
13460+ .set_speed_live(Lane::V1, 0, Speed::from_permille(permille))
13461+ .expect("a clip alone on its lane may be speeded");
13462+ for edge in [Edge::Start, Edge::End] {
13463+ let clip = session.lane_clips(Lane::V1)[0];
13464+ let (lo, hi) = session
13465+ .trim_room(Lane::V1, 0, edge)
13466+ .expect("clip 0 is there");
13467+ // Both walls and the middle of the room: the whole range a
13468+ // pointer can be clamped to.
13469+ for to in [lo, (lo + hi) / 2, hi] {
13470+ let preview = trimmed_clip(clip, edge, to, false);
13471+ // The drag is one edit and one undo step, so the next `to`
13472+ // is measured from the same clip this one was.
13473+ if session.trim_clip(Lane::V1, 0, edge, to) {
13474+ assert_eq!(
13475+ preview,
13476+ session.lane_clips(Lane::V1)[0],
13477+ "{edge:?} to {to} at {permille} per mille"
13478+ );
13479+ assert!(session.undo(), "the trim is one undo step");
13480+ } else {
13481+ // An edge already where it was asked to go is not an
13482+ // edit, and the preview draws the clip unchanged.
13483+ assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille");
13484+ }
13485+ assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
13486+ }
13487+ }
13488+ }
13489+ }
13490+
13491+ /// A still trims the same way, and the preview knows it: its head grows
13492+ /// forward from source frame 0 -- every frame of it is the same picture --
13493+ /// so the box stretches instead of sliding left.
13494+ #[test]
13495+ fn a_stills_trim_preview_grows_forward_like_the_commit() {
13496+ let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens");
13497+ for edge in [Edge::Start, Edge::End] {
13498+ let clip = session.lane_clips(Lane::V1)[0];
13499+ let (lo, hi) = session
13500+ .trim_room(Lane::V1, 0, edge)
13501+ .expect("clip 0 is there");
13502+ for to in [lo, (lo + hi) / 2, hi] {
13503+ let preview = trimmed_clip(clip, edge, to, true);
13504+ match session.trim_clip(Lane::V1, 0, edge, to) {
13505+ true => {
13506+ assert_eq!(
13507+ preview,
13508+ session.lane_clips(Lane::V1)[0],
13509+ "a still {edge:?} to {to}"
13510+ );
13511+ assert!(session.undo(), "the trim is one undo step");
13512+ }
13513+ false => assert_eq!(preview, clip, "a still {edge:?} to {to}"),
13514+ }
13515+ assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
13516+ }
13517+ }
13518+ }
13519+
13520+ /// gpui freezes a drag's payload for the whole gesture, and nothing stops a
13521+ /// stroke from editing the lane under it: the drop has to find the clip that
13522+ /// was picked up, not whatever slid into its index.
13523+ #[test]
13524+ fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() {
13525+ let at = |start: u32| Clip {
13526+ start,
13527+ in_frame: 0,
13528+ out_frame: 30,
13529+ source: 0,
13530+ link: None,
13531+ eq: None,
13532+ color: None,
13533+ fit: FitPolicy::Fit,
13534+ speed: Speed::NORMAL,
13535+ };
13536+ let lane = [at(0), at(30), at(60)];
13537+ let dragged = lane[2];
13538+ assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved");
13539+ // A delete in front of it: the clip is now index 1, and the index the
13540+ // drag froze names a clip nobody grabbed.
13541+ let after = [at(0), at(60)];
13542+ assert_eq!(live_idx(&after, 2, dragged), Some(1));
13543+ assert_eq!(live_idx(&after, 1, dragged), Some(1));
13544+ // Deleted mid-drag: there is nothing to move, and moving its neighbour
13545+ // instead is exactly the bug this exists for.
13546+ assert_eq!(live_idx(&[at(0)], 2, dragged), None);
13547+ assert_eq!(live_idx(&[], 0, dragged), None);
13548+ }
13549+
12482 #[test]13550 #[test]
12483 fn a_quiet_source_still_draws_as_a_shape() {13551 fn a_quiet_source_still_draws_as_a_shape() {
12484 // An eighth of full scale, which is about where the fixtures sit.13552 // An eighth of full scale, which is about where the fixtures sit.
@@ -12827,6 +13895,8 @@ fn main() {
12827 scrubbing: false,13895 scrubbing: false,
12828 trim: None,13896 trim: None,
12829 grab: 0,13897 grab: 0,
13898+ snap: true,
13899+ snap_cue: None,
12830 last_scrub: Instant::now(),13900 last_scrub: Instant::now(),
12831 last_target: 0,13901 last_target: 0,
12832 export: None,13902 export: None,
crates/engine/src/audio.rsmodified+116 -65
@@ -203,10 +203,14 @@ impl AudioSession {
203 /// pause — the master clock counts what the device has been fed, so a hole203 /// pause — the master clock counts what the device has been fed, so a hole
204 /// that fed nothing would stall the whole timeline on it.204 /// that fed nothing would stall the whole timeline on it.
205 ///205 ///
206+ /// A segment naming a source that has **no track** is the same silence: a
207+ /// clip of a silent file is a hole with a picture over it, and the timeline
208+ /// let it in on exactly that footing ([`crate::PlaybackSession::import`]).
209+ ///
206 /// Only the sources some segment names are opened. `Ok(None)` when `sources`210 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
207- /// is empty or its first entry has no AAC track; a later source that is211+ /// is empty or its first entry has no AAC track; a later source that
208- /// missing audio or disagrees on rate/layout is an `Err` — import refuses212+ /// disagrees on rate/layout is an `Err` — import refuses those up front (one
209- /// those up front (one timeline, one output device), this is the backstop.213+ /// timeline, one output device), this is the backstop.
210 pub fn open_multi_segments(214 pub fn open_multi_segments(
211 sources: &[PathBuf],215 sources: &[PathBuf],
212 segs: &[(Option<usize>, f64, f64)],216 segs: &[(Option<usize>, f64, f64)],
@@ -294,11 +298,18 @@ impl AudioSession {
294 first.check_decoder()?;298 first.check_decoder()?;
295 299
296 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();300 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
301+ // ...and which of them turned out to have no track at all, so a silent
302+ // source is opened once like any other rather than once per segment
303+ // naming it.
304+ let mut silent: Vec<bool> = sources.iter().map(|_| false).collect();
297 tracks[at] = Some(first);305 tracks[at] = Some(first);
298 for &(source, ..) in segs {306 for &(source, ..) in segs {
299 let Some(source) = source else {307 let Some(source) = source else {
300 continue; // a gap opens no file308 continue; // a gap opens no file
301 };309 };
310+ if silent.get(source) == Some(&true) {
311+ continue;
312+ }
302 let slot = tracks313 let slot = tracks
303 .get_mut(source)314 .get_mut(source)
304 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;315 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;
@@ -306,8 +317,14 @@ impl AudioSession {
306 continue; // already opened, and the checks below already ran317 continue; // already opened, and the checks below already ran
307 }318 }
308 let (path, stream) = &sources[source];319 let (path, stream) = &sources[source];
309- let track = Track::open(path, *stream)?320+ // A source with no audio track at all is not a failure: its
310- .ok_or_else(|| format!("source {source} has no audio track"))?;321+ // segments are silence, exactly as a gap's are, and the slot stays
322+ // empty to say so. That is what a silent clip on an audio lane
323+ // means -- a picture over a hole.
324+ let Some(track) = Track::open(path, *stream)? else {
325+ silent[source] = true;
326+ continue;
327+ };
311 if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {328 if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {
312 return Err(format!(329 return Err(format!(
313 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",330 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",
@@ -324,14 +341,15 @@ impl AudioSession {
324 341
325 let segments: Vec<Segment> = segs342 let segments: Vec<Segment> = segs
326 .iter()343 .iter()
327- .map(|&(source, start_secs, end_secs)| match source {344+ // A gap, and a source with no track to decode, are the same stretch
328- Some(source) => tracks[source]345+ // of nothing: as many frames of silence as the window is long.
329- .as_ref()346+ .map(|&(source, start_secs, end_secs)| {
330- .expect("opened above")347+ match source.and_then(|source| Some((source, tracks[source].as_ref()?))) {
331- .segment(source, start_secs, end_secs),348+ Some((source, track)) => track.segment(source, start_secs, end_secs),
332- None => Segment::silence(349+ None => Segment::silence(
333- ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,350+ ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
334- ),351+ ),
352+ }
335 })353 })
336 .collect();354 .collect();
337 // Chunk numbering is continuous across every join, counted from the first355 // Chunk numbering is continuous across every join, counted from the first
@@ -622,7 +640,11 @@ impl AudioSession {
622 decodable: matches!(track.channels, 1 | 2),640 decodable: matches!(track.channels, 1 | 2),
623 }]);641 }]);
624 }642 }
625- let Ok(track) = SymTrack::open(path) else {643+ // No audio track lists as the silent source it is; a track that
644+ // will not open at all is an `Err` here, as it is in
645+ // [`Track::open`] -- a listing that quietly came back empty for a
646+ // broken file is how a lane ends up silent with nothing to go on.
647+ let Some(track) = SymTrack::open(path)? else {
626 return Ok(Vec::new());648 return Ok(Vec::new());
627 };649 };
628 return Ok(vec![StreamInfo {650 return Ok(vec![StreamInfo {
@@ -635,7 +657,7 @@ impl AudioSession {
635 }]);657 }]);
636 }658 }
637 if crate::is_audio(path) {659 if crate::is_audio(path) {
638- let track = SymTrack::open(path)?;660+ let track = SymTrack::open_required(path)?;
639 return Ok(vec![StreamInfo {661 return Ok(vec![StreamInfo {
640 index: 0,662 index: 0,
641 codec: track.codec.into(),663 codec: track.codec.into(),
@@ -762,15 +784,18 @@ impl AudioSession {
762 /// half a packet over the whole list however many files it spans, and the784 /// half a packet over the whole list however many files it spans, and the
763 /// extra priming packet is still the very first segment's alone.785 /// extra priming packet is still the very first segment's alone.
764 ///786 ///
765- /// Every source must declare the same [`AacTrackParams`]: the copy becomes787+ /// Every source that *has* a track must declare the same
766- /// one output track with one esds. Import refuses a mismatch up front; the788+ /// [`AacTrackParams`]: the copy becomes one output track with one esds.
767- /// check here is the backstop, as is the missing-track `Err`.789+ /// Import refuses a mismatch up front; the check here is the backstop.
768 ///790 ///
769 /// A segment naming **no** source is a gap, and is copied as that many791 /// A segment naming **no** source is a gap, and is copied as that many
770 /// packets of [`silent_packet`] silence — the rounding debt carried through792 /// packets of [`silent_packet`] silence — the rounding debt carried through
771 /// it like any other, so the hole occupies its exact duration and the audio793 /// it like any other, so the hole occupies its exact duration and the audio
772 /// after it stays in sync with the picture. A gap the track *opens* on gets794 /// after it stays in sync with the picture. A gap the track *opens* on gets
773- /// one silent packet more, which is the priming a reader drops.795+ /// one silent packet more, which is the priming a reader drops. A segment
796+ /// naming a *silent* source is written the same way: a clip whose file has
797+ /// no audio track is a hole with a picture over it, and the timeline it
798+ /// joined already said so ([`crate::PlaybackSession::import`]).
774 pub fn copy_multi_segments(799 pub fn copy_multi_segments(
775 sources: &[PathBuf],800 sources: &[PathBuf],
776 segs: &[(Option<usize>, f64, f64)],801 segs: &[(Option<usize>, f64, f64)],
@@ -789,24 +814,34 @@ impl AudioSession {
789 sources: &[(PathBuf, usize)],814 sources: &[(PathBuf, usize)],
790 segs: &[(Option<usize>, f64, f64)],815 segs: &[(Option<usize>, f64, f64)],
791 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {816 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
792- let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {817+ // The output track is declared from the first source that has one --
818+ // not simply the first one named, which may be a silent clip. Such a
819+ // clip defines no rate and no layout; it is written as silence below
820+ // and the track goes on being the audible sources' track.
821+ let mut tracks: Vec<Option<Option<AacTrack>>> = sources.iter().map(|_| None).collect();
822+ let mut first = None;
823+ for &(source, ..) in segs {
824+ let Some(source) = source else { continue };
825+ if let Some(track) = source_at(&mut tracks, sources, source)? {
826+ first = Some(track.track_params());
827+ break;
828+ }
829+ }
830+ let Some(params) = first else {
793 return Ok(None); // no segments, or nothing but silence831 return Ok(None); // no segments, or nothing but silence
794 };832 };
795- let (path, stream) = sources
796- .get(first)
797- .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;
798- let Some(track) = copy_track(path, *stream)? else {
799- return Ok(None); // silent source, silent export
800- };
801- let params = track.track_params();
802- let mut tracks: Vec<Option<AacTrack>> = sources.iter().map(|_| None).collect();
803- tracks[first] = Some(track);
804 833
805 let sample_rate = params.sample_rate;834 let sample_rate = params.sample_rate;
806 let mut err = 0i64;835 let mut err = 0i64;
807 let mut packets: Vec<AacPacket> = Vec::new();836 let mut packets: Vec<AacPacket> = Vec::new();
808 for &(source, start_secs, end_secs) in segs {837 for &(source, start_secs, end_secs) in segs {
809- let Some(source) = source else {838+ // A gap, and a clip whose source carries no track, are the same hole
839+ // to write: silence for as long as the window is.
840+ let named = match source {
841+ Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)),
842+ None => None,
843+ };
844+ let Some((source, track)) = named else {
810 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;845 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
811 let bytes = silent_packet(params.chan_conf)?;846 let bytes = silent_packet(params.chan_conf)?;
812 // A reader drops the first packet of an AAC track as the847 // A reader drops the first packet of an AAC track as the
@@ -824,7 +859,6 @@ impl AudioSession {
824 }859 }
825 continue;860 continue;
826 };861 };
827- let track = source_at(&mut tracks, sources, source)?;
828 if track.track_params() != params {862 if track.track_params() != params {
829 return Err(format!(863 return Err(format!(
830 "source {source} audio is {:?}, the timeline's is {params:?}",864 "source {source} audio is {:?}, the timeline's is {params:?}",
@@ -885,24 +919,25 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
885 }919 }
886 }920 }
887 921
888-/// The source at `index`, on the stream it names, opened on first use. Sources922+/// The source at `index`, on the stream it names, opened on first use -- and
889-/// a segment list never names are never touched: a project's list only grows.923+/// `None` for a source that has no track at all, which the caller writes as
924+/// silence exactly as it writes a gap. The outer `Option` is "has it been
925+/// opened", the inner one "was there anything in it", so a silent source is
926+/// opened once like any other. Sources a segment list never names are never
927+/// touched: a project's list only grows.
890 fn source_at<'a>(928 fn source_at<'a>(
891- tracks: &'a mut [Option<AacTrack>],929+ tracks: &'a mut [Option<Option<AacTrack>>],
892 sources: &[(PathBuf, usize)],930 sources: &[(PathBuf, usize)],
893 index: usize,931 index: usize,
894-) -> crate::Result<&'a mut AacTrack> {932+) -> crate::Result<Option<&'a mut AacTrack>> {
895 let slot = tracks933 let slot = tracks
896 .get_mut(index)934 .get_mut(index)
897 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;935 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
898 if slot.is_none() {936 if slot.is_none() {
899 let (path, stream) = &sources[index];937 let (path, stream) = &sources[index];
900- *slot = Some(938+ *slot = Some(copy_track(path, *stream)?);
901- copy_track(path, *stream)?
902- .ok_or_else(|| format!("source {index} has no audio track"))?,
903- );
904 }939 }
905- Ok(slot.as_mut().expect("just opened"))940+ Ok(slot.as_mut().expect("just opened").as_mut())
906 }941 }
907 942
908 /// A source's track for the *copy* path, which needs raw AAC access units.943 /// A source's track for the *copy* path, which needs raw AAC access units.
@@ -994,8 +1029,8 @@ impl Track {
994 // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither1029 // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither
995 // one can decode (Opus, DTS) leaves the source the silent one it always1030 // one can decode (Opus, DTS) leaves the source the silent one it always
996 // was, which `AudioSession::unsupported` puts into words, rather than1031 // was, which `AudioSession::unsupported` puts into words, rather than
997- // failing the import of a file whose picture is fine -- and so does an1032+ // failing the import of a file whose picture is fine. A track that will
998- // AC-3 track that will not open, a laced block say.1033+ // not open at all is *not* in that group: see below.
999 if crate::demux::is_matroska(path) {1034 if crate::demux::is_matroska(path) {
1000 if stream > 0 {1035 if stream > 0 {
1001 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());1036 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
@@ -1003,24 +1038,27 @@ impl Track {
1003 match MkvAc3Track::open(path) {1038 match MkvAc3Track::open(path) {
1004 Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),1039 Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
1005 Ok(None) => {}1040 Ok(None) => {}
1006- // Named on the way past for the same reason symphonia's failure1041+ // Named on the way past rather than returned: symphonia gets the
1007- // is, below: an AC-3 track that broke is a bug, not a codec we1042+ // same file next and may read the track perfectly well (a laced
1008- // never had.1043+ // block is [`MkvAc3Track`]'s limitation, not the file's), and
1044+ // if it cannot either, *its* `Err` is the one that comes back.
1009 Err(e) => eprintln!("matroska audio: {}: {e}", path.display()),1045 Err(e) => eprintln!("matroska audio: {}: {e}", path.display()),
1010 }1046 }
1011- // Logged on the way past: "silent" here covers both a codec nothing1047+ // Two things are silent here and no more: a file with no audio
1012- // decodes and a track that genuinely broke, and only the second is a1048+ // track at all, and a track whose codec nothing in this project
1013- // bug -- with no trace at all it reaches the user as a lane that1049+ // decodes (Opus, DTS -- [`AudioSession::unsupported`] is what puts
1014- // drew no waveform and nothing else to go on.1050+ // that into words). A track that will not *open* is an `Err`, the
1015- return Ok(SymTrack::open(path)1051+ // same answer the mp4 arm gives: turned into silence it would play
1016- .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))1052+ // and export as a hole with only an eprintln to say why, which is a
1017- .ok()1053+ // bug wearing a feature's clothes.
1018- .filter(|t| {1054+ let Some(track) = SymTrack::open(path)? else {
1019- t.decoder()1055+ return Ok(None);
1020- .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))1056+ };
1021- .is_ok()1057+ if let Err(e) = track.decoder() {
1022- })1058+ eprintln!("matroska audio: {}: {e}", path.display());
1023- .map(Self::Sym));1059+ return Ok(None);
1060+ }
1061+ return Ok(Some(Self::Sym(track)));
1024 }1062 }
1025 let audio_file = crate::is_audio(path);1063 let audio_file = crate::is_audio(path);
1026 // Ahead of the AAC reader, because that one answers "not AAC" for a1064 // Ahead of the AAC reader, because that one answers "not AAC" for a
@@ -1041,7 +1079,7 @@ impl Track {
1041 if stream > 0 {1079 if stream > 0 {
1042 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());1080 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
1043 }1081 }
1044- SymTrack::open(path).map(|track| Some(Self::Sym(track)))1082+ SymTrack::open_required(path).map(|track| Some(Self::Sym(track)))
1045 }1083 }
1046 1084
1047 fn sample_rate(&self) -> u32 {1085 fn sample_rate(&self) -> u32 {
@@ -1166,7 +1204,13 @@ struct SymTrack {
1166 }1204 }
1167 1205
1168 impl SymTrack {1206 impl SymTrack {
1169- fn open(path: &Path) -> crate::Result<Self> {1207+ /// `Ok(None)` for a container that opened and holds no audio track at all --
1208+ /// a silent source, which is a thing a file is allowed to be. Everything
1209+ /// else that goes wrong here is an `Err`: a file that will not open, will
1210+ /// not parse, or carries a track it cannot describe is *broken*, and the
1211+ /// difference matters because silence is played and exported without a word
1212+ /// while an `Err` is shown ([`Track::open`]).
1213+ fn open(path: &Path) -> crate::Result<Option<Self>> {
1170 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());1214 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
1171 // The extension is a hint, not a decision: the probe reads the magic and1215 // The extension is a hint, not a decision: the probe reads the magic and
1172 // is free to disagree, which is what makes a mislabelled file work.1216 // is free to disagree, which is what makes a mislabelled file work.
@@ -1180,9 +1224,9 @@ impl SymTrack {
1180 FormatOptions::default(),1224 FormatOptions::default(),
1181 MetadataOptions::default(),1225 MetadataOptions::default(),
1182 )?;1226 )?;
1183- let track = reader1227+ let Some(track) = reader.default_track(SymKind::Audio) else {
1184- .default_track(SymKind::Audio)1228+ return Ok(None);
1185- .ok_or_else(|| format!("{} has no audio track", path.display()))?;1229+ };
1186 let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay);1230 let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay);
1187 let time_base = track1231 let time_base = track
1188 .time_base1232 .time_base
@@ -1203,7 +1247,7 @@ impl SymTrack {
1203 let codec = symphonia::default::get_codecs()1247 let codec = symphonia::default::get_codecs()
1204 .get_audio_decoder(params.codec)1248 .get_audio_decoder(params.codec)
1205 .map_or("an unsupported format", |d| d.codec.info.short_name);1249 .map_or("an unsupported format", |d| d.codec.info.short_name);
1206- Ok(Self {1250+ Ok(Some(Self {
1207 reader,1251 reader,
1208 track_id,1252 track_id,
1209 sample_rate,1253 sample_rate,
@@ -1217,7 +1261,14 @@ impl SymTrack {
1217 time_base,1261 time_base,
1218 params,1262 params,
1219 codec,1263 codec,
1220- })1264+ }))
1265+ }
1266+
1267+ /// [`open`](Self::open) where having no audio track is itself the error:
1268+ /// what a standalone audio file is held to, since a song with no sound in
1269+ /// it is a broken file and not a silent source.
1270+ fn open_required(path: &Path) -> crate::Result<Self> {
1271+ Self::open(path)?.ok_or_else(|| format!("{} has no audio track", path.display()).into())
1221 }1272 }
1222 1273
1223 /// A fresh decoder: seeking mid-stream leaves state that belongs to the1274 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
crates/engine/src/playback.rsmodified+43 -27
@@ -1659,8 +1659,9 @@ impl PlaybackSession {
1659 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take1659 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
1660 /// back, and nothing reseeks.1660 /// back, and nothing reseeks.
1661 ///1661 ///
1662- /// Refused unless it can join the timeline -- same codec, same audio1662+ /// Refused unless it can join the timeline -- a decoder this machine can
1663- /// parameters or both silent; the `Err` names the property that disagrees,1663+ /// open, and audio parameters that agree or none at all; the `Err` names
1664+ /// the property that disagrees,
1664 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of1665 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
1665 /// its own is not a refusal: the clip is placed on the project canvas by its1666 /// its own is not a refusal: the clip is placed on the project canvas by its
1666 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame1667 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
@@ -2018,8 +2019,9 @@ impl Drop for PlaybackSession {
2018 }2019 }
2019 2020
2020 /// Whether `path`, already demuxed to `meta`, may join a timeline whose2021 /// Whether `path`, already demuxed to `meta`, may join a timeline whose
2021-/// parameters are `timeline` and whose audio probes as `first`: same codec,2022+/// parameters are `timeline` and whose audio probes as `first`: a decoder this
2022-/// same audio parameters or both silent, and a frame rate that can be named2023+/// machine can open, audio parameters that agree (or no audio at all), and a
2024+/// frame rate that can be named
2023 /// against the timeline's. The [`Rate`] it will be read at comes back with the2025 /// against the timeline's. The [`Rate`] it will be read at comes back with the
2024 /// answer, so the number the check was decided on is the number it plays by.2026 /// answer, so the number the check was decided on is the number it plays by.
2025 ///2027 ///
@@ -2028,7 +2030,9 @@ impl Drop for PlaybackSession {
2028 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a2030 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
2029 /// letterboxed clip rather than a refusal, and so is a frame rate of its own:2031 /// letterboxed clip rather than a refusal, and so is a frame rate of its own:
2030 /// the timeline keeps its own rate and the file is read at [`Rate`] against it2032 /// the timeline keeps its own rate and the file is read at [`Rate`] against it
2031-/// ([`PlaybackSession::import`] notes how long it is *here*).2033+/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same
2034+/// codec: every clip opens its own decoder, so a mixed-codec timeline is a
2035+/// decoder each rather than a refusal.
2032 ///2036 ///
2033 /// The `Err` names the property that disagrees, and those strings are what a2037 /// The `Err` names the property that disagrees, and those strings are what a
2034 /// front-end shows verbatim; [`PlaybackSession::import`] and2038 /// front-end shows verbatim; [`PlaybackSession::import`] and
@@ -2040,18 +2044,22 @@ fn matches_timeline(
2040 timeline: &VideoMeta,2044 timeline: &VideoMeta,
2041 first: &Option<crate::AudioProbe>,2045 first: &Option<crate::AudioProbe>,
2042 ) -> crate::Result<Rate> {2046 ) -> crate::Result<Rate> {
2043- // Codec first: one timeline is one kind of source. Mixing them would decode2047+ // The codec is *not* held to the timeline's -- every clip opens its own
2044- // (every clip opens its own decoder) but on a machine without the VA-API2048+ // decoder, so an H.264 take and an HEVC one play on one timeline. What the
2045- // plugin the VP9 half would be black frames with the refusal only on2049+ // codec gate was really protecting against stays, in the one place that can
2046- // stderr, which is exactly what a front-end cannot show.2050+ // actually answer it: on a machine without the VA-API plugin an HEVC or VP9
2047- if meta.codec != timeline.codec {2051+ // clip would be black frames with the refusal on stderr alone, so the file
2048- return Err(format!(2052+ // is asked for a decoder *here*, at the door, where the `Err` is still
2049- "{} does not match the timeline's {}",2053+ // something a front-end can show. A zero-length range probes and starts no
2050- meta.codec.name(),2054+ // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
2051- timeline.codec.name()2055+ // only enters VA-API off that path.
2052- )2056+ DecodeSession::open_worker(
2053- .into());2057+ &source.path,
2054- }2058+ 0,
2059+ 0,
2060+ ColorParams::default(),
2061+ Composer::passthrough(),
2062+ )?;
2055 // The frame rate is *not* a refusal any more: a file shot at another rate is2063 // The frame rate is *not* a refusal any more: a file shot at another rate is
2056 // placed for the seconds it lasts and read through [`Rate`] at the2064 // placed for the seconds it lasts and read through [`Rate`] at the
2057 // decoder's door, so it plays at the speed it was shot at on a timeline2065 // decoder's door, so it plays at the speed it was shot at on a timeline
@@ -2069,8 +2077,9 @@ fn matches_timeline(
2069 }2077 }
2070 2078
2071 /// Whether a candidate's audio may join a timeline whose first source probes as2079 /// Whether a candidate's audio may join a timeline whose first source probes as
2072-/// `first`: same rate, same layout, or both silent. One output device and one2080+/// `first`: same rate, same layout -- or no audio of its own at all, which is
2073-/// exported track is all there is, and no resampler.2081+/// silence over the clip's span and agrees with everything. One output device
2082+/// and one exported track is all there is, and no resampler.
2074 ///2083 ///
2075 /// The audio half of [`matches_timeline`], which a stream placed on its own2084 /// The audio half of [`matches_timeline`], which a stream placed on its own
2076 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it2085 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
@@ -2088,9 +2097,9 @@ fn matches_timeline(
2088 /// `Ok(None)` for a timeline whose first such source is silent, and for one of2097 /// `Ok(None)` for a timeline whose first such source is silent, and for one of
2089 /// nothing but stills. That is a silent timeline, and a file with sound is2098 /// nothing but stills. That is a silent timeline, and a file with sound is
2090 /// still refused by [`audio_matches`] in the words it always used ("the file2099 /// still refused by [`audio_matches`] in the words it always used ("the file
2091-/// has audio, the timeline is silent") -- the same answer a silent *video* as2100+/// has audio, the timeline is silent") -- the device was opened on source 0's
2092-/// source 0 has always given. This function widens which source is asked, not2101+/// track and there is none to open. This function widens which source is asked,
2093-/// what the answer means.2102+/// not what the answer means.
2094 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {2103 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
2095 match audio_source_of(sources) {2104 match audio_source_of(sources) {
2096 Some(first) => AudioSession::probe(&first.path, first.audio_stream),2105 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
@@ -2119,12 +2128,19 @@ fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::R
2119 if probe == *first {2128 if probe == *first {
2120 return Ok(());2129 return Ok(());
2121 }2130 }
2122- Err(match (probe, first) {2131+ // ...and a *silent* file joins whatever the timeline is: it contributes
2123- (None, _) => "the file is silent, the timeline has audio".to_string(),2132+ // silence over its span, which is the very thing both audio paths already
2124- (_, None) => "the file has audio, the timeline is silent".to_string(),2133+ // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
2125- (Some(a), Some(b)) => format!(2134+ // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
2135+ // no layout to disagree about, so there is nothing left to refuse.
2136+ let Some(probe) = probe else {
2137+ return Ok(());
2138+ };
2139+ Err(match first {
2140+ None => "the file has audio, the timeline is silent".to_string(),
2141+ Some(b) => format!(
2126 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",2142 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
2127- a.sample_rate, a.channels, b.sample_rate, b.channels2143+ probe.sample_rate, probe.channels, b.sample_rate, b.channels
2128 ),2144 ),
2129 }2145 }
2130 .into())2146 .into())
crates/engine/tests/audio_decode.rsmodified+37 -0
@@ -272,3 +272,40 @@ fn an_ac3_source_refuses_an_mp4_audio_copy() {
272 "unhelpful refusal: {err}"272 "unhelpful refusal: {err}"
273 );273 );
274 }274 }
275+
276+/// The two things a Matroska file with no *readable* sound can be, told apart:
277+/// a file with no audio track is the silent source it says it is, and a file
278+/// whose audio will not open at all is an error. They used to be the same
279+/// answer -- silence -- so a broken track played and exported as a hole with
280+/// nothing but an `eprintln` to say why.
281+#[test]
282+fn a_matroska_with_no_track_is_silent_and_a_broken_one_is_an_error() {
283+ // No audio track at all: a picture and two subtitle tracks. Silent, and the
284+ // stream picker offers nothing rather than refusing the file.
285+ let subs = asset("test_subs.mkv");
286+ assert!(
287+ AudioSession::probe(&subs, 0)
288+ .expect("no audio is not an error")
289+ .is_none(),
290+ "an mkv with no audio track is a silent source"
291+ );
292+ assert!(AudioSession::probe_streams(&subs).expect("list").is_empty());
293+ assert!(
294+ AudioSession::open(&subs).expect("open").is_none(),
295+ "no sound"
296+ );
297+
298+ // ...and a file that will not parse at all, under the same extension: an
299+ // `Err` a front-end can show, not a silent import.
300+ let broken = std::env::temp_dir().join(format!("ve_broken_{}.mkv", std::process::id()));
301+ std::fs::write(&broken, b"\x1a\x45\xdf\xa3not a matroska file at all").expect("write");
302+ let err = AudioSession::probe(&broken, 0)
303+ .expect_err("a broken file must not pass for a silent one")
304+ .to_string();
305+ assert!(!err.is_empty(), "the refusal says something");
306+ assert!(
307+ AudioSession::probe_streams(&broken).is_err(),
308+ "and so does the listing"
309+ );
310+ std::fs::remove_file(&broken).unwrap();
311+}
crates/engine/tests/audio_export.rsmodified+61 -0
@@ -511,6 +511,67 @@ fn a_cancelled_audio_export_leaves_no_file() {
511 assert!(!part_path(&out).exists(), "no half-written .part either");511 assert!(!part_path(&out).exists(), "no half-written .part either");
512 }512 }
513 513
514+/// The samples a silent take contributes: a clip of a file with no audio track
515+/// is silence for exactly its span, between two clips that are heard. This is
516+/// what makes `PlaybackSession::import` letting such a file in honest -- the
517+/// export reads the same play list playback does, so a hole here is a hole in
518+/// the ear too.
519+#[test]
520+fn a_silent_clip_exports_as_silence_over_its_own_span() {
521+ let clip = |start, source| Clip {
522+ start,
523+ in_frame: 0,
524+ out_frame: 30,
525+ source,
526+ link: None,
527+ eq: None,
528+ color: None,
529+ fit: FitPolicy::default(),
530+ speed: Speed::NORMAL,
531+ };
532+ let project = Project::from_parts(
533+ vec![
534+ Source::new(asset("test_av.mp4"), 0),
535+ // Video only, no audio track at all: the silent take.
536+ Source::new(asset("test_mismatch.mp4"), 0),
537+ ],
538+ vec![
539+ (LaneKind::Video, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
540+ (LaneKind::Audio, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
541+ ],
542+ Vec::new(),
543+ Vec::new(),
544+ )
545+ .expect("a project whose middle take is silent");
546+
547+ let out = out_path("silent_clip", "wav");
548+ let handle = engine::export::start(
549+ project,
550+ meta(),
551+ &out,
552+ &ExportSettings {
553+ format: Format::Wav,
554+ ..Default::default()
555+ },
556+ );
557+ wait(&handle, Duration::from_secs(60)).expect("wav export");
558+ let (audio, samples) = decode(&out);
559+ let channels = usize::from(audio.channels);
560+ assert_eq!(
561+ samples.len(),
562+ (3.0 * f64::from(RATE)) as usize * channels,
563+ "three seconds of timeline, silent take included"
564+ );
565+ let heard = rms(&samples, channels, 0.05, 0.95);
566+ let quiet = rms(&samples, channels, 1.0, 2.0);
567+ let again = rms(&samples, channels, 2.05, 2.95);
568+ println!("rms: heard {heard:.4} silent take {quiet:.6} heard {again:.4}");
569+ assert!(heard > 0.01, "the first take is audible");
570+ assert!(again > 0.01, "the third take is audible");
571+ assert_eq!(quiet, 0.0, "the silent take is exact silence, not a stall");
572+ std::fs::remove_file(&out).unwrap();
573+}
574+
514 /// A silent timeline cannot become an audio file, and says so rather than575 /// A silent timeline cannot become an audio file, and says so rather than
515 /// writing zero samples that a user would take for a broken microphone.576 /// writing zero samples that a user would take for a broken microphone.
516 #[test]577 #[test]
crates/engine/tests/audio_multi.rsmodified+67 -7
@@ -250,18 +250,19 @@ fn the_join_carries_no_second_priming_packet() {
250 }250 }
251 251
252 #[test]252 #[test]
253-fn a_source_without_the_timeline_audio_is_refused() {253+fn a_source_that_disagrees_on_rate_or_layout_is_refused() {
254- // Import refuses these up front (same rate, same layout, or both silent);254+ // Import refuses these up front (one output device, one set of parameters);
255 // the copy and the decode paths refuse them again rather than mislabel one255 // the copy and the decode paths refuse them again rather than mislabel one
256- // esds for two different tracks.256+ // esds for two different tracks. Stream 1 of the multi-audio fixture is
257- let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")];257+ // 22.05 kHz mono against the timeline's 44.1 kHz stereo.
258+ let mixed = [(asset("test_av.mp4"), 0), (asset("test_multiaudio.mp4"), 1)];
258 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];259 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
259 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)260 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)
260 for e in [261 for e in [
261- AudioSession::copy_multi_segments(&mixed, &segs).err(),262+ AudioSession::copy_multi_streams(&mixed, &segs).err(),
262- AudioSession::open_multi_segments(&mixed, &segs).err(),263+ AudioSession::open_multi_streams(&mixed, &segs).err(),
263 ]264 ]
264- .map(|e| e.expect("a source with no audio track must be refused"))265+ .map(|e| e.expect("a source at another rate must be refused"))
265 {266 {
266 let msg = e.to_string();267 let msg = e.to_string();
267 assert!(msg.contains("source 1"), "{msg}");268 assert!(msg.contains("source 1"), "{msg}");
@@ -270,3 +271,62 @@ fn a_source_without_the_timeline_audio_is_refused() {
270 assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());271 assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
271 assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());272 assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
272 }273 }
274+
275+/// A source with **no** track is not a refusal at all: its segments are the
276+/// same silence a gap is, in both paths. That is what a silent clip on an audio
277+/// lane is -- a picture over a hole -- and the timeline lets one in
278+/// (`PlaybackSession::import`) precisely because these two agree here.
279+#[test]
280+fn a_silent_source_is_silence_and_not_a_refusal() {
281+ let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")];
282+ let segs = [
283+ (Some(0), 0.0, 1.0),
284+ (Some(1), 0.0, 1.0),
285+ (Some(0), 0.0, 1.0),
286+ ];
287+
288+ // Decoded: three seconds, the middle one exact zero, and the chunks still
289+ // arrive contiguous (`drain` asserts that), so the clock is fed through it.
290+ let (_, rx) = AudioSession::open_multi_segments(&mixed, &segs)
291+ .expect("a silent source opens")
292+ .expect("the first source has an audio track");
293+ let (samples, _, _) = drain(rx);
294+ let frames = samples.len() / CHANNELS;
295+ assert!(
296+ (frames as i64 - 3 * RATE as i64).unsigned_abs() < PACKET,
297+ "{frames} frames for three seconds"
298+ );
299+ let second = |n: usize| {
300+ let at = |s: usize| (s * RATE as usize * CHANNELS).min(samples.len());
301+ &samples[at(n)..at(n + 1)]
302+ };
303+ assert!(
304+ second(0).iter().any(|s| *s != 0.0),
305+ "the first second plays"
306+ );
307+ assert!(
308+ second(1).iter().all(|s| *s == 0.0),
309+ "the silent source is exact silence"
310+ );
311+ assert!(second(2).iter().any(|s| *s != 0.0), "and it comes back");
312+
313+ // Copied: the same shape in packets, so an mp4 export of that timeline is
314+ // as long as the timeline and quiet where the silent clip is.
315+ let (params, packets) = AudioSession::copy_multi_segments(&mixed, &segs)
316+ .expect("a silent source copies")
317+ .expect("the timeline has an audible source");
318+ let copied = packets.len() as u64 * PACKET;
319+ assert!(
320+ (copied as i64 - 3 * RATE as i64).unsigned_abs() < 2 * PACKET,
321+ "{copied} samples for three seconds, priming included"
322+ );
323+ assert_eq!(
324+ params.sample_rate, RATE as u32,
325+ "the audible source's track"
326+ );
327+ let silence: Vec<_> = packets[44..44 + 43].iter().map(|p| &p.bytes).collect();
328+ assert!(
329+ silence.iter().all(|b| b.len() <= 7),
330+ "the hole is written as the hand-made silent packet, not as audio"
331+ );
332+}
crates/engine/tests/av1.rsmodified+16 -6
@@ -155,17 +155,27 @@ fn the_software_path_refuses_av1_by_name() {
155 assert!(refused.contains("plugin"), "{refused}");155 assert!(refused.contains("plugin"), "{refused}");
156 }156 }
157 157
158-/// A timeline is refused a source coded differently, in the same words a158+/// A timeline is *not* refused a source coded differently -- every clip opens
159-/// resolution mismatch is refused in: a front-end shows the string as it is.159+/// its own decoder. What survives is the reason the codec gate existed: on a
160+/// machine that cannot decode AV1 the file is refused at the door, by the
161+/// decoder's own name, rather than becoming a clip of black frames.
160 #[test]162 #[test]
161-fn a_timeline_refuses_the_other_codec() {163+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
162 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");164 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
165+ // The no-plugin machine, forced.
166+ // SAFETY: the suite is documented to run with --test-threads=1.
167+ unsafe { std::env::set_var("VE_SW", "1") };
163 let refused = session168 let refused = session
164 .import(&asset("test_av1.mkv"))169 .import(&asset("test_av1.mkv"))
165- .expect_err("AV1 must not join an H.264 timeline")170+ .expect_err("no AV1 decoder means no AV1 clip")
166 .to_string();171 .to_string();
167- assert!(refused.contains("AV1"), "{refused}");172+ unsafe { std::env::remove_var("VE_SW") };
168- assert!(refused.contains("H.264"), "{refused}");173+ assert_eq!(refused, Codec::Av1.needs_plugin());
174+ assert!(
175+ !refused.contains("H.264"),
176+ "the timeline's own codec is no longer a reason: {refused}"
177+ );
178+ assert_eq!(session.sources().len(), 1, "a refusal left no row");
169 }179 }
170 180
171 /// The end-to-end user path: opening the file yields pictures, all of them,181 /// The end-to-end user path: opening the file yields pictures, all of them,
crates/engine/tests/hevc.rsmodified+83 -6
@@ -112,17 +112,35 @@ fn the_software_path_refuses_hevc_by_name() {
112 assert!(h264, "software H.264 decode still opens");112 assert!(h264, "software H.264 decode still opens");
113 }113 }
114 114
115-/// A timeline is refused a source coded differently, in the same words a115+/// A timeline is *not* refused a source coded differently -- every clip opens
116-/// resolution mismatch is refused in: a front-end shows the string as it is.116+/// its own decoder, so H.264 and HEVC share one timeline. What survives is the
117+/// reason the codec gate existed: on a machine that cannot decode HEVC the file
118+/// is refused at the door, by the decoder's own name, rather than becoming a
119+/// clip of black frames with the complaint on stderr.
117 #[test]120 #[test]
118-fn a_timeline_refuses_the_other_codec() {121+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
119 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");122 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
123+ // The no-plugin machine, forced: the refusal must still arrive, and it must
124+ // be the decoder's words and not the timeline's.
125+ // SAFETY: the suite is documented to run with --test-threads=1.
126+ unsafe { std::env::set_var("VE_SW", "1") };
120 let refused = session127 let refused = session
121 .import(&asset("test_hevc.mp4"))128 .import(&asset("test_hevc.mp4"))
122- .expect_err("HEVC must not join an H.264 timeline")129+ .expect_err("no HEVC decoder means no HEVC clip")
123 .to_string();130 .to_string();
124- assert!(refused.contains("HEVC"), "{refused}");131+ unsafe { std::env::remove_var("VE_SW") };
125- assert!(refused.contains("H.264"), "{refused}");132+ assert_eq!(refused, Codec::Hevc.needs_plugin());
133+ assert!(
134+ !refused.contains("H.264"),
135+ "the timeline's own codec is no longer a reason: {refused}"
136+ );
137+ assert_eq!(session.sources().len(), 1, "a refusal left no row");
138+
139+ // ...and where a decoder exists, it simply joins.
140+ match session.import(&asset("test_hevc.mp4")) {
141+ Ok(_) => assert_eq!(session.sources().len(), 2, "HEVC beside H.264"),
142+ Err(e) => assert_eq!(e.to_string(), Codec::Hevc.needs_plugin()),
143+ }
126 }144 }
127 145
128 /// The end-to-end user path: opening the file yields pictures, all of them,146 /// The end-to-end user path: opening the file yields pictures, all of them,
@@ -155,6 +173,65 @@ fn the_plugin_decodes_every_hevc_frame() {
155 );173 );
156 }174 }
157 175
176+/// The mixed-codec timeline, end to end: an H.264 take joins an HEVC one, both
177+/// spans really decode (a decoder each, opened at the span), and the export --
178+/// which re-encodes -- writes every frame of both. The refusal that used to
179+/// stand here would have made this whole timeline impossible.
180+#[test]
181+#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
182+fn an_h264_take_plays_and_exports_on_an_hevc_timeline() {
183+ let hevc = asset("test_hevc.mp4");
184+ let h264 = asset("test_av.mp4");
185+ let mut session = PlaybackSession::open(&hevc).expect("open test_hevc.mp4");
186+ session.set_gain(0.0);
187+ session.import(&h264).expect("H.264 joins an HEVC timeline");
188+ let end = session.timeline_duration();
189+ assert!(
190+ session
191+ .place_stream_at(end, &h264, 0, None)
192+ .expect("a file just imported is on this timeline"),
193+ "drag it onto the end"
194+ );
195+ assert_eq!(session.clip_spans().len(), 2, "two takes, two codecs");
196+
197+ // One picture out of each span, which is one decoder each: the HEVC clip
198+ // through the plugin, the H.264 one through either backend.
199+ for (at, what) in [(1.0, "the HEVC take"), (end + 1.0, "the H.264 take")] {
200+ session.seek(at);
201+ let deadline = Instant::now() + Duration::from_secs(10);
202+ let frame = loop {
203+ if let Some(frame) = session.try_frame() {
204+ break frame;
205+ }
206+ assert!(Instant::now() < deadline, "no frame from {what}");
207+ std::thread::sleep(Duration::from_millis(4));
208+ };
209+ assert_eq!(
210+ (frame.width, frame.height),
211+ session.resolution(),
212+ "{what} came out at the project size"
213+ );
214+ }
215+
216+ // ...and the export -- the one a front-end starts, off the session itself --
217+ // re-encodes both to one H.264 track.
218+ let frames =
219+ (session.timeline_duration() * f64::from(session.meta().frame_rate as f32)).round() as u32;
220+ let out = std::env::temp_dir().join(format!("ve_export_mixed_{}.mp4", std::process::id()));
221+ let _ = std::fs::remove_file(&out);
222+ let handle = session.export_to_with(&out, &ExportSettings::default());
223+ let started = Instant::now();
224+ while !handle.is_finished() {
225+ assert!(started.elapsed() < Duration::from_secs(240), "export hung");
226+ std::thread::sleep(Duration::from_millis(20));
227+ }
228+ handle.result().expect("outcome").expect("the mixed export");
229+ let (written, _) = Demuxer::open(&out).expect("reopen the export");
230+ assert_eq!(written.codec, Codec::H264, "exports are always H.264");
231+ assert_eq!(written.frame_count, frames, "both takes were written");
232+ let _ = std::fs::remove_file(&out);
233+}
234+
158 /// Export re-encodes to H.264 whatever the source was coded with: the packet235 /// Export re-encodes to H.264 whatever the source was coded with: the packet
159 /// copy path is audio-only, so no HEVC byte can reach an `avc1` track.236 /// copy path is audio-only, so no HEVC byte can reach an `avc1` track.
160 #[test]237 #[test]
crates/engine/tests/lanes.rsmodified+9 -4
@@ -52,8 +52,13 @@ fn out_path(name: &str, ext: &str) -> PathBuf {
52 /// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle52 /// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle
53 /// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`.53 /// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`.
54 /// Exactly the file a user would write by hand, parsed by the real loader.54 /// Exactly the file a user would write by hand, parsed by the real loader.
55-fn three_lane_file() -> PathBuf {55+///
56- let path = out_path("project", "edith");56+/// `name` is the caller's own, because [`out_path`] is unique per *run* and not
57+/// per test: two tests sharing one name run in parallel over one file, and the
58+/// first to finish deletes it out from under the second -- which then fails on
59+/// a file that is simply not there any more.
60+fn three_lane_file(name: &str) -> PathBuf {
61+ let path = out_path(name, "edith");
57 // `source <audio stream> <path>`: the number is which audio track of the62 // `source <audio stream> <path>`: the number is which audio track of the
58 // file plays, not the source index -- both of these are on their first.63 // file plays, not the source index -- both of these are on their first.
59 let text = format!(64 let text = format!(
@@ -143,7 +148,7 @@ fn frame_of(session: &mut PlaybackSession, timeline: u32) -> Vec<u8> {
143 #[test]148 #[test]
144 fn playback_shows_the_topmost_video_lane() {149 fn playback_shows_the_topmost_video_lane() {
145 pin_software();150 pin_software();
146- let project = three_lane_file();151+ let project = three_lane_file("playback");
147 let mut session = PlaybackSession::open_project(&project).expect("open the project");152 let mut session = PlaybackSession::open_project(&project).expect("open the project");
148 session.set_gain(0.0);153 session.set_gain(0.0);
149 assert_eq!(session.timeline_duration(), f64::from(TOTAL) / FPS);154 assert_eq!(session.timeline_duration(), f64::from(TOTAL) / FPS);
@@ -164,7 +169,7 @@ fn playback_shows_the_topmost_video_lane() {
164 #[test]169 #[test]
165 fn export_writes_the_same_composite() {170 fn export_writes_the_same_composite() {
166 pin_software();171 pin_software();
167- let file = three_lane_file();172+ let file = three_lane_file("export");
168 let session = PlaybackSession::open_project(&file).expect("open the project");173 let session = PlaybackSession::open_project(&file).expect("open the project");
169 let out = out_path("composite", "mp4");174 let out = out_path("composite", "mp4");
170 175
crates/engine/tests/playback.rsmodified+60 -25
@@ -13,7 +13,7 @@ use std::time::{Duration, Instant};
13 13
14 use engine::export::{ExportSettings, Format};14 use engine::export::{ExportSettings, Format};
15 use engine::project::Lane;15 use engine::project::Lane;
16-use engine::{DecodeSession, Frame, PlaybackSession};16+use engine::{Codec, DecodeSession, Frame, PlaybackSession};
17 17
18 fn asset(name: &str) -> PathBuf {18 fn asset(name: &str) -> PathBuf {
19 PathBuf::from(env!("CARGO_MANIFEST_DIR"))19 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -788,30 +788,31 @@ fn the_first_import_opens_a_library_over_an_empty_timeline() {
788 assert_eq!(session.sources().len(), 1, "the row survives the undo");788 assert_eq!(session.sources().len(), 1, "the row survives the undo");
789 }789 }
790 790
791-/// One timeline, one set of parameters: everything else is refused by name and791+/// One timeline, one frame rate and one set of audio parameters: what is left
792-/// changes nothing.792+/// is refused by name and changes nothing.
793 #[test]793 #[test]
794 fn import_refuses_what_does_not_match() {794 fn import_refuses_what_does_not_match() {
795 let mut session = open(asset("test_av.mp4"));795 let mut session = open(asset("test_av.mp4"));
796 796
797- // A different *codec* cannot join: one timeline is one kind of source.797+ // A different *codec* is not among them any more -- every clip opens its
798- let err = session798+ // own decoder. The only refusal left on that axis is a decoder this machine
799- .import(&asset("test_vp9.mp4"))799+ // cannot open, and it is the plugin's own words, not the timeline's.
800- .expect_err("VP9 must be refused")800+ match session.import(&asset("test_vp9.mp4")) {
801- .to_string();801+ Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 joined the H.264 timeline"),
802- assert!(err.contains("VP9"), "refusal must name the codec: {err}");802+ Err(e) => assert_eq!(
803+ e.to_string(),
804+ Codec::Vp9.needs_plugin(),
805+ "the only codec refusal left is the missing decoder"
806+ ),
807+ }
808+ let rows = session.sources().len();
803 809
804 // A different resolution is no longer among the refusals -- it is placed on810 // A different resolution is no longer among the refusals -- it is placed on
805- // the project canvas instead -- but this file is also silent, and that is.811+ // the project canvas instead -- and neither is a file with no sound: it
806- let err = session812+ // contributes silence over its span.
813+ session
807 .import(&asset("test_mismatch.mp4"))814 .import(&asset("test_mismatch.mp4"))
808- .expect_err("a silent file must be refused")815+ .expect("a silent 640x360 file joins a timeline with sound");
809- .to_string();
810- assert!(err.contains("audio"), "refusal must name the audio: {err}");
811- assert!(
812- !err.contains("640x360"),
813- "a resolution of its own is not a refusal any more: {err}"
814- );
815 816
816 // A frame rate of its own is no longer a refusal either: 25 fps joins a817 // A frame rate of its own is no longer a refusal either: 25 fps joins a
817 // 30 fps timeline and is read at `Rate` against it -- see818 // 30 fps timeline and is read at `Rate` against it -- see
@@ -823,22 +824,32 @@ fn import_refuses_what_does_not_match() {
823 .remove_source(&asset("test_25fps.mp4"), 0)824 .remove_source(&asset("test_25fps.mp4"), 0)
824 .expect("...and the row it made comes back off");825 .expect("...and the row it made comes back off");
825 826
826- // Same size and rate, no audio track: the timeline has one.827+ // What is still refused, and all that is: one output device means one rate
828+ // and one layout, and there is no resampler to make two into one.
827 let err = session829 let err = session
828- .import(&asset("test_baseline.mp4"))830+ .import(&asset("test_ac3.mp4"))
829- .expect_err("a silent file must be refused")831+ .expect_err("a mono track cannot join a stereo timeline")
830 .to_string();832 .to_string();
831- assert!(err.contains("audio"), "refusal must name the audio: {err}");833+ assert_eq!(
834+ err,
835+ "audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch"
836+ );
832 837
833 assert!(838 assert!(
834 session.import(&asset("no_such_file.mp4")).is_err(),839 session.import(&asset("no_such_file.mp4")).is_err(),
835 "a missing file is an error, not a panic"840 "a missing file is an error, not a panic"
836 );841 );
837- assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing");842+ assert_eq!(session.clip_spans().len(), 1, "an import places nothing");
838- assert_eq!(session.sources().len(), 1, "a refusal left a library row");843+ assert_eq!(
844+ session.sources().len(),
845+ rows + 1,
846+ "only the silent file was taken in"
847+ );
839 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);848 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
840 849
841- // The mirror: audio into a silent timeline is refused just as loudly.850+ // The mirror is still refused: the device was opened on source 0's track
851+ // and a silent timeline has none to open, so a file with sound cannot be
852+ // heard on one.
842 let mut silent = open(asset("test_baseline.mp4"));853 let mut silent = open(asset("test_baseline.mp4"));
843 let err = silent854 let err = silent
844 .import(&asset("test_av.mp4"))855 .import(&asset("test_av.mp4"))
@@ -847,6 +858,30 @@ fn import_refuses_what_does_not_match() {
847 assert!(err.contains("audio"), "refusal must name the audio: {err}");858 assert!(err.contains("audio"), "refusal must name the audio: {err}");
848 }859 }
849 860
861+/// The user path a silent take goes down: a file with no audio track lands on a
862+/// timeline that has one, is placed as the grouped take every video file is,
863+/// and plays -- pictures over its span, silence under them. The sound itself is
864+/// asserted on the samples in `tests/audio_export.rs`; what is asserted here is
865+/// that nothing about the *timeline* is refused or lost.
866+#[test]
867+fn a_silent_file_joins_a_timeline_with_sound_and_plays() {
868+ let mut session = open(asset("test_av.mp4"));
869+ import_and_place(&mut session, &asset("test_mismatch.mp4"));
870+ // 150 frames of test_av, then 60 of the silent file, at 30 fps.
871+ assert_eq!(session.clip_spans().len(), 2, "the silent take landed");
872+ assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
873+ // Both lanes carry it: a silent file is a normal grouped take, and its
874+ // audio clip is the span the worker fills with silence.
875+ assert_eq!(session.lane_clips(Lane::V1).len(), 2);
876+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
877+
878+ // ...and it decodes: a picture from inside the silent clip's span, at the
879+ // project's resolution like every other clip.
880+ session.seek(6.0);
881+ let frame = next_frame(&mut session, "the silent clip");
882+ assert_eq!((frame.width, frame.height), session.resolution());
883+}
884+
850 /// The user-facing point of a project resolution: media of two sizes on one885 /// The user-facing point of a project resolution: media of two sizes on one
851 /// timeline, each composed onto the project's own canvas.886 /// timeline, each composed onto the project's own canvas.
852 ///887 ///
crates/engine/tests/saveload.rsmodified+7 -4
@@ -733,7 +733,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
733 fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {733 fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
734 let dir = scratch("mismatch");734 let dir = scratch("mismatch");
735 copy_in(&dir, "test_av.mp4");735 copy_in(&dir, "test_av.mp4");
736- std::fs::copy(asset("test_mismatch.mp4"), dir.join("test_av2.mp4")).expect("substitute");736+ std::fs::copy(asset("test_ac3.mp4"), dir.join("test_av2.mp4")).expect("substitute");
737 let path = dir.join("swapped.edith");737 let path = dir.join("swapped.edith");
738 std::fs::write(738 std::fs::write(
739 &path,739 &path,
@@ -745,12 +745,15 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
745 .expect("a source that stopped matching must not open")745 .expect("a source that stopped matching must not open")
746 .to_string();746 .to_string();
747 // The suffix is `import`'s own refusal, word for word. The substitute is747 // The suffix is `import`'s own refusal, word for word. The substitute is
748- // 640x360 *and* silent; only the second of those is a refusal now -- a748+ // mono, which is the shape of what is left: one output device means one
749- // resolution of its own is placed on the project canvas.749+ // rate and one layout. A resolution of its own is placed on the project
750+ // canvas, a rate of its own is read through `Rate`, a codec of its own
751+ // opens its own decoder and a file with no sound plays silence -- none of
752+ // those is a refusal any more.
750 assert_eq!(753 assert_eq!(
751 err,754 err,
752 format!(755 format!(
753- "source {}: the file is silent, the timeline has audio",756+ "source {}: audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch",
754 dir.join("test_av2.mp4").display()757 dir.join("test_av2.mp4").display()
755 )758 )
756 );759 );
crates/engine/tests/vp9.rsmodified+22 -6
@@ -76,17 +76,33 @@ fn the_software_path_refuses_vp9_by_name() {
76 assert!(h264, "software H.264 decode still opens");76 assert!(h264, "software H.264 decode still opens");
77 }77 }
78 78
79-/// A VP9 timeline is refused a source coded differently, in the same words a79+/// A timeline is *not* refused a source coded differently -- every clip opens
80-/// resolution mismatch is refused in: a front-end shows the string as it is.80+/// its own decoder. What survives is the reason the codec gate existed: on a
81+/// machine that cannot decode VP9 the file is refused at the door, by the
82+/// decoder's own name, rather than becoming a clip of black frames.
81 #[test]83 #[test]
82-fn a_timeline_refuses_the_other_codec() {84+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
83 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");85 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
86+ // The no-plugin machine, forced.
87+ // SAFETY: the suite is documented to run with --test-threads=1.
88+ unsafe { std::env::set_var("VE_SW", "1") };
84 let refused = session89 let refused = session
85 .import(&asset("test_vp9.mp4"))90 .import(&asset("test_vp9.mp4"))
86- .expect_err("VP9 must not join an H.264 timeline")91+ .expect_err("no VP9 decoder means no VP9 clip")
87 .to_string();92 .to_string();
88- assert!(refused.contains("VP9"), "{refused}");93+ unsafe { std::env::remove_var("VE_SW") };
89- assert!(refused.contains("H.264"), "{refused}");94+ assert_eq!(refused, Codec::Vp9.needs_plugin());
95+ assert!(
96+ !refused.contains("H.264"),
97+ "the timeline's own codec is no longer a reason: {refused}"
98+ );
99+ assert_eq!(session.sources().len(), 1, "a refusal left no row");
100+
101+ // ...and where a decoder exists, it simply joins.
102+ match session.import(&asset("test_vp9.mp4")) {
103+ Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 beside H.264"),
104+ Err(e) => assert_eq!(e.to_string(), Codec::Vp9.needs_plugin()),
105+ }
90 }106 }
91 107
92 /// The end-to-end user path: opening the file yields pictures, all of them,108 /// The end-to-end user path: opening the file yields pictures, all of them,