Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix variable frame rate confusing ffmpeg and ensure uploads complete before exit

PJaff9b69da3f1
diff --git a/apps/desktop/src-tauri/src/media/audio.rs b/apps/desktop/src-tauri/src/media/audio.rs
index 634178e9b..2da6f9956 100644
--- a/apps/desktop/src-tauri/src/media/audio.rs
+++ b/apps/desktop/src-tauri/src/media/audio.rs
@@ -2,14 +2,14 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{Device, SampleFormat, SizedSample, Stream, SupportedStreamConfig};
use indexmap::IndexMap;
use num_traits::ToBytes;
-use std::{future::Future, path::PathBuf};
+use std::{future::Future, path::PathBuf, sync::Arc};
use tokio::sync::mpsc::error::TrySendError;
use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};
use super::{Instant, SharedFlag, SharedInstant};
use crate::utils;
-type SampleReceiver = mpsc::Receiver<Vec<u8>>;
+type SampleReceiver = mpsc::Receiver<Arc<Vec<u8>>>;
pub struct AudioCapturer {
device: Device,
@@ -103,6 +103,8 @@ impl AudioCapturer {
receiver.close();
}
}
+
+ let _ = pipe.sync_all().await;
}
}
@@ -165,16 +167,19 @@ impl AudioCapturer {
let sample_size = std::mem::size_of::<T>();
let mut bytes = vec![0; data.len() * sample_size];
+ let size = bytes.len();
for (dest, source) in bytes.chunks_exact_mut(sample_size).zip(data.iter()) {
dest.copy_from_slice(source.to_le_bytes().as_ref());
}
- match sender.try_send(bytes) {
+ let sample_data = Arc::new(bytes);
+ match sender.try_send(sample_data) {
Ok(_) => {
if let Ok(ref mut start_time_option) = first_frame_time_guard {
if start_time_option.is_none() {
**start_time_option = Some(Instant::now());
+ tracing::info!("Audio sample size: {size}");
tracing::trace!("Audio start time captured");
}
}
@@ -184,7 +189,7 @@ impl AudioCapturer {
tracing::error!("Channel buffer is full!");
}
_ => {
- tracing::info!("Recording has been stopped. Dropping data.")
+ tracing::trace!("Recording has been stopped. Dropping data.")
}
}
},
diff --git a/apps/desktop/src-tauri/src/media/mod.rs b/apps/desktop/src-tauri/src/media/mod.rs
index 31215ccae..d12ee6da2 100644
--- a/apps/desktop/src-tauri/src/media/mod.rs
+++ b/apps/desktop/src-tauri/src/media/mod.rs
@@ -11,8 +11,10 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, Command};
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
+use tracing::Level;
use crate::{
+ app::config,
recording::RecordingOptions,
utils::{create_named_pipe, ffmpeg_path_as_str},
};
@@ -59,7 +61,8 @@ pub struct MediaRecorder {
// video_capturer: Option<VideoCapturer>,
should_stop: SharedFlag,
ffmpeg_process: Option<Child>,
- ffmpeg_stdin: Option<Arc<Mutex<Option<ChildStdin>>>>,
+ // ffmpeg_stdin: Option<Arc<Mutex<Option<ChildStdin>>>>,
+ ffmpeg_stdin: Option<ChildStdin>,
device_name: Option<String>,
start_time: Option<Instant>,
audio_file_path: Option<PathBuf>,
@@ -149,18 +152,27 @@ impl MediaRecorder {
let mut ffmpeg_command = Command::new(ffmpeg_binary_path_str);
+ // Quiet ffmpeg output a bit
+ let log_level = config::logging_level();
+ if log_level == Level::DEBUG || log_level == Level::TRACE {
+ ffmpeg_command.args(["-nostats", "-hide_banner"]);
+ }
if let Some((TimeOffsetTarget::Video, args)) = &time_offset {
ffmpeg_command.args(args);
}
+ let fps = VideoCapturer::FPS.to_string();
ffmpeg_command
// video in
.args(["-f", "rawvideo", "-pix_fmt", "bgra"])
- .args(["-s", &size, "-r", "30"])
+ .args(["-s", &size, "-r", &fps])
.args(["-thread_queue_size", "4096", "-i"])
.arg(&video_pipe_path)
// video out
- .args(["-vf", "fps=30,scale=in_range=full:out_range=limited"])
+ .args([
+ "-vf",
+ &format!("fps={fps},scale=in_range=full:out_range=limited"),
+ ])
.args(["-c:v", "libx264", "-preset", "ultrafast"])
.args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
.args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
@@ -200,21 +212,12 @@ impl MediaRecorder {
tracing::trace!("Starting FFmpeg process...");
- tracing::trace!("Starting FFmpeg process...");
-
let (ffmpeg_child, ffmpeg_stdin) = self
.start_ffmpeg_process(ffmpeg_command)
.await
.map_err(|e| e.to_string())?;
tracing::trace!("Ffmpeg process started");
- if let Some(ffmpeg_stdin_mutex) = &self.ffmpeg_stdin {
- let mut stdin_lock = ffmpeg_stdin_mutex.lock().await;
- *stdin_lock = Some(ffmpeg_stdin);
- drop(stdin_lock);
- tracing::trace!("Ffmpeg stdin set");
- }
-
if self.audio_enabled {
let capturer = self.audio_capturer.as_mut().unwrap();
self.audio_pipe_task = Some(tokio::spawn(capturer.collect_samples(audio_pipe_path)));
@@ -226,6 +229,7 @@ impl MediaRecorder {
self.audio_file_path = Some(audio_chunks_dir.to_path_buf());
self.video_file_path = Some(video_chunks_dir.to_path_buf());
self.ffmpeg_process = Some(ffmpeg_child);
+ self.ffmpeg_stdin = Some(ffmpeg_stdin);
self.device_name = self.audio_capturer.as_ref().map(|c| c.device_name.clone());
tracing::info!("Media recording successfully started");
@@ -256,19 +260,28 @@ impl MediaRecorder {
tracing::info!("Video capturing stopped");
}
- if let Some(ref ffmpeg_stdin) = self.ffmpeg_stdin {
- let mut stdin_guard = ffmpeg_stdin.lock().await;
- tracing::debug!("Shutting down recording");
- if let Some(mut stdin) = stdin_guard.take() {
- if let Err(e) = stdin.write_all(b"q\n").await {
- tracing::error!("Failed to send 'q' to video FFmpeg process: {}", e);
- }
- let _ = stdin.shutdown().await.map_err(|e| e.to_string());
- }
+ if let Some(ref mut stdin) = self.ffmpeg_stdin {
+ tracing::info!("Shutting down recording");
+ stdin.shutdown().await.map_err(|e| e.to_string())?;
}
- if let Some(process) = &mut self.ffmpeg_process {
- let _ = process.kill().await.map_err(|e| e.to_string());
+ if let Some(mut process) = self.ffmpeg_process.take() {
+ tracing::info!("Writing remaining segments to disk...");
+ loop {
+ match process.try_wait() {
+ Ok(Some(_)) => {
+ tracing::info!("Successfully written all segments to disk");
+ break;
+ }
+ Ok(None) => {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+ Err(error) => {
+ tracing::error!("Couldn't check on FFmpeg process");
+ return Err(error.to_string());
+ }
+ }
+ }
}
tracing::info!("All recording stopped.");
@@ -312,8 +325,8 @@ async fn start_recording_process(
tokio::spawn(async move {
let mut process_reader = BufReader::new(process_stderr).lines();
while let Ok(Some(line)) = process_reader.next_line().await {
- // TODO: Collect this into one event. Custom implementation of Into<Stdio>?
- tracing::error!("FFmpeg process STDERR: {}", line);
+ // TODO: Replace with ingesting the output of ffmpeg's -process flag and reserve this for actual errors?
+ tracing::info!("FFmpeg process: {}", line);
}
});
}
diff --git a/apps/desktop/src-tauri/src/media/video.rs b/apps/desktop/src-tauri/src/media/video.rs
index a592ed843..37231f7a4 100644
--- a/apps/desktop/src-tauri/src/media/video.rs
+++ b/apps/desktop/src-tauri/src/media/video.rs
@@ -7,6 +7,7 @@ use scap::{
use std::{
future::Future,
path::{Path, PathBuf},
+ sync::Arc,
time::Duration,
};
use tokio::sync::mpsc::error::TrySendError;
@@ -21,13 +22,15 @@ pub struct VideoCapturer {
should_stop: SharedFlag,
pub frame_width: u32,
pub frame_height: u32,
- frame_receiver: Option<mpsc::Receiver<Vec<u8>>>,
+ frame_receiver: Option<mpsc::Receiver<Arc<Vec<u8>>>>,
}
impl VideoCapturer {
+ pub const FPS: u32 = 60;
+
pub fn new(_width: usize, _height: usize, should_stop: SharedFlag) -> VideoCapturer {
let mut capturer = Capturer::new(Options {
- fps: 60,
+ fps: Self::FPS,
target: None,
show_cursor: true,
show_highlight: true,
@@ -62,14 +65,17 @@ impl VideoCapturer {
self.frame_receiver = Some(receiver);
let screenshot_file_path = screenshot_dir.as_ref().join("screen-capture.jpg");
- let should_stop = self.should_stop.clone();
std::thread::spawn(move || {
tracing::trace!("Starting video recording capture thread...");
+ let mut frame_count = 0u32;
+ let mut last_sampled_frame_count = 0u32;
let capture_start_time = Instant::now();
+ let mut fps_sample_time = Instant::now();
let mut screenshot_captured: bool = false;
let take_screenshot_delay = Duration::from_secs(3);
+ let mut last_frame: Option<Arc<Vec<u8>>> = None;
capturer.start_capture();
@@ -79,13 +85,27 @@ impl VideoCapturer {
match capturer.get_next_frame() {
Ok(Frame::BGRA(frame)) => {
- // TODO: Check if stride needs adjusting. Implement that in scap instead of here?
let now = Instant::now();
+ let width = frame.width;
+ let height = frame.height;
+ let frame_data = match frame.width == 0 && frame.height == 0 {
+ true => match last_frame.take() {
+ Some(data) => data,
+ None => {
+ tracing::error!(
+ "Somehow got an idle frame before any complete frame"
+ );
+ continue;
+ }
+ },
+ false => Arc::new(frame.data),
+ };
+
if now - capture_start_time >= take_screenshot_delay && !screenshot_captured
{
screenshot_captured = true;
- let mut frame_data_clone = frame.data.clone();
+ let mut frame_data_clone = (*frame_data).clone();
std::thread::spawn(move || {
for chunk in frame_data_clone.chunks_mut(4) {
@@ -93,8 +113,8 @@ impl VideoCapturer {
}
let image: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(
- frame.width.try_into().unwrap(),
- frame.height.try_into().unwrap(),
+ width.try_into().unwrap(),
+ height.try_into().unwrap(),
frame_data_clone,
)
.expect("Failed to create image buffer");
@@ -139,7 +159,8 @@ impl VideoCapturer {
});
}
- match sender.try_send(frame.data) {
+ last_frame = Some(Arc::clone(&frame_data));
+ match sender.try_send(frame_data) {
Ok(_) => {
let mut first_frame_time_guard = start_time.try_lock();
@@ -156,10 +177,11 @@ impl VideoCapturer {
tracing::error!("Channel buffer is full!");
}
_ => {
- tracing::info!("Recording has been stopped. Dropping data.");
+ tracing::trace!("Recording has been stopped. Dropping data.");
break;
}
}
+ frame_count += 1;
}
Ok(_) => unreachable!(),
Err(error) => {
@@ -167,6 +189,18 @@ impl VideoCapturer {
break;
}
}
+
+ let elapsed_time = fps_sample_time.elapsed();
+ let elapsed_total_time = capture_start_time.elapsed();
+ if elapsed_time > Duration::from_millis(1500) {
+ let delta_frame_count = frame_count - last_sampled_frame_count;
+ let current_fps = (delta_frame_count as f64) / elapsed_time.as_secs_f64();
+ let total_fps = (frame_count as f64) / elapsed_total_time.as_secs_f64();
+
+ last_sampled_frame_count = frame_count;
+ fps_sample_time = Instant::now();
+ tracing::info!("🏁🏁 Current FPS: {current_fps}, Total FPS: {total_fps}");
+ }
}
});
}
@@ -191,6 +225,8 @@ impl VideoCapturer {
receiver.close();
}
}
+
+ let _ = pipe.sync_all().await;
}
}
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 0cfa5a281..2d235c27f 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -139,10 +139,6 @@ pub async fn stop_all_recordings(
) -> Result<(), String> {
let mut guard = state.lock().await;
- tracing::info!("Stopping media recording...");
-
- guard.shutdown_flag.store(true, Ordering::SeqCst);
-
if let Some(mut media_process) = guard.media_process.take() {
tracing::info!("Stopping media recording...");
media_process
@@ -151,6 +147,8 @@ pub async fn stop_all_recordings(
.expect("Failed to stop media recording");
}
+ guard.shutdown_flag.store(true, Ordering::SeqCst);
+
if !config::is_local_mode() {
while !guard.video_uploading_finished.load(Ordering::SeqCst)
|| !guard.audio_uploading_finished.load(Ordering::SeqCst)