Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(editor): mix timeline music tracks in audio renderer

Richie McIlroy1e0ad2601166
diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rs
index e4400eeca..11dc94206 100644
--- a/crates/editor/src/audio.rs
+++ b/crates/editor/src/audio.rs
@@ -12,15 +12,21 @@ use ringbuf::{
HeapRb,
traits::{Consumer, Observer, Producer},
};
-use std::sync::Arc;
+use std::{collections::HashMap, sync::Arc};
use tracing::info;
+/// Decoded music/imported-audio tracks, keyed by the path string stored in the
+/// project config's `timeline.audio_segments`. The renderer mixes these on top
+/// of the recording audio in output/timeline time.
+pub type MusicTracks = HashMap<String, Arc<AudioData>>;
+
pub struct AudioRenderer {
data: Vec<AudioSegment>,
cursor: AudioRendererCursor,
// sum of `frame.samples()` that have elapsed
// this * channel count = cursor
elapsed_samples: usize,
+ music: MusicTracks,
}
#[derive(Clone, Copy, Debug)]
@@ -108,9 +114,15 @@ impl AudioRenderer {
timescale: 1.0,
},
elapsed_samples: 0,
+ music: MusicTracks::new(),
}
}
+ pub fn with_music(mut self, music: MusicTracks) -> Self {
+ self.music = music;
+ self
+ }
+
pub fn set_playhead(&mut self, playhead: f64, project: &ProjectConfiguration) {
self.elapsed_samples = self.playhead_to_samples(playhead);
@@ -159,7 +171,16 @@ impl AudioRenderer {
project: &ProjectConfiguration,
) -> Option<(usize, Vec<f32>)> {
if let Some(timeline) = &project.timeline {
- return self.render_timeline_frame_raw(samples, project, timeline);
+ // Capture the output-time playhead before the recording mix advances
+ // it, so timeline-positioned music is aligned to the same grid.
+ let frame_start = self.elapsed_samples;
+ let (written, mut buf) = self.render_timeline_frame_raw(samples, project, timeline)?;
+
+ if !self.music.is_empty() && !timeline.audio_segments.is_empty() {
+ mix_music(&self.music, timeline, frame_start, written, &mut buf);
+ }
+
+ return Some((written, buf));
}
self.render_linear_frame_raw(samples, project)
@@ -327,6 +348,114 @@ impl AudioRenderer {
}
}
+/// Below this volume a music track is treated as silent and skipped entirely.
+const MUSIC_SILENCE_DB: f32 = -60.0;
+
+fn music_gain(volume_db: f32) -> f32 {
+ if volume_db <= MUSIC_SILENCE_DB {
+ 0.0
+ } else {
+ 10.0_f32.powf(volume_db / 20.0)
+ }
+}
+
+/// Mixes timeline-positioned music tracks into an already-rendered, interleaved
+/// stereo buffer covering output samples `[frame_start, frame_start + samples)`.
+///
+/// Each segment is placed in output time (`start`/`end`), reads its source from
+/// `trim_start`, and applies linear fade-in/out ramps. Sources may be mono or
+/// stereo; mono is centre-panned at -3dB to match `cap_audio::render_audio`.
+fn mix_music(
+ music: &MusicTracks,
+ timeline: &TimelineConfiguration,
+ frame_start: usize,
+ samples: usize,
+ out: &mut [f32],
+) {
+ if samples == 0 {
+ return;
+ }
+
+ let sample_rate = AudioData::SAMPLE_RATE as f64;
+ let frame_start = frame_start as i64;
+ let frame_end = frame_start + samples as i64;
+
+ for segment in &timeline.audio_segments {
+ if !segment.enabled || segment.end <= segment.start {
+ continue;
+ }
+
+ let gain = music_gain(segment.volume_db);
+ if gain <= 0.0 {
+ continue;
+ }
+
+ let Some(data) = music.get(&segment.path) else {
+ continue;
+ };
+
+ let start_sample = (segment.start * sample_rate).round() as i64;
+ let end_sample = (segment.end * sample_rate).round() as i64;
+ let segment_len = end_sample - start_sample;
+ if segment_len <= 0 {
+ continue;
+ }
+
+ // Window of this segment that intersects the current frame.
+ let lo = start_sample.max(frame_start);
+ let hi = end_sample.min(frame_end);
+ if lo >= hi {
+ continue;
+ }
+
+ let trim_sample = (segment.trim_start.max(0.0) * sample_rate).round() as i64;
+ let fade_in = (segment.fade_in.max(0.0) * sample_rate).round() as i64;
+ let fade_out = (segment.fade_out.max(0.0) * sample_rate).round() as i64;
+
+ let channels = data.channels() as usize;
+ let src = data.samples();
+ let src_frames = data.sample_count() as i64;
+
+ for out_sample in lo..hi {
+ let local = out_sample - start_sample;
+ let src_index = trim_sample + local;
+ if src_index < 0 || src_index >= src_frames {
+ continue;
+ }
+
+ let mut g = gain;
+ if fade_in > 0 && local < fade_in {
+ g *= local as f32 / fade_in as f32;
+ }
+ let until_end = segment_len - local;
+ if fade_out > 0 && until_end <= fade_out {
+ g *= (until_end as f32 / fade_out as f32).clamp(0.0, 1.0);
+ }
+ if g <= 0.0 {
+ continue;
+ }
+
+ let (l, r) = if channels == 1 {
+ let Some(sample) = src.get(src_index as usize) else {
+ continue;
+ };
+ let s = sample * 0.707;
+ (s, s)
+ } else {
+ let base = (src_index as usize) * channels;
+ let (Some(l), Some(r)) = (src.get(base), src.get(base + 1)) else {
+ continue;
+ };
+ (*l, *r)
+ };
+
+ let out_index = ((out_sample - frame_start) as usize) * 2;
+ out[out_index] = (out[out_index] + l * g).clamp(-1.0, 1.0);
+ out[out_index + 1] = (out[out_index + 1] + r * g).clamp(-1.0, 1.0);
+ }
+ }
+}
+
#[cfg(not(target_os = "windows"))]
pub struct AudioPlaybackBuffer<T: FromSampleBytes> {
frame_buffer: AudioRenderer,
@@ -342,7 +471,7 @@ impl<T: FromSampleBytes> AudioPlaybackBuffer<T> {
const PROCESSING_SAMPLES_COUNT: u32 = 1024;
- pub fn new(data: Vec<AudioSegment>, output_info: AudioInfo) -> Self {
+ pub fn new(data: Vec<AudioSegment>, music: MusicTracks, output_info: AudioInfo) -> Self {
// Clamp output info for FFmpeg compatibility (max 8 channels)
let output_info = output_info.for_ffmpeg_output();
@@ -360,7 +489,7 @@ impl<T: FromSampleBytes> AudioPlaybackBuffer<T> {
* output_info.sample_format.bytes();
let resampled_buffer = HeapRb::new(capacity);
- let frame_buffer = AudioRenderer::new(data);
+ let frame_buffer = AudioRenderer::new(data).with_music(music);
Self {
frame_buffer,
@@ -541,6 +670,7 @@ pub struct PrerenderedAudioBuffer<T: FromSampleBytes> {
impl<T: FromSampleBytes> PrerenderedAudioBuffer<T> {
pub fn new(
segments: Vec<AudioSegment>,
+ music: MusicTracks,
project: &ProjectConfiguration,
output_info: AudioInfo,
duration_secs: f64,
@@ -556,7 +686,7 @@ impl<T: FromSampleBytes> PrerenderedAudioBuffer<T> {
"Pre-rendering audio for playback"
);
- let mut renderer = AudioRenderer::new(segments);
+ let mut renderer = AudioRenderer::new(segments).with_music(music);
let mut resampler = AudioResampler::new(output_info).unwrap();
let total_source_samples = (duration_secs * AudioData::SAMPLE_RATE as f64) as usize;
@@ -793,6 +923,7 @@ mod tests {
text_segments: Vec::new(),
caption_segments: Vec::new(),
keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
}),
clips: vec![
ClipConfiguration {
@@ -890,6 +1021,7 @@ mod tests {
text_segments: Vec::new(),
caption_segments: Vec::new(),
keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
}),
clips: vec![ClipConfiguration {
index: 0,
@@ -979,6 +1111,7 @@ mod tests {
text_segments: Vec::new(),
caption_segments: Vec::new(),
keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
}),
clips: vec![ClipConfiguration {
index: 0,
@@ -1016,6 +1149,7 @@ mod tests {
text_segments: Vec::new(),
caption_segments: Vec::new(),
keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
}),
clips: vec![ClipConfiguration {
index: 0,
@@ -1027,8 +1161,13 @@ mod tests {
let mut export_renderer = AudioRenderer::new(segments.clone());
let export_stream = render_export_audio(&mut export_renderer, &project, 30, 3 * 30);
- let mut playback_buffer =
- PrerenderedAudioBuffer::<f32>::new(segments, &project, AudioRenderer::info(), 3.0);
+ let mut playback_buffer = PrerenderedAudioBuffer::<f32>::new(
+ segments,
+ MusicTracks::new(),
+ &project,
+ AudioRenderer::info(),
+ 3.0,
+ );
let mut playback_stream = vec![0.0; 3 * AudioData::SAMPLE_RATE as usize * 2];
playback_buffer.fill(&mut playback_stream);
@@ -1114,4 +1253,127 @@ mod tests {
assert!((left_at_second(&stream, 0) - expected(values[0])).abs() < 0.01);
assert!((left_at_second(&stream, 1) - expected(values[3])).abs() < 0.01);
}
+
+ fn music_track_segment(
+ path: &str,
+ start: f64,
+ end: f64,
+ fade_in: f64,
+ fade_out: f64,
+ ) -> cap_project::AudioTrackSegment {
+ cap_project::AudioTrackSegment {
+ start,
+ end,
+ track: 0,
+ path: path.to_string(),
+ name: None,
+ enabled: true,
+ trim_start: 0.0,
+ volume_db: 0.0,
+ fade_in,
+ fade_out,
+ duration: Some(end - start),
+ }
+ }
+
+ fn music_project(audio_segments: Vec<cap_project::AudioTrackSegment>) -> ProjectConfiguration {
+ ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: vec![segment(0, 0.0, 3.0, 1.0)],
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments,
+ }),
+ clips: vec![ClipConfiguration {
+ index: 0,
+ offsets: Default::default(),
+ }],
+ ..Default::default()
+ }
+ }
+
+ // Timeline music must be mixed on top of the recording even when the
+ // recording itself carries no audio (empty renderer `data`).
+ #[test]
+ fn mixes_timeline_music_over_silent_recording() {
+ let _ = ffmpeg::init();
+ let dir = tempfile::tempdir().unwrap();
+ let music_path = dir.path().join("music.wav");
+ write_step_wav(&music_path, &[8000, 8000, 8000]);
+
+ let mut music = MusicTracks::new();
+ music.insert(
+ "music.wav".to_string(),
+ Arc::new(AudioData::from_file(&music_path).unwrap()),
+ );
+
+ let project = music_project(vec![music_track_segment("music.wav", 0.0, 3.0, 0.0, 0.0)]);
+ let mut renderer = AudioRenderer::new(vec![]).with_music(music);
+ let stream = render_export_audio(&mut renderer, &project, 30, 3 * 30);
+
+ for second in 0..3usize {
+ assert!(
+ (left_at_second(&stream, second) - expected(8000)).abs() < 0.02,
+ "second {second}: music not mixed",
+ );
+ }
+ }
+
+ // A timeline-positioned music clip only sounds inside its [start, end) window.
+ #[test]
+ fn timeline_music_respects_start_offset() {
+ let _ = ffmpeg::init();
+ let dir = tempfile::tempdir().unwrap();
+ let music_path = dir.path().join("music.wav");
+ write_step_wav(&music_path, &[8000, 8000, 8000]);
+
+ let mut music = MusicTracks::new();
+ music.insert(
+ "music.wav".to_string(),
+ Arc::new(AudioData::from_file(&music_path).unwrap()),
+ );
+
+ // Starts at 1.0s, so output second 0 is silent and 1..3 play.
+ let project = music_project(vec![music_track_segment("music.wav", 1.0, 3.0, 0.0, 0.0)]);
+ let mut renderer = AudioRenderer::new(vec![]).with_music(music);
+ let stream = render_export_audio(&mut renderer, &project, 30, 3 * 30);
+
+ assert!(
+ left_at_second(&stream, 0).abs() < 0.001,
+ "before start must be silent"
+ );
+ assert!((left_at_second(&stream, 1) - expected(8000)).abs() < 0.02);
+ assert!((left_at_second(&stream, 2) - expected(8000)).abs() < 0.02);
+ }
+
+ // A linear fade-in ramps the gain from 0 at the clip start to full at
+ // `fade_in` seconds. Sampling the mid-point of each output second reveals
+ // the ramp.
+ #[test]
+ fn timeline_music_applies_fade_in() {
+ let _ = ffmpeg::init();
+ let dir = tempfile::tempdir().unwrap();
+ let music_path = dir.path().join("music.wav");
+ write_step_wav(&music_path, &[8000, 8000, 8000]);
+
+ let mut music = MusicTracks::new();
+ music.insert(
+ "music.wav".to_string(),
+ Arc::new(AudioData::from_file(&music_path).unwrap()),
+ );
+
+ // 2s fade-in over a 3s clip: 0.5s -> ~25%, 1.5s -> ~75%, 2.5s -> 100%.
+ let project = music_project(vec![music_track_segment("music.wav", 0.0, 3.0, 2.0, 0.0)]);
+ let mut renderer = AudioRenderer::new(vec![]).with_music(music);
+ let stream = render_export_audio(&mut renderer, &project, 30, 3 * 30);
+
+ let full = expected(8000);
+ assert!((left_at_second(&stream, 0) - full * 0.25).abs() < 0.03);
+ assert!((left_at_second(&stream, 1) - full * 0.75).abs() < 0.03);
+ assert!((left_at_second(&stream, 2) - full).abs() < 0.03);
+ }
}