Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add atomic manifest writes and sync for segmented outputs
Richie McIlroy3ba3568e0bea
diff --git a/crates/enc-avfoundation/src/segmented.rs b/crates/enc-avfoundation/src/segmented.rsindex 8cae09c91..222ea7586 100644--- a/crates/enc-avfoundation/src/segmented.rs+++ b/crates/enc-avfoundation/src/segmented.rs@@ -3,7 +3,37 @@ use cap_media_info::{AudioInfo, VideoInfo};use cidre::arc;use ffmpeg::frame;use serde::Serialize;-use std::{path::PathBuf, time::Duration};+use std::{+ io::Write,+ path::{Path, PathBuf},+ time::Duration,+};++fn atomic_write_json<T: Serialize>(path: &Path, data: &T) -> std::io::Result<()> {+ let temp_path = path.with_extension("json.tmp");+ let json = serde_json::to_string_pretty(data)+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;++ let mut file = std::fs::File::create(&temp_path)?;+ file.write_all(json.as_bytes())?;+ file.sync_all()?;++ std::fs::rename(&temp_path, path)?;++ if let Some(parent) = path.parent() {+ if let Ok(dir) = std::fs::File::open(parent) {+ let _ = dir.sync_all();+ }+ }++ Ok(())+}++fn sync_file(path: &Path) {+ if let Ok(file) = std::fs::File::open(path) {+ let _ = file.sync_all();+ }+}pub struct SegmentedMP4Encoder {base_path: PathBuf,@@ -55,7 +85,7 @@ impl SegmentedMP4Encoder {let segment_path = base_path.join("fragment_000.mp4");let encoder = MP4Encoder::init(segment_path, video_config, audio_config, output_height)?;- Ok(Self {+ let instance = Self {base_path,video_config,audio_config,@@ -65,7 +95,11 @@ impl SegmentedMP4Encoder {segment_duration,segment_start_time: None,completed_segments: Vec::new(),- })+ };++ instance.write_in_progress_manifest();++ Ok(instance)}pub fn queue_video_frame(@@ -106,15 +140,20 @@ impl SegmentedMP4Encoder {fn rotate_segment(&mut self, timestamp: Duration) -> Result<(), QueueFrameError> {let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);let segment_duration = timestamp.saturating_sub(segment_start);+ let completed_segment_path = self.current_segment_path();if let Some(mut encoder) = self.current_encoder.take() {let _ = encoder.finish(Some(timestamp));+ sync_file(&completed_segment_path);+self.completed_segments.push(SegmentInfo {- path: self.current_segment_path(),+ path: completed_segment_path,index: self.current_index,duration: segment_duration,});++ self.write_manifest();}self.current_index += 1;@@ -131,7 +170,7 @@ impl SegmentedMP4Encoder {.map_err(|_| QueueFrameError::Failed)?,);- self.write_manifest();+ self.write_in_progress_manifest();Ok(())}@@ -163,10 +202,56 @@ impl SegmentedMP4Encoder {};let manifest_path = self.base_path.join("manifest.json");- let _ = std::fs::write(- manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- );+ if let Err(e) = atomic_write_json(&manifest_path, &manifest) {+ tracing::warn!(+ "Failed to write manifest to {}: {e}",+ manifest_path.display()+ );+ }+ }++ fn write_in_progress_manifest(&self) {+ let mut fragments: Vec<FragmentEntry> = self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect();++ fragments.push(FragmentEntry {+ path: self+ .current_segment_path()+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: self.current_index,+ duration: 0.0,+ is_complete: false,+ });++ let manifest = Manifest {+ fragments,+ total_duration: None,+ is_complete: false,+ };++ let manifest_path = self.base_path.join("manifest.json");+ if let Err(e) = atomic_write_json(&manifest_path, &manifest) {+ tracing::warn!(+ "Failed to write in-progress manifest to {}: {e}",+ manifest_path.display()+ );+ }}pub fn pause(&mut self) {@@ -227,10 +312,12 @@ impl SegmentedMP4Encoder {};let manifest_path = self.base_path.join("manifest.json");- let _ = std::fs::write(- manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- );+ if let Err(e) = atomic_write_json(&manifest_path, &manifest) {+ tracing::warn!(+ "Failed to write final manifest to {}: {e}",+ manifest_path.display()+ );+ }}pub fn completed_segments(&self) -> &[SegmentInfo] {diff --git a/crates/enc-ffmpeg/src/mux/segmented_audio.rs b/crates/enc-ffmpeg/src/mux/segmented_audio.rsindex b00f7c4a3..76779cb9d 100644--- a/crates/enc-ffmpeg/src/mux/segmented_audio.rs+++ b/crates/enc-ffmpeg/src/mux/segmented_audio.rs@@ -2,7 +2,37 @@ use crate::audio::aac::{AACEncoder, AACEncoderError};use cap_media_info::AudioInfo;use ffmpeg::{format, frame};use serde::Serialize;-use std::{path::PathBuf, time::Duration};+use std::{+ io::Write,+ path::{Path, PathBuf},+ time::Duration,+};++fn atomic_write_json<T: Serialize>(path: &Path, data: &T) -> std::io::Result<()> {+ let temp_path = path.with_extension("json.tmp");+ let json = serde_json::to_string_pretty(data)+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;++ let mut file = std::fs::File::create(&temp_path)?;+ file.write_all(json.as_bytes())?;+ file.sync_all()?;++ std::fs::rename(&temp_path, path)?;++ if let Some(parent) = path.parent() {+ if let Ok(dir) = std::fs::File::open(parent) {+ let _ = dir.sync_all();+ }+ }++ Ok(())+}++fn sync_file(path: &Path) {+ if let Ok(file) = std::fs::File::open(path) {+ let _ = file.sync_all();+ }+}pub struct SegmentedAudioEncoder {base_path: PathBuf,@@ -81,7 +111,7 @@ impl SegmentedAudioEncoder {let segment_path = base_path.join("fragment_000.m4a");let encoder = Self::create_segment_encoder(segment_path, audio_config)?;- Ok(Self {+ let instance = Self {base_path,audio_config,current_encoder: Some(encoder),@@ -90,7 +120,11 @@ impl SegmentedAudioEncoder {segment_start_time: None,last_frame_timestamp: None,completed_segments: Vec::new(),- })+ };++ instance.write_in_progress_manifest();++ Ok(instance)}fn create_segment_encoder(@@ -149,16 +183,21 @@ impl SegmentedAudioEncoder {fn rotate_segment(&mut self, timestamp: Duration) -> Result<(), QueueFrameError> {let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);let segment_duration = timestamp.saturating_sub(segment_start);+ let completed_segment_path = self.current_segment_path();if let Some(mut encoder) = self.current_encoder.take() {let _ = encoder.encoder.flush(&mut encoder.output);let _ = encoder.output.write_trailer();+ sync_file(&completed_segment_path);+self.completed_segments.push(SegmentInfo {- path: self.current_segment_path(),+ path: completed_segment_path,index: self.current_index,duration: segment_duration,});++ self.write_manifest();}self.current_index += 1;@@ -167,7 +206,7 @@ impl SegmentedAudioEncoder {let new_path = self.current_segment_path();self.current_encoder = Some(Self::create_segment_encoder(new_path, self.audio_config)?);- self.write_manifest();+ self.write_in_progress_manifest();Ok(())}@@ -199,10 +238,56 @@ impl SegmentedAudioEncoder {};let manifest_path = self.base_path.join("manifest.json");- let _ = std::fs::write(- manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- );+ if let Err(e) = atomic_write_json(&manifest_path, &manifest) {+ tracing::warn!(+ "Failed to write manifest to {}: {e}",+ manifest_path.display()+ );+ }+ }++ fn write_in_progress_manifest(&self) {+ let mut fragments: Vec<FragmentEntry> = self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect();++ fragments.push(FragmentEntry {+ path: self+ .current_segment_path()+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: self.current_index,+ duration: 0.0,+ is_complete: false,+ });++ let manifest = Manifest {+ fragments,+ total_duration: None,+ is_complete: false,+ };++ let manifest_path = self.base_path.join("manifest.json");+ if let Err(e) = atomic_write_json(&manifest_path, &manifest) {+ tracing::warn!(+ "Failed to write in-progress manifest to {}: {e}",+ manifest_path.display()+ );+ }}pub fn finish(&mut self) -> Result<(), FinishError> {@@ -298,10 +383,12 @@ impl SegmentedAudioEncoder {};let manifest_path = self.base_path.join("manifest.json");- let _ = std::fs::write(- manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- );+ if let Err(e) = atomic_write_json(&manifest_path, &manifest) {+ tracing::warn!(+ "Failed to write final manifest to {}: {e}",+ manifest_path.display()+ );+ }}pub fn completed_segments(&self) -> &[SegmentInfo] {diff --git a/crates/recording/src/fragmentation/mod.rs b/crates/recording/src/fragmentation/mod.rsindex 0f40f0ecb..ca9d398e0 100644--- a/crates/recording/src/fragmentation/mod.rs+++ b/crates/recording/src/fragmentation/mod.rs@@ -1,7 +1,38 @@mod manifest;pub use manifest::*;-use std::{path::PathBuf, time::Duration};+use serde::Serialize;+use std::{+ io::Write,+ path::{Path, PathBuf},+ time::Duration,+};++pub fn atomic_write_json<T: Serialize>(path: &Path, data: &T) -> std::io::Result<()> {+ let temp_path = path.with_extension("json.tmp");+ let json = serde_json::to_string_pretty(data)+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;++ let mut file = std::fs::File::create(&temp_path)?;+ file.write_all(json.as_bytes())?;+ file.sync_all()?;++ std::fs::rename(&temp_path, path)?;++ if let Some(parent) = path.parent() {+ if let Ok(dir) = std::fs::File::open(parent) {+ let _ = dir.sync_all();+ }+ }++ Ok(())+}++pub fn sync_file(path: &Path) {+ if let Ok(file) = std::fs::File::open(path) {+ let _ = file.sync_all();+ }+}pub struct FragmentManager {base_path: PathBuf,@@ -75,9 +106,7 @@ impl FragmentManager {};let manifest_path = self.base_path.join("manifest.json");- let json = serde_json::to_string_pretty(&manifest)?;- std::fs::write(manifest_path, json)?;- Ok(())+ atomic_write_json(&manifest_path, &manifest)}pub fn finalize_manifest(&self) -> std::io::Result<()> {@@ -88,9 +117,7 @@ impl FragmentManager {};let manifest_path = self.base_path.join("manifest.json");- let json = serde_json::to_string_pretty(&manifest)?;- std::fs::write(manifest_path, json)?;- Ok(())+ atomic_write_json(&manifest_path, &manifest)}fn total_duration(&self) -> Option<Duration> {diff --git a/crates/recording/src/output_pipeline/win_segmented.rs b/crates/recording/src/output_pipeline/win_segmented.rsindex 7a134ebfe..7f1acfbfa 100644--- a/crates/recording/src/output_pipeline/win_segmented.rs+++ b/crates/recording/src/output_pipeline/win_segmented.rs@@ -1,4 +1,4 @@-use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, screen_capture};+use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, fragmentation, screen_capture};use anyhow::{Context, anyhow};use cap_media_info::{AudioInfo, VideoInfo};use serde::Serialize;@@ -209,6 +209,8 @@ impl Muxer for WindowsSegmentedMuxer {.lock().map_err(|_| anyhow!("Failed to lock output"))?;output.write_trailer()?;++ fragmentation::sync_file(&self.current_segment_path());}self.finalize_manifest();@@ -245,10 +247,12 @@ impl WindowsSegmentedMuxer {};let manifest_path = self.base_path.join("manifest.json");- let _ = std::fs::write(- manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- );+ if let Err(e) = fragmentation::atomic_write_json(&manifest_path, &manifest) {+ warn!(+ "Failed to write manifest to {}: {e}",+ manifest_path.display()+ );+ }}fn finalize_manifest(&self) {@@ -275,10 +279,12 @@ impl WindowsSegmentedMuxer {};let manifest_path = self.base_path.join("manifest.json");- let _ = std::fs::write(- manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- );+ if let Err(e) = fragmentation::atomic_write_json(&manifest_path, &manifest) {+ warn!(+ "Failed to write final manifest to {}: {e}",+ manifest_path.display()+ );+ }}fn create_segment(&mut self) -> anyhow::Result<()> {@@ -500,6 +506,7 @@ impl WindowsSegmentedMuxer {fn rotate_segment(&mut self, timestamp: Duration) -> anyhow::Result<()> {let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);let segment_duration = timestamp.saturating_sub(segment_start);+ let completed_segment_path = self.current_segment_path();if let Some(mut state) = self.current_state.take() {let _ = state.video_tx.send(None);@@ -529,18 +536,22 @@ impl WindowsSegmentedMuxer {.map_err(|_| anyhow!("Failed to lock output"))?;output.write_trailer()?;+ fragmentation::sync_file(&completed_segment_path);+self.completed_segments.push(SegmentInfo {- path: self.current_segment_path(),+ path: completed_segment_path,index: self.current_index,duration: segment_duration,});++ self.write_manifest();}self.current_index += 1;self.segment_start_time = Some(timestamp);self.create_segment()?;- self.write_manifest();+ self.write_in_progress_manifest();info!("Rotated to segment {} at {:?}",@@ -549,6 +560,50 @@ impl WindowsSegmentedMuxer {Ok(())}++ fn write_in_progress_manifest(&self) {+ let mut fragments: Vec<FragmentEntry> = self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect();++ fragments.push(FragmentEntry {+ path: self+ .current_segment_path()+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: self.current_index,+ duration: 0.0,+ is_complete: false,+ });++ let manifest = Manifest {+ fragments,+ total_duration: None,+ is_complete: false,+ };++ let manifest_path = self.base_path.join("manifest.json");+ if let Err(e) = fragmentation::atomic_write_json(&manifest_path, &manifest) {+ warn!(+ "Failed to write in-progress manifest to {}: {e}",+ manifest_path.display()+ );+ }+ }}impl VideoMuxer for WindowsSegmentedMuxer {@@ -566,6 +621,7 @@ impl VideoMuxer for WindowsSegmentedMuxer {if self.current_state.is_none() {self.segment_start_time = Some(adjusted_timestamp);self.create_segment()?;+ self.write_in_progress_manifest();}if self.segment_start_time.is_none() {diff --git a/crates/recording/src/output_pipeline/win_segmented_camera.rs b/crates/recording/src/output_pipeline/win_segmented_camera.rsindex 97a4e5b16..32e7fc880 100644--- a/crates/recording/src/output_pipeline/win_segmented_camera.rs+++ b/crates/recording/src/output_pipeline/win_segmented_camera.rs@@ -1,5 +1,5 @@use crate::output_pipeline::win::{NativeCameraFrame, upload_mf_buffer_to_texture};-use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer};+use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, fragmentation};use anyhow::{Context, anyhow};use cap_media_info::{AudioInfo, VideoInfo};use serde::Serialize;@@ -200,6 +200,8 @@ impl Muxer for WindowsSegmentedCameraMuxer {.lock().map_err(|_| anyhow!("Failed to lock output"))?;output.write_trailer()?;++ fragmentation::sync_file(&self.current_segment_path());}self.finalize_manifest();@@ -236,10 +238,7 @@ impl WindowsSegmentedCameraMuxer {};let manifest_path = self.base_path.join("manifest.json");- if let Err(e) = std::fs::write(- &manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- ) {+ if let Err(e) = fragmentation::atomic_write_json(&manifest_path, &manifest) {warn!("Failed to write manifest to {}: {e}",manifest_path.display()@@ -271,10 +270,7 @@ impl WindowsSegmentedCameraMuxer {};let manifest_path = self.base_path.join("manifest.json");- if let Err(e) = std::fs::write(- &manifest_path,- serde_json::to_string_pretty(&manifest).unwrap_or_default(),- ) {+ if let Err(e) = fragmentation::atomic_write_json(&manifest_path, &manifest) {warn!("Failed to write final manifest to {}: {e}",manifest_path.display()@@ -449,6 +445,7 @@ impl WindowsSegmentedCameraMuxer {) -> anyhow::Result<()> {let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);let segment_duration = timestamp.saturating_sub(segment_start);+ let completed_segment_path = self.current_segment_path();if let Some(mut state) = self.current_state.take() {let _ = state.video_tx.send(None);@@ -483,18 +480,22 @@ impl WindowsSegmentedCameraMuxer {.map_err(|_| anyhow!("Failed to lock output"))?;output.write_trailer()?;+ fragmentation::sync_file(&completed_segment_path);+self.completed_segments.push(SegmentInfo {- path: self.current_segment_path(),+ path: completed_segment_path,index: self.current_index,duration: segment_duration,});++ self.write_manifest();}self.current_index += 1;self.segment_start_time = Some(timestamp);self.create_segment(next_frame)?;- self.write_manifest();+ self.write_in_progress_manifest();info!("Camera rotated to segment {} at {:?}",@@ -503,6 +504,50 @@ impl WindowsSegmentedCameraMuxer {Ok(())}++ fn write_in_progress_manifest(&self) {+ let mut fragments: Vec<FragmentEntry> = self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect();++ fragments.push(FragmentEntry {+ path: self+ .current_segment_path()+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: self.current_index,+ duration: 0.0,+ is_complete: false,+ });++ let manifest = Manifest {+ fragments,+ total_duration: None,+ is_complete: false,+ };++ let manifest_path = self.base_path.join("manifest.json");+ if let Err(e) = fragmentation::atomic_write_json(&manifest_path, &manifest) {+ warn!(+ "Failed to write in-progress manifest to {}: {e}",+ manifest_path.display()+ );+ }+ }}impl VideoMuxer for WindowsSegmentedCameraMuxer {@@ -520,6 +565,7 @@ impl VideoMuxer for WindowsSegmentedCameraMuxer {if self.current_state.is_none() {self.segment_start_time = Some(adjusted_timestamp);self.create_segment(&frame)?;+ self.write_in_progress_manifest();}if self.segment_start_time.is_none() {