From a3668f5aad0a3cbe1abab501c476008719cfb52d Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:38:06 +0000 Subject: [PATCH 1/5] test: mid-take h264 swap rewinds the mp4 timeline A second encoder on the stream Media Foundation already wrote rebases timestamps, and the mov muxer rejects the next packet. Co-authored-by: Kyzer --- crates/enc-ffmpeg/src/video/h264.rs | 46 +++ crates/enc-ffmpeg/src/video/mid_take.rs | 288 +++++++++++++++++++ crates/enc-ffmpeg/src/video/mod.rs | 2 + crates/enc-mediafoundation/src/lib.rs | 2 +- crates/enc-mediafoundation/src/video/h264.rs | 24 ++ crates/mediafoundation-ffmpeg/src/h264.rs | 8 + crates/recording/src/output_pipeline/win.rs | 236 ++++++++++++--- 7 files changed, 564 insertions(+), 42 deletions(-) create mode 100644 crates/enc-ffmpeg/src/video/mid_take.rs diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs index 6f10c31278f..396705b81b4 100644 --- a/crates/enc-ffmpeg/src/video/h264.rs +++ b/crates/enc-ffmpeg/src/video/h264.rs @@ -411,6 +411,52 @@ impl H264EncoderBuilder { }) } + /// Opens libx264 on a stream another encoder already added. + pub fn build_software_on_stream( + self, + stream_index: usize, + last_stream_dts: Option, + ) -> Result { + let input_config = self.input_config; + let (raw_width, raw_height) = self + .output_size + .unwrap_or((input_config.width, input_config.height)); + let (output_width, output_height) = (ensure_even(raw_width), ensure_even(raw_height)); + let OpenedVideoEncoder { + encoder, + converter, + converted_frame_pool, + output_format, + output_width, + output_height, + input_format, + input_width, + input_height, + hw_upload, + } = self.open_software(output_width, output_height)?; + let encoder = H264Encoder { + base: EncoderBase::new(stream_index), + encoder, + converter, + output_format, + output_width, + output_height, + input_format, + input_width, + input_height, + converted_frame_pool, + hw_upload, + #[cfg(target_os = "macos")] + videotoolbox_hw: None, + software_fallback: None, + #[cfg(test)] + injected_failure: None, + hardware_session: None, + }; + let _ = last_stream_dts; + Ok(encoder) + } + fn open_software( &self, output_width: u32, diff --git a/crates/enc-ffmpeg/src/video/mid_take.rs b/crates/enc-ffmpeg/src/video/mid_take.rs new file mode 100644 index 00000000000..d1d5f2ef025 --- /dev/null +++ b/crates/enc-ffmpeg/src/video/mid_take.rs @@ -0,0 +1,288 @@ +use std::time::Duration; + +use cap_media_info::{AudioInfo, VideoInfo}; +use ffmpeg::format::sample::{Sample, Type}; +use ffmpeg::{ChannelLayout, Packet, Rational, frame}; + +use super::h264::{H264Encoder, QueueFrameError}; +use crate::PacketSink; +use crate::aac::AACEncoder; + +const FAILURE: ffmpeg::Error = ffmpeg::Error::Other { + errno: ffmpeg::error::EIO, +}; + +#[test] +fn injected_mid_take_failure_keeps_video_and_audio_on_one_timeline() { + ffmpeg::init().unwrap(); + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("take.mp4"); + let mut output = ffmpeg::format::output(&path).unwrap(); + + let audio_info = AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 2); + let mut audio = AACEncoder::init(audio_info, &mut output).unwrap(); + let video = test_video(); + let video_index = add_h264_stream(&mut output, video.width, video.height, video.fps()); + assert_ne!(video_index, audio.stream_index()); + output.write_header().unwrap(); + + let mut index = 0u64; + let mut audio_samples = 0u64; + { + let mut sink = Interleaved { + output: &mut output, + video_index, + last_video_dts: None, + }; + let mut hardware = H264Encoder::builder(video) + .build_software_on_stream(video_index, None) + .unwrap(); + hardware.inject_codec_failure_after(30, FAILURE, None); + + loop { + let timestamp = frame_timestamp(index); + push_audio_until(&mut audio, &mut sink, &mut audio_samples, timestamp); + match hardware.queue_frame_to(nv12_frame(16), timestamp, &mut sink) { + Ok(()) => index += 1, + Err(QueueFrameError::Encode(error)) if error == FAILURE => break, + Err(error) => panic!("encode before the switch: {error}"), + } + } + assert_eq!(index, 30, "the injected failure fires after 30 frames"); + let last_dts = sink.last_video_dts; + let mut software = H264Encoder::builder(video) + .build_software_on_stream(video_index, last_dts) + .unwrap(); + let end = index + 30; + while index < end { + let timestamp = frame_timestamp(index); + push_audio_until(&mut audio, &mut sink, &mut audio_samples, timestamp); + software + .queue_frame_to(nv12_frame(235), timestamp, &mut sink) + .unwrap_or_else(|error| panic!("encode after the switch: {error}")); + index += 1; + } + let end_timestamp = frame_timestamp(index.saturating_sub(1)); + push_audio_until(&mut audio, &mut sink, &mut audio_samples, end_timestamp); + software.flush_to(&mut sink).unwrap(); + audio.flush_to(&mut sink).unwrap(); + } + output.write_trailer().unwrap(); + drop(output); + + let decoded = decode_take(&path); + assert!( + decoded.dark_frames > 0 && decoded.bright_frames > 0, + "both sides of the switch must decode, dark={} bright={}", + decoded.dark_frames, + decoded.bright_frames + ); + assert!( + decoded.video_errors == 0, + "decoded video has {} frames with errors", + decoded.video_errors + ); + assert!( + decoded.last_video_secs > 1.5, + "video timestamps restart at the switch, last pts {:.3}s", + decoded.last_video_secs + ); + assert!( + decoded.last_audio_secs > 1.5, + "audio stops at the switch, last pts {:.3}s", + decoded.last_audio_secs + ); + assert!( + decoded.max_audio_gap_secs < 0.05, + "audio gap across the switch is {:.3}s", + decoded.max_audio_gap_secs + ); + assert!(decoded.audio_monotonic); +} + +fn test_video() -> VideoInfo { + VideoInfo { + pixel_format: cap_media_info::Pixel::NV12, + width: 320, + height: 240, + time_base: Rational(1, 1_000_000), + frame_rate: Rational(30, 1), + } +} + +fn frame_timestamp(index: u64) -> Duration { + Duration::from_micros(index * 33_333) +} + +fn add_h264_stream( + output: &mut ffmpeg::format::context::Output, + width: u32, + height: u32, + fps: u32, +) -> usize { + let codec = ffmpeg::codec::decoder::find(ffmpeg::codec::Id::H264).unwrap(); + let mut stream = output.add_stream(codec).unwrap(); + let index = stream.index(); + let time_base = Rational::new(1, fps as i32 * 1000); + stream.set_time_base(time_base); + unsafe { + let codecpar = (*stream.as_mut_ptr()).codecpar; + (*codecpar).codec_type = ffmpeg::ffi::AVMediaType::AVMEDIA_TYPE_VIDEO; + (*codecpar).codec_id = ffmpeg::ffi::AVCodecID::AV_CODEC_ID_H264; + (*codecpar).width = width as i32; + (*codecpar).height = height as i32; + (*codecpar).format = ffmpeg::ffi::AVPixelFormat::AV_PIX_FMT_NV12 as i32; + (*stream.as_mut_ptr()).avg_frame_rate = ffmpeg::ffi::AVRational { + num: fps as i32, + den: 1, + }; + } + index +} + +fn nv12_frame(y: u8) -> frame::Video { + let mut frame = frame::Video::new(ffmpeg::format::Pixel::NV12, 320, 240); + for plane in 0..frame.planes() { + let value = if plane == 0 { y } else { 128 }; + frame.data_mut(plane).fill(value); + } + frame +} + +fn push_audio_until( + audio: &mut AACEncoder, + sink: &mut Interleaved<'_>, + audio_samples: &mut u64, + until: Duration, +) { + const RATE: u64 = 48_000; + const SAMPLES: u64 = 1_024; + while Duration::from_secs_f64(*audio_samples as f64 / RATE as f64) <= until { + let mut frame = frame::Audio::new( + Sample::F32(Type::Packed), + SAMPLES as usize, + ChannelLayout::STEREO, + ); + frame.set_rate(RATE as u32); + frame.data_mut(0).fill(0); + let timestamp = Duration::from_secs_f64(*audio_samples as f64 / RATE as f64); + audio + .send_frame_to(frame, timestamp, sink) + .unwrap_or_else(|error| panic!("audio encode: {error}")); + *audio_samples += SAMPLES; + } +} + +struct Interleaved<'a> { + output: &'a mut ffmpeg::format::context::Output, + video_index: usize, + last_video_dts: Option, +} + +impl PacketSink for Interleaved<'_> { + fn stream_time_base(&self, stream_index: usize) -> Rational { + self.output.stream_time_base(stream_index) + } + + fn write_packet(&mut self, packet: Packet) -> Result<(), ffmpeg::Error> { + if packet.stream() == self.video_index { + self.last_video_dts = packet.dts().or_else(|| packet.pts()); + } + packet.write_interleaved(self.output) + } +} + +struct DecodedTake { + dark_frames: usize, + bright_frames: usize, + video_errors: usize, + last_video_secs: f64, + last_audio_secs: f64, + max_audio_gap_secs: f64, + audio_monotonic: bool, +} + +fn decode_take(path: &std::path::Path) -> DecodedTake { + let mut input = ffmpeg::format::input(path).unwrap(); + let video_index = input + .streams() + .best(ffmpeg::media::Type::Video) + .unwrap() + .index(); + let audio_index = input + .streams() + .best(ffmpeg::media::Type::Audio) + .unwrap() + .index(); + let video_tb = input.stream(video_index).unwrap().time_base(); + let audio_tb = input.stream(audio_index).unwrap().time_base(); + let video_params = input.stream(video_index).unwrap().parameters(); + let mut video_decoder = ffmpeg::codec::context::Context::from_parameters(video_params) + .unwrap() + .decoder() + .video() + .unwrap(); + + let mut decoded = DecodedTake { + dark_frames: 0, + bright_frames: 0, + video_errors: 0, + last_video_secs: 0.0, + last_audio_secs: 0.0, + max_audio_gap_secs: 0.0, + audio_monotonic: true, + }; + let mut previous_audio = None; + let mut frame = frame::Video::empty(); + for (stream, packet) in input.packets() { + if stream.index() == audio_index { + let Some(pts) = packet.pts() else { + continue; + }; + let secs = + pts as f64 * f64::from(audio_tb.numerator()) / f64::from(audio_tb.denominator()); + if let Some(previous) = previous_audio { + decoded.audio_monotonic &= secs + 0.000_1 >= previous; + decoded.max_audio_gap_secs = decoded.max_audio_gap_secs.max(secs - previous); + } + previous_audio = Some(secs); + decoded.last_audio_secs = decoded.last_audio_secs.max(secs); + continue; + } + if stream.index() != video_index { + continue; + } + video_decoder.send_packet(&packet).unwrap(); + while video_decoder.receive_frame(&mut frame).is_ok() { + if unsafe { (*frame.as_ptr()).decode_error_flags } != 0 { + decoded.video_errors += 1; + } + if let Some(pts) = frame.pts() { + let secs = pts as f64 * f64::from(video_tb.numerator()) + / f64::from(video_tb.denominator()); + decoded.last_video_secs = decoded.last_video_secs.max(secs); + } + let data = frame.data(0); + let y = data[data.len() / 2]; + if y < 40 { + decoded.dark_frames += 1; + } else if y > 200 { + decoded.bright_frames += 1; + } + } + } + video_decoder.send_eof().unwrap(); + while video_decoder.receive_frame(&mut frame).is_ok() { + if unsafe { (*frame.as_ptr()).decode_error_flags } != 0 { + decoded.video_errors += 1; + } + let data = frame.data(0); + let y = data[data.len() / 2]; + if y < 40 { + decoded.dark_frames += 1; + } else if y > 200 { + decoded.bright_frames += 1; + } + } + decoded +} diff --git a/crates/enc-ffmpeg/src/video/mod.rs b/crates/enc-ffmpeg/src/video/mod.rs index c83201a08b4..67c21e54915 100644 --- a/crates/enc-ffmpeg/src/video/mod.rs +++ b/crates/enc-ffmpeg/src/video/mod.rs @@ -6,6 +6,8 @@ pub mod h264_packet; pub mod hardware_crash; pub mod hevc; pub mod isolated_self_test; +#[cfg(test)] +mod mid_take; mod packed_yuv; pub mod prores; mod rgb_to_yuv; diff --git a/crates/enc-mediafoundation/src/lib.rs b/crates/enc-mediafoundation/src/lib.rs index 630da66d6c7..16d98cfc5ce 100644 --- a/crates/enc-mediafoundation/src/lib.rs +++ b/crates/enc-mediafoundation/src/lib.rs @@ -5,4 +5,4 @@ pub mod media; pub mod mft; pub mod video; -pub use video::H264Encoder; +pub use video::{H264Encoder, injected_failure_after_frames}; diff --git a/crates/enc-mediafoundation/src/video/h264.rs b/crates/enc-mediafoundation/src/video/h264.rs index 2b7911eb5a4..ae8c77dca63 100644 --- a/crates/enc-mediafoundation/src/video/h264.rs +++ b/crates/enc-mediafoundation/src/video/h264.rs @@ -66,6 +66,15 @@ pub enum EncoderFailureReason { ConsecutiveProcessFailures, Timeout, TooManyEmptySamples, + Injected, +} + +pub fn injected_failure_after_frames() -> Option { + let Ok(value) = std::env::var("CAP_MF_FAIL_AFTER_FRAMES") else { + return None; + }; + let frames = value.parse::().ok()?; + (frames > 0).then_some(frames) } struct EncoderHealthMonitor { @@ -576,7 +585,22 @@ impl H264Encoder { let mut consecutive_empty_samples: u8 = 0; let mut should_exit = false; + let fail_after = injected_failure_after_frames(); while !should_exit { + if let Some(limit) = fail_after + && health_monitor.total_frames_encoded >= limit + { + let frames_encoded = health_monitor.total_frames_encoded; + let inputs_without_output = health_monitor.inputs_without_output; + let process_failures = health_monitor.consecutive_process_failures; + let _ = self.cleanup_encoder(); + return Err(EncoderRuntimeError::EncoderUnhealthy { + reason: EncoderFailureReason::Injected, + inputs_without_output, + process_failures, + frames_encoded, + }); + } let health_status = health_monitor.check_health(); if !health_status.is_healthy && let Some(reason) = health_status.failure_reason diff --git a/crates/mediafoundation-ffmpeg/src/h264.rs b/crates/mediafoundation-ffmpeg/src/h264.rs index f1077860e9d..63fa4c30b73 100644 --- a/crates/mediafoundation-ffmpeg/src/h264.rs +++ b/crates/mediafoundation-ffmpeg/src/h264.rs @@ -197,6 +197,14 @@ impl H264StreamMuxer { Ok(()) } + pub fn stream_index(&self) -> usize { + self.stream_index + } + + pub fn last_written_pts(&self) -> Option { + self.last_written_pts + } + pub fn frame_count(&self) -> u64 { self.frame_count } diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs index 2ce521fb6b3..c078689c4e4 100644 --- a/crates/recording/src/output_pipeline/win.rs +++ b/crates/recording/src/output_pipeline/win.rs @@ -1,7 +1,7 @@ use crate::{ AudioFrame, AudioMuxer, Muxer, TaskPool, VideoFrame, VideoMuxer, output_pipeline::{ - HealthSender, PipelineHealthEvent, emit_health, + HealthSender, PipelineHealthEvent, SharedHealthSender, emit_health, frame_pacing::{FramePacer, Paced}, mjpeg::MjpegDecoder, }, @@ -30,6 +30,29 @@ const DEFAULT_MUXER_BUFFER_SIZE: usize = 240; /// FFmpeg's `h264_mf`, so it shares that name for crash recovery. const MEDIA_FOUNDATION_ENCODER: &str = "h264_mf"; +fn media_foundation_skipped(preferences: &crate::capture_pipeline::EncoderPreferences) -> bool { + preferences.should_force_software() + || (cap_enc_mediafoundation::injected_failure_after_frames().is_none() + && matches!( + cap_frame_converter::detect_primary_gpu().map(|gpu| gpu.vendor), + Some(cap_frame_converter::GpuVendor::Amd) + )) +} + +fn even_output_size(size: SizeInt32, fallback_width: u32, fallback_height: u32) -> (u32, u32) { + let width = if size.Width > 0 { + size.Width as u32 + } else { + fallback_width + }; + let height = if size.Height > 0 { + size.Height as u32 + } else { + fallback_height + }; + (width, height) +} + fn get_muxer_buffer_size() -> usize { std::env::var("CAP_MUXER_BUFFER_SIZE") .ok() @@ -138,6 +161,7 @@ pub struct WindowsMuxer { output: Arc>, audio_encoder: Option, frame_drops: FrameDropTracker, + health: SharedHealthSender, } pub struct WindowsMuxerConfig { @@ -193,10 +217,12 @@ impl Muxer for WindowsMuxer { let output = Arc::new(Mutex::new(output)); let (ready_tx, ready_rx) = oneshot::channel::>(); + let health = SharedHealthSender::new(); { let output = output.clone(); let pause_flag = pause_flag.clone(); + let health = health.clone(); tasks.spawn_thread("windows-encoder", move || { cap_mediafoundation_utils::thread_init(); @@ -214,16 +240,11 @@ impl Muxer for WindowsMuxer { info!("Using FFmpeg H264 encoder"); } - let fallback_width = if output_size.Width > 0 { - output_size.Width as u32 - } else { - video_config.width - }; - let fallback_height = if output_size.Height > 0 { - output_size.Height as u32 - } else { - video_config.height - }; + let (fallback_width, fallback_height) = even_output_size( + output_size, + video_config.width, + video_config.height, + ); let mut output_guard = match output.lock() { Ok(guard) => guard, @@ -242,12 +263,7 @@ impl Muxer for WindowsMuxer { .map_err(|e| anyhow!("ScreenSoftwareEncoder/{e}")) }; - if encoder_preferences.should_force_software() - || matches!( - cap_frame_converter::detect_primary_gpu().map(|gpu| gpu.vendor), - Some(cap_frame_converter::GpuVendor::Amd) - ) - { + if media_foundation_skipped(encoder_preferences) { return fallback(None); } @@ -417,16 +433,87 @@ impl Muxer for WindowsMuxer { ); Ok(()) } - Err(e) => { - if e.should_fallback() { - error!( - "Hardware encoder failed with recoverable error, marking for software fallback: {}", - e - ); - encoder_preferences.force_software_only(); + Err(e) if e.should_fallback() => { + encoder_preferences.force_software_only(); + let (last_dts, stream_index) = { + let last_dts = muxer.last_written_pts(); + let stream_index = muxer.stream_index(); + (last_dts, stream_index) + }; + drop(encoder); + _media_foundation_session = None; + let (width, height) = even_output_size( + output_size, + video_config.width, + video_config.height, + ); + let mut soft = match cap_enc_ffmpeg::h264::H264Encoder::builder( + video_config, + ) + .with_output_size(width, height) + .and_then(|builder| { + builder.build_software_on_stream(stream_index, last_dts) + }) { + Ok(encoder) => encoder, + Err(err) => { + return Err(anyhow!( + "Hardware encoder error: {e}; software encoder did not start: {err}" + )); + } + }; + warn!( + error = %e, + "Media Foundation H264 stopped mid-take; switching to libx264" + ); + health.emit(PipelineHealthEvent::EncoderRebuilt { + backend: "libx264".to_string(), + attempt: 1, + }); + let mut last_ffmpeg_frame: Option = None; + loop { + let (ffmpeg_frame, ts) = match pacer.next(&video_rx, &pause_flag) + { + Paced::Frame(frame, timestamp) => match frame.as_ffmpeg() { + Ok(frame) => { + last_ffmpeg_frame = + Some(reference_video_frame(&frame)); + (Some(frame), timestamp) + } + Err(err) => { + warn!("Failed to convert frame: {err:?}"); + ( + last_ffmpeg_frame + .as_ref() + .map(reference_video_frame), + timestamp, + ) + } + }, + Paced::Repeat(timestamp) => ( + last_ffmpeg_frame.as_ref().map(reference_video_frame), + timestamp, + ), + Paced::End => break, + }; + let Some(ffmpeg_frame) = ffmpeg_frame else { + continue; + }; + let normalized_ts = + normalize_timestamp(ts, &mut first_timestamp); + let Ok(mut output_guard) = output.lock() else { + continue; + }; + soft.queue_frame(ffmpeg_frame, normalized_ts, &mut output_guard) + .context("queue_frame")?; } - Err(anyhow!("Hardware encoder error: {}", e)) + let mut output_guard = output.lock().map_err(|_| { + anyhow!("Failed to lock output while flushing software encoder") + })?; + soft.flush(&mut output_guard) + .context("flush software encoder")?; + Ok(()) } + Err(e) => Err(anyhow!("Hardware encoder error: {e}")), } } either::Right(mut encoder) => { @@ -492,11 +579,13 @@ impl Muxer for WindowsMuxer { output, audio_encoder, frame_drops: FrameDropTracker::new(None, "muxer:windows-mp4"), + health, }) } fn set_health_sender(&mut self, tx: HealthSender) { - self.frame_drops.health_tx = Some(tx); + self.frame_drops.health_tx = Some(tx.clone()); + self.health.set(tx); } fn stop(&mut self) { @@ -658,6 +747,7 @@ pub struct WindowsCameraMuxer { output: Arc>, audio_encoder: Option, frame_drops: FrameDropTracker, + health: SharedHealthSender, } pub struct WindowsCameraMuxerConfig { @@ -747,6 +837,7 @@ impl Muxer for WindowsCameraMuxer { let output = Arc::new(Mutex::new(output)); let (ready_tx, ready_rx) = oneshot::channel::>(); + let health = SharedHealthSender::new(); let expected_input_format = config .expected_pixel_format @@ -757,6 +848,7 @@ impl Muxer for WindowsCameraMuxer { let output = output.clone(); let pause_flag = pause_flag.clone(); let encoder_preferences = config.encoder_preferences; + let health = health.clone(); tasks.spawn_thread("windows-camera-encoder", move || { cap_mediafoundation_utils::thread_init(); @@ -797,12 +889,7 @@ impl Muxer for WindowsCameraMuxer { .map_err(|e| anyhow!("CameraSoftwareEncoder/{e}")) }; - if encoder_preferences.should_force_software() - || matches!( - cap_frame_converter::detect_primary_gpu().map(|gpu| gpu.vendor), - Some(cap_frame_converter::GpuVendor::Amd) - ) - { + if media_foundation_skipped(&encoder_preferences) { return fallback(None); } @@ -960,15 +1047,80 @@ impl Muxer for WindowsCameraMuxer { health_status.total_frames_encoded ); } - Err(e) => { - if e.should_fallback() { - error!( - "Camera hardware encoder failed with recoverable error, marking for software fallback: {}", - e - ); - encoder_preferences.force_software_only(); + Err(e) if e.should_fallback() => { + encoder_preferences.force_software_only(); + let (last_dts, stream_index) = { + let last_dts = muxer.last_written_pts(); + let stream_index = muxer.stream_index(); + (last_dts, stream_index) + }; + drop(encoder); + _media_foundation_session = None; + let mut soft = match cap_enc_ffmpeg::h264::H264Encoder::builder( + video_config, + ) + .with_output_size(output_width, output_height) + .and_then(|builder| { + builder.build_software_on_stream(stream_index, last_dts) + }) { + Ok(encoder) => encoder, + Err(err) => { + return Err(anyhow!( + "Camera hardware encoder error: {e}; software encoder did not start: {err}" + )); + } + }; + warn!( + error = %e, + "Media Foundation camera H264 stopped mid-take; switching to libx264" + ); + health.emit(PipelineHealthEvent::EncoderRebuilt { + backend: "libx264".to_string(), + attempt: 1, + }); + let mut mjpeg_decoder = MjpegDecoder::default(); + loop { + let ts = match pacer.next(&video_rx, &pause_flag) { + Paced::Frame(frame, timestamp) => { + last_frame = Some(frame); + timestamp + } + Paced::Repeat(timestamp) => timestamp, + Paced::End => break, + }; + let Some(frame) = last_frame.clone() else { + continue; + }; + let normalized_ts = + normalize_camera_timestamp(ts, &mut first_timestamp); + let ffmpeg_frame = + match camera_frame_to_ffmpeg(&frame, &mut mjpeg_decoder) { + Ok(frame) => frame, + Err(err) => { + error!("Failed to convert camera frame: {err}"); + continue; + } + }; + let Ok(mut output_guard) = output.lock() else { + continue; + }; + soft.queue_frame( + ffmpeg_frame, + normalized_ts, + &mut output_guard, + ) + .context("queue camera frame")?; } - return Err(anyhow!("Camera hardware encoder error: {}", e)); + let mut output_guard = output.lock().map_err(|_| { + anyhow!( + "Failed to lock camera output while flushing software encoder" + ) + })?; + soft.flush(&mut output_guard) + .context("flush software encoder")?; + } + Err(e) => { + return Err(anyhow!("Camera hardware encoder error: {e}")); } } @@ -1058,11 +1210,13 @@ impl Muxer for WindowsCameraMuxer { output, audio_encoder, frame_drops: FrameDropTracker::new(None, "muxer:windows-mp4-camera"), + health, }) } fn set_health_sender(&mut self, tx: HealthSender) { - self.frame_drops.health_tx = Some(tx); + self.frame_drops.health_tx = Some(tx.clone()); + self.health.set(tx); } fn stop(&mut self) { From 8ba82e49fc6736736aebdfe89b73c73393d99c6b Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:38:53 +0000 Subject: [PATCH 2/5] fix: keep capture timestamps when libx264 replaces media foundation The software encoder stays on the existing stream and the take clock, so the next packet cannot move backwards. Co-authored-by: Kyzer --- crates/enc-ffmpeg/src/base.rs | 8 ++++++++ crates/enc-ffmpeg/src/video/h264.rs | 6 ++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/enc-ffmpeg/src/base.rs b/crates/enc-ffmpeg/src/base.rs index 5a017399ae2..d30a49a3af8 100644 --- a/crates/enc-ffmpeg/src/base.rs +++ b/crates/enc-ffmpeg/src/base.rs @@ -113,6 +113,14 @@ impl EncoderBase { } } + /// Keeps capture timestamps that already start at the beginning of the take. + /// `last_stream_dts` is the last dts written on this stream, in the stream + /// time base, so the next packet cannot move backwards. + pub(crate) fn continue_after(&mut self, last_stream_dts: Option) { + self.first_pts = Some(0); + self.last_written_dts = last_stream_dts; + } + pub fn set_packet_stats(&mut self, stats: Arc) { self.packet_stats = Some(stats); } diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs index 396705b81b4..a82b5088a46 100644 --- a/crates/enc-ffmpeg/src/video/h264.rs +++ b/crates/enc-ffmpeg/src/video/h264.rs @@ -412,6 +412,8 @@ impl H264EncoderBuilder { } /// Opens libx264 on a stream another encoder already added. + /// Frame timestamps are capture time since the start of the take. + /// `last_stream_dts` is the last dts already written, in that stream's time base. pub fn build_software_on_stream( self, stream_index: usize, @@ -434,7 +436,7 @@ impl H264EncoderBuilder { input_height, hw_upload, } = self.open_software(output_width, output_height)?; - let encoder = H264Encoder { + let mut encoder = H264Encoder { base: EncoderBase::new(stream_index), encoder, converter, @@ -453,7 +455,7 @@ impl H264EncoderBuilder { injected_failure: None, hardware_session: None, }; - let _ = last_stream_dts; + encoder.base.continue_after(last_stream_dts); Ok(encoder) } From 12d98a0725909b7e8c2a8d0c09d350859a003590 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:37:29 +0000 Subject: [PATCH 3/5] fix: repeat the last screen frame across the libx264 switch A static capture sends no new frames. The software loop was starting without the frame Media Foundation had been repeating, so those repeats encoded nothing until the screen changed. --- .../src/output_pipeline/frame_pacing.rs | 96 +++++++++++++++++++ crates/recording/src/output_pipeline/win.rs | 58 ++++++----- 2 files changed, 130 insertions(+), 24 deletions(-) diff --git a/crates/recording/src/output_pipeline/frame_pacing.rs b/crates/recording/src/output_pipeline/frame_pacing.rs index 3dd9719bf85..f2f74c916db 100644 --- a/crates/recording/src/output_pipeline/frame_pacing.rs +++ b/crates/recording/src/output_pipeline/frame_pacing.rs @@ -28,6 +28,22 @@ pub(crate) enum Paced { End, } +/// A repeat encodes the frame already carried. An empty carry drops it. +pub(crate) enum PacedPixels { + New(F), + Repeat, +} + +pub(crate) fn frame_to_encode(carried: &mut Option, step: PacedPixels) -> Option<&F> { + match step { + PacedPixels::New(frame) => { + *carried = Some(frame); + carried.as_ref() + } + PacedPixels::Repeat => carried.as_ref(), + } +} + pub(crate) struct FramePacer { interval: Duration, last: Option, @@ -249,6 +265,86 @@ mod tests { drop(tx); } + fn record( + carried: &mut Option, + emitted: &mut Vec, + step: super::PacedPixels, + stamp: Duration, + ) { + if super::frame_to_encode(carried, step).is_some() { + emitted.push(stamp); + } + } + + fn static_switch_timestamps(keep_carried_frame: bool) -> Vec { + let interval = Duration::from_secs(1) / 30; + let mut carried = None; + let mut emitted = Vec::new(); + let mut stamp = Duration::ZERO; + record( + &mut carried, + &mut emitted, + super::PacedPixels::New(1), + stamp, + ); + for _ in 0..30 { + stamp += interval; + record( + &mut carried, + &mut emitted, + super::PacedPixels::Repeat, + stamp, + ); + } + if !keep_carried_frame { + carried = None; + } + for _ in 0..90 { + stamp += interval; + record( + &mut carried, + &mut emitted, + super::PacedPixels::Repeat, + stamp, + ); + } + stamp += interval; + record( + &mut carried, + &mut emitted, + super::PacedPixels::New(2), + stamp, + ); + emitted + } + + fn widest_gap(timestamps: &[Duration]) -> Duration { + timestamps + .windows(2) + .map(|pair| pair[1].saturating_sub(pair[0])) + .max() + .unwrap_or(Duration::ZERO) + } + + #[test] + fn static_screen_across_the_software_switch_has_no_multi_frame_gap() { + let interval = Duration::from_secs(1) / 30; + let kept = static_switch_timestamps(true); + let kept_gap = widest_gap(&kept); + assert!( + kept_gap <= interval * 2, + "static handover gap {kept_gap:?} exceeds two frame intervals ({interval:?})" + ); + assert_eq!(kept.len(), 122); + + let dropped = static_switch_timestamps(false); + let dropped_gap = widest_gap(&dropped); + assert!( + dropped_gap > interval * 2, + "clearing the carried frame should open the static-screen gap" + ); + } + #[test] fn the_stream_ends_on_none_or_disconnect() { let paused = AtomicBool::new(false); diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs index c078689c4e4..4b1fea80b50 100644 --- a/crates/recording/src/output_pipeline/win.rs +++ b/crates/recording/src/output_pipeline/win.rs @@ -2,7 +2,7 @@ use crate::{ AudioFrame, AudioMuxer, Muxer, TaskPool, VideoFrame, VideoMuxer, output_pipeline::{ HealthSender, PipelineHealthEvent, SharedHealthSender, emit_health, - frame_pacing::{FramePacer, Paced}, + frame_pacing::{FramePacer, Paced, PacedPixels, frame_to_encode}, mjpeg::MjpegDecoder, }, screen_capture, @@ -374,7 +374,7 @@ impl Muxer for WindowsMuxer { _media_foundation_session = Some(session); trace!("Running native encoder with frame pacing"); let mut pacer = FramePacer::new(config.frame_rate); - let mut last_texture: Option = None; + let mut last_screen_frame: Option = None; let mut first_timestamp: Option = None; let mut frame_count: u64 = 0; let mut frames_reused: u64 = 0; @@ -385,11 +385,11 @@ impl Muxer for WindowsMuxer { let (texture, timestamp) = match pacer.next(&video_rx, &pause_flag) { Paced::Frame(frame, timestamp) => { let texture = frame.texture().clone(); - last_texture = Some(texture.clone()); + last_screen_frame = Some(frame); (texture, timestamp) } Paced::Repeat(timestamp) => { - let Some(texture) = &last_texture else { + let Some(frame) = last_screen_frame.as_ref() else { continue; }; frames_reused += 1; @@ -400,7 +400,7 @@ impl Muxer for WindowsMuxer { "Frame pacing: reusing frames due to slow capture" ); } - (texture.clone(), timestamp) + (frame.texture().clone(), timestamp) } Paced::End => { trace!("End of stream signal received"); @@ -435,6 +435,20 @@ impl Muxer for WindowsMuxer { } Err(e) if e.should_fallback() => { encoder_preferences.force_software_only(); + let carried_frame = + last_screen_frame.as_ref().and_then(|frame| { + match frame.as_ffmpeg() { + Ok(ffmpeg_frame) => { + Some(reference_video_frame(&ffmpeg_frame)) + } + Err(err) => { + warn!( + "Could not read the last screen frame for libx264: {err}" + ); + None + } + } + }); let (last_dts, stream_index) = { let last_dts = muxer.last_written_pts(); let stream_index = muxer.stream_index(); @@ -469,35 +483,31 @@ impl Muxer for WindowsMuxer { backend: "libx264".to_string(), attempt: 1, }); - let mut last_ffmpeg_frame: Option = None; + let mut last_ffmpeg_frame = carried_frame; loop { - let (ffmpeg_frame, ts) = match pacer.next(&video_rx, &pause_flag) - { + let next = pacer.next(&video_rx, &pause_flag); + let (step, ts) = match next { Paced::Frame(frame, timestamp) => match frame.as_ffmpeg() { - Ok(frame) => { - last_ffmpeg_frame = - Some(reference_video_frame(&frame)); - (Some(frame), timestamp) - } + Ok(frame) => ( + PacedPixels::New(reference_video_frame(&frame)), + timestamp, + ), Err(err) => { warn!("Failed to convert frame: {err:?}"); - ( - last_ffmpeg_frame - .as_ref() - .map(reference_video_frame), - timestamp, - ) + (PacedPixels::Repeat, timestamp) } }, - Paced::Repeat(timestamp) => ( - last_ffmpeg_frame.as_ref().map(reference_video_frame), - timestamp, - ), + Paced::Repeat(timestamp) => { + (PacedPixels::Repeat, timestamp) + } Paced::End => break, }; - let Some(ffmpeg_frame) = ffmpeg_frame else { + let Some(stored) = + frame_to_encode(&mut last_ffmpeg_frame, step) + else { continue; }; + let ffmpeg_frame = reference_video_frame(stored); let normalized_ts = normalize_timestamp(ts, &mut first_timestamp); let Ok(mut output_guard) = output.lock() else { From 46ea27dd1a330b833fe20cf64eadcb1886581602 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:27:05 +0000 Subject: [PATCH 4/5] test: bound video spacing across the mid-take h264 switch Record every video packet timestamp and reject a backwards step, a gap wider than two frames, or an audio and video ending more than 100ms apart. Drop the comment that restated frame_to_encode. --- crates/enc-ffmpeg/src/video/mid_take.rs | 43 ++++++++++++++----- .../src/output_pipeline/frame_pacing.rs | 1 - 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/crates/enc-ffmpeg/src/video/mid_take.rs b/crates/enc-ffmpeg/src/video/mid_take.rs index d1d5f2ef025..558cc886d33 100644 --- a/crates/enc-ffmpeg/src/video/mid_take.rs +++ b/crates/enc-ffmpeg/src/video/mid_take.rs @@ -82,15 +82,35 @@ fn injected_mid_take_failure_keeps_video_and_audio_on_one_timeline() { "decoded video has {} frames with errors", decoded.video_errors ); + let video_pts = &decoded.video_timestamps; assert!( - decoded.last_video_secs > 1.5, - "video timestamps restart at the switch, last pts {:.3}s", - decoded.last_video_secs + video_pts.len() >= 55, + "video packets disappeared across the switch, got {}", + video_pts.len() ); + let frame_secs = 1.0 / 30.0; + let mut max_video_gap_secs = 0.0_f64; + for pair in video_pts.windows(2) { + assert!( + pair[1] > pair[0], + "video timestamp moved backwards: {:.6}s -> {:.6}s", + pair[0], + pair[1] + ); + max_video_gap_secs = max_video_gap_secs.max(pair[1] - pair[0]); + } assert!( - decoded.last_audio_secs > 1.5, - "audio stops at the switch, last pts {:.3}s", - decoded.last_audio_secs + max_video_gap_secs < frame_secs * 2.0, + "video gap across the switch is {:.3}s", + max_video_gap_secs + ); + let duration_delta = (decoded.last_audio_secs - decoded.last_video_secs).abs(); + assert!( + duration_delta < 0.1, + "audio and video end {:.3}s apart (audio {:.3}s, video {:.3}s)", + duration_delta, + decoded.last_audio_secs, + decoded.last_video_secs ); assert!( decoded.max_audio_gap_secs < 0.05, @@ -196,6 +216,7 @@ struct DecodedTake { dark_frames: usize, bright_frames: usize, video_errors: usize, + video_timestamps: Vec, last_video_secs: f64, last_audio_secs: f64, max_audio_gap_secs: f64, @@ -227,6 +248,7 @@ fn decode_take(path: &std::path::Path) -> DecodedTake { dark_frames: 0, bright_frames: 0, video_errors: 0, + video_timestamps: Vec::new(), last_video_secs: 0.0, last_audio_secs: 0.0, max_audio_gap_secs: 0.0, @@ -252,16 +274,15 @@ fn decode_take(path: &std::path::Path) -> DecodedTake { if stream.index() != video_index { continue; } + let pts = packet.pts().expect("video packet has no timestamp"); + let secs = pts as f64 * f64::from(video_tb.numerator()) / f64::from(video_tb.denominator()); + decoded.video_timestamps.push(secs); + decoded.last_video_secs = secs; video_decoder.send_packet(&packet).unwrap(); while video_decoder.receive_frame(&mut frame).is_ok() { if unsafe { (*frame.as_ptr()).decode_error_flags } != 0 { decoded.video_errors += 1; } - if let Some(pts) = frame.pts() { - let secs = pts as f64 * f64::from(video_tb.numerator()) - / f64::from(video_tb.denominator()); - decoded.last_video_secs = decoded.last_video_secs.max(secs); - } let data = frame.data(0); let y = data[data.len() / 2]; if y < 40 { diff --git a/crates/recording/src/output_pipeline/frame_pacing.rs b/crates/recording/src/output_pipeline/frame_pacing.rs index f2f74c916db..3530bf98507 100644 --- a/crates/recording/src/output_pipeline/frame_pacing.rs +++ b/crates/recording/src/output_pipeline/frame_pacing.rs @@ -28,7 +28,6 @@ pub(crate) enum Paced { End, } -/// A repeat encodes the frame already carried. An empty carry drops it. pub(crate) enum PacedPixels { New(F), Repeat, From be8cd99e74fc26d78f9ccff52d0a17d29784f074 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:53:22 +0800 Subject: [PATCH 5/5] chore: retrigger CI after flaky windows real-capture shard