Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Improve video metadata extraction
Richie McIlroy250eb1a7ad0c
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex d881b3576..a64ec5f7c 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -4,7 +4,7 @@ use cap_export::ExporterBase;use cap_project::{RecordingMeta, XY};use cap_rendering::{FrameRenderer, ProjectRecordingsMeta, ProjectUniforms, RenderSegment, RenderVideoConstants,- RendererLayers,+ RendererLayers, ZoomFocusInterpolator, spring_mass_damper::SpringMassDamperSimulationConfig,};use image::codecs::jpeg::JpegEncoder;use serde::{Deserialize, Serialize};@@ -266,6 +266,25 @@ pub async fn generate_export_preview(.ok_or_else(|| "Failed to decode frame".to_string())?;let frame_number = (frame_time * settings.fps as f64).floor() as u32;+ let total_duration = project_config+ .timeline+ .as_ref()+ .map(|t| t.duration())+ .unwrap_or(0.0);++ let cursor_smoothing =+ (!project_config.cursor.raw).then_some(SpringMassDamperSimulationConfig {+ tension: project_config.cursor.tension,+ mass: project_config.cursor.mass,+ friction: project_config.cursor.friction,+ });++ let zoom_focus_interpolator = ZoomFocusInterpolator::new(+ &render_segment.cursor,+ cursor_smoothing,+ project_config.screen_movement_spring,+ total_duration,+ );let uniforms = ProjectUniforms::new(&render_constants,@@ -275,6 +294,8 @@ pub async fn generate_export_preview(settings.resolution_base,&render_segment.cursor,&segment_frames,+ total_duration,+ &zoom_focus_interpolator,);let mut frame_renderer = FrameRenderer::new(&render_constants);@@ -384,6 +405,25 @@ pub async fn generate_export_preview_fast(let segment_frames = segment_frames.ok_or_else(|| "Failed to decode frame".to_string())?;let frame_number = (frame_time * settings.fps as f64).floor() as u32;+ let total_duration = project_config+ .timeline+ .as_ref()+ .map(|t| t.duration())+ .unwrap_or(0.0);++ let cursor_smoothing =+ (!project_config.cursor.raw).then_some(SpringMassDamperSimulationConfig {+ tension: project_config.cursor.tension,+ mass: project_config.cursor.mass,+ friction: project_config.cursor.friction,+ });++ let zoom_focus_interpolator = ZoomFocusInterpolator::new(+ &segment_media.cursor,+ cursor_smoothing,+ project_config.screen_movement_spring,+ total_duration,+ );let uniforms = ProjectUniforms::new(&editor.render_constants,@@ -393,6 +433,8 @@ pub async fn generate_export_preview_fast(settings.resolution_base,&segment_media.cursor,&segment_frames,+ total_duration,+ &zoom_focus_interpolator,);let mut frame_renderer = FrameRenderer::new(&editor.render_constants);diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex d1d3418e1..9d032e4d6 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -16,6 +16,7 @@ mod frame_ws;mod general_settings;mod hotkeys;mod http_client;+mod import;mod logging;mod notifications;mod permissions;@@ -1467,6 +1468,12 @@ async fn get_editor_meta(editor: WindowEditorInstance) -> Result<RecordingMeta,let path = editor.project_path.clone();RecordingMeta::load_for_project(&path).map_err(|e| e.to_string())}++#[tauri::command]+#[specta::specta]+async fn get_recording_meta_by_path(project_path: PathBuf) -> Result<RecordingMeta, String> {+ RecordingMeta::load_for_project(&project_path).map_err(|e| e.to_string())+}#[tauri::command]#[specta::specta]#[instrument(skip(editor))]@@ -2578,6 +2585,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {export::get_export_estimates,export::generate_export_preview,export::generate_export_preview_fast,+ import::start_video_import,+ import::check_import_ready,copy_file_to_path,copy_video_to_clipboard,copy_screenshot_to_clipboard,@@ -2627,6 +2636,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {update_auth_plan,set_window_transparent,get_editor_meta,+ get_recording_meta_by_path,set_pretty_name,set_server_url,set_camera_preview_state,@@ -2673,6 +2683,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {target_select_overlay::TargetUnderCursor,hotkeys::OnEscapePress,upload::UploadProgressEvent,+ import::VideoImportProgress,SetCaptureAreaPending,DevicesUpdated,])@@ -2782,6 +2793,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {CapWindowId::RecordingsOverlay.label().as_str(),CapWindowId::RecordingControls.label().as_str(),CapWindowId::Upgrade.label().as_str(),+ "editor",+ "screenshot-editor",]).map_label(|label| match label {label if label.starts_with("editor-") => "editor",diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 5cb79a0da..a1e09dda4 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -95,6 +95,12 @@ async generateExportPreview(projectPath: string, frameTime: number, settings: Exasync generateExportPreviewFast(frameTime: number, settings: ExportPreviewSettings) : Promise<ExportPreviewResult> {return await TAURI_INVOKE("generate_export_preview_fast", { frameTime, settings });},+async startVideoImport(sourcePath: string) : Promise<string> {+ return await TAURI_INVOKE("start_video_import", { sourcePath });+},+async checkImportReady(projectPath: string) : Promise<boolean> {+ return await TAURI_INVOKE("check_import_ready", { projectPath });+},async copyFileToPath(src: string, dst: string) : Promise<null> {return await TAURI_INVOKE("copy_file_to_path", { src, dst });},@@ -247,6 +253,9 @@ async setWindowTransparent(value: boolean) : Promise<void> {async getEditorMeta() : Promise<RecordingMeta> {return await TAURI_INVOKE("get_editor_meta");},+async getRecordingMetaByPath(projectPath: string) : Promise<RecordingMeta> {+ return await TAURI_INVOKE("get_recording_meta_by_path", { projectPath });+},async setPrettyName(prettyName: string) : Promise<null> {return await TAURI_INVOKE("set_pretty_name", { prettyName });},@@ -346,7 +355,8 @@ requestScreenCapturePrewarm: RequestScreenCapturePrewarm,requestStartRecording: RequestStartRecording,setCaptureAreaPending: SetCaptureAreaPending,targetUnderCursor: TargetUnderCursor,-uploadProgressEvent: UploadProgressEvent+uploadProgressEvent: UploadProgressEvent,+videoImportProgress: VideoImportProgress}>({audioInputLevelChange: "audio-input-level-change",currentRecordingChanged: "current-recording-changed",@@ -369,7 +379,8 @@ requestScreenCapturePrewarm: "request-screen-capture-prewarm",requestStartRecording: "request-start-recording",setCaptureAreaPending: "set-capture-area-pending",targetUnderCursor: "target-under-cursor",-uploadProgressEvent: "upload-progress-event"+uploadProgressEvent: "upload-progress-event",+videoImportProgress: "video-import-progress"})/** user-defined constants **/@@ -391,7 +402,7 @@ export type AuthStore = { secret: AuthSecret; user_id: string | null; plan: Planexport type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; roundingType: CornerStyle; inset: number; crop: Crop | null; shadow: number; advancedShadow: ShadowConfiguration | null; border: BorderConfiguration | null }export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number]; alpha?: number } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }export type BorderConfiguration = { enabled: boolean; width: number; color: [number, number, number]; opacity: number }-export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoomSize: number | null; rounding: number; shadow: number; advancedShadow: ShadowConfiguration | null; shape: CameraShape; roundingType: CornerStyle }+export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoomSize: number | null; rounding: number; shadow: number; advancedShadow: ShadowConfiguration | null; shape: CameraShape; roundingType: CornerStyle; scaleDuringZoom?: number }export type CameraInfo = { device_id: string; model_id: ModelIDType | null; display_name: string }export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }export type CameraPreviewShape = "round" | "square" | "full"@@ -408,6 +419,7 @@ export type CaptureDisplay = { id: DisplayId; name: string; refresh_rate: numberexport type CaptureDisplayWithThumbnail = { id: DisplayId; name: string; refresh_rate: number; thumbnail: string | null }export type CaptureWindow = { id: WindowId; owner_name: string; name: string; bounds: LogicalBounds; refresh_rate: number; bundle_identifier: string | null }export type CaptureWindowWithThumbnail = { id: WindowId; owner_name: string; name: string; bounds: LogicalBounds; refresh_rate: number; thumbnail: string | null; app_icon: string | null; bundle_identifier: string | null }+export type ClickSpringConfig = { tension: number; mass: number; friction: number }export type ClipConfiguration = { index: number; offsets: ClipOffsets }export type ClipOffsets = { camera?: number; mic?: number; system_audio?: number }export type CommercialLicense = { licenseKey: string; expiryDate: number | null; refresh: number; activatedOn: number }@@ -417,7 +429,7 @@ export type CurrentRecording = { target: CurrentRecordingTarget; mode: Recordingexport type CurrentRecordingChanged = nullexport type CurrentRecordingTarget = { window: { id: WindowId; bounds: LogicalBounds | null } } | { screen: { id: DisplayId } } | { area: { screen: DisplayId; bounds: LogicalBounds } }export type CursorAnimationStyle = "slow" | "mellow" | "custom"-export type CursorConfiguration = { hide: boolean; hideWhenIdle: boolean; hideWhenIdleDelay: number; size: number; type: CursorType; animationStyle: CursorAnimationStyle; tension: number; mass: number; friction: number; raw: boolean; motionBlur: number; useSvg: boolean }+export type CursorConfiguration = { hide: boolean; hideWhenIdle: boolean; hideWhenIdleDelay: number; size: number; type: CursorType; animationStyle: CursorAnimationStyle; tension: number; mass: number; friction: number; raw: boolean; motionBlur: number; useSvg: boolean; rotationAmount?: number; baseRotation?: number; clickSpring?: ClickSpringConfig | null; stopMovementInLastSeconds?: number | null }export type CursorMeta = { imagePath: string; hotspot: XY<number>; shape?: string | null }export type CursorType = "auto" | "pointer" | "circle"export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }@@ -447,19 +459,21 @@ quality: number | null;* Whether to prioritize speed over quality (default: false)*/fast: boolean | null }+export type GlideDirection = "none" | "left" | "right" | "up" | "down"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 }export type HotkeyAction = "startStudioRecording" | "startInstantRecording" | "stopRecording" | "restartRecording" | "togglePauseRecording" | "cycleRecordingMode" | "openRecordingPicker" | "openRecordingPickerDisplay" | "openRecordingPickerWindow" | "openRecordingPickerArea" | "other"export type HotkeysConfiguration = { show: boolean }export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }+export type ImportStage = "Probing" | "Converting" | "Finalizing" | "Complete" | "Failed"export type IncompleteRecordingInfo = { projectPath: string; prettyName: string; segmentCount: number; estimatedDurationSecs: number }export type InstantRecordingMeta = { recording: boolean } | { error: string } | { fps: number; sample_rate: number | null }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 = { displayName: string }+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"@@ -486,7 +500,7 @@ export type PostDeletionBehaviour = "doNothing" | "reopenRecordingWindow"export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay"export type Preset = { name: string; config: ProjectConfiguration }export type PresetsStore = { presets: Preset[]; default: number | null }-export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline: TimelineConfiguration | null; captions: CaptionsData | null; clips: ClipConfiguration[]; annotations: Annotation[] }+export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline: TimelineConfiguration | null; captions: CaptionsData | null; clips: ClipConfiguration[]; annotations: Annotation[]; screenMotionBlur?: number; screenMovementSpring?: ScreenMovementSpring }export type ProjectRecordingsMeta = { segments: SegmentRecordings[] }export type RecordingAction = "Started" | "InvalidAuthentication" | "UpgradeRequired"export type RecordingDeleted = { path: string }@@ -510,6 +524,7 @@ export type S3UploadMeta = { id: string }export type SceneMode = "default" | "cameraOnly" | "hideCamera"export type SceneSegment = { start: number; end: number; mode?: SceneMode }export type ScreenCaptureTarget = { variant: "window"; id: WindowId } | { variant: "display"; id: DisplayId } | { variant: "area"; screen: DisplayId; bounds: LogicalBounds }+export type ScreenMovementSpring = { stiffness: number; damping: number; mass: number }export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audio | null; system_audio: Audio | null }export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string }export type SerializedScreenshotEditorInstance = { framesSocketUrl: string; path: string; config: ProjectConfiguration | null; prettyName: string }@@ -522,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 = { macosVersion: MacOSVersionInfo | null; availableEncoders: string[]; screenCaptureSupported: 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[] }@@ -533,6 +548,7 @@ export type UploadProgress = { progress: number }export type UploadProgressEvent = { video_id: string; uploaded: string; total: string }export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"export type Video = { duration: number; width: number; height: number; fps: number; start_time: number }+export type VideoImportProgress = { project_path: string; stage: ImportStage; progress: number; message: string }export type VideoMeta = { path: string; fps?: number; start_time?: number | null; device_id?: string | null }export type VideoRecordingMetadata = { duration: number; size: number }export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }@@ -541,7 +557,7 @@ export type WindowId = stringexport type WindowUnderCursor = { id: WindowId; app_name: string; bounds: LogicalBounds }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 }+export type ZoomSegment = { start: number; end: number; amount: number; mode: ZoomMode; glideDirection?: GlideDirection; glideSpeed?: number; instantAnimation?: boolean; edgeSnapRatio?: number }/** tauri-specta globals **/diff --git a/crates/rendering/src/project_recordings.rs b/crates/rendering/src/project_recordings.rsindex 839cb59dd..7186fb98b 100644--- a/crates/rendering/src/project_recordings.rs+++ b/crates/rendering/src/project_recordings.rs@@ -26,19 +26,44 @@ impl Video {.best(ffmpeg::media::Type::Video).ok_or_else(|| "No video stream found".to_string())?;- let video_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())- .map_err(|e| format!("Failed to create decoder: {e}"))?- .decoder()- .video()- .map_err(|e| format!("Failed to get video decoder: {e}"))?;+ let params = stream.parameters();++ let (width, height) = unsafe {+ let ptr = params.as_ptr();+ ((*ptr).width as u32, (*ptr).height as u32)+ };++ if width == 0 || height == 0 {+ return Err("Invalid video dimensions".to_string());+ }let rate = stream.avg_frame_rate();- let fps = rate.numerator() as f64 / rate.denominator() as f64;+ let fps = if rate.denominator() != 0 {+ rate.numerator() as f64 / rate.denominator() as f64+ } else {+ 30.0+ };++ let duration = {+ let container_duration = input.duration();+ if container_duration > 0 {+ container_duration as f64 / 1_000_000.0+ } else {+ let stream_duration = stream.duration();+ let time_base = stream.time_base();+ if stream_duration > 0 && time_base.denominator() > 0 {+ stream_duration as f64 * time_base.numerator() as f64+ / time_base.denominator() as f64+ } else {+ return Err("Could not determine video duration".to_string());+ }+ }+ };Ok(Video {- width: video_decoder.width(),- height: video_decoder.height(),- duration: input.duration() as f64 / 1_000_000.0,+ width,+ height,+ duration,fps: fps.round() as u32,start_time,})