Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Remove fragmented_mp4, add segmented_stream encoder

Richie McIlroyb7011d8206c9
diff --git a/crates/enc-ffmpeg/src/lib.rs b/crates/enc-ffmpeg/src/lib.rs
index d57097346..2dd64f560 100644
--- a/crates/enc-ffmpeg/src/lib.rs
+++ b/crates/enc-ffmpeg/src/lib.rs
@@ -13,6 +13,3 @@ pub mod remux;
pub mod segmented_audio {
pub use crate::mux::segmented_audio::*;
}
-pub mod fragmented_mp4 {
- pub use crate::mux::fragmented_mp4::*;
-}
diff --git a/crates/enc-ffmpeg/src/mux/fragmented_mp4.rs b/crates/enc-ffmpeg/src/mux/fragmented_mp4.rs
deleted file mode 100644
index 20f1b034e..000000000
--- a/crates/enc-ffmpeg/src/mux/fragmented_mp4.rs
+++ /dev/null
@@ -1,170 +0,0 @@
-use cap_media_info::RawVideoFormat;
-use ffmpeg::{format, frame};
-use std::{path::PathBuf, time::Duration};
-use tracing::*;
-
-use crate::{
- audio::AudioEncoder,
- h264,
- video::h264::{H264Encoder, H264EncoderError},
-};
-
-pub struct FragmentedMP4File {
- output: format::context::Output,
- video: H264Encoder,
- audio: Option<Box<dyn AudioEncoder + Send>>,
- is_finished: bool,
- has_frames: bool,
-}
-
-#[derive(thiserror::Error, Debug)]
-pub enum InitError {
- #[error("{0:?}")]
- Ffmpeg(ffmpeg::Error),
- #[error("Video/{0}")]
- VideoInit(H264EncoderError),
- #[error("Audio/{0}")]
- AudioInit(Box<dyn std::error::Error>),
- #[error("Failed to create output directory: {0}")]
- CreateDirectory(std::io::Error),
-}
-
-#[derive(thiserror::Error, Debug)]
-pub enum FinishError {
- #[error("Already finished")]
- AlreadyFinished,
- #[error("{0}")]
- WriteTrailerFailed(ffmpeg::Error),
-}
-
-pub struct FinishResult {
- pub video_finish: Result<(), ffmpeg::Error>,
- pub audio_finish: Result<(), ffmpeg::Error>,
-}
-
-impl FragmentedMP4File {
- pub fn init(
- mut output_path: PathBuf,
- video: impl FnOnce(&mut format::context::Output) -> Result<H264Encoder, H264EncoderError>,
- audio: impl FnOnce(
- &mut format::context::Output,
- )
- -> Option<Result<Box<dyn AudioEncoder + Send>, Box<dyn std::error::Error>>>,
- ) -> Result<Self, InitError> {
- output_path.set_extension("mp4");
-
- if let Some(parent) = output_path.parent() {
- std::fs::create_dir_all(parent).map_err(InitError::CreateDirectory)?;
- }
-
- let mut output = format::output_as(&output_path, "mp4").map_err(InitError::Ffmpeg)?;
-
- unsafe {
- let opts = output.as_mut_ptr();
- let key = std::ffi::CString::new("movflags").unwrap();
- let value =
- std::ffi::CString::new("frag_keyframe+empty_moov+default_base_moof").unwrap();
- ffmpeg::ffi::av_opt_set((*opts).priv_data, key.as_ptr(), value.as_ptr(), 0);
- }
-
- trace!("Preparing encoders for fragmented mp4 file");
-
- let video = video(&mut output).map_err(InitError::VideoInit)?;
- let audio = audio(&mut output)
- .transpose()
- .map_err(InitError::AudioInit)?;
-
- info!("Prepared encoders for fragmented mp4 file");
-
- output.write_header().map_err(InitError::Ffmpeg)?;
-
- Ok(Self {
- output,
- video,
- audio,
- is_finished: false,
- has_frames: false,
- })
- }
-
- pub fn video_format() -> RawVideoFormat {
- RawVideoFormat::Yuv420p
- }
-
- pub fn queue_video_frame(
- &mut self,
- frame: frame::Video,
- timestamp: Duration,
- ) -> Result<(), h264::QueueFrameError> {
- if self.is_finished {
- return Ok(());
- }
-
- self.has_frames = true;
- self.video.queue_frame(frame, timestamp, &mut self.output)
- }
-
- pub fn queue_audio_frame(&mut self, frame: frame::Audio) {
- if self.is_finished {
- return;
- }
-
- let Some(audio) = &mut self.audio else {
- return;
- };
-
- self.has_frames = true;
- audio.send_frame(frame, &mut self.output);
- }
-
- pub fn finish(&mut self) -> Result<FinishResult, FinishError> {
- if self.is_finished {
- return Err(FinishError::AlreadyFinished);
- }
-
- self.is_finished = true;
-
- tracing::info!("FragmentedMP4File: Finishing encoding");
-
- let video_finish = self.video.flush(&mut self.output).inspect_err(|e| {
- error!("Failed to finish video encoder: {e:#}");
- });
-
- let audio_finish = self
- .audio
- .as_mut()
- .map(|enc| {
- tracing::info!("FragmentedMP4File: Flushing audio encoder");
- enc.flush(&mut self.output).inspect_err(|e| {
- error!("Failed to finish audio encoder: {e:#}");
- })
- })
- .unwrap_or(Ok(()));
-
- tracing::info!("FragmentedMP4File: Writing trailer");
- self.output
- .write_trailer()
- .map_err(FinishError::WriteTrailerFailed)?;
-
- Ok(FinishResult {
- video_finish,
- audio_finish,
- })
- }
-
- pub fn video(&self) -> &H264Encoder {
- &self.video
- }
-
- pub fn video_mut(&mut self) -> &mut H264Encoder {
- &mut self.video
- }
-}
-
-impl Drop for FragmentedMP4File {
- fn drop(&mut self) {
- if let Err(e) = self.finish() {
- error!("Failed to finish FragmentedMP4File in Drop: {e}");
- }
- }
-}
diff --git a/crates/enc-ffmpeg/src/mux/mod.rs b/crates/enc-ffmpeg/src/mux/mod.rs
index 8ed8362d1..28b1fcf0d 100644
--- a/crates/enc-ffmpeg/src/mux/mod.rs
+++ b/crates/enc-ffmpeg/src/mux/mod.rs
@@ -1,5 +1,5 @@
pub mod fragmented_audio;
-pub mod fragmented_mp4;
pub mod mp4;
pub mod ogg;
pub mod segmented_audio;
+pub mod segmented_stream;
diff --git a/crates/enc-ffmpeg/src/mux/segmented_audio.rs b/crates/enc-ffmpeg/src/mux/segmented_audio.rs
index 1f54d3e74..e24a8ff05 100644
--- a/crates/enc-ffmpeg/src/mux/segmented_audio.rs
+++ b/crates/enc-ffmpeg/src/mux/segmented_audio.rs
@@ -367,6 +367,10 @@ impl SegmentedAudioEncoder {
pub fn finish_with_timestamp(&mut self, timestamp: Duration) -> Result<(), FinishError> {
let segment_path = self.current_segment_path();
let segment_start = self.segment_start_time;
+ let effective_end_timestamp = self
+ .last_frame_timestamp
+ .map(|last| last.max(timestamp))
+ .unwrap_or(timestamp);
if let Some(mut encoder) = self.current_encoder.take() {
if encoder.has_frames {
@@ -383,7 +387,7 @@ impl SegmentedAudioEncoder {
sync_file(&segment_path);
if let Some(start) = segment_start {
- let final_duration = timestamp.saturating_sub(start);
+ let final_duration = effective_end_timestamp.saturating_sub(start);
let file_size = std::fs::metadata(&segment_path).ok().map(|m| m.len());
self.completed_segments.push(SegmentInfo {
diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
new file mode 100644
index 000000000..8dab6f9ae
--- /dev/null
+++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
@@ -0,0 +1,603 @@
+use cap_media_info::VideoInfo;
+use ffmpeg::{format, frame};
+use serde::Serialize;
+use std::{
+ ffi::CString,
+ io::Write,
+ path::{Path, PathBuf},
+ time::Duration,
+};
+
+use crate::video::h264::{H264Encoder, H264EncoderBuilder, H264EncoderError, H264Preset};
+
+const INIT_SEGMENT_NAME: &str = "init.mp4";
+
+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()
+ && let Ok(dir) = std::fs::File::open(parent)
+ && let Err(e) = dir.sync_all()
+ {
+ tracing::warn!(
+ "Directory fsync failed after rename for {}: {e}",
+ parent.display()
+ );
+ }
+
+ Ok(())
+}
+
+fn sync_file(path: &Path) {
+ if let Ok(file) = std::fs::File::open(path) {
+ if let Err(e) = file.sync_all() {
+ tracing::warn!("File fsync failed for {}: {e}", path.display());
+ }
+ }
+}
+
+pub struct SegmentedVideoEncoder {
+ base_path: PathBuf,
+
+ encoder: H264Encoder,
+ output: format::context::Output,
+
+ current_index: u32,
+ segment_duration: Duration,
+ segment_start_time: Option<Duration>,
+ last_frame_timestamp: Option<Duration>,
+ frames_in_segment: u32,
+
+ completed_segments: Vec<VideoSegmentInfo>,
+}
+
+#[derive(Debug, Clone)]
+pub struct VideoSegmentInfo {
+ pub path: PathBuf,
+ pub index: u32,
+ pub duration: Duration,
+ pub file_size: Option<u64>,
+}
+
+#[derive(Serialize)]
+struct SegmentEntry {
+ path: String,
+ index: u32,
+ duration: f64,
+ is_complete: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ file_size: Option<u64>,
+}
+
+const MANIFEST_VERSION: u32 = 4;
+
+#[derive(Serialize)]
+struct Manifest {
+ version: u32,
+ #[serde(rename = "type")]
+ manifest_type: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ init_segment: Option<String>,
+ segments: Vec<SegmentEntry>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ total_duration: Option<f64>,
+ is_complete: bool,
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum InitError {
+ #[error("FFmpeg: {0}")]
+ FFmpeg(#[from] ffmpeg::Error),
+ #[error("Encoder: {0}")]
+ Encoder(#[from] H264EncoderError),
+ #[error("IO: {0}")]
+ Io(#[from] std::io::Error),
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum QueueFrameError {
+ #[error("FFmpeg: {0}")]
+ FFmpeg(#[from] ffmpeg::Error),
+ #[error("Init: {0}")]
+ Init(#[from] InitError),
+ #[error("Encode: {0}")]
+ Encode(#[from] crate::video::h264::QueueFrameError),
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum FinishError {
+ #[error("FFmpeg: {0}")]
+ FFmpeg(#[from] ffmpeg::Error),
+}
+
+pub struct SegmentedVideoEncoderConfig {
+ pub segment_duration: Duration,
+ pub preset: H264Preset,
+ pub bpp: f32,
+ pub output_size: Option<(u32, u32)>,
+}
+
+impl Default for SegmentedVideoEncoderConfig {
+ fn default() -> Self {
+ Self {
+ segment_duration: Duration::from_secs(3),
+ preset: H264Preset::Ultrafast,
+ bpp: H264EncoderBuilder::QUALITY_BPP,
+ output_size: None,
+ }
+ }
+}
+
+impl SegmentedVideoEncoder {
+ pub fn init(
+ base_path: PathBuf,
+ video_config: VideoInfo,
+ config: SegmentedVideoEncoderConfig,
+ ) -> Result<Self, InitError> {
+ std::fs::create_dir_all(&base_path)?;
+
+ let manifest_path = base_path.join("dash_manifest.mpd");
+
+ let mut output = format::output_as(&manifest_path, "dash")?;
+
+ unsafe {
+ let opts = output.as_mut_ptr();
+
+ let set_opt = |key: &str, value: &str| {
+ let k = CString::new(key).unwrap();
+ let v = CString::new(value).unwrap();
+ ffmpeg::ffi::av_opt_set((*opts).priv_data, k.as_ptr(), v.as_ptr(), 0);
+ };
+
+ set_opt("init_seg_name", INIT_SEGMENT_NAME);
+ set_opt("media_seg_name", "segment_$Number%03d$.m4s");
+ set_opt(
+ "seg_duration",
+ &config.segment_duration.as_secs().to_string(),
+ );
+ set_opt("use_timeline", "0");
+ set_opt("use_template", "1");
+ set_opt("single_file", "0");
+ }
+
+ let mut builder = H264EncoderBuilder::new(video_config)
+ .with_preset(config.preset)
+ .with_bpp(config.bpp);
+
+ if let Some((width, height)) = config.output_size {
+ builder = builder.with_output_size(width, height)?;
+ }
+
+ let encoder = builder.build(&mut output)?;
+
+ output.write_header()?;
+
+ tracing::info!(
+ path = %base_path.display(),
+ segment_duration_secs = config.segment_duration.as_secs(),
+ "Initialized segmented video encoder with FFmpeg DASH muxer (init.mp4 + m4s segments)"
+ );
+
+ let instance = Self {
+ base_path,
+ encoder,
+ output,
+ current_index: 1,
+ segment_duration: config.segment_duration,
+ segment_start_time: None,
+ last_frame_timestamp: None,
+ frames_in_segment: 0,
+ completed_segments: Vec::new(),
+ };
+
+ instance.write_in_progress_manifest();
+
+ Ok(instance)
+ }
+
+ pub fn queue_frame(
+ &mut self,
+ frame: frame::Video,
+ timestamp: Duration,
+ ) -> Result<(), QueueFrameError> {
+ if self.segment_start_time.is_none() {
+ self.segment_start_time = Some(timestamp);
+ }
+
+ self.last_frame_timestamp = Some(timestamp);
+
+ let prev_segment_index = self.detect_current_segment_index();
+
+ self.encoder
+ .queue_frame(frame, timestamp, &mut self.output)?;
+ self.frames_in_segment += 1;
+
+ let new_segment_index = self.detect_current_segment_index();
+
+ if new_segment_index > prev_segment_index {
+ self.on_segment_completed(prev_segment_index, timestamp)?;
+ }
+
+ Ok(())
+ }
+
+ fn detect_current_segment_index(&self) -> u32 {
+ let next_segment_path = self
+ .base_path
+ .join(format!("segment_{:03}.m4s", self.current_index + 1));
+ if next_segment_path.exists() {
+ self.current_index + 1
+ } else {
+ self.current_index
+ }
+ }
+
+ fn on_segment_completed(
+ &mut self,
+ completed_index: u32,
+ timestamp: Duration,
+ ) -> Result<(), QueueFrameError> {
+ let segment_path = self
+ .base_path
+ .join(format!("segment_{completed_index:03}.m4s"));
+
+ if segment_path.exists() {
+ sync_file(&segment_path);
+
+ let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);
+ let segment_duration = timestamp.saturating_sub(segment_start);
+
+ let file_size = std::fs::metadata(&segment_path).ok().map(|m| m.len());
+
+ tracing::debug!(
+ segment_index = completed_index,
+ duration_secs = segment_duration.as_secs_f64(),
+ file_size = ?file_size,
+ frames = self.frames_in_segment,
+ "Segment completed"
+ );
+
+ self.completed_segments.push(VideoSegmentInfo {
+ path: segment_path,
+ index: completed_index,
+ duration: segment_duration,
+ file_size,
+ });
+
+ self.current_index = completed_index + 1;
+ self.segment_start_time = Some(timestamp);
+ self.frames_in_segment = 0;
+
+ self.write_manifest();
+ self.write_in_progress_manifest();
+ }
+
+ Ok(())
+ }
+
+ fn current_segment_path(&self) -> PathBuf {
+ self.base_path
+ .join(format!("segment_{:03}.m4s", self.current_index))
+ }
+
+ fn write_manifest(&self) {
+ let manifest = Manifest {
+ version: MANIFEST_VERSION,
+ manifest_type: "m4s_segments",
+ init_segment: Some(INIT_SEGMENT_NAME.to_string()),
+ segments: self
+ .completed_segments
+ .iter()
+ .map(|s| SegmentEntry {
+ 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,
+ file_size: s.file_size,
+ })
+ .collect(),
+ 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 manifest to {}: {e}",
+ manifest_path.display()
+ );
+ }
+ }
+
+ fn write_in_progress_manifest(&self) {
+ let mut segments: Vec<SegmentEntry> = self
+ .completed_segments
+ .iter()
+ .map(|s| SegmentEntry {
+ 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,
+ file_size: s.file_size,
+ })
+ .collect();
+
+ segments.push(SegmentEntry {
+ 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,
+ file_size: None,
+ });
+
+ let manifest = Manifest {
+ version: MANIFEST_VERSION,
+ manifest_type: "m4s_segments",
+ init_segment: Some(INIT_SEGMENT_NAME.to_string()),
+ segments,
+ 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> {
+ let segment_start = self.segment_start_time;
+ let last_timestamp = self.last_frame_timestamp;
+ let frames_before_flush = self.frames_in_segment;
+
+ 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}");
+ }
+
+ self.finalize_pending_tmp_files();
+
+ let end_timestamp =
+ last_timestamp.unwrap_or_else(|| segment_start.unwrap_or(Duration::ZERO));
+ self.collect_orphaned_segments(segment_start, end_timestamp, frames_before_flush);
+
+ self.finalize_manifest();
+
+ Ok(())
+ }
+
+ pub fn finish_with_timestamp(&mut self, timestamp: Duration) -> Result<(), FinishError> {
+ let segment_start = self.segment_start_time;
+ let frames_before_flush = self.frames_in_segment;
+
+ 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}");
+ }
+
+ self.finalize_pending_tmp_files();
+
+ let effective_end_timestamp = self
+ .last_frame_timestamp
+ .map(|last| last.max(timestamp))
+ .unwrap_or(timestamp);
+
+ self.collect_orphaned_segments(segment_start, effective_end_timestamp, frames_before_flush);
+
+ self.finalize_manifest();
+
+ Ok(())
+ }
+
+ fn finalize_pending_tmp_files(&self) {
+ let Ok(entries) = std::fs::read_dir(&self.base_path) else {
+ return;
+ };
+
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
+ if name.starts_with("segment_") && name.ends_with(".m4s.tmp") {
+ let final_name = name.trim_end_matches(".tmp");
+ let final_path = self.base_path.join(final_name);
+
+ if let Ok(metadata) = std::fs::metadata(&path) {
+ if metadata.len() > 0 {
+ if let Err(e) = std::fs::rename(&path, &final_path) {
+ tracing::warn!(
+ "Failed to rename tmp segment {} to {}: {}",
+ path.display(),
+ final_path.display(),
+ e
+ );
+ } else {
+ tracing::debug!(
+ "Finalized pending segment: {} ({} bytes)",
+ final_path.display(),
+ metadata.len()
+ );
+ sync_file(&final_path);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ fn collect_orphaned_segments(
+ &mut self,
+ segment_start: Option<Duration>,
+ end_timestamp: Duration,
+ frames_before_flush: u32,
+ ) {
+ let completed_indices: std::collections::HashSet<u32> =
+ self.completed_segments.iter().map(|s| s.index).collect();
+
+ let Ok(entries) = std::fs::read_dir(&self.base_path) else {
+ return;
+ };
+
+ let mut orphaned: Vec<(u32, PathBuf)> = Vec::new();
+
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
+ if name.starts_with("segment_") && name.ends_with(".m4s") && !name.contains(".tmp")
+ {
+ if let Some(index_str) = name
+ .strip_prefix("segment_")
+ .and_then(|s| s.strip_suffix(".m4s"))
+ {
+ if let Ok(index) = index_str.parse::<u32>() {
+ if !completed_indices.contains(&index) {
+ orphaned.push((index, path));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ orphaned.sort_by_key(|(idx, _)| *idx);
+
+ for (index, segment_path) in orphaned {
+ if let Ok(metadata) = std::fs::metadata(&segment_path) {
+ let file_size = metadata.len();
+
+ if file_size < 100 {
+ tracing::debug!(
+ "Skipping tiny orphaned segment {} ({} bytes)",
+ segment_path.display(),
+ file_size
+ );
+ continue;
+ }
+
+ sync_file(&segment_path);
+
+ let duration = if index == self.current_index && frames_before_flush > 0 {
+ if let Some(start) = segment_start {
+ end_timestamp.saturating_sub(start)
+ } else {
+ self.segment_duration
+ }
+ } else {
+ self.segment_duration
+ };
+
+ tracing::info!(
+ "Recovered orphaned segment {} with {} bytes, estimated duration {:?}",
+ segment_path.display(),
+ file_size,
+ duration
+ );
+
+ self.completed_segments.push(VideoSegmentInfo {
+ path: segment_path,
+ index,
+ duration,
+ file_size: Some(file_size),
+ });
+ }
+ }
+
+ self.completed_segments.sort_by_key(|s| s.index);
+ }
+
+ fn finalize_manifest(&self) {
+ let total_duration: Duration = self.completed_segments.iter().map(|s| s.duration).sum();
+
+ let manifest = Manifest {
+ version: MANIFEST_VERSION,
+ manifest_type: "m4s_segments",
+ init_segment: Some(INIT_SEGMENT_NAME.to_string()),
+ segments: self
+ .completed_segments
+ .iter()
+ .map(|s| SegmentEntry {
+ 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,
+ file_size: s.file_size,
+ })
+ .collect(),
+ total_duration: Some(total_duration.as_secs_f64()),
+ is_complete: true,
+ };
+
+ 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()
+ );
+ }
+ }
+
+ pub fn completed_segments(&self) -> &[VideoSegmentInfo] {
+ &self.completed_segments
+ }
+
+ pub fn current_encoder(&self) -> Option<&H264Encoder> {
+ Some(&self.encoder)
+ }
+
+ pub fn current_encoder_mut(&mut self) -> Option<&mut H264Encoder> {
+ Some(&mut self.encoder)
+ }
+
+ pub fn base_path(&self) -> &Path {
+ &self.base_path
+ }
+
+ pub fn segment_duration(&self) -> Duration {
+ self.segment_duration
+ }
+
+ pub fn current_index(&self) -> u32 {
+ self.current_index
+ }
+
+ pub fn init_segment_path(&self) -> PathBuf {
+ self.base_path.join(INIT_SEGMENT_NAME)
+ }
+}
diff --git a/crates/enc-ffmpeg/src/remux.rs b/crates/enc-ffmpeg/src/remux.rs
index cf858002e..5c658fff9 100644
--- a/crates/enc-ffmpeg/src/remux.rs
+++ b/crates/enc-ffmpeg/src/remux.rs
@@ -364,3 +364,146 @@ pub fn get_video_fps(path: &Path) -> Option<u32> {
}
Some((rate.numerator() as f64 / rate.denominator() as f64).round() as u32)
}
+
+pub fn probe_m4s_can_decode_with_init(
+ init_path: &Path,
+ segment_path: &Path,
+) -> Result<bool, String> {
+ let temp_path = segment_path.with_extension("probe_temp.mp4");
+
+ let init_data = std::fs::read(init_path)
+ .map_err(|e| format!("Failed to read init segment {}: {e}", init_path.display()))?;
+ let segment_data = std::fs::read(segment_path)
+ .map_err(|e| format!("Failed to read segment {}: {e}", segment_path.display()))?;
+
+ {
+ let mut temp_file = std::fs::File::create(&temp_path)
+ .map_err(|e| format!("Failed to create temp file: {e}"))?;
+ temp_file
+ .write_all(&init_data)
+ .map_err(|e| format!("Failed to write init data: {e}"))?;
+ temp_file
+ .write_all(&segment_data)
+ .map_err(|e| format!("Failed to write segment data: {e}"))?;
+ temp_file
+ .sync_all()
+ .map_err(|e| format!("Failed to sync temp file: {e}"))?;
+ }
+
+ let result = probe_video_can_decode(&temp_path);
+
+ let _ = std::fs::remove_file(&temp_path);
+
+ result
+}
+
+pub fn concatenate_m4s_segments_with_init(
+ init_path: &Path,
+ segments: &[PathBuf],
+ output: &Path,
+) -> Result<(), RemuxError> {
+ if segments.is_empty() {
+ return Err(RemuxError::NoFragments);
+ }
+
+ if !init_path.exists() {
+ return Err(RemuxError::FragmentNotFound(init_path.to_path_buf()));
+ }
+
+ for segment in segments {
+ if !segment.exists() {
+ return Err(RemuxError::FragmentNotFound(segment.clone()));
+ }
+ }
+
+ let combined_path = output.with_extension("combined_fmp4.mp4");
+
+ {
+ let init_data = std::fs::read(init_path)?;
+ let mut combined_file = std::fs::File::create(&combined_path)?;
+ combined_file.write_all(&init_data)?;
+
+ for segment in segments {
+ let segment_data = std::fs::read(segment)?;
+ combined_file.write_all(&segment_data)?;
+ }
+ combined_file.sync_all()?;
+ }
+
+ let result = remux_to_regular_mp4(&combined_path, output);
+
+ let _ = std::fs::remove_file(&combined_path);
+
+ result
+}
+
+fn remux_to_regular_mp4(input_path: &Path, output_path: &Path) -> Result<(), RemuxError> {
+ let mut ictx = avformat::input(input_path)?;
+ let mut octx = avformat::output(output_path)?;
+
+ let mut stream_mapping: Vec<Option<usize>> = Vec::new();
+ let mut output_stream_index = 0usize;
+
+ for input_stream in ictx.streams() {
+ let codec_params = input_stream.parameters();
+ let medium = codec_params.medium();
+
+ if medium == ffmpeg::media::Type::Video || medium == ffmpeg::media::Type::Audio {
+ stream_mapping.push(Some(output_stream_index));
+ output_stream_index += 1;
+
+ let mut output_stream = octx.add_stream(None)?;
+ output_stream.set_parameters(codec_params);
+ unsafe {
+ (*output_stream.as_mut_ptr()).time_base = (*input_stream.as_ptr()).time_base;
+ }
+ } else {
+ stream_mapping.push(None);
+ }
+ }
+
+ octx.write_header()?;
+
+ let mut last_dts: Vec<i64> = vec![i64::MIN; output_stream_index];
+ let mut dts_offset: Vec<i64> = vec![0; output_stream_index];
+
+ for (input_stream, packet) in ictx.packets() {
+ let input_stream_index = input_stream.index();
+
+ if let Some(Some(output_index)) = stream_mapping.get(input_stream_index) {
+ let output_index = *output_index;
+ let mut packet = packet;
+ let input_time_base = input_stream.time_base();
+ let output_time_base = octx.stream(output_index).unwrap().time_base();
+
+ packet.rescale_ts(input_time_base, output_time_base);
+
+ let current_dts = packet.dts().unwrap_or(0);
+
+ if last_dts[output_index] != i64::MIN && current_dts <= last_dts[output_index] {
+ dts_offset[output_index] = last_dts[output_index] - current_dts + 1;
+ }
+
+ let adjusted_dts = current_dts + dts_offset[output_index];
+ let adjusted_pts = packet.pts().map(|pts| pts + dts_offset[output_index]);
+
+ unsafe {
+ (*packet.as_mut_ptr()).dts = adjusted_dts;
+ if let Some(pts) = adjusted_pts {
+ (*packet.as_mut_ptr()).pts = pts;
+ }
+ }
+
+ last_dts[output_index] = adjusted_dts;
+
+ packet.set_stream(output_index);
+ packet.set_position(-1);
+
+ packet.write_interleaved(&mut octx)?;
+ }
+ }
+
+ octx.write_trailer()?;
+
+ Ok(())
+}
diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs
index fa440c6f9..d8e76718c 100644
--- a/crates/enc-ffmpeg/src/video/h264.rs
+++ b/crates/enc-ffmpeg/src/video/h264.rs
@@ -120,7 +120,23 @@ impl H264EncoderBuilder {
self.external_conversion,
) {
Ok(encoder) => {
- debug!("Using encoder {}", codec_name);
+ let is_hardware = matches!(
+ codec_name.as_str(),
+ "h264_videotoolbox" | "h264_nvenc" | "h264_qsv" | "h264_amf" | "h264_mf"
+ );
+ if is_hardware {
+ debug!(
+ encoder = %codec_name,
+ "Selected hardware H264 encoder"
+ );
+ } else {
+ error!(
+ encoder = %codec_name,
+ input_width = input_config.width,
+ input_height = input_config.height,
+ "WARNING: Using SOFTWARE H264 encoder (high CPU usage expected)"
+ );
+ }
return Ok(encoder);
}
Err(err) => {
@@ -156,16 +172,18 @@ impl H264EncoderBuilder {
input_config.pixel_format
} else {
needs_pixel_conversion = true;
- let format = ffmpeg::format::Pixel::NV12;
- if !external_conversion {
- debug!(
- "Converting from {:?} to {:?} for H264 encoding",
- input_config.pixel_format, format
- );
- }
- format
+ ffmpeg::format::Pixel::NV12
};
+ debug!(
+ encoder = %codec.name(),
+ input_format = ?input_config.pixel_format,
+ output_format = ?output_format,
+ needs_pixel_conversion = needs_pixel_conversion,
+ external_conversion = external_conversion,
+ "Encoder pixel format configuration"
+ );
+
if is_420(output_format)
&& (!output_width.is_multiple_of(2) || !output_height.is_multiple_of(2))
{
@@ -187,8 +205,10 @@ impl H264EncoderBuilder {
let converter = if external_conversion {
debug!(
- "External conversion enabled, skipping internal converter. Expected input: {:?} {}x{}",
- output_format, output_width, output_height
+ output_format = ?output_format,
+ output_width = output_width,
+ output_height = output_height,
+ "External conversion enabled, skipping internal converter"
);
None
} else if needs_pixel_conversion || needs_scaling {
@@ -207,7 +227,18 @@ impl H264EncoderBuilder {
output_height,
flags,
) {
- Ok(context) => Some(context),
+ Ok(context) => {
+ debug!(
+ encoder = %codec.name(),
+ src_format = ?input_config.pixel_format,
+ src_size = %format!("{}x{}", input_config.width, input_config.height),
+ dst_format = ?output_format,
+ dst_size = %format!("{}x{}", output_width, output_height),
+ needs_scaling = needs_scaling,
+ "Created SOFTWARE scaler for pixel format conversion (CPU-intensive)"
+ );
+ Some(context)
+ }
Err(e) => {
if needs_pixel_conversion {
error!(
@@ -223,6 +254,10 @@ impl H264EncoderBuilder {
}
}
} else {
+ debug!(
+ encoder = %codec.name(),
+ "No pixel format conversion needed (zero-copy path)"
+ );
None
};
@@ -351,6 +386,36 @@ impl H264Encoder {
Ok(())
}
+ pub fn queue_frame_reusable(
+ &mut self,
+ frame: &mut frame::Video,
+ converted_frame: &mut Option<frame::Video>,
+ timestamp: Duration,
+ output: &mut format::context::Output,
+ ) -> Result<(), QueueFrameError> {
+ self.base.update_pts(frame, timestamp, &mut self.encoder);
+
+ let frame_to_send = if let Some(converter) = &mut self.converter {
+ let pts = frame.pts();
+ let converted = converted_frame.get_or_insert_with(|| {
+ frame::Video::new(self.output_format, self.output_width, self.output_height)
+ });
+ converter
+ .run(frame, converted)
+ .map_err(QueueFrameError::Converter)?;
+ converted.set_pts(pts);
+ converted as &frame::Video
+ } else {
+ frame as &frame::Video
+ };
+
+ self.base
+ .send_frame(frame_to_send, output, &mut self.encoder)
+ .map_err(QueueFrameError::Encode)?;
+
+ Ok(())
+ }
+
pub fn queue_preconverted_frame(
&mut self,
mut frame: frame::Video,