Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve video import robustness and add debug logging

Richie McIlroy65e1f8910712
diff --git a/apps/desktop/src-tauri/src/import.rs b/apps/desktop/src-tauri/src/import.rs
index d22f9ca49..c155654b5 100644
--- a/apps/desktop/src-tauri/src/import.rs
+++ b/apps/desktop/src-tauri/src/import.rs
@@ -20,7 +20,9 @@ use specta::Type;
use std::path::{Path, PathBuf};
use tauri::{AppHandle, Manager};
use tauri_specta::Event;
-use tracing::{error, info};
+use tracing::{debug, error, info};
+
+use crate::create_screenshot;
#[derive(Serialize, Type, Clone, Debug)]
pub enum ImportStage {
@@ -169,8 +171,9 @@ fn transcode_video(
let output_width = ensure_even(video_info.width);
let output_height = ensure_even(video_info.height);
- let fps = if video_info.frame_rate.0 > 0 && video_info.frame_rate.1 > 0 {
- (video_info.frame_rate.0 as u32 / video_info.frame_rate.1 as u32).clamp(1, 120)
+ let fps = if video_info.frame_rate.1 > 0 {
+ ((video_info.frame_rate.0 as f64 / video_info.frame_rate.1 as f64).round() as u32)
+ .clamp(1, 120)
} else {
30
};
@@ -335,17 +338,15 @@ fn transcode_video(
);
}
}
- } else if let Some((audio_idx, decoder, _)) = audio_decoder.as_mut() {
- if stream_index == *audio_idx {
- if let (Some(encoder), Some(audio_out)) =
- (audio_encoder.as_mut(), audio_output.as_mut())
- {
- decoder.send_packet(&packet)?;
+ } else if let Some((audio_idx, decoder, _)) = audio_decoder.as_mut()
+ && stream_index == *audio_idx
+ && let (Some(encoder), Some(audio_out)) =
+ (audio_encoder.as_mut(), audio_output.as_mut())
+ {
+ decoder.send_packet(&packet)?;
- while decoder.receive_frame(&mut audio_frame).is_ok() {
- encoder.send_frame(audio_frame.clone(), audio_out);
- }
- }
+ while decoder.receive_frame(&mut audio_frame).is_ok() {
+ encoder.send_frame(audio_frame.clone(), audio_out);
}
}
}
@@ -420,10 +421,10 @@ fn transcode_video(
if let Ok(file) = std::fs::File::open(output_path) {
let _ = file.sync_all();
}
- if let Some(audio_path) = audio_output_path {
- if let Ok(file) = std::fs::File::open(audio_path) {
- let _ = file.sync_all();
- }
+ if let Some(audio_path) = audio_output_path
+ && let Ok(file) = std::fs::File::open(audio_path)
+ {
+ let _ = file.sync_all();
}
Ok((fps, sample_rate))
@@ -619,6 +620,21 @@ pub async fn start_video_import(app: AppHandle, source_path: PathBuf) -> Result<
return;
}
+ let screenshots_dir = project_path.join("screenshots");
+ if let Err(e) = std::fs::create_dir_all(&screenshots_dir) {
+ error!("Failed to create screenshots directory: {:?}", e);
+ } else {
+ let display_screenshot = screenshots_dir.join("display.jpg");
+ let video_path = output_video_path.clone();
+ tokio::spawn(async move {
+ if let Err(e) =
+ create_screenshot(video_path, display_screenshot, None).await
+ {
+ error!("Failed to create thumbnail for imported video: {}", e);
+ }
+ });
+ }
+
emit_progress(
&app,
&project_path_str,
@@ -658,9 +674,14 @@ pub async fn start_video_import(app: AppHandle, source_path: PathBuf) -> Result<
#[tauri::command]
#[specta::specta]
pub async fn check_import_ready(project_path: PathBuf) -> Result<bool, String> {
+ debug!("check_import_ready called for: {:?}", project_path);
+
let meta = match RecordingMeta::load_for_project(&project_path) {
Ok(m) => m,
- Err(_) => return Ok(false),
+ Err(e) => {
+ debug!("check_import_ready: meta load failed: {:?}", e);
+ return Ok(false);
+ }
};
let is_complete = match &meta.inner {
@@ -673,6 +694,7 @@ pub async fn check_import_ready(project_path: PathBuf) -> Result<bool, String> {
};
if !is_complete {
+ debug!("check_import_ready: not complete yet");
return Ok(false);
}
@@ -683,16 +705,31 @@ pub async fn check_import_ready(project_path: PathBuf) -> Result<bool, String> {
.join("display.mp4");
if !video_path.exists() {
+ debug!(
+ "check_import_ready: video path doesn't exist: {:?}",
+ video_path
+ );
return Ok(false);
}
- if !probe_video_can_decode(&video_path).unwrap_or(false) {
+ let can_decode = probe_video_can_decode(&video_path);
+ debug!(
+ "check_import_ready: probe_video_can_decode result: {:?}",
+ can_decode
+ );
+ if !can_decode.unwrap_or(false) {
return Ok(false);
}
- if get_media_duration(&video_path).is_none() {
+ let duration = get_media_duration(&video_path);
+ debug!(
+ "check_import_ready: get_media_duration result: {:?}",
+ duration
+ );
+ if duration.is_none() {
return Ok(false);
}
+ debug!("check_import_ready: all checks passed, returning true");
Ok(true)
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 9d032e4d6..2ba65ec5f 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1025,7 +1025,7 @@ async fn get_current_recording(
#[derive(Serialize, Type, tauri_specta::Event, Clone)]
pub struct CurrentRecordingChanged;
-async fn create_screenshot(
+pub(crate) async fn create_screenshot(
input: PathBuf,
output: PathBuf,
size: Option<(u32, u32)>,
@@ -3448,6 +3448,45 @@ async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Result<(), St
}
};
+ if let Some(studio_meta) = meta.studio_meta() {
+ if matches!(studio_meta.status(), StudioRecordingStatus::InProgress) {
+ info!("Recording/import is in progress, waiting for completion...");
+ const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(250);
+ const MAX_WAIT: std::time::Duration = std::time::Duration::from_secs(600);
+ let start = std::time::Instant::now();
+
+ loop {
+ if start.elapsed() > MAX_WAIT {
+ return Err("Timed out waiting for import to complete".to_string());
+ }
+
+ tokio::time::sleep(POLL_INTERVAL).await;
+
+ let current_meta = match RecordingMeta::load_for_project(path) {
+ Ok(m) => m,
+ Err(_) => continue,
+ };
+
+ if let Some(current_studio) = current_meta.studio_meta() {
+ match current_studio.status() {
+ StudioRecordingStatus::Complete => {
+ info!("Recording/import completed");
+ break;
+ }
+ StudioRecordingStatus::Failed { error } => {
+ return Err(format!("Import failed: {error}"));
+ }
+ StudioRecordingStatus::InProgress => continue,
+ StudioRecordingStatus::NeedsRemux => break,
+ }
+ }
+ }
+ }
+ }
+
+ let meta = RecordingMeta::load_for_project(path)
+ .map_err(|e| format!("Failed to reload recording meta: {e}"))?;
+
if let Some(studio_meta) = meta.studio_meta()
&& recording::needs_fragment_remux(path, studio_meta)
{
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index c76ad09b1..e8f452d8b 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -74,8 +74,9 @@ export function Editor() {
const rawImportStatus = createMemo(() => {
const meta = rawMetaQuery.data;
if (!meta) return "loading" as const;
- const status = (meta as { status?: { status: string } }).status;
- if (status?.status === "InProgress") return "importing" as const;
+ const metaWithStatus = meta as { status?: { status: string } };
+ if (metaWithStatus.status?.status === "InProgress")
+ return "importing" as const;
return "ready" as const;
});
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 16a822fd7..fde6d9d87 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -23,19 +23,48 @@ use tokio_util::sync::CancellationToken;
use tracing::warn;
fn get_video_duration_fallback(path: &Path) -> Option<f64> {
- let input = ffmpeg::format::input(path).ok()?;
+ tracing::debug!("get_video_duration_fallback called for: {:?}", path);
+ let input = match ffmpeg::format::input(path) {
+ Ok(i) => i,
+ Err(e) => {
+ tracing::warn!("get_video_duration_fallback: failed to open input: {}", e);
+ return None;
+ }
+ };
let container_duration = input.duration();
+ tracing::debug!(
+ "get_video_duration_fallback: container_duration (raw i64) = {}",
+ container_duration
+ );
if container_duration > 0 {
- return Some(container_duration as f64 / 1_000_000.0);
+ let secs = container_duration as f64 / 1_000_000.0;
+ tracing::debug!(
+ "get_video_duration_fallback: returning container duration {} seconds",
+ secs
+ );
+ return Some(secs);
}
let stream = input.streams().best(ffmpeg::media::Type::Video)?;
let stream_duration = stream.duration();
let time_base = stream.time_base();
+ tracing::debug!(
+ "get_video_duration_fallback: stream_duration = {}, time_base = {}/{}",
+ stream_duration,
+ time_base.numerator(),
+ time_base.denominator()
+ );
if stream_duration > 0 && time_base.denominator() > 0 {
- Some(stream_duration as f64 * time_base.numerator() as f64 / time_base.denominator() as f64)
+ let secs =
+ stream_duration as f64 * time_base.numerator() as f64 / time_base.denominator() as f64;
+ tracing::debug!(
+ "get_video_duration_fallback: returning stream duration {} seconds",
+ secs
+ );
+ Some(secs)
} else {
+ tracing::warn!("get_video_duration_fallback: no valid duration found");
None
}
}
@@ -125,8 +154,12 @@ impl EditorInstance {
.enumerate()
.filter_map(|(i, segment)| {
let display_path = recording_meta.path(&segment.display.path);
+ tracing::debug!("Attempting to get duration for segment {}: {:?}", i, display_path);
let duration = match Video::new(&display_path, 0.0) {
- Ok(v) => v.duration,
+ Ok(v) => {
+ tracing::debug!("Video::new succeeded, duration: {}", v.duration);
+ v.duration
+ }
Err(e) => {
warn!(
"Failed to load video for duration calculation: {} (path: {}), trying fallback",
@@ -134,7 +167,10 @@ impl EditorInstance {
display_path.display()
);
match get_video_duration_fallback(&display_path) {
- Some(d) => d,
+ Some(d) => {
+ tracing::debug!("Fallback succeeded, duration: {}", d);
+ d
+ }
None => {
warn!("Fallback also failed, using default duration 5.0s");
5.0
@@ -142,6 +178,7 @@ impl EditorInstance {
}
}
};
+ tracing::debug!("Final duration for segment {}: {}", i, duration);
if duration <= 0.0 {
return None;
}
@@ -511,7 +548,6 @@ impl EditorInstance {
}
pub fn get_total_frames(&self, fps: u32) -> u32 {
- // Calculate total frames based on actual video duration and fps
let duration = get_duration(
&self.recordings,
&self.meta,