Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Repair corrupt MP4s and refine upload flow
Richie McIlroy8545ac6b7f77
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 4e3852ab6..a0a16f46d 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1514,18 +1514,28 @@ pub async fn take_screenshot(Ok(image_path)}-// runs when a recording ends, whether from success or failureasync fn handle_recording_end(handle: AppHandle,recording: Result<CompletedRecording, String>,app: &mut App,recording_dir: PathBuf,) -> Result<(), String> {- // Clear current recording, just in case :)- app.clear_current_recording();+ let cleared = app.clear_current_recording();app.disconnected_inputs.clear();app.camera_in_use = false;+ if recording.is_err()+ && let Some(InProgressRecording::Instant {+ progressive_upload,+ video_upload_info,+ ..+ }) = cleared+ {+ info!("Aborting progressive upload due to recording failure");+ progressive_upload.handle.abort();+ crate::upload::emit_upload_complete(&handle, &video_upload_info.id);+ }+if app.was_camera_only_recording {app.was_camera_only_recording = false;@@ -1796,33 +1806,62 @@ async fn handle_recording_finish(}}- } else if let Ok(meta) = build_video_meta(&output_path)- .map_err(|err| error!("Error getting video metadata: {}", err))- {- // The upload_video function handles screenshot upload, so we can pass it along- upload_video(- &app,- video_upload_info.id.clone(),- output_path,- display_screenshot.clone(),- meta,- None,- )- .await- .map(|_| info!("Final video upload with screenshot completed successfully"))- .map_err(|error| {- error!("Error in upload_video: {error}");-- if let Ok(mut meta) = RecordingMeta::load_for_project(&recording_dir) {- meta.upload = Some(UploadMeta::Failed {- error: error.to_string(),- });- meta.save_for_project()- .map_err(|e| format!("Failed to save recording meta: {e}"))- .ok();+ } else {+ let meta = match build_video_meta(&output_path) {+ Ok(m) => Some(m),+ Err(err) => {+ error!("Error getting video metadata: {err}");+ warn!(+ "Attempting to repair corrupt recording before fallback upload"+ );+ match crate::upload::try_repair_corrupt_mp4(&output_path) {+ Ok(()) => {+ info!("Repair succeeded, retrying metadata extraction");+ build_video_meta(&output_path)+ .map_err(|e| {+ error!("Still unreadable after repair: {e}")+ })+ .ok()+ }+ Err(e) => {+ error!("Repair failed: {e}");+ None+ }+ }}- })- .ok();+ };++ if let Some(meta) = meta {+ upload_video(+ &app,+ video_upload_info.id.clone(),+ output_path,+ display_screenshot.clone(),+ meta,+ None,+ )+ .await+ .map(|_| {+ info!("Final video upload with screenshot completed successfully")+ })+ .map_err(|error| {+ error!("Error in upload_video: {error}");++ if let Ok(mut meta) =+ RecordingMeta::load_for_project(&recording_dir)+ {+ meta.upload = Some(UploadMeta::Failed {+ error: error.to_string(),+ });+ meta.save_for_project()+ .map_err(|e| format!("Failed to save recording meta: {e}"))+ .ok();+ }+ })+ .ok();+ } else {+ crate::upload::emit_upload_complete(&app, &video_upload_info.id);+ }}}});diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex cf64309d5..bbe106bd2 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -144,6 +144,8 @@ pub async fn upload_video(let (video_result, thumbnail_result): (Result<_, AuthedApiError>, Result<_, AuthedApiError>) =tokio::join!(video_fut, thumbnail_fut);+ emit_upload_complete(app, &video_id);+async_capture_event(match &video_result {Ok(meta) => PostHogEvent::MultipartUploadComplete {duration: start.elapsed(),@@ -314,6 +316,40 @@ pub fn build_video_meta(path: &PathBuf) -> Result<S3VideoMeta, String> {})}+pub fn try_repair_corrupt_mp4(path: &Path) -> Result<(), String> {+ let repaired_path = path.with_extension("repaired.mp4");++ info!(+ original = %path.display(),+ repaired = %repaired_path.display(),+ "Attempting to repair corrupt MP4 via FFmpeg remux"+ );++ cap_enc_ffmpeg::remux::remux_file(path, &repaired_path)+ .map_err(|e| format!("FFmpeg remux repair failed for {}: {e}", path.display()))?;++ let repaired_size = std::fs::metadata(&repaired_path)+ .map(|m| m.len())+ .unwrap_or(0);++ if repaired_size == 0 {+ let _ = std::fs::remove_file(&repaired_path);+ return Err("Repaired file is empty — no recoverable data".to_string());+ }++ std::fs::rename(&repaired_path, path).map_err(|e| {+ let _ = std::fs::remove_file(&repaired_path);+ format!("Failed to replace original file with repaired version: {e}")+ })?;++ info!(+ repaired_size_mb = repaired_size as f64 / 1_000_000.0,+ "Successfully replaced corrupt file with repaired version"+ );++ Ok(())+}+#[instrument]pub async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {task::spawn_blocking(move || {@@ -454,14 +490,47 @@ impl InstantMultipartUpload {parts = deduplicated_parts.into_values().collect::<Vec<_>>();parts.sort_by_key(|part| part.part_number);- let metadata = build_video_meta(&file_path)- .map_err(|e| error!("Failed to get video metadata: {e}"))- .ok();+ let metadata = match build_video_meta(&file_path) {+ Ok(meta) => Some(meta),+ Err(e) => {+ error!("Failed to get video metadata: {e}");+ warn!("Output file may be corrupt, attempting FFmpeg remux repair for {video_id}");++ match try_repair_corrupt_mp4(&file_path) {+ Ok(()) => {+ info!("Successfully repaired corrupt recording for {video_id}");+ match build_video_meta(&file_path) {+ Ok(meta) => Some(meta),+ Err(repair_meta_err) => {+ error!(+ "File still unreadable after repair attempt: {repair_meta_err}"+ );+ return Err(format!(+ "Recording file could not be salvaged after encoder failure. \+ Original error: {e}, Post-repair error: {repair_meta_err}"+ )+ .into());+ }+ }+ }+ Err(repair_err) => {+ error!("FFmpeg repair also failed: {repair_err}");+ return Err(format!(+ "Recording file could not be salvaged after encoder failure. \+ Original error: {e}, Repair error: {repair_err}"+ )+ .into());+ }+ }+ }+ };api::upload_multipart_complete(&app, &video_id, &upload_id, &parts, metadata.clone()).await?;info!("Multipart upload complete for {video_id}.");+ emit_upload_complete(&app, &video_id);+let mut project_meta = RecordingMeta::load_for_project(&recording_dir).map_err(|err| {format!("Error reading project meta from {recording_dir:?} for upload complete: {err}")})?;@@ -542,19 +611,25 @@ pub fn from_pending_file_to_chunks(let mut part_number = 1;let mut last_read_position: u64 = 0;let mut realtime_is_done = realtime_upload_done.as_ref().map(|_| false);+ let mut recording_completed_cleanly = false;let mut first_chunk_size: Option<u64> = None;let mut chunk_buffer = vec![0u8; MAX_CHUNK_SIZE as usize];loop {- // Check if realtime recording is doneif !realtime_is_done.unwrap_or(true) && let Some(ref realtime_receiver) = realtime_upload_done {match realtime_receiver.try_recv() {- Ok(_) => realtime_is_done = Some(true),+ Ok(_) => {+ realtime_is_done = Some(true);+ recording_completed_cleanly = true;+ },Err(flume::TryRecvError::Empty) => {},- // This means all senders where dropped.- // This can assume this means realtime is done.- // It possibly means something has gone wrong but that's not the uploader's problem.- Err(_) => realtime_is_done = Some(true),+ Err(flume::TryRecvError::Disconnected) => {+ warn!(+ "Recording channel disconnected without completion signal — \+ recording may have failed, finishing upload without header correction"+ );+ realtime_is_done = Some(true);+ },}}@@ -606,8 +681,7 @@ pub fn from_pending_file_to_chunks(last_read_position += total_read as u64;}} else if new_data_size == 0 && realtime_is_done.unwrap_or(true) {- // Recording is done and no new data - re-emit first chunk with corrected MP4 header- if let Some(first_size) = first_chunk_size && realtime_upload_done.is_some() {+ if let Some(first_size) = first_chunk_size && realtime_upload_done.is_some() && recording_completed_cleanly {file.seek(std::io::SeekFrom::Start(0)).await?;let chunk_size = first_size as usize;@@ -1192,7 +1266,6 @@ fn progress<T: UploadedChunk, E>(let mut uploaded = 0u64;let mut pending_task: Option<JoinHandle<()>> = None;let mut reemit_task: Option<JoinHandle<()>> = None;- let (video_id2, app_handle) = (video_id.clone(), app.clone());stream! {let mut stream = pin!(stream);@@ -1202,12 +1275,10 @@ fn progress<T: UploadedChunk, E>(uploaded += chunk.size();let total = chunk.total();- // Cancel any pending taskif let Some(handle) = pending_task.take() {handle.abort();}- // Cancel any existing reemit taskif let Some(handle) = reemit_task.take() {handle.abort();}@@ -1215,14 +1286,12 @@ fn progress<T: UploadedChunk, E>(let should_send_immediately = uploaded >= total;if should_send_immediately {- // Send immediately if upload is completelet app_clone = app.clone();let video_id_clone = video_id.clone();tokio::spawn(async move {api::desktop_video_progress(&app_clone, &video_id_clone, uploaded, total).await.ok();});} else {- // Schedule delayed updatelet app_clone = app.clone();let video_id_clone = video_id.clone();pending_task = Some(tokio::spawn(async move {@@ -1230,14 +1299,13 @@ fn progress<T: UploadedChunk, E>(api::desktop_video_progress(&app_clone, &video_id_clone, uploaded, total).await.ok();}));- // Start reemit task for continuous progress updates every 700mslet app_reemit = app.clone();let video_id_reemit = video_id.clone();let uploaded_reemit = uploaded;let total_reemit = total;reemit_task = Some(tokio::spawn(async move {let mut interval = time::interval(Duration::from_millis(700));- interval.tick().await; // Skip first immediate tick+ interval.tick().await;loop {interval.tick().await;@@ -1252,7 +1320,6 @@ fn progress<T: UploadedChunk, E>(}));}- // Emit progress event for the app frontendUploadProgressEvent {video_id: video_id.clone(),uploaded: uploaded.to_string(),@@ -1265,25 +1332,20 @@ fn progress<T: UploadedChunk, E>(yield chunk;}- // Clean up reemit task when stream endsif let Some(handle) = reemit_task.take() {handle.abort();}}- .map(Some)- .chain(stream::once(async move {- // This will trigger the frontend to remove the event from the SolidJS store.- UploadProgressEvent {- video_id: video_id2,- uploaded: "0".into(),- total: "0".into(),- }- .emit(&app_handle)- .ok();+}- None- }))- .filter_map(|item| async move { item })+pub fn emit_upload_complete(app: &AppHandle, video_id: &str) {+ UploadProgressEvent {+ video_id: video_id.to_string(),+ uploaded: "0".into(),+ total: "0".into(),+ }+ .emit(app)+ .ok();}/// Track the upload progress into a Tauri channeldiff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsxindex 8bc1f20bd..bfd7e5112 100644--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx@@ -1050,7 +1050,7 @@ function Page() {);createTauriEventListener(events.uploadProgressEvent, (e) => {- if (e.uploaded === e.total) {+ if (e.uploaded === "0" && e.total === "0") {setUploadProgress(produce((s) => {delete s[e.video_id];diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsxindex 2560a82e1..616a3670e 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx@@ -111,7 +111,7 @@ export default function Recordings() {const recordings = createQuery(() => recordingsQuery);createTauriEventListener(events.uploadProgressEvent, (e) => {- if (e.uploaded === e.total) {+ if (e.uploaded === "0" && e.total === "0") {setUploadProgress(produce((s) => {delete s[e.video_id];diff --git a/crates/enc-avfoundation/src/mp4.rs b/crates/enc-avfoundation/src/mp4.rsindex d40753eeb..2e97944d5 100644--- a/crates/enc-avfoundation/src/mp4.rs+++ b/crates/enc-avfoundation/src/mp4.rs@@ -446,8 +446,6 @@ impl MP4Encoder {pts_duration = adjusted_pts;}- self.last_video_pts = Some(pts_duration);-let frame_duration_us = self.video_frame_duration().as_micros() as i64;let timing = SampleTimingInfo {duration: cm::Time::new(frame_duration_us.max(1), 1_000_000),@@ -475,6 +473,7 @@ impl MP4Encoder {Err(e) => return Err(e),}+ self.last_video_pts = Some(pts_duration);self.video_frames_appended += 1;self.last_timestamp = Some(timestamp);@@ -590,16 +589,32 @@ impl MP4Encoder {cm::AudioFormatDesc::with_asbd(&audio_desc).map_err(QueueFrameError::Construct)?;let sample_rate = frame.rate().max(1) as i32;- let pts_value = match (self.last_audio_end_pts, self.last_audio_timescale) {+ let mut pts_value = match (self.last_audio_end_pts, self.last_audio_timescale) {(Some(end), Some(scale)) if scale == sample_rate => end,(Some(end), Some(scale)) => {- duration_to_timescale_value(timescale_value_to_duration(end, scale), sample_rate)+ let converted = duration_to_timescale_value(+ timescale_value_to_duration(end, scale),+ sample_rate,+ );+ converted.max(end.max(0) + 1)}_ => 0,};- self.last_audio_end_pts = Some(pts_value.saturating_add(frame.samples() as i64));- self.last_audio_timescale = Some(sample_rate);+ if let Some(last_end) = self.last_audio_end_pts+ && self.last_audio_timescale == Some(sample_rate)+ && pts_value < last_end+ {+ warn!(+ pts_value,+ last_end,+ sample_rate,+ "Audio PTS went backwards, correcting to maintain monotonicity"+ );+ pts_value = last_end;+ }++ let new_end = pts_value.saturating_add(frame.samples() as i64);let pts = cm::Time::new(pts_value, sample_rate);@@ -626,6 +641,8 @@ impl MP4Encoder {Err(e) => return Err(e),}+ self.last_audio_end_pts = Some(new_end);+ self.last_audio_timescale = Some(sample_rate);self.audio_frames_appended += 1;self.last_timestamp = Some(timestamp);diff --git a/crates/enc-ffmpeg/src/remux.rs b/crates/enc-ffmpeg/src/remux.rsindex 5ff2e0eeb..65297969a 100644--- a/crates/enc-ffmpeg/src/remux.rs+++ b/crates/enc-ffmpeg/src/remux.rs@@ -502,3 +502,7 @@ fn remux_to_regular_mp4(input_path: &Path, output_path: &Path) -> Result<(), Remremux_streams(&mut ictx, &mut octx)}++pub fn remux_file(input_path: &Path, output_path: &Path) -> Result<(), RemuxError> {+ remux_to_regular_mp4(input_path, output_path)+}