Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Better export estimates

Richie McIlroy1980d659d795
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 0189b235a..31805c62a 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -105,3 +105,87 @@ pub async fn export_video(
}
}
}
+
+#[derive(Debug, serde::Serialize, specta::Type)]
+pub struct ExportEstimates {
+ pub duration_seconds: f64,
+ pub estimated_time_seconds: f64,
+ pub estimated_size_mb: f64,
+}
+
+// This will need to be refactored at some point to be more accurate.
+#[tauri::command]
+#[specta::specta]
+pub async fn get_export_estimates(
+ app: AppHandle,
+ video_id: String,
+ resolution: XY<u32>,
+ fps: u32,
+) -> Result<ExportEstimates, String> {
+ let screen_metadata =
+ get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen)).await?;
+ let camera_metadata =
+ get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Camera))
+ .await
+ .ok();
+
+ let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
+ let total_frames = editor_instance.get_total_frames(fps);
+
+ let raw_duration = screen_metadata.duration.max(
+ camera_metadata
+ .map(|m| m.duration)
+ .unwrap_or(screen_metadata.duration),
+ );
+
+ let meta = editor_instance.meta();
+ let project_config = meta.project_config();
+ let duration_seconds = if let Some(timeline) = &project_config.timeline {
+ timeline
+ .segments
+ .iter()
+ .map(|s| (s.end - s.start) / s.timescale)
+ .sum()
+ } else {
+ raw_duration
+ };
+
+ let (width, height) = (resolution.x, resolution.y);
+
+ let base_bitrate = if width <= 1280 && height <= 720 {
+ 4_000_000.0
+ } else if width <= 1920 && height <= 1080 {
+ 8_000_000.0
+ } else if width <= 2560 && height <= 1440 {
+ 14_000_000.0
+ } else {
+ 20_000_000.0
+ };
+
+ let fps_factor = (fps as f64) / 30.0;
+ let video_bitrate = base_bitrate * fps_factor;
+
+ let audio_bitrate = 192_000.0;
+
+ let total_bitrate = video_bitrate + audio_bitrate;
+
+ let estimated_size_mb = (total_bitrate * duration_seconds) / (8.0 * 1024.0 * 1024.0);
+
+ let base_factor = match (width, height) {
+ (w, h) if w <= 1280 && h <= 720 => 0.43,
+ (w, h) if w <= 1920 && h <= 1080 => 0.64,
+ (w, h) if w <= 2560 && h <= 1440 => 0.75,
+ _ => 0.86,
+ };
+
+ let processing_time = duration_seconds * base_factor * fps_factor;
+ let overhead_time = 0.0;
+
+ let estimated_time_seconds = processing_time + overhead_time;
+
+ Ok(ExportEstimates {
+ duration_seconds,
+ estimated_time_seconds,
+ estimated_size_mb,
+ })
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index e099a4bd1..9d01dba05 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -943,25 +943,6 @@ async fn copy_video_to_clipboard(
Ok(())
}
-
-
-// Helper function to estimate rendered file size based on duration and quality
-fn estimate_rendered_size(duration: f64) -> f64 {
- // Use actual encoder bitrates:
- // - Video: 8-10 Mbps (from H264 encoder implementations)
- // - Audio: 128 Kbps (fixed in all encoders)
- #[cfg(target_os = "macos")]
- let video_bitrate = 10_000_000.0; // 10 Mbps (AVAssetWriter)
- #[cfg(not(target_os = "macos"))]
- let video_bitrate = 8_000_000.0; // 8 Mbps (libx264)
-
- let audio_bitrate = 128_000.0; // 128 Kbps (fixed in encoders)
-
- // Total data = (video_bitrate + audio_bitrate) * duration / 8 bits per byte
- // Convert to MB by dividing by (1024 * 1024)
- ((video_bitrate + audio_bitrate) * duration) / (8.0 * 1024.0 * 1024.0)
-}
-
#[tauri::command]
#[specta::specta]
async fn get_video_metadata(
@@ -987,7 +968,9 @@ async fn get_video_metadata(
fn get_duration_for_paths(paths: Vec<PathBuf>) -> Result<f64, String> {
let mut max_duration: f64 = 0.0;
for path in paths {
- let reader = BufReader::new(File::open(&path).map_err(|e| format!("Failed to open video file: {}", e))?);
+ let reader = BufReader::new(
+ File::open(&path).map_err(|e| format!("Failed to open video file: {}", e))?,
+ );
let file_size = path
.metadata()
.map_err(|e| format!("Failed to get file metadata: {}", e))?
@@ -1041,11 +1024,28 @@ async fn get_video_metadata(
// Use the longer duration
let duration = display_duration.max(camera_duration);
- // Estimate the rendered file size based on the duration
- let estimated_size = estimate_rendered_size(duration);
+ // Calculate estimated size using same logic as get_export_estimates
+ let (width, height) = (1920, 1080); // Default to 1080p
+ let fps = 30; // Default to 30fps
+
+ let base_bitrate = if width <= 1280 && height <= 720 {
+ 4_000_000.0
+ } else if width <= 1920 && height <= 1080 {
+ 8_000_000.0
+ } else if width <= 2560 && height <= 1440 {
+ 14_000_000.0
+ } else {
+ 20_000_000.0
+ };
+
+ let fps_factor = (fps as f64) / 30.0;
+ let video_bitrate = base_bitrate * fps_factor;
+ let audio_bitrate = 192_000.0;
+ let total_bitrate = video_bitrate + audio_bitrate;
+ let estimated_size_mb = (total_bitrate * duration) / (8.0 * 1024.0 * 1024.0);
Ok(VideoRecordingMetadata {
- size: estimated_size,
+ size: estimated_size_mb,
duration,
})
}
@@ -1862,6 +1862,7 @@ pub async fn run() {
focus_captures_panel,
get_current_recording,
export::export_video,
+ export::get_export_estimates,
copy_file_to_path,
copy_video_to_clipboard,
copy_screenshot_to_clipboard,
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index 6e13390fe..ba63b3af5 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -63,24 +63,16 @@ const FPS_OPTIONS = [
{ label: "60 FPS", value: 60 },
] satisfies Array<{ label: string; value: number }>;
+export interface ExportEstimates {
+ duration_seconds: number;
+ estimated_time_seconds: number;
+ estimated_size_mb: number;
+}
+
export function Header() {
const currentWindow = getCurrentWindow();
const { videoId, project, prettyName } = useEditorContext();
- const [metadata] = createResource(async () => {
- const result = await commands.getVideoMetadata(videoId, null).catch((e) => {
- console.error(`Failed to get metadata: ${e}`);
- });
- if (!result) return;
-
- const { duration, size } = result;
- const estimatedExportTime = Math.ceil(duration * 1.5);
- console.log(
- `Metadata for video: duration=${duration}, size=${size}, estimatedExport=${estimatedExportTime}`
- );
- return { duration, size, estimatedExportTime };
- });
-
const [showExportOptions, setShowExportOptions] = createSignal(false);
const [selectedFps, setSelectedFps] = createSignal(
Number(localStorage.getItem("cap-export-fps")) || 30
@@ -92,6 +84,24 @@ export function Header() {
) || RESOLUTION_OPTIONS[0]
);
+ const [exportEstimates] = createResource(
+ () => ({
+ videoId,
+ resolution: {
+ x: selectedResolution()?.width || RESOLUTION_OPTIONS[0].width,
+ y: selectedResolution()?.height || RESOLUTION_OPTIONS[0].height,
+ },
+ fps: selectedFps(),
+ }),
+ async (params) => {
+ return commands.getExportEstimates(
+ params.videoId,
+ params.resolution,
+ params.fps
+ );
+ }
+ );
+
let unlistenTitlebar: UnlistenFn | undefined;
onMount(async () => {
unlistenTitlebar = await initializeTitlebar();
@@ -189,8 +199,8 @@ export function Header() {
true,
selectedFps(),
{
- x: selectedResolution().width,
- y: selectedResolution().height,
+ x: selectedResolution()?.width || RESOLUTION_OPTIONS[0].width,
+ y: selectedResolution()?.height || RESOLUTION_OPTIONS[0].height,
}
);
await commands.copyFileToPath(videoPath, path);
@@ -287,9 +297,9 @@ export function Header() {
</div>
<div>
<label class="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
- Frame Rate
+ FPS
</label>
- <KSelect<(typeof FPS_OPTIONS)[number]>
+ <KSelect
options={FPS_OPTIONS}
optionValue="value"
optionTextValue="label"
@@ -341,8 +351,8 @@ export function Header() {
>
Export Video
</Button>
- <Show when={metadata()}>
- {(metadata) => (
+ <Show when={exportEstimates()}>
+ {(est) => (
<div
class={cx(
"font-medium z-40 flex justify-between items-center pointer-events-none transition-all max-w-full overflow-hidden text-xs"
@@ -351,21 +361,55 @@ export function Header() {
<p class="flex items-center gap-4">
<span class="flex items-center text-[--gray-500]">
<IconCapCamera class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />
- {Math.floor(metadata().duration / 60)}:
- {Math.floor(metadata().duration % 60)
- .toString()
- .padStart(2, "0")}
+ {(() => {
+ const totalSeconds = Math.round(
+ est().duration_seconds
+ );
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor(
+ (totalSeconds % 3600) / 60
+ );
+ const seconds = totalSeconds % 60;
+
+ if (hours > 0) {
+ return `${hours}:${minutes
+ .toString()
+ .padStart(2, "0")}:${seconds
+ .toString()
+ .padStart(2, "0")}`;
+ }
+ return `${minutes}:${seconds
+ .toString()
+ .padStart(2, "0")}`;
+ })()}
</span>
<span class="flex items-center text-[--gray-500]">
<IconLucideHardDrive class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />
- {metadata().size.toFixed(2)} MB
+ {est().estimated_size_mb.toFixed(2)} MB
</span>
<span class="flex items-center text-[--gray-500]">
<IconLucideClock class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />
- ~{Math.floor(metadata().estimatedExportTime / 60)}:
- {Math.floor(metadata().estimatedExportTime % 60)
- .toString()
- .padStart(2, "0")}
+ {(() => {
+ const totalSeconds = Math.round(
+ est().estimated_time_seconds
+ );
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor(
+ (totalSeconds % 3600) / 60
+ );
+ const seconds = totalSeconds % 60;
+
+ if (hours > 0) {
+ return `~${hours}:${minutes
+ .toString()
+ .padStart(2, "0")}:${seconds
+ .toString()
+ .padStart(2, "0")}`;
+ }
+ return `~${minutes}:${seconds
+ .toString()
+ .padStart(2, "0")}`;
+ })()}
</span>
</p>
</div>
@@ -652,8 +696,10 @@ function ShareButton(props: ShareButtonProps) {
true,
props.selectedFps(),
{
- x: props.selectedResolution().width,
- y: props.selectedResolution().height,
+ x: props.selectedResolution()?.width || RESOLUTION_OPTIONS[0].width,
+ y:
+ props.selectedResolution()?.height ||
+ RESOLUTION_OPTIONS[0].height,
}
);
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 2d4157038..5b0bdae89 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -56,6 +56,9 @@ async getCurrentRecording() : Promise<JsonValue<RecordingInfo | null>> {
async exportVideo(videoId: string, project: ProjectConfiguration, progress: TAURI_CHANNEL<RenderProgress>, force: boolean, fps: number, resolutionBase: XY<number>) : Promise<string> {
return await TAURI_INVOKE("export_video", { videoId, project, progress, force, fps, resolutionBase });
},
+async getExportEstimates(videoId: string, resolution: XY<number>, fps: number) : Promise<ExportEstimates> {
+ return await TAURI_INVOKE("get_export_estimates", { videoId, resolution, fps });
+},
async copyFileToPath(src: string, dst: string) : Promise<null> {
return await TAURI_INVOKE("copy_file_to_path", { src, dst });
},
@@ -240,6 +243,7 @@ export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: C
export type CursorType = "pointer" | "circle"
export type Display = { path: string; fps?: number }
export type EditorStateChanged = { playhead_position: number }
+export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
export type Flags = { recordMouse: boolean; split: boolean; pauseResume: boolean; zoom: boolean }
export type GeneralSettingsStore = { uploadIndividualFiles?: boolean; openEditorAfterRecording?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; recordingConfig?: RecordingConfig | null }
export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }