forge
Explore
Log in

Don't you dare go Hollow

Silences are cut out or played fast in one press

Browse files at this commit

d4ac3fc4f0a2b951234a74ab7f00cd9598a2178aAhmet Kaan GümüşParent: c892972
  • feat
    • silences are cut out or played fast in one press
Show full message
✨ feat(timeline): silences are cut out or played fast in one press

A scan of the selected clip's own sound (RMS dBFS over 20 ms windows, off
the decode path the waveform already takes) marks every silence on the
lane before anything moves; `enter` cuts them all out with a ripple, `f`
plays them at 4x with the room they no longer need closed behind them.
Either way it is one edit and one undo press, however many it found.

Four numbers, all keyboard-driven from the card: the threshold, the quiet
short enough to forgive, the padding kept either side of speech, and the
kept sliver short enough to swallow -- the last of which is what stops a
breath between two silences surviving as one-frame confetti.

`set_speed` does not ripple, so speed mode closes the gaps itself; a clip
on another lane lapping over a silence is refused by name, because the
lanes would shrink by different amounts. A source with no audio track at
all is refused by name too rather than read as one long silence.

Output is ordinary clips: `.edith` stays v8.
crates/app/src/keymap.rsmodified+33 -5
@@ -71,13 +71,14 @@ pub enum ActionId {
71 VolumeDown,71 VolumeDown,
72 Equalizer,72 Equalizer,
73 Speed,73 Speed,
74+ Silence,
74 CancelExport,75 CancelExport,
75 }76 }
76 77
77 impl ActionId {78 impl ActionId {
78 /// Display order everywhere -- the editor lists them in it and79 /// Display order everywhere -- the editor lists them in it and
79 /// [`Keymap::defaults`] binds them in it.80 /// [`Keymap::defaults`] binds them in it.
80- pub const ALL: [ActionId; 32] = [81+ pub const ALL: [ActionId; 33] = [
81 ActionId::Play,82 ActionId::Play,
82 ActionId::StepBack,83 ActionId::StepBack,
83 ActionId::StepForward,84 ActionId::StepForward,
@@ -109,6 +110,7 @@ impl ActionId {
109 ActionId::VolumeDown,110 ActionId::VolumeDown,
110 ActionId::Equalizer,111 ActionId::Equalizer,
111 ActionId::Speed,112 ActionId::Speed,
113+ ActionId::Silence,
112 ActionId::CancelExport,114 ActionId::CancelExport,
113 ];115 ];
114 116
@@ -146,6 +148,7 @@ impl ActionId {
146 ActionId::VolumeDown => "Volume down",148 ActionId::VolumeDown => "Volume down",
147 ActionId::Equalizer => "Equalizer",149 ActionId::Equalizer => "Equalizer",
148 ActionId::Speed => "Speed (tape)…",150 ActionId::Speed => "Speed (tape)…",
151+ ActionId::Silence => "Silences: cut or speed up…",
149 ActionId::CancelExport => "Cancel export",152 ActionId::CancelExport => "Cancel export",
150 }153 }
151 }154 }
@@ -185,6 +188,7 @@ impl ActionId {
185 ActionId::VolumeDown => "volume-down",188 ActionId::VolumeDown => "volume-down",
186 ActionId::Equalizer => "equalizer",189 ActionId::Equalizer => "equalizer",
187 ActionId::Speed => "speed",190 ActionId::Speed => "speed",
191+ ActionId::Silence => "silence",
188 ActionId::CancelExport => "cancel-export",192 ActionId::CancelExport => "cancel-export",
189 }193 }
190 }194 }
@@ -217,7 +221,11 @@ impl ActionId {
217 // A rate is the clip's, not the sound's: it re-times the picture221 // A rate is the clip's, not the sound's: it re-times the picture
218 // and the sound together, and the card opens on whichever half was222 // and the sound together, and the card opens on whichever half was
219 // clicked.223 // clicked.
220- | ActionId::Speed => Category::Clips,224+ | ActionId::Speed
225+ // The scan reads a clip's sound, but what it does is edit the
226+ // timeline the clip is on -- it is a clip card like the three
227+ // above it, opened on whichever half was picked.
228+ | ActionId::Silence => Category::Clips,
221 // The project's own picture size is not a clip's business, and not229 // The project's own picture size is not a clip's business, and not
222 // a file operation either: it is what the viewer is looking at.230 // a file operation either: it is what the viewer is looking at.
223 ActionId::Resolution => Category::View,231 ActionId::Resolution => Category::View,
@@ -283,7 +291,7 @@ pub struct Fixed {
283 pub category: Category,291 pub category: Category,
284 }292 }
285 293
286-pub const FIXED: [Fixed; 12] = [294+pub const FIXED: [Fixed; 14] = [
287 Fixed {295 Fixed {
288 chord: "esc",296 chord: "esc",
289 label: "Close this card or menu, or cancel a capture",297 label: "Close this card or menu, or cancel a capture",
@@ -349,6 +357,20 @@ pub const FIXED: [Fixed; 12] = [
349 label: "Take the colour grade off the clip",357 label: "Take the colour grade off the clip",
350 category: Category::Clips,358 category: Category::Clips,
351 },359 },
360+ // The silence card's two apply keys. Card-local like every stroke above --
361+ // they mean nothing while it is closed -- but the card is the one place in
362+ // this editor where a key rewrites forty places at once, so both of them
363+ // are listed rather than hidden in the card's own hint line.
364+ Fixed {
365+ chord: "enter",
366+ label: "Cut every silence the card found",
367+ category: Category::Clips,
368+ },
369+ Fixed {
370+ chord: "f",
371+ label: "Speed the silences up instead of cutting them",
372+ category: Category::Clips,
373+ },
352 ];374 ];
353 375
354 /// A stroke as the key handler sees it: gpui's key name plus the one modifier376 /// A stroke as the key handler sees it: gpui's key name plus the one modifier
@@ -520,6 +542,11 @@ impl Keymap {
520 // right hand with the other clip keys (k grades, l lifts), and542 // right hand with the other clip keys (k grades, l lifts), and
521 // is not next to anything that deletes.543 // is not next to anything that deletes.
522 b(ActionId::Speed, "j", false),544 b(ActionId::Speed, "j", false),
545+ // The silence card takes "u": free, sits with the other clip-card
546+ // keys under the right hand, and is nowhere near the two that
547+ // delete (x and delete) -- what it opens is a card that can cut
548+ // forty places at once.
549+ b(ActionId::Silence, "u", false),
523 b(ActionId::CancelExport, "escape", false),550 b(ActionId::CancelExport, "escape", false),
524 ],551 ],
525 }552 }
@@ -782,7 +809,7 @@ mod tests {
782 #[test]809 #[test]
783 fn every_default_stroke_reaches_its_action() {810 fn every_default_stroke_reaches_its_action() {
784 let k = Keymap::defaults();811 let k = Keymap::defaults();
785- assert_eq!(k.entries().len(), 34);812+ assert_eq!(k.entries().len(), 35);
786 assert_eq!(k.lookup("space", false), Some(ActionId::Play));813 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
787 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two814 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
788 // ends of the timeline.815 // ends of the timeline.
@@ -828,6 +855,7 @@ mod tests {
828 assert_eq!(k.lookup("e", true), None);855 assert_eq!(k.lookup("e", true), None);
829 assert_eq!(k.lookup("space", true), None);856 assert_eq!(k.lookup("space", true), None);
830 assert_eq!(k.lookup("j", false), Some(ActionId::Speed));857 assert_eq!(k.lookup("j", false), Some(ActionId::Speed));
858+ assert_eq!(k.lookup("u", false), Some(ActionId::Silence));
831 assert_eq!(k.lookup("j", true), None);859 assert_eq!(k.lookup("j", true), None);
832 // Nothing is bound twice, or lookup's first match would be a coin toss.860 // Nothing is bound twice, or lookup's first match would be a coin toss.
833 for (i, a) in k.entries().iter().enumerate() {861 for (i, a) in k.entries().iter().enumerate() {
@@ -1010,7 +1038,7 @@ mod tests {
1010 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1038 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1011 // The label is the editor's column, and never the file's word for it.1039 // The label is the editor's column, and never the file's word for it.
1012 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1040 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1013- assert_eq!(ActionId::ALL.len(), 32);1041+ assert_eq!(ActionId::ALL.len(), 33);
1014 }1042 }
1015 1043
1016 #[test]1044 #[test]
crates/app/src/main.rsmodified+539 -11
@@ -357,6 +357,33 @@ fn speed_at(permille: i32) -> Speed {
357 Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16)357 Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16)
358 }358 }
359 359
360+/// The silence card's rows, in the order it lists them: the four settings a
361+/// scan is told and the rate the speed-up plays at. What `silence_field`
362+/// indexes and what [`Player::nudge_silence`] moves.
363+const SILENCE_ROWS: usize = 5;
364+
365+/// One press of a nudge key on each kind of row: a dB on the threshold, a
366+/// twentieth of a second on the three durations, and the speed card's own step
367+/// on the rate.
368+const SILENCE_DB_STEP: f32 = 1.;
369+const SILENCE_SECS_STEP: f64 = 0.05;
370+
371+/// How far each of them may be pushed. UI decisions, all of them: the engine
372+/// takes any finite number, but a threshold at 0 dBFS calls a whole take silent
373+/// and a forgiveness of ten seconds finds nothing in a talking head.
374+const SILENCE_DB_RANGE: (f32, f32) = (-80., -10.);
375+const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.);
376+
377+/// The speed-up rate is bounded *below* by real time: a "speed-up" that slows
378+/// the silence down would make the timeline longer, which is the one thing
379+/// neither button may do. The top is [`Speed::MAX`].
380+fn silence_rate(permille: i32) -> Speed {
381+ speed_at(permille.clamp(
382+ i32::from(Speed::NORMAL.permille()) + SPEED_STEP,
383+ i32::from(Speed::MAX.permille()),
384+ ))
385+}
386+
360 /// The graph's frequency axis: the range an ear works in, and the range every387 /// The graph's frequency axis: the range an ear works in, and the range every
361 /// band a file can carry sits inside. Log-spaced, so an octave is an octave388 /// band a file can carry sits inside. Log-spaced, so an octave is an octave
362 /// wherever it falls.389 /// wherever it falls.
@@ -571,6 +598,25 @@ struct Player {
571 /// The bar is being dragged. On the root like the colour card's, for the598 /// The bar is being dragged. On the root like the colour card's, for the
572 /// same reason: the pointer leaves a 4 px bar on the first move.599 /// same reason: the pointer leaves a 4 px bar on the first move.
573 speed_dragging: bool,600 speed_dragging: bool,
601+ /// The silence card is up on this clip -- the lane it is on and its index
602+ /// there, exactly as the speed card's handle is.
603+ silence_open: Option<(Lane, usize)>,
604+ /// What a scan is told to look for, and how fast the speed-up button plays
605+ /// what it found. Kept across closes like the export card's quality: a
606+ /// second run offers what the first one settled on.
607+ silence: engine::silence::Settings,
608+ silence_factor: Speed,
609+ /// Which of the card's [`SILENCE_ROWS`] the arrow keys move. The card's own
610+ /// focus, since nothing in it takes gpui's (ledger:182).
611+ silence_field: usize,
612+ /// What the last scan found, in timeline frames: what the lane draws marks
613+ /// over and what an apply acts on -- *exactly* the previewed set, never a
614+ /// second scan at the moment of the press.
615+ silence_marks: Vec<(u32, u32)>,
616+ /// The levels of the last source scanned, kept so moving a threshold is
617+ /// arithmetic rather than another decode. One entry: a card is open on one
618+ /// clip, and the next one it opens on is the next thing worth holding.
619+ silence_levels: Option<(PathBuf, usize, Arc<Vec<f32>>)>,
574 /// Which of the card's four sliders the arrow keys and a drag move. The620 /// Which of the card's four sliders the arrow keys and a drag move. The
575 /// card's own focus, since nothing in it takes gpui's (ledger:182).621 /// card's own focus, since nothing in it takes gpui's (ledger:182).
576 color_band: usize,622 color_band: usize,
@@ -738,6 +784,7 @@ impl Player {
738 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),784 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
739 ActionId::Equalizer => self.open_eq(cx),785 ActionId::Equalizer => self.open_eq(cx),
740 ActionId::Speed => self.open_speed(cx),786 ActionId::Speed => self.open_speed(cx),
787+ ActionId::Silence => self.open_silence(cx),
741 // Nothing to cancel while nothing is exporting; the export guard in788 // Nothing to cancel while nothing is exporting; the export guard in
742 // the key handler is what answers this one while there is.789 // the key handler is what answers this one while there is.
743 ActionId::CancelExport => {}790 ActionId::CancelExport => {}
@@ -1004,11 +1051,12 @@ impl Player {
1004 Some(clip) => {1051 Some(clip) => {
1005 self.speed_open = Some(clip);1052 self.speed_open = Some(clip);
1006 self.speed_dragging = false;1053 self.speed_dragging = false;
1007- // One card at a time, the rule the other three follow.1054+ // One card at a time, the rule the other four follow.
1008 self.keys_open = false;1055 self.keys_open = false;
1009 self.export_open = false;1056 self.export_open = false;
1010 self.eq_open = None;1057 self.eq_open = None;
1011 self.color_open = None;1058 self.color_open = None;
1059+ self.close_silence();
1012 self.context_menu = None;1060 self.context_menu = None;
1013 }1061 }
1014 None => self.notice = Some("no clip under the playhead to re-time".into()),1062 None => self.notice = Some("no clip under the playhead to re-time".into()),
@@ -1085,6 +1133,225 @@ impl Player {
1085 self.write_speed(speed_at(stepped), !first, cx);1133 self.write_speed(speed_at(stepped), !first, cx);
1086 }1134 }
1087 1135
1136+ /// Opens the silence card on the clip to be scanned: the selected one, or
1137+ /// -- with nothing selected -- the clip the picture is coming from, which is
1138+ /// the rule the speed card follows and what a person means by "this shot".
1139+ /// Either half of a take will do: the scan reads the *source*, and both
1140+ /// halves of an A/V take name the same file.
1141+ ///
1142+ /// The scan runs at once, so the card is never up saying nothing: a clip
1143+ /// whose source has no audio track at all is refused by name instead, and
1144+ /// the card does not open on it.
1145+ fn open_silence(&mut self, cx: &mut Context<Self>) {
1146+ if self.exporting().is_some() {
1147+ return;
1148+ }
1149+ let Some(session) = &self.session else {
1150+ self.notice = Some("no timeline to scan — open a file first".into());
1151+ cx.notify();
1152+ return;
1153+ };
1154+ match self
1155+ .selected
1156+ .or_else(|| session.video_clip_at(session.now()))
1157+ .map(|clip| audio_half(session, clip))
1158+ {
1159+ Some(clip) => {
1160+ self.silence_open = Some(clip);
1161+ self.silence_field = 0;
1162+ // One card at a time, the rule the other four follow.
1163+ self.keys_open = false;
1164+ self.export_open = false;
1165+ self.eq_open = None;
1166+ self.color_open = None;
1167+ self.speed_open = None;
1168+ self.context_menu = None;
1169+ self.scan_silences();
1170+ }
1171+ None => self.notice = Some("no clip under the playhead to scan".into()),
1172+ }
1173+ cx.notify();
1174+ }
1175+
1176+ /// Closes it and drops the preview with it: marks left on the lane after
1177+ /// the card is gone would name frames the next edit has already moved.
1178+ fn close_silence(&mut self) {
1179+ self.silence_open = None;
1180+ self.silence_marks.clear();
1181+ }
1182+
1183+ /// Runs the scan and replaces the preview -- never stacks on it. The decode
1184+ /// happens once per source ([`engine::silence::levels`] is cached here), so
1185+ /// every later run is the settings applied to numbers already in hand,
1186+ /// which is what makes moving a threshold feel like moving a slider.
1187+ ///
1188+ /// Changes nothing about the project: a preview is not an edit, and no undo
1189+ /// step is spent until a button is pressed.
1190+ ///
1191+ /// ponytail: the first scan for a source runs on the render thread -- ~1700x
1192+ /// realtime, so a ten-minute take is well under a second and an hour-long
1193+ /// one would be felt. Upgrade path is the waveform's: hand it to
1194+ /// `cx.background_spawn` and repaint when it lands.
1195+ fn scan_silences(&mut self) {
1196+ let Some((lane, idx)) = self.silence_open else {
1197+ return;
1198+ };
1199+ self.silence_marks.clear();
1200+ // Copied out before anything is written back: the cache below lives on
1201+ // the same struct the session does.
1202+ let Some((clip, source)) = self.session.as_ref().and_then(|session| {
1203+ let clip = *session.lane_clips(lane).get(idx)?;
1204+ Some((clip, session.sources().get(clip.source)?.clone()))
1205+ }) else {
1206+ return;
1207+ };
1208+ let cached = self
1209+ .silence_levels
1210+ .as_ref()
1211+ .filter(|(path, stream, _)| *path == source.path && *stream == source.audio_stream)
1212+ .map(|(_, _, levels)| levels.clone());
1213+ let levels = match cached {
1214+ Some(levels) => levels,
1215+ None => match engine::silence::levels(&source.path, source.audio_stream) {
1216+ Ok(Some(levels)) => {
1217+ let levels = Arc::new(levels);
1218+ self.silence_levels =
1219+ Some((source.path.clone(), source.audio_stream, levels.clone()));
1220+ levels
1221+ }
1222+ // A source with no audio track is not one long silence: it is a
1223+ // clip this card has nothing to say about, named so the user
1224+ // knows which one it meant.
1225+ Ok(None) => {
1226+ self.silence_open = None;
1227+ self.notice = Some(
1228+ format!(
1229+ "{} clip {} has no audio to scan — {} is silent",
1230+ lane.label(),
1231+ idx + 1,
1232+ file_name(&source.path)
1233+ )
1234+ .into(),
1235+ );
1236+ return;
1237+ }
1238+ Err(e) => {
1239+ self.silence_open = None;
1240+ self.notice = Some(format!("SCAN FAILED: {e}").into());
1241+ return;
1242+ }
1243+ },
1244+ };
1245+ self.silence_marks = engine::silence::timeline_regions(
1246+ &clip,
1247+ self.fps,
1248+ &engine::silence::regions(&levels, self.silence),
1249+ );
1250+ }
1251+
1252+ /// Moves the picked row by `steps` and re-runs the scan against it, so the
1253+ /// marks on the lane are always what the numbers on the card say.
1254+ fn nudge_silence(&mut self, steps: i32) {
1255+ let secs = |at: f64| {
1256+ (at + f64::from(steps) * SILENCE_SECS_STEP)
1257+ .clamp(SILENCE_SECS_RANGE.0, SILENCE_SECS_RANGE.1)
1258+ };
1259+ match self.silence_field {
1260+ 0 => {
1261+ self.silence.threshold_db = (self.silence.threshold_db
1262+ + steps as f32 * SILENCE_DB_STEP)
1263+ .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1)
1264+ }
1265+ 1 => self.silence.min_silence = secs(self.silence.min_silence),
1266+ 2 => self.silence.padding = secs(self.silence.padding),
1267+ 3 => self.silence.min_keep = secs(self.silence.min_keep),
1268+ _ => {
1269+ self.silence_factor =
1270+ silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP)
1271+ }
1272+ }
1273+ // The rate is not part of the scan, but re-running is cheap (the levels
1274+ // are cached) and one path is one place for the marks to come from.
1275+ self.scan_silences();
1276+ }
1277+
1278+ /// What an apply acts on: the previewed set, or nothing at all with a
1279+ /// notice saying so in the numbers that found nothing.
1280+ fn previewed(&mut self) -> Option<Vec<(u32, u32)>> {
1281+ if self.silence_marks.is_empty() {
1282+ self.notice = Some(
1283+ format!(
1284+ "no silence under {:.0} dBFS lasting {:.2} s — raise the threshold or forgive less",
1285+ self.silence.threshold_db, self.silence.min_silence
1286+ )
1287+ .into(),
1288+ );
1289+ return None;
1290+ }
1291+ Some(self.silence_marks.clone())
1292+ }
1293+
1294+ /// Cuts every previewed silence out of every lane, rippling each hole
1295+ /// closed -- one edit and **one** undo press however many there were
1296+ /// ([`engine::PlaybackSession::cut_regions`]). The linked picture slides
1297+ /// with its sound, because a ripple is uniform across the lanes.
1298+ fn cut_silences(&mut self, cx: &mut Context<Self>) {
1299+ let Some(regions) = self.previewed() else {
1300+ cx.notify();
1301+ return;
1302+ };
1303+ let saved = f64::from(regions.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;
1304+ let count = regions.len();
1305+ let cut = self
1306+ .session
1307+ .as_mut()
1308+ .is_some_and(|session| session.cut_regions(&regions));
1309+ if cut {
1310+ self.close_silence();
1311+ self.reset_after_reseek();
1312+ self.notice = Some(
1313+ format!(
1314+ "{count} SILENCES CUT — {saved:.1}s shorter, {} takes it back",
1315+ self.keymap.display(ActionId::Undo)
1316+ )
1317+ .into(),
1318+ );
1319+ }
1320+ cx.notify();
1321+ }
1322+
1323+ /// Plays them fast instead of cutting them, closing the room each one no
1324+ /// longer needs. One undo press like the cut; the refusal (a clip on
1325+ /// another lane lapping over a silence) comes back in the engine's own
1326+ /// words and names the lane and frame, and the card stays up so the numbers
1327+ /// that produced it are still on screen.
1328+ fn speed_silences(&mut self, cx: &mut Context<Self>) {
1329+ let Some(regions) = self.previewed() else {
1330+ cx.notify();
1331+ return;
1332+ };
1333+ let (count, rate) = (regions.len(), self.silence_factor);
1334+ let Some(session) = self.session.as_mut() else {
1335+ cx.notify();
1336+ return;
1337+ };
1338+ match session.speed_regions(&regions, rate) {
1339+ Ok(()) => {
1340+ self.close_silence();
1341+ self.reset_after_reseek();
1342+ self.notice = Some(
1343+ format!(
1344+ "{count} SILENCES AT {rate} — {} takes it back",
1345+ self.keymap.display(ActionId::Undo)
1346+ )
1347+ .into(),
1348+ );
1349+ }
1350+ Err(e) => self.notice = Some(e.to_string().into()),
1351+ }
1352+ cx.notify();
1353+ }
1354+
1088 /// Whether a card owns the window. While one does the timeline under it is1355 /// Whether a card owns the window. While one does the timeline under it is
1089 /// out of reach, so a right-click there opens no menu -- the same rule the1356 /// out of reach, so a right-click there opens no menu -- the same rule the
1090 /// key handler and the drop target already follow.1357 /// key handler and the drop target already follow.
@@ -1094,6 +1361,7 @@ impl Player {
1094 || self.eq_open.is_some()1361 || self.eq_open.is_some()
1095 || self.color_open.is_some()1362 || self.color_open.is_some()
1096 || self.speed_open.is_some()1363 || self.speed_open.is_some()
1364+ || self.silence_open.is_some()
1097 || self.exporting().is_some()1365 || self.exporting().is_some()
1098 }1366 }
1099 1367
@@ -1960,6 +2228,8 @@ impl Player {
1960 self.context_menu = None;2228 self.context_menu = None;
1961 self.eq_open = None;2229 self.eq_open = None;
1962 self.color_open = None;2230 self.color_open = None;
2231+ // Marks are timeline frames of the timeline that was.
2232+ self.close_silence();
1963 // A different set of sources: the row that was picked is not2233 // A different set of sources: the row that was picked is not
1964 // the file that index names any more.2234 // the file that index names any more.
1965 self.selected_asset = None;2235 self.selected_asset = None;
@@ -2500,6 +2770,31 @@ impl Render for Player {
2500 cx.notify();2770 cx.notify();
2501 return;2771 return;
2502 }2772 }
2773+ // The silence card, the same way again: the arrows pick one of
2774+ // its rows and move it, and its two apply keys are the two
2775+ // things it can do to the timeline. Card-local, every one of
2776+ // them -- and listed in the keys menu (keymap.rs `FIXED`),
2777+ // because a key that cuts forty places at once is not a secret.
2778+ if this.silence_open.is_some() {
2779+ if key == ESCAPE {
2780+ // Nothing to undo: a preview is not an edit.
2781+ this.close_silence();
2782+ } else if key == "down" {
2783+ this.silence_field = (this.silence_field + 1) % SILENCE_ROWS;
2784+ } else if key == "up" {
2785+ this.silence_field = (this.silence_field + SILENCE_ROWS - 1) % SILENCE_ROWS;
2786+ } else if key == "right" {
2787+ this.nudge_silence(1);
2788+ } else if key == "left" {
2789+ this.nudge_silence(-1);
2790+ } else if key == "enter" {
2791+ this.cut_silences(cx);
2792+ } else if key == "f" {
2793+ this.speed_silences(cx);
2794+ }
2795+ cx.notify();
2796+ return;
2797+ }
2503 // A clip menu names an index, and every edit below moves2798 // A clip menu names an index, and every edit below moves
2504 // indices -- so a stroke closes it before it acts. Escape means2799 // indices -- so a stroke closes it before it acts. Escape means
2505 // that and nothing else, which is the `esc` the keys menu2800 // that and nothing else, which is the `esc` the keys menu
@@ -2711,6 +3006,7 @@ impl Render for Player {
2711 .children(self.eq_card(cx))3006 .children(self.eq_card(cx))
2712 .children(self.color_card(cx))3007 .children(self.color_card(cx))
2713 .children(self.speed_card(cx))3008 .children(self.speed_card(cx))
3009+ .children(self.silence_card(cx))
2714 }3010 }
2715 }3011 }
2716 3012
@@ -4137,6 +4433,147 @@ impl Player {
4137 )4433 )
4138 }4434 }
4139 4435
4436+ /// The silence card: what the scan is looking for, what it found, and the
4437+ /// two things that can be done about it.
4438+ ///
4439+ /// Its scrim is the lightest of the cards' on purpose. Every other card is
4440+ /// about the clip it names and can black the timeline out; this one is
4441+ /// *about* the timeline -- the marks under it are the whole preview -- so
4442+ /// the bed stays readable and the card sits up in the picture area rather
4443+ /// than over the lanes.
4444+ fn silence_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
4445+ let (lane, idx) = self.silence_open?;
4446+ let cfg = self.silence;
4447+ let rows = [
4448+ ("Silence is under", format!("{:.0} dBFS", cfg.threshold_db)),
4449+ (
4450+ "Forgive quiet shorter than",
4451+ format!("{:.2} s", cfg.min_silence),
4452+ ),
4453+ (
4454+ "Keep either side of speech",
4455+ format!("{:.2} s", cfg.padding),
4456+ ),
4457+ (
4458+ "Swallow kept slivers under",
4459+ format!("{:.2} s", cfg.min_keep),
4460+ ),
4461+ ("Speed-up plays at", format!("{}", self.silence_factor)),
4462+ ];
4463+ let found = self.silence_marks.len();
4464+ let secs =
4465+ f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;
4466+ let rows: Vec<_> = rows
4467+ .into_iter()
4468+ .enumerate()
4469+ .map(|(n, (label, value))| {
4470+ div()
4471+ .id(("silence-row", n))
4472+ .flex()
4473+ .min_h(px(KEYS_ROW_H))
4474+ .items_center()
4475+ .justify_between()
4476+ .px(px(6.))
4477+ .rounded(px(3.))
4478+ .bg(rgb(match n == self.silence_field {
4479+ true => SELECTED,
4480+ false => CHROME,
4481+ }))
4482+ .cursor_pointer()
4483+ .hover(|s| s.bg(rgb(HOVER)))
4484+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
4485+ this.silence_field = n;
4486+ cx.notify();
4487+ }))
4488+ .child(div().text_color(rgb(INK_DIM)).child(label))
4489+ .child(value)
4490+ })
4491+ .collect();
4492+ // The two buttons the ask names, side by side: a mode toggle would hide
4493+ // one of them behind the other, and there are only two.
4494+ let button = |n: usize, text: String, act: fn(&mut Self, &mut Context<Self>)| {
4495+ div()
4496+ .id(("silence-apply", n))
4497+ .flex_1()
4498+ .flex()
4499+ .min_h(px(KEYS_ROW_H))
4500+ .items_center()
4501+ .justify_center()
4502+ .rounded(px(3.))
4503+ .bg(rgb(match found {
4504+ 0 => CHROME,
4505+ _ => SELECTED,
4506+ }))
4507+ .cursor_pointer()
4508+ .hover(|s| s.bg(rgb(HOVER)))
4509+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| act(this, cx)))
4510+ .child(text)
4511+ };
4512+ Some(
4513+ div()
4514+ .absolute()
4515+ .inset_0()
4516+ .flex()
4517+ .justify_center()
4518+ .items_start()
4519+ .pt(px(HEADER_H + 8.))
4520+ // Light enough to read the lanes and the marks on them through:
4521+ // the preview is the point of this card.
4522+ .bg(rgba(0x10101055))
4523+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
4524+ cx.stop_propagation()
4525+ })
4526+ .child(
4527+ div()
4528+ .w(px(COLOR_W))
4529+ .flex()
4530+ .flex_col()
4531+ .gap(px(6.))
4532+ .p(px(12.))
4533+ .rounded(px(6.))
4534+ .bg(rgb(SURFACE))
4535+ .child(div().flex_none().px(px(6.)).child(format!(
4536+ "Silences — {} clip {}",
4537+ lane.label(),
4538+ idx + 1
4539+ )))
4540+ .child(
4541+ div()
4542+ .flex_none()
4543+ .px(px(6.))
4544+ .text_size(px(11.))
4545+ .text_color(rgb(INK_DIM))
4546+ .child(
4547+ "↑↓ picks a setting, ←→ moves it — the marks on the lane are what would go; esc closes",
4548+ ),
4549+ )
4550+ .children(rows)
4551+ .child(
4552+ div()
4553+ .flex_none()
4554+ .px(px(6.))
4555+ .text_color(rgb(match found {
4556+ 0 => INK_DIM,
4557+ _ => ACCENT,
4558+ }))
4559+ .child(match found {
4560+ 0 => "nothing quiet enough for long enough".to_string(),
4561+ 1 => format!("1 silence, {secs:.1}s"),
4562+ n => format!("{n} silences, {secs:.1}s"),
4563+ }),
4564+ )
4565+ .child(div().flex().gap(px(4.)).children([
4566+ button(0, "Cut them out (enter)".into(), Self::cut_silences),
4567+ button(
4568+ 1,
4569+ format!("Play them at {} (f)", self.silence_factor),
4570+ Self::speed_silences,
4571+ ),
4572+ ])),
4573+ ),
4574+ )
4575+ }
4576+
4140 /// The menu a right-click on a library row opens: what can be done with the4577 /// The menu a right-click on a library row opens: what can be done with the
4141 /// *file* rather than with a clip of it, and a turn-over side saying what4578 /// *file* rather than with a clip of it, and a turn-over side saying what
4142 /// that file is. Built like [`Player::context_card`] down to the scrim, the4579 /// that file is. Built like [`Player::context_card`] down to the scrim, the
@@ -4783,6 +5220,25 @@ impl Player {
4783 )5220 )
4784 })5221 })
4785 }))5222 }))
5223+ // What the silence card found, over the clips it found them
5224+ // in and over the waveform band that shows why: on the lane
5225+ // the scan ran on and no other, because that is the only
5226+ // lane whose sound was read. Drawn before anything is cut,
5227+ // and replaced -- never stacked -- by every re-run.
5228+ .children(
5229+ self.silence_marks
5230+ .iter()
5231+ .filter(|_| self.silence_open.is_some_and(|(on, _)| on == lane))
5232+ .map(|&(at, len)| {
5233+ div()
5234+ .absolute()
5235+ .top_0()
5236+ .h_full()
5237+ .left(relative(start_frac(f64::from(at) / self.fps, duration)))
5238+ .w(relative(width_frac(f64::from(len) / self.fps, duration)))
5239+ .bg(rgba(0x4a9effaa))
5240+ }),
5241+ )
4786 // Last, so it is over the clips: the same fraction in both5242 // Last, so it is over the clips: the same fraction in both
4787 // lanes, which is the playhead being one line.5243 // lanes, which is the playhead being one line.
4788 .child(5244 .child(
@@ -5377,6 +5833,36 @@ enum ColorKey {
5377 Reset,5833 Reset,
5378 }5834 }
5379 5835
5836+/// The half of a take whose *sound* the silence card scans: a link is one span
5837+/// on however many lanes, so a card opened on the picture opens on the sound it
5838+/// is grouped with. That is the lane the waveform is drawn on, and so the lane
5839+/// the marks have to land on to be read against it -- and the ranges agree,
5840+/// because a group is one span.
5841+///
5842+/// The clip itself for one already on an audio lane, for a detached picture,
5843+/// and for a take whose sound is not on any lane: there is nothing better to
5844+/// open on, and the refusal for a source with no audio at all is `scan`'s.
5845+fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) {
5846+ if lane.kind == LaneKind::Audio {
5847+ return (lane, idx);
5848+ }
5849+ let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else {
5850+ return (lane, idx);
5851+ };
5852+ session
5853+ .lanes()
5854+ .into_iter()
5855+ .filter(|l| l.kind == LaneKind::Audio)
5856+ .find_map(|l| {
5857+ session
5858+ .lane_clips(l)
5859+ .iter()
5860+ .position(|c| c.link == Some(link))
5861+ .map(|i| (l, i))
5862+ })
5863+ .unwrap_or((lane, idx))
5864+}
5865+
5380 fn color_key(key: &str) -> Option<ColorKey> {5866 fn color_key(key: &str) -> Option<ColorKey> {
5381 Some(match key {5867 Some(match key {
5382 ESCAPE => ColorKey::Close,5868 ESCAPE => ColorKey::Close,
@@ -6094,16 +6580,17 @@ mod tests {
6094 use super::{6580 use super::{
6095 ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH,6581 ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH,
6096 EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS,6582 EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS,
6097- Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM,6583+ Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,
6098- KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,6584+ INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
6099- LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,6585+ LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H,
6100- RULER_HIT_H, SELECTED, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source,6586+ Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS,
6101- Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add,6587+ SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave,
6102- cancels_export, color_snap, envelope, eq_x, eq_y, export_path, export_settings, format_key,6588+ applicable, band_label, can_add, cancels_export, color_snap, envelope, eq_x, eq_y,
6103- format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier,6589+ export_path, export_settings, format_key, format_line, format_refusal, frac_along,
6104- is_project, keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit,6590+ frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked,
6105- retarget, scrub_due, show_label, source_tint, span_partner, speed_at, start_frac, timecode,6591+ menu_at, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,
6106- unseen_paths, unseen_sources, whole_take, width_frac, window_title,6592+ silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths,
6593+ unseen_sources, whole_take, width_frac, window_title,
6107 };6594 };
6108 use super::{file_name, file_uri, library_rows};6595 use super::{file_name, file_uri, library_rows};
6109 6596
@@ -7591,6 +8078,39 @@ mod tests {
7591 assert!(u64::from(push_digit(99, 9)) * 1_000_000 < u64::from(u32::MAX));8078 assert!(u64::from(push_digit(99, 9)) * 1_000_000 < u64::from(u32::MAX));
7592 }8079 }
7593 8080
8081+ #[test]
8082+ fn the_silence_card_fits_the_smallest_window_and_never_slows_a_silence_down() {
8083+ // The same 640x360 floor, and this card starts below the header: a
8084+ // title and a hint over its five rows, the count line and the two
8085+ // buttons.
8086+ let (title, hint, count) = (17., 17., 17.);
8087+ let gaps = 6. * 5.;
8088+ let padding = 24.;
8089+ assert!(
8090+ HEADER_H
8091+ + 8.
8092+ + title
8093+ + hint
8094+ + SILENCE_ROWS as f32 * KEYS_ROW_H
8095+ + count
8096+ + KEYS_ROW_H
8097+ + gaps
8098+ + padding
8099+ <= 360.,
8100+ "card too tall"
8101+ );
8102+ // Its rows and buttons are clicked, so WCAG 2.5.8 binds them.
8103+ assert!(KEYS_ROW_H >= HIT_MIN);
8104+ // A "speed-up" is never a slow-down: the rate stops above real time at
8105+ // one end and at what a clip can hold at the other, whatever the keys
8106+ // ask for. A silence played *slower* would make the timeline longer,
8107+ // which is the one thing neither button may do.
8108+ assert!(silence_rate(0) > Speed::NORMAL);
8109+ assert!(silence_rate(1000) > Speed::NORMAL);
8110+ assert_eq!(silence_rate(i32::MAX), Speed::MAX);
8111+ assert_eq!(silence_rate(4000), Speed::MAX);
8112+ }
8113+
7594 #[test]8114 #[test]
7595 fn the_export_card_fits_the_smallest_window() {8115 fn the_export_card_fits_the_smallest_window() {
7596 // Same 640x360 floor the keybindings card is measured against: the8116 // Same 640x360 floor the keybindings card is measured against: the
@@ -8051,6 +8571,14 @@ fn main() {
8051 speed_open: None,8571 speed_open: None,
8052 speed_bar: Rc::default(),8572 speed_bar: Rc::default(),
8053 speed_dragging: false,8573 speed_dragging: false,
8574+ silence_open: None,
8575+ // The conservative defaults the engine documents: a first
8576+ // scan that leaves a little too much is one nobody undoes.
8577+ silence: engine::silence::Settings::default(),
8578+ silence_factor: Speed::MAX,
8579+ silence_field: 0,
8580+ silence_marks: Vec::new(),
8581+ silence_levels: None,
8054 color_open: None,8582 color_open: None,
8055 color_band: 0,8583 color_band: 0,
8056 color_dragging: false,8584 color_dragging: false,
crates/engine/src/lib.rsmodified+1 -0
@@ -15,6 +15,7 @@ pub mod mux;
15 pub mod playback;15 pub mod playback;
16 pub mod project;16 pub mod project;
17 pub mod scale;17 pub mod scale;
18+pub mod silence;
18 pub mod waveform;19 pub mod waveform;
19 20
20 pub use audio::{21 pub use audio::{
crates/engine/src/playback.rsmodified+23 -0
@@ -1003,6 +1003,29 @@ impl PlaybackSession {
1003 Ok(())1003 Ok(())
1004 }1004 }
1005 1005
1006+ /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out
1007+ /// of every lane and closes each hole, as **one** edit
1008+ /// ([`Project::cut_regions`]): the jumpcut a silence scan
1009+ /// ([`crate::silence`]) asks for, one undo press however many silences it
1010+ /// found. Reseeks like every other edit, so what plays is the cut timeline
1011+ /// from the playhead on. `false`, and no undo step, for an empty list.
1012+ pub fn cut_regions(&mut self, regions: &[(u32, u32)]) -> bool {
1013+ self.edit(|p| p.cut_regions(regions))
1014+ }
1015+
1016+ /// Plays every one of those regions at `speed` instead of cutting them,
1017+ /// closing the room each one no longer needs ([`Project::speed_regions`]) --
1018+ /// one edit, one undo press. The `Err` names the lane and frame in the way
1019+ /// and nothing changes.
1020+ pub fn speed_regions(&mut self, regions: &[(u32, u32)], speed: Speed) -> crate::Result<()> {
1021+ // Spelled out rather than through `edit`, whose closure hands back a
1022+ // bool and would drop the refusal's own words.
1023+ self.project.speed_regions(regions, speed)?;
1024+ let now = self.now();
1025+ self.seek(now);
1026+ Ok(())
1027+ }
1028+
1006 /// Where that edge may land, `(first, last)` timeline frame inclusive: what1029 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
1007 /// a drag clamps the pointer to so the box it draws is the box1030 /// a drag clamps the pointer to so the box it draws is the box
1008 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.1031 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
crates/engine/src/project.rsmodified+190 -4
@@ -1306,6 +1306,13 @@ impl Project {
1306 ///1306 ///
1307 /// Metadata only: no mapping changes, in any lane.1307 /// Metadata only: no mapping changes, in any lane.
1308 pub fn split(&mut self, timeline_frame: u32) -> bool {1308 pub fn split(&mut self, timeline_frame: u32) -> bool {
1309+ self.write_split(timeline_frame, true)
1310+ }
1311+
1312+ /// [`split`](Project::split), with the snapshot optional: a batch that has
1313+ /// already taken one ([`speed_regions`](Project::speed_regions)) splits at
1314+ /// two frames per region and must still be one undo press.
1315+ fn write_split(&mut self, timeline_frame: u32, snapshot: bool) -> bool {
1309 let cut: Vec<Option<Clip>> = self1316 let cut: Vec<Option<Clip>> = self
1310 .lanes1317 .lanes
1311 .iter()1318 .iter()
@@ -1314,7 +1321,9 @@ impl Project {
1314 if cut.iter().all(Option::is_none) {1321 if cut.iter().all(Option::is_none) {
1315 return false;1322 return false;
1316 }1323 }
1324+ if snapshot {
1317 self.snapshot();1325 self.snapshot();
1326+ }
1318 // Each side is its own question: two clips may start together and end1327 // Each side is its own question: two clips may start together and end
1319 // apart, and every lane whose halves do line up stays one take.1328 // apart, and every lane whose halves do line up stays one take.
1320 let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();1329 let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();
@@ -1861,14 +1870,156 @@ impl Project {
1861 return false;1870 return false;
1862 }1871 }
1863 self.snapshot();1872 self.snapshot();
1873+ ripple(&mut self.lanes, at, len);
1874+ true
1875+ }
1876+
1877+ /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
1878+ /// out of every lane and close each hole, as one edit: the jumpcut a
1879+ /// silence scan asks for ([`crate::silence`]).
1880+ ///
1881+ /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
1882+ /// reason this exists rather than a caller's loop over
1883+ /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
1884+ /// undo press, not forty. Cut back to front, so a region's frames still
1885+ /// mean what the caller measured while the ones before it are cut.
1886+ ///
1887+ /// The list is sorted and overlapping entries are merged before anything is
1888+ /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
1889+ /// other's frames -- and `false`, with no undo step, for a list with
1890+ /// nothing in it.
1891+ pub fn cut_regions(&mut self, regions: &[(u32, u32)]) -> bool {
1892+ let regions = tidy(regions);
1893+ if regions.is_empty() {
1894+ return false;
1895+ }
1896+ self.snapshot();
1897+ for &(at, len) in regions.iter().rev() {
1898+ ripple(&mut self.lanes, at, len);
1899+ }
1900+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
1901+ true
1902+ }
1903+
1904+ /// Play every one of `regions` at `speed` instead of cutting it: each is
1905+ /// split out of whatever covers it, re-rated, and the room it no longer
1906+ /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
1907+ /// does not ripple, and a hole where a silence shrank is the one thing this
1908+ /// must not leave. One snapshot for the lot, like
1909+ /// [`cut_regions`](Project::cut_regions).
1910+ ///
1911+ /// The rate is **absolute**, not a multiplier on what is there: running it
1912+ /// twice over the same stretch leaves it at `speed`, not at `speed`
1913+ /// squared, so a second pass over an already-cut timeline changes nothing.
1914+ ///
1915+ /// Refused by name, with nothing changed and no undo step, when:
1916+ ///
1917+ /// * a clip on any lane covers only *part* of a region -- the lanes shrink
1918+ /// by different amounts and the ripple would pull them apart, which is
1919+ /// what cutting does not suffer and why delete mode has no such refusal;
1920+ /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
1921+ /// piece could not be split out exactly;
1922+ /// * two lanes' pieces would end up different lengths, which is a group
1923+ /// whose halves disagree about their span (the refusal
1924+ /// [`write_speed`](Project::write_speed) already makes, in its words);
1925+ /// * the region would grow rather than shrink, i.e. it already plays faster
1926+ /// than `speed`.
1927+ pub fn speed_regions(&mut self, regions: &[(u32, u32)], speed: Speed) -> crate::Result<()> {
1928+ let regions = tidy(regions);
1929+ if regions.is_empty() {
1930+ return Err("nothing to speed up".into());
1931+ }
1932+ let labels = handles(&self.lanes);
1933+ // Before anything is touched, because this is the refusal a person can
1934+ // act on: a clip that laps over the edge of a silence has to be trimmed
1935+ // (or the silences cut instead), and saying so after a rollback would
1936+ // be saying it about a timeline that already looks different.
1937+ for &(at, len) in &regions {
1938+ for (l, data) in self.lanes.iter().enumerate() {
1939+ for c in &data.clips {
1940+ if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
1941+ {
1942+ return Err(format!(
1943+ "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
1944+ speeding it up would pull the lanes apart -- trim it first, or cut the \
1945+ silences out instead",
1946+ labels[l].label(),
1947+ c.start,
1948+ at + len
1949+ )
1950+ .into());
1951+ }
1952+ }
1953+ }
1954+ }
1955+ // The rest is checked as it is built: a split's own arithmetic is what
1956+ // says whether a rate can address an edge. So the snapshot is taken
1957+ // first and *rolled back* on a refusal -- one undo either way, and a
1958+ // refusal still costs no step (`undo` pops the one just pushed).
1959+ self.snapshot();
1960+ for &(at, len) in regions.iter().rev() {
1961+ self.write_split(at, false);
1962+ self.write_split(at + len, false);
1963+ let mut room: Option<(Lane, u32)> = None;
1964+ let mut refused = None;
1965+ for (l, data) in self.lanes.iter().enumerate() {
1966+ for c in data.clips.iter().filter(|c| c.end() > at && c.start < at + len) {
1967+ if (c.start, c.end()) != (at, at + len) {
1968+ refused = Some(format!(
1969+ "the {} clip at frame {} plays at {} and cannot be cut at frame {at}: \
1970+ detach it, or put it back to 1.00x first",
1971+ labels[l].label(),
1972+ c.start,
1973+ c.speed
1974+ ));
1975+ continue;
1976+ }
1977+ let after = speed.frames(c.len());
1978+ match room {
1979+ None => room = Some((labels[l], after)),
1980+ Some((first, n)) if n != after => {
1981+ refused = Some(format!(
1982+ "at {speed} the {} half of the silence at frame {at} would cover \
1983+ {after} frames and the {} half {n}: they are one take and a take \
1984+ is one span -- detach them first",
1985+ labels[l].label(),
1986+ first.label()
1987+ ));
1988+ }
1989+ Some(_) => {}
1990+ }
1991+ }
1992+ }
1993+ let shrunk = match (refused, room) {
1994+ (Some(e), _) => {
1995+ self.undo();
1996+ return Err(e.into());
1997+ }
1998+ // A gap on every lane: nothing to re-rate, and nothing to close.
1999+ (None, None) => continue,
2000+ (None, Some((_, after))) => after,
2001+ };
2002+ let Some(delta) = len.checked_sub(shrunk) else {
2003+ self.undo();
2004+ return Err(format!(
2005+ "the silence at frame {at} already plays faster than {speed}: \
2006+ at that rate it would be {shrunk} frames instead of {len}"
2007+ )
2008+ .into());
2009+ };
1864 for data in &mut self.lanes {2010 for data in &mut self.lanes {
1865- clear(&mut data.clips, at, at + len);2011+ for c in &mut data.clips {
1866- for c in data.clips.iter_mut().filter(|c| c.start >= at) {2012+ if c.start == at && c.end() == at + len {
1867- c.start -= len;2013+ c.speed = speed;
2014+ } else if c.start >= at + len {
2015+ c.start -= delta;
2016+ }
1868 }2017 }
1869 debug_assert!(sorted_disjoint(&data.clips));2018 debug_assert!(sorted_disjoint(&data.clips));
1870 }2019 }
1871- true2020+ }
2021+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
2022+ Ok(())
1872 }2023 }
1873 2024
1874 /// Remove the `V1` clip at `idx` and everything under it, closing the gap2025 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
@@ -2307,6 +2458,41 @@ fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
2307 *clips = out;2458 *clips = out;
2308 }2459 }
2309 2460
2461+/// Cuts `[at, at + len)` out of every lane and slides what is behind it back --
2462+/// the body of [`Project::ripple_delete`], and of every cut a batch
2463+/// ([`Project::cut_regions`]) makes. No snapshot of its own: whose undo step
2464+/// this is belongs to the caller.
2465+fn ripple(lanes: &mut [LaneData], at: u32, len: u32) {
2466+ for data in lanes {
2467+ clear(&mut data.clips, at, at + len);
2468+ for c in data.clips.iter_mut().filter(|c| c.start >= at) {
2469+ c.start -= len;
2470+ }
2471+ debug_assert!(sorted_disjoint(&data.clips));
2472+ }
2473+}
2474+
2475+/// A caller's region list as a batch may use it: sorted by start, empty entries
2476+/// dropped, and touching or overlapping entries merged into one.
2477+///
2478+/// Overlapping regions are the one thing a batch cannot take -- cutting the
2479+/// second would cut frames the first already moved -- and a detector handing
2480+/// back two that touch means one silence, not two cuts. Merged rather than
2481+/// refused: this is arithmetic on a preview, not a user's mistake.
2482+fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
2483+ let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
2484+ sorted.sort_by_key(|&(at, _)| at);
2485+ let mut out: Vec<(u32, u32)> = Vec::new();
2486+ for (at, len) in sorted {
2487+ let end = at.saturating_add(len);
2488+ match out.last_mut() {
2489+ Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
2490+ _ => out.push((at, len)),
2491+ }
2492+ }
2493+ out
2494+}
2495+
2310 /// Slides everything from `at` on later by `len`, splitting a placement that2496 /// Slides everything from `at` on later by `len`, splitting a placement that
2311 /// straddles `at` so the two halves end up on either side of the hole. The2497 /// straddles `at` so the two halves end up on either side of the hole. The
2312 /// insert half of a rippling paste. The two halves lose the group id for the2498 /// insert half of a rippling paste. The two halves lose the group id for the
crates/engine/src/silence.rsadded+380 -0
@@ -0,0 +1,380 @@
1+//! Where a clip goes quiet: RMS levels off the same read-only decode path the
2+//! waveform takes, and the stretches of them nobody wants to watch.
3+//!
4+//! Three steps, kept apart so only the first one costs a decode: [`levels`]
5+//! turns a file into one loudness number per 20 ms window, [`regions`] turns
6+//! those numbers plus a [`Settings`] into silent stretches of *source* seconds,
7+//! and [`timeline_regions`] puts those on the timeline through one clip's own
8+//! range and rate. A card tweaking a threshold re-runs the last two and decodes
9+//! nothing.
10+//!
11+//! Loudness in **dBFS**, which is the unit every tool that does this speaks
12+//! (ffmpeg's `silencedetect` noise floor, auto-editor's threshold) -- and RMS
13+//! rather than the peak [`crate::waveform::peaks`] draws, because a single
14+//! sample spike in a breath is not speech and a peak meter cannot tell them
15+//! apart.
16+
17+use std::path::Path;
18+
19+use crate::AudioSession;
20+use crate::project::{Clip, Speed};
21+
22+/// Loudness windows per second: 50, i.e. 20 ms each -- short enough to place a
23+/// cut inside one frame at any sane rate, long enough that one glottal pulse is
24+/// not a silence of its own.
25+pub const WINDOWS_PER_SEC: u32 = 50;
26+
27+/// What a window with no samples in it, or with digital nothing in it, reads
28+/// as: a floor rather than `-inf`, so a level is always a number a comparison
29+/// and a `Display` can take.
30+pub const SILENT_DB: f32 = -120.;
31+
32+/// What counts as a silence worth cutting. Seconds, not frames: detection runs
33+/// on the *source*, whose sample rate is its own business, and the frame grid
34+/// is applied once at the end ([`timeline_regions`]).
35+#[derive(Clone, Copy, PartialEq, Debug)]
36+pub struct Settings {
37+ /// At or below this level a window is quiet.
38+ pub threshold_db: f32,
39+ /// Quiet shorter than this is forgiven -- the pause between two words is
40+ /// not a cut.
41+ pub min_silence: f64,
42+ /// Kept at both ends of every region, so a cut never lands on the consonant
43+ /// that starts the next word.
44+ pub padding: f64,
45+ /// A kept sliver shorter than this joins the silences either side of it:
46+ /// breaths and mouth clicks between two long silences would otherwise
47+ /// survive as one-frame confetti nobody can watch.
48+ pub min_keep: f64,
49+}
50+
51+impl Default for Settings {
52+ /// The conservative end of what shipped tools default to (auto-editor
53+ /// ~-28 dBFS / 0.2 s margin, `silencedetect` -60 dB / 2 s): a first run
54+ /// that leaves a little too much is a run nobody has to undo.
55+ fn default() -> Self {
56+ Self {
57+ threshold_db: -40.,
58+ min_silence: 0.5,
59+ padding: 0.15,
60+ min_keep: 0.15,
61+ }
62+ }
63+}
64+
65+/// One RMS level in dBFS per [`WINDOWS_PER_SEC`]th of a second of `stream` of
66+/// `path`, from media time 0 -- the same decode [`crate::waveform::peaks`] runs
67+/// and with the same contract: channels folded together, `Ok(None)` for a file
68+/// with **no audio track at all**, which is a source to refuse by name rather
69+/// than one long silence to cut.
70+///
71+/// Linear in source length at ~1700x realtime, so a ten-minute take scans in
72+/// well under a second; a caller caches it per source and stream, because the
73+/// settings above are all applied to the result and none of them needs a second
74+/// decode.
75+pub fn levels(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<Vec<f32>>> {
76+ let sources = [(path.as_ref().to_path_buf(), stream)];
77+ let Some((meta, rx)) =
78+ AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?
79+ else {
80+ return Ok(None);
81+ };
82+ // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,
83+ // and a rounded window drifts a bucket every few seconds over a long take.
84+ let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);
85+ let channels = (meta.channels as usize).max(1);
86+ // Sum of squares and how many samples went into it -- the two halves of a
87+ // mean square, kept in f64 because a loud minute is millions of terms.
88+ let mut sums: Vec<(f64, u64)> = Vec::new();
89+ for chunk in rx {
90+ for (frame, values) in chunk.samples.chunks(channels).enumerate() {
91+ let window = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize;
92+ if window >= sums.len() {
93+ sums.resize(window + 1, (0., 0));
94+ }
95+ let slot = &mut sums[window];
96+ for &v in values {
97+ slot.0 += f64::from(v) * f64::from(v);
98+ slot.1 += 1;
99+ }
100+ }
101+ }
102+ Ok(Some(sums.iter().map(|&(sq, n)| dbfs(sq, n)).collect()))
103+}
104+
105+/// Mean square -> dBFS, floored at [`SILENT_DB`]: full scale is 1.0, so a
106+/// window of digital zero is `-inf` and is reported as the floor instead.
107+fn dbfs(square_sum: f64, samples: u64) -> f32 {
108+ if samples == 0 {
109+ return SILENT_DB;
110+ }
111+ let rms = (square_sum / samples as f64).sqrt();
112+ if rms <= 0. {
113+ return SILENT_DB;
114+ }
115+ (20. * rms.log10()).max(f64::from(SILENT_DB)) as f32
116+}
117+
118+/// The silent stretches of a `levels` track, as half-open `(from, to)` *source*
119+/// seconds, in order and never overlapping.
120+///
121+/// Pure arithmetic: this is what a card re-runs on every keystroke. The three
122+/// settings are applied in the order a person means them -- quiet runs first,
123+/// then the short ones forgiven ([`Settings::min_silence`]), then a
124+/// [`Settings::padding`] left at both ends so the cut never touches speech, and
125+/// last the slivers too short to keep ([`Settings::min_keep`]) swallowed by the
126+/// silences around them. Padding before the merge on purpose: what the merge
127+/// measures is what would actually survive the cut.
128+pub fn regions(levels: &[f32], cfg: Settings) -> Vec<(f64, f64)> {
129+ let window = 1. / f64::from(WINDOWS_PER_SEC);
130+ let mut quiet: Vec<(f64, f64)> = Vec::new();
131+ let mut run: Option<usize> = None;
132+ for (i, &db) in levels.iter().enumerate() {
133+ match (db <= cfg.threshold_db, run) {
134+ (true, None) => run = Some(i),
135+ (false, Some(from)) => {
136+ quiet.push((from as f64 * window, i as f64 * window));
137+ run = None;
138+ }
139+ _ => {}
140+ }
141+ }
142+ if let Some(from) = run {
143+ quiet.push((from as f64 * window, levels.len() as f64 * window));
144+ }
145+ let padded = quiet
146+ .into_iter()
147+ .filter(|&(from, to)| to - from >= cfg.min_silence)
148+ .map(|(from, to)| (from + cfg.padding, to - cfg.padding))
149+ .filter(|&(from, to)| to > from);
150+ let mut out: Vec<(f64, f64)> = Vec::new();
151+ for (from, to) in padded {
152+ match out.last_mut() {
153+ Some(last) if from - last.1 < cfg.min_keep => last.1 = to,
154+ _ => out.push((from, to)),
155+ }
156+ }
157+ out
158+}
159+
160+/// Where those source stretches sit on the timeline, as `(start, len)` frame
161+/// pairs of the lane `clip` is on -- what a preview marks and what
162+/// [`crate::Project::cut_regions`] cuts.
163+///
164+/// Only the part of each region the clip actually plays: the scan reads the
165+/// whole file and the clip is a range of it, so a silence outside `[in, out)`
166+/// is not on the timeline at all. Positions go through the clip's **own rate**
167+/// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is
168+/// really on.
169+///
170+/// Both edges are rounded **inward** -- start up, end down -- so a frame that
171+/// is partly speech stays outside the region at every rate. An empty remainder
172+/// is dropped rather than returned as a zero-length cut.
173+pub fn timeline_regions(clip: &Clip, fps: f64, regions: &[(f64, f64)]) -> Vec<(u32, u32)> {
174+ if !(fps.is_finite() && fps > 0.) {
175+ return Vec::new();
176+ }
177+ let frame = |secs: f64, round: fn(f64) -> f64| {
178+ let n = round(secs * fps);
179+ n.clamp(0., f64::from(u32::MAX)) as u32
180+ };
181+ regions
182+ .iter()
183+ .filter_map(|&(from, to)| {
184+ let first = frame(from, f64::ceil).max(clip.in_frame);
185+ let last = frame(to, f64::floor).min(clip.out_frame);
186+ if last <= first {
187+ return None;
188+ }
189+ let start = clip.start + clip.speed.timeline_at(first - clip.in_frame);
190+ let end = clip.start + floor_timeline(clip.speed, last - clip.in_frame);
191+ (end > start).then_some((start, end - start))
192+ })
193+ .collect()
194+}
195+
196+/// [`Speed::timeline_at`] floored instead of ceiled: which timeline frame of a
197+/// clip a source frame lands on, rounded the way an *end* has to be so a
198+/// region never eats the frame speech starts on. The ceil is the right rounding
199+/// for a start and for playback's stamps, and this is its partner.
200+fn floor_timeline(speed: Speed, offset: u32) -> u32 {
201+ (u64::from(offset) * 1000 / u64::from(speed.permille())).min(u64::from(u32::MAX)) as u32
202+}
203+
204+#[cfg(test)]
205+mod tests {
206+ use std::path::PathBuf;
207+
208+ use super::{Settings, levels, regions, timeline_regions};
209+ use crate::project::{Clip, Speed};
210+ use crate::scale::FitPolicy;
211+
212+ fn asset(name: &str) -> PathBuf {
213+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
214+ .join("../../assets")
215+ .join(name)
216+ }
217+
218+ fn clip(start: u32, in_frame: u32, out_frame: u32, speed: Speed) -> Clip {
219+ Clip {
220+ start,
221+ in_frame,
222+ out_frame,
223+ source: 0,
224+ link: None,
225+ eq: None,
226+ color: None,
227+ fit: FitPolicy::default(),
228+ speed,
229+ }
230+ }
231+
232+ /// A level track: `db` for every window, with the named half-open window
233+ /// ranges dropped to digital silence.
234+ fn track(windows: usize, db: f32, quiet: &[(usize, usize)]) -> Vec<f32> {
235+ let mut out = vec![db; windows];
236+ for &(from, to) in quiet {
237+ out[from..to].fill(super::SILENT_DB);
238+ }
239+ out
240+ }
241+
242+ /// Seconds compared as seconds: a window edge is a multiple of 0.02 and a
243+ /// padding is added to it, neither of which is exact in binary.
244+ fn near(got: &[(f64, f64)], want: &[(f64, f64)]) {
245+ assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
246+ for (&(a, b), &(c, d)) in got.iter().zip(want) {
247+ assert!(
248+ (a - c).abs() < 1e-9 && (b - d).abs() < 1e-9,
249+ "{got:?} against {want:?}"
250+ );
251+ }
252+ }
253+
254+ /// The fixture's envelope is `0.5 + 0.5*sin(2*PI*t)`: full silence every
255+ /// second at t = 0.75. Detection has to land on those five dips and on
256+ /// nothing else -- a scan that lost the chunk positions, or that measured
257+ /// peaks instead of RMS, would not line up second after second.
258+ #[test]
259+ fn the_dips_of_the_1hz_pulse_are_where_the_silences_are() {
260+ let levels = levels(asset("test_av.mp4"), 0)
261+ .expect("open")
262+ .expect("test_av.mp4 has an audio track");
263+ // A short forgiveness, because each dip of a sine is brief.
264+ let cfg = Settings {
265+ threshold_db: -40.,
266+ min_silence: 0.08,
267+ padding: 0.,
268+ min_keep: 0.,
269+ };
270+ let found = regions(&levels, cfg);
271+ assert_eq!(found.len(), 5, "{found:?}");
272+ for (second, &(from, to)) in found.iter().enumerate() {
273+ let dip = second as f64 + 0.75;
274+ assert!(
275+ (from..to).contains(&dip),
276+ "second {second}: {from}..{to} does not cover the dip at {dip}"
277+ );
278+ }
279+ // Nothing survives a forgiveness longer than any dip is.
280+ assert!(
281+ regions(
282+ &levels,
283+ Settings {
284+ min_silence: 1.5,
285+ ..cfg
286+ }
287+ )
288+ .is_empty()
289+ );
290+ }
291+
292+ /// The three settings, each one visible on its own: a quiet run shorter
293+ /// than `min_silence` is forgiven, `padding` shrinks what is left at both
294+ /// ends, and a kept sliver shorter than `min_keep` joins the silences
295+ /// around it rather than surviving as one-frame confetti.
296+ #[test]
297+ fn forgiveness_padding_and_min_keep_each_show_up() {
298+ // 10 s of speech with a 0.2 s dip, a 1 s silence and a 2 s silence.
299+ let levels = track(500, -12., &[(50, 60), (100, 150), (300, 400)]);
300+ let bare = Settings {
301+ threshold_db: -40.,
302+ min_silence: 0.5,
303+ padding: 0.,
304+ min_keep: 0.,
305+ };
306+ near(&regions(&levels, bare), &[(2., 3.), (6., 8.)]);
307+ // Padding takes 0.15 s off each end of each region, and off nothing
308+ // else: a region is 0.3 s shorter and starts 0.15 s later.
309+ let padded = regions(
310+ &levels,
311+ Settings {
312+ padding: 0.15,
313+ ..bare
314+ },
315+ );
316+ near(&padded, &[(2.15, 2.85), (6.15, 7.85)]);
317+ // Two silences with a two-window sliver of speech between them: with
318+ // nothing to keep it, the sliver joins them into one region.
319+ let sliver = track(500, -12., &[(100, 150), (152, 250)]);
320+ assert_eq!(
321+ regions(&sliver, bare).len(),
322+ 2,
323+ "the sliver is kept while min_keep is zero"
324+ );
325+ let merged = regions(
326+ &sliver,
327+ Settings {
328+ min_keep: 0.15,
329+ ..bare
330+ },
331+ );
332+ near(&merged, &[(2., 5.)]);
333+ }
334+
335+ /// Where a region lands on the timeline is the clip's business: its range
336+ /// clips what was scanned, its placement offsets it, and its rate divides
337+ /// it. A 2x clip's silences mark half as many frames, at the right place.
338+ #[test]
339+ fn regions_map_through_the_clips_range_and_rate() {
340+ let secs = [(1., 2.), (3., 3.5)];
341+ // Whole file, real time, placed at the start: source seconds are
342+ // timeline frames at 30 fps.
343+ let whole = clip(0, 0, 300, Speed::NORMAL);
344+ assert_eq!(
345+ timeline_regions(&whole, 30., &secs),
346+ vec![(30, 30), (90, 15)]
347+ );
348+ // The same clip placed at frame 100 and reading from source frame 45:
349+ // the first region is only the half of it the clip still plays, and it
350+ // lands at the clip's own start.
351+ let placed = clip(100, 45, 300, Speed::NORMAL);
352+ assert_eq!(
353+ timeline_regions(&placed, 30., &secs),
354+ vec![(100, 15), (145, 15)]
355+ );
356+ // At 2x every timeline frame is two source frames, so both regions are
357+ // half as wide and sit half as far along.
358+ let fast = clip(0, 0, 300, Speed::from_permille(2000));
359+ assert_eq!(timeline_regions(&fast, 30., &secs), vec![(15, 15), (45, 7)]);
360+ // A region entirely outside what the clip plays is not on the timeline.
361+ assert!(timeline_regions(&clip(0, 200, 300, Speed::NORMAL), 30., &[(1., 2.)]).is_empty());
362+ }
363+
364+ /// Rounded inward at both ends: a region whose seconds fall between frames
365+ /// gives back the frames it *fully* covers, so no frame of speech is ever
366+ /// inside a cut. Half a frame of silence is dropped, never claimed.
367+ #[test]
368+ fn edges_round_inward_so_speech_keeps_its_frames() {
369+ let whole = clip(0, 0, 300, Speed::NORMAL);
370+ // [1.01, 1.99) s at 30 fps is source frames 30.3 .. 59.7: the region
371+ // may only claim 31..59.
372+ assert_eq!(
373+ timeline_regions(&whole, 30., &[(1.01, 1.99)]),
374+ vec![(31, 28)]
375+ );
376+ // Under a frame wide: nothing survives the rounding, and a zero-length
377+ // cut is never handed back.
378+ assert!(timeline_regions(&whole, 30., &[(1.01, 1.02)]).is_empty());
379+ }
380+}
crates/engine/tests/silence.rsadded+233 -0
@@ -0,0 +1,233 @@
1+//! The jumpcut, end to end through the front door: a real file scanned for its
2+//! silences, the regions that come back cut (or sped up) as **one** edit, and
3+//! the timeline that leaves.
4+//!
5+//! `silence.rs`'s own unit tests own the detection arithmetic. What is measured
6+//! here is what an editor would see: how long the timeline is afterwards, that
7+//! every lane moved together, that one undo press takes the whole batch back,
8+//! and that the refusals name what is in the way. Group consistency is checked
9+//! the way a save checks it -- the parts are handed back to
10+//! `Project::from_parts`, which is the door a `.edith` comes in through.
11+
12+use std::path::PathBuf;
13+
14+use engine::project::{Lane, LaneKind, Speed};
15+use engine::silence::{self, Settings};
16+use engine::{Clip, Project};
17+
18+const FPS: f64 = 30.0;
19+
20+fn asset(name: &str) -> PathBuf {
21+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
22+ .join("../../assets")
23+ .join(name)
24+}
25+
26+/// The A/V fixture as a fresh project: `V1` and `A1`, one grouped clip each
27+/// covering the whole file -- what opening it in the editor gives.
28+fn fixture() -> Project {
29+ let path = asset("test_av.mp4");
30+ let (meta, _) = engine::demux::Demuxer::open(&path).expect("open the fixture");
31+ Project::single(&path, meta.frame_count)
32+}
33+
34+/// A link is one span on however many lanes, and a project whose links disagree
35+/// is one no save could load: this is that check, through the same door a load
36+/// takes.
37+fn loadable(project: &Project) {
38+ let (sources, lanes, eq, color) = project.without_orphan_sources();
39+ Project::from_parts(sources, lanes, eq, color).expect("the lanes still load");
40+}
41+
42+fn spans(project: &Project) -> (Vec<(u32, u32)>, Vec<(u32, u32)>) {
43+ (
44+ project.lane_spans(Lane::V1),
45+ project.lane_spans(Lane::new(LaneKind::Audio, 0)),
46+ )
47+}
48+
49+/// Five cuts, one undo press. The linked picture slides exactly as its sound
50+/// does, the timeline is shorter by exactly what was cut, and the press after
51+/// the undo reaches the edit that came *before* the jumpcut -- which is what a
52+/// loop over `ripple_delete` would have buried under five steps.
53+#[test]
54+fn a_batch_of_cuts_is_one_edit_and_moves_every_lane_alike() {
55+ let mut p = fixture();
56+ let was = p.timeline_frames();
57+ // An edit first, so the undo stack has something under the batch.
58+ assert!(p.split(60));
59+ let before = p.lane(Lane::V1).to_vec();
60+ let regions = [(10, 5), (30, 5), (50, 5), (70, 5), (90, 5)];
61+ assert!(p.cut_regions(&regions));
62+
63+ let cut: u32 = regions.iter().map(|&(_, len)| len).sum();
64+ assert_eq!(p.timeline_frames(), was - cut);
65+ let (video, audio) = spans(&p);
66+ assert_eq!(video, audio, "the picture and its sound moved apart");
67+ loadable(&p);
68+
69+ // One press takes the whole batch back...
70+ assert!(p.undo());
71+ assert_eq!(p.lane(Lane::V1), before, "one undo did not restore the lot");
72+ assert_eq!(p.timeline_frames(), was);
73+ // ...and the next one is the split, not another fifth of the jumpcut.
74+ assert!(p.undo());
75+ assert_eq!(p.lane(Lane::V1).len(), 1);
76+ assert!(!p.undo(), "the batch left extra history behind");
77+}
78+
79+/// Speeding the silences up leaves **no holes**: `set_speed` on its own does
80+/// not ripple, and a gap where a silence shrank is the whole failure this
81+/// guards. Everything that was contiguous stays contiguous, both lanes shrink
82+/// alike, and it is one undo press.
83+#[test]
84+fn speeding_silences_up_closes_the_room_they_no_longer_need() {
85+ let mut p = fixture();
86+ let was = p.timeline_frames();
87+ let regions = [(30, 20), (80, 20)];
88+ p.speed_regions(&regions, Speed::MAX).expect("no lane laps");
89+
90+ // 20 source frames at 4x occupy 5, so each region gives back 15.
91+ let shrunk = Speed::MAX.frames(20);
92+ let (video, audio) = spans(&p);
93+ assert_eq!(video, audio);
94+ assert_eq!(p.timeline_frames(), was - 2 * (20 - shrunk));
95+ for pair in video.windows(2) {
96+ assert_eq!(
97+ pair[0].0 + pair[0].1,
98+ pair[1].0,
99+ "a hole was left where a silence shrank: {video:?}"
100+ );
101+ }
102+ // The pieces that were the silences are the ones running fast, and only
103+ // those.
104+ let fast: Vec<u32> = p
105+ .lane(Lane::V1)
106+ .iter()
107+ .filter(|c| c.speed == Speed::MAX)
108+ .map(|c| c.start)
109+ .collect();
110+ assert_eq!(fast, vec![30, 30 + shrunk + (80 - 50)]);
111+ loadable(&p);
112+
113+ // Absolute, not compounding: running it again over where those pieces sit
114+ // now leaves the timeline byte for byte as it was -- 4x set twice is 4x.
115+ let settled = p.lane(Lane::V1).to_vec();
116+ let again: Vec<(u32, u32)> = fast.iter().map(|&at| (at, shrunk)).collect();
117+ p.speed_regions(&again, Speed::MAX).expect("still no lap");
118+ assert_eq!(p.lane(Lane::V1), settled, "a second pass compounded");
119+
120+ assert!(p.undo());
121+ assert!(p.undo());
122+ assert_eq!(p.lane(Lane::V1).len(), 1, "one press per apply, no more");
123+ assert!(!p.undo());
124+}
125+
126+/// A clip on another lane that laps over the edge of a silence makes speed mode
127+/// refuse **by name**: the lanes would shrink by different amounts and the
128+/// ripple would pull them apart. The refusal costs no undo step and changes
129+/// nothing -- and cutting the same regions is still fine, which is why delete
130+/// mode needs no such rule.
131+#[test]
132+fn speed_mode_refuses_a_clip_that_laps_over_a_silence() {
133+ let mut p = fixture();
134+ let lane = p.add_lane(LaneKind::Video);
135+ assert_eq!(lane.label(), "V2");
136+ let broll = Clip {
137+ start: 0,
138+ in_frame: 0,
139+ out_frame: 20,
140+ source: 0,
141+ link: None,
142+ eq: None,
143+ color: None,
144+ fit: Default::default(),
145+ speed: Speed::NORMAL,
146+ };
147+ assert!(p.place(lane, 40, broll));
148+ let before = spans(&p);
149+
150+ let err = p
151+ .speed_regions(&[(30, 20)], Speed::MAX)
152+ .expect_err("a half-covered region must not be sped up")
153+ .to_string();
154+ assert!(err.contains("V2"), "{err}");
155+ assert!(err.contains("40"), "{err}");
156+ assert_eq!(spans(&p), before, "a refusal changed the timeline");
157+
158+ // No undo step was spent on it: the press below is the `place` above.
159+ assert!(p.undo());
160+ assert!(p.lane(lane).is_empty());
161+
162+ // The same regions cut instead: a ripple is uniform, so nothing laps.
163+ assert!(p.place(lane, 40, broll));
164+ assert!(p.cut_regions(&[(30, 20)]));
165+ loadable(&p);
166+}
167+
168+/// The whole chain a person presses one key for: the fixture is scanned, its
169+/// silences come back as timeline frames, and cutting them shortens the
170+/// timeline by exactly what was found -- with the scan itself having changed
171+/// nothing at all.
172+///
173+/// `test_av.mp4`'s envelope is silent every second at t≈0.75, so the regions
174+/// land there ±1 frame.
175+#[test]
176+fn scanning_a_clip_and_cutting_what_it_finds() {
177+ let mut p = fixture();
178+ let was = p.timeline_frames();
179+ // Nothing to undo yet, and the scan below must not change that: a preview
180+ // is not an edit.
181+ assert!(!p.undo());
182+
183+ let levels = silence::levels(asset("test_av.mp4"), 0)
184+ .expect("scan")
185+ .expect("the fixture has audio");
186+ let cfg = Settings {
187+ threshold_db: -40.,
188+ min_silence: 0.08,
189+ padding: 0.02,
190+ min_keep: 0.,
191+ };
192+ let audio = Lane::new(LaneKind::Audio, 0);
193+ let clip = p.lane(audio)[0];
194+ let regions = silence::timeline_regions(&clip, FPS, &silence::regions(&levels, cfg));
195+ assert_eq!(regions.len(), 5, "{regions:?}");
196+ for (second, &(start, len)) in regions.iter().enumerate() {
197+ // The dip of that second, in frames, sits inside the marked region.
198+ let dip = (second as f64 + 0.75) * FPS;
199+ assert!(
200+ (f64::from(start) - 1.0..f64::from(start + len) + 1.0).contains(&dip),
201+ "second {second}: [{start}, {}) is not the dip at {dip}",
202+ start + len
203+ );
204+ }
205+ assert!(!p.undo(), "the scan took an undo step");
206+
207+ let cut: u32 = regions.iter().map(|&(_, len)| len).sum();
208+ assert!(p.cut_regions(&regions));
209+ assert_eq!(p.timeline_frames(), was - cut);
210+ let (video, audio_spans) = spans(&p);
211+ assert_eq!(video, audio_spans);
212+ loadable(&p);
213+
214+ // What a jumpcut leaves is ordinary clips, so the file it saves to is the
215+ // same dialect it always was -- no wire change went with this feature.
216+ let dir = std::env::temp_dir().join(format!("edith-silence-{}", std::process::id()));
217+ std::fs::create_dir_all(&dir).expect("a place to save");
218+ let file = dir.join("cut.edith");
219+ let (sources, lanes, eq, color) = p.without_orphan_sources();
220+ engine::edith::save(&file, &sources, &lanes, &eq, &color, (1920, 1080), 0).expect("save");
221+ let text = std::fs::read_to_string(&file).expect("read it back");
222+ assert!(
223+ text.starts_with("edith 8"),
224+ "{:?}",
225+ &text[..16.min(text.len())]
226+ );
227+ let back = engine::edith::load(&file).expect("load");
228+ assert_eq!(back.lanes, lanes, "the cut timeline did not round-trip");
229+ std::fs::remove_dir_all(&dir).ok();
230+
231+ assert!(p.undo());
232+ assert_eq!(p.timeline_frames(), was);
233+}