Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(recording): harden fragmented recovery with respawn groups and tmp rescue

Richie McIlroye6fc73e36418
diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rs
index 78c0b372e..d6f793c3c 100644
--- a/crates/recording/src/recovery.rs
+++ b/crates/recording/src/recovery.rs
@@ -3,6 +3,7 @@ use std::{
time::Duration,
};
+use cap_enc_ffmpeg::fragmented_mp4::tail_is_complete;
use cap_enc_ffmpeg::remux::{
concatenate_audio_to_ogg, concatenate_m4s_segments_with_init, concatenate_video_fragments,
get_media_duration, get_video_fps, probe_media_valid, probe_video_can_decode,
@@ -16,6 +17,8 @@ use cap_project::{
use relative_path::RelativePathBuf;
use tracing::{debug, info, warn};
+use crate::output_pipeline::{HealthSender, PipelineHealthEvent, emit_health};
+
#[derive(Debug, Clone)]
pub struct IncompleteRecording {
pub project_path: PathBuf,
@@ -403,6 +406,181 @@ impl RecoveryManager {
}
}
+ fn collect_respawn_groups(
+ dir: &Path,
+ health_tx: Option<&HealthSender>,
+ ) -> Vec<(u32, PathBuf, Vec<PathBuf>)> {
+ const MIN_VALID_FRAGMENT_SIZE: u64 = 100;
+
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return Vec::new();
+ };
+
+ let mut respawn_dirs: Vec<(u32, PathBuf)> = entries
+ .filter_map(|e| e.ok())
+ .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
+ .filter_map(|e| {
+ let name = e.file_name().to_string_lossy().to_string();
+ let n: u32 = name.strip_prefix("respawn-")?.parse().ok()?;
+ Some((n, e.path()))
+ })
+ .collect();
+
+ respawn_dirs.sort_by_key(|(n, _)| *n);
+
+ let mut groups = Vec::new();
+ for (n, respawn_dir) in respawn_dirs {
+ let init_path = respawn_dir.join("init.mp4");
+ if !init_path.exists() {
+ debug!(
+ "respawn-{} at {} missing init.mp4",
+ n,
+ respawn_dir.display()
+ );
+ continue;
+ }
+
+ Self::rescue_pending_tmp_fragments(&respawn_dir, health_tx);
+
+ let Ok(dir_entries) = std::fs::read_dir(&respawn_dir) else {
+ debug!(
+ "respawn-{} at {} could not be read",
+ n,
+ respawn_dir.display()
+ );
+ continue;
+ };
+
+ let mut indexed: Vec<(u32, PathBuf)> = dir_entries
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter_map(|p| {
+ let name = p.file_name()?.to_str()?;
+ let idx: u32 = name
+ .strip_prefix("segment_")
+ .and_then(|s| s.strip_suffix(".m4s"))
+ .and_then(|s| s.parse().ok())?;
+ let metadata = std::fs::metadata(&p).ok()?;
+ if metadata.len() < MIN_VALID_FRAGMENT_SIZE {
+ debug!(
+ "Skipping tiny respawn fragment {} ({} bytes)",
+ p.display(),
+ metadata.len()
+ );
+ return None;
+ }
+ Some((idx, p))
+ })
+ .collect();
+
+ if indexed.is_empty() {
+ debug!(
+ "respawn-{} at {} has no segment_*.m4s fragments",
+ n,
+ respawn_dir.display()
+ );
+ continue;
+ }
+
+ indexed.sort_by_key(|(idx, _)| *idx);
+
+ info!(
+ "Including {} fragments from respawn-{} at {}",
+ indexed.len(),
+ n,
+ respawn_dir.display()
+ );
+
+ let fragments: Vec<PathBuf> = indexed.into_iter().map(|(_, p)| p).collect();
+ groups.push((n, init_path, fragments));
+ }
+
+ groups
+ }
+
+ fn rescue_pending_tmp_fragments(dir: &Path, health_tx: Option<&HealthSender>) {
+ const MIN_VALID_TMP_SIZE: u64 = 100;
+
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return;
+ };
+
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
+ continue;
+ };
+ if !name.starts_with("segment_") || !name.ends_with(".m4s.tmp") {
+ continue;
+ }
+ let Ok(metadata) = std::fs::metadata(&path) else {
+ continue;
+ };
+ if metadata.len() < MIN_VALID_TMP_SIZE {
+ continue;
+ }
+ let corrupt_marker = dir.join(format!("{name}.corrupt"));
+ if corrupt_marker.exists() {
+ continue;
+ }
+ let final_name = name.trim_end_matches(".tmp");
+ let final_path = dir.join(final_name);
+ if final_path.exists() {
+ continue;
+ }
+ match tail_is_complete(&path) {
+ Ok(true) => {}
+ Ok(false) => {
+ let reason = "truncated_fragment".to_string();
+ warn!("Refusing to rescue truncated fragment {}", path.display());
+ if let Some(health_tx) = health_tx {
+ emit_health(
+ health_tx,
+ PipelineHealthEvent::RecoveryFragmentCorrupt {
+ path: path.display().to_string(),
+ reason: reason.clone(),
+ },
+ );
+ }
+ let _ = std::fs::write(&corrupt_marker, &reason);
+ continue;
+ }
+ Err(error) => {
+ let reason = error.to_string();
+ warn!(
+ "Failed to inspect in-progress tmp fragment {}: {}",
+ path.display(),
+ error
+ );
+ if let Some(health_tx) = health_tx {
+ emit_health(
+ health_tx,
+ PipelineHealthEvent::RecoveryFragmentCorrupt {
+ path: path.display().to_string(),
+ reason: reason.clone(),
+ },
+ );
+ }
+ let _ = std::fs::write(&corrupt_marker, reason);
+ continue;
+ }
+ }
+ match std::fs::rename(&path, &final_path) {
+ Ok(()) => {
+ info!(
+ "Rescued in-progress tmp fragment: {} -> {} ({} bytes)",
+ path.display(),
+ final_path.display(),
+ metadata.len()
+ );
+ }
+ Err(e) => {
+ debug!("Failed to rescue tmp fragment {}: {}", path.display(), e);
+ }
+ }
+ }
+ }
+
fn is_video_file(path: &Path) -> bool {
path.extension()
.map(|e| e.eq_ignore_ascii_case("mp4") || e.eq_ignore_ascii_case("m4s"))
@@ -542,52 +720,47 @@ impl RecoveryManager {
.join(format!("segment-{}", segment.index));
let display_output = segment_dir.join("display.mp4");
+ let display_dir = segment_dir.join("display");
+
if segment.display_fragments.len() == 1 && segment.display_init_segment.is_none() {
let source = &segment.display_fragments[0];
if source != &display_output {
info!("Moving single display fragment to {:?}", display_output);
std::fs::rename(source, &display_output)?;
- let display_dir = segment_dir.join("display");
- if display_dir.exists()
- && let Err(e) = std::fs::remove_dir_all(&display_dir)
- {
- debug!("Failed to clean up display dir {:?}: {e}", display_dir);
- }
+ }
+ Self::validate_required_video(&display_output, "display")?;
+ if display_dir.exists()
+ && let Err(e) = std::fs::remove_dir_all(&display_dir)
+ {
+ debug!("Failed to clean up display dir {:?}: {e}", display_dir);
}
} else if !segment.display_fragments.is_empty() {
- if let Some(init_path) = &segment.display_init_segment {
- info!(
- "Concatenating {} M4S display segments with init to {:?}",
- segment.display_fragments.len(),
- display_output
- );
- concatenate_m4s_segments_with_init(
- init_path,
+ let finalize_result = if display_dir.exists() {
+ Self::finalize_to_progressive_mp4(&display_dir, &display_output).map(|_| ())
+ } else {
+ Self::finalize_fragments_to_progressive_mp4(
&segment.display_fragments,
+ segment.display_init_segment.as_deref(),
&display_output,
+ "display",
)
- .map_err(RecoveryError::VideoConcat)?;
- } else {
- info!(
- "Concatenating {} display fragments to {:?}",
- segment.display_fragments.len(),
- display_output
- );
- concatenate_video_fragments(&segment.display_fragments, &display_output)
- .map_err(RecoveryError::VideoConcat)?;
- }
+ };
- for fragment in &segment.display_fragments {
- if let Err(e) = std::fs::remove_file(fragment) {
- debug!("Failed to remove display fragment {:?}: {e}", fragment);
+ match finalize_result {
+ Ok(()) => {}
+ Err(err) => {
+ if let Err(e) = std::fs::remove_file(&display_output)
+ && e.kind() != std::io::ErrorKind::NotFound
+ {
+ debug!(
+ "Failed to remove invalid display output {:?}: {e}",
+ display_output
+ );
+ }
+ return Err(err);
}
}
- if let Some(init_path) = &segment.display_init_segment
- && let Err(e) = std::fs::remove_file(init_path)
- {
- debug!("Failed to remove display init segment {:?}: {e}", init_path);
- }
- let display_dir = segment_dir.join("display");
+
if display_dir.exists()
&& let Err(e) = std::fs::remove_dir_all(&display_dir)
{
@@ -597,52 +770,76 @@ impl RecoveryManager {
if let Some(camera_frags) = &segment.camera_fragments {
let camera_output = segment_dir.join("camera.mp4");
+ let camera_dir = segment_dir.join("camera");
+
if camera_frags.len() == 1 && segment.camera_init_segment.is_none() {
let source = &camera_frags[0];
if source != &camera_output {
info!("Moving single camera fragment to {:?}", camera_output);
std::fs::rename(source, &camera_output)?;
- let camera_dir = segment_dir.join("camera");
- if camera_dir.exists()
- && let Err(e) = std::fs::remove_dir_all(&camera_dir)
- {
- debug!("Failed to clean up camera dir {:?}: {e}", camera_dir);
+ }
+ match Self::validate_required_video(&camera_output, "camera") {
+ Ok(()) => {
+ if camera_dir.exists()
+ && let Err(e) = std::fs::remove_dir_all(&camera_dir)
+ {
+ debug!("Failed to clean up camera dir {:?}: {e}", camera_dir);
+ }
+ }
+ Err(e) => {
+ warn!(
+ "Camera video validation failed for {:?}: {}",
+ camera_output, e
+ );
+ if let Err(remove_err) = std::fs::remove_file(&camera_output) {
+ debug!(
+ "Failed to remove invalid camera video {:?}: {remove_err}",
+ camera_output
+ );
+ }
}
}
} else if !camera_frags.is_empty() {
- if let Some(init_path) = &segment.camera_init_segment {
- info!(
- "Concatenating {} M4S camera segments with init to {:?}",
- camera_frags.len(),
- camera_output
- );
- concatenate_m4s_segments_with_init(init_path, camera_frags, &camera_output)
- .map_err(RecoveryError::VideoConcat)?;
- } else {
- info!(
- "Concatenating {} camera fragments to {:?}",
- camera_frags.len(),
- camera_output
- );
- concatenate_video_fragments(camera_frags, &camera_output)
- .map_err(RecoveryError::VideoConcat)?;
- }
+ let camera_ok = match Self::finalize_fragments_to_progressive_mp4(
+ camera_frags,
+ segment.camera_init_segment.as_deref(),
+ &camera_output,
+ "camera",
+ ) {
+ Ok(()) => true,
+ Err(err) => {
+ warn!(
+ "Camera track recovery failed for {:?}: {err}. Preserving fragments for retry.",
+ camera_output
+ );
+ if let Err(e) = std::fs::remove_file(&camera_output)
+ && e.kind() != std::io::ErrorKind::NotFound
+ {
+ debug!(
+ "Failed to remove invalid camera output {:?}: {e}",
+ camera_output
+ );
+ }
+ false
+ }
+ };
- for fragment in camera_frags {
- if let Err(e) = std::fs::remove_file(fragment) {
- debug!("Failed to remove camera fragment {:?}: {e}", fragment);
+ if camera_ok {
+ for fragment in camera_frags {
+ if let Err(e) = std::fs::remove_file(fragment) {
+ debug!("Failed to remove camera fragment {:?}: {e}", fragment);
+ }
+ }
+ if let Some(init_path) = &segment.camera_init_segment
+ && let Err(e) = std::fs::remove_file(init_path)
+ {
+ debug!("Failed to remove camera init segment {:?}: {e}", init_path);
+ }
+ if camera_dir.exists()
+ && let Err(e) = std::fs::remove_dir_all(&camera_dir)
+ {
+ debug!("Failed to clean up camera dir {:?}: {e}", camera_dir);
}
- }
- if let Some(init_path) = &segment.camera_init_segment
- && let Err(e) = std::fs::remove_file(init_path)
- {
- debug!("Failed to remove camera init segment {:?}: {e}", init_path);
- }
- let camera_dir = segment_dir.join("camera");
- if camera_dir.exists()
- && let Err(e) = std::fs::remove_dir_all(&camera_dir)
- {
- debug!("Failed to clean up camera dir {:?}: {e}", camera_dir);
}
}
}
@@ -745,34 +942,6 @@ impl RecoveryManager {
}
}
- for segment in &recording.recoverable_segments {
- let segment_dir = recording
- .project_path
- .join("content/segments")
- .join(format!("segment-{}", segment.index));
-
- let display_output = segment_dir.join("display.mp4");
- if display_output.exists() {
- Self::validate_required_video(&display_output, "display")?;
- }
-
- let camera_output = segment_dir.join("camera.mp4");
- if camera_output.exists()
- && let Err(e) = Self::validate_required_video(&camera_output, "camera")
- {
- warn!(
- "Camera video validation failed for {:?}: {}",
- camera_output, e
- );
- if let Err(remove_err) = std::fs::remove_file(&camera_output) {
- debug!(
- "Failed to remove invalid camera video {:?}: {remove_err}",
- camera_output
- );
- }
- }
- }
-
let meta = Self::build_recovered_meta(recording)?;
let mut recording_meta = recording.meta.clone();
@@ -794,6 +963,126 @@ impl RecoveryManager {
})
}
+ pub fn finalize_to_progressive_mp4(
+ fragmented_dir: &Path,
+ output: &Path,
+ ) -> Result<PathBuf, RecoveryError> {
+ Self::finalize_to_progressive_mp4_with_health(fragmented_dir, output, None)
+ }
+
+ pub fn finalize_to_progressive_mp4_with_health(
+ fragmented_dir: &Path,
+ output: &Path,
+ health_tx: Option<&HealthSender>,
+ ) -> Result<PathBuf, RecoveryError> {
+ Self::rescue_pending_tmp_fragments(fragmented_dir, health_tx);
+
+ let info = Self::find_complete_fragments_with_init(fragmented_dir);
+ if info.fragments.is_empty() {
+ return Err(RecoveryError::NoRecoverableSegments);
+ }
+
+ let respawn_groups = Self::collect_respawn_groups(fragmented_dir, health_tx);
+
+ if respawn_groups.is_empty() {
+ Self::finalize_fragments_to_progressive_mp4(
+ &info.fragments,
+ info.init_segment.as_deref(),
+ output,
+ "display",
+ )?;
+ return Ok(output.to_path_buf());
+ }
+
+ let mut group_outputs: Vec<PathBuf> = Vec::new();
+ let mut temp_paths: Vec<PathBuf> = Vec::new();
+ let stem = output
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or("recovered");
+ let parent = output.parent().unwrap_or_else(|| Path::new("."));
+
+ let main_tmp = parent.join(format!("{stem}.main.mp4"));
+ Self::finalize_fragments_to_progressive_mp4(
+ &info.fragments,
+ info.init_segment.as_deref(),
+ &main_tmp,
+ "display",
+ )?;
+ temp_paths.push(main_tmp.clone());
+ group_outputs.push(main_tmp);
+
+ for (n, init, fragments) in respawn_groups {
+ let group_tmp = parent.join(format!("{stem}.respawn-{n}.mp4"));
+ match Self::finalize_fragments_to_progressive_mp4(
+ &fragments,
+ Some(init.as_path()),
+ &group_tmp,
+ &format!("display respawn-{n}"),
+ ) {
+ Ok(()) => {
+ temp_paths.push(group_tmp.clone());
+ group_outputs.push(group_tmp);
+ }
+ Err(err) => {
+ warn!(
+ "Respawn-{} group remux failed; skipping those fragments: {err}",
+ n
+ );
+ }
+ }
+ }
+
+ let concat_result = if group_outputs.len() == 1 {
+ std::fs::rename(&group_outputs[0], output)
+ .map_err(|e| RecoveryError::VideoConcat(cap_enc_ffmpeg::remux::RemuxError::Io(e)))
+ } else {
+ concatenate_video_fragments(&group_outputs, output).map_err(RecoveryError::VideoConcat)
+ };
+
+ for tmp in &temp_paths {
+ if tmp.exists() && tmp != output {
+ let _ = std::fs::remove_file(tmp);
+ }
+ }
+
+ concat_result?;
+ Self::validate_required_video(output, "display")?;
+
+ Ok(output.to_path_buf())
+ }
+
+ fn finalize_fragments_to_progressive_mp4(
+ fragments: &[PathBuf],
+ init_segment: Option<&Path>,
+ output: &Path,
+ label: &str,
+ ) -> Result<(), RecoveryError> {
+ if fragments.is_empty() {
+ return Err(RecoveryError::NoRecoverableSegments);
+ }
+
+ if let Some(init_path) = init_segment {
+ info!(
+ "Concatenating {} M4S {label} segments with init to {:?}",
+ fragments.len(),
+ output
+ );
+ concatenate_m4s_segments_with_init(init_path, fragments, output)
+ .map_err(RecoveryError::VideoConcat)?;
+ } else {
+ info!(
+ "Concatenating {} {label} fragments to {:?}",
+ fragments.len(),
+ output
+ );
+ concatenate_video_fragments(fragments, output).map_err(RecoveryError::VideoConcat)?;
+ }
+
+ Self::validate_required_video(output, label)?;
+ Ok(())
+ }
+
fn validate_required_video(path: &Path, label: &str) -> Result<(), RecoveryError> {
info!("Validating recovered {} video: {:?}", label, path);
@@ -886,7 +1175,7 @@ impl RecoveryManager {
let display_start_time = original_segment.and_then(|s| s.display.start_time);
let get_start_time_or_fallback = |original_time: Option<f64>| -> Option<f64> {
- original_time.or_else(|| display_start_time.map(|_| 0.0))
+ start_time_or_display_fallback(original_time, display_start_time)
};
MultipleSegment {
@@ -1167,6 +1456,13 @@ impl RecoveryManager {
}
}
+fn start_time_or_display_fallback(
+ original_time: Option<f64>,
+ display_start_time: Option<f64>,
+) -> Option<f64> {
+ original_time.or(display_start_time)
+}
+
fn replace_file(src: &Path, dst: &Path) -> Result<(), RecoveryError> {
if dst.exists() {
std::fs::remove_file(dst).map_err(RecoveryError::Io)?;
@@ -1177,7 +1473,7 @@ fn replace_file(src: &Path, dst: &Path) -> Result<(), RecoveryError> {
#[cfg(test)]
mod tests {
- use super::replace_file;
+ use super::{replace_file, start_time_or_display_fallback};
use std::fs;
use tempfile::tempdir;
@@ -1195,4 +1491,27 @@ mod tests {
assert_eq!(fs::read(&dst).unwrap(), b"new");
assert!(!src.exists());
}
+
+ #[test]
+ fn start_time_fallback_prefers_original_value() {
+ let original = Some(0.8);
+ let display = Some(0.4);
+ assert_eq!(start_time_or_display_fallback(original, display), Some(0.8),);
+ }
+
+ #[test]
+ fn start_time_fallback_returns_display_value_when_original_missing() {
+ let display = Some(0.4374473);
+ assert_eq!(
+ start_time_or_display_fallback(None, display),
+ Some(0.4374473),
+ "mic/system audio start_time must align with display when unknown \
+ so the editor's offset calculation (latest - start_time) stays at 0",
+ );
+ }
+
+ #[test]
+ fn start_time_fallback_returns_none_when_display_missing() {
+ assert_eq!(start_time_or_display_fallback(None, None), None);
+ }
}
diff --git a/crates/recording/tests/recovery.rs b/crates/recording/tests/recovery.rs
index 62b7b3268..6ab9d52bd 100644
--- a/crates/recording/tests/recovery.rs
+++ b/crates/recording/tests/recovery.rs
@@ -1175,3 +1175,373 @@ fn test_orphaned_segment_minimum_size() {
"Valid segment should be at or above threshold"
);
}
+
+fn make_synthetic_video_frame(width: u32, height: u32) -> ffmpeg::frame::Video {
+ let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, width, height);
+ for plane_idx in 0..frame.planes() {
+ let data = frame.data_mut(plane_idx);
+ for byte in data.iter_mut() {
+ *byte = 128;
+ }
+ }
+ frame
+}
+
+fn synthetic_video_info() -> cap_media_info::VideoInfo {
+ cap_media_info::VideoInfo {
+ pixel_format: cap_media_info::Pixel::NV12,
+ width: 320,
+ height: 240,
+ time_base: ffmpeg::Rational(1, 1_000_000),
+ frame_rate: ffmpeg::Rational(30, 1),
+ }
+}
+
+fn write_synthetic_fragments(display_dir: &Path, total_frames: u64, segment_duration: Duration) {
+ let mut encoder = SegmentedVideoEncoder::init(
+ display_dir.to_path_buf(),
+ synthetic_video_info(),
+ SegmentedVideoEncoderConfig {
+ segment_duration,
+ ..Default::default()
+ },
+ )
+ .expect("synthetic encoder init");
+
+ for i in 0..total_frames {
+ let frame = make_synthetic_video_frame(320, 240);
+ let ts = Duration::from_micros(i * 33_333);
+ encoder.queue_frame(frame, ts).expect("queue frame");
+ }
+
+ drop(encoder);
+}
+
+#[test]
+fn recover_after_simulated_crash_produces_playable_mp4_with_preserved_duration() {
+ test_utils::init_tracing();
+
+ let recording = TestRecording::new().unwrap();
+ let display_dir = recording.create_display_dir(0).unwrap();
+
+ let total_frames = 180u64;
+ write_synthetic_fragments(&display_dir, total_frames, Duration::from_secs(2));
+
+ let m4s_segments: Vec<_> = std::fs::read_dir(&display_dir)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().extension().is_some_and(|ext| ext == "m4s"))
+ .collect();
+ assert!(
+ m4s_segments.len() >= 2,
+ "expected at least 2 complete segments before crash, got {}",
+ m4s_segments.len()
+ );
+ let init_path = display_dir.join("init.mp4");
+ assert!(
+ init_path.exists(),
+ "init.mp4 must exist after simulated crash"
+ );
+
+ recording
+ .write_recording_meta(StudioRecordingStatus::InProgress)
+ .unwrap();
+
+ let incomplete = RecoveryManager::inspect_recording(recording.path())
+ .expect("inspect should find recoverable fragments");
+ assert!(!incomplete.recoverable_segments.is_empty());
+
+ RecoveryManager::recover(&incomplete).expect("recovery should succeed");
+
+ let display_mp4 = recording
+ .path()
+ .join("content/segments/segment-0/display.mp4");
+ assert!(
+ display_mp4.exists(),
+ "display.mp4 must exist after recovery"
+ );
+
+ assert!(
+ probe_video_can_decode(&display_mp4).unwrap_or(false),
+ "recovered display.mp4 must be decodable"
+ );
+
+ let duration = cap_enc_ffmpeg::remux::get_media_duration(&display_mp4)
+ .expect("recovered display.mp4 must expose a duration");
+ assert!(
+ duration >= Duration::from_secs(4),
+ "recovered duration {duration:?} below 4s (wrote ~6s)"
+ );
+
+ assert!(
+ !display_dir.exists() || std::fs::read_dir(&display_dir).unwrap().next().is_none(),
+ "display/ fragment dir should be emptied or removed after successful recovery"
+ );
+}
+
+#[test]
+fn recover_preserves_fragments_when_progressive_mp4_validation_fails() {
+ test_utils::init_tracing();
+
+ let recording = TestRecording::new().unwrap();
+ let display_dir = recording.create_display_dir(0).unwrap();
+
+ write_synthetic_fragments(&display_dir, 180, Duration::from_secs(2));
+
+ let init_path = display_dir.join("init.mp4");
+ std::fs::write(&init_path, vec![0u8; 2048]).unwrap();
+
+ let fragment_count_before = std::fs::read_dir(&display_dir).unwrap().count();
+ assert!(
+ fragment_count_before > 1,
+ "expected multiple files before recovery"
+ );
+
+ recording
+ .write_recording_meta(StudioRecordingStatus::InProgress)
+ .unwrap();
+
+ let incomplete = RecoveryManager::inspect_recording(recording.path())
+ .expect("inspect should still detect fragments");
+
+ let result = RecoveryManager::recover(&incomplete);
+ assert!(
+ result.is_err(),
+ "recovery must propagate failure when progressive MP4 is unplayable"
+ );
+ assert!(
+ matches!(
+ result,
+ Err(RecoveryError::UnplayableVideo(_)) | Err(RecoveryError::VideoConcat(_))
+ ),
+ "failure should be UnplayableVideo or VideoConcat, got {result:?}"
+ );
+
+ assert!(
+ display_dir.exists(),
+ "display/ fragment dir must remain after validation failure"
+ );
+ let fragment_count_after = std::fs::read_dir(&display_dir).unwrap().count();
+ assert_eq!(
+ fragment_count_after, fragment_count_before,
+ "no fragments should be deleted after validation failure"
+ );
+
+ let display_mp4 = recording
+ .path()
+ .join("content/segments/segment-0/display.mp4");
+ assert!(
+ !display_mp4.exists(),
+ "invalid concatenated display.mp4 should be removed on failure"
+ );
+}
+
+#[test]
+fn finalize_to_progressive_mp4_includes_respawn_fragments() {
+ test_utils::init_tracing();
+
+ let recording = TestRecording::new().unwrap();
+ let display_dir = recording.create_display_dir(0).unwrap();
+
+ write_synthetic_fragments(&display_dir, 300, Duration::from_secs(2));
+
+ let original_segments: Vec<_> = std::fs::read_dir(&display_dir)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().extension().is_some_and(|ext| ext == "m4s"))
+ .collect();
+ let original_count = original_segments.len();
+ assert!(
+ original_count >= 2,
+ "expected at least 2 original segments, got {original_count}"
+ );
+
+ let respawn_dir = display_dir.join("respawn-1");
+ std::fs::create_dir_all(&respawn_dir).unwrap();
+ write_synthetic_fragments(&respawn_dir, 300, Duration::from_secs(2));
+
+ let respawn_segments: Vec<_> = std::fs::read_dir(&respawn_dir)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().extension().is_some_and(|ext| ext == "m4s"))
+ .collect();
+ let respawn_count = respawn_segments.len();
+ assert!(
+ respawn_count >= 2,
+ "expected at least 2 respawn fragments, got {respawn_count}"
+ );
+
+ let output = recording.path().join("finalized.mp4");
+ RecoveryManager::finalize_to_progressive_mp4(&display_dir, &output)
+ .expect("finalize_to_progressive_mp4 should succeed with respawn fragments");
+
+ let duration = cap_enc_ffmpeg::remux::get_media_duration(&output).expect("read duration");
+
+ let single_dir_output = recording.path().join("single_dir_baseline.mp4");
+ let baseline_dir = recording.path().join("baseline_dir");
+ std::fs::create_dir_all(&baseline_dir).unwrap();
+ write_synthetic_fragments(&baseline_dir, 300, Duration::from_secs(2));
+ RecoveryManager::finalize_to_progressive_mp4(&baseline_dir, &single_dir_output)
+ .expect("baseline finalize should succeed");
+ let baseline_duration =
+ cap_enc_ffmpeg::remux::get_media_duration(&single_dir_output).expect("baseline duration");
+
+ assert!(
+ duration.as_secs_f64() > baseline_duration.as_secs_f64() * 1.5,
+ "finalized duration {:?} must be substantially longer than single-dir baseline {:?} \
+ when respawn fragments exist",
+ duration,
+ baseline_duration
+ );
+
+ assert!(
+ probe_video_can_decode(&output).unwrap_or(false),
+ "finalized MP4 with respawn fragments must be decodable"
+ );
+}
+
+#[test]
+fn finalize_to_progressive_mp4_rescues_pending_tmp_fragments_in_respawn_dir() {
+ test_utils::init_tracing();
+
+ let recording = TestRecording::new().unwrap();
+ let display_dir = recording.create_display_dir(0).unwrap();
+ write_synthetic_fragments(&display_dir, 300, Duration::from_secs(2));
+
+ let respawn_dir = display_dir.join("respawn-1");
+ std::fs::create_dir_all(&respawn_dir).unwrap();
+ write_synthetic_fragments(&respawn_dir, 300, Duration::from_secs(2));
+
+ let respawn_entries: Vec<_> = std::fs::read_dir(&respawn_dir)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| {
+ p.extension().is_some_and(|ext| ext == "m4s")
+ && p.file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with("segment_"))
+ })
+ .collect();
+
+ let to_disguise = respawn_entries
+ .last()
+ .expect("respawn dir should have at least one .m4s");
+ let tmp_target = to_disguise.with_extension("m4s.tmp");
+ let file_size_before = std::fs::metadata(to_disguise).unwrap().len();
+ std::fs::rename(to_disguise, &tmp_target).unwrap();
+ assert!(tmp_target.exists(), "renamed .tmp should exist");
+ assert!(
+ !to_disguise.exists(),
+ "original .m4s should no longer exist"
+ );
+
+ let output = recording.path().join("finalized_with_tmp.mp4");
+ RecoveryManager::finalize_to_progressive_mp4(&display_dir, &output)
+ .expect("finalize should succeed and rescue the .tmp");
+
+ assert!(
+ to_disguise.exists() || !tmp_target.exists(),
+ "either the .tmp was rescued into .m4s ({}) or still present as .tmp ({})",
+ to_disguise.display(),
+ tmp_target.display()
+ );
+
+ if to_disguise.exists() {
+ let size_after = std::fs::metadata(to_disguise).unwrap().len();
+ assert_eq!(
+ size_after, file_size_before,
+ "rescued .m4s should have same byte count as the original .m4s.tmp"
+ );
+ }
+
+ assert!(
+ probe_video_can_decode(&output).unwrap_or(false),
+ "output MP4 should decode cleanly even after rescuing a .tmp fragment"
+ );
+}
+
+#[test]
+fn finalize_to_progressive_mp4_rejects_truncated_tmp_fragments_in_respawn_dir() {
+ test_utils::init_tracing();
+
+ let recording = TestRecording::new().unwrap();
+ let display_dir = recording.create_display_dir(0).unwrap();
+ write_synthetic_fragments(&display_dir, 300, Duration::from_secs(2));
+
+ let respawn_dir = display_dir.join("respawn-1");
+ std::fs::create_dir_all(&respawn_dir).unwrap();
+ write_synthetic_fragments(&respawn_dir, 300, Duration::from_secs(2));
+
+ let respawn_entries: Vec<_> = std::fs::read_dir(&respawn_dir)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| {
+ p.extension().is_some_and(|ext| ext == "m4s")
+ && p.file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with("segment_"))
+ })
+ .collect();
+
+ let to_disguise = respawn_entries
+ .last()
+ .expect("respawn dir should have at least one .m4s");
+ let tmp_target = to_disguise.with_extension("m4s.tmp");
+ std::fs::rename(to_disguise, &tmp_target).unwrap();
+
+ let original_len = std::fs::metadata(&tmp_target).unwrap().len();
+ let truncated_len = original_len.saturating_sub(12);
+ std::fs::OpenOptions::new()
+ .write(true)
+ .open(&tmp_target)
+ .unwrap()
+ .set_len(truncated_len)
+ .unwrap();
+
+ let output = recording.path().join("finalized_with_truncated_tmp.mp4");
+ RecoveryManager::finalize_to_progressive_mp4(&display_dir, &output)
+ .expect("finalize should succeed while skipping truncated tmp");
+
+ let corrupt_marker = respawn_dir.join(format!(
+ "{}.corrupt",
+ tmp_target.file_name().unwrap().to_string_lossy()
+ ));
+
+ assert!(tmp_target.exists(), "truncated tmp must remain quarantined");
+ assert!(
+ corrupt_marker.exists(),
+ "truncated tmp must get a .corrupt marker for future retries"
+ );
+ assert!(
+ probe_video_can_decode(&output).unwrap_or(false),
+ "output MP4 should decode cleanly after skipping truncated tmp"
+ );
+}
+
+#[test]
+fn finalize_to_progressive_mp4_public_api_produces_playable_output() {
+ test_utils::init_tracing();
+
+ let recording = TestRecording::new().unwrap();
+ let display_dir = recording.create_display_dir(0).unwrap();
+
+ write_synthetic_fragments(&display_dir, 120, Duration::from_secs(2));
+
+ let output = recording.path().join("finalized.mp4");
+ let produced = RecoveryManager::finalize_to_progressive_mp4(&display_dir, &output)
+ .expect("finalize_to_progressive_mp4 should succeed on valid fragments");
+
+ assert_eq!(produced, output);
+ assert!(output.exists(), "progressive MP4 must exist");
+ assert!(
+ probe_video_can_decode(&output).unwrap_or(false),
+ "finalized MP4 must be decodable"
+ );
+
+ assert!(
+ display_dir.join("init.mp4").exists(),
+ "finalize_to_progressive_mp4 must not delete fragments - that's the caller's responsibility"
+ );
+}