Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve video muxing and camera error handling

Richie McIlroy383d2a65b391
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index b68eb5ad2..c91af5e67 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -429,7 +429,7 @@ async fn setup_muxer<TMuxer: Muxer>(
fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: VideoSource>(
setup_ctx: &mut SetupCtx,
mut video_source: TVideo,
- mut video_rx: mpsc::Receiver<TVideo::Frame>,
+ video_rx: mpsc::Receiver<TVideo::Frame>,
first_tx: oneshot::Sender<Timestamp>,
stop_token: CancellationToken,
muxer: Arc<Mutex<TMutex>>,
@@ -450,34 +450,53 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
}
});
- setup_ctx.tasks().spawn("mux-video", async move {
- use futures::StreamExt;
-
- let mut first_tx = Some(first_tx);
+ setup_ctx.tasks().spawn("mux-video", {
+ let stop_token_on_close = stop_token.clone();
+ async move {
+ use futures::StreamExt;
- stop_token
- .run_until_cancelled(async {
- while let Some(frame) = video_rx.next().await {
- let timestamp = frame.timestamp();
+ let mut first_tx = Some(first_tx);
+ let cancelled = stop_token.cancelled_owned();
+ tokio::pin!(cancelled);
+ let mut video_rx = video_rx.fuse();
- if let Some(first_tx) = first_tx.take() {
- let _ = first_tx.send(timestamp);
+ loop {
+ tokio::select! {
+ _ = &mut cancelled => {
+ break;
+ }
+ maybe_frame = video_rx.next() => {
+ match maybe_frame {
+ Some(frame) => {
+ let timestamp = frame.timestamp();
+
+ if let Some(first_tx) = first_tx.take() {
+ let _ = first_tx.send(timestamp);
+ }
+
+ muxer
+ .lock()
+ .await
+ .send_video_frame(frame, timestamp.duration_since(timestamps))
+ .map_err(|e| anyhow!("Error queueing video frame: {e}"))?;
+ }
+ None => {
+ warn!(
+ video_source = %std::any::type_name::<TVideo>(),
+ "Video mux channel closed before cancellation; cancelling pipeline"
+ );
+ stop_token_on_close.cancel();
+ break;
+ }
+ }
}
-
- muxer
- .lock()
- .await
- .send_video_frame(frame, timestamp.duration_since(timestamps))
- .map_err(|e| anyhow!("Error queueing video frame: {e}"))?;
}
+ }
- Ok::<(), anyhow::Error>(())
- })
- .await;
-
- muxer.lock().await.stop();
+ muxer.lock().await.stop();
- Ok(())
+ Ok(())
+ }
});
}
diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rs
index 8453479de..a54336577 100644
--- a/crates/recording/src/output_pipeline/ffmpeg.rs
+++ b/crates/recording/src/output_pipeline/ffmpeg.rs
@@ -28,6 +28,8 @@ pub struct Mp4Muxer {
output: ffmpeg::format::context::Output,
video_encoder: Option<H264Encoder>,
audio_encoder: Option<AACEncoder>,
+ video_frame_duration: Option<Duration>,
+ last_video_ts: Option<Duration>,
}
impl Muxer for Mp4Muxer {
@@ -46,10 +48,16 @@ impl Muxer for Mp4Muxer {
{
let mut output = ffmpeg::format::output(&output_path)?;
- let video_encoder = video_config
- .map(|video_config| H264Encoder::builder(video_config).build(&mut output))
- .transpose()
- .context("video encoder")?;
+ let (video_encoder, video_frame_duration) = match video_config {
+ Some(config) => {
+ let duration = Self::frame_duration(&config);
+ let encoder = H264Encoder::builder(config)
+ .build(&mut output)
+ .context("video encoder")?;
+ (Some(encoder), Some(duration))
+ }
+ None => (None, None),
+ };
let audio_encoder = audio_config
.map(|config| AACEncoder::init(config, &mut output))
@@ -62,6 +70,8 @@ impl Muxer for Mp4Muxer {
output,
video_encoder,
audio_encoder,
+ video_frame_duration,
+ last_video_ts: None,
})
}
@@ -96,9 +106,19 @@ impl VideoMuxer for Mp4Muxer {
fn send_video_frame(
&mut self,
frame: Self::VideoFrame,
- timestamp: Duration,
+ mut timestamp: Duration,
) -> anyhow::Result<()> {
if let Some(video_encoder) = self.video_encoder.as_mut() {
+ if let Some(frame_duration) = self.video_frame_duration {
+ if let Some(last_ts) = self.last_video_ts {
+ if timestamp <= last_ts {
+ timestamp = last_ts + frame_duration;
+ }
+ }
+
+ self.last_video_ts = Some(timestamp);
+ }
+
video_encoder.queue_frame(frame.inner, timestamp, &mut self.output)?;
}
@@ -106,6 +126,17 @@ impl VideoMuxer for Mp4Muxer {
}
}
+impl Mp4Muxer {
+ fn frame_duration(info: &VideoInfo) -> Duration {
+ let num = info.frame_rate.numerator().max(1);
+ let den = info.frame_rate.denominator().max(1);
+
+ let nanos = ((den as u128 * 1_000_000_000u128) / num as u128).max(1);
+
+ Duration::from_nanos(nanos as u64)
+ }
+}
+
impl AudioMuxer for Mp4Muxer {
fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {
if let Some(audio_encoder) = self.audio_encoder.as_mut() {
diff --git a/crates/recording/src/sources/camera.rs b/crates/recording/src/sources/camera.rs
index 48daae8e3..f26a8c5f5 100644
--- a/crates/recording/src/sources/camera.rs
+++ b/crates/recording/src/sources/camera.rs
@@ -7,6 +7,7 @@ use anyhow::anyhow;
use cap_media_info::VideoInfo;
use futures::{SinkExt, channel::mpsc};
use std::sync::Arc;
+use tracing::{error, warn};
pub struct Camera(Arc<CameraFeedLock>);
@@ -29,9 +30,37 @@ impl VideoSource for Camera {
.await
.map_err(|e| anyhow!("Failed to add camera sender: {e}"))?;
- tokio::spawn(async move {
- while let Ok(frame) = rx.recv_async().await {
- let _ = video_tx.send(frame).await;
+ tokio::spawn({
+ let feed_lock = feed_lock.clone();
+ async move {
+ let mut receiver = rx;
+
+ loop {
+ match receiver.recv_async().await {
+ Ok(frame) => {
+ if let Err(err) = video_tx.send(frame).await {
+ error!(
+ ?err,
+ "Camera pipeline receiver dropped; stopping camera forwarding"
+ );
+ break;
+ }
+ }
+ Err(_) => {
+ let (tx, new_rx) = flume::bounded(8);
+
+ if let Err(err) = feed_lock.ask(camera::AddSender(tx)).await {
+ warn!(
+ ?err,
+ "Camera sender disconnected and could not be reattached"
+ );
+ break;
+ }
+
+ receiver = new_rx;
+ }
+ }
+ }
}
});