diff --git a/.github/workflows/fork-macos-release.yml b/.github/workflows/fork-macos-release.yml new file mode 100644 index 00000000000..cabce9a7fab --- /dev/null +++ b/.github/workflows/fork-macos-release.yml @@ -0,0 +1,187 @@ +name: "fork-macos-release" + +# Builds Cap for Apple Silicon and attaches the disk image to a GitHub release +# on this fork. The app keeps the so.cap.desktop identity, so it installs over +# the official Cap and reuses its recordings and settings. It is signed with +# the fork owner's Developer ID and notarized, so macOS keeps its privacy +# grants across updates. Without the APPLE_* secrets it falls back to an +# ad-hoc signature, and macOS asks for permissions again after every update. +# +# Every merge to main builds and publishes a release tagged +# fw-v-build.. It also runs from the Actions tab, or when a tag +# named fw-v is pushed. The tag the release step creates is pushed +# with GITHUB_TOKEN, which does not start another run. + +on: + workflow_dispatch: + push: + branches: + - main + tags: + - "fw-v*" + +permissions: + contents: write + +concurrency: + group: fork-macos-release-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + if: ${{ github.repository != 'CapSoftware/Cap' }} + runs-on: macos-15 + timeout-minutes: 360 + env: + TARGET: aarch64-apple-darwin + CAP_BUNDLE: apps/desktop-gpui/target/aarch64-apple-darwin/release/bundle + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Rust setup + uses: dtolnay/rust-toolchain@1.88.0 + with: + targets: aarch64-apple-darwin + + - uses: ./.github/actions/setup-rust-cache + with: + target: aarch64-apple-darwin + prefix-key: v1-rust-fork-release + save-cache: true + cache-on-failure: true + workspaces: | + . -> target + apps/desktop-gpui -> target + + - uses: ./.github/actions/setup-js + + - name: Name the release + id: release + shell: bash + run: | + set -euo pipefail + version="$(sed -n 's/^version = "\(.*\)"$/\1/p' apps/desktop-gpui/Cargo.toml | head -n 1)" + if [[ "$GITHUB_REF_TYPE" == "tag" ]]; then + tag="$GITHUB_REF_NAME" + else + tag="fw-v$version-build.$GITHUB_RUN_NUMBER" + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + + - name: Check signing secrets + id: signing + shell: bash + env: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_API_KEY_FILE: ${{ secrets.APPLE_API_KEY_FILE }} + run: | + if [[ -n "$APPLE_CERTIFICATE" && -n "$APPLE_API_KEY_FILE" ]]; then + echo "signed=true" >> "$GITHUB_OUTPUT" + else + echo "signed=false" >> "$GITHUB_OUTPUT" + fi + + - name: Write the notarization key + if: ${{ steps.signing.outputs.signed == 'true' }} + shell: bash + env: + APPLE_API_KEY_FILE: ${{ secrets.APPLE_API_KEY_FILE }} + run: printf '%s\n' "$APPLE_API_KEY_FILE" > "$RUNNER_TEMP/api.p8" + + - uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2 + if: ${{ steps.signing.outputs.signed == 'true' }} + with: + p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }} + p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + + - name: Create .env file in root + shell: bash + run: | + { + echo "appVersion=${{ steps.release.outputs.version }}" + echo "VITE_ENVIRONMENT=production" + echo "RUST_TARGET_TRIPLE=$TARGET" + } >> .env + + # cap-setup downloads the ONNX Runtime dylib that ships in the app's + # Resources. Tauri does not sign resources, so cap-setup signs it here. + # It needs the Developer ID already in the keychain, or notarization + # rejects the app. + - name: Run cap-setup + shell: bash + run: bun run cap-setup + env: + RUST_TARGET_TRIPLE: ${{ env.TARGET }} + APPLE_SIGNING_IDENTITY: ${{ steps.signing.outputs.signed == 'true' && secrets.APPLE_SIGNING_IDENTITY || '' }} + APPLE_KEYCHAIN: ${{ steps.signing.outputs.signed == 'true' && format('{0}/build.keychain', runner.temp) || '' }} + + - name: Build desktop binaries + shell: bash + env: + CARGO_PROFILE_RELEASE_DEBUG: "0" + CARGO_PROFILE_RELEASE_STRIP: symbols + run: ./scripts/build-desktop-binaries.sh "$TARGET" + + # With the secrets, Tauri signs with the Developer ID and notarizes. The + # updater archive is skipped because only Cap can sign one. + - name: Build Cap + shell: bash + env: + CI: false + CAP_BUILD_REVISION: ${{ github.sha }} + RUST_TARGET_TRIPLE: ${{ env.TARGET }} + SIGNED: ${{ steps.signing.outputs.signed }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} + APPLE_API_KEY_PATH: ${{ runner.temp }}/api.p8 + run: | + if [[ "$SIGNED" == "true" ]]; then + config='{"bundle":{"createUpdaterArtifacts":false}}' + else + unset APPLE_SIGNING_IDENTITY APPLE_API_ISSUER APPLE_API_KEY APPLE_API_KEY_PATH + config='{"bundle":{"createUpdaterArtifacts":false,"macOS":{"signingIdentity":"-"}}}' + fi + node scripts/bundle-gpui.mjs "$TARGET" --bundles app,dmg --config "$config" + + - name: Verify the app + shell: bash + run: | + set -euo pipefail + app="$CAP_BUNDLE/macos/Cap.app" + test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist")" = "so.cap.desktop" + codesign --verify --deep --strict "$app" + for binary in Cap cap-cli cap-muxer; do + test -x "$app/Contents/MacOS/$binary" + done + + - name: Stage the disk image + id: dmg + shell: bash + run: | + set -euo pipefail + source="$(find "$CAP_BUNDLE/dmg" -maxdepth 1 -name '*.dmg' | head -n 1)" + test -n "$source" + dmg="$RUNNER_TEMP/Cap_${{ steps.release.outputs.tag }}_aarch64.dmg" + hdiutil convert "$source" -format ULMO -o "$dmg" + hdiutil verify "$dmg" + echo "path=$dmg" >> "$GITHUB_OUTPUT" + + - name: Publish the release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.release.outputs.tag }} + target_commitish: ${{ github.sha }} + name: Cap ${{ steps.release.outputs.version }} (${{ steps.release.outputs.tag }}) + files: ${{ steps.dmg.outputs.path }} + make_latest: true + body: | + Cap ${{ steps.release.outputs.version }} built from ${{ github.sha }} for Apple Silicon Macs. + + **Install:** quit Cap, open the disk image and drag Cap to Applications, replacing the existing copy. Recordings and settings carry over. + + **First launch:** macOS asks for Screen Recording, Camera and Microphone access once. If this release was built without the Apple signing secrets it is not notarized: open System Settings → Privacy & Security and click **Open Anyway** next to Cap. + + **Updates:** declining Cap's own update prompts keeps this version. Accepting one replaces it with the official Cap. diff --git a/apps/desktop-gpui/README.md b/apps/desktop-gpui/README.md index d13e0114602..d8a8f148f58 100644 --- a/apps/desktop-gpui/README.md +++ b/apps/desktop-gpui/README.md @@ -1871,11 +1871,63 @@ its baseline values, every drag and delete having been undone. | **Escape clears only the selection** | The source also clears `audioPicker` and `camera3dSetup`, neither of which exists yet. | | **No `hidden_text_segments` bookkeeping** | `#[serde(skip_serializing)]` on the field means it never round-trips through a write in either app; nothing here maintains it. | +### Clean Up + +The sidebar's **Clean Up** tab (scissors) cuts silences out of the timeline +before captions or export. It has no Tauri counterpart. + +- **Detection** runs on audio the editor has already decoded. + `load_editor_waveforms` measures each recording clip's mic and system audio + once, as a 10ms RMS loudness envelope (`kernels/src/silence.rs`), on the + background executor next to the waveform peaks. + - `clean_up::detect_silences` turns the two envelopes into silence ranges in + **source time**. It combines them per window by the louder track, after + each track's clip offset, timing repair and project gain; a track at + -30 dB or below is ignored. + - The ranges are recomputed only when the settings, the track gains or the + clip offsets change. Timeline edits only re-map them. +- **The settings**, in order of application: + 1. **Silence Threshold:** the loudness below which a window counts as silent. + 2. Blips of 20ms or less inside a pause are bridged. + 3. **Min Duration:** the shortest silence that gets cut. + 4. **Min Keep:** a sound shorter than this between two cut silences is cut + with them. + 5. **Pad start / Pad end:** silence left in after speech stops and before it + resumes. Neither pad applies at a recording's own edges. + + Presets are fixed settings; any other combination shows no preset + selected. The settings live on the window, not in the project. +- **Mapping:** `timeline_silences` intersects each clip segment with its + recording clip's ranges and places them in output time through + `clip_timeline_offsets` and the hold windows. + - It stays out of a transition's overlap. + - It snaps to a clip edge rather than leaving a sliver of under 30ms. + - One detected range can appear in several segments once a clip has been + split, and keeping or cutting it acts on every part. +- **Cutting** is one `edit`, so one undo entry. + - `editor_edits::cut_clip_source_range` removes a source range from a + segment by trimming its head or tail or splitting it. + - It ripples every other track exactly as `delete_clip_segments` does, + through `ripple_delete_output_tracks`. + - The cuts apply from the last segment and latest range backwards, so + earlier indices never move. A segment the cut covers entirely is + deleted, unless it is the last one. +- **Review:** "Review silences" draws the ranges on the clip track and floats + a pill over the timeline. Its controls are previous/next, keep (toggle), + cut this one, and `Esc`. + - The overlays show whenever the Clean Up tab is open. + - Kept ranges draw grey and are left out of "Cut N silences". + - Each cut logs `clean up cut silences` plus the usual `timeline edit` line. +- **Captions** need nothing special. They are source-timed, so + `synchronize_captions` re-projects them onto the edited timeline on the + next `project_changed`. + ## The config sidebar The panel on the right, **complete**: six tabs, the colour-grade section they -share, and the eight per-segment panels the timeline selection routes to. +share, and the eight per-segment panels the timeline selection routes to. A +seventh tab, Clean Up, is this app's own (see [Clean Up](#clean-up)). `ConfigSidebar.tsx` is 6500 lines and really twenty small panels in a trenchcoat, so it lands in four modules: diff --git a/apps/desktop-gpui/kernels/src/lib.rs b/apps/desktop-gpui/kernels/src/lib.rs index 3971ea2da35..b6ff72fe68e 100644 --- a/apps/desktop-gpui/kernels/src/lib.rs +++ b/apps/desktop-gpui/kernels/src/lib.rs @@ -3,6 +3,7 @@ pub mod frame; pub mod mask_cache; pub mod png; pub mod screenshot; +pub mod silence; pub mod texture; pub mod thumbnail; pub mod waveform; diff --git a/apps/desktop-gpui/kernels/src/silence.rs b/apps/desktop-gpui/kernels/src/silence.rs new file mode 100644 index 00000000000..77821867184 --- /dev/null +++ b/apps/desktop-gpui/kernels/src/silence.rs @@ -0,0 +1,88 @@ +pub const WINDOW_FRAMES: usize = 480; +pub const FLOOR_DB: f32 = -100.0; + +pub fn loudness_db<'a>(slices: impl IntoIterator, channels: u16) -> Vec { + let window = WINDOW_FRAMES * usize::from(channels.max(1)); + let mut levels = Vec::new(); + let mut sum = 0.0_f32; + let mut count = 0; + for mut slice in slices { + while !slice.is_empty() { + let (chunk, rest) = slice.split_at((window - count).min(slice.len())); + sum = chunk.iter().fold(sum, |sum, sample| sum + sample * sample); + count += chunk.len(); + slice = rest; + if count == window { + levels.push(mean_square_db(sum / count as f32)); + sum = 0.0; + count = 0; + } + } + } + if count > 0 { + levels.push(mean_square_db(sum / count as f32)); + } + levels +} + +fn mean_square_db(mean_square: f32) -> f32 { + if mean_square.is_finite() && mean_square > 1e-10 { + (10.0 * mean_square.log10()).max(FLOOR_DB) + } else { + FLOOR_DB + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sine(frames: usize, channels: u16, amplitude: f32) -> Vec { + (0..frames) + .flat_map(|frame| { + let value = + amplitude * (frame as f32 * 1_000.0 * std::f32::consts::TAU / 48_000.0).sin(); + std::iter::repeat_n(value, usize::from(channels)) + }) + .collect() + } + + #[test] + fn digital_silence_sits_on_the_floor() { + let samples = vec![0.0; WINDOW_FRAMES * 3]; + assert_eq!(loudness_db([samples.as_slice()], 1), vec![FLOOR_DB; 3]); + } + + #[test] + fn a_full_scale_sine_measures_minus_three_db() { + let samples = sine(WINDOW_FRAMES * 10, 2, 1.0); + let levels = loudness_db([samples.as_slice()], 2); + assert_eq!(levels.len(), 10); + for level in levels { + assert!((level + 3.01).abs() < 0.05, "{level}"); + } + } + + #[test] + fn uneven_blocks_match_one_contiguous_slice() { + let samples = sine(WINDOW_FRAMES * 7 + 123, 2, 0.25); + let expected = loudness_db([samples.as_slice()], 2); + for block in [1, 7, 959, 960, 4_096] { + let actual = loudness_db(samples.chunks(block), 2); + assert_eq!(actual.len(), expected.len()); + for (actual, expected) in actual.iter().zip(&expected) { + assert!( + (actual - expected).abs() < 1e-4, + "{block}: {actual} {expected}" + ); + } + } + } + + #[test] + fn a_trailing_partial_window_is_measured() { + let samples = sine(WINDOW_FRAMES + 10, 1, 0.5); + assert_eq!(loudness_db([samples.as_slice()], 1).len(), 2); + assert!(loudness_db(std::iter::empty::<&[f32]>(), 1).is_empty()); + } +} diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 4088893cb8e..a49b62ef043 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -2512,6 +2512,7 @@ audio = "Audio" background = "Hintergrund" camera = "Kamera" captions = "Untertitel" +clean_up = "Bereinigen" cursor = "Cursor" keyboard = "Tastatur" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index e35ece3f5d2..38cb06639b9 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -2514,6 +2514,7 @@ audio = "Audio" background = "Background" camera = "Camera" captions = "Captions" +clean_up = "Clean Up" cursor = "Cursor" keyboard = "Keyboard" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 05919083e97..055a4754cc4 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -2512,6 +2512,7 @@ audio = "Audio" background = "Fondo" camera = "Cámara" captions = "Subtítulos" +clean_up = "Limpieza" cursor = "Cursor" keyboard = "Teclado" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 1910c1c9fd7..7e0614e6777 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -2512,6 +2512,7 @@ audio = "Audio" background = "Arrière-plan" camera = "Caméra" captions = "Sous-titres" +clean_up = "Nettoyage" cursor = "Curseur" keyboard = "Clavier" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 3897e1496fc..b1484887e4b 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -2512,6 +2512,7 @@ audio = "ऑडियो" background = "बैकग्राउंड" camera = "कैमरा" captions = "कैप्शन" +clean_up = "सफ़ाई" cursor = "कर्सर" keyboard = "कीबोर्ड" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 193023eb2cb..d13a456555a 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -2512,6 +2512,7 @@ audio = "音声" background = "背景" camera = "カメラ" captions = "字幕" +clean_up = "クリーンアップ" cursor = "カーソル" keyboard = "キーボード" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 8e832b80999..f2e525385b9 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -2512,6 +2512,7 @@ audio = "音频" background = "背景" camera = "摄像头" captions = "字幕" +clean_up = "清理" cursor = "光标" keyboard = "键盘" diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs index 82686f87b0e..55f2b891cd7 100644 --- a/apps/desktop-gpui/src/app_windows.rs +++ b/apps/desktop-gpui/src/app_windows.rs @@ -6467,6 +6467,21 @@ fn log_timeline_model(model: &editor_timeline::TimelineModel) { /// awaits a tokio watch channel, so it runs on the tokio runtime; the peak /// extraction itself is a per-sample loop over a whole track, which goes to the /// background executor rather than the UI thread. +fn measure_audio_tracks( + tracks: &[Option>], + kernel: fn(&[&[f32]], u16) -> Vec, +) -> Vec>> { + tracks + .iter() + .map(|audio| { + Arc::new(match audio { + Some(audio) => kernel(&audio.sample_slices().collect::>(), audio.channels()), + None => Vec::new(), + }) + }) + .collect() +} + fn load_editor_waveforms( instance: Arc, handle: WindowHandle, @@ -6477,6 +6492,7 @@ fn load_editor_waveforms( gpui_tokio::Tokio::spawn(cx, async move { let mut mic = Vec::with_capacity(instance.segment_medias.len()); let mut system = Vec::with_capacity(instance.segment_medias.len()); + let mut repairs = Vec::with_capacity(instance.segment_medias.len()); for segment in instance.segment_medias.iter() { for (loader, out) in [ (&segment.audio, &mut mic), @@ -6484,40 +6500,55 @@ fn load_editor_waveforms( ] { out.push(loader.get().await.ok().flatten()); } + repairs.push(segment.audio_timing_repair); } - (mic, system) + (mic, system, repairs) }) }); - let Ok((mic, system)) = task.await else { + let Ok((mic, system, repairs)) = task.await else { return; }; - let peaks = cx + let (mic, system, peaks) = cx .background_executor() .spawn(async move { - let [mic, system] = [mic, system].map(|tracks| { - tracks - .into_iter() - .map(|audio| { - Arc::new(match audio { - Some(audio) => editor_timeline::waveform_peaks( - &audio.sample_slices().collect::>(), - audio.channels(), - ), - None => Vec::new(), - }) - }) - .collect::>() - }); - (mic, system) + let peaks = ( + measure_audio_tracks(&mic, editor_timeline::waveform_peaks), + measure_audio_tracks(&system, editor_timeline::waveform_peaks), + ); + (mic, system, peaks) }) .await; - let _ = handle.update(cx, |view, window, cx| { + let shown = handle.update(cx, |view, window, cx| { tracing::info!( mic = peaks.0.iter().filter(|peaks| !peaks.is_empty()).count(), system = peaks.1.iter().filter(|peaks| !peaks.is_empty()).count(), "editor waveforms ready" ); - view.set_waveforms(peaks.0, peaks.1, window, cx) + view.set_waveforms(peaks.0, peaks.1, window, cx); + }); + if shown.is_err() { + return; + } + let envelopes = cx + .background_executor() + .spawn(async move { + let mic_levels = measure_audio_tracks(&mic, crate::clean_up::loudness_db); + let system_levels = measure_audio_tracks(&system, crate::clean_up::loudness_db); + mic_levels + .into_iter() + .zip(system_levels) + .zip(repairs) + .map(|((mic, system), repair)| crate::clean_up::ClipEnvelope { + mic: (!mic.is_empty()).then_some(mic), + system: (!system.is_empty()).then_some(system), + mic_repair_secs: f64::from(repair.mic_offset_secs), + system_repair_secs: f64::from(repair.system_audio_offset_secs), + }) + .collect::>() + }) + .await; + let _ = handle.update(cx, |view, window, cx| { + view.set_clean_up_envelopes(envelopes, window, cx); }); }) .detach(); diff --git a/apps/desktop-gpui/src/assets.rs b/apps/desktop-gpui/src/assets.rs index b32032ba8e8..ce40287fa33 100644 --- a/apps/desktop-gpui/src/assets.rs +++ b/apps/desktop-gpui/src/assets.rs @@ -360,6 +360,7 @@ mod tests { // The five later tabs, the colour-grade section and the eight segment // panels each name their own glyphs. include_str!("editor_tabs.rs"), + include_str!("editor_clean_up.rs"), // The cursor tab's style picker and ripple section live one directory // down, and the ripple field names its own glyph. include_str!("editor_sidebar/cursor.rs"), diff --git a/apps/desktop-gpui/src/clean_up.rs b/apps/desktop-gpui/src/clean_up.rs new file mode 100644 index 00000000000..9ec01513044 --- /dev/null +++ b/apps/desktop-gpui/src/clean_up.rs @@ -0,0 +1,1121 @@ +use std::{collections::HashSet, sync::Arc}; + +use cap_gpui_kernels::silence::FLOOR_DB; +use cap_project::{ProjectConfiguration, TimelineConfiguration}; + +use crate::{ + editor_edits::{cut_clip_source_range, effective_to_output_end}, + editor_timeline::clip_timeline_offsets, + ui::CollapsibleState, +}; + +pub const ENVELOPE_STEP_SECS: f64 = cap_gpui_kernels::silence::WINDOW_FRAMES as f64 / 48_000.0; +const BLIP_WINDOWS: usize = 2; +const MIN_CUT_SECS: f64 = 0.05; +const EDGE_SNAP_SECS: f64 = 0.03; +const MUTED_TRACK_DB: f32 = -30.0; +const VOICE_REFERENCE_DB: f32 = -20.0; +const VOICE_PERCENTILE: f64 = 0.95; +const MAX_LEVEL_BOOST_DB: f32 = 30.0; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SilencePreset { + Conservative, + Balanced, + Aggressive, +} + +impl SilencePreset { + pub const ALL: [Self; 3] = [Self::Conservative, Self::Balanced, Self::Aggressive]; + + pub fn label(self) -> &'static str { + match self { + Self::Conservative => "Conservative", + Self::Balanced => "Balanced", + Self::Aggressive => "Aggressive", + } + } + + pub fn settings(self) -> SilenceSettings { + match self { + Self::Conservative => SilenceSettings { + threshold_db: -45., + min_silence_ms: 1000., + min_keep_ms: 200., + pad_start_ms: 100., + pad_end_ms: 150., + normalize: true, + }, + Self::Balanced => SilenceSettings { + threshold_db: -40., + min_silence_ms: 500., + min_keep_ms: 300., + pad_start_ms: 10., + pad_end_ms: 10., + normalize: true, + }, + Self::Aggressive => SilenceSettings { + threshold_db: -35., + min_silence_ms: 250., + min_keep_ms: 400., + pad_start_ms: 0., + pad_end_ms: 0., + normalize: true, + }, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SilenceSettings { + pub threshold_db: f32, + pub min_silence_ms: f32, + pub min_keep_ms: f32, + pub pad_start_ms: f32, + pub pad_end_ms: f32, + pub normalize: bool, +} + +impl Default for SilenceSettings { + fn default() -> Self { + SilencePreset::Balanced.settings() + } +} + +impl SilenceSettings { + pub fn preset(&self) -> Option { + SilencePreset::ALL + .into_iter() + .find(|preset| preset.settings().with_normalize(self.normalize) == *self) + } + + pub fn with_normalize(mut self, normalize: bool) -> Self { + self.normalize = normalize; + self + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SilenceParameter { + Threshold, + MinSilence, + MinKeep, + PadStart, + PadEnd, +} + +impl SilenceParameter { + pub const ALL: [Self; 5] = [ + Self::Threshold, + Self::MinSilence, + Self::MinKeep, + Self::PadStart, + Self::PadEnd, + ]; + + pub fn label(self) -> &'static str { + match self { + Self::Threshold => "Silence Threshold", + Self::MinSilence => "Min Duration", + Self::MinKeep => "Min Keep", + Self::PadStart => "Pad start", + Self::PadEnd => "Pad end", + } + } + + pub fn description(self) -> &'static str { + match self { + Self::Threshold => { + "Audio quieter than this counts as silence, measured after quiet recordings are boosted" + } + Self::MinSilence => "Only cut silences at least this long", + Self::MinKeep => { + "Sounds shorter than this between two silences (clicks, breaths) are cut with them" + } + Self::PadStart => "Silence left in after speech stops, so words don't end abruptly", + Self::PadEnd => "Silence left in before speech resumes, so words don't start abruptly", + } + } + + pub fn limits(self) -> (f32, f32, f32) { + match self { + Self::Threshold => (-70., -10., 1.), + Self::MinSilence => (100., 3000., 50.), + Self::MinKeep => (0., 1000., 10.), + Self::PadStart | Self::PadEnd => (0., 500., 10.), + } + } + + pub fn read(self, settings: &SilenceSettings) -> f32 { + match self { + Self::Threshold => settings.threshold_db, + Self::MinSilence => settings.min_silence_ms, + Self::MinKeep => settings.min_keep_ms, + Self::PadStart => settings.pad_start_ms, + Self::PadEnd => settings.pad_end_ms, + } + } + + pub fn write(self, settings: &mut SilenceSettings, value: f32) { + let (min, max, step) = self.limits(); + let value = ((value / step).round() * step).clamp(min, max); + match self { + Self::Threshold => settings.threshold_db = value, + Self::MinSilence => settings.min_silence_ms = value, + Self::MinKeep => settings.min_keep_ms = value, + Self::PadStart => settings.pad_start_ms = value, + Self::PadEnd => settings.pad_end_ms = value, + } + } + + pub fn value_label(self, value: f32) -> String { + match self { + Self::Threshold => format!("{}", value.round() as i32), + _ => format!("{}ms", value.round() as i32), + } + } + + pub fn unit(self) -> Option<&'static str> { + match self { + Self::Threshold => Some("DB"), + _ => None, + } + } +} + +#[derive(Debug, Clone, Default)] +pub struct ClipEnvelope { + pub mic: Option>>, + pub system: Option>>, + pub mic_repair_secs: f64, + pub system_repair_secs: f64, +} + +impl ClipEnvelope { + fn has_audio(&self) -> bool { + self.mic.as_ref().is_some_and(|levels| !levels.is_empty()) + || self + .system + .as_ref() + .is_some_and(|levels| !levels.is_empty()) + } +} + +pub fn loudness_db(blocks: &[&[f32]], channels: u16) -> Vec { + cap_gpui_kernels::silence::loudness_db(blocks.iter().copied(), channels) +} + +pub struct TrackLevels<'a> { + pub levels: &'a [f32], + pub offset_secs: f64, + pub gain_db: f32, +} + +/// Merges tracks into one envelope, never longer than the longest track. +/// Offsets come from the project file, so they are clamped: an out-of-range +/// offset only moves a track out of view, it can't grow the allocation. +pub fn combined_levels(tracks: &[TrackLevels]) -> Vec { + let max_len = tracks + .iter() + .map(|track| track.levels.len()) + .max() + .unwrap_or(0); + let bound = isize::try_from(max_len).unwrap_or(isize::MAX); + let shifts: Vec = tracks + .iter() + .map(|track| { + let shift = track.offset_secs / ENVELOPE_STEP_SECS; + if shift.is_finite() { + shift.round().clamp(-(bound as f64), bound as f64) as isize + } else { + 0 + } + }) + .collect(); + let len = tracks + .iter() + .zip(&shifts) + .map(|(track, shift)| (track.levels.len() as isize - shift).clamp(0, bound)) + .max() + .unwrap_or(0) as usize; + (0..len) + .map(|index| { + tracks + .iter() + .zip(&shifts) + .filter_map(|(track, shift)| { + let at = index as isize + shift; + usize::try_from(at) + .ok() + .and_then(|at| track.levels.get(at)) + .map(|level| level + track.gain_db) + }) + .fold(FLOOR_DB, f32::max) + }) + .collect() +} + +fn bridge_gaps(runs: Vec<(usize, usize)>, max_gap: usize) -> Vec<(usize, usize)> { + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for run in runs { + match merged.last_mut() { + Some(last) if run.0.saturating_sub(last.1) <= max_gap => last.1 = run.1, + _ => merged.push(run), + } + } + merged +} + +pub fn detect_silences(levels: &[f32], settings: &SilenceSettings) -> Vec<(f64, f64)> { + let windows = |ms: f32| (f64::from(ms) / 1000. / ENVELOPE_STEP_SECS).round() as usize; + let min_silence = windows(settings.min_silence_ms).max(1); + let min_keep = windows(settings.min_keep_ms); + let len = levels.len(); + + let mut runs = Vec::new(); + let mut open = None; + for (index, level) in levels.iter().enumerate() { + let silent = level.is_nan() || *level < settings.threshold_db; + match (silent, open) { + (true, None) => open = Some(index), + (false, Some(start)) => { + runs.push((start, index)); + open = None; + } + _ => {} + } + } + if let Some(start) = open { + runs.push((start, len)); + } + + let mut runs = bridge_gaps(runs, BLIP_WINDOWS); + runs.retain(|(start, end)| end - start >= min_silence); + let mut runs = if min_keep > 0 { + bridge_gaps(runs, min_keep - 1) + } else { + runs + }; + if let Some(first) = runs.first_mut() + && first.0 < min_keep + { + first.0 = 0; + } + if let Some(last) = runs.last_mut() + && len - last.1 < min_keep + { + last.1 = len; + } + + let pad_start = f64::from(settings.pad_start_ms) / 1000.; + let pad_end = f64::from(settings.pad_end_ms) / 1000.; + runs.into_iter() + .filter_map(|(start, end)| { + let mut from = start as f64 * ENVELOPE_STEP_SECS; + let mut to = end as f64 * ENVELOPE_STEP_SECS; + if start > 0 { + from += pad_start; + } + if end < len { + to -= pad_end; + } + (to - from >= MIN_CUT_SECS).then_some((from, to)) + }) + .collect() +} + +#[derive(Debug, Clone, PartialEq)] +struct DetectionInputs { + settings: SilenceSettings, + mic_volume_db: f32, + system_volume_db: f32, + offsets: Vec<(f32, f32)>, +} + +impl DetectionInputs { + fn new(project: &ProjectConfiguration, settings: SilenceSettings, clips: usize) -> Self { + Self { + settings, + mic_volume_db: project.audio.mic_volume_db, + system_volume_db: project.audio.system_volume_db, + offsets: (0..clips) + .map(|index| { + project + .clips + .iter() + .find(|clip| clip.index as usize == index) + .map_or((0., 0.), |clip| { + (clip.offsets.mic, clip.offsets.system_audio) + }) + }) + .collect(), + } + } +} + +pub fn level_boost_db<'a>(clips: impl IntoIterator) -> f32 { + let mut audible: Vec = clips + .into_iter() + .flatten() + .copied() + .filter(|level| level.is_finite() && *level > FLOOR_DB) + .collect(); + if audible.is_empty() { + return 0.; + } + let index = ((audible.len() - 1) as f64 * VOICE_PERCENTILE).round() as usize; + let (_, reference, _) = audible.select_nth_unstable_by(index, f32::total_cmp); + (VOICE_REFERENCE_DB - *reference).clamp(0., MAX_LEVEL_BOOST_DB) +} + +struct Detection { + ranges: Vec>, + boost_db: f32, +} + +fn detect_clips(envelopes: &[ClipEnvelope], inputs: &DetectionInputs) -> Detection { + let combined: Vec>> = envelopes + .iter() + .zip(&inputs.offsets) + .map(|(envelope, (mic_offset, system_offset))| { + let mut tracks = Vec::with_capacity(2); + if let Some(levels) = &envelope.mic + && inputs.mic_volume_db > MUTED_TRACK_DB + { + tracks.push(TrackLevels { + levels: levels.as_slice(), + offset_secs: f64::from(*mic_offset) + envelope.mic_repair_secs, + gain_db: inputs.mic_volume_db, + }); + } + if let Some(levels) = &envelope.system + && inputs.system_volume_db > MUTED_TRACK_DB + { + tracks.push(TrackLevels { + levels: levels.as_slice(), + offset_secs: f64::from(*system_offset) + envelope.system_repair_secs, + gain_db: inputs.system_volume_db, + }); + } + (!tracks.is_empty()).then(|| combined_levels(&tracks)) + }) + .collect(); + let boost_db = if inputs.settings.normalize { + level_boost_db(combined.iter().flatten().map(Vec::as_slice)) + } else { + 0. + }; + let ranges = combined + .into_iter() + .map(|levels| match levels { + Some(mut levels) => { + if boost_db > 0. { + for level in &mut levels { + *level += boost_db; + } + } + detect_silences(&levels, &inputs.settings) + } + None => Vec::new(), + }) + .collect(); + Detection { ranges, boost_db } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct SilenceKey { + pub recording_clip: u32, + pub index: usize, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct TimelineSilence { + pub key: SilenceKey, + pub segment_index: usize, + pub source_start: f64, + pub source_end: f64, + pub start: f64, + pub end: f64, +} + +impl TimelineSilence { + pub fn duration(&self) -> f64 { + (self.end - self.start).max(0.) + } +} + +pub fn timeline_silences( + timeline: &TimelineConfiguration, + detected: &[Vec<(f64, f64)>], +) -> Vec { + let offsets = clip_timeline_offsets(timeline); + let holds = timeline.hold_windows(); + let mut silences = Vec::new(); + for (index, segment) in timeline.segments.iter().enumerate() { + let Some(ranges) = detected.get(segment.recording_clip as usize) else { + continue; + }; + let timescale = segment.timescale; + if !timescale.is_finite() || timescale <= 0. { + continue; + } + let incoming = timeline + .effective_transition(index) + .map_or(0., |transition| transition.duration); + let outgoing = timeline + .effective_transition(index + 1) + .map_or(0., |transition| transition.duration); + let lower = segment.start + incoming * timescale; + let upper = segment.end - outgoing * timescale; + let clip_start = offsets.get(index).copied().unwrap_or(0.); + for (range_index, (range_start, range_end)) in ranges.iter().enumerate() { + if *range_start >= upper { + break; + } + if *range_end <= lower { + continue; + } + let mut start = range_start.max(lower); + let mut end = range_end.min(upper); + if incoming <= 0. && (start - segment.start) / timescale < EDGE_SNAP_SECS { + start = segment.start; + } + if outgoing <= 0. && (segment.end - end) / timescale < EDGE_SNAP_SECS { + end = segment.end; + } + if (end - start) / timescale < MIN_CUT_SECS { + continue; + } + let effective_start = clip_start + (start - segment.start) / timescale; + let effective_end = clip_start + (end - segment.start) / timescale; + silences.push(TimelineSilence { + key: SilenceKey { + recording_clip: segment.recording_clip, + index: range_index, + }, + segment_index: index, + source_start: start, + source_end: end, + start: effective_to_output_end(&holds, effective_start), + end: effective_to_output_end(&holds, effective_end), + }); + } + } + silences.sort_by(|a, b| a.start.total_cmp(&b.start)); + silences +} + +pub fn cut_silences<'a>( + timeline: &mut TimelineConfiguration, + silences: impl IntoIterator, +) -> usize { + let mut ordered: Vec<&TimelineSilence> = silences.into_iter().collect(); + ordered.sort_by(|a, b| { + b.segment_index + .cmp(&a.segment_index) + .then(b.source_start.total_cmp(&a.source_start)) + }); + ordered + .into_iter() + .filter(|silence| { + cut_clip_source_range( + timeline, + silence.segment_index, + silence.source_start, + silence.source_end, + ) + }) + .count() +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CleanUpSummary { + pub count: usize, + pub kept: usize, + pub saved: f64, + pub before: f64, +} + +impl CleanUpSummary { + pub fn after(&self) -> f64 { + (self.before - self.saved).max(0.) + } + + pub fn fraction(&self) -> f64 { + if self.before > 0. { + (self.saved / self.before).clamp(0., 1.) + } else { + 0. + } + } +} + +pub fn format_duration(seconds: f64) -> String { + let tenths = (seconds.max(0.) * 10.).round() as u64; + let hours = tenths / 36_000; + let minutes = tenths / 600 % 60; + let secs = (tenths % 600) as f64 / 10.; + if hours > 0 { + format!("{hours}h {minutes}m {secs:.1}s") + } else if minutes > 0 { + format!("{minutes}m {secs:.1}s") + } else { + format!("{secs:.1}s") + } +} + +pub struct CleanUpState { + pub settings: SilenceSettings, + pub advanced_open: CollapsibleState, + pub envelopes: Option>>, + detected_for: Option, + detected: Vec>, + pub level_boost_db: f32, + pub silences: Vec, + pub kept: HashSet, + pub focused: Option, + pub reviewing: bool, + pub message: Option, +} + +impl Default for CleanUpState { + fn default() -> Self { + Self { + settings: SilenceSettings::default(), + advanced_open: CollapsibleState::new(true), + envelopes: None, + detected_for: None, + detected: Vec::new(), + level_boost_db: 0., + silences: Vec::new(), + kept: HashSet::new(), + focused: None, + reviewing: false, + message: None, + } + } +} + +impl CleanUpState { + pub fn loaded(&self) -> bool { + self.envelopes.is_some() + } + + pub fn has_audio(&self) -> bool { + self.envelopes + .as_ref() + .is_some_and(|envelopes| envelopes.iter().any(ClipEnvelope::has_audio)) + } + + pub fn set_envelopes(&mut self, envelopes: Vec) { + self.envelopes = Some(Arc::new(envelopes)); + self.detected_for = None; + } + + pub fn set_settings(&mut self, settings: SilenceSettings) -> bool { + if self.settings == settings { + return false; + } + self.settings = settings; + self.message = None; + true + } + + pub fn refresh(&mut self, project: &ProjectConfiguration) { + let Some(envelopes) = self.envelopes.clone() else { + self.silences.clear(); + return; + }; + let inputs = DetectionInputs::new(project, self.settings, envelopes.len()); + if self.detected_for.as_ref() != Some(&inputs) { + let detection = detect_clips(&envelopes, &inputs); + self.detected = detection.ranges; + self.level_boost_db = detection.boost_db; + self.detected_for = Some(inputs); + self.kept.clear(); + self.focused = None; + } + self.silences = project + .timeline + .as_ref() + .map(|timeline| timeline_silences(timeline, &self.detected)) + .unwrap_or_default(); + let live: HashSet = self.silences.iter().map(|silence| silence.key).collect(); + self.kept.retain(|key| live.contains(key)); + if self.focused.is_some_and(|key| !live.contains(&key)) { + self.focused = None; + } + if self.silences.is_empty() { + self.reviewing = false; + } + } + + pub fn is_kept(&self, silence: &TimelineSilence) -> bool { + self.kept.contains(&silence.key) + } + + pub fn pending(&self) -> impl Iterator { + self.silences + .iter() + .filter(|silence| !self.kept.contains(&silence.key)) + } + + pub fn summary(&self, before: f64) -> CleanUpSummary { + CleanUpSummary { + count: self.pending().count(), + kept: self.silences.len() - self.pending().count(), + saved: self.pending().map(TimelineSilence::duration).sum(), + before, + } + } + + pub fn focused_position(&self) -> Option { + let key = self.focused?; + self.silences.iter().position(|silence| silence.key == key) + } + + pub fn focused_silence(&self) -> Option<&TimelineSilence> { + self.silences.get(self.focused_position()?) + } + + pub fn focus_at_or_after(&mut self, time: f64) -> Option { + let silence = self + .silences + .iter() + .find(|silence| silence.end > time + 1e-6) + .or_else(|| self.silences.last()) + .copied()?; + self.focused = Some(silence.key); + Some(silence) + } + + pub fn step_focus(&mut self, forward: bool) -> Option { + if self.silences.is_empty() { + return None; + } + let last = self.silences.len() - 1; + let next = match self.focused_position() { + Some(position) if forward => (position + 1).min(last), + Some(position) => position.saturating_sub(1), + None if forward => 0, + None => last, + }; + let silence = self.silences[next]; + self.focused = Some(silence.key); + Some(silence) + } + + pub fn silence_at(&self, time: f64) -> Option { + self.silences + .iter() + .find(|silence| time >= silence.start && time < silence.end) + .copied() + } + + pub fn skip_target(&self, time: f64, lead: f64) -> Option { + let pending: Vec<&TimelineSilence> = self.pending().collect(); + let mut end = pending + .iter() + .find(|silence| time >= silence.start - lead && time < silence.end - lead)? + .end; + while let Some(next) = pending + .iter() + .find(|silence| silence.start <= end + lead && silence.end > end) + { + end = next.end; + } + Some(end) + } + + pub fn toggle_kept(&mut self, key: SilenceKey) { + if !self.kept.remove(&key) { + self.kept.insert(key); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn timeline(json: serde_json::Value) -> TimelineConfiguration { + let project: ProjectConfiguration = + serde_json::from_value(serde_json::json!({ "timeline": json })).expect("fixture"); + project.timeline.expect("timeline") + } + + fn levels(spec: &[(f64, f32)]) -> Vec { + spec.iter() + .flat_map(|(seconds, level)| { + std::iter::repeat_n(*level, (seconds / ENVELOPE_STEP_SECS).round() as usize) + }) + .collect() + } + + fn settings(min_silence_ms: f32, min_keep_ms: f32, pad: f32) -> SilenceSettings { + SilenceSettings { + threshold_db: -40., + min_silence_ms, + min_keep_ms, + pad_start_ms: pad, + pad_end_ms: pad, + normalize: false, + } + } + + fn approx(actual: &[(f64, f64)], expected: &[(f64, f64)]) { + assert_eq!(actual.len(), expected.len(), "{actual:?}"); + for ((a0, a1), (e0, e1)) in actual.iter().zip(expected) { + assert!( + (a0 - e0).abs() < 1e-6 && (a1 - e1).abs() < 1e-6, + "{actual:?} != {expected:?}" + ); + } + } + + #[test] + fn the_balanced_preset_matches_its_settings() { + assert_eq!( + SilenceSettings::default().preset(), + Some(SilencePreset::Balanced) + ); + let mut custom = SilenceSettings::default(); + SilenceParameter::PadEnd.write(&mut custom, 20.); + assert_eq!(custom.preset(), None); + } + + #[test] + fn parameter_writes_snap_and_clamp() { + let mut settings = SilenceSettings::default(); + SilenceParameter::MinSilence.write(&mut settings, 512.); + assert_eq!(settings.min_silence_ms, 500.); + SilenceParameter::Threshold.write(&mut settings, -200.); + assert_eq!(settings.threshold_db, -70.); + } + + #[test] + fn a_long_pause_is_detected_with_padding() { + let levels = levels(&[(1.0, -20.), (2.0, -60.), (1.0, -20.)]); + approx( + &detect_silences(&levels, &settings(500., 0., 100.)), + &[(1.1, 2.9)], + ); + } + + #[test] + fn pauses_shorter_than_the_minimum_are_left_alone() { + let levels = levels(&[(1.0, -20.), (0.4, -60.), (1.0, -20.)]); + assert!(detect_silences(&levels, &settings(500., 0., 0.)).is_empty()); + } + + #[test] + fn edges_are_not_padded() { + let levels = levels(&[(1.0, -60.), (1.0, -20.), (1.0, -60.)]); + approx( + &detect_silences(&levels, &settings(500., 0., 100.)), + &[(0.0, 0.9), (2.1, 3.0)], + ); + } + + #[test] + fn a_short_click_inside_a_pause_does_not_split_it() { + let levels = levels(&[ + (1.0, -20.), + (1.0, -60.), + (0.02, -10.), + (1.0, -60.), + (1.0, -20.), + ]); + approx( + &detect_silences(&levels, &settings(500., 0., 0.)), + &[(1.0, 3.02)], + ); + } + + #[test] + fn a_short_sound_between_two_pauses_is_cut_with_them() { + let levels = levels(&[ + (1.0, -20.), + (1.0, -60.), + (0.2, -20.), + (1.0, -60.), + (1.0, -20.), + ]); + approx( + &detect_silences(&levels, &settings(500., 300., 0.)), + &[(1.0, 3.2)], + ); + approx( + &detect_silences(&levels, &settings(500., 100., 0.)), + &[(1.0, 2.0), (2.2, 3.2)], + ); + } + + #[test] + fn syllable_gaps_never_add_up_to_a_cut() { + let mut spec = Vec::new(); + for _ in 0..20 { + spec.push((0.15, -20.)); + spec.push((0.03, -60.)); + } + let levels = levels(&spec); + assert!(detect_silences(&levels, &SilenceSettings::default()).is_empty()); + } + + #[test] + fn tracks_combine_by_their_loudest_level_after_offset_and_gain() { + let mic = levels(&[(1.0, -60.), (1.0, -20.)]); + let system = levels(&[(2.0, -90.)]); + let combined = combined_levels(&[ + TrackLevels { + levels: &mic, + offset_secs: 0.5, + gain_db: -6., + }, + TrackLevels { + levels: &system, + offset_secs: 0., + gain_db: 0., + }, + ]); + assert_eq!(combined.len(), 200); + assert_eq!(combined[0], -66.); + assert_eq!(combined[49], -66.); + assert_eq!(combined[50], -26.); + assert_eq!(combined[150], -90.); + } + + #[test] + fn extreme_offsets_never_grow_the_envelope_past_the_longest_track() { + let mic = levels(&[(1.0, -20.)]); + for offset_secs in [-1.0e12, 1.0e12, f64::MIN, f64::MAX, f64::NAN, f64::INFINITY] { + let combined = combined_levels(&[TrackLevels { + levels: &mic, + offset_secs, + gain_db: 0., + }]); + assert!(combined.len() <= mic.len(), "offset {offset_secs}"); + } + } + + #[test] + fn silences_map_through_trims_and_speed_changes() { + let timeline = timeline(serde_json::json!({ + "segments": [ + { "recordingSegment": 0, "timescale": 1.0, "start": 1.0, "end": 10.0 }, + { "recordingSegment": 0, "timescale": 2.0, "start": 12.0, "end": 20.0 } + ], + "zoomSegments": [] + })); + let detected = vec![vec![(0.0, 2.0), (4.0, 5.0), (9.5, 13.0), (16.0, 18.0)]]; + let silences = timeline_silences(&timeline, &detected); + let spans: Vec<(usize, f64, f64, f64, f64)> = silences + .iter() + .map(|s| { + ( + s.segment_index, + s.source_start, + s.source_end, + s.start, + s.end, + ) + }) + .collect(); + assert_eq!( + spans, + vec![ + (0, 1.0, 2.0, 0.0, 1.0), + (0, 4.0, 5.0, 3.0, 4.0), + (0, 9.5, 10.0, 8.5, 9.0), + (1, 12.0, 13.0, 9.0, 9.5), + (1, 16.0, 18.0, 11.0, 12.0), + ] + ); + assert_eq!(silences[2].key, silences[3].key); + } + + #[test] + fn silences_stay_out_of_transitions() { + let mut timeline = timeline(serde_json::json!({ + "segments": [ + { "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 10.0 }, + { "recordingSegment": 1, "timescale": 1.0, "start": 0.0, "end": 10.0 } + ], + "zoomSegments": [] + })); + timeline.transitions = vec![cap_project::ClipTransition { + segment_index: 1, + kind: cap_project::ClipTransitionType::CrossFade, + duration: 1.0, + }]; + let detected = vec![vec![(8.0, 10.0)], vec![(0.0, 2.0)]]; + let silences = timeline_silences(&timeline, &detected); + let spans: Vec<(f64, f64)> = silences + .iter() + .map(|s| (s.source_start, s.source_end)) + .collect(); + assert_eq!(spans, vec![(8.0, 9.0), (1.0, 2.0)]); + } + + #[test] + fn cutting_splits_clips_and_ripples_the_other_tracks() { + let mut timeline = timeline(serde_json::json!({ + "segments": [ + { "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 10.0 } + ], + "zoomSegments": [ + { "start": 1.0, "end": 3.5, "amount": 1.5, "mode": "auto" }, + { "start": 6.0, "end": 8.0, "amount": 2.0, "mode": "auto" } + ] + })); + let detected = vec![vec![(0.0, 1.0), (3.0, 4.0), (6.5, 7.0), (9.0, 10.0)]]; + let silences = timeline_silences(&timeline, &detected); + assert_eq!(cut_silences(&mut timeline, &silences), 4); + + let clips: Vec<(f64, f64)> = timeline + .segments + .iter() + .map(|segment| (segment.start, segment.end)) + .collect(); + assert_eq!(clips, vec![(1.0, 3.0), (4.0, 6.5), (7.0, 9.0)]); + assert!((timeline.duration() - 6.5).abs() < 1e-9); + + let zooms: Vec<(f64, f64)> = timeline + .zoom_segments + .iter() + .map(|zoom| (zoom.start, zoom.end)) + .collect(); + assert_eq!(zooms, vec![(0.0, 2.0), (4.0, 5.5)]); + } + + #[test] + fn a_fully_silent_clip_is_removed_but_never_the_last_one() { + let mut timeline = timeline(serde_json::json!({ + "segments": [ + { "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 4.0 }, + { "recordingSegment": 1, "timescale": 1.0, "start": 0.0, "end": 4.0 } + ], + "zoomSegments": [] + })); + let detected = vec![vec![(0.0, 4.0)], vec![(0.0, 4.0)]]; + let silences = timeline_silences(&timeline, &detected); + assert_eq!(silences.len(), 2); + assert_eq!(cut_silences(&mut timeline, &silences), 1); + assert_eq!(timeline.segments.len(), 1); + } + + #[test] + fn the_summary_counts_only_pending_silences() { + let mut state = CleanUpState { + silences: vec![ + TimelineSilence { + key: SilenceKey { + recording_clip: 0, + index: 0, + }, + segment_index: 0, + source_start: 1., + source_end: 3., + start: 1., + end: 3., + }, + TimelineSilence { + key: SilenceKey { + recording_clip: 0, + index: 1, + }, + segment_index: 0, + source_start: 5., + source_end: 6., + start: 5., + end: 6., + }, + ], + ..CleanUpState::default() + }; + state.toggle_kept(state.silences[0].key); + let summary = state.summary(10.); + assert_eq!((summary.count, summary.kept), (1, 1)); + assert!((summary.saved - 1.).abs() < 1e-9); + assert!((summary.after() - 9.).abs() < 1e-9); + assert!((summary.fraction() - 0.1).abs() < 1e-9); + + assert_eq!(state.step_focus(true).map(|s| s.start), Some(1.)); + assert_eq!(state.step_focus(true).map(|s| s.start), Some(5.)); + assert_eq!(state.step_focus(true).map(|s| s.start), Some(5.)); + assert_eq!(state.step_focus(false).map(|s| s.start), Some(1.)); + } + + fn silence(index: usize, start: f64, end: f64) -> TimelineSilence { + TimelineSilence { + key: SilenceKey { + recording_clip: 0, + index, + }, + segment_index: 0, + source_start: start, + source_end: end, + start, + end, + } + } + + #[test] + fn playback_skips_pending_silences_and_their_neighbours() { + let mut state = CleanUpState { + silences: vec![silence(0, 1., 2.), silence(1, 2.01, 3.), silence(2, 5., 6.)], + ..CleanUpState::default() + }; + let lead = 1. / 60.; + assert_eq!(state.skip_target(0.5, lead), None); + assert_eq!(state.skip_target(0.99, lead), Some(3.)); + assert_eq!(state.skip_target(1.5, lead), Some(3.)); + assert_eq!(state.skip_target(3., lead), None); + state.toggle_kept(state.silences[2].key); + assert_eq!(state.skip_target(5.5, lead), None); + state.toggle_kept(state.silences[1].key); + assert_eq!(state.skip_target(1.5, lead), Some(2.)); + assert_eq!(state.silence_at(2.5).map(|s| s.key.index), Some(1)); + assert_eq!(state.silence_at(4.), None); + } + + #[test] + fn quiet_recordings_are_boosted_towards_a_voice_reference() { + let quiet = levels(&[(3.0, -45.), (1.0, -70.)]); + assert!((level_boost_db([quiet.as_slice()]) - 25.).abs() < 1e-4); + let loud = levels(&[(3.0, -12.), (1.0, -60.)]); + assert_eq!(level_boost_db([loud.as_slice()]), 0.); + let silent = vec![FLOOR_DB; 100]; + assert_eq!(level_boost_db([silent.as_slice()]), 0.); + let whisper = levels(&[(3.0, -80.)]); + assert_eq!(level_boost_db([whisper.as_slice()]), MAX_LEVEL_BOOST_DB); + } + + #[test] + fn boosting_finds_speech_the_default_threshold_misses() { + let envelope = ClipEnvelope { + mic: Some(Arc::new(levels(&[(1.0, -45.), (1.0, -70.), (1.0, -45.)]))), + ..ClipEnvelope::default() + }; + let inputs = |normalize: bool| DetectionInputs { + settings: SilenceSettings::default().with_normalize(normalize), + mic_volume_db: 0., + system_volume_db: 0., + offsets: vec![(0., 0.)], + }; + let flat = detect_clips(std::slice::from_ref(&envelope), &inputs(false)); + assert_eq!(flat.ranges[0].len(), 1); + assert!(flat.ranges[0][0].1 - flat.ranges[0][0].0 > 2.5); + let boosted = detect_clips(std::slice::from_ref(&envelope), &inputs(true)); + assert!((boosted.boost_db - 25.).abs() < 1e-4); + approx(&boosted.ranges[0], &[(1.01, 1.99)]); + } + + #[test] + fn durations_format_like_the_summary_card() { + assert_eq!(format_duration(150.8), "2m 30.8s"); + assert_eq!(format_duration(937.6), "15m 37.6s"); + assert_eq!(format_duration(4.25), "4.3s"); + assert_eq!(format_duration(3_725.), "1h 2m 5.0s"); + } +} diff --git a/apps/desktop-gpui/src/editor_clean_up.rs b/apps/desktop-gpui/src/editor_clean_up.rs new file mode 100644 index 00000000000..8309ebcd2d4 --- /dev/null +++ b/apps/desktop-gpui/src/editor_clean_up.rs @@ -0,0 +1,845 @@ +use gpui::{ + AnyElement, Context, FontWeight, Hsla, InteractiveElement, IntoElement, MouseButton, + ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div, + prelude::FluentBuilder, px, relative, svg, +}; + +use crate::{ + clean_up::{ + CleanUpSummary, SilenceParameter, SilencePreset, SilenceSettings, TimelineSilence, + cut_silences, format_duration, + }, + editor_sidebar::{SliderKey, collapsible, disclosure_row, section_action}, + editor_timeline::TrackKind, + editor_window::EditorWindow, + theme::Theme, + ui, +}; + +const SILENCE_RED: u32 = 0xef4444; + +impl EditorWindow { + pub(crate) fn render_clean_up_tab(&self, cx: &mut Context) -> AnyElement { + let theme = self.theme; + let state = &self.clean_up; + let summary = state.summary(self.total_duration()); + let current_preset = state.settings.preset(); + let open = state.advanced_open.is_open(); + let ready = self.project_ready() && state.has_audio(); + + let status = if !state.loaded() { + self.render_clean_up_notice("Analyzing audio…") + } else if !state.has_audio() { + self.render_clean_up_notice("This recording has no audio to analyze.") + } else { + self.render_clean_up_summary(summary) + }; + + let count_line = match (summary.count, summary.kept) { + (0, 0) => "No silences match these settings".to_string(), + (count, 0) => format!("{count} {} to cut", plural(count, "silence", "silences")), + (count, kept) => format!( + "{count} {} to cut · {kept} kept", + plural(count, "silence", "silences") + ), + }; + + let presets = ui::SegmentedControl::editor( + &theme, + "clean-up-presets", + SilencePreset::ALL + .iter() + .map(|preset| { + ui::SegmentOption::new(preset.label(), current_preset == Some(*preset)) + }) + .collect(), + ) + .stretch() + .on_select(cx.listener(|this, index: &usize, window, cx| { + if let Some(preset) = SilencePreset::ALL.get(*index) { + let normalize = this.clean_up.settings.normalize; + this.apply_clean_up_settings( + preset.settings().with_normalize(normalize), + window, + cx, + ); + } + })); + + let advanced = div() + .flex() + .flex_col() + .gap(px(14.)) + .pt(px(6.)) + .child(self.render_clean_up_normalize(cx)) + .children( + SilenceParameter::ALL + .into_iter() + .map(|parameter| self.render_clean_up_parameter(parameter, cx)), + ) + .into_any_element(); + + let cut_label = match summary.count { + 0 => "No silences to cut".to_string(), + count => format!("Cut {count} {}", plural(count, "silence", "silences")), + }; + + let actions = div() + .flex() + .flex_col() + .gap(px(8.)) + .child( + ui::Button::plain( + &theme, + "clean-up-cut", + ui::ButtonVariant::Primary, + ui::ButtonSize::Md, + ) + .icon("icons/scissors.svg") + .label(cut_label) + .full_width() + .disabled(!ready || summary.count == 0) + .on_click(cx.listener(|this, _, window, cx| { + this.cut_all_silences(window, cx); + })), + ) + .child( + ui::Button::plain( + &theme, + "clean-up-review", + ui::ButtonVariant::Gray, + ui::ButtonSize::Md, + ) + .label(if state.reviewing { + "Stop reviewing" + } else { + "Review silences" + }) + .full_width() + .disabled(!ready || state.silences.is_empty()) + .on_click(cx.listener(|this, _, window, cx| { + if this.clean_up.reviewing { + this.stop_silence_review(window, cx); + } else { + this.start_silence_review(window, cx); + } + })), + ); + + ui::Field::section(&theme, "Silence") + .icon("icons/scissors.svg") + .child( + div() + .flex() + .flex_col() + .gap(px(14.)) + .child(status) + .when(ready, |this| { + this.child( + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap(px(8.)) + .child( + div() + .text_size(px(12.)) + .text_color(Hsla::from(theme.editor.text_2)) + .child(count_line), + ) + .when(summary.kept > 0, |this| { + this.child(section_action( + &theme, + "clean-up-restore-kept", + "Cut kept too", + None, + false, + cx.listener(|this, _, window, cx| { + this.clean_up.kept.clear(); + this.refresh_clean_up(window, cx); + }), + )) + }), + ) + }) + .child(presets) + .child(disclosure_row( + &theme, + "clean-up-advanced", + "Advanced", + open, + cx.listener(|this, _, window, cx| { + this.clean_up.advanced_open.toggle(); + this.animate_collapsibles(window, cx); + }), + )) + .child(collapsible(&self.clean_up.advanced_open, advanced)) + .child(actions) + .children(self.clean_up.message.as_ref().map(|message| { + div() + .text_size(px(12.)) + .text_color(Hsla::from(theme.editor.text_2)) + .child(message.clone()) + })) + .child( + div() + .text_size(px(11.5)) + .line_height(px(16.)) + .text_color(Hsla::from(theme.editor.text_3)) + .child( + "Silences are cut from the timeline in one step, so undo brings \ + them back. Captions and exports follow the edited timeline.", + ), + ), + ) + .into_any_element() + } + + fn render_clean_up_notice(&self, message: &'static str) -> AnyElement { + let theme = self.theme; + div() + .p(px(14.)) + .rounded(px(10.)) + .bg(Hsla::from(theme.editor.card_2)) + .border_1() + .border_color(Hsla::from(theme.editor.line)) + .text_size(px(12.)) + .text_color(Hsla::from(theme.editor.text_2)) + .child(message) + .into_any_element() + } + + fn render_clean_up_summary(&self, summary: CleanUpSummary) -> AnyElement { + let theme = self.theme; + let (saved, before, after, fraction) = ( + summary.saved, + summary.before, + summary.after(), + summary.fraction(), + ); + let muted = Hsla::from(theme.editor.text_3); + div() + .flex() + .flex_col() + .gap(px(10.)) + .p(px(14.)) + .rounded(px(10.)) + .bg(Hsla::from(theme.editor.card_2)) + .border_1() + .border_color(Hsla::from(theme.editor.line)) + .child( + div() + .flex() + .flex_row() + .items_end() + .gap(px(8.)) + .child( + div() + .pb(px(3.)) + .text_size(px(10.5)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(muted) + .child("SAVED"), + ) + .child( + div() + .text_size(px(20.)) + .line_height(px(24.)) + .font_weight(FontWeight::BOLD) + .text_color(Hsla::from(theme.editor.text_1)) + .child(format_duration(saved)), + ) + .child(div().flex_1()) + .child( + div() + .pb(px(2.)) + .text_size(px(14.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(Hsla::from(theme.editor.accent)) + .child(format!("{}%", (fraction * 100.).round() as i32)), + ), + ) + .child( + div() + .w_full() + .h(px(6.)) + .rounded_full() + .overflow_hidden() + .bg(Hsla::from(theme.editor.ctl_active)) + .child( + div() + .h_full() + .rounded_full() + .bg(Hsla::from(theme.editor.accent)) + .w(relative(fraction as f32)), + ), + ) + .child( + div() + .flex() + .flex_row() + .justify_between() + .gap(px(8.)) + .text_size(px(11.5)) + .text_color(muted) + .child(format!("From {}", format_duration(before))) + .child(format!( + "→ {} ({} cut)", + format_duration(after), + format_duration(saved) + )), + ) + .into_any_element() + } + + fn render_clean_up_normalize(&self, cx: &mut Context) -> AnyElement { + let theme = self.theme; + let settings = self.clean_up.settings; + let boost = self.clean_up.level_boost_db; + let detail = if !settings.normalize { + "Levels are measured as recorded".to_string() + } else if boost >= 0.5 { + format!( + "Quiet recording, boosted +{} dB for detection", + boost.round() as i32 + ) + } else { + "Recording is loud enough, no boost needed".to_string() + }; + div() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(6.)) + .child( + div() + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.editor.text_1)) + .child("Boost quiet audio"), + ) + .child( + div() + .id("clean-up-info-normalize") + .flex() + .items_center() + .child( + svg() + .path("icons/info.svg") + .size(px(12.)) + .text_color(Hsla::from(theme.editor.text_3)), + ) + .tooltip(move |_window, cx| { + ui::Tooltip::new( + &theme, + "Lifts a quiet voice to a normal level before looking for \ + silence, so the threshold works on soft or distant mics. \ + Detection only: playback and export are unchanged.", + ) + .view(cx) + }), + ) + .child(div().flex_1()) + .child( + ui::Toggle::plain(&theme, "clean-up-normalize", settings.normalize) + .on_click(cx.listener(move |this, _, window, cx| { + let next = this + .clean_up + .settings + .with_normalize(!this.clean_up.settings.normalize); + this.apply_clean_up_settings(next, window, cx); + })), + ), + ) + .child( + div() + .text_size(px(11.5)) + .text_color(Hsla::from(theme.editor.text_3)) + .child(detail), + ) + .into_any_element() + } + + fn render_clean_up_parameter( + &self, + parameter: SilenceParameter, + cx: &mut Context, + ) -> AnyElement { + let theme = self.theme; + let value = parameter.read(&self.clean_up.settings); + let (min, max, _) = parameter.limits(); + let description = parameter.description(); + + let step_button = |direction: f32, icon: &'static str, enabled: bool| { + div() + .id(SharedString::from(format!( + "clean-up-step-{parameter:?}-{direction}" + ))) + .size(px(24.)) + .flex() + .flex_none() + .items_center() + .justify_center() + .rounded(px(6.)) + .border_1() + .border_color(Hsla::from(theme.editor.line)) + .bg(Hsla::from(theme.editor.ctl)) + .child( + svg() + .path(icon) + .size(px(12.)) + .text_color(Hsla::from(theme.editor.text_2)), + ) + .when(!enabled, |this| this.opacity(0.4)) + .when(enabled, |this| { + this.cursor_pointer() + .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover))) + .on_click(cx.listener(move |this, _, window, cx| { + this.step_clean_up_parameter(parameter, direction, window, cx); + })) + }) + }; + + let stepper = div() + .flex() + .flex_row() + .items_center() + .gap(px(4.)) + .child(step_button(-1., "icons/minus.svg", value > min)) + .child( + div() + .min_w(px(64.)) + .h(px(24.)) + .px(px(8.)) + .flex() + .flex_row() + .items_center() + .justify_center() + .gap(px(4.)) + .rounded(px(6.)) + .border_1() + .border_color(Hsla::from(theme.editor.line)) + .bg(Hsla::from(theme.editor.ctl)) + .text_size(px(11.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.editor.accent)) + .child(parameter.value_label(value)) + .children(parameter.unit().map(|unit| { + div() + .text_size(px(9.5)) + .text_color(Hsla::from(theme.editor.text_3)) + .child(unit) + })), + ) + .child(step_button(1., "icons/plus.svg", value < max)); + + div() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(6.)) + .child( + div() + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.editor.text_1)) + .child(parameter.label()), + ) + .child( + div() + .id(SharedString::from(format!("clean-up-info-{parameter:?}"))) + .flex() + .items_center() + .child( + svg() + .path("icons/info.svg") + .size(px(12.)) + .text_color(Hsla::from(theme.editor.text_3)), + ) + .tooltip(move |_window, cx| { + ui::Tooltip::new(&theme, description).view(cx) + }), + ) + .child(div().flex_1()) + .child(stepper), + ) + .child(self.slider(SliderKey::CleanUp(parameter), "int", cx)) + .into_any_element() + } + + pub(crate) fn render_silence_review_pill(&self, cx: &mut Context) -> Option { + if !self.clean_up.reviewing || !self.project_ready() { + return None; + } + let theme = self.theme; + let state = &self.clean_up; + let focused = state.focused_silence().copied(); + let position = state.focused_position(); + let total = state.silences.len(); + let kept = focused.is_some_and(|silence| state.is_kept(&silence)); + let red = Hsla::from(gpui::rgb(SILENCE_RED)); + let idle = Hsla::from(theme.editor.text_2); + let separator = || div().w(px(1.)).h(px(16.)).bg(Hsla::from(theme.editor.line)); + + let detail = match focused { + Some(silence) => format!("{:.3}s · {:.2}s", silence.start, silence.duration()), + None => format!("{total} {}", plural(total, "silence", "silences")), + }; + + let pill = div() + .id("silence-review-pill") + .flex() + .flex_row() + .items_center() + .gap(px(8.)) + .h(px(32.)) + .pl(px(12.)) + .pr(px(6.)) + .rounded_full() + .border_1() + .border_color(Hsla::from(theme.editor.line)) + .bg(Hsla::from(theme.editor.card)) + .shadow(theme.editor.pop_shadow()) + .on_mouse_down( + MouseButton::Left, + cx.listener(|_, _, _, cx| cx.stop_propagation()), + ) + .child(div().size(px(7.)).rounded_full().bg(red)) + .child( + div() + .text_size(px(12.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(Hsla::from(theme.editor.text_1)) + .child("Silence"), + ) + .child( + div() + .text_size(px(11.5)) + .text_color(Hsla::from(theme.editor.text_2)) + .child(detail), + ) + .children(position.map(|position| { + div() + .text_size(px(11.)) + .text_color(Hsla::from(theme.editor.text_3)) + .child(format!("{}/{total}", position + 1)) + })) + .child( + pill_button( + &theme, + "silence-previous", + "icons/chevron-left.svg", + idle, + "Previous silence", + ) + .on_click(cx.listener(|this, _, window, cx| { + this.step_silence(false, window, cx); + })), + ) + .child( + pill_button( + &theme, + "silence-next", + "icons/chevron-right.svg", + idle, + "Next silence", + ) + .on_click(cx.listener(|this, _, window, cx| { + this.step_silence(true, window, cx); + })), + ) + .child(separator()) + .when_some(focused, |this, silence| { + this.child( + pill_text_button( + &theme, + "silence-keep", + "icons/audio-on.svg", + if kept { "Kept" } else { "Keep" }, + if kept { + Hsla::from(theme.editor.accent) + } else { + idle + }, + if kept { + "Kept in the video. Click to cut it with the rest" + } else { + "Keep this silence in the video (double-click a mark to toggle)" + }, + ) + .when(kept, |this| this.bg(Hsla::from(theme.editor.ctl_active))) + .on_click(cx.listener(move |this, _, window, cx| { + this.clean_up.toggle_kept(silence.key); + this.refresh_clean_up(window, cx); + })), + ) + .child( + pill_text_button( + &theme, + "silence-cut", + "icons/scissors.svg", + "Cut now", + red, + "Cut this silence from the timeline", + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.cut_focused_silence(window, cx); + })), + ) + .child(separator()) + }) + .child( + div() + .id("silence-review-close") + .h(px(22.)) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(6.)) + .border_1() + .border_color(Hsla::from(theme.editor.line)) + .text_size(px(11.)) + .text_color(Hsla::from(theme.editor.text_2)) + .cursor_pointer() + .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover))) + .child("Esc") + .tooltip(move |_window, cx| ui::Tooltip::new(&theme, "Stop reviewing").view(cx)) + .on_click(cx.listener(|this, _, window, cx| { + this.stop_silence_review(window, cx); + })), + ); + + Some( + div() + .absolute() + .top(px(4.)) + .left_0() + .right_0() + .flex() + .flex_row() + .justify_center() + .child(pill) + .into_any_element(), + ) + } + + pub(crate) fn set_clean_up_parameter( + &mut self, + parameter: SilenceParameter, + value: f32, + window: &mut Window, + cx: &mut Context, + ) { + let mut settings = self.clean_up.settings; + parameter.write(&mut settings, value); + self.apply_clean_up_settings(settings, window, cx); + } + + fn step_clean_up_parameter( + &mut self, + parameter: SilenceParameter, + direction: f32, + window: &mut Window, + cx: &mut Context, + ) { + let (_, _, step) = parameter.limits(); + let value = parameter.read(&self.clean_up.settings) + direction * step; + self.set_clean_up_parameter(parameter, value, window, cx); + } + + fn apply_clean_up_settings( + &mut self, + settings: SilenceSettings, + window: &mut Window, + cx: &mut Context, + ) { + if self.clean_up.set_settings(settings) { + self.refresh_clean_up(window, cx); + } + } + + fn refresh_clean_up(&mut self, window: &mut Window, cx: &mut Context) { + self.sync_silence_marks(); + cx.notify(); + window.refresh(); + } + + fn cut_all_silences(&mut self, window: &mut Window, cx: &mut Context) { + let pending: Vec = self.clean_up.pending().copied().collect(); + self.apply_silence_cuts(&pending, window, cx); + } + + fn cut_focused_silence(&mut self, window: &mut Window, cx: &mut Context) { + let Some(focused) = self.clean_up.focused_silence().copied() else { + return; + }; + let targets: Vec = self + .clean_up + .silences + .iter() + .filter(|silence| silence.key == focused.key) + .copied() + .collect(); + self.clean_up.kept.remove(&focused.key); + if self.apply_silence_cuts(&targets, window, cx) > 0 + && let Some(next) = self.clean_up.focus_at_or_after(focused.start) + { + self.focus_silence(next, window, cx); + } + } + + fn apply_silence_cuts( + &mut self, + silences: &[TimelineSilence], + window: &mut Window, + cx: &mut Context, + ) -> usize { + if silences.is_empty() { + return 0; + } + let saved: f64 = silences.iter().map(TimelineSilence::duration).sum(); + let mut cut = 0; + self.edit( + |timeline| { + cut = cut_silences(timeline, silences); + cut > 0 + }, + window, + cx, + ); + if cut == 0 { + self.clean_up.message = Some("Nothing could be cut here.".to_string()); + } else { + self.note_edit("clean-up-cut", Some(TrackKind::Clip)); + tracing::info!(cut, saved = format!("{saved:.3}"), "clean up cut silences"); + self.clean_up.message = Some(format!( + "Cut {cut} {}, saved {}. Undo brings them back.", + plural(cut, "silence", "silences"), + format_duration(saved) + )); + } + self.refresh_clean_up(window, cx); + cut + } + + fn start_silence_review(&mut self, window: &mut Window, cx: &mut Context) { + self.clean_up.reviewing = true; + match self.clean_up.focus_at_or_after(self.playhead_time()) { + Some(silence) => self.focus_silence(silence, window, cx), + None => { + self.clean_up.reviewing = false; + self.refresh_clean_up(window, cx); + } + } + } + + pub(crate) fn stop_silence_review(&mut self, window: &mut Window, cx: &mut Context) { + self.clean_up.reviewing = false; + self.clean_up.focused = None; + self.refresh_clean_up(window, cx); + } + + pub(crate) fn press_silence( + &mut self, + silence: TimelineSilence, + click_count: usize, + window: &mut Window, + cx: &mut Context, + ) { + let already_focused = self.clean_up.reviewing && self.clean_up.focused == Some(silence.key); + self.clean_up.reviewing = true; + self.clean_up.focused = Some(silence.key); + if click_count >= 2 && already_focused { + self.clean_up.toggle_kept(silence.key); + } else if !self.playing { + self.seek_to_time(silence.start, cx); + } + self.refresh_clean_up(window, cx); + } + + fn step_silence(&mut self, forward: bool, window: &mut Window, cx: &mut Context) { + if let Some(silence) = self.clean_up.step_focus(forward) { + self.focus_silence(silence, window, cx); + } + } + + fn focus_silence( + &mut self, + silence: TimelineSilence, + window: &mut Window, + cx: &mut Context, + ) { + self.reveal_time_range(silence.start, silence.end); + self.seek_to_time(silence.start, cx); + self.refresh_clean_up(window, cx); + } +} + +fn pill_button( + theme: &Theme, + id: &'static str, + icon: &'static str, + color: Hsla, + tooltip: &'static str, +) -> gpui::Stateful { + let theme = *theme; + div() + .id(id) + .size(px(24.)) + .flex() + .flex_none() + .items_center() + .justify_center() + .rounded(px(6.)) + .cursor_pointer() + .hover(move |this| this.bg(Hsla::from(theme.editor.ctl_hover))) + .child(svg().path(icon).size(px(14.)).text_color(color)) + .tooltip(move |_window, cx| ui::Tooltip::new(&theme, tooltip).view(cx)) +} + +fn pill_text_button( + theme: &Theme, + id: &'static str, + icon: &'static str, + label: &'static str, + color: Hsla, + tooltip: &'static str, +) -> gpui::Stateful { + let theme = *theme; + div() + .id(id) + .h(px(24.)) + .px(px(8.)) + .flex() + .flex_none() + .flex_row() + .items_center() + .gap(px(5.)) + .rounded(px(6.)) + .cursor_pointer() + .hover(move |this| this.bg(Hsla::from(theme.editor.ctl_hover))) + .child(svg().path(icon).size(px(13.)).text_color(color)) + .child( + div() + .text_size(px(11.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(color) + .child(label), + ) + .tooltip(move |_window, cx| ui::Tooltip::new(&theme, tooltip).view(cx)) +} + +fn plural(count: usize, one: &'static str, many: &'static str) -> &'static str { + if count == 1 { one } else { many } +} diff --git a/apps/desktop-gpui/src/editor_edits.rs b/apps/desktop-gpui/src/editor_edits.rs index a9583b1d671..fef34177b2b 100644 --- a/apps/desktop-gpui/src/editor_edits.rs +++ b/apps/desktop-gpui/src/editor_edits.rs @@ -1396,6 +1396,62 @@ pub fn delete_clip_segments(timeline: &mut TimelineConfiguration, indices: &[usi deleted } +pub fn cut_clip_source_range( + timeline: &mut TimelineConfiguration, + index: usize, + source_start: f64, + source_end: f64, +) -> bool { + let Some(segment) = timeline.segments.get(index).cloned() else { + return false; + }; + if !segment.timescale.is_finite() || segment.timescale <= 0.0 { + return false; + } + let start = source_start.max(segment.start); + let end = source_end.min(segment.end); + if !start.is_finite() || !end.is_finite() || end <= start { + return false; + } + let removes_head = start <= segment.start; + let removes_tail = end >= segment.end; + if removes_head && removes_tail { + return delete_clip_segments(timeline, &[index]); + } + + let offsets = editor_timeline::clip_timeline_offsets(timeline); + let clip_start = offsets.get(index).copied().unwrap_or(0.0); + let cut_start = clip_start + (start - segment.start) / segment.timescale; + let cut_end = clip_start + (end - segment.start) / segment.timescale; + let holds = timeline.hold_windows(); + let output_cut_start = effective_to_output_end(&holds, cut_start); + let output_cut_end = effective_to_output_end(&holds, cut_end); + + if removes_head { + timeline.segments[index].start = end; + } else if removes_tail { + timeline.segments[index].end = start; + } else { + let mut tail = segment; + tail.start = end; + timeline.segments[index].end = start; + timeline.segments.insert(index + 1, tail); + for transition in timeline.transitions.iter_mut() { + if transition.segment_index as usize > index { + transition.segment_index += 1; + } + } + } + + ripple_delete_output_tracks( + timeline, + output_cut_start, + output_cut_end, + (output_cut_end - output_cut_start).max(cut_end - cut_start), + ); + true +} + pub(crate) fn effective_to_output_end(holds: &[(f64, f64)], effective: f64) -> f64 { let mut output = effective; for (start, finish) in holds { diff --git a/apps/desktop-gpui/src/editor_sidebar.rs b/apps/desktop-gpui/src/editor_sidebar.rs index e328a8247bb..849b14d4dd8 100644 --- a/apps/desktop-gpui/src/editor_sidebar.rs +++ b/apps/desktop-gpui/src/editor_sidebar.rs @@ -254,9 +254,9 @@ const UNPLACED_NOTCH: NotchConfiguration = NotchConfiguration { // Pure model // --------------------------------------------------------------------------- -/// The six tabs of the rail (`:596-621`). `hotkeys` is commented out at `:620` -/// and its dead `KTabs.Content` still exists at `:1053-1061`; it is not a tab -/// here either. +/// The six tabs of the rail (`:596-621`), plus Clean Up, which the Tauri app +/// does not have. `hotkeys` is commented out at `:620` and its dead +/// `KTabs.Content` still exists at `:1053-1061`; it is not a tab here either. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SidebarTab { Background, @@ -264,16 +264,18 @@ pub enum SidebarTab { Audio, Cursor, Keyboard, + CleanUp, Captions, } impl SidebarTab { - pub const ALL: [SidebarTab; 6] = [ + pub const ALL: [SidebarTab; 7] = [ Self::Background, Self::Camera, Self::Audio, Self::Cursor, Self::Keyboard, + Self::CleanUp, Self::Captions, ]; @@ -284,6 +286,7 @@ impl SidebarTab { Self::Audio => "icons/audio-on.svg", Self::Cursor => "icons/cursor.svg", Self::Keyboard => "icons/keyboard.svg", + Self::CleanUp => "icons/scissors.svg", Self::Captions => "icons/message-bubble.svg", } } @@ -295,6 +298,7 @@ impl SidebarTab { Self::Audio => tr::editor::sidebar::tab::audio(), Self::Cursor => tr::editor::sidebar::tab::cursor(), Self::Keyboard => tr::editor::sidebar::tab::keyboard(), + Self::CleanUp => tr::editor::sidebar::tab::clean_up(), Self::Captions => tr::editor::sidebar::tab::captions(), } } @@ -309,6 +313,7 @@ impl SidebarTab { Self::Audio => "Audio", Self::Cursor => "Cursor", Self::Keyboard => "Keyboard", + Self::CleanUp => "Clean Up", Self::Captions => "Captions", } } @@ -728,6 +733,7 @@ pub enum SliderKey { Cursor(CursorSlider), Caption(CaptionSlider), Keyboard(KeyboardSlider), + CleanUp(crate::clean_up::SilenceParameter), Panel(PanelSlider, usize), VoiceEq(crate::editor_voice_eq::VoiceEqSlider), } @@ -1304,6 +1310,7 @@ impl EditorWindow { SliderKey::Cursor(slider) => slider.limits(), SliderKey::Caption(slider) => slider.limits(), SliderKey::Keyboard(slider) => slider.limits(), + SliderKey::CleanUp(parameter) => parameter.limits(), SliderKey::Panel(slider, index) => self.panel_slider_limits(slider, index), SliderKey::VoiceEq(slider) => slider.limits(), } @@ -1334,6 +1341,7 @@ impl EditorWindow { SliderKey::Cursor(slider) => slider.read(&project), SliderKey::Caption(slider) => slider.read(&project), SliderKey::Keyboard(slider) => slider.read(&project), + SliderKey::CleanUp(parameter) => parameter.read(&self.clean_up.settings), SliderKey::Panel(slider, index) => self.panel_slider_value(slider, index), SliderKey::VoiceEq(slider) => self.voice_eq_slider_value(slider), } @@ -1366,6 +1374,9 @@ impl EditorWindow { SliderKey::Cursor(slider) => self.apply_cursor_slider(slider, value, window, cx), SliderKey::Caption(slider) => self.apply_caption_slider(slider, value, window, cx), SliderKey::Keyboard(slider) => self.apply_keyboard_slider(slider, value, window, cx), + SliderKey::CleanUp(parameter) => { + self.set_clean_up_parameter(parameter, value, window, cx) + } SliderKey::Panel(slider, index) => { self.apply_panel_slider(slider, index, value, window, cx) } @@ -2746,6 +2757,7 @@ impl EditorWindow { SidebarTab::Audio => self.render_audio_tab(cx), SidebarTab::Cursor => self.render_cursor_tab(cx), SidebarTab::Keyboard => self.render_keyboard_tab(cx), + SidebarTab::CleanUp => self.render_clean_up_tab(cx), SidebarTab::Captions => self.render_captions_tab(cx), }; diff --git a/apps/desktop-gpui/src/editor_timeline.rs b/apps/desktop-gpui/src/editor_timeline.rs index 148ebd652d7..053e3966364 100644 --- a/apps/desktop-gpui/src/editor_timeline.rs +++ b/apps/desktop-gpui/src/editor_timeline.rs @@ -1379,6 +1379,16 @@ pub struct TimelineModel { /// The span a live ghost trim is removing, in output time. Drawn as a gap /// with a red duration badge, the way Blip's ghost resize marks the cut. pub clip_ghost_gap: Option<(f64, f64)>, + pub silences: Vec, + pub show_silences: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SilenceMark { + pub start: f64, + pub end: f64, + pub kept: bool, + pub focused: bool, } impl TimelineModel { @@ -1631,6 +1641,8 @@ impl TimelineModel { imported_waveforms: Arc::default(), waveform_paths: Arc::default(), clip_ghost_gap: None, + silences: Vec::new(), + show_silences: false, }; model.rows = build_rows( config, @@ -1841,6 +1853,39 @@ fn clip_rows( .collect() } +fn render_silence_mark( + theme: &Theme, + mark: SilenceMark, + view: TimelineView, + secs_per_pixel: f64, +) -> AnyElement { + let red = Hsla::from(gpui::rgb(0xef4444)); + let x = ((mark.start - view.transform.position) / secs_per_pixel) as f32; + let width = (((mark.end - mark.start) / secs_per_pixel) as f32).max(2.); + let (fill, border, border_width) = if mark.kept { + ( + with_alpha(Hsla::from(theme.editor.text_3), 0.08), + with_alpha(Hsla::from(theme.editor.text_3), 0.45), + 1., + ) + } else if mark.focused { + (with_alpha(red, 0.3), red, 1.5) + } else { + (with_alpha(red, 0.16), with_alpha(red, 0.5), 1.) + }; + div() + .absolute() + .top_0() + .bottom_0() + .left(px(x)) + .w(px(width)) + .rounded(px(4.)) + .bg(fill) + .border(px(border_width)) + .border_color(border) + .into_any_element() +} + /// `#rrggbb` / `#rgb`, the form every colour in the config takes. fn parse_hex_color(value: &str) -> Option { let hex = value.strip_prefix('#')?; @@ -2458,6 +2503,20 @@ fn render_track_content( } } + if row.kind == TrackKind::Clip && model.show_silences { + let (visible_start, visible_end) = ( + view.transform.position, + view.transform.position + view.transform.zoom, + ); + for mark in model + .silences + .iter() + .filter(|mark| mark.end >= visible_start && mark.start <= visible_end) + { + content = content.child(render_silence_mark(theme, *mark, view, secs_per_pixel)); + } + } + if row.kind == TrackKind::Clip && let Some((gap_start, gap_end)) = model.clip_ghost_gap { diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index ea0e874245f..ca41e557de6 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -1793,6 +1793,7 @@ pub struct EditorWindow { hovering_generate_zoom: bool, pub(crate) generating_keyboard: bool, pub(crate) keyboard_generation_message: Option, + pub(crate) clean_up: crate::clean_up::CleanUpState, clip_speed: Option, markers: markers::MarkersState, transition_popover: Option, @@ -1940,6 +1941,7 @@ pub struct EditorWindow { notice_seq: u64, /// While a shot is being auditioned, the time playback stops itself at. play_until: Option, + silence_skip_target: Option, /// The empty 3D lane's "How many shots?" picker, and the pill under the /// pointer in it or in the panel's Auto scene row -- which is what the /// lane draws its preview ghosts from. @@ -2553,6 +2555,7 @@ impl EditorWindow { zoom_prompt_dismissed: false, hovering_generate_zoom: false, generating_keyboard: false, + clean_up: crate::clean_up::CleanUpState::default(), keyboard_generation_message: None, clip_speed: None, markers: markers_state, @@ -2621,6 +2624,7 @@ impl EditorWindow { notice: None, notice_seq: 0, play_until: None, + silence_skip_target: None, camera3d_picker: false, camera3d_count_hover: None, timeline_height_override: None, @@ -2800,6 +2804,51 @@ impl EditorWindow { self.apply_seek(end); } } + self.sync_silence_marks(); + } + + pub(crate) fn sync_silence_marks(&mut self) { + self.clean_up.refresh(&self.project); + let focused = self.clean_up.focused; + self.timeline.silences = self + .clean_up + .silences + .iter() + .map(|silence| timeline::SilenceMark { + start: silence.start, + end: silence.end, + kept: self.clean_up.is_kept(silence), + focused: focused == Some(silence.key), + }) + .collect(); + } + + pub(crate) fn silence_marks_visible(&self) -> bool { + self.clean_up.reviewing + || (self.sidebar.tab == crate::editor_sidebar::SidebarTab::CleanUp + && self.sidebar_selection().is_none()) + } + + pub(crate) fn reveal_time_range(&mut self, start: f64, end: f64) { + let transform = &mut self.view.transform; + if start >= transform.position && end <= transform.position + transform.zoom { + return; + } + let total = self.timeline.total_duration; + let lead = (transform.zoom - (end - start)).max(0.) / 2.; + transform.set_position(start - lead, total); + } + + pub fn set_clean_up_envelopes( + &mut self, + envelopes: Vec, + window: &mut Window, + cx: &mut Context, + ) { + self.clean_up.set_envelopes(envelopes); + self.sync_silence_marks(); + cx.notify(); + window.refresh(); } /// The transient popovers a project change closes, shared by the full @@ -3057,7 +3106,7 @@ impl EditorWindow { changed } - fn edit( + pub(crate) fn edit( &mut self, change: impl FnOnce(&mut TimelineConfiguration) -> bool, window: &mut Window, @@ -3893,16 +3942,49 @@ impl EditorWindow { self.stop_playback(cx); } + self.skip_pending_silence(next, cx); + self.last_playhead_redraw = Instant::now(); self.invalidate_playback_chrome(window, cx); self.transcript_sync_active(true, cx); } + /// While the Clean Up marks are on screen, playback previews the cut: a + /// pending silence is jumped over a frame before it starts. Frames the + /// engine emits before the jump lands still sit inside the silence, so + /// the target is remembered until playback reaches it. + fn skip_pending_silence(&mut self, now: f64, cx: &mut Context) { + if !self.playing || !self.silence_marks_visible() { + self.silence_skip_target = None; + return; + } + let frame = self.preview_speed.as_f64().max(1.) / f64::from(EDITOR_PREVIEW_FPS); + if let Some(target) = self.silence_skip_target { + if now < target - frame { + return; + } + self.silence_skip_target = None; + } + let Some(end) = self.clean_up.skip_target(now, frame) else { + return; + }; + let play_until = self.play_until; + if end >= self.total_duration() - frame { + self.stop_playback(cx); + self.seek_to_time(end, cx); + return; + } + self.seek_to_time(end, cx); + self.play_until = play_until; + self.silence_skip_target = Some(end); + } + /// The pause half of `handlePlayPauseClick`, also used by the end-of-media /// effect, by prev/next, and by the clips sidebar's import path /// (`ClipsSidebar.tsx:508-511`). pub(crate) fn stop_playback(&mut self, cx: &mut Context) { self.play_until = None; + self.silence_skip_target = None; self.playback_follow.reset(); if self.preparing_transport_active() { self.preparing_command(None, Some(false)); @@ -4144,6 +4226,7 @@ impl EditorWindow { fn apply_seek(&mut self, time: f64) -> bool { // Moving the playhead by hand ends any shot audition. self.play_until = None; + self.silence_skip_target = None; if self.preparing_transport_active() { self.preparing_command(Some(time), None); return false; @@ -4597,6 +4680,11 @@ impl EditorWindow { cx.stop_propagation(); return; } + if event.keystroke.key.as_str() == "escape" && self.clean_up.reviewing { + self.stop_silence_review(window, cx); + cx.stop_propagation(); + return; + } if ui::text_input_has_focus(window, cx) { return; } @@ -5463,6 +5551,17 @@ impl EditorWindow { "timeline press" ); + if kind == TrackKind::Clip + && !self.split_mode + && !matches!(hit, Hit::Handle { .. }) + && self.silence_marks_visible() + && let Some(silence) = self.clean_up.silence_at(press_time) + { + cx.stop_propagation(); + self.press_silence(silence, event.click_count, window, cx); + return; + } + // The selected 3D shot's pose dots: a press on one picks that pose // instead of starting a move. Only inside the body, so the resize // handles keep the outer pixels. @@ -6432,6 +6531,7 @@ impl EditorWindow { *source_duration = draft.end - draft.start; } model.clip_ghost_gap = gap; + model.show_silences = false; return Some(model); } let anim = self.clip_anim.as_ref()?; @@ -12718,6 +12818,7 @@ impl EditorWindow { cx: &mut Context, ) -> impl IntoElement { let theme = self.theme; + self.timeline.show_silences = self.silence_marks_visible(); self.timeline.waveform_paths.sweep(); if !self.project_ready() { if self @@ -12915,6 +13016,7 @@ impl EditorWindow { x.is_finite() .then(|| render_split_preview(&theme, x, true, false)) })) + .children(self.render_silence_review_pill(cx)) .into_any_element() } diff --git a/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs b/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs index c4661c14d9d..eb8a9982911 100644 --- a/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs @@ -473,6 +473,7 @@ fn editor_panels_match_the_literals_they_replaced() { (tr::editor::sidebar::tab::audio(), "Audio"), (tr::editor::sidebar::tab::cursor(), "Cursor"), (tr::editor::sidebar::tab::keyboard(), "Keyboard"), + (tr::editor::sidebar::tab::clean_up(), "Clean Up"), (tr::editor::sidebar::tab::captions(), "Captions"), (tr::editor::sidebar::source::desktop(), "Desktop"), (tr::editor::sidebar::source::wallpaper(), "Wallpaper"), diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index ba16e714edc..be65a699353 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -20,6 +20,7 @@ mod camera_loading; mod camera_picture; mod camera_window; mod caption_export; +mod clean_up; mod controls_window; mod crash_capture; mod deeplink; @@ -32,6 +33,7 @@ mod editor_audio; mod editor_audio_only; mod editor_bench; mod editor_canvas; +mod editor_clean_up; mod editor_clips; mod editor_color; mod editor_crop;