Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add option to force FFmpeg decoder for video export
Richie McIlroye515f45f85b7
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex 3516da005..b2dde7d1d 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -31,21 +31,15 @@ impl ExportSettings {}}-#[tauri::command]-#[specta::specta]-#[instrument(skip(progress))]-pub async fn export_video(- project_path: PathBuf,- progress: tauri::ipc::Channel<FramesRendered>,- settings: ExportSettings,+async fn do_export(+ project_path: &PathBuf,+ settings: &ExportSettings,+ progress: &tauri::ipc::Channel<FramesRendered>,) -> Result<PathBuf, String> {- let exporter_base = ExporterBase::builder(project_path)+ let exporter_base = ExporterBase::builder(project_path.clone()).build().await- .map_err(|e| {- sentry::capture_message(&e.to_string(), sentry::Level::Error);- e.to_string()- })?;+ .map_err(|e| e.to_string())?;let total_frames = exporter_base.total_frames(settings.fps());@@ -54,11 +48,11 @@ pub async fn export_video(total_frames,});- let output_path = match settings {- ExportSettings::Mp4(settings) => {- settings+ match settings {+ ExportSettings::Mp4(mp4_settings) => {+ let progress = progress.clone();+ mp4_settings.export(exporter_base, move |frame_index| {- // Ensure progress never exceeds total framesprogress.send(FramesRendered {rendered_count: (frame_index + 1).min(total_frames),@@ -68,10 +62,10 @@ pub async fn export_video(}).await}- ExportSettings::Gif(settings) => {- settings+ ExportSettings::Gif(gif_settings) => {+ let progress = progress.clone();+ gif_settings.export(exporter_base, move |frame_index| {- // Ensure progress never exceeds total framesprogress.send(FramesRendered {rendered_count: (frame_index + 1).min(total_frames),@@ -82,14 +76,68 @@ pub async fn export_video(.await}}- .map_err(|e| {- sentry::capture_message(&e.to_string(), sentry::Level::Error);- e.to_string()- })?;+}- info!("Exported to {} completed", output_path.display());+fn is_frame_decode_error(error: &str) -> bool {+ error.contains("Failed to decode video frames")+ || error.contains("FrameDecodeFailed")+ || error.contains("Too many consecutive frame failures")+}- Ok(output_path)+#[tauri::command]+#[specta::specta]+#[instrument(skip(progress))]+pub async fn export_video(+ project_path: PathBuf,+ progress: tauri::ipc::Channel<FramesRendered>,+ settings: ExportSettings,+) -> Result<PathBuf, String> {+ let force_ffmpeg = match &settings {+ ExportSettings::Mp4(s) => s.force_ffmpeg_decoder,+ ExportSettings::Gif(_) => false,+ };+ cap_rendering::set_force_ffmpeg_decoder(force_ffmpeg);++ let result = do_export(&project_path, &settings, &progress).await;++ match result {+ Ok(path) => {+ cap_rendering::set_force_ffmpeg_decoder(false);+ info!("Exported to {} completed", path.display());+ Ok(path)+ }+ Err(e) if !force_ffmpeg && is_frame_decode_error(&e) => {+ info!(+ "Export failed with frame decode error, retrying with FFmpeg decoder: {}",+ e+ );++ cap_rendering::set_force_ffmpeg_decoder(true);++ let retry_result = do_export(&project_path, &settings, &progress).await;++ cap_rendering::set_force_ffmpeg_decoder(false);++ match retry_result {+ Ok(path) => {+ info!(+ "Export succeeded with FFmpeg decoder fallback: {}",+ path.display()+ );+ Ok(path)+ }+ Err(retry_e) => {+ sentry::capture_message(&retry_e, sentry::Level::Error);+ Err(retry_e)+ }+ }+ }+ Err(e) => {+ cap_rendering::set_force_ffmpeg_decoder(false);+ sentry::capture_message(&e, sentry::Level::Error);+ Err(e)+ }+ }}#[derive(Debug, serde::Serialize, specta::Type)]diff --git a/apps/desktop/src/routes/editor/ExportPage.tsx b/apps/desktop/src/routes/editor/ExportPage.tsxindex f6b34ce7e..5033de03e 100644--- a/apps/desktop/src/routes/editor/ExportPage.tsx+++ b/apps/desktop/src/routes/editor/ExportPage.tsx@@ -224,6 +224,7 @@ export function ExportPage() {COMPRESSION_TO_BPP[_settings.compression] ?? 0.15,);const [advancedMode, setAdvancedMode] = createSignal(false);+ const [forceFfmpegDecoder, setForceFfmpegDecoder] = createSignal(false);const isCustomBpp = () => {const currentBpp = compressionBpp();@@ -369,6 +370,7 @@ export function ExportPage() {},compression: settings.compression,custom_bpp: customBpp,+ force_ffmpeg_decoder: forceFfmpegDecoder(),}: {format: "Gif",@@ -1083,6 +1085,42 @@ export function ExportPage() {Using custom bitrate</p></Show>++ <Show+ when={ostype() === "macos" && settings.format === "Mp4"}+ >+ <div class="mt-4 pt-3 border-t border-gray-4">+ <button+ type="button"+ class="flex items-center gap-2 text-xs text-gray-11 hover:text-gray-12 transition-colors w-full"+ onClick={() =>+ setForceFfmpegDecoder(!forceFfmpegDecoder())+ }+ >+ <div+ class={cx(+ "w-8 h-4 rounded-full transition-colors relative flex-shrink-0",+ forceFfmpegDecoder() ? "bg-blue-9" : "bg-gray-5",+ )}+ >+ <div+ class={cx(+ "absolute top-0.5 w-3 h-3 rounded-full bg-white transition-transform",+ forceFfmpegDecoder()+ ? "translate-x-4"+ : "translate-x-0.5",+ )}+ />+ </div>+ <div class="text-left">+ <span class="block">Force FFmpeg decoder</span>+ <span class="text-[10px] text-gray-9">+ Skip hardware decoder (auto-fallback enabled)+ </span>+ </div>+ </button>+ </div>+ </Show></div></Show></Field>diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex f47420ef1..52627a33e 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -389,7 +389,6 @@ videoImportProgress: "video-import-progress"/** user-defined types **/-export type AllGpusInfo = { gpus: GpuInfoDiag[]; primaryGpuIndex: number | null; isMultiGpuSystem: boolean; hasDiscreteGpu: boolean }export type Annotation = { id: string; type: AnnotationType; x: number; y: number; width: number; height: number; strokeColor: string; strokeWidth: number; fillColor: string; opacity: number; rotation: number; text: string | null; maskType?: MaskType | null; maskLevel?: number | null }export type AnnotationType = "arrow" | "circle" | "rectangle" | "text" | "mask"export type AppTheme = "system" | "light" | "dark"@@ -461,7 +460,6 @@ quality: number | null;*/fast: boolean | null }export type GlideDirection = "none" | "left" | "right" | "up" | "down"-export type GpuInfoDiag = { vendor: string; description: string; dedicatedVideoMemoryMb: number; adapterIndex: number; isSoftwareAdapter: boolean; isBasicRenderDriver: boolean; supportsHardwareEncoding: boolean }export type HapticPattern = "alignment" | "levelChange" | "generic"export type HapticPerformanceTime = "default" | "now" | "drawCompleted"export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }@@ -475,6 +473,7 @@ export type JsonValue<T> = [T]export type LogicalBounds = { position: LogicalPosition; size: LogicalSize }export type LogicalPosition = { x: number; y: number }export type LogicalSize = { width: number; height: number }+export type MacOSVersionInfo = { major: number; minor: number; patch: number; displayName: string; buildNumber: string; isAppleSilicon: boolean }export type MainWindowRecordingStartBehaviour = "close" | "minimise"export type MaskKeyframes = { position?: MaskVectorKeyframe[]; size?: MaskVectorKeyframe[]; intensity?: MaskScalarKeyframe[] }export type MaskKind = "sensitive" | "highlight"@@ -483,7 +482,7 @@ export type MaskSegment = { start: number; end: number; enabled?: boolean; maskTexport type MaskType = "blur" | "pixelate"export type MaskVectorKeyframe = { time: number; x: number; y: number }export type ModelIDType = string-export type Mp4ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression; custom_bpp: number | null }+export type Mp4ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression; custom_bpp: number | null; force_ffmpeg_decoder?: boolean }export type MultipleSegment = { display: VideoMeta; camera?: VideoMeta | null; mic?: AudioMeta | null; system_audio?: AudioMeta | null; cursor?: string | null }export type MultipleSegments = { segments: MultipleSegment[]; cursors: Cursors; status?: StudioRecordingStatus | null }export type NewNotification = { title: string; body: string; is_error: boolean }@@ -517,7 +516,6 @@ export type RecordingStatus = "pending" | "recording"export type RecordingStopped = nullexport type RecordingTargetMode = "display" | "window" | "area"export type RenderFrameEvent = { frame_number: number; fps: number; resolution_base: XY<number> }-export type RenderingStatus = { isUsingSoftwareRendering: boolean; isUsingBasicRenderDriver: boolean; hardwareEncodingAvailable: boolean; warningMessage: string | null }export type RequestOpenRecordingPicker = { target_mode: RecordingTargetMode | null }export type RequestOpenSettings = { page: string }export type RequestScreenCapturePrewarm = { force?: boolean }@@ -539,7 +537,7 @@ export type StartRecordingInputs = { capture_target: ScreenCaptureTarget; capturexport type StereoMode = "stereo" | "monoL" | "monoR"export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }export type StudioRecordingStatus = { status: "InProgress" } | { status: "NeedsRemux" } | { status: "Failed"; error: string } | { status: "Complete" }-export type SystemDiagnostics = { windowsVersion: WindowsVersionInfo | null; gpuInfo: GpuInfoDiag | null; allGpus: AllGpusInfo | null; renderingStatus: RenderingStatus; availableEncoders: string[]; graphicsCaptureSupported: boolean; d3D11VideoProcessorAvailable: boolean }+export type SystemDiagnostics = { macosVersion: MacOSVersionInfo | null; availableEncoders: string[]; screenCaptureSupported: boolean; metalSupported: boolean; gpuName: string | null }export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }export type TextSegment = { start: number; end: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string; fadeDuration?: number }export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[] }@@ -557,7 +555,6 @@ export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }export type WindowExclusion = { bundleIdentifier?: string | null; ownerName?: string | null; windowTitle?: string | null }export type WindowId = stringexport type WindowUnderCursor = { id: WindowId; app_name: string; bounds: LogicalBounds }-export type WindowsVersionInfo = { major: number; minor: number; build: number; displayName: string; meetsRequirements: boolean; isWindows11: boolean }export type XY<T> = { x: T; y: T }export type ZoomMode = "auto" | { manual: { x: number; y: number } }export type ZoomSegment = { start: number; end: number; amount: number; mode: ZoomMode; glideDirection?: GlideDirection; glideSpeed?: number; instantAnimation?: boolean; edgeSnapRatio?: number }diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rsindex e8c26818a..848a48f4b 100644--- a/crates/export/src/mp4.rs+++ b/crates/export/src/mp4.rs@@ -36,6 +36,8 @@ pub struct Mp4ExportSettings {pub resolution_base: XY<u32>,pub compression: ExportCompression,pub custom_bpp: Option<f32>,+ #[serde(default)]+ pub force_ffmpeg_decoder: bool,}impl Mp4ExportSettings {diff --git a/crates/export/tests/export_benchmark.rs b/crates/export/tests/export_benchmark.rsindex a4d98184b..99540b6cd 100644--- a/crates/export/tests/export_benchmark.rs+++ b/crates/export/tests/export_benchmark.rs@@ -26,6 +26,7 @@ async fn run_export(project_path: PathBuf) -> Result<(PathBuf, Duration, u32), Sresolution_base: XY::new(1920, 1080),compression: ExportCompression::Maximum,custom_bpp: None,+ force_ffmpeg_decoder: false,};let start = Instant::now();diff --git a/crates/export/tests/long_video_export.rs b/crates/export/tests/long_video_export.rsindex 1e16ff2a4..279eca426 100644--- a/crates/export/tests/long_video_export.rs+++ b/crates/export/tests/long_video_export.rs@@ -133,6 +133,7 @@ async fn run_export(project_path: PathBuf, fps: u32) -> Result<(PathBuf, Duratioresolution_base: XY::new(TEST_VIDEO_WIDTH, TEST_VIDEO_HEIGHT),compression: ExportCompression::Potato,custom_bpp: None,+ force_ffmpeg_decoder: false,};let total_frames = exporter_base.total_frames(fps);diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rsindex f0baaaf3c..f4cc76895 100644--- a/crates/rendering/src/decoder/mod.rs+++ b/crates/rendering/src/decoder/mod.rs@@ -2,12 +2,29 @@ use ::ffmpeg::Rational;use std::{fmt,path::PathBuf,- sync::{Arc, mpsc},+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ mpsc,+ },time::Duration,};use tokio::sync::oneshot;use tracing::info;+static FORCE_FFMPEG_DECODER: AtomicBool = AtomicBool::new(false);++pub fn set_force_ffmpeg_decoder(force: bool) {+ FORCE_FFMPEG_DECODER.store(force, Ordering::SeqCst);+ if force {+ tracing::info!("FFmpeg decoder forced via experimental setting");+ }+}++pub fn is_ffmpeg_decoder_forced() -> bool {+ FORCE_FFMPEG_DECODER.load(Ordering::SeqCst)+}+#[cfg(target_os = "macos")]mod avassetreader;mod ffmpeg;@@ -468,12 +485,12 @@ impl AsyncVideoDecoderHandle {return None;}- match tokio::time::timeout(std::time::Duration::from_millis(2000), rx).await {+ match tokio::time::timeout(std::time::Duration::from_millis(1000), rx).await {Ok(result) => result.ok(),Err(_) => {tracing::warn!(time = adjusted_time,- "Frame decode request timed out after 2000ms"+ "Frame decode request timed out after 1000ms");None}@@ -505,6 +522,48 @@ impl AsyncVideoDecoderHandle {}}+async fn spawn_ffmpeg_decoder(+ name: &'static str,+ path: PathBuf,+ fps: u32,+ offset: f64,+ timeout_duration: Duration,+ path_display: &str,+) -> Result<AsyncVideoDecoderHandle, String> {+ 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 decoder / {e}"))?;++ 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}' 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}"+ )),+ }+}+pub async fn spawn_decoder(name: &'static str,path: PathBuf,@@ -516,34 +575,94 @@ pub async fn spawn_decoder(#[cfg(target_os = "macos")]{- let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();- let (tx, rx) = mpsc::channel();+ if is_ffmpeg_decoder_forced() {+ info!(+ "Video '{}' using FFmpeg decoder (forced via experimental setting)",+ name+ );+ return spawn_ffmpeg_decoder(name, path, fps, offset, timeout_duration, &path_display)+ .await;+ }- avassetreader::AVAssetReaderDecoder::spawn(name, path, fps, rx, ready_tx);+ let avasset_result = {+ let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();+ let (tx, rx) = mpsc::channel();++ avassetreader::AVAssetReaderDecoder::spawn(name, path.clone(), 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!("AVAssetReader initialization failed: {e}")),+ Ok(Err(e)) => Err(format!("AVAssetReader channel closed: {e}")),+ Err(_) => Err(format!(+ "AVAssetReader 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+ match avasset_result {+ Ok(handle) => Ok(handle),+ Err(avasset_error) => {+ tracing::warn!(+ name = name,+ error = %avasset_error,+ "AVAssetReader failed, falling back to FFmpeg decoder");- 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,- })++ let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();+ let (tx, rx) = mpsc::channel();++ if let Err(e) = ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx) {+ return Err(format!(+ "'{name}' decoder failed - AVAssetReader: {avasset_error}, FFmpeg: {e}"+ ));+ }++ match tokio::time::timeout(timeout_duration, ready_rx).await {+ Ok(Ok(Ok(init_result))) => {+ info!(+ "Video '{}' using {} decoder ({}x{}) after AVAssetReader failure",+ 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(avasset_error),+ };+ Ok(AsyncVideoDecoderHandle {+ sender: tx,+ offset,+ status,+ })+ }+ Ok(Ok(Err(e))) => Err(format!(+ "'{name}' decoder failed - AVAssetReader: {avasset_error}, FFmpeg: {e}"+ )),+ Ok(Err(e)) => Err(format!(+ "'{name}' decoder failed - AVAssetReader: {avasset_error}, FFmpeg channel: {e}"+ )),+ Err(_) => Err(format!(+ "'{name}' decoder failed - AVAssetReader: {avasset_error}, FFmpeg timed out"+ )),+ }}- 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 fa4e68582..b9c144422 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -7,6 +7,7 @@ use composite_frame::CompositeVideoFrameUniforms;use core::f64;use cursor_interpolation::{InterpolatedCursorPosition, interpolate_cursor};use decoder::{AsyncVideoDecoderHandle, spawn_decoder};+pub use decoder::{is_ffmpeg_decoder_forced, set_force_ffmpeg_decoder};use frame_pipeline::{RenderSession, finish_encoder};use futures::FutureExt;use futures::future::OptionFuture;@@ -235,6 +236,13 @@ pub enum RenderingError {ImageLoadError(String),#[error("Error polling wgpu: {0}")]PollError(#[from] wgpu::PollError),+ #[error(+ "Failed to decode video frames. The recording may be corrupted or incomplete. Try re-recording or contact support if the issue persists."+ )]+ FrameDecodeFailed {+ frame_number: u32,+ consecutive_failures: u32,+ },}pub struct RenderSegment {@@ -322,12 +330,11 @@ pub async fn render_video_to_channel(let mut segment_frames = None;let mut retry_count = 0;- const MAX_RETRIES: u32 = 5;+ const MAX_RETRIES: u32 = 3;while segment_frames.is_none() && retry_count < MAX_RETRIES {if retry_count > 0 {- tokio::time::sleep(std::time::Duration::from_millis(100 * retry_count as u64))- .await;+ tokio::time::sleep(std::time::Duration::from_millis(50 * retry_count as u64)).await;}segment_frames = render_segment@@ -423,7 +430,10 @@ pub async fn render_video_to_channel(consecutive_failures = consecutive_failures,"Too many consecutive frame failures - aborting export");- return Err(RenderingError::BufferMapWaitingFailed);+ return Err(RenderingError::FrameDecodeFailed {+ frame_number: current_frame_number,+ consecutive_failures,+ });}if let Some(ref last_frame) = last_successful_frame {@@ -431,8 +441,8 @@ pub async fn render_video_to_channel(frame_number = current_frame_number,segment_time = segment_time,consecutive_failures = consecutive_failures,- "Frame decode failed after {} retries - using previous frame",- MAX_RETRIES+ max_retries = MAX_RETRIES,+ "Frame decode failed after retries - using previous frame");let mut fallback = last_frame.clone();fallback.frame_number = current_frame_number;@@ -443,8 +453,8 @@ pub async fn render_video_to_channel(tracing::error!(frame_number = current_frame_number,segment_time = segment_time,- "First frame decode failed after {} retries - cannot continue",- MAX_RETRIES+ max_retries = MAX_RETRIES,+ "First frame decode failed after retries - cannot continue");continue;}diff --git a/crates/rendering/src/zoom.rs b/crates/rendering/src/zoom.rsindex 2ce9e9cc5..73582bdcd 100644--- a/crates/rendering/src/zoom.rs+++ b/crates/rendering/src/zoom.rs@@ -901,8 +901,7 @@ mod test {let result = zoom.ensure_cursor_visible(cursor_pos);assert!(cursor_is_visible_in_zoom(&result, cursor_pos),- "Cursor at {:?} should be visible",- cursor_pos+ "Cursor at {cursor_pos:?} should be visible");}}