Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(recording): finalize static captures and stream instant segments

Richie McIlroye390c42bd142
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index 9355b084f..35151b2c6 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -386,6 +386,7 @@ impl MakeCapturePipeline for screen_capture::X11Capture {
},
output_size,
shared_pause_state,
+ segment_tx: None,
})
.await
}
@@ -395,7 +396,7 @@ impl MakeCapturePipeline for screen_capture::X11Capture {
segments_dir: PathBuf,
output_size: (u32, u32),
start_time: Timestamps,
- _segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
) -> anyhow::Result<OutputPipeline> {
OutputPipeline::builder(segments_dir)
.with_video::<screen_capture::VideoSource>(screen_capture)
@@ -405,6 +406,7 @@ impl MakeCapturePipeline for screen_capture::X11Capture {
preset: H264Preset::Ultrafast,
output_size: Some(output_size),
shared_pause_state: None,
+ segment_tx,
})
.await
}
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 91355fbf6..b02ec1396 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -2048,6 +2048,15 @@ fn estimate_video_frame_duration_ns(video_info: &VideoInfo) -> u64 {
1_000_000_000 / fps as u64
}
+fn static_video_tail_timestamp(
+ last_timestamp: Duration,
+ stopped_at: Duration,
+ frame_duration: Duration,
+) -> Option<Duration> {
+ let final_timestamp = stopped_at.saturating_sub(frame_duration);
+ (final_timestamp > last_timestamp.saturating_add(frame_duration)).then_some(final_timestamp)
+}
+
/// Span of the video timestamps actually sent to the muxer, used to report
/// the real encoded media duration. Capture is VFR (static screens, dropped
/// frames), so `frame_count / fps` under-reports the duration by the length
@@ -2131,6 +2140,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
let mut drift_tracker = VideoDriftTracker::new();
let mut source_clock = SourceClockState::new("video");
let mut dropped_during_pause: u64 = 0;
+ let mut last_frame = None;
let res = stop_token
.run_until_cancelled(async {
@@ -2224,9 +2234,11 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
);
}
+ let duplicate = frame.duplicate();
if let Err(e) = muxer.lock().await.send_video_frame(frame, duration) {
return Err(video_mux_send_error(frame_count, e));
}
+ last_frame = duplicate;
}
info!("mux-video stream ended (rx closed)");
@@ -2235,6 +2247,10 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
.await;
let was_cancelled = res.is_none();
+ let stopped_at = timestamps
+ .instant()
+ .elapsed()
+ .saturating_sub(shared_pause.total_pause_duration());
if was_cancelled {
info!("mux-video cancelled, draining remaining frames from channel");
@@ -2309,8 +2325,9 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
drift_tracker.calculate_timestamp(raw_duration, wall_clock_elapsed);
timestamp_span.record(duration);
+ let duplicate = frame.duplicate();
match muxer.lock().await.send_video_frame(frame, duration) {
- Ok(()) => {}
+ Ok(()) => last_frame = duplicate,
Err(e) => {
warn!("Error processing drained frame: {e}");
skipped += 1;
@@ -2343,6 +2360,39 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
let final_pause_duration = shared_pause.total_pause_duration();
+ if was_cancelled
+ && !shared_pause.check().0
+ && let Some(mut frame) = last_frame
+ && let Some((_, last_timestamp)) = timestamp_span.get()
+ && let Some(final_timestamp) = static_video_tail_timestamp(
+ last_timestamp,
+ stopped_at,
+ Duration::from_nanos(frame_duration_ns),
+ )
+ {
+ let penultimate_timestamp =
+ final_timestamp.saturating_sub(Duration::from_nanos(frame_duration_ns));
+ if penultimate_timestamp > last_timestamp
+ && let Some(final_frame) = frame.duplicate()
+ {
+ muxer
+ .lock()
+ .await
+ .send_video_frame(frame, penultimate_timestamp)
+ .map_err(|error| video_mux_send_error(frame_count + 1, error))?;
+ timestamp_span.record(penultimate_timestamp);
+ frame_count += 1;
+ frame = final_frame;
+ }
+ muxer
+ .lock()
+ .await
+ .send_video_frame(frame, final_timestamp)
+ .map_err(|error| video_mux_send_error(frame_count + 1, error))?;
+ timestamp_span.record(final_timestamp);
+ frame_count += 1;
+ }
+
if dropped_during_pause > 0 {
debug!(
dropped_during_pause,
@@ -3383,6 +3433,13 @@ pub trait AudioSource: Send + 'static {
pub trait VideoFrame: Send + 'static {
fn timestamp(&self) -> Timestamp;
+
+ fn duplicate(&self) -> Option<Self>
+ where
+ Self: Sized,
+ {
+ None
+ }
}
pub trait Muxer: Send + 'static {
@@ -5044,6 +5101,107 @@ mod tests {
}
}
+ mod static_video_finalization {
+ use super::*;
+
+ #[derive(Clone, Copy)]
+ struct StaticFrame {
+ timestamp: Timestamp,
+ }
+
+ impl VideoFrame for StaticFrame {
+ fn timestamp(&self) -> Timestamp {
+ self.timestamp
+ }
+
+ fn duplicate(&self) -> Option<Self> {
+ Some(*self)
+ }
+ }
+
+ struct ObservedMuxer {
+ timestamps: Arc<std::sync::Mutex<Vec<Duration>>>,
+ }
+
+ impl Muxer for ObservedMuxer {
+ type Config = Arc<std::sync::Mutex<Vec<Duration>>>;
+
+ async fn setup(
+ timestamps: Self::Config,
+ _output_path: PathBuf,
+ _video_config: Option<VideoInfo>,
+ _audio_config: Option<AudioInfo>,
+ _pause_flag: Arc<AtomicBool>,
+ _tasks: &mut TaskPool,
+ ) -> anyhow::Result<Self> {
+ Ok(Self { timestamps })
+ }
+
+ fn finish(&mut self, _timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
+ Ok(Ok(()))
+ }
+ }
+
+ impl VideoMuxer for ObservedMuxer {
+ type VideoFrame = StaticFrame;
+
+ fn send_video_frame(
+ &mut self,
+ _frame: Self::VideoFrame,
+ timestamp: Duration,
+ ) -> anyhow::Result<()> {
+ self.timestamps.lock().unwrap().push(timestamp);
+ Ok(())
+ }
+ }
+
+ impl AudioMuxer for ObservedMuxer {
+ fn send_audio_frame(
+ &mut self,
+ _frame: AudioFrame,
+ _timestamp: Duration,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+ }
+
+ #[tokio::test]
+ async fn static_capture_finishes_with_two_nominally_spaced_frames() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let clock = Timestamps::now();
+ let (sender, receiver) = flume::bounded(4);
+ let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let pipeline = OutputPipeline::builder(temp_dir.path().join("static.mp4"))
+ .with_video::<ChannelVideoSource<StaticFrame>>(ChannelVideoSourceConfig::new(
+ VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 16, 16, 30),
+ receiver,
+ ))
+ .with_timestamps(clock)
+ .build::<ObservedMuxer>(sent.clone())
+ .await
+ .unwrap();
+
+ sender
+ .send_async(StaticFrame {
+ timestamp: Timestamp::Instant(clock.instant()),
+ })
+ .await
+ .unwrap();
+ tokio::time::sleep(Duration::from_millis(180)).await;
+ pipeline.stop().await.unwrap();
+
+ let timestamps = sent.lock().unwrap().clone();
+ assert_eq!(timestamps.len(), 3);
+ let final_frame = timestamps[timestamps.len() - 1];
+ let penultimate_frame = timestamps[timestamps.len() - 2];
+ assert_eq!(
+ final_frame.saturating_sub(penultimate_frame),
+ Duration::from_nanos(33_333_333)
+ );
+ assert!(final_frame > Duration::from_millis(100));
+ }
+ }
+
mod blocking_thread_finish {
use super::*;
@@ -6205,5 +6363,41 @@ mod tests {
assert_eq!(first, Duration::from_millis(100));
assert_eq!(last, Duration::from_millis(4000));
}
+
+ #[test]
+ fn static_video_tail_covers_the_final_capture_gap() {
+ assert_eq!(
+ static_video_tail_timestamp(
+ Duration::from_millis(80),
+ Duration::from_secs(3),
+ Duration::from_millis(16),
+ ),
+ Some(Duration::from_millis(2984))
+ );
+ }
+
+ #[test]
+ fn active_video_does_not_gain_a_redundant_tail_frame() {
+ assert_eq!(
+ static_video_tail_timestamp(
+ Duration::from_millis(2980),
+ Duration::from_secs(3),
+ Duration::from_millis(16),
+ ),
+ None
+ );
+ }
+
+ #[test]
+ fn video_tail_never_precedes_the_last_frame() {
+ assert_eq!(
+ static_video_tail_timestamp(
+ Duration::from_millis(100),
+ Duration::from_millis(10),
+ Duration::from_millis(16),
+ ),
+ None
+ );
+ }
}
}
diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rs
index 00d176d5a..f2527586e 100644
--- a/crates/recording/src/output_pipeline/ffmpeg.rs
+++ b/crates/recording/src/output_pipeline/ffmpeg.rs
@@ -39,6 +39,15 @@ impl VideoFrame for FFmpegVideoFrame {
fn timestamp(&self) -> Timestamp {
self.timestamp
}
+
+ fn duplicate(&self) -> Option<Self> {
+ let mut inner = ffmpeg::frame::Video::empty();
+ let status = unsafe { ffmpeg::ffi::av_frame_ref(inner.as_mut_ptr(), self.inner.as_ptr()) };
+ (status >= 0).then_some(Self {
+ inner,
+ timestamp: self.timestamp,
+ })
+ }
}
pub struct Mp4Muxer {
@@ -414,6 +423,7 @@ pub struct SegmentedVideoMuxer {
segment_duration: Duration,
preset: H264Preset,
output_size: Option<(u32, u32)>,
+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
state: Option<SegmentedEncoderState>,
pause: SharedPauseState,
frame_drops: FrameDropTracker,
@@ -425,6 +435,7 @@ pub struct SegmentedVideoMuxerConfig {
pub preset: H264Preset,
pub output_size: Option<(u32, u32)>,
pub shared_pause_state: Option<SharedPauseState>,
+ pub segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
}
impl Default for SegmentedVideoMuxerConfig {
@@ -434,6 +445,7 @@ impl Default for SegmentedVideoMuxerConfig {
preset: H264Preset::Ultrafast,
output_size: None,
shared_pause_state: None,
+ segment_tx: None,
}
}
}
@@ -468,6 +480,7 @@ impl Muxer for SegmentedVideoMuxer {
segment_duration: config.segment_duration,
preset: config.preset,
output_size: config.output_size,
+ segment_tx: config.segment_tx,
state: None,
pause,
frame_drops: FrameDropTracker::new(),
@@ -584,8 +597,11 @@ impl SegmentedVideoMuxer {
};
let slow_threshold_ms = frame_timing_log_threshold_ms(&self.video_config);
- let encoder =
+ let mut encoder =
SegmentedVideoEncoder::init(self.base_path.clone(), self.video_config, encoder_config)?;
+ if let Some(tx) = &self.segment_tx {
+ encoder.set_segment_callback(tx.clone());
+ }
let encoder = Arc::new(Mutex::new(encoder));
let encoder_clone = encoder.clone();
@@ -804,3 +820,43 @@ impl AudioMuxer for DashSegmentedAudioMuxer {
.map_err(|e| anyhow!("Failed to queue audio frame: {e}"))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::{FFmpegVideoFrame, VideoFrame};
+ use cap_timestamp::Timestamp;
+ use std::time::Instant;
+
+ #[test]
+ fn duplicated_video_frame_reuses_reference_counted_pixel_storage() {
+ let timestamp = Instant::now();
+ let mut inner = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 16, 12);
+ inner.set_pts(Some(417));
+ inner.data_mut(0)[..4].copy_from_slice(&[11, 22, 33, 44]);
+ let original = FFmpegVideoFrame {
+ inner,
+ timestamp: Timestamp::Instant(timestamp),
+ };
+
+ let duplicate = original.duplicate().expect("reference-counted video frame");
+
+ assert_eq!(
+ duplicate.inner.data(0).as_ptr(),
+ original.inner.data(0).as_ptr()
+ );
+ assert_eq!(duplicate.inner.format(), original.inner.format());
+ assert_eq!(duplicate.inner.width(), original.inner.width());
+ assert_eq!(duplicate.inner.height(), original.inner.height());
+ assert_eq!(duplicate.inner.pts(), Some(417));
+ assert!(matches!(duplicate.timestamp, Timestamp::Instant(value) if value == timestamp));
+ let buffer = unsafe { (*original.inner.as_ptr()).buf[0] };
+ assert!(!buffer.is_null());
+ assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(buffer) }, 2);
+
+ drop(original);
+
+ assert_eq!(&duplicate.inner.data(0)[..4], &[11, 22, 33, 44]);
+ let retained = unsafe { (*duplicate.inner.as_ptr()).buf[0] };
+ assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(retained) }, 1);
+ }
+}
diff --git a/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs b/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
index 46aa90a0f..50c5eaa44 100644
--- a/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
+++ b/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
@@ -6,6 +6,7 @@ use super::oop_muxer::{
MuxerSubprocessConfig, MuxerSubprocessError, RespawningMuxerSubprocess, VideoStreamInit,
resolve_muxer_binary,
};
+use super::win::reference_video_frame;
use crate::{
AudioFrame, AudioMuxer, Muxer, SharedPauseState, TaskPool, VideoMuxer, screen_capture,
};
@@ -465,7 +466,7 @@ impl WindowsOOPFragmentedM4SMuxer {
let (ffmpeg_frame, timestamp) = match video_rx.recv_timeout(frame_interval) {
Ok(Some((frame, ts))) => match frame.as_ffmpeg() {
Ok(f) => {
- last_ffmpeg_frame = Some(f.clone());
+ last_ffmpeg_frame = Some(reference_video_frame(&f));
last_timestamp = Some(ts);
(Some(f), ts)
}
@@ -476,7 +477,7 @@ impl WindowsOOPFragmentedM4SMuxer {
let new_ts = last_ts.saturating_add(frame_interval);
last_timestamp = Some(new_ts);
duplicated_frames += 1;
- (Some(f.clone()), new_ts)
+ (Some(reference_video_frame(f)), new_ts)
}
_ => (None, Duration::ZERO),
}
@@ -524,7 +525,7 @@ impl WindowsOOPFragmentedM4SMuxer {
let new_ts = last_ts.saturating_add(frame_interval);
last_timestamp = Some(new_ts);
duplicated_frames += 1;
- (Some(f.clone()), new_ts)
+ (Some(reference_video_frame(f)), new_ts)
}
_ => continue,
}
@@ -714,3 +715,28 @@ impl AudioMuxer for WindowsOOPFragmentedM4SMuxer {
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::reference_video_frame;
+
+ #[test]
+ fn out_of_process_fragment_frames_reuse_reference_counted_pixels() {
+ let mut original = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 16, 12);
+ original.set_pts(Some(173));
+ original.data_mut(0)[0] = 84;
+ let retained = reference_video_frame(&original);
+ let replay = reference_video_frame(&retained);
+
+ assert_eq!(retained.data(0).as_ptr(), original.data(0).as_ptr());
+ assert_eq!(replay.data(0).as_ptr(), original.data(0).as_ptr());
+ assert_eq!(replay.pts(), Some(173));
+ let buffer = unsafe { (*original.as_ptr()).buf[0] };
+ assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(buffer) }, 3);
+
+ drop(original);
+ drop(retained);
+
+ assert_eq!(replay.data(0)[0], 84);
+ }
+}
diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs
index d7c7831c9..f291851c3 100644
--- a/crates/recording/src/output_pipeline/win.rs
+++ b/crates/recording/src/output_pipeline/win.rs
@@ -28,6 +28,17 @@ fn get_muxer_buffer_size() -> usize {
.unwrap_or(DEFAULT_MUXER_BUFFER_SIZE)
}
+pub(super) fn reference_video_frame(frame: &ffmpeg::frame::Video) -> ffmpeg::frame::Video {
+ let mut reference = ffmpeg::frame::Video::empty();
+ let status = unsafe { ffmpeg::ffi::av_frame_ref(reference.as_mut_ptr(), frame.as_ptr()) };
+
+ if status >= 0 {
+ reference
+ } else {
+ frame.clone()
+ }
+}
+
struct FrameDropTracker {
drops_in_window: u32,
frames_in_window: u32,
@@ -185,13 +196,13 @@ impl Muxer for WindowsMuxer {
let encoder = (|| {
let fallback = |reason: Option<String>| {
- use tracing::{error, info};
+ use tracing::{info, warn};
encoder_preferences.force_software_only();
if let Some(reason) = reason.as_ref() {
- error!("Falling back to software H264 encoder: {reason}");
+ warn!(%reason, "Media Foundation H264 unavailable; using FFmpeg");
} else {
- info!("Falling back to software H264 encoder");
+ info!("Using FFmpeg H264 encoder");
}
let fallback_width = if output_size.Width > 0 {
@@ -222,7 +233,12 @@ impl Muxer for WindowsMuxer {
.map_err(|e| anyhow!("ScreenSoftwareEncoder/{e}"))
};
- if encoder_preferences.should_force_software() {
+ if encoder_preferences.should_force_software()
+ || matches!(
+ cap_frame_converter::detect_primary_gpu().map(|gpu| gpu.vendor),
+ Some(cap_frame_converter::GpuVendor::Amd)
+ )
+ {
return fallback(None);
}
@@ -421,7 +437,7 @@ impl Muxer for WindowsMuxer {
}
}
either::Right(mut encoder) => {
- trace!("Running software encoder with frame pacing");
+ trace!("Running FFmpeg encoder with frame pacing");
let frame_interval = Duration::from_secs_f64(1.0 / config.frame_rate as f64);
let mut last_ffmpeg_frame: Option<ffmpeg::frame::Video> = None;
let mut first_timestamp: Option<Duration> = None;
@@ -433,12 +449,17 @@ impl Muxer for WindowsMuxer {
last_timestamp = Some(timestamp);
match frame.as_ffmpeg() {
Ok(f) => {
- last_ffmpeg_frame = Some(f.clone());
+ last_ffmpeg_frame = Some(reference_video_frame(&f));
(Some(f), timestamp)
}
Err(e) => {
warn!("Failed to convert frame: {e:?}");
- (last_ffmpeg_frame.clone(), timestamp)
+ (
+ last_ffmpeg_frame
+ .as_ref()
+ .map(reference_video_frame),
+ timestamp,
+ )
}
}
}
@@ -451,7 +472,12 @@ impl Muxer for WindowsMuxer {
if let Some(last_ts) = last_timestamp {
let new_ts = last_ts.saturating_add(frame_interval);
last_timestamp = Some(new_ts);
- (last_ffmpeg_frame.clone(), new_ts)
+ (
+ last_ffmpeg_frame
+ .as_ref()
+ .map(reference_video_frame),
+ new_ts,
+ )
} else {
continue;
}
@@ -531,6 +557,53 @@ impl Muxer for WindowsMuxer {
}
}
+#[cfg(test)]
+mod tests {
+ use super::reference_video_frame;
+
+ #[test]
+ fn retained_software_frame_shares_pixels_and_survives_original() {
+ let mut original = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 16, 12);
+ original.set_pts(Some(417));
+ original.data_mut(0)[..4].copy_from_slice(&[11, 22, 33, 44]);
+
+ let retained = reference_video_frame(&original);
+
+ assert_eq!(retained.data(0).as_ptr(), original.data(0).as_ptr());
+ assert_eq!(retained.format(), original.format());
+ assert_eq!(retained.width(), original.width());
+ assert_eq!(retained.height(), original.height());
+ assert_eq!(retained.pts(), Some(417));
+ let buffer = unsafe { (*original.as_ptr()).buf[0] };
+ assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(buffer) }, 2);
+
+ drop(original);
+
+ assert_eq!(&retained.data(0)[..4], &[11, 22, 33, 44]);
+ let retained_buffer = unsafe { (*retained.as_ptr()).buf[0] };
+ assert_eq!(
+ unsafe { ffmpeg::ffi::av_buffer_get_ref_count(retained_buffer) },
+ 1
+ );
+ }
+
+ #[test]
+ fn repeated_static_software_frames_reuse_retained_pixels() {
+ let original = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 16, 12);
+ let retained = reference_video_frame(&original);
+ let pointer = retained.data(0).as_ptr();
+ let buffer = unsafe { (*retained.as_ptr()).buf[0] };
+
+ for _ in 0..8 {
+ let replay = reference_video_frame(&retained);
+ assert_eq!(replay.data(0).as_ptr(), pointer);
+ assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(buffer) }, 3);
+ drop(replay);
+ assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(buffer) }, 2);
+ }
+ }
+}
+
impl VideoMuxer for WindowsMuxer {
type VideoFrame = screen_capture::VideoFrame;
@@ -739,11 +812,9 @@ impl Muxer for WindowsCameraMuxer {
let fallback = |reason: Option<String>| {
encoder_preferences.force_software_only();
if let Some(reason) = reason.as_ref() {
- error!(
- "Falling back to software H264 encoder for camera: {reason}"
- );
+ warn!(%reason, "Media Foundation camera H264 unavailable; using FFmpeg");
} else {
- info!("Using software H264 encoder for camera");
+ info!("Using FFmpeg H264 encoder for camera");
}
let mut output_guard = match output.lock() {
@@ -763,7 +834,12 @@ impl Muxer for WindowsCameraMuxer {
.map_err(|e| anyhow!("CameraSoftwareEncoder/{e}"))
};
- if encoder_preferences.should_force_software() {
+ if encoder_preferences.should_force_software()
+ || matches!(
+ cap_frame_converter::detect_primary_gpu().map(|gpu| gpu.vendor),
+ Some(cap_frame_converter::GpuVendor::Amd)
+ )
+ {
return fallback(None);
}
@@ -963,7 +1039,7 @@ impl Muxer for WindowsCameraMuxer {
}
either::Right(mut encoder) => {
info!(
- "Windows camera encoder started (software) with frame pacing: {}x{} -> {}x{} @ {}fps",
+ "Windows camera encoder started (FFmpeg) with frame pacing: {}x{} -> {}x{} @ {}fps",
video_config.width,
video_config.height,
output_width,
@@ -1037,14 +1113,14 @@ impl Muxer for WindowsCameraMuxer {
frame_count += 1;
if frame_count.is_multiple_of(30) {
debug!(
- "Windows camera encoder (software): processed {} frames",
+ "Windows camera encoder (FFmpeg): processed {} frames",
frame_count
);
}
}
info!(
- "Windows camera encoder finished (software): {} frames encoded",
+ "Windows camera encoder finished (FFmpeg): {} frames encoded",
frame_count
);
Ok(())
diff --git a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs
index 4fec3ba9f..208ab9f4e 100644
--- a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs
+++ b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs
@@ -2,6 +2,7 @@ use super::core::{
BlockingThreadFinish, DiskSpaceMonitor, HealthSender, PipelineHealthEvent, SharedHealthSender,
combine_finish_errors, wait_for_blocking_thread_finish,
};
+use super::win::reference_video_frame;
use crate::{
AudioFrame, AudioMuxer, Muxer, SharedPauseState, TaskPool, VideoMuxer,
output_pipeline::{NativeCameraFrame, camera_frame_to_ffmpeg},
@@ -438,7 +439,7 @@ impl WindowsFragmentedM4SMuxer {
let (ffmpeg_frame, timestamp) = match video_rx.recv_timeout(frame_interval) {
Ok(Some((frame, ts))) => match frame.as_ffmpeg() {
Ok(f) => {
- last_ffmpeg_frame = Some(f.clone());
+ last_ffmpeg_frame = Some(reference_video_frame(&f));
last_timestamp = Some(ts);
(Some(f), ts)
}
@@ -449,7 +450,7 @@ impl WindowsFragmentedM4SMuxer {
let new_ts = last_ts.saturating_add(frame_interval);
last_timestamp = Some(new_ts);
duplicated_frames += 1;
- (Some(f.clone()), new_ts)
+ (Some(reference_video_frame(f)), new_ts)
}
_ => (None, Duration::ZERO),
}
@@ -500,7 +501,7 @@ impl WindowsFragmentedM4SMuxer {
let new_ts = last_ts.saturating_add(frame_interval);
last_timestamp = Some(new_ts);
duplicated_frames += 1;
- (Some(f.clone()), new_ts)
+ (Some(reference_video_frame(f)), new_ts)
}
_ => continue,
}
@@ -1088,3 +1089,28 @@ impl AudioMuxer for WindowsFragmentedM4SCameraMuxer {
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::reference_video_frame;
+
+ #[test]
+ fn instant_fragment_frames_reuse_reference_counted_pixels() {
+ let mut original = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 16, 12);
+ original.set_pts(Some(91));
+ original.data_mut(0)[0] = 63;
+ let retained = reference_video_frame(&original);
+ let replay = reference_video_frame(&retained);
+
+ assert_eq!(retained.data(0).as_ptr(), original.data(0).as_ptr());
+ assert_eq!(replay.data(0).as_ptr(), original.data(0).as_ptr());
+ assert_eq!(replay.pts(), Some(91));
+ let buffer = unsafe { (*original.as_ptr()).buf[0] };
+ assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(buffer) }, 3);
+
+ drop(original);
+ drop(retained);
+
+ assert_eq!(replay.data(0)[0], 63);
+ }
+}
diff --git a/crates/recording/tests/sync_matrix.rs b/crates/recording/tests/sync_matrix.rs
index 882ee3ade..8df7dc0ef 100644
--- a/crates/recording/tests/sync_matrix.rs
+++ b/crates/recording/tests/sync_matrix.rs
@@ -29,6 +29,7 @@ use cap_timestamp::{Timestamp, Timestamps};
use serde::{Deserialize, Serialize};
const CONTENT_SECS: f64 = 4.0;
+const MAX_PRODUCTION_CAPTURE_FPS: u32 = 240;
/// Absolute tolerance for a muxed pts vs the sent capture timestamp,
/// measured from each side's own origin (first sent frame vs first muxed
/// pts). Covers warmup anchoring, emission jitter and encoder rounding,
@@ -241,6 +242,11 @@ impl VideoCase {
}
}
+fn minimum_overload_coverage(delivered_fps: u32) -> f64 {
+ 0.9 * f64::from(MAX_PRODUCTION_CAPTURE_FPS)
+ / f64::from(delivered_fps.max(MAX_PRODUCTION_CAPTURE_FPS))
+}
+
async fn run_video_case(case: VideoCase) -> Result<String, String> {
let temp = tempfile::tempdir().map_err(|e| format!("tempdir: {e}"))?;
let out_path = if case.fragmented {
@@ -277,7 +283,7 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
// exist to verify drop handling, not consumer throughput: a weak
// runner saturated by the firehose proves nothing, so send blocking
// still counts as falling behind there and earns a loud skip.
- let overload_case = case.delivered_fps > 240;
+ let overload_case = case.delivered_fps > MAX_PRODUCTION_CAPTURE_FPS;
tokio::spawn(async move {
let mut max_late = 0.0f64;
let mut last_send_end: Option<std::time::Instant> = None;
@@ -391,9 +397,10 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
// cannot real-time-encode several hundred fps of worst-case content.
// Timestamp correctness is still enforced below on every frame that
// was muxed; extra frames or heavy loss always fail.
- let overload_case = case.delivered_fps > 240;
+ let overload_case = case.delivered_fps > MAX_PRODUCTION_CAPTURE_FPS;
let coverage = pts.len() as f64 / sent.len() as f64;
- if !overload_case || coverage < 0.9 || pts.len() > sent.len() {
+ let minimum_coverage = minimum_overload_coverage(case.delivered_fps);
+ if !overload_case || coverage < minimum_coverage || pts.len() > sent.len() {
return Err(format!(
"frame count mismatch: sent {} frames, container has {} \
(missing sent indices: {})",
@@ -1433,6 +1440,15 @@ fn report_chunk_ms_only_trusts_a_narrow_buffer_range() {
assert_eq!(report_chunk_ms(0, Some((480, 960))), 20.0);
}
+#[test]
+fn overload_coverage_preserves_supported_capture_throughput() {
+ assert!((minimum_overload_coverage(240) - 0.9).abs() < f64::EPSILON);
+ assert!((minimum_overload_coverage(480) - 0.45).abs() < f64::EPSILON);
+ assert!((minimum_overload_coverage(1_000) - 0.216).abs() < f64::EPSILON);
+ assert!(1620.0 / 3298.0 >= minimum_overload_coverage(938));
+ assert!(700.0 / 3298.0 < minimum_overload_coverage(938));
+}
+
fn cases_from_report(path: &Path) -> Result<Vec<(String, VideoCase, AudioCase)>, String> {
let raw = std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?;
let envelope: ReportEnvelope =
@@ -1734,6 +1750,58 @@ async fn run_video_case_with_cold_retry(case: VideoCase) -> Result<String, Strin
}
}
+#[tokio::test(flavor = "multi_thread")]
+async fn segmented_video_muxer_forwards_completed_video_segments() {
+ let temp = tempfile::tempdir().expect("temporary recording directory");
+ let info = VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 160, 120, 30);
+ let (frame_tx, frame_rx) = flume::bounded::<FFmpegVideoFrame>(8);
+ let (segment_tx, segment_rx) = std::sync::mpsc::channel();
+ let timestamps = Timestamps::now();
+ let base = timestamps.instant();
+ let mut rng = Rng(7);
+
+ let pipeline = OutputPipeline::builder(temp.path().join("progressive-video"))
+ .with_video::<ChannelVideoSource<FFmpegVideoFrame>>(ChannelVideoSourceConfig::new(
+ info, frame_rx,
+ ))
+ .with_timestamps(timestamps)
+ .build::<SegmentedVideoMuxer>(SegmentedVideoMuxerConfig {
+ segment_duration: Duration::from_millis(250),
+ segment_tx: Some(segment_tx),
+ ..Default::default()
+ })
+ .await
+ .expect("segmented video pipeline");
+
+ for index in 0..90u64 {
+ frame_tx
+ .send_async(FFmpegVideoFrame {
+ inner: make_video_frame(160, 120, index, Content::Motion, &mut rng),
+ timestamp: Timestamp::Instant(base + Duration::from_millis(index * 33)),
+ })
+ .await
+ .expect("synthetic video frame");
+ }
+ drop(frame_tx);
+
+ pipeline.stop().await.expect("finalized video pipeline");
+
+ let events = segment_rx.try_iter().collect::<Vec<_>>();
+ assert!(
+ events.iter().any(|event| event.is_init),
+ "segmented video pipeline did not forward its initialization segment"
+ );
+ assert!(
+ events.iter().any(|event| !event.is_init),
+ "segmented video pipeline did not forward a completed media segment"
+ );
+ assert!(events.iter().all(|event| {
+ event.media_type == cap_enc_ffmpeg::segmented_stream::SegmentMediaType::Video
+ && event.file_size > 0
+ && event.path.is_file()
+ }));
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn synthetic_device_matrix_preserves_sync() {
// Silent without RUST_LOG; with it, pipeline drop/stall warnings become