Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add encoder health monitoring and fallback logic
Richie McIlroy4973b1b76b94
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsonindex 8e65ddf10..c45c99482 100644--- a/.claude/settings.local.json+++ b/.claude/settings.local.json@@ -44,7 +44,8 @@"WebFetch(domain:docs.rs)","WebFetch(domain:gix.github.io)","Bash(cargo clean:*)",- "Bash(cargo test:*)"+ "Bash(cargo test:*)",+ "Bash(powershell -Command \"[System.Environment]::OSVersion.Version.ToString()\")"],"deny": [],"ask": []diff --git a/crates/enc-mediafoundation/src/video/h264.rs b/crates/enc-mediafoundation/src/video/h264.rsindex dd371989c..129ba0024 100644--- a/crates/enc-mediafoundation/src/video/h264.rs+++ b/crates/enc-mediafoundation/src/video/h264.rs@@ -3,9 +3,12 @@ use crate::{mft::EncoderDevice,video::{NewVideoProcessorError, VideoProcessor},};-use std::sync::{- Arc,- atomic::{AtomicBool, Ordering},+use std::{+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+ time::{Duration, Instant},};use windows::{Foundation::TimeSpan,@@ -36,6 +39,89 @@ use windows::{};const MAX_CONSECUTIVE_EMPTY_SAMPLES: u8 = 20;+const MAX_INPUT_WITHOUT_OUTPUT: u32 = 30;+const MAX_PROCESS_INPUT_FAILURES: u32 = 5;+const ENCODER_OPERATION_TIMEOUT: Duration = Duration::from_secs(5);++#[derive(Debug, Clone)]+pub struct EncoderHealthStatus {+ pub inputs_without_output: u32,+ pub consecutive_process_failures: u32,+ pub total_frames_encoded: u64,+ pub is_healthy: bool,+ pub failure_reason: Option<EncoderFailureReason>,+}++#[derive(Debug, Clone)]+pub enum EncoderFailureReason {+ Stalled,+ ConsecutiveProcessFailures,+ Timeout,+ TooManyEmptySamples,+}++struct EncoderHealthMonitor {+ inputs_without_output: u32,+ consecutive_process_failures: u32,+ total_frames_encoded: u64,+ last_output_time: Instant,+}++impl EncoderHealthMonitor {+ fn new() -> Self {+ Self {+ inputs_without_output: 0,+ consecutive_process_failures: 0,+ total_frames_encoded: 0,+ last_output_time: Instant::now(),+ }+ }++ fn record_input(&mut self) {+ self.inputs_without_output += 1;+ }++ fn record_output(&mut self) {+ self.inputs_without_output = 0;+ self.consecutive_process_failures = 0;+ self.total_frames_encoded += 1;+ self.last_output_time = Instant::now();+ }++ fn record_process_failure(&mut self) {+ self.consecutive_process_failures += 1;+ }++ fn reset_process_failures(&mut self) {+ self.consecutive_process_failures = 0;+ }++ fn check_health(&self) -> EncoderHealthStatus {+ let mut is_healthy = true;+ let mut failure_reason = None;++ if self.inputs_without_output > MAX_INPUT_WITHOUT_OUTPUT {+ is_healthy = false;+ failure_reason = Some(EncoderFailureReason::Stalled);+ } else if self.consecutive_process_failures >= MAX_PROCESS_INPUT_FAILURES {+ is_healthy = false;+ failure_reason = Some(EncoderFailureReason::ConsecutiveProcessFailures);+ } else if self.last_output_time.elapsed() > ENCODER_OPERATION_TIMEOUT+ && self.total_frames_encoded > 0+ {+ is_healthy = false;+ failure_reason = Some(EncoderFailureReason::Timeout);+ }++ EncoderHealthStatus {+ inputs_without_output: self.inputs_without_output,+ consecutive_process_failures: self.consecutive_process_failures,+ total_frames_encoded: self.total_frames_encoded,+ is_healthy,+ failure_reason,+ }+ }+}pub struct VideoEncoderOutputSample {sample: IMFSample,@@ -98,6 +184,36 @@ pub enum HandleNeedsInputError {ProcessInput(windows::core::Error),}+#[derive(Clone, Debug, thiserror::Error)]+pub enum EncoderRuntimeError {+ #[error("Windows error: {0}")]+ Windows(windows::core::Error),+ #[error(+ "Encoder unhealthy: {reason:?} (inputs_without_output={inputs_without_output}, process_failures={process_failures}, frames_encoded={frames_encoded})"+ )]+ EncoderUnhealthy {+ reason: EncoderFailureReason,+ inputs_without_output: u32,+ process_failures: u32,+ frames_encoded: u64,+ },+}++impl EncoderRuntimeError {+ pub fn should_fallback(&self) -> bool {+ match self {+ EncoderRuntimeError::Windows(_) => false,+ EncoderRuntimeError::EncoderUnhealthy { .. } => true,+ }+ }+}++impl From<windows::core::Error> for EncoderRuntimeError {+ fn from(err: windows::core::Error) -> Self {+ EncoderRuntimeError::Windows(err)+ }+}+unsafe impl Send for H264Encoder {}impl H264Encoder {@@ -385,12 +501,35 @@ impl H264Encoder {&self.output_type}+ pub fn validate(&self) -> Result<(), NewVideoEncoderError> {+ unsafe {+ self.transform+ .ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0)+ .map_err(NewVideoEncoderError::EncoderTransform)?;++ self.transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)+ .map_err(NewVideoEncoderError::EncoderTransform)?;++ self.transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0)+ .map_err(NewVideoEncoderError::EncoderTransform)?;++ self.transform+ .ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0)+ .map_err(NewVideoEncoderError::EncoderTransform)?;+ }+ Ok(())+ }+pub fn run(&mut self,should_stop: Arc<AtomicBool>,mut get_frame: impl FnMut() -> windows::core::Result<Option<(ID3D11Texture2D, TimeSpan)>>,mut on_sample: impl FnMut(IMFSample) -> windows::core::Result<()>,- ) -> windows::core::Result<()> {+ ) -> Result<EncoderHealthStatus, EncoderRuntimeError> {+ let mut health_monitor = EncoderHealthMonitor::new();+unsafe {self.transform.ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0)?;@@ -399,33 +538,72 @@ impl H264Encoder {self.transform.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)?;- let mut consecutive_empty_samples = 0;+ let mut consecutive_empty_samples: u8 = 0;let mut should_exit = false;while !should_exit {+ let health_status = health_monitor.check_health();+ if !health_status.is_healthy {+ if let Some(reason) = health_status.failure_reason {+ let _ = self.cleanup_encoder();+ return Err(EncoderRuntimeError::EncoderUnhealthy {+ reason,+ inputs_without_output: health_status.inputs_without_output,+ process_failures: health_status.consecutive_process_failures,+ frames_encoded: health_status.total_frames_encoded,+ });+ }+ }+let event = self.event_generator.GetEvent(MF_EVENT_FLAG_NONE)?;let event_type = MF_EVENT_TYPE(event.GetType()? as i32);match event_type {MediaFoundation::METransformNeedInput => {+ health_monitor.record_input();should_exit = true;if !should_stop.load(Ordering::SeqCst)&& let Some((texture, timestamp)) = get_frame()?{- self.video_processor.process_texture(&texture)?;- let input_buffer = {- MFCreateDXGISurfaceBuffer(+ let process_result = (|| -> windows::core::Result<()> {+ self.video_processor.process_texture(&texture)?;+ let input_buffer = MFCreateDXGISurfaceBuffer(&ID3D11Texture2D::IID,self.video_processor.output_texture(),0,false,- )?- };- let mf_sample = MFCreateSample()?;- mf_sample.AddBuffer(&input_buffer)?;- mf_sample.SetSampleTime(timestamp.Duration)?;- self.transform- .ProcessInput(self.input_stream_id, &mf_sample, 0)?;- should_exit = false;+ )?;+ let mf_sample = MFCreateSample()?;+ mf_sample.AddBuffer(&input_buffer)?;+ mf_sample.SetSampleTime(timestamp.Duration)?;+ self.transform+ .ProcessInput(self.input_stream_id, &mf_sample, 0)?;+ Ok(())+ })();++ match process_result {+ Ok(()) => {+ health_monitor.reset_process_failures();+ should_exit = false;+ }+ Err(_) => {+ health_monitor.record_process_failure();+ let health_status = health_monitor.check_health();+ if !health_status.is_healthy {+ if let Some(reason) = health_status.failure_reason {+ let _ = self.cleanup_encoder();+ return Err(EncoderRuntimeError::EncoderUnhealthy {+ reason,+ inputs_without_output: health_status+ .inputs_without_output,+ process_failures: health_status+ .consecutive_process_failures,+ frames_encoded: health_status.total_frames_encoded,+ });+ }+ }+ should_exit = false;+ }+ }}}MediaFoundation::METransformHaveOutput => {@@ -435,25 +613,24 @@ impl H264Encoder {..Default::default()};- // ProcessOutput may succeed but not populate pSample in some edge cases- // (e.g., hardware encoder transient failures, specific MFT implementations).- // This is a known contract violation by certain Media Foundation Transforms.- // We handle this gracefully by skipping the frame instead of panicking.let mut output_buffers = [output_buffer];self.transform.ProcessOutput(0, &mut output_buffers, &mut status)?;- // Use the sample directly without cloning to prevent memory leaksif let Some(sample) = output_buffers[0].pSample.take() {consecutive_empty_samples = 0;+ health_monitor.record_output();on_sample(sample)?;} else {consecutive_empty_samples += 1;if consecutive_empty_samples > MAX_CONSECUTIVE_EMPTY_SAMPLES {- return Err(windows::core::Error::new(- windows::core::HRESULT(0),- "Too many consecutive empty samples",- ));+ let _ = self.cleanup_encoder();+ return Err(EncoderRuntimeError::EncoderUnhealthy {+ reason: EncoderFailureReason::TooManyEmptySamples,+ inputs_without_output: health_monitor.inputs_without_output,+ process_failures: health_monitor.consecutive_process_failures,+ frames_encoded: health_monitor.total_frames_encoded,+ });}}}@@ -471,7 +648,19 @@ impl H264Encoder {.ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0)?;}- Ok(())+ Ok(health_monitor.check_health())+ }++ fn cleanup_encoder(&mut self) -> windows::core::Result<()> {+ unsafe {+ let _ = self+ .transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);+ let _ = self+ .transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0);+ self.transform.ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0)+ }}}diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rsindex b332813b8..6312f370b 100644--- a/crates/recording/src/output_pipeline/win.rs+++ b/crates/recording/src/output_pipeline/win.rs@@ -189,6 +189,12 @@ impl Muxer for WindowsMuxer {config.bitrate_multiplier,) {Ok(encoder) => {+ if let Err(e) = encoder.validate() {+ return fallback(Some(format!(+ "Hardware encoder validation failed: {e}"+ )));+ }+let width = match u32::try_from(output_size.Width) {Ok(width) if width > 0 => width,_ => {@@ -260,36 +266,54 @@ impl Muxer for WindowsMuxer {either::Left((mut encoder, mut muxer)) => {trace!("Running native encoder");let mut first_timestamp: Option<Duration> = None;- encoder- .run(- Arc::new(AtomicBool::default()),- || {- let Ok(Some((frame, timestamp))) = video_rx.recv() else {- trace!("No more frames available");- return Ok(None);- };-- let relative = if let Some(first) = first_timestamp {- timestamp.checked_sub(first).unwrap_or(Duration::ZERO)- } else {- first_timestamp = Some(timestamp);- Duration::ZERO- };- let frame_time = duration_to_timespan(relative);-- Ok(Some((frame.texture().clone(), frame_time)))- },- |output_sample| {- let mut output = output.lock().unwrap();+ let result = encoder.run(+ Arc::new(AtomicBool::default()),+ || {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more frames available");+ return Ok(None);+ };- let _ = muxer- .write_sample(&output_sample, &mut output)- .map_err(|e| format!("WriteSample: {e}"));+ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };+ let frame_time = duration_to_timespan(relative);- Ok(())- },- )- .context("run native encoder")+ Ok(Some((frame.texture().clone(), frame_time)))+ },+ |output_sample| {+ let mut output = output.lock().unwrap();++ let _ = muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| format!("WriteSample: {e}"));++ Ok(())+ },+ );++ match result {+ Ok(health_status) => {+ debug!(+ "Hardware encoder completed: {} frames encoded",+ health_status.total_frames_encoded+ );+ 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(anyhow!("Hardware encoder error: {}", e))+ }+ }}either::Right(mut encoder) => {while let Ok(Some((frame, time))) = video_rx.recv() {@@ -571,6 +595,12 @@ impl Muxer for WindowsCameraMuxer {bitrate_multiplier,) {Ok(encoder) => {+ if let Err(e) = encoder.validate() {+ return fallback(Some(format!(+ "Camera hardware encoder validation failed: {e}"+ )));+ }+let muxer = {let mut output_guard = match output.lock() {Ok(guard) => guard,@@ -655,43 +685,55 @@ impl Muxer for WindowsCameraMuxer {if let Ok(Some((texture, frame_time))) =process_frame(first_frame.0, first_frame.1){- encoder- .run(- Arc::new(AtomicBool::default()),- || {- if frame_count > 0 {- let Ok(Some((frame, timestamp))) = video_rx.recv()- else {- trace!("No more camera frames available");- return Ok(None);- };- frame_count += 1;- if frame_count.is_multiple_of(30) {- debug!(- "Windows camera encoder: processed {} frames",- frame_count- );- }- return process_frame(frame, timestamp);- }+ let result = encoder.run(+ Arc::new(AtomicBool::default()),+ || {+ if frame_count > 0 {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more camera frames available");+ return Ok(None);+ };frame_count += 1;- Ok(Some((texture.clone(), frame_time)))- },- |output_sample| {- let mut output = output.lock().unwrap();- let _ = muxer- .write_sample(&output_sample, &mut output)- .map_err(|e| format!("WriteSample: {e}"));- Ok(())- },- )- .context("run camera encoder")?;+ if frame_count.is_multiple_of(30) {+ debug!(+ "Windows camera encoder: processed {} frames",+ frame_count+ );+ }+ return process_frame(frame, timestamp);+ }+ frame_count += 1;+ Ok(Some((texture.clone(), frame_time)))+ },+ |output_sample| {+ let mut output = output.lock().unwrap();+ let _ = muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| format!("WriteSample: {e}"));+ Ok(())+ },+ );++ match result {+ Ok(health_status) => {+ info!(+ "Windows camera encoder finished (hardware): {} frames encoded",+ 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();+ }+ return Err(anyhow!("Camera hardware encoder error: {}", e));+ }+ }}- info!(- "Windows camera encoder finished (hardware): {} frames encoded",- frame_count- );Ok(())}either::Right(mut encoder) => {diff --git a/crates/recording/src/output_pipeline/win_segmented.rs b/crates/recording/src/output_pipeline/win_segmented.rsindex 7976712d6..c83e64b73 100644--- a/crates/recording/src/output_pipeline/win_segmented.rs+++ b/crates/recording/src/output_pipeline/win_segmented.rs@@ -424,6 +424,12 @@ impl WindowsSegmentedMuxer {bitrate_multiplier,) {Ok(encoder) => {+ if let Err(e) = encoder.validate() {+ return fallback(Some(format!(+ "Hardware encoder validation failed: {e}"+ )));+ }+let width = match u32::try_from(output_size.Width) {Ok(width) if width > 0 => width,_ => {@@ -495,36 +501,54 @@ impl WindowsSegmentedMuxer {either::Left((mut encoder, mut muxer)) => {trace!("Running native encoder for segment");let mut first_timestamp: Option<Duration> = None;- encoder- .run(- Arc::new(AtomicBool::default()),- || {- let Ok(Some((frame, timestamp))) = video_rx.recv() else {- trace!("No more frames available for segment");- return Ok(None);- };-- let relative = if let Some(first) = first_timestamp {- timestamp.checked_sub(first).unwrap_or(Duration::ZERO)- } else {- first_timestamp = Some(timestamp);- Duration::ZERO- };- let frame_time = duration_to_timespan(relative);-- Ok(Some((frame.texture().clone(), frame_time)))- },- |output_sample| {- let mut output = output_clone.lock().unwrap();-- let _ = muxer- .write_sample(&output_sample, &mut output)- .map_err(|e| format!("WriteSample: {e}"));-- Ok(())- },- )- .context("run native encoder for segment")+ let result = encoder.run(+ Arc::new(AtomicBool::default()),+ || {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more frames available for segment");+ return Ok(None);+ };++ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };+ let frame_time = duration_to_timespan(relative);++ Ok(Some((frame.texture().clone(), frame_time)))+ },+ |output_sample| {+ let mut output = output_clone.lock().unwrap();++ let _ = muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| format!("WriteSample: {e}"));++ Ok(())+ },+ );++ match result {+ Ok(health_status) => {+ debug!(+ "Hardware encoder completed for segment: {} frames encoded",+ health_status.total_frames_encoded+ );+ 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(anyhow!("Hardware encoder error: {}", e))+ }+ }}either::Right(mut encoder) => {while let Ok(Some((frame, time))) = video_rx.recv() {diff --git a/crates/recording/src/output_pipeline/win_segmented_camera.rs b/crates/recording/src/output_pipeline/win_segmented_camera.rsindex 88462f1d6..36ec47c86 100644--- a/crates/recording/src/output_pipeline/win_segmented_camera.rs+++ b/crates/recording/src/output_pipeline/win_segmented_camera.rs@@ -430,6 +430,12 @@ impl WindowsSegmentedCameraMuxer {bitrate_multiplier,) {Ok(encoder) => {+ if let Err(e) = encoder.validate() {+ return fallback(Some(format!(+ "Camera hardware encoder validation failed: {e}"+ )));+ }+let muxer = {let mut output_guard = match output_clone.lock() {Ok(guard) => guard,@@ -491,38 +497,56 @@ impl WindowsSegmentedCameraMuxer {let mut first_timestamp: Option<Duration> = None;- encoder- .run(- Arc::new(AtomicBool::default()),- || {- let Ok(Some((frame, timestamp))) = video_rx.recv() else {- trace!("No more camera frames available for segment");- return Ok(None);- };-- let relative = if let Some(first) = first_timestamp {- timestamp.checked_sub(first).unwrap_or(Duration::ZERO)- } else {- first_timestamp = Some(timestamp);- Duration::ZERO- };-- let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;- Ok(Some((texture, duration_to_timespan(relative))))- },- |output_sample| {- let mut output = output_clone.lock().unwrap();- muxer- .write_sample(&output_sample, &mut output)- .map_err(|e| {- windows::core::Error::new(- windows::core::HRESULT(-1),- format!("WriteSample: {e}"),- )- })- },- )- .context("run camera encoder for segment")+ let result = encoder.run(+ Arc::new(AtomicBool::default()),+ || {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more camera frames available for segment");+ return Ok(None);+ };++ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };++ let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;+ Ok(Some((texture, duration_to_timespan(relative))))+ },+ |output_sample| {+ let mut output = output_clone.lock().unwrap();+ muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| {+ windows::core::Error::new(+ windows::core::HRESULT(-1),+ format!("WriteSample: {e}"),+ )+ })+ },+ );++ match result {+ Ok(health_status) => {+ info!(+ "Camera segment encoder finished (hardware): {} frames encoded",+ health_status.total_frames_encoded+ );+ Ok(())+ }+ 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(anyhow!("Camera hardware encoder error: {}", e))+ }+ }}either::Right(mut encoder) => {info!(diff --git a/crates/scap-direct3d/Cargo.toml b/crates/scap-direct3d/Cargo.tomlindex f95306ec8..928ce647c 100644--- a/crates/scap-direct3d/Cargo.toml+++ b/crates/scap-direct3d/Cargo.toml@@ -30,6 +30,7 @@ windows = { workspace = true, features = ["Storage_Search","Storage_Streams","Win32_System_SystemInformation",+ "Win32_System_LibraryLoader",] }[dev-dependencies]