Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: let DASH own manifest publication on Windows

Richie McIlroy7af8b850b252
diff --git a/crates/enc-ffmpeg/src/mux/dash_audio.rs b/crates/enc-ffmpeg/src/mux/dash_audio.rs
index 4bff4b82d..9ee89ce28 100644
--- a/crates/enc-ffmpeg/src/mux/dash_audio.rs
+++ b/crates/enc-ffmpeg/src/mux/dash_audio.rs
@@ -127,6 +127,8 @@ pub enum QueueFrameError {
pub enum FinishError {
#[error("FFmpeg: {0}")]
FFmpeg(#[from] ffmpeg::Error),
+ #[error("IO: {0}")]
+ Io(#[from] std::io::Error),
}
impl DashAudioSegmentEncoder {
@@ -144,7 +146,7 @@ impl DashAudioSegmentEncoder {
#[cfg(not(target_os = "windows"))]
let manifest_path_str = manifest_path.to_string_lossy().to_string();
- let mut output = format::output_as(&manifest_path_str, "dash")?;
+ let mut output = super::dash_output::create(&manifest_path_str)?;
let init_seg_str = INIT_SEGMENT_NAME;
let media_seg_str = "segment_$Number%03d$.m4s";
@@ -368,13 +370,12 @@ impl DashAudioSegmentEncoder {
}
pub fn finish(&mut self) -> Result<(), FinishError> {
- if let Err(e) = self.encoder.flush(&mut self.output) {
- tracing::warn!("Audio encoder flush warning: {e}");
- }
-
- if let Err(e) = self.output.write_trailer() {
- tracing::warn!("Audio write_trailer warning: {e}");
- }
+ let flush_result = self.encoder.flush(&mut self.output).inspect_err(|error| {
+ tracing::warn!(%error, "Audio encoder flush failed");
+ });
+ let trailer_result = self.output.write_trailer().inspect_err(|error| {
+ tracing::warn!(%error, "Audio trailer publication failed");
+ });
self.try_notify_init_segment();
self.finalize_pending_tmp_files();
@@ -382,7 +383,15 @@ impl DashAudioSegmentEncoder {
self.collect_orphaned_segments();
- self.finalize_manifest();
+ if let Err(error) = flush_result.and(trailer_result) {
+ self.write_in_progress_manifest();
+ return Err(error.into());
+ }
+ if let Err(error) = super::dash_output::verify_final_manifest(&self.base_path) {
+ self.write_in_progress_manifest();
+ return Err(error.into());
+ }
+ self.finalize_manifest()?;
Ok(())
}
@@ -486,7 +495,7 @@ impl DashAudioSegmentEncoder {
self.completed_segments.sort_by_key(|s| s.index);
}
- fn finalize_manifest(&self) {
+ fn finalize_manifest(&self) -> std::io::Result<()> {
let total_duration: Duration = self.completed_segments.iter().map(|s| s.duration).sum();
let manifest = Manifest {
@@ -514,12 +523,7 @@ impl DashAudioSegmentEncoder {
};
let manifest_path = self.base_path.join("manifest.json");
- if let Err(e) = atomic_write_json(&manifest_path, &manifest) {
- tracing::warn!(
- "Failed to write final audio manifest to {}: {e}",
- manifest_path.display()
- );
- }
+ atomic_write_json(&manifest_path, &manifest)
}
pub fn completed_segments(&self) -> &[AudioSegmentInfo] {
@@ -638,6 +642,52 @@ mod tests {
assert!((manifest["total_duration"].as_f64().unwrap() - 2.496).abs() < 1e-6);
}
+ #[test]
+ fn failed_dash_manifest_publication_retains_audio_without_claiming_completion() {
+ ffmpeg::init().unwrap();
+ let directory = tempfile::tempdir().unwrap();
+ let base_path = directory.path().to_path_buf();
+ let mut encoder = DashAudioSegmentEncoder::init(
+ base_path.clone(),
+ test_audio_info(),
+ DashAudioSegmentEncoderConfig {
+ segment_duration: Duration::from_secs(1),
+ },
+ )
+ .unwrap();
+ for i in 0..60 {
+ encoder
+ .queue_frame(
+ create_test_audio_frame(1024, i * 1024),
+ Duration::from_secs_f64((i * 1024) as f64 / 48_000.0),
+ )
+ .unwrap();
+ }
+ let retained_segments: Vec<_> = encoder
+ .completed_segments()
+ .iter()
+ .map(|segment| (segment.path.clone(), std::fs::read(&segment.path).unwrap()))
+ .collect();
+ assert!(!retained_segments.is_empty());
+ let manifest_path = base_path.join("dash_manifest.mpd");
+ if manifest_path.exists() {
+ std::fs::remove_file(&manifest_path).unwrap();
+ }
+ std::fs::create_dir(&manifest_path).unwrap();
+
+ assert!(encoder.finish().is_err());
+
+ let manifest: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(base_path.join("manifest.json")).unwrap())
+ .unwrap();
+ assert_eq!(manifest["is_complete"], false);
+ assert!(!encoder.completed_segments().is_empty());
+ assert!(encoder.init_segment_path().is_file());
+ for (path, bytes) in retained_segments {
+ assert_eq!(std::fs::read(path).unwrap(), bytes);
+ }
+ }
+
#[test]
fn dash_audio_encoder_creates_init_segment() {
ffmpeg::init().ok();
diff --git a/crates/enc-ffmpeg/src/mux/dash_output.rs b/crates/enc-ffmpeg/src/mux/dash_output.rs
new file mode 100644
index 000000000..05b4a9880
--- /dev/null
+++ b/crates/enc-ffmpeg/src/mux/dash_output.rs
@@ -0,0 +1,55 @@
+use ffmpeg::{Error, format};
+use std::{ffi::CString, path::Path, ptr};
+
+pub(super) fn create(path: &str) -> Result<format::context::Output, Error> {
+ let path = CString::new(path).map_err(|_| Error::InvalidData)?;
+ let mut context = ptr::null_mut();
+
+ // DASH owns manifest I/O; opening pb here prevents Windows from replacing the manifest.
+ let result = unsafe {
+ ffmpeg::ffi::avformat_alloc_output_context2(
+ &mut context,
+ ptr::null_mut(),
+ c"dash".as_ptr(),
+ path.as_ptr(),
+ )
+ };
+ if result < 0 {
+ return Err(Error::from(result));
+ }
+ if context.is_null() {
+ return Err(Error::Unknown);
+ }
+
+ Ok(unsafe { format::context::Output::wrap(context) })
+}
+
+pub(super) fn verify_final_manifest(base_path: &Path) -> std::io::Result<()> {
+ let manifest = std::fs::read_to_string(base_path.join("dash_manifest.mpd"))?;
+ if !manifest.contains("type=\"static\"") || !manifest.trim_end().ends_with("</MPD>") {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "DASH manifest was not finalized",
+ ));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn dash_context_does_not_open_or_truncate_manifest() {
+ ffmpeg::init().unwrap();
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("dash_manifest.mpd");
+ std::fs::write(&path, b"previous manifest").unwrap();
+
+ let output = create(path.to_str().unwrap()).unwrap();
+
+ assert!(output.format().flags().contains(format::Flags::NO_FILE));
+ assert!(unsafe { (*output.as_ptr()).pb.is_null() });
+ assert_eq!(std::fs::read(&path).unwrap(), b"previous manifest");
+ }
+}
diff --git a/crates/enc-ffmpeg/src/mux/mod.rs b/crates/enc-ffmpeg/src/mux/mod.rs
index 86d58a9c0..24e53ac50 100644
--- a/crates/enc-ffmpeg/src/mux/mod.rs
+++ b/crates/enc-ffmpeg/src/mux/mod.rs
@@ -1,4 +1,5 @@
pub mod dash_audio;
+mod dash_output;
pub mod fragment_manifest;
mod fragment_metadata;
pub mod fragmented_audio;
diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
index b35aba5ca..68e751f7e 100644
--- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs
+++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
@@ -166,6 +166,8 @@ pub enum QueueFrameError {
pub enum FinishError {
#[error("FFmpeg: {0}")]
FFmpeg(#[from] ffmpeg::Error),
+ #[error("IO: {0}")]
+ Io(#[from] std::io::Error),
}
pub struct SegmentedVideoEncoderConfig {
@@ -207,7 +209,7 @@ impl SegmentedVideoEncoder {
#[cfg(not(target_os = "windows"))]
let manifest_path_str = manifest_path.to_string_lossy().to_string();
- let mut output = format::output_as(&manifest_path_str, "dash")?;
+ let mut output = super::dash_output::create(&manifest_path_str)?;
let init_seg_str = INIT_SEGMENT_NAME;
let media_seg_str = "segment_$Number%03d$.m4s";
@@ -494,13 +496,12 @@ impl SegmentedVideoEncoder {
}
pub fn finish(&mut self) -> Result<(), FinishError> {
- if let Err(e) = self.encoder.flush(&mut self.output) {
- tracing::warn!("Video encoder flush warning: {e}");
- }
-
- if let Err(e) = self.output.write_trailer() {
- tracing::warn!("Video write_trailer warning: {e}");
- }
+ let flush_result = self.encoder.flush(&mut self.output).inspect_err(|error| {
+ tracing::warn!(%error, "Video encoder flush failed");
+ });
+ let trailer_result = self.output.write_trailer().inspect_err(|error| {
+ tracing::warn!(%error, "Video trailer publication failed");
+ });
self.try_notify_init_segment();
self.finalize_pending_tmp_files();
@@ -508,7 +509,15 @@ impl SegmentedVideoEncoder {
self.collect_orphaned_segments();
- self.finalize_manifest();
+ if let Err(error) = flush_result.and(trailer_result) {
+ self.write_in_progress_manifest();
+ return Err(error.into());
+ }
+ if let Err(error) = super::dash_output::verify_final_manifest(&self.base_path) {
+ self.write_in_progress_manifest();
+ return Err(error.into());
+ }
+ self.finalize_manifest()?;
Ok(())
}
@@ -650,7 +659,7 @@ impl SegmentedVideoEncoder {
self.completed_segments.sort_by_key(|s| s.index);
}
- fn finalize_manifest(&self) {
+ fn finalize_manifest(&self) -> std::io::Result<()> {
let total_duration: Duration = self.completed_segments.iter().map(|s| s.duration).sum();
let manifest = Manifest {
@@ -679,12 +688,7 @@ impl SegmentedVideoEncoder {
};
let manifest_path = self.base_path.join("manifest.json");
- if let Err(e) = atomic_write_json(&manifest_path, &manifest) {
- tracing::warn!(
- "Failed to write final manifest to {}: {e}",
- manifest_path.display()
- );
- }
+ atomic_write_json(&manifest_path, &manifest)
}
pub fn completed_segments(&self) -> &[VideoSegmentInfo] {
@@ -836,6 +840,50 @@ mod tests {
);
}
+ #[test]
+ fn failed_dash_manifest_publication_retains_video_without_claiming_completion() {
+ ffmpeg::init().unwrap();
+ let directory = tempfile::tempdir().unwrap();
+ let base_path = directory.path().to_path_buf();
+ let mut encoder = SegmentedVideoEncoder::init(
+ base_path.clone(),
+ test_video_info(),
+ SegmentedVideoEncoderConfig::default(),
+ )
+ .unwrap();
+ for i in 0..120 {
+ encoder
+ .queue_frame(
+ create_test_frame(320, 240),
+ Duration::from_micros(i * 33_320),
+ )
+ .unwrap();
+ }
+ let retained_segments: Vec<_> = encoder
+ .completed_segments()
+ .iter()
+ .map(|segment| (segment.path.clone(), std::fs::read(&segment.path).unwrap()))
+ .collect();
+ assert!(!retained_segments.is_empty());
+ let manifest_path = base_path.join("dash_manifest.mpd");
+ if manifest_path.exists() {
+ std::fs::remove_file(&manifest_path).unwrap();
+ }
+ std::fs::create_dir(&manifest_path).unwrap();
+
+ assert!(encoder.finish().is_err());
+
+ let manifest: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(base_path.join("manifest.json")).unwrap())
+ .unwrap();
+ assert_eq!(manifest["is_complete"], false);
+ assert!(!encoder.completed_segments().is_empty());
+ assert!(encoder.init_segment_path().is_file());
+ for (path, bytes) in retained_segments {
+ assert_eq!(std::fs::read(path).unwrap(), bytes);
+ }
+ }
+
#[test]
fn segment_callback_fires_for_init_segment() {
ffmpeg::init().ok();