Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(audio): upgrade Studio Sound denoising and alignment

Richie McIlroyd4bc0995db74
diff --git a/Cargo.lock b/Cargo.lock
index 280a91700..1f89b4a26 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -387,12 +387,6 @@ version = "1.0.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100"
-[[package]]
-name = "anymap3"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
-
[[package]]
name = "apple-native-keyring-store"
version = "1.0.1"
@@ -445,12 +439,6 @@ dependencies = [
"syn 2.0.106",
]
-[[package]]
-name = "array-init"
-version = "2.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
-
[[package]]
name = "arrayref"
version = "0.3.9"
@@ -1281,10 +1269,10 @@ name = "cap-audio"
version = "0.1.0"
dependencies = [
"cap-enc-ffmpeg",
+ "cap-rnnoise",
"cidre",
"cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=6013cb5f8bd3)",
"ffmpeg-next",
- "nnnoiseless",
"serde",
"serde_json",
"tempfile",
@@ -1999,6 +1987,13 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "cap-rnnoise"
+version = "0.1.0"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "cap-test"
version = "0.1.0"
@@ -3446,19 +3441,6 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
-[[package]]
-name = "easyfft"
-version = "0.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "767e39eef2ad8a3b6f1d733be3ec70364d21d437d06d4f18ea76ce08df20b75f"
-dependencies = [
- "array-init",
- "generic_singleton",
- "num-complex",
- "realfft",
- "rustfft",
-]
-
[[package]]
name = "either"
version = "1.15.0"
@@ -4165,16 +4147,6 @@ dependencies = [
"version_check",
]
-[[package]]
-name = "generic_singleton"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ab6e923c8e978e57cf63e2e200ca967d1d20f0ea2662b28f6d4e11c44aa6ab16"
-dependencies = [
- "anymap3",
- "parking_lot",
-]
-
[[package]]
name = "gethostname"
version = "1.0.2"
@@ -6415,16 +6387,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "nnnoiseless"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "805d5964d1e7a0006a7fdced7dae75084d66d18b35f1dfe81bd76929b1f8da0c"
-dependencies = [
- "easyfft",
- "once_cell",
-]
-
[[package]]
name = "nodrop"
version = "0.1.14"
@@ -6519,7 +6481,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
- "serde",
]
[[package]]
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index 2a9f3e5aa..b3c0c16f4 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -453,12 +453,6 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
-[[package]]
-name = "anymap3"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
-
[[package]]
name = "ar_archive_writer"
version = "0.5.3"
@@ -485,12 +479,6 @@ dependencies = [
"syn 2.0.119",
]
-[[package]]
-name = "array-init"
-version = "2.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
-
[[package]]
name = "arrayref"
version = "0.3.9"
@@ -1409,10 +1397,10 @@ name = "cap-audio"
version = "0.1.0"
dependencies = [
"cap-enc-ffmpeg",
+ "cap-rnnoise",
"cidre",
"cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=6013cb5f8bd3)",
"ffmpeg-next",
- "nnnoiseless",
"serde",
"serde_json",
"tokio",
@@ -1962,6 +1950,13 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "cap-rnnoise"
+version = "0.1.0"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "cap-timestamp"
version = "0.1.0"
@@ -3422,19 +3417,6 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
-[[package]]
-name = "easyfft"
-version = "0.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "767e39eef2ad8a3b6f1d733be3ec70364d21d437d06d4f18ea76ce08df20b75f"
-dependencies = [
- "array-init",
- "generic_singleton",
- "num-complex",
- "realfft",
- "rustfft",
-]
-
[[package]]
name = "either"
version = "1.17.0"
@@ -4151,16 +4133,6 @@ dependencies = [
"version_check",
]
-[[package]]
-name = "generic_singleton"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ab6e923c8e978e57cf63e2e200ca967d1d20f0ea2662b28f6d4e11c44aa6ab16"
-dependencies = [
- "anymap3",
- "parking_lot",
-]
-
[[package]]
name = "gethostname"
version = "1.1.0"
@@ -6717,16 +6689,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "nnnoiseless"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "805d5964d1e7a0006a7fdced7dae75084d66d18b35f1dfe81bd76929b1f8da0c"
-dependencies = [
- "easyfft",
- "once_cell",
-]
-
[[package]]
name = "no_std_io2"
version = "0.9.4"
@@ -6848,7 +6810,6 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"bytemuck",
"num-traits",
- "serde",
]
[[package]]
diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml
index 04154e62e..a9431abb6 100644
--- a/crates/audio/Cargo.toml
+++ b/crates/audio/Cargo.toml
@@ -7,7 +7,7 @@ edition = "2024"
test-support = []
[dependencies]
-nnnoiseless = { version = "0.5.2", default-features = false }
+cap-rnnoise = { path = "../rnnoise" }
cap-enc-ffmpeg = { path = "../enc-ffmpeg" }
ffmpeg = { workspace = true }
cpal = { workspace = true }
diff --git a/crates/audio/src/voice.rs b/crates/audio/src/voice.rs
index 89a0c5bed..32e786a37 100644
--- a/crates/audio/src/voice.rs
+++ b/crates/audio/src/voice.rs
@@ -1,18 +1,24 @@
-use crate::AudioSampleSource;
-use nnnoiseless::DenoiseState;
-use std::ops::Range;
+use crate::{AudioSampleSource, VoiceProfile, voice_level::VoiceFilter};
+use cap_rnnoise::{DELAY_SAMPLES, DenoiseState, FRAME_SIZE};
+use std::{collections::VecDeque, ops::Range};
-const FRAME: usize = DenoiseState::FRAME_SIZE;
-pub const VOICE_PREROLL_SAMPLES: usize = 9_600;
-pub const VOICE_WINDOW_PADDING_SAMPLES: usize = FRAME * 3;
+const FRAME: usize = FRAME_SIZE;
+pub const VOICE_PREROLL_SAMPLES: usize = 24_000;
+pub const VOICE_WINDOW_PADDING_SAMPLES: usize = FRAME * 9;
pub struct VoiceEnhancer {
- states: Vec<Box<DenoiseState<'static>>>,
+ states: Vec<DenoiseState>,
next_input: usize,
expected_start: Option<usize>,
- frame_start: Option<usize>,
- frame: Vec<f32>,
+ warm_start: usize,
+ pending_start: usize,
+ pending: VecDeque<f32>,
previous: Vec<f32>,
+ frame: Vec<f32>,
+ wet: f32,
+ profile: Option<VoiceProfile>,
+ leveler: Option<VoiceFilter>,
+ speech_frames: usize,
}
impl VoiceEnhancer {
@@ -22,17 +28,37 @@ impl VoiceEnhancer {
states: (0..channels).map(|_| DenoiseState::new()).collect(),
next_input: 0,
expected_start: None,
- frame_start: None,
+ warm_start: 0,
+ pending_start: 0,
+ pending: VecDeque::new(),
+ previous: vec![0.0; DELAY_SAMPLES * channels],
frame: vec![0.0; FRAME * channels],
- previous: vec![0.0; FRAME * channels],
+ wet: 0.9,
+ profile: None,
+ leveler: None,
+ speech_frames: 0,
}
}
+ pub fn with_settings(channels: u16, wet: f32, profile: VoiceProfile) -> Self {
+ let mut enhancer = Self::new(channels);
+ enhancer.wet = if wet.is_finite() {
+ wet.clamp(0.0, 1.0)
+ } else {
+ 0.9
+ };
+ enhancer.profile = Some(profile);
+ enhancer
+ }
+
+ pub fn speech_frames(&self) -> usize {
+ self.speech_frames
+ }
+
pub fn is_contiguous(&self, start: usize) -> bool {
self.expected_start == Some(start)
- || self
- .frame_start
- .is_some_and(|first| (first..first + FRAME).contains(&start))
+ || (self.pending_start..self.pending_start + self.pending.len() / self.states.len())
+ .contains(&start)
}
pub fn source_range(&self, start: usize, count: usize) -> Range<usize> {
@@ -44,10 +70,21 @@ impl VoiceEnhancer {
} else {
(start / FRAME * FRAME).saturating_sub(VOICE_PREROLL_SAMPLES)
};
+ let padding = if self.profile.is_some() { 7 } else { 3 };
+ let end = start
+ .saturating_add(count)
+ .div_ceil(FRAME)
+ .saturating_add(padding)
+ .saturating_mul(FRAME);
+ first..end.max(first)
+ }
+
+ pub fn initial_source_range(start: usize, count: usize) -> Range<usize> {
+ let first = (start / FRAME * FRAME).saturating_sub(VOICE_PREROLL_SAMPLES);
let end = start
.saturating_add(count)
.div_ceil(FRAME)
- .saturating_add(1)
+ .saturating_add(7)
.saturating_mul(FRAME);
first..end.max(first)
}
@@ -60,28 +97,48 @@ impl VoiceEnhancer {
) -> VoiceAudio {
let channels = self.states.len();
let count = count.min(source.sample_count().saturating_sub(start));
+ if count == 0 {
+ return VoiceAudio {
+ samples: Vec::new(),
+ channels: channels as u16,
+ start,
+ total_samples: source.sample_count(),
+ };
+ }
if count > 0 && !self.is_contiguous(start) {
self.next_input = self.source_range(start, count).start;
- self.states = (0..channels).map(|_| DenoiseState::new()).collect();
- self.frame_start = None;
+ self.warm_start = self.next_input;
+ self.pending_start = self.next_input;
+ self.pending.clear();
self.previous.fill(0.0);
+ self.states = (0..channels).map(|_| DenoiseState::new()).collect();
+ self.speech_frames = 0;
+ self.leveler = self.profile.and_then(|profile| {
+ VoiceFilter::new(channels as u16, &profile.filter(channels as u16))
+ .map_err(|error| {
+ tracing::warn!(%error, "Studio Sound leveling is unavailable");
+ })
+ .ok()
+ });
}
- let mut samples = vec![0.0; count * channels];
- let mut written = 0;
- while written < count {
- let cursor = start + written;
- while !self
- .frame_start
- .is_some_and(|first| (first..first + FRAME).contains(&cursor))
- {
- self.process_frame(source);
- }
- let offset = cursor - self.frame_start.unwrap();
- let take = (FRAME - offset).min(count - written);
- samples[written * channels..(written + take) * channels]
- .copy_from_slice(&self.frame[offset * channels..(offset + take) * channels]);
- written += take;
+ while count > 0 && self.pending_start + self.pending.len() / channels < start + count {
+ self.process_frame(source);
}
+ let first = (start - self.pending_start) * channels;
+ let samples = self
+ .pending
+ .iter()
+ .skip(first)
+ .take(count * channels)
+ .copied()
+ .collect();
+ // Fractional timeline mappings can repeat a source sample without rewinding the decoder.
+ let history_start = (start + count - 1) / FRAME * FRAME;
+ let discard = history_start
+ .saturating_sub(self.pending_start)
+ .min(self.pending.len() / channels);
+ drop(self.pending.drain(..discard * channels));
+ self.pending_start += discard;
self.expected_start = Some(start + count);
VoiceAudio {
samples,
@@ -95,6 +152,8 @@ impl VoiceEnhancer {
let channels = self.states.len();
let mut input = [0.0; FRAME];
let mut output = [0.0; FRAME];
+ let delayed = (self.next_input / FRAME % 2) * FRAME * channels;
+ let mut speech = false;
for (channel, state) in self.states.iter_mut().enumerate() {
for (index, sample) in input.iter_mut().enumerate() {
let value = source
@@ -107,16 +166,26 @@ impl VoiceEnhancer {
0.0
};
}
- state.process_frame(&mut output, &input);
+ speech |= state.process_frame(&mut output, &input) > 0.6;
for (index, (&clean, &raw)) in output.iter().zip(&input).enumerate() {
let index = index * channels + channel;
self.frame[index] =
- (clean / 32_768.0 * 0.9 + self.previous[index] * 0.1).clamp(-1.0, 1.0);
- self.previous[index] = raw / 32_768.0;
+ clean / 32_768.0 * self.wet + self.previous[delayed + index] * (1.0 - self.wet);
+ self.previous[delayed + index] = raw / 32_768.0;
+ }
+ }
+ self.speech_frames += usize::from(speech);
+ if self.next_input >= self.warm_start + DELAY_SAMPLES {
+ if let Some(leveler) = &mut self.leveler {
+ if let Err(error) = leveler.process(&self.frame, &mut self.pending) {
+ tracing::warn!(%error, "Studio Sound leveling failed");
+ self.leveler = None;
+ self.pending.extend(&self.frame);
+ }
+ } else {
+ self.pending.extend(&self.frame);
}
}
- // RNNoise emits the preceding 10 ms frame. Reading ahead keeps source timestamps intact.
- self.frame_start = self.next_input.checked_sub(FRAME);
self.next_input += FRAME;
}
}
@@ -128,6 +197,12 @@ pub struct VoiceAudio {
total_samples: usize,
}
+impl VoiceAudio {
+ pub fn samples(&self) -> &[f32] {
+ &self.samples
+ }
+}
+
impl AudioSampleSource for VoiceAudio {
fn channels(&self) -> u16 {
self.channels
@@ -212,6 +287,70 @@ mod tests {
}
}
+ #[test]
+ fn leveling_preserves_chunk_boundaries_timing_and_peak_headroom() {
+ ffmpeg::init().unwrap();
+ for channels in [1, 2] {
+ let mut source = signal(96_137, channels);
+ for (index, sample) in source.data.iter_mut().enumerate() {
+ let position = index / usize::from(channels);
+ *sample = if (8_000..80_000).contains(&position) {
+ (position as f32 * 0.037).sin() * 0.05
+ } else {
+ 0.0
+ };
+ }
+ let profile = VoiceProfile {
+ gain_db: 12.0,
+ makeup_db: 2.0,
+ };
+ let expected = VoiceEnhancer::with_settings(channels, 0.9, profile).render(
+ &source,
+ 0,
+ source.sample_count(),
+ );
+ let mut enhancer = VoiceEnhancer::with_settings(channels, 0.9, profile);
+ let mut actual = Vec::new();
+ let mut cursor = 0;
+ while cursor < source.sample_count() {
+ let audio = enhancer.render(&source, cursor, cursor % 5_007 + 1);
+ cursor += audio.samples.len() / usize::from(channels);
+ actual.extend(audio.samples);
+ assert!(
+ enhancer.pending.len() < VOICE_WINDOW_PADDING_SAMPLES * usize::from(channels)
+ );
+ }
+ assert_eq!(actual, expected.samples);
+ assert!(
+ actual
+ .iter()
+ .all(|value| value.is_finite() && value.abs() < 0.86)
+ );
+ assert!(actual.iter().any(|value| value.abs() > 0.05));
+ for remainder in 0..FRAME {
+ let range = enhancer.source_range(48_000 + remainder, 4_096);
+ assert!(
+ range.len() <= 4_096 + VOICE_PREROLL_SAMPLES + VOICE_WINDOW_PADDING_SAMPLES
+ );
+ }
+ let mut impulse = Samples {
+ data: vec![0.0; 12_017 * usize::from(channels)],
+ channels,
+ };
+ impulse.data[5_333 * usize::from(channels)] = 0.8;
+ let audio = VoiceEnhancer::with_settings(channels, 0.0, VoiceProfile::default())
+ .render(&impulse, 0, impulse.sample_count());
+ let peak = audio
+ .samples
+ .iter()
+ .enumerate()
+ .max_by(|(_, a), (_, b)| a.abs().total_cmp(&b.abs()))
+ .unwrap()
+ .0;
+ assert_eq!(peak / usize::from(channels), 5_333);
+ }
+ }
+
#[test]
fn arbitrary_blocks_match_whole_processing_including_stereo_and_tail() {
for channels in [1, 2] {
@@ -311,6 +450,6 @@ mod tests {
);
assert_eq!(enhancer.states.len(), 1);
assert_eq!(enhancer.frame.len(), FRAME);
- assert_eq!(enhancer.previous.len(), FRAME);
+ assert_eq!(enhancer.previous.len(), DELAY_SAMPLES);
}
}