diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 672359a..a617a54 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -71,13 +71,14 @@ pub enum ActionId { VolumeDown, Equalizer, Speed, + Silence, CancelExport, } impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 32] = [ + pub const ALL: [ActionId; 33] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -109,6 +110,7 @@ impl ActionId { ActionId::VolumeDown, ActionId::Equalizer, ActionId::Speed, + ActionId::Silence, ActionId::CancelExport, ]; @@ -146,6 +148,7 @@ impl ActionId { ActionId::VolumeDown => "Volume down", ActionId::Equalizer => "Equalizer", ActionId::Speed => "Speed (tape)…", + ActionId::Silence => "Silences: cut or speed up…", ActionId::CancelExport => "Cancel export", } } @@ -185,6 +188,7 @@ impl ActionId { ActionId::VolumeDown => "volume-down", ActionId::Equalizer => "equalizer", ActionId::Speed => "speed", + ActionId::Silence => "silence", ActionId::CancelExport => "cancel-export", } } @@ -217,7 +221,11 @@ impl ActionId { // A rate is the clip's, not the sound's: it re-times the picture // and the sound together, and the card opens on whichever half was // clicked. - | ActionId::Speed => Category::Clips, + | ActionId::Speed + // The scan reads a clip's sound, but what it does is edit the + // timeline the clip is on -- it is a clip card like the three + // above it, opened on whichever half was picked. + | ActionId::Silence => Category::Clips, // The project's own picture size is not a clip's business, and not // a file operation either: it is what the viewer is looking at. ActionId::Resolution => Category::View, @@ -283,7 +291,7 @@ pub struct Fixed { pub category: Category, } -pub const FIXED: [Fixed; 12] = [ +pub const FIXED: [Fixed; 14] = [ Fixed { chord: "esc", label: "Close this card or menu, or cancel a capture", @@ -349,6 +357,20 @@ pub const FIXED: [Fixed; 12] = [ label: "Take the colour grade off the clip", category: Category::Clips, }, + // The silence card's two apply keys. Card-local like every stroke above -- + // they mean nothing while it is closed -- but the card is the one place in + // this editor where a key rewrites forty places at once, so both of them + // are listed rather than hidden in the card's own hint line. + Fixed { + chord: "enter", + label: "Cut every silence the card found", + category: Category::Clips, + }, + Fixed { + chord: "f", + label: "Speed the silences up instead of cutting them", + category: Category::Clips, + }, ]; /// A stroke as the key handler sees it: gpui's key name plus the one modifier @@ -520,6 +542,11 @@ impl Keymap { // right hand with the other clip keys (k grades, l lifts), and // is not next to anything that deletes. b(ActionId::Speed, "j", false), + // The silence card takes "u": free, sits with the other clip-card + // keys under the right hand, and is nowhere near the two that + // delete (x and delete) -- what it opens is a card that can cut + // forty places at once. + b(ActionId::Silence, "u", false), b(ActionId::CancelExport, "escape", false), ], } @@ -782,7 +809,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 34); + assert_eq!(k.entries().len(), 35); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -828,6 +855,7 @@ mod tests { assert_eq!(k.lookup("e", true), None); assert_eq!(k.lookup("space", true), None); assert_eq!(k.lookup("j", false), Some(ActionId::Speed)); + assert_eq!(k.lookup("u", false), Some(ActionId::Silence)); assert_eq!(k.lookup("j", true), None); // Nothing is bound twice, or lookup's first match would be a coin toss. for (i, a) in k.entries().iter().enumerate() { @@ -1010,7 +1038,7 @@ mod tests { assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 32); + assert_eq!(ActionId::ALL.len(), 33); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 27a6d97..7514dc0 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -357,6 +357,33 @@ fn speed_at(permille: i32) -> Speed { Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16) } +/// The silence card's rows, in the order it lists them: the four settings a +/// scan is told and the rate the speed-up plays at. What `silence_field` +/// indexes and what [`Player::nudge_silence`] moves. +const SILENCE_ROWS: usize = 5; + +/// One press of a nudge key on each kind of row: a dB on the threshold, a +/// twentieth of a second on the three durations, and the speed card's own step +/// on the rate. +const SILENCE_DB_STEP: f32 = 1.; +const SILENCE_SECS_STEP: f64 = 0.05; + +/// How far each of them may be pushed. UI decisions, all of them: the engine +/// takes any finite number, but a threshold at 0 dBFS calls a whole take silent +/// and a forgiveness of ten seconds finds nothing in a talking head. +const SILENCE_DB_RANGE: (f32, f32) = (-80., -10.); +const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.); + +/// The speed-up rate is bounded *below* by real time: a "speed-up" that slows +/// the silence down would make the timeline longer, which is the one thing +/// neither button may do. The top is [`Speed::MAX`]. +fn silence_rate(permille: i32) -> Speed { + speed_at(permille.clamp( + i32::from(Speed::NORMAL.permille()) + SPEED_STEP, + i32::from(Speed::MAX.permille()), + )) +} + /// The graph's frequency axis: the range an ear works in, and the range every /// band a file can carry sits inside. Log-spaced, so an octave is an octave /// wherever it falls. @@ -571,6 +598,25 @@ struct Player { /// The bar is being dragged. On the root like the colour card's, for the /// same reason: the pointer leaves a 4 px bar on the first move. speed_dragging: bool, + /// The silence card is up on this clip -- the lane it is on and its index + /// there, exactly as the speed card's handle is. + silence_open: Option<(Lane, usize)>, + /// What a scan is told to look for, and how fast the speed-up button plays + /// what it found. Kept across closes like the export card's quality: a + /// second run offers what the first one settled on. + silence: engine::silence::Settings, + silence_factor: Speed, + /// Which of the card's [`SILENCE_ROWS`] the arrow keys move. The card's own + /// focus, since nothing in it takes gpui's (ledger:182). + silence_field: usize, + /// What the last scan found, in timeline frames: what the lane draws marks + /// over and what an apply acts on -- *exactly* the previewed set, never a + /// second scan at the moment of the press. + silence_marks: Vec<(u32, u32)>, + /// The levels of the last source scanned, kept so moving a threshold is + /// arithmetic rather than another decode. One entry: a card is open on one + /// clip, and the next one it opens on is the next thing worth holding. + silence_levels: Option<(PathBuf, usize, Arc>)>, /// Which of the card's four sliders the arrow keys and a drag move. The /// card's own focus, since nothing in it takes gpui's (ledger:182). color_band: usize, @@ -738,6 +784,7 @@ impl Player { ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx), ActionId::Equalizer => self.open_eq(cx), ActionId::Speed => self.open_speed(cx), + ActionId::Silence => self.open_silence(cx), // Nothing to cancel while nothing is exporting; the export guard in // the key handler is what answers this one while there is. ActionId::CancelExport => {} @@ -1004,11 +1051,12 @@ impl Player { Some(clip) => { self.speed_open = Some(clip); self.speed_dragging = false; - // One card at a time, the rule the other three follow. + // One card at a time, the rule the other four follow. self.keys_open = false; self.export_open = false; self.eq_open = None; self.color_open = None; + self.close_silence(); self.context_menu = None; } None => self.notice = Some("no clip under the playhead to re-time".into()), @@ -1085,6 +1133,225 @@ impl Player { self.write_speed(speed_at(stepped), !first, cx); } + /// Opens the silence card on the clip to be scanned: the selected one, or + /// -- with nothing selected -- the clip the picture is coming from, which is + /// the rule the speed card follows and what a person means by "this shot". + /// Either half of a take will do: the scan reads the *source*, and both + /// halves of an A/V take name the same file. + /// + /// The scan runs at once, so the card is never up saying nothing: a clip + /// whose source has no audio track at all is refused by name instead, and + /// the card does not open on it. + fn open_silence(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some(session) = &self.session else { + self.notice = Some("no timeline to scan — open a file first".into()); + cx.notify(); + return; + }; + match self + .selected + .or_else(|| session.video_clip_at(session.now())) + .map(|clip| audio_half(session, clip)) + { + Some(clip) => { + self.silence_open = Some(clip); + self.silence_field = 0; + // One card at a time, the rule the other four follow. + self.keys_open = false; + self.export_open = false; + self.eq_open = None; + self.color_open = None; + self.speed_open = None; + self.context_menu = None; + self.scan_silences(); + } + None => self.notice = Some("no clip under the playhead to scan".into()), + } + cx.notify(); + } + + /// Closes it and drops the preview with it: marks left on the lane after + /// the card is gone would name frames the next edit has already moved. + fn close_silence(&mut self) { + self.silence_open = None; + self.silence_marks.clear(); + } + + /// Runs the scan and replaces the preview -- never stacks on it. The decode + /// happens once per source ([`engine::silence::levels`] is cached here), so + /// every later run is the settings applied to numbers already in hand, + /// which is what makes moving a threshold feel like moving a slider. + /// + /// Changes nothing about the project: a preview is not an edit, and no undo + /// step is spent until a button is pressed. + /// + /// ponytail: the first scan for a source runs on the render thread -- ~1700x + /// realtime, so a ten-minute take is well under a second and an hour-long + /// one would be felt. Upgrade path is the waveform's: hand it to + /// `cx.background_spawn` and repaint when it lands. + fn scan_silences(&mut self) { + let Some((lane, idx)) = self.silence_open else { + return; + }; + self.silence_marks.clear(); + // Copied out before anything is written back: the cache below lives on + // the same struct the session does. + let Some((clip, source)) = self.session.as_ref().and_then(|session| { + let clip = *session.lane_clips(lane).get(idx)?; + Some((clip, session.sources().get(clip.source)?.clone())) + }) else { + return; + }; + let cached = self + .silence_levels + .as_ref() + .filter(|(path, stream, _)| *path == source.path && *stream == source.audio_stream) + .map(|(_, _, levels)| levels.clone()); + let levels = match cached { + Some(levels) => levels, + None => match engine::silence::levels(&source.path, source.audio_stream) { + Ok(Some(levels)) => { + let levels = Arc::new(levels); + self.silence_levels = + Some((source.path.clone(), source.audio_stream, levels.clone())); + levels + } + // A source with no audio track is not one long silence: it is a + // clip this card has nothing to say about, named so the user + // knows which one it meant. + Ok(None) => { + self.silence_open = None; + self.notice = Some( + format!( + "{} clip {} has no audio to scan — {} is silent", + lane.label(), + idx + 1, + file_name(&source.path) + ) + .into(), + ); + return; + } + Err(e) => { + self.silence_open = None; + self.notice = Some(format!("SCAN FAILED: {e}").into()); + return; + } + }, + }; + self.silence_marks = engine::silence::timeline_regions( + &clip, + self.fps, + &engine::silence::regions(&levels, self.silence), + ); + } + + /// Moves the picked row by `steps` and re-runs the scan against it, so the + /// marks on the lane are always what the numbers on the card say. + fn nudge_silence(&mut self, steps: i32) { + let secs = |at: f64| { + (at + f64::from(steps) * SILENCE_SECS_STEP) + .clamp(SILENCE_SECS_RANGE.0, SILENCE_SECS_RANGE.1) + }; + match self.silence_field { + 0 => { + self.silence.threshold_db = (self.silence.threshold_db + + steps as f32 * SILENCE_DB_STEP) + .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1) + } + 1 => self.silence.min_silence = secs(self.silence.min_silence), + 2 => self.silence.padding = secs(self.silence.padding), + 3 => self.silence.min_keep = secs(self.silence.min_keep), + _ => { + self.silence_factor = + silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP) + } + } + // The rate is not part of the scan, but re-running is cheap (the levels + // are cached) and one path is one place for the marks to come from. + self.scan_silences(); + } + + /// What an apply acts on: the previewed set, or nothing at all with a + /// notice saying so in the numbers that found nothing. + fn previewed(&mut self) -> Option> { + if self.silence_marks.is_empty() { + self.notice = Some( + format!( + "no silence under {:.0} dBFS lasting {:.2} s — raise the threshold or forgive less", + self.silence.threshold_db, self.silence.min_silence + ) + .into(), + ); + return None; + } + Some(self.silence_marks.clone()) + } + + /// Cuts every previewed silence out of every lane, rippling each hole + /// closed -- one edit and **one** undo press however many there were + /// ([`engine::PlaybackSession::cut_regions`]). The linked picture slides + /// with its sound, because a ripple is uniform across the lanes. + fn cut_silences(&mut self, cx: &mut Context) { + let Some(regions) = self.previewed() else { + cx.notify(); + return; + }; + let saved = f64::from(regions.iter().map(|&(_, len)| len).sum::()) / self.fps; + let count = regions.len(); + let cut = self + .session + .as_mut() + .is_some_and(|session| session.cut_regions(®ions)); + if cut { + self.close_silence(); + self.reset_after_reseek(); + self.notice = Some( + format!( + "{count} SILENCES CUT — {saved:.1}s shorter, {} takes it back", + self.keymap.display(ActionId::Undo) + ) + .into(), + ); + } + cx.notify(); + } + + /// Plays them fast instead of cutting them, closing the room each one no + /// longer needs. One undo press like the cut; the refusal (a clip on + /// another lane lapping over a silence) comes back in the engine's own + /// words and names the lane and frame, and the card stays up so the numbers + /// that produced it are still on screen. + fn speed_silences(&mut self, cx: &mut Context) { + let Some(regions) = self.previewed() else { + cx.notify(); + return; + }; + let (count, rate) = (regions.len(), self.silence_factor); + let Some(session) = self.session.as_mut() else { + cx.notify(); + return; + }; + match session.speed_regions(®ions, rate) { + Ok(()) => { + self.close_silence(); + self.reset_after_reseek(); + self.notice = Some( + format!( + "{count} SILENCES AT {rate} — {} takes it back", + self.keymap.display(ActionId::Undo) + ) + .into(), + ); + } + Err(e) => self.notice = Some(e.to_string().into()), + } + cx.notify(); + } + /// Whether a card owns the window. While one does the timeline under it is /// out of reach, so a right-click there opens no menu -- the same rule the /// key handler and the drop target already follow. @@ -1094,6 +1361,7 @@ impl Player { || self.eq_open.is_some() || self.color_open.is_some() || self.speed_open.is_some() + || self.silence_open.is_some() || self.exporting().is_some() } @@ -1960,6 +2228,8 @@ impl Player { self.context_menu = None; self.eq_open = None; self.color_open = None; + // Marks are timeline frames of the timeline that was. + self.close_silence(); // A different set of sources: the row that was picked is not // the file that index names any more. self.selected_asset = None; @@ -2500,6 +2770,31 @@ impl Render for Player { cx.notify(); return; } + // The silence card, the same way again: the arrows pick one of + // its rows and move it, and its two apply keys are the two + // things it can do to the timeline. Card-local, every one of + // them -- and listed in the keys menu (keymap.rs `FIXED`), + // because a key that cuts forty places at once is not a secret. + if this.silence_open.is_some() { + if key == ESCAPE { + // Nothing to undo: a preview is not an edit. + this.close_silence(); + } else if key == "down" { + this.silence_field = (this.silence_field + 1) % SILENCE_ROWS; + } else if key == "up" { + this.silence_field = (this.silence_field + SILENCE_ROWS - 1) % SILENCE_ROWS; + } else if key == "right" { + this.nudge_silence(1); + } else if key == "left" { + this.nudge_silence(-1); + } else if key == "enter" { + this.cut_silences(cx); + } else if key == "f" { + this.speed_silences(cx); + } + cx.notify(); + return; + } // A clip menu names an index, and every edit below moves // indices -- so a stroke closes it before it acts. Escape means // that and nothing else, which is the `esc` the keys menu @@ -2711,6 +3006,7 @@ impl Render for Player { .children(self.eq_card(cx)) .children(self.color_card(cx)) .children(self.speed_card(cx)) + .children(self.silence_card(cx)) } } @@ -4137,6 +4433,147 @@ impl Player { ) } + /// The silence card: what the scan is looking for, what it found, and the + /// two things that can be done about it. + /// + /// Its scrim is the lightest of the cards' on purpose. Every other card is + /// about the clip it names and can black the timeline out; this one is + /// *about* the timeline -- the marks under it are the whole preview -- so + /// the bed stays readable and the card sits up in the picture area rather + /// than over the lanes. + fn silence_card(&self, cx: &mut Context) -> Option { + let (lane, idx) = self.silence_open?; + let cfg = self.silence; + let rows = [ + ("Silence is under", format!("{:.0} dBFS", cfg.threshold_db)), + ( + "Forgive quiet shorter than", + format!("{:.2} s", cfg.min_silence), + ), + ( + "Keep either side of speech", + format!("{:.2} s", cfg.padding), + ), + ( + "Swallow kept slivers under", + format!("{:.2} s", cfg.min_keep), + ), + ("Speed-up plays at", format!("{}", self.silence_factor)), + ]; + let found = self.silence_marks.len(); + let secs = + f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::()) / self.fps; + let rows: Vec<_> = rows + .into_iter() + .enumerate() + .map(|(n, (label, value))| { + div() + .id(("silence-row", n)) + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .px(px(6.)) + .rounded(px(3.)) + .bg(rgb(match n == self.silence_field { + true => SELECTED, + false => CHROME, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.silence_field = n; + cx.notify(); + })) + .child(div().text_color(rgb(INK_DIM)).child(label)) + .child(value) + }) + .collect(); + // The two buttons the ask names, side by side: a mode toggle would hide + // one of them behind the other, and there are only two. + let button = |n: usize, text: String, act: fn(&mut Self, &mut Context)| { + div() + .id(("silence-apply", n)) + .flex_1() + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(match found { + 0 => CHROME, + _ => SELECTED, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| act(this, cx))) + .child(text) + }; + Some( + div() + .absolute() + .inset_0() + .flex() + .justify_center() + .items_start() + .pt(px(HEADER_H + 8.)) + // Light enough to read the lanes and the marks on them through: + // the preview is the point of this card. + .bg(rgba(0x10101055)) + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .child( + div() + .w(px(COLOR_W)) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + .child(div().flex_none().px(px(6.)).child(format!( + "Silences — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child( + "↑↓ picks a setting, ←→ moves it — the marks on the lane are what would go; esc closes", + ), + ) + .children(rows) + .child( + div() + .flex_none() + .px(px(6.)) + .text_color(rgb(match found { + 0 => INK_DIM, + _ => ACCENT, + })) + .child(match found { + 0 => "nothing quiet enough for long enough".to_string(), + 1 => format!("1 silence, {secs:.1}s"), + n => format!("{n} silences, {secs:.1}s"), + }), + ) + .child(div().flex().gap(px(4.)).children([ + button(0, "Cut them out (enter)".into(), Self::cut_silences), + button( + 1, + format!("Play them at {} (f)", self.silence_factor), + Self::speed_silences, + ), + ])), + ), + ) + } + /// The menu a right-click on a library row opens: what can be done with the /// *file* rather than with a clip of it, and a turn-over side saying what /// that file is. Built like [`Player::context_card`] down to the scrim, the @@ -4783,6 +5220,25 @@ impl Player { ) }) })) + // What the silence card found, over the clips it found them + // in and over the waveform band that shows why: on the lane + // the scan ran on and no other, because that is the only + // lane whose sound was read. Drawn before anything is cut, + // and replaced -- never stacked -- by every re-run. + .children( + self.silence_marks + .iter() + .filter(|_| self.silence_open.is_some_and(|(on, _)| on == lane)) + .map(|&(at, len)| { + div() + .absolute() + .top_0() + .h_full() + .left(relative(start_frac(f64::from(at) / self.fps, duration))) + .w(relative(width_frac(f64::from(len) / self.fps, duration))) + .bg(rgba(0x4a9effaa)) + }), + ) // Last, so it is over the clips: the same fraction in both // lanes, which is the playhead being one line. .child( @@ -5377,6 +5833,36 @@ enum ColorKey { Reset, } +/// The half of a take whose *sound* the silence card scans: a link is one span +/// on however many lanes, so a card opened on the picture opens on the sound it +/// is grouped with. That is the lane the waveform is drawn on, and so the lane +/// the marks have to land on to be read against it -- and the ranges agree, +/// because a group is one span. +/// +/// The clip itself for one already on an audio lane, for a detached picture, +/// and for a take whose sound is not on any lane: there is nothing better to +/// open on, and the refusal for a source with no audio at all is `scan`'s. +fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) { + if lane.kind == LaneKind::Audio { + return (lane, idx); + } + let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else { + return (lane, idx); + }; + session + .lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Audio) + .find_map(|l| { + session + .lane_clips(l) + .iter() + .position(|c| c.link == Some(link)) + .map(|i| (l, i)) + }) + .unwrap_or((lane, idx)) +} + fn color_key(key: &str) -> Option { Some(match key { ESCAPE => ColorKey::Close, @@ -6094,16 +6580,17 @@ mod tests { use super::{ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS, - Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, - KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, - LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, - RULER_HIT_H, SELECTED, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, - Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, - cancels_export, color_snap, envelope, eq_x, eq_y, export_path, export_settings, format_key, - format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, - is_project, keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, - retarget, scrub_due, show_label, source_tint, span_partner, speed_at, start_frac, timecode, - unseen_paths, unseen_sources, whole_take, width_frac, window_title, + Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, + INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, + LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, + Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, + SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, + applicable, band_label, can_add, cancels_export, color_snap, envelope, eq_x, eq_y, + export_path, export_settings, format_key, format_line, format_refusal, frac_along, + frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, + menu_at, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, + silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths, + unseen_sources, whole_take, width_frac, window_title, }; use super::{file_name, file_uri, library_rows}; @@ -7591,6 +8078,39 @@ mod tests { assert!(u64::from(push_digit(99, 9)) * 1_000_000 < u64::from(u32::MAX)); } + #[test] + fn the_silence_card_fits_the_smallest_window_and_never_slows_a_silence_down() { + // The same 640x360 floor, and this card starts below the header: a + // title and a hint over its five rows, the count line and the two + // buttons. + let (title, hint, count) = (17., 17., 17.); + let gaps = 6. * 5.; + let padding = 24.; + assert!( + HEADER_H + + 8. + + title + + hint + + SILENCE_ROWS as f32 * KEYS_ROW_H + + count + + KEYS_ROW_H + + gaps + + padding + <= 360., + "card too tall" + ); + // Its rows and buttons are clicked, so WCAG 2.5.8 binds them. + assert!(KEYS_ROW_H >= HIT_MIN); + // A "speed-up" is never a slow-down: the rate stops above real time at + // one end and at what a clip can hold at the other, whatever the keys + // ask for. A silence played *slower* would make the timeline longer, + // which is the one thing neither button may do. + assert!(silence_rate(0) > Speed::NORMAL); + assert!(silence_rate(1000) > Speed::NORMAL); + assert_eq!(silence_rate(i32::MAX), Speed::MAX); + assert_eq!(silence_rate(4000), Speed::MAX); + } + #[test] fn the_export_card_fits_the_smallest_window() { // Same 640x360 floor the keybindings card is measured against: the @@ -8051,6 +8571,14 @@ fn main() { speed_open: None, speed_bar: Rc::default(), speed_dragging: false, + silence_open: None, + // The conservative defaults the engine documents: a first + // scan that leaves a little too much is one nobody undoes. + silence: engine::silence::Settings::default(), + silence_factor: Speed::MAX, + silence_field: 0, + silence_marks: Vec::new(), + silence_levels: None, color_open: None, color_band: 0, color_dragging: false, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3077af3..246839b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod mux; pub mod playback; pub mod project; pub mod scale; +pub mod silence; pub mod waveform; pub use audio::{ diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 3e0c4cd..61eeea5 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -1003,6 +1003,29 @@ impl PlaybackSession { Ok(()) } + /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out + /// of every lane and closes each hole, as **one** edit + /// ([`Project::cut_regions`]): the jumpcut a silence scan + /// ([`crate::silence`]) asks for, one undo press however many silences it + /// found. Reseeks like every other edit, so what plays is the cut timeline + /// from the playhead on. `false`, and no undo step, for an empty list. + pub fn cut_regions(&mut self, regions: &[(u32, u32)]) -> bool { + self.edit(|p| p.cut_regions(regions)) + } + + /// Plays every one of those regions at `speed` instead of cutting them, + /// closing the room each one no longer needs ([`Project::speed_regions`]) -- + /// one edit, one undo press. The `Err` names the lane and frame in the way + /// and nothing changes. + pub fn speed_regions(&mut self, regions: &[(u32, u32)], speed: Speed) -> crate::Result<()> { + // Spelled out rather than through `edit`, whose closure hands back a + // bool and would drop the refusal's own words. + self.project.speed_regions(regions, speed)?; + let now = self.now(); + self.seek(now); + Ok(()) + } + /// Where that edge may land, `(first, last)` timeline frame inclusive: what /// a drag clamps the pointer to so the box it draws is the box /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 85017ec..90cadb7 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1306,6 +1306,13 @@ impl Project { /// /// Metadata only: no mapping changes, in any lane. pub fn split(&mut self, timeline_frame: u32) -> bool { + self.write_split(timeline_frame, true) + } + + /// [`split`](Project::split), with the snapshot optional: a batch that has + /// already taken one ([`speed_regions`](Project::speed_regions)) splits at + /// two frames per region and must still be one undo press. + fn write_split(&mut self, timeline_frame: u32, snapshot: bool) -> bool { let cut: Vec> = self .lanes .iter() @@ -1314,7 +1321,9 @@ impl Project { if cut.iter().all(Option::is_none) { return false; } - self.snapshot(); + if snapshot { + self.snapshot(); + } // Each side is its own question: two clips may start together and end // apart, and every lane whose halves do line up stays one take. let starts: Vec> = cut.iter().map(|c| c.map(|c| c.start)).collect(); @@ -1861,16 +1870,158 @@ impl Project { return false; } self.snapshot(); - for data in &mut self.lanes { - clear(&mut data.clips, at, at + len); - for c in data.clips.iter_mut().filter(|c| c.start >= at) { - c.start -= len; - } - debug_assert!(sorted_disjoint(&data.clips)); + ripple(&mut self.lanes, at, len); + true + } + + /// Cut **every** one of `regions` -- `(start, len)` in timeline frames -- + /// out of every lane and close each hole, as one edit: the jumpcut a + /// silence scan asks for ([`crate::silence`]). + /// + /// One [`snapshot`](Project::snapshot) for the lot, which is the whole + /// reason this exists rather than a caller's loop over + /// [`ripple_delete`](Project::ripple_delete): forty silences must be one + /// undo press, not forty. Cut back to front, so a region's frames still + /// mean what the caller measured while the ones before it are cut. + /// + /// The list is sorted and overlapping entries are merged before anything is + /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each + /// other's frames -- and `false`, with no undo step, for a list with + /// nothing in it. + pub fn cut_regions(&mut self, regions: &[(u32, u32)]) -> bool { + let regions = tidy(regions); + if regions.is_empty() { + return false; } + self.snapshot(); + for &(at, len) in regions.iter().rev() { + ripple(&mut self.lanes, at, len); + } + debug_assert!(links_are_consistent(&self.lanes).is_ok()); true } + /// Play every one of `regions` at `speed` instead of cutting it: each is + /// split out of whatever covers it, re-rated, and the room it no longer + /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone + /// does not ripple, and a hole where a silence shrank is the one thing this + /// must not leave. One snapshot for the lot, like + /// [`cut_regions`](Project::cut_regions). + /// + /// The rate is **absolute**, not a multiplier on what is there: running it + /// twice over the same stretch leaves it at `speed`, not at `speed` + /// squared, so a second pass over an already-cut timeline changes nothing. + /// + /// Refused by name, with nothing changed and no undo step, when: + /// + /// * a clip on any lane covers only *part* of a region -- the lanes shrink + /// by different amounts and the ripple would pull them apart, which is + /// what cutting does not suffer and why delete mode has no such refusal; + /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the + /// piece could not be split out exactly; + /// * two lanes' pieces would end up different lengths, which is a group + /// whose halves disagree about their span (the refusal + /// [`write_speed`](Project::write_speed) already makes, in its words); + /// * the region would grow rather than shrink, i.e. it already plays faster + /// than `speed`. + pub fn speed_regions(&mut self, regions: &[(u32, u32)], speed: Speed) -> crate::Result<()> { + let regions = tidy(regions); + if regions.is_empty() { + return Err("nothing to speed up".into()); + } + let labels = handles(&self.lanes); + // Before anything is touched, because this is the refusal a person can + // act on: a clip that laps over the edge of a silence has to be trimmed + // (or the silences cut instead), and saying so after a rollback would + // be saying it about a timeline that already looks different. + for &(at, len) in ®ions { + for (l, data) in self.lanes.iter().enumerate() { + for c in &data.clips { + if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len) + { + return Err(format!( + "the {} clip at frame {} covers only part of the silence at [{at}, {}): \ + speeding it up would pull the lanes apart -- trim it first, or cut the \ + silences out instead", + labels[l].label(), + c.start, + at + len + ) + .into()); + } + } + } + } + // The rest is checked as it is built: a split's own arithmetic is what + // says whether a rate can address an edge. So the snapshot is taken + // first and *rolled back* on a refusal -- one undo either way, and a + // refusal still costs no step (`undo` pops the one just pushed). + self.snapshot(); + for &(at, len) in regions.iter().rev() { + self.write_split(at, false); + self.write_split(at + len, false); + let mut room: Option<(Lane, u32)> = None; + let mut refused = None; + for (l, data) in self.lanes.iter().enumerate() { + for c in data.clips.iter().filter(|c| c.end() > at && c.start < at + len) { + if (c.start, c.end()) != (at, at + len) { + refused = Some(format!( + "the {} clip at frame {} plays at {} and cannot be cut at frame {at}: \ + detach it, or put it back to 1.00x first", + labels[l].label(), + c.start, + c.speed + )); + continue; + } + let after = speed.frames(c.len()); + match room { + None => room = Some((labels[l], after)), + Some((first, n)) if n != after => { + refused = Some(format!( + "at {speed} the {} half of the silence at frame {at} would cover \ + {after} frames and the {} half {n}: they are one take and a take \ + is one span -- detach them first", + labels[l].label(), + first.label() + )); + } + Some(_) => {} + } + } + } + let shrunk = match (refused, room) { + (Some(e), _) => { + self.undo(); + return Err(e.into()); + } + // A gap on every lane: nothing to re-rate, and nothing to close. + (None, None) => continue, + (None, Some((_, after))) => after, + }; + let Some(delta) = len.checked_sub(shrunk) else { + self.undo(); + return Err(format!( + "the silence at frame {at} already plays faster than {speed}: \ + at that rate it would be {shrunk} frames instead of {len}" + ) + .into()); + }; + for data in &mut self.lanes { + for c in &mut data.clips { + if c.start == at && c.end() == at + len { + c.speed = speed; + } else if c.start >= at + len { + c.start -= delta; + } + } + debug_assert!(sorted_disjoint(&data.clips)); + } + } + debug_assert!(links_are_consistent(&self.lanes).is_ok()); + Ok(()) + } + /// Remove the `V1` clip at `idx` and everything under it, closing the gap /// -- the whole-group delete a single-lane front-end means. `false` for a /// bad index. Changes the mapping: the caller must reseek. @@ -2307,6 +2458,41 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { *clips = out; } +/// Cuts `[at, at + len)` out of every lane and slides what is behind it back -- +/// the body of [`Project::ripple_delete`], and of every cut a batch +/// ([`Project::cut_regions`]) makes. No snapshot of its own: whose undo step +/// this is belongs to the caller. +fn ripple(lanes: &mut [LaneData], at: u32, len: u32) { + for data in lanes { + clear(&mut data.clips, at, at + len); + for c in data.clips.iter_mut().filter(|c| c.start >= at) { + c.start -= len; + } + debug_assert!(sorted_disjoint(&data.clips)); + } +} + +/// A caller's region list as a batch may use it: sorted by start, empty entries +/// dropped, and touching or overlapping entries merged into one. +/// +/// Overlapping regions are the one thing a batch cannot take -- cutting the +/// second would cut frames the first already moved -- and a detector handing +/// back two that touch means one silence, not two cuts. Merged rather than +/// refused: this is arithmetic on a preview, not a user's mistake. +fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> { + let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect(); + sorted.sort_by_key(|&(at, _)| at); + let mut out: Vec<(u32, u32)> = Vec::new(); + for (at, len) in sorted { + let end = at.saturating_add(len); + match out.last_mut() { + Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1), + _ => out.push((at, len)), + } + } + out +} + /// Slides everything from `at` on later by `len`, splitting a placement that /// straddles `at` so the two halves end up on either side of the hole. The /// insert half of a rippling paste. The two halves lose the group id for the diff --git a/crates/engine/src/silence.rs b/crates/engine/src/silence.rs new file mode 100644 index 0000000..8f412f0 --- /dev/null +++ b/crates/engine/src/silence.rs @@ -0,0 +1,380 @@ +//! Where a clip goes quiet: RMS levels off the same read-only decode path the +//! waveform takes, and the stretches of them nobody wants to watch. +//! +//! Three steps, kept apart so only the first one costs a decode: [`levels`] +//! turns a file into one loudness number per 20 ms window, [`regions`] turns +//! those numbers plus a [`Settings`] into silent stretches of *source* seconds, +//! and [`timeline_regions`] puts those on the timeline through one clip's own +//! range and rate. A card tweaking a threshold re-runs the last two and decodes +//! nothing. +//! +//! Loudness in **dBFS**, which is the unit every tool that does this speaks +//! (ffmpeg's `silencedetect` noise floor, auto-editor's threshold) -- and RMS +//! rather than the peak [`crate::waveform::peaks`] draws, because a single +//! sample spike in a breath is not speech and a peak meter cannot tell them +//! apart. + +use std::path::Path; + +use crate::AudioSession; +use crate::project::{Clip, Speed}; + +/// Loudness windows per second: 50, i.e. 20 ms each -- short enough to place a +/// cut inside one frame at any sane rate, long enough that one glottal pulse is +/// not a silence of its own. +pub const WINDOWS_PER_SEC: u32 = 50; + +/// What a window with no samples in it, or with digital nothing in it, reads +/// as: a floor rather than `-inf`, so a level is always a number a comparison +/// and a `Display` can take. +pub const SILENT_DB: f32 = -120.; + +/// What counts as a silence worth cutting. Seconds, not frames: detection runs +/// on the *source*, whose sample rate is its own business, and the frame grid +/// is applied once at the end ([`timeline_regions`]). +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct Settings { + /// At or below this level a window is quiet. + pub threshold_db: f32, + /// Quiet shorter than this is forgiven -- the pause between two words is + /// not a cut. + pub min_silence: f64, + /// Kept at both ends of every region, so a cut never lands on the consonant + /// that starts the next word. + pub padding: f64, + /// A kept sliver shorter than this joins the silences either side of it: + /// breaths and mouth clicks between two long silences would otherwise + /// survive as one-frame confetti nobody can watch. + pub min_keep: f64, +} + +impl Default for Settings { + /// The conservative end of what shipped tools default to (auto-editor + /// ~-28 dBFS / 0.2 s margin, `silencedetect` -60 dB / 2 s): a first run + /// that leaves a little too much is a run nobody has to undo. + fn default() -> Self { + Self { + threshold_db: -40., + min_silence: 0.5, + padding: 0.15, + min_keep: 0.15, + } + } +} + +/// One RMS level in dBFS per [`WINDOWS_PER_SEC`]th of a second of `stream` of +/// `path`, from media time 0 -- the same decode [`crate::waveform::peaks`] runs +/// and with the same contract: channels folded together, `Ok(None)` for a file +/// with **no audio track at all**, which is a source to refuse by name rather +/// than one long silence to cut. +/// +/// Linear in source length at ~1700x realtime, so a ten-minute take scans in +/// well under a second; a caller caches it per source and stream, because the +/// settings above are all applied to the result and none of them needs a second +/// decode. +pub fn levels(path: impl AsRef, stream: usize) -> crate::Result>> { + let sources = [(path.as_ref().to_path_buf(), stream)]; + let Some((meta, rx)) = + AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])? + else { + return Ok(None); + }; + // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not, + // and a rounded window drifts a bucket every few seconds over a long take. + let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC); + let channels = (meta.channels as usize).max(1); + // Sum of squares and how many samples went into it -- the two halves of a + // mean square, kept in f64 because a loud minute is millions of terms. + let mut sums: Vec<(f64, u64)> = Vec::new(); + for chunk in rx { + for (frame, values) in chunk.samples.chunks(channels).enumerate() { + let window = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize; + if window >= sums.len() { + sums.resize(window + 1, (0., 0)); + } + let slot = &mut sums[window]; + for &v in values { + slot.0 += f64::from(v) * f64::from(v); + slot.1 += 1; + } + } + } + Ok(Some(sums.iter().map(|&(sq, n)| dbfs(sq, n)).collect())) +} + +/// Mean square -> dBFS, floored at [`SILENT_DB`]: full scale is 1.0, so a +/// window of digital zero is `-inf` and is reported as the floor instead. +fn dbfs(square_sum: f64, samples: u64) -> f32 { + if samples == 0 { + return SILENT_DB; + } + let rms = (square_sum / samples as f64).sqrt(); + if rms <= 0. { + return SILENT_DB; + } + (20. * rms.log10()).max(f64::from(SILENT_DB)) as f32 +} + +/// The silent stretches of a `levels` track, as half-open `(from, to)` *source* +/// seconds, in order and never overlapping. +/// +/// Pure arithmetic: this is what a card re-runs on every keystroke. The three +/// settings are applied in the order a person means them -- quiet runs first, +/// then the short ones forgiven ([`Settings::min_silence`]), then a +/// [`Settings::padding`] left at both ends so the cut never touches speech, and +/// last the slivers too short to keep ([`Settings::min_keep`]) swallowed by the +/// silences around them. Padding before the merge on purpose: what the merge +/// measures is what would actually survive the cut. +pub fn regions(levels: &[f32], cfg: Settings) -> Vec<(f64, f64)> { + let window = 1. / f64::from(WINDOWS_PER_SEC); + let mut quiet: Vec<(f64, f64)> = Vec::new(); + let mut run: Option = None; + for (i, &db) in levels.iter().enumerate() { + match (db <= cfg.threshold_db, run) { + (true, None) => run = Some(i), + (false, Some(from)) => { + quiet.push((from as f64 * window, i as f64 * window)); + run = None; + } + _ => {} + } + } + if let Some(from) = run { + quiet.push((from as f64 * window, levels.len() as f64 * window)); + } + let padded = quiet + .into_iter() + .filter(|&(from, to)| to - from >= cfg.min_silence) + .map(|(from, to)| (from + cfg.padding, to - cfg.padding)) + .filter(|&(from, to)| to > from); + let mut out: Vec<(f64, f64)> = Vec::new(); + for (from, to) in padded { + match out.last_mut() { + Some(last) if from - last.1 < cfg.min_keep => last.1 = to, + _ => out.push((from, to)), + } + } + out +} + +/// Where those source stretches sit on the timeline, as `(start, len)` frame +/// pairs of the lane `clip` is on -- what a preview marks and what +/// [`crate::Project::cut_regions`] cuts. +/// +/// Only the part of each region the clip actually plays: the scan reads the +/// whole file and the clip is a range of it, so a silence outside `[in, out)` +/// is not on the timeline at all. Positions go through the clip's **own rate** +/// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is +/// really on. +/// +/// Both edges are rounded **inward** -- start up, end down -- so a frame that +/// is partly speech stays outside the region at every rate. An empty remainder +/// is dropped rather than returned as a zero-length cut. +pub fn timeline_regions(clip: &Clip, fps: f64, regions: &[(f64, f64)]) -> Vec<(u32, u32)> { + if !(fps.is_finite() && fps > 0.) { + return Vec::new(); + } + let frame = |secs: f64, round: fn(f64) -> f64| { + let n = round(secs * fps); + n.clamp(0., f64::from(u32::MAX)) as u32 + }; + regions + .iter() + .filter_map(|&(from, to)| { + let first = frame(from, f64::ceil).max(clip.in_frame); + let last = frame(to, f64::floor).min(clip.out_frame); + if last <= first { + return None; + } + let start = clip.start + clip.speed.timeline_at(first - clip.in_frame); + let end = clip.start + floor_timeline(clip.speed, last - clip.in_frame); + (end > start).then_some((start, end - start)) + }) + .collect() +} + +/// [`Speed::timeline_at`] floored instead of ceiled: which timeline frame of a +/// clip a source frame lands on, rounded the way an *end* has to be so a +/// region never eats the frame speech starts on. The ceil is the right rounding +/// for a start and for playback's stamps, and this is its partner. +fn floor_timeline(speed: Speed, offset: u32) -> u32 { + (u64::from(offset) * 1000 / u64::from(speed.permille())).min(u64::from(u32::MAX)) as u32 +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::{Settings, levels, regions, timeline_regions}; + use crate::project::{Clip, Speed}; + use crate::scale::FitPolicy; + + fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) + } + + fn clip(start: u32, in_frame: u32, out_frame: u32, speed: Speed) -> Clip { + Clip { + start, + in_frame, + out_frame, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed, + } + } + + /// A level track: `db` for every window, with the named half-open window + /// ranges dropped to digital silence. + fn track(windows: usize, db: f32, quiet: &[(usize, usize)]) -> Vec { + let mut out = vec![db; windows]; + for &(from, to) in quiet { + out[from..to].fill(super::SILENT_DB); + } + out + } + + /// Seconds compared as seconds: a window edge is a multiple of 0.02 and a + /// padding is added to it, neither of which is exact in binary. + fn near(got: &[(f64, f64)], want: &[(f64, f64)]) { + assert_eq!(got.len(), want.len(), "{got:?} against {want:?}"); + for (&(a, b), &(c, d)) in got.iter().zip(want) { + assert!( + (a - c).abs() < 1e-9 && (b - d).abs() < 1e-9, + "{got:?} against {want:?}" + ); + } + } + + /// The fixture's envelope is `0.5 + 0.5*sin(2*PI*t)`: full silence every + /// second at t = 0.75. Detection has to land on those five dips and on + /// nothing else -- a scan that lost the chunk positions, or that measured + /// peaks instead of RMS, would not line up second after second. + #[test] + fn the_dips_of_the_1hz_pulse_are_where_the_silences_are() { + let levels = levels(asset("test_av.mp4"), 0) + .expect("open") + .expect("test_av.mp4 has an audio track"); + // A short forgiveness, because each dip of a sine is brief. + let cfg = Settings { + threshold_db: -40., + min_silence: 0.08, + padding: 0., + min_keep: 0., + }; + let found = regions(&levels, cfg); + assert_eq!(found.len(), 5, "{found:?}"); + for (second, &(from, to)) in found.iter().enumerate() { + let dip = second as f64 + 0.75; + assert!( + (from..to).contains(&dip), + "second {second}: {from}..{to} does not cover the dip at {dip}" + ); + } + // Nothing survives a forgiveness longer than any dip is. + assert!( + regions( + &levels, + Settings { + min_silence: 1.5, + ..cfg + } + ) + .is_empty() + ); + } + + /// The three settings, each one visible on its own: a quiet run shorter + /// than `min_silence` is forgiven, `padding` shrinks what is left at both + /// ends, and a kept sliver shorter than `min_keep` joins the silences + /// around it rather than surviving as one-frame confetti. + #[test] + fn forgiveness_padding_and_min_keep_each_show_up() { + // 10 s of speech with a 0.2 s dip, a 1 s silence and a 2 s silence. + let levels = track(500, -12., &[(50, 60), (100, 150), (300, 400)]); + let bare = Settings { + threshold_db: -40., + min_silence: 0.5, + padding: 0., + min_keep: 0., + }; + near(®ions(&levels, bare), &[(2., 3.), (6., 8.)]); + // Padding takes 0.15 s off each end of each region, and off nothing + // else: a region is 0.3 s shorter and starts 0.15 s later. + let padded = regions( + &levels, + Settings { + padding: 0.15, + ..bare + }, + ); + near(&padded, &[(2.15, 2.85), (6.15, 7.85)]); + // Two silences with a two-window sliver of speech between them: with + // nothing to keep it, the sliver joins them into one region. + let sliver = track(500, -12., &[(100, 150), (152, 250)]); + assert_eq!( + regions(&sliver, bare).len(), + 2, + "the sliver is kept while min_keep is zero" + ); + let merged = regions( + &sliver, + Settings { + min_keep: 0.15, + ..bare + }, + ); + near(&merged, &[(2., 5.)]); + } + + /// Where a region lands on the timeline is the clip's business: its range + /// clips what was scanned, its placement offsets it, and its rate divides + /// it. A 2x clip's silences mark half as many frames, at the right place. + #[test] + fn regions_map_through_the_clips_range_and_rate() { + let secs = [(1., 2.), (3., 3.5)]; + // Whole file, real time, placed at the start: source seconds are + // timeline frames at 30 fps. + let whole = clip(0, 0, 300, Speed::NORMAL); + assert_eq!( + timeline_regions(&whole, 30., &secs), + vec![(30, 30), (90, 15)] + ); + // The same clip placed at frame 100 and reading from source frame 45: + // the first region is only the half of it the clip still plays, and it + // lands at the clip's own start. + let placed = clip(100, 45, 300, Speed::NORMAL); + assert_eq!( + timeline_regions(&placed, 30., &secs), + vec![(100, 15), (145, 15)] + ); + // At 2x every timeline frame is two source frames, so both regions are + // half as wide and sit half as far along. + let fast = clip(0, 0, 300, Speed::from_permille(2000)); + assert_eq!(timeline_regions(&fast, 30., &secs), vec![(15, 15), (45, 7)]); + // A region entirely outside what the clip plays is not on the timeline. + assert!(timeline_regions(&clip(0, 200, 300, Speed::NORMAL), 30., &[(1., 2.)]).is_empty()); + } + + /// Rounded inward at both ends: a region whose seconds fall between frames + /// gives back the frames it *fully* covers, so no frame of speech is ever + /// inside a cut. Half a frame of silence is dropped, never claimed. + #[test] + fn edges_round_inward_so_speech_keeps_its_frames() { + let whole = clip(0, 0, 300, Speed::NORMAL); + // [1.01, 1.99) s at 30 fps is source frames 30.3 .. 59.7: the region + // may only claim 31..59. + assert_eq!( + timeline_regions(&whole, 30., &[(1.01, 1.99)]), + vec![(31, 28)] + ); + // Under a frame wide: nothing survives the rounding, and a zero-length + // cut is never handed back. + assert!(timeline_regions(&whole, 30., &[(1.01, 1.02)]).is_empty()); + } +} diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs new file mode 100644 index 0000000..7712c68 --- /dev/null +++ b/crates/engine/tests/silence.rs @@ -0,0 +1,233 @@ +//! The jumpcut, end to end through the front door: a real file scanned for its +//! silences, the regions that come back cut (or sped up) as **one** edit, and +//! the timeline that leaves. +//! +//! `silence.rs`'s own unit tests own the detection arithmetic. What is measured +//! here is what an editor would see: how long the timeline is afterwards, that +//! every lane moved together, that one undo press takes the whole batch back, +//! and that the refusals name what is in the way. Group consistency is checked +//! the way a save checks it -- the parts are handed back to +//! `Project::from_parts`, which is the door a `.edith` comes in through. + +use std::path::PathBuf; + +use engine::project::{Lane, LaneKind, Speed}; +use engine::silence::{self, Settings}; +use engine::{Clip, Project}; + +const FPS: f64 = 30.0; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The A/V fixture as a fresh project: `V1` and `A1`, one grouped clip each +/// covering the whole file -- what opening it in the editor gives. +fn fixture() -> Project { + let path = asset("test_av.mp4"); + let (meta, _) = engine::demux::Demuxer::open(&path).expect("open the fixture"); + Project::single(&path, meta.frame_count) +} + +/// A link is one span on however many lanes, and a project whose links disagree +/// is one no save could load: this is that check, through the same door a load +/// takes. +fn loadable(project: &Project) { + let (sources, lanes, eq, color) = project.without_orphan_sources(); + Project::from_parts(sources, lanes, eq, color).expect("the lanes still load"); +} + +fn spans(project: &Project) -> (Vec<(u32, u32)>, Vec<(u32, u32)>) { + ( + project.lane_spans(Lane::V1), + project.lane_spans(Lane::new(LaneKind::Audio, 0)), + ) +} + +/// Five cuts, one undo press. The linked picture slides exactly as its sound +/// does, the timeline is shorter by exactly what was cut, and the press after +/// the undo reaches the edit that came *before* the jumpcut -- which is what a +/// loop over `ripple_delete` would have buried under five steps. +#[test] +fn a_batch_of_cuts_is_one_edit_and_moves_every_lane_alike() { + let mut p = fixture(); + let was = p.timeline_frames(); + // An edit first, so the undo stack has something under the batch. + assert!(p.split(60)); + let before = p.lane(Lane::V1).to_vec(); + let regions = [(10, 5), (30, 5), (50, 5), (70, 5), (90, 5)]; + assert!(p.cut_regions(®ions)); + + let cut: u32 = regions.iter().map(|&(_, len)| len).sum(); + assert_eq!(p.timeline_frames(), was - cut); + let (video, audio) = spans(&p); + assert_eq!(video, audio, "the picture and its sound moved apart"); + loadable(&p); + + // One press takes the whole batch back... + assert!(p.undo()); + assert_eq!(p.lane(Lane::V1), before, "one undo did not restore the lot"); + assert_eq!(p.timeline_frames(), was); + // ...and the next one is the split, not another fifth of the jumpcut. + assert!(p.undo()); + assert_eq!(p.lane(Lane::V1).len(), 1); + assert!(!p.undo(), "the batch left extra history behind"); +} + +/// Speeding the silences up leaves **no holes**: `set_speed` on its own does +/// not ripple, and a gap where a silence shrank is the whole failure this +/// guards. Everything that was contiguous stays contiguous, both lanes shrink +/// alike, and it is one undo press. +#[test] +fn speeding_silences_up_closes_the_room_they_no_longer_need() { + let mut p = fixture(); + let was = p.timeline_frames(); + let regions = [(30, 20), (80, 20)]; + p.speed_regions(®ions, Speed::MAX).expect("no lane laps"); + + // 20 source frames at 4x occupy 5, so each region gives back 15. + let shrunk = Speed::MAX.frames(20); + let (video, audio) = spans(&p); + assert_eq!(video, audio); + assert_eq!(p.timeline_frames(), was - 2 * (20 - shrunk)); + for pair in video.windows(2) { + assert_eq!( + pair[0].0 + pair[0].1, + pair[1].0, + "a hole was left where a silence shrank: {video:?}" + ); + } + // The pieces that were the silences are the ones running fast, and only + // those. + let fast: Vec = p + .lane(Lane::V1) + .iter() + .filter(|c| c.speed == Speed::MAX) + .map(|c| c.start) + .collect(); + assert_eq!(fast, vec![30, 30 + shrunk + (80 - 50)]); + loadable(&p); + + // Absolute, not compounding: running it again over where those pieces sit + // now leaves the timeline byte for byte as it was -- 4x set twice is 4x. + let settled = p.lane(Lane::V1).to_vec(); + let again: Vec<(u32, u32)> = fast.iter().map(|&at| (at, shrunk)).collect(); + p.speed_regions(&again, Speed::MAX).expect("still no lap"); + assert_eq!(p.lane(Lane::V1), settled, "a second pass compounded"); + + assert!(p.undo()); + assert!(p.undo()); + assert_eq!(p.lane(Lane::V1).len(), 1, "one press per apply, no more"); + assert!(!p.undo()); +} + +/// A clip on another lane that laps over the edge of a silence makes speed mode +/// refuse **by name**: the lanes would shrink by different amounts and the +/// ripple would pull them apart. The refusal costs no undo step and changes +/// nothing -- and cutting the same regions is still fine, which is why delete +/// mode needs no such rule. +#[test] +fn speed_mode_refuses_a_clip_that_laps_over_a_silence() { + let mut p = fixture(); + let lane = p.add_lane(LaneKind::Video); + assert_eq!(lane.label(), "V2"); + let broll = Clip { + start: 0, + in_frame: 0, + out_frame: 20, + source: 0, + link: None, + eq: None, + color: None, + fit: Default::default(), + speed: Speed::NORMAL, + }; + assert!(p.place(lane, 40, broll)); + let before = spans(&p); + + let err = p + .speed_regions(&[(30, 20)], Speed::MAX) + .expect_err("a half-covered region must not be sped up") + .to_string(); + assert!(err.contains("V2"), "{err}"); + assert!(err.contains("40"), "{err}"); + assert_eq!(spans(&p), before, "a refusal changed the timeline"); + + // No undo step was spent on it: the press below is the `place` above. + assert!(p.undo()); + assert!(p.lane(lane).is_empty()); + + // The same regions cut instead: a ripple is uniform, so nothing laps. + assert!(p.place(lane, 40, broll)); + assert!(p.cut_regions(&[(30, 20)])); + loadable(&p); +} + +/// The whole chain a person presses one key for: the fixture is scanned, its +/// silences come back as timeline frames, and cutting them shortens the +/// timeline by exactly what was found -- with the scan itself having changed +/// nothing at all. +/// +/// `test_av.mp4`'s envelope is silent every second at t≈0.75, so the regions +/// land there ±1 frame. +#[test] +fn scanning_a_clip_and_cutting_what_it_finds() { + let mut p = fixture(); + let was = p.timeline_frames(); + // Nothing to undo yet, and the scan below must not change that: a preview + // is not an edit. + assert!(!p.undo()); + + let levels = silence::levels(asset("test_av.mp4"), 0) + .expect("scan") + .expect("the fixture has audio"); + let cfg = Settings { + threshold_db: -40., + min_silence: 0.08, + padding: 0.02, + min_keep: 0., + }; + let audio = Lane::new(LaneKind::Audio, 0); + let clip = p.lane(audio)[0]; + let regions = silence::timeline_regions(&clip, FPS, &silence::regions(&levels, cfg)); + assert_eq!(regions.len(), 5, "{regions:?}"); + for (second, &(start, len)) in regions.iter().enumerate() { + // The dip of that second, in frames, sits inside the marked region. + let dip = (second as f64 + 0.75) * FPS; + assert!( + (f64::from(start) - 1.0..f64::from(start + len) + 1.0).contains(&dip), + "second {second}: [{start}, {}) is not the dip at {dip}", + start + len + ); + } + assert!(!p.undo(), "the scan took an undo step"); + + let cut: u32 = regions.iter().map(|&(_, len)| len).sum(); + assert!(p.cut_regions(®ions)); + assert_eq!(p.timeline_frames(), was - cut); + let (video, audio_spans) = spans(&p); + assert_eq!(video, audio_spans); + loadable(&p); + + // What a jumpcut leaves is ordinary clips, so the file it saves to is the + // same dialect it always was -- no wire change went with this feature. + let dir = std::env::temp_dir().join(format!("edith-silence-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a place to save"); + let file = dir.join("cut.edith"); + let (sources, lanes, eq, color) = p.without_orphan_sources(); + engine::edith::save(&file, &sources, &lanes, &eq, &color, (1920, 1080), 0).expect("save"); + let text = std::fs::read_to_string(&file).expect("read it back"); + assert!( + text.starts_with("edith 8"), + "{:?}", + &text[..16.min(text.len())] + ); + let back = engine::edith::load(&file).expect("load"); + assert_eq!(back.lanes, lanes, "the cut timeline did not round-trip"); + std::fs::remove_dir_all(&dir).ok(); + + assert!(p.undo()); + assert_eq!(p.timeline_frames(), was); +}