Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve audio sync (#425)

Brendan Alland03560b9c372
diff --git a/Cargo.lock b/Cargo.lock
index 37ed6c519..08e5a89bb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2266,6 +2266,16 @@ dependencies = [
"dirs-sys",
]
+[[package]]
+name = "dirs-next"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
+dependencies = [
+ "cfg-if 1.0.0",
+ "dirs-sys-next",
+]
+
[[package]]
name = "dirs-sys"
version = "0.5.0"
@@ -2274,10 +2284,21 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
- "redox_users",
+ "redox_users 0.5.0",
"windows-sys 0.59.0",
]
+[[package]]
+name = "dirs-sys-next"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
+dependencies = [
+ "libc",
+ "redox_users 0.4.6",
+ "winapi",
+]
+
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -4155,13 +4176,14 @@ checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "mac-notification-sys"
-version = "0.6.4"
+version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b95dfb34071d1592b45622bf93e315e3a72d414b6782aca9a015c12bec367ef"
+checksum = "dce8f34f3717aa37177e723df6c1fc5fb02b2a1087374ea3fe0ea42316dc8f91"
dependencies = [
"cc",
- "objc2 0.6.0",
- "objc2-foundation 0.3.0",
+ "dirs-next",
+ "objc-foundation",
+ "objc_id",
"time",
]
@@ -6030,6 +6052,17 @@ dependencies = [
"bitflags 2.9.0",
]
+[[package]]
+name = "redox_users"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
+dependencies = [
+ "getrandom 0.2.15",
+ "libredox",
+ "thiserror 1.0.69",
+]
+
[[package]]
name = "redox_users"
version = "0.5.0"
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index db91ce75f..29d9e8202 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -420,7 +420,6 @@ async fn handle_recording_end(
if let Some(window) = CapWindowId::Main.get(&app) {
window.unminimize().ok();
} else {
- println!("SPIEJWPFIJE");
CapWindowId::Camera.get(&app).map(|v| {
let _ = v.close();
});
diff --git a/crates/media/src/encoders/mp4_avassetwriter.rs b/crates/media/src/encoders/mp4_avassetwriter.rs
index b72b3d23e..9b9597770 100644
--- a/crates/media/src/encoders/mp4_avassetwriter.rs
+++ b/crates/media/src/encoders/mp4_avassetwriter.rs
@@ -177,9 +177,8 @@ impl MP4AVAssetWriterEncoder {
let new_pts = self
.start_time
- .add(time)
- .sub(self.first_timestamp.unwrap())
- .add(self.elapsed_duration);
+ .add(self.elapsed_duration)
+ .add(time.sub(self.first_timestamp.unwrap()));
let mut timing = frame.timing_info(0).unwrap();
timing.pts = new_pts;
@@ -201,10 +200,6 @@ impl MP4AVAssetWriterEncoder {
return Err(MediaError::Any("Not ready for more media data"));
}
- let Some(first_timestamp) = self.first_timestamp else {
- return Ok(());
- };
-
let audio_desc = cat::audio::StreamBasicDesc::common_f32(
frame.rate() as f64,
frame.channels() as u32,
@@ -235,13 +230,12 @@ impl MP4AVAssetWriterEncoder {
let format_desc = cm::AudioFormatDesc::with_asbd(&audio_desc)
.map_err(|_| MediaError::Any("Failed to create audio format desc"))?;
- let pts = cm::Time::new(frame.pts().unwrap_or(0), AV_TIME_BASE_Q.den);
+ let time = cm::Time::new(frame.pts().unwrap_or(0), AV_TIME_BASE_Q.den);
let pts = self
.start_time
- .add(pts)
- .sub(first_timestamp)
- .add(self.elapsed_duration);
+ .add(self.elapsed_duration)
+ .add(time.sub(self.first_timestamp.unwrap()));
let buffer = cm::SampleBuf::create(
Some(&block_buf),
diff --git a/crates/media/src/feeds/audio.rs b/crates/media/src/feeds/audio.rs
index f702789ee..f1606de94 100644
--- a/crates/media/src/feeds/audio.rs
+++ b/crates/media/src/feeds/audio.rs
@@ -176,7 +176,7 @@ impl AudioRenderer {
// this will only seek if there is a significant change in actual vs expected next sample
// (corresponding to a trim or split point). Currently this change is at least 0.2 seconds
// - not sure we offer that much precision in the editor even!
- let new_cursor = match timeline.get_segment_time(playhead) {
+ let new_cursor = match dbg!(timeline.get_segment_time(dbg!(playhead))) {
Some((segment_time, segment_i)) => AudioRendererCursor {
segment_index: segment_i,
samples: self.playhead_to_samples(segment_time),
@@ -245,7 +245,7 @@ impl AudioRenderer {
let max_samples = track_datas.iter().map(|t| t.sample_count()).min().unwrap();
if self.cursor.samples >= max_samples {
- self.elapsed_samples += max_samples;
+ self.elapsed_samples += samples;
return None;
}
diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rs
index 365b1eb49..ffdcaca13 100644
--- a/crates/media/src/sources/audio_input.rs
+++ b/crates/media/src/sources/audio_input.rs
@@ -2,6 +2,7 @@ use std::time::SystemTime;
use cap_fail::fail;
use cpal::{Device, StreamInstant, SupportedStreamConfig};
+use ffmpeg_sys_next::AV_TIME_BASE_Q;
use flume::{Receiver, Sender};
use indexmap::IndexMap;
use tracing::{error, info};
@@ -75,7 +76,10 @@ impl AudioInputSource {
.as_secs_f64()
- self.start_time;
- let frame = self.audio_info.wrap_frame(&samples.data, 0);
+ let frame = self.audio_info.wrap_frame(
+ &samples.data,
+ (elapsed.as_secs_f64() * AV_TIME_BASE_Q.den as f64) as i64,
+ );
if let Err(_) = self.tx.send((frame, timestamp)) {
return Err(MediaError::Any("Pipeline is unreachable! Stopping capture"));
}
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 89aa29b8f..bd54e7a2f 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -1,7 +1,7 @@
use cap_flags::FLAGS;
use cpal::traits::{DeviceTrait, HostTrait};
use ffmpeg::{format::Sample, frame::Audio, ChannelLayout};
-use ffmpeg_sys_next::AV_TIME_BASE_Q;
+use ffmpeg_sys_next::{AV_TIMECODE_STR_SIZE, AV_TIME_BASE_Q};
use flume::Sender;
use scap::{
capturer::{
@@ -440,6 +440,10 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
}
}
+ buffer.set_pts(Some(
+ (elapsed.as_secs_f64() * AV_TIME_BASE_Q.den as f64) as i64,
+ ));
+
if let Err(_) = video_tx.send((buffer, elapsed.as_secs_f64())) {
error!("Pipeline is unreachable. Shutting down recording.");
return Some(ControlFlow::Break(()));
@@ -450,7 +454,11 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
Ok(Frame::Audio(frame)) => {
if let Some(audio_tx) = &audio_tx {
let elapsed = frame.time().duration_since(start_time).unwrap();
- let _ = audio_tx.send((scap_audio_to_ffmpeg(frame), elapsed.as_secs_f64()));
+ let mut frame = scap_audio_to_ffmpeg(frame);
+ frame.set_pts(Some(
+ (elapsed.as_secs_f64() * AV_TIME_BASE_Q.den as f64) as i64,
+ ));
+ let _ = audio_tx.send((frame, elapsed.as_secs_f64()));
}
None
}
@@ -611,7 +619,6 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
}
}
SCStreamOutputType::Audio => {
- // println!("audio: {frame_time}");
let Some(audio_tx) = &audio_tx else {
return Some(ControlFlow::Continue(()));
};
@@ -633,7 +640,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
);
}
- frame.set_pts(Some((frame_time * AV_TIME_BASE_Q.den as f64) as i64));
+ frame.set_pts(Some((relative_time * AV_TIME_BASE_Q.den as f64) as i64));
let _ = audio_tx.send((frame, relative_time));
}
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 9c710e4c6..a4aa93d87 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -396,6 +396,7 @@ impl TimelineConfiguration {
for segment in self.segments.iter() {
if frame_time < accum_duration + segment.duration() {
+ dbg!(frame_time, accum_duration);
return segment
.interpolate_time(frame_time - accum_duration)
.map(|t| (t, segment.recording_segment));
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index ef133411f..534b0ccd6 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -18,6 +18,7 @@ use cap_media::{
};
use ffmpeg::ffi::AV_TIME_BASE_Q;
use flume::{Receiver, Sender};
+use tokio::sync::oneshot;
use tracing::error;
use crate::RecordingError;
@@ -128,13 +129,38 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
)?,
));
+ use cidre::cm;
+
+ let (first_frame_tx, mut first_frame_rx) = oneshot::channel::<(cm::Time, f64)>();
+
if has_audio_sources {
builder.spawn_source("audio_mixer", audio_mixer);
let mp4 = mp4.clone();
builder.spawn_task("audio_encoding", move |ready| {
let _ = ready.send(Ok(()));
- while let Ok(frame) = audio_rx.recv() {
+ let mut time = None;
+
+ while let Ok(mut frame) = audio_rx.recv() {
+ let pts = frame.pts().unwrap();
+
+ if let Ok(first_time) = first_frame_rx.try_recv() {
+ time = Some(first_time);
+ };
+
+ let Some(time) = time else {
+ continue;
+ };
+
+ let elapsed = (pts as f64 / AV_TIME_BASE_Q.den as f64) - time.1;
+
+ let time = time.0.add(cm::Time::new(
+ (elapsed * time.0.scale as f64 + time.1 * time.0.scale as f64) as i64,
+ time.0.scale,
+ ));
+
+ frame.set_pts(Some(time.value / (time.scale / AV_TIME_BASE_Q.den) as i64));
+
if let Ok(mut mp4) = mp4.lock() {
if let Err(e) = mp4.queue_audio_frame(frame) {
error!("{e}");
@@ -145,6 +171,7 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
});
}
+ let mut first_frame_tx = Some(first_frame_tx);
builder.spawn_task("screen_capture_encoder", move |ready| {
let _ = ready.send(Ok(()));
while let Ok((frame, unix_time)) = source.1.recv() {
@@ -155,6 +182,10 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
mp4.resume();
}
+ if let Some(first_frame_tx) = first_frame_tx.take() {
+ let _ = first_frame_tx.send((frame.pts(), unix_time));
+ }
+
mp4.queue_video_frame(frame.as_ref());
}
}
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 08dc593bf..ba1ba12f6 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -76,7 +76,7 @@ declare global {
const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']
const IconLucideChevronDown: typeof import("~icons/lucide/chevron-down.jsx")["default"]
const IconLucideClock: typeof import('~icons/lucide/clock.jsx')['default']
- const IconLucideDatabase: typeof import("~icons/lucide/database.jsx")["default"]
+ const IconLucideDatabase: typeof import('~icons/lucide/database.jsx')['default']
const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default']
const IconLucideEye: typeof import('~icons/lucide/eye.jsx')['default']
const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default']
@@ -95,8 +95,8 @@ declare global {
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']
const IconLucideUnplug: typeof import('~icons/lucide/unplug.jsx')['default']
const IconLucideVideo: typeof import("~icons/lucide/video.jsx")["default"]
- const IconLucideVolume2: typeof import("~icons/lucide/volume2.jsx")["default"]
- const IconLucideVolumeX: typeof import("~icons/lucide/volume-x.jsx")["default"]
+ const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']
+ const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']
const IconMdiMonitor: typeof import("~icons/mdi/monitor.jsx")["default"]
const IconPhMonitorBold: typeof import('~icons/ph/monitor-bold.jsx')['default']
}