Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add decoder type/status reporting and health monitoring
Richie McIlroyb4fcdd5b19e9
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rsindex 8192e0c2c..408490097 100644--- a/crates/rendering/src/decoder/avassetreader.rs+++ b/crates/rendering/src/decoder/avassetreader.rs@@ -18,7 +18,7 @@ use tokio::{runtime::Handle as TokioHandle, sync::oneshot};use crate::{DecodedFrame, PixelFormat};use super::frame_converter::{copy_bgra_to_rgba, copy_rgba_plane};-use super::{FRAME_CACHE_SIZE, VideoDecoderMessage, pts_to_frame};+use super::{DecoderInitResult, DecoderType, FRAME_CACHE_SIZE, VideoDecoderMessage, pts_to_frame};#[derive(Clone)]struct ProcessedFrame {@@ -253,7 +253,7 @@ impl AVAssetReaderDecoder {path: PathBuf,fps: u32,rx: mpsc::Receiver<VideoDecoderMessage>,- ready_tx: oneshot::Sender<Result<(), String>>,+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,) {let handle = tokio::runtime::Handle::current();@@ -265,14 +265,11 @@ impl AVAssetReaderDecoder {path: PathBuf,fps: u32,rx: mpsc::Receiver<VideoDecoderMessage>,- ready_tx: oneshot::Sender<Result<(), String>>,+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,tokio_handle: tokio::runtime::Handle,) {let mut this = match AVAssetReaderDecoder::new(path, tokio_handle) {- Ok(v) => {- ready_tx.send(Ok(())).ok();- v- }+ Ok(v) => v,Err(e) => {ready_tx.send(Err(e)).ok();return;@@ -282,6 +279,13 @@ impl AVAssetReaderDecoder {let video_width = this.inner.width();let video_height = this.inner.height();+ let init_result = DecoderInitResult {+ width: video_width,+ height: video_height,+ decoder_type: DecoderType::AVAssetReader,+ };+ ready_tx.send(Ok(init_result)).ok();+let mut cache = BTreeMap::<u32, CachedFrame>::new();#[allow(unused)]diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rsindex 450e8db07..8504f14b8 100644--- a/crates/rendering/src/decoder/ffmpeg.rs+++ b/crates/rendering/src/decoder/ffmpeg.rs@@ -10,10 +10,14 @@ use std::{sync::{Arc, mpsc},};use tokio::sync::oneshot;+use tracing::info;use crate::{DecodedFrame, PixelFormat};-use super::{FRAME_CACHE_SIZE, VideoDecoderMessage, frame_converter::FrameConverter, pts_to_frame};+use super::{+ DecoderInitResult, DecoderType, FRAME_CACHE_SIZE, VideoDecoderMessage,+ frame_converter::FrameConverter, pts_to_frame,+};#[derive(Clone)]struct ProcessedFrame {@@ -134,29 +138,36 @@ pub struct FfmpegDecoder;impl FfmpegDecoder {pub fn spawn(- _name: &'static str,+ name: &'static str,path: PathBuf,fps: u32,rx: mpsc::Receiver<VideoDecoderMessage>,- ready_tx: oneshot::Sender<Result<(), String>>,+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,) -> Result<(), String> {- let (continue_tx, continue_rx) = mpsc::channel();+ let (continue_tx, continue_rx) = mpsc::channel::<Result<(u32, u32, bool), String>>();std::thread::spawn(move || {- let mut this = match cap_video_decode::FFmpegDecoder::new(- path,- Some(if cfg!(target_os = "macos") {- AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX- } else {- AVHWDeviceType::AV_HWDEVICE_TYPE_DXVA2- }),- ) {+ let hw_device_type = if cfg!(target_os = "macos") {+ Some(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX)+ } else {+ Some(AVHWDeviceType::AV_HWDEVICE_TYPE_DXVA2)+ };++ let mut this = match cap_video_decode::FFmpegDecoder::new(path.clone(), hw_device_type)+ {Err(e) => {let _ = continue_tx.send(Err(e));return;}Ok(v) => {- let _ = continue_tx.send(Ok(()));+ let is_hw = v.is_hardware_accelerated();+ let width = v.decoder().width();+ let height = v.decoder().height();+ info!(+ "FFmpeg decoder created for '{}': {}x{}, hw_accel={}",+ name, width, height, is_hw+ );+ let _ = continue_tx.send(Ok((width, height, is_hw)));v}};@@ -165,10 +176,9 @@ impl FfmpegDecoder {let start_time = this.start_time();let video_width = this.decoder().width();let video_height = this.decoder().height();+ let is_hw = this.is_hardware_accelerated();let mut cache = BTreeMap::<u32, CachedFrame>::new();- // active frame is a frame that triggered decode.- // frames that are within render_more_margin of this frame won't trigger decode.#[allow(unused)]let mut last_active_frame = None::<u32>;@@ -177,7 +187,17 @@ impl FfmpegDecoder {let mut frames = this.frames();let mut converter = FrameConverter::new();- let _ = ready_tx.send(Ok(()));+ let decoder_type = if is_hw {+ DecoderType::FFmpegHardware+ } else {+ DecoderType::FFmpegSoftware+ };+ let init_result = DecoderInitResult {+ width: video_width,+ height: video_height,+ decoder_type,+ };+ let _ = ready_tx.send(Ok(init_result));while let Ok(r) = rx.recv() {match r {@@ -356,9 +376,7 @@ impl FfmpegDecoder {}});- continue_rx.recv().map_err(|e| e.to_string())??;-- Ok(())+ continue_rx.recv().map_err(|e| e.to_string())?.map(|_| ())}}diff --git a/crates/rendering/src/decoder/media_foundation.rs b/crates/rendering/src/decoder/media_foundation.rsindex 2963f09c0..18a142b73 100644--- a/crates/rendering/src/decoder/media_foundation.rs+++ b/crates/rendering/src/decoder/media_foundation.rs@@ -2,12 +2,88 @@ use std::{collections::BTreeMap,path::PathBuf,sync::{Arc, mpsc},+ time::{Duration, Instant},};use tokio::sync::oneshot;use tracing::{debug, info, warn};use windows::Win32::{Foundation::HANDLE, Graphics::Direct3D11::ID3D11Texture2D};-use super::{DecodedFrame, FRAME_CACHE_SIZE, VideoDecoderMessage};+use super::{DecodedFrame, DecoderInitResult, DecoderType, FRAME_CACHE_SIZE, VideoDecoderMessage};++struct DecoderHealthMonitor {+ consecutive_errors: u32,+ consecutive_texture_read_failures: u32,+ total_frames_decoded: u64,+ total_errors: u64,+ last_successful_decode: Instant,+ frame_decode_times: [Duration; 32],+ frame_decode_index: usize,+ slow_frame_count: u32,+}++impl DecoderHealthMonitor {+ fn new() -> Self {+ Self {+ consecutive_errors: 0,+ consecutive_texture_read_failures: 0,+ total_frames_decoded: 0,+ total_errors: 0,+ last_successful_decode: Instant::now(),+ frame_decode_times: [Duration::ZERO; 32],+ frame_decode_index: 0,+ slow_frame_count: 0,+ }+ }++ fn record_success(&mut self, decode_time: Duration) {+ self.consecutive_errors = 0;+ self.consecutive_texture_read_failures = 0;+ self.total_frames_decoded += 1;+ self.last_successful_decode = Instant::now();++ self.frame_decode_times[self.frame_decode_index] = decode_time;+ self.frame_decode_index = (self.frame_decode_index + 1) % 32;++ const SLOW_FRAME_THRESHOLD: Duration = Duration::from_millis(100);+ if decode_time > SLOW_FRAME_THRESHOLD {+ self.slow_frame_count += 1;+ }+ }++ fn record_error(&mut self) {+ self.consecutive_errors += 1;+ self.total_errors += 1;+ }++ fn record_texture_read_failure(&mut self) {+ self.consecutive_texture_read_failures += 1;+ }++ fn is_healthy(&self) -> bool {+ const MAX_CONSECUTIVE_ERRORS: u32 = 10;+ const MAX_CONSECUTIVE_TEXTURE_FAILURES: u32 = 5;+ const MAX_TIME_SINCE_SUCCESS: Duration = Duration::from_secs(5);++ self.consecutive_errors < MAX_CONSECUTIVE_ERRORS+ && self.consecutive_texture_read_failures < MAX_CONSECUTIVE_TEXTURE_FAILURES+ && self.last_successful_decode.elapsed() < MAX_TIME_SINCE_SUCCESS+ }++ #[allow(dead_code)]+ fn average_decode_time(&self) -> Duration {+ let sum: Duration = self.frame_decode_times.iter().sum();+ sum / 32+ }++ #[allow(dead_code)]+ fn get_health_summary(&self) -> (u64, u64, u32) {+ (+ self.total_frames_decoded,+ self.total_errors,+ self.slow_frame_count,+ )+ }+}#[derive(Clone)]struct CachedFrame {@@ -49,7 +125,7 @@ impl MFDecoder {path: PathBuf,fps: u32,rx: mpsc::Receiver<VideoDecoderMessage>,- ready_tx: oneshot::Sender<Result<(), String>>,+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,) -> Result<(), String> {let (continue_tx, continue_rx) = mpsc::channel();@@ -60,14 +136,34 @@ impl MFDecoder {return;}Ok(v) => {+ let width = v.width();+ let height = v.height();+ let caps = v.capabilities();++ let exceeds_hw_limits = width > caps.max_width || height > caps.max_height;++ if exceeds_hw_limits {+ warn!(+ "Video '{}' dimensions {}x{} exceed hardware decoder limits ({}x{})",+ name, width, height, caps.max_width, caps.max_height+ );+ let _ = continue_tx.send(Err(format!(+ "Video dimensions {}x{} exceed hardware decoder limits {}x{}",+ width, height, caps.max_width, caps.max_height+ )));+ return;+ }+info!(- "MediaFoundation decoder created for '{}': {}x{} @ {:?}fps",+ "MediaFoundation decoder created for '{}': {}x{} @ {:?}fps (hw max: {}x{})",name,- v.width(),- v.height(),- v.frame_rate()+ width,+ height,+ v.frame_rate(),+ caps.max_width,+ caps.max_height);- let _ = continue_tx.send(Ok(()));+ let _ = continue_tx.send(Ok((width, height)));v}};@@ -77,8 +173,14 @@ impl MFDecoder {let mut cache = BTreeMap::<u32, CachedFrame>::new();let mut last_decoded_frame: Option<u32> = None;+ let mut health = DecoderHealthMonitor::new();- let _ = ready_tx.send(Ok(()));+ let init_result = DecoderInitResult {+ width: video_width,+ height: video_height,+ decoder_type: DecoderType::MediaFoundation,+ };+ let _ = ready_tx.send(Ok(init_result));while let Ok(r) = rx.recv() {match r {@@ -87,6 +189,16 @@ impl MFDecoder {continue;}+ if !health.is_healthy() {+ warn!(+ name = name,+ consecutive_errors = health.consecutive_errors,+ texture_failures = health.consecutive_texture_read_failures,+ total_decoded = health.total_frames_decoded,+ "MediaFoundation decoder unhealthy, performance may degrade"+ );+ }+let requested_frame = (requested_time * fps as f32).floor() as u32;if let Some(cached) = cache.get(&requested_frame) {@@ -123,8 +235,10 @@ impl MFDecoder {let mut last_valid_frame: Option<CachedFrame> = None;loop {+ let decode_start = Instant::now();match decoder.read_sample() {Ok(Some(mf_frame)) => {+ let decode_time = decode_start.elapsed();let frame_number = pts_100ns_to_frame(mf_frame.pts, fps);let nv12_data = match decoder.read_texture_to_cpu(@@ -133,6 +247,7 @@ impl MFDecoder {mf_frame.height,) {Ok(data) => {+ health.record_success(decode_time);debug!(frame = frame_number,data_len = data.data.len(),@@ -140,11 +255,13 @@ impl MFDecoder {uv_stride = data.uv_stride,width = mf_frame.width,height = mf_frame.height,+ decode_ms = decode_time.as_millis(),"read_texture_to_cpu succeeded");Some(Arc::new(data))}Err(e) => {+ health.record_texture_read_failure();warn!("Failed to read texture to CPU for frame {frame_number}: {e}");@@ -211,7 +328,11 @@ impl MFDecoder {break;}Err(e) => {- warn!("MediaFoundation read_sample error: {e}");+ health.record_error();+ warn!(+ consecutive_errors = health.consecutive_errors,+ "MediaFoundation read_sample error: {e}"+ );break;}}@@ -243,9 +364,7 @@ impl MFDecoder {}});- continue_rx.recv().map_err(|e| e.to_string())??;-- Ok(())+ continue_rx.recv().map_err(|e| e.to_string())?.map(|_| ())}}diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rsindex 765f0d45a..4ba74a146 100644--- a/crates/rendering/src/decoder/mod.rs+++ b/crates/rendering/src/decoder/mod.rs@@ -3,9 +3,10 @@ use std::{fmt,path::PathBuf,sync::{Arc, mpsc},+ time::Duration,};use tokio::sync::oneshot;-use tracing::debug;+use tracing::{debug, info, warn};#[cfg(target_os = "macos")]mod avassetreader;@@ -14,6 +15,57 @@ mod frame_converter;#[cfg(target_os = "windows")]mod media_foundation;+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DecoderType {+ #[cfg(target_os = "macos")]+ AVAssetReader,+ #[cfg(target_os = "windows")]+ MediaFoundation,+ FFmpegHardware,+ FFmpegSoftware,+}++impl DecoderType {+ pub fn is_hardware_accelerated(&self) -> bool {+ match self {+ #[cfg(target_os = "macos")]+ DecoderType::AVAssetReader => true,+ #[cfg(target_os = "windows")]+ DecoderType::MediaFoundation => true,+ DecoderType::FFmpegHardware => true,+ DecoderType::FFmpegSoftware => false,+ }+ }+}++impl fmt::Display for DecoderType {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ #[cfg(target_os = "macos")]+ DecoderType::AVAssetReader => write!(f, "AVAssetReader (hardware)"),+ #[cfg(target_os = "windows")]+ DecoderType::MediaFoundation => write!(f, "MediaFoundation (hardware)"),+ DecoderType::FFmpegHardware => write!(f, "FFmpeg (hardware)"),+ DecoderType::FFmpegSoftware => write!(f, "FFmpeg (software)"),+ }+ }+}++#[derive(Debug, Clone)]+pub struct DecoderStatus {+ pub decoder_type: DecoderType,+ pub video_width: u32,+ pub video_height: u32,+ pub fallback_reason: Option<String>,+}++#[derive(Debug, Clone)]+pub struct DecoderInitResult {+ pub width: u32,+ pub height: u32,+ pub decoder_type: DecoderType,+}+#[cfg(target_os = "macos")]use cidre::{arc::R, cv};@@ -403,6 +455,7 @@ pub const FRAME_CACHE_SIZE: usize = 750;pub struct AsyncVideoDecoderHandle {sender: mpsc::Sender<VideoDecoderMessage>,offset: f64,+ status: DecoderStatus,}impl AsyncVideoDecoderHandle {@@ -425,6 +478,26 @@ impl AsyncVideoDecoderHandle {pub fn get_time(&self, time: f32) -> f32 {time + self.offset as f32}++ pub fn decoder_status(&self) -> &DecoderStatus {+ &self.status+ }++ pub fn decoder_type(&self) -> DecoderType {+ self.status.decoder_type+ }++ pub fn is_hardware_accelerated(&self) -> bool {+ self.status.decoder_type.is_hardware_accelerated()+ }++ pub fn video_dimensions(&self) -> (u32, u32) {+ (self.status.video_width, self.status.video_height)+ }++ pub fn fallback_reason(&self) -> Option<&str> {+ self.status.fallback_reason.as_deref()+ }}pub async fn spawn_decoder(@@ -433,61 +506,160 @@ pub async fn spawn_decoder(fps: u32,offset: f64,) -> Result<AsyncVideoDecoderHandle, String> {- let (ready_tx, ready_rx) = oneshot::channel::<Result<(), String>>();- let (tx, rx) = mpsc::channel();-- let handle = AsyncVideoDecoderHandle { sender: tx, offset };-let path_display = path.display().to_string();+ let timeout_duration = Duration::from_secs(30);#[cfg(target_os = "macos")]{+ let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();+ let (tx, rx) = mpsc::channel();+avassetreader::AVAssetReaderDecoder::spawn(name, path, fps, rx, ready_tx);++ match tokio::time::timeout(timeout_duration, ready_rx).await {+ Ok(Ok(Ok(init_result))) => {+ info!(+ "Video '{}' using {} decoder ({}x{})",+ name, init_result.decoder_type, init_result.width, init_result.height+ );+ let status = DecoderStatus {+ decoder_type: init_result.decoder_type,+ video_width: init_result.width,+ video_height: init_result.height,+ fallback_reason: None,+ };+ Ok(AsyncVideoDecoderHandle {+ sender: tx,+ offset,+ status,+ })+ }+ Ok(Ok(Err(e))) => Err(format!("'{name}' decoder initialization failed: {e}")),+ Ok(Err(e)) => Err(format!("'{name}' decoder channel closed: {e}")),+ Err(_) => Err(format!(+ "'{name}' decoder timed out after 30s initializing: {path_display}"+ )),+ }}#[cfg(target_os = "windows")]{+ let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();+ let (tx, rx) = mpsc::channel();+match media_foundation::MFDecoder::spawn(name, path.clone(), fps, rx, ready_tx) {- Ok(()) => {- debug!("Using MediaFoundation decoder for '{name}'");- }+ Ok(()) => match tokio::time::timeout(timeout_duration, ready_rx).await {+ Ok(Ok(Ok(init_result))) => {+ info!(+ "Video '{}' using {} decoder ({}x{})",+ name, init_result.decoder_type, init_result.width, init_result.height+ );+ let status = DecoderStatus {+ decoder_type: init_result.decoder_type,+ video_width: init_result.width,+ video_height: init_result.height,+ fallback_reason: None,+ };+ return Ok(AsyncVideoDecoderHandle {+ sender: tx,+ offset,+ status,+ });+ }+ Ok(Ok(Err(e))) => {+ warn!(+ "MediaFoundation decoder ready but failed for '{}': {}, falling back to FFmpeg",+ name, e+ );+ }+ Ok(Err(e)) => {+ warn!(+ "MediaFoundation decoder channel closed for '{}': {}, falling back to FFmpeg",+ name, e+ );+ }+ Err(_) => {+ warn!(+ "MediaFoundation decoder timed out for '{}', falling back to FFmpeg",+ name+ );+ }+ },Err(mf_err) => {debug!(- "MediaFoundation decoder failed for '{name}': {mf_err}, falling back to FFmpeg"+ "MediaFoundation decoder spawn failed for '{}': {}, falling back to FFmpeg",+ name, mf_err);- let (ready_tx, ready_rx_new) = oneshot::channel::<Result<(), String>>();- let (tx, rx) = mpsc::channel();- let handle = AsyncVideoDecoderHandle { sender: tx, offset };-- ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx)- .map_err(|e| format!("'{name}' decoder / {e}"))?;-- return match tokio::time::timeout(std::time::Duration::from_secs(30), ready_rx_new)- .await- {- Ok(result) => result- .map_err(|e| format!("'{name}' decoder channel closed: {e}"))?- .map(|()| handle),- Err(_) => Err(format!(- "'{name}' decoder timed out after 30s initializing: {path_display}"- )),+ }+ }++ let fallback_reason =+ format!("MediaFoundation decoder unavailable for '{name}', using FFmpeg fallback");+ let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();+ let (tx, rx) = mpsc::channel();++ ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx)+ .map_err(|e| format!("'{name}' FFmpeg fallback decoder / {e}"))?;++ match tokio::time::timeout(timeout_duration, ready_rx).await {+ Ok(Ok(Ok(init_result))) => {+ info!(+ "Video '{}' using {} decoder ({}x{}) [fallback]",+ name, init_result.decoder_type, init_result.width, init_result.height+ );+ let status = DecoderStatus {+ decoder_type: init_result.decoder_type,+ video_width: init_result.width,+ video_height: init_result.height,+ fallback_reason: Some(fallback_reason),};+ Ok(AsyncVideoDecoderHandle {+ sender: tx,+ offset,+ status,+ })}+ Ok(Ok(Err(e))) => Err(format!(+ "'{name}' FFmpeg decoder initialization failed: {e}"+ )),+ Ok(Err(e)) => Err(format!("'{name}' FFmpeg decoder channel closed: {e}")),+ Err(_) => Err(format!(+ "'{name}' FFmpeg decoder timed out after 30s initializing: {path_display}"+ )),}}#[cfg(not(any(target_os = "macos", target_os = "windows")))]{+ let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();+ let (tx, rx) = mpsc::channel();+ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx).map_err(|e| format!("'{name}' decoder / {e}"))?;- }- match tokio::time::timeout(std::time::Duration::from_secs(30), ready_rx).await {- Ok(result) => result- .map_err(|e| format!("'{name}' decoder channel closed: {e}"))?- .map(|()| handle),- Err(_) => Err(format!(- "'{name}' decoder timed out after 30s initializing: {path_display}"- )),+ match tokio::time::timeout(timeout_duration, ready_rx).await {+ Ok(Ok(Ok(init_result))) => {+ info!(+ "Video '{}' using {} decoder ({}x{})",+ name, init_result.decoder_type, init_result.width, init_result.height+ );+ let status = DecoderStatus {+ decoder_type: init_result.decoder_type,+ video_width: init_result.width,+ video_height: init_result.height,+ fallback_reason: None,+ };+ Ok(AsyncVideoDecoderHandle {+ sender: tx,+ offset,+ status,+ })+ }+ Ok(Ok(Err(e))) => Err(format!("'{name}' decoder initialization failed: {e}")),+ Ok(Err(e)) => Err(format!("'{name}' decoder channel closed: {e}")),+ Err(_) => Err(format!(+ "'{name}' decoder timed out after 30s initializing: {path_display}"+ )),+ }}}diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex b781874bf..4da4bc794 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -40,7 +40,7 @@ pub mod yuv_converter;mod zoom;pub use coord::*;-pub use decoder::{DecodedFrame, PixelFormat};+pub use decoder::{DecodedFrame, DecoderStatus, DecoderType, PixelFormat};pub use frame_pipeline::RenderedFrame;pub use project_recordings::{ProjectRecordingsMeta, SegmentRecordings, Video};diff --git a/crates/video-decode/src/ffmpeg.rs b/crates/video-decode/src/ffmpeg.rsindex 354c71e93..7a7a69f29 100644--- a/crates/video-decode/src/ffmpeg.rs+++ b/crates/video-decode/src/ffmpeg.rs@@ -281,6 +281,10 @@ impl FFmpegDecoder {pub fn start_time(&self) -> i64 {self.start_time}++ pub fn is_hardware_accelerated(&self) -> bool {+ self.hw_device.is_some()+ }}unsafe impl Send for FFmpegDecoder {}