Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(recording): add out-of-process fragmented-m4s muxer adapter

Richie McIlroy96bfb72ab486
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index d8d00cc84..f3808bfec 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -28,6 +28,7 @@ cap-camera-ffmpeg = { path = "../camera-ffmpeg" }
cap-enc-ffmpeg = { path = "../enc-ffmpeg" }
cap-frame-converter = { path = "../frame-converter" }
cap-timestamp = { path = "../timestamp" }
+cap-muxer-protocol = { path = "../cap-muxer-protocol" }
scap-ffmpeg = { path = "../scap-ffmpeg" }
specta = { workspace = true }
@@ -58,6 +59,7 @@ inquire = "0.7.5"
replace_with = "0.1.8"
retry = "2.1.0"
sysinfo = "0.35"
+parking_lot = "0.12"
dhat = { version = "0.3", optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs
index a9a662ed5..9d312be13 100644
--- a/crates/recording/src/lib.rs
+++ b/crates/recording/src/lib.rs
@@ -21,6 +21,7 @@ pub use resolution_limits::{H264_MAX_DIMENSION, calculate_gpu_compatible_size};
pub mod test_sources;
pub use feeds::{camera::CameraFeed, microphone::MicrophoneFeed};
+pub use output_pipeline::oop_muxer;
pub use output_pipeline::*;
pub use sources::screen_capture;
diff --git a/crates/recording/src/output_pipeline/macos_frame_convert.rs b/crates/recording/src/output_pipeline/macos_frame_convert.rs
new file mode 100644
index 000000000..c349a1ece
--- /dev/null
+++ b/crates/recording/src/output_pipeline/macos_frame_convert.rs
@@ -0,0 +1,170 @@
+use cidre::cv::{self, pixel_buffer::LockFlags};
+
+pub(crate) fn copy_plane_data(
+ src: &[u8],
+ dest: &mut [u8],
+ height: usize,
+ row_width: usize,
+ src_stride: usize,
+ dest_stride: usize,
+) {
+ if src_stride == row_width && dest_stride == row_width {
+ let total_bytes = height * row_width;
+ dest[..total_bytes].copy_from_slice(&src[..total_bytes]);
+ } else if src_stride == dest_stride {
+ let total_bytes = height * src_stride;
+ dest[..total_bytes].copy_from_slice(&src[..total_bytes]);
+ } else {
+ for y in 0..height {
+ let src_row = &src[y * src_stride..y * src_stride + row_width];
+ let dest_row = &mut dest[y * dest_stride..y * dest_stride + row_width];
+ dest_row.copy_from_slice(src_row);
+ }
+ }
+}
+
+pub(crate) struct FramePool {
+ frame: Option<ffmpeg::frame::Video>,
+ pixel_format: ffmpeg::format::Pixel,
+ width: u32,
+ height: u32,
+}
+
+impl FramePool {
+ pub(crate) fn new(pixel_format: ffmpeg::format::Pixel, width: u32, height: u32) -> Self {
+ Self {
+ frame: Some(ffmpeg::frame::Video::new(pixel_format, width, height)),
+ pixel_format,
+ width,
+ height,
+ }
+ }
+
+ pub(crate) fn get_frame(&mut self) -> &mut ffmpeg::frame::Video {
+ if self.frame.is_none() {
+ self.frame = Some(ffmpeg::frame::Video::new(
+ self.pixel_format,
+ self.width,
+ self.height,
+ ));
+ }
+ self.frame.as_mut().expect("frame initialized above")
+ }
+
+ pub(crate) fn take_frame(&mut self) -> ffmpeg::frame::Video {
+ self.frame.take().unwrap_or_else(|| {
+ ffmpeg::frame::Video::new(self.pixel_format, self.width, self.height)
+ })
+ }
+}
+
+#[derive(Debug)]
+#[allow(dead_code)]
+pub(crate) enum SampleBufConversionError {
+ UnsupportedFormat(cv::PixelFormat),
+ BaseAddrLock(cidre::os::Error),
+ NoImageBuffer,
+}
+
+struct BaseAddrLockGuard<'a>(&'a mut cv::ImageBuf, LockFlags);
+
+impl<'a> BaseAddrLockGuard<'a> {
+ fn lock(image_buf: &'a mut cv::ImageBuf, flags: LockFlags) -> cidre::os::Result<Self> {
+ unsafe { image_buf.lock_base_addr(flags) }.result()?;
+ Ok(Self(image_buf, flags))
+ }
+
+ fn plane_data(&self, index: usize) -> &[u8] {
+ let base_addr = self.0.plane_base_address(index);
+ let plane_size = self.0.plane_bytes_per_row(index);
+ unsafe { std::slice::from_raw_parts(base_addr, plane_size * self.0.plane_height(index)) }
+ }
+}
+
+impl Drop for BaseAddrLockGuard<'_> {
+ fn drop(&mut self) {
+ unsafe { self.0.unlock_lock_base_addr(self.1) };
+ }
+}
+
+pub(crate) fn fill_frame_from_sample_buf(
+ sample_buf: &cidre::cm::SampleBuf,
+ frame: &mut ffmpeg::frame::Video,
+) -> Result<(), SampleBufConversionError> {
+ let Some(image_buf_ref) = sample_buf.image_buf() else {
+ return Err(SampleBufConversionError::NoImageBuffer);
+ };
+ let mut image_buf = image_buf_ref.retained();
+
+ let width = image_buf.width();
+ let height = image_buf.height();
+ let pixel_format = image_buf.pixel_format();
+ let plane0_stride = image_buf.plane_bytes_per_row(0);
+ let plane1_stride = image_buf.plane_bytes_per_row(1);
+
+ let bytes_lock = BaseAddrLockGuard::lock(image_buf.as_mut(), LockFlags::READ_ONLY)
+ .map_err(SampleBufConversionError::BaseAddrLock)?;
+
+ match pixel_format {
+ cv::PixelFormat::_420V => {
+ let dest_stride0 = frame.stride(0);
+ let dest_stride1 = frame.stride(1);
+
+ copy_plane_data(
+ bytes_lock.plane_data(0),
+ frame.data_mut(0),
+ height,
+ width,
+ plane0_stride,
+ dest_stride0,
+ );
+
+ copy_plane_data(
+ bytes_lock.plane_data(1),
+ frame.data_mut(1),
+ height / 2,
+ width,
+ plane1_stride,
+ dest_stride1,
+ );
+ }
+ cv::PixelFormat::_32_BGRA => {
+ let row_width = width * 4;
+ let dest_stride = frame.stride(0);
+ copy_plane_data(
+ bytes_lock.plane_data(0),
+ frame.data_mut(0),
+ height,
+ row_width,
+ plane0_stride,
+ dest_stride,
+ );
+ }
+ cv::PixelFormat::_2VUY => {
+ let row_width = width * 2;
+ let dest_stride = frame.stride(0);
+ copy_plane_data(
+ bytes_lock.plane_data(0),
+ frame.data_mut(0),
+ height,
+ row_width,
+ plane0_stride,
+ dest_stride,
+ );
+ }
+ format => return Err(SampleBufConversionError::UnsupportedFormat(format)),
+ }
+
+ Ok(())
+}
+
+pub(crate) fn ffmpeg_pixel_format_for_cap(
+ cap_pixel: cap_media_info::Pixel,
+) -> ffmpeg::format::Pixel {
+ match cap_pixel {
+ cap_media_info::Pixel::NV12 => ffmpeg::format::Pixel::NV12,
+ cap_media_info::Pixel::BGRA => ffmpeg::format::Pixel::BGRA,
+ cap_media_info::Pixel::UYVY422 => ffmpeg::format::Pixel::UYVY422,
+ _ => ffmpeg::format::Pixel::NV12,
+ }
+}
diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rs
index 43d2ed5c2..dcf9924bc 100644
--- a/crates/recording/src/output_pipeline/mod.rs
+++ b/crates/recording/src/output_pipeline/mod.rs
@@ -3,12 +3,19 @@ mod core;
pub mod ffmpeg;
#[cfg(target_os = "macos")]
mod macos_fragmented_m4s;
+#[cfg(target_os = "macos")]
+mod macos_frame_convert;
+#[cfg(target_os = "macos")]
+mod oop_fragmented_m4s;
+pub mod oop_muxer;
pub use async_camera::*;
pub use core::*;
pub use ffmpeg::*;
#[cfg(target_os = "macos")]
pub use macos_fragmented_m4s::*;
+#[cfg(target_os = "macos")]
+pub use oop_fragmented_m4s::*;
#[cfg(target_os = "macos")]
mod macos;
@@ -34,3 +41,8 @@ pub use win_segmented_camera::*;
mod win_fragmented_m4s;
#[cfg(windows)]
pub use win_fragmented_m4s::*;
+
+#[cfg(windows)]
+mod oop_fragmented_m4s_win;
+#[cfg(windows)]
+pub use oop_fragmented_m4s_win::*;
diff --git a/crates/recording/src/output_pipeline/oop_fragmented_m4s.rs b/crates/recording/src/output_pipeline/oop_fragmented_m4s.rs
new file mode 100644
index 000000000..79a6dd9dc
--- /dev/null
+++ b/crates/recording/src/output_pipeline/oop_fragmented_m4s.rs
@@ -0,0 +1,689 @@
+use super::core::{
+ BlockingThreadFinish, DiskSpaceMonitor, HealthSender, PipelineHealthEvent, SharedHealthSender,
+ wait_for_blocking_thread_finish,
+};
+use super::macos_frame_convert::{
+ FramePool, ffmpeg_pixel_format_for_cap, fill_frame_from_sample_buf,
+};
+use super::oop_muxer::{
+ MuxerSubprocessConfig, MuxerSubprocessError, RespawningMuxerSubprocess, VideoStreamInit,
+ resolve_muxer_binary,
+};
+use crate::{
+ AudioFrame, AudioMuxer, Muxer, SharedPauseState, TaskPool, VideoMuxer, screen_capture,
+};
+use anyhow::{Context, anyhow};
+use cap_enc_ffmpeg::fragment_manifest::FragmentManifestTracker;
+use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset};
+use cap_enc_ffmpeg::h264_packet::EncodePacketError;
+use cap_enc_ffmpeg::segmented_stream::{DiskSpaceCallback, SegmentCompletedEvent};
+use cap_media_info::{AudioInfo, VideoInfo};
+use std::{
+ path::PathBuf,
+ sync::{Arc, atomic::AtomicBool},
+ thread::JoinHandle,
+ time::Duration,
+};
+use tracing::*;
+
+fn get_muxer_buffer_size() -> usize {
+ std::env::var("CAP_MUXER_BUFFER_SIZE")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(60)
+}
+
+const DEFAULT_MAX_RESPAWNS: u32 = 3;
+
+struct FrameDropTracker {
+ drops_in_window: u32,
+ frames_in_window: u32,
+ total_drops: u64,
+ total_frames: u64,
+ last_check: std::time::Instant,
+ health_tx: SharedHealthSender,
+ source: &'static str,
+}
+
+impl FrameDropTracker {
+ fn new(health_tx: SharedHealthSender, source: &'static str) -> Self {
+ Self {
+ drops_in_window: 0,
+ frames_in_window: 0,
+ total_drops: 0,
+ total_frames: 0,
+ last_check: std::time::Instant::now(),
+ health_tx,
+ source,
+ }
+ }
+
+ fn record_frame(&mut self) {
+ self.frames_in_window += 1;
+ self.total_frames += 1;
+ self.check_drop_rate();
+ }
+
+ fn record_drop(&mut self) {
+ self.drops_in_window += 1;
+ self.total_drops += 1;
+ self.check_drop_rate();
+ }
+
+ fn check_drop_rate(&mut self) {
+ if self.last_check.elapsed() >= Duration::from_secs(5) {
+ let total_in_window = self.frames_in_window + self.drops_in_window;
+ if total_in_window > 0 {
+ let drop_rate = 100.0 * self.drops_in_window as f64 / total_in_window as f64;
+ if drop_rate > 5.0 {
+ warn!(
+ frames = self.frames_in_window,
+ drops = self.drops_in_window,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ total_frames = self.total_frames,
+ total_drops = self.total_drops,
+ "OOP M4S muxer frame drop rate exceeds 5% threshold"
+ );
+ self.health_tx.emit(PipelineHealthEvent::FrameDropRateHigh {
+ source: self.source.to_string(),
+ rate_pct: drop_rate,
+ });
+ } else if self.drops_in_window > 0 {
+ debug!(
+ frames = self.frames_in_window,
+ drops = self.drops_in_window,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ "OOP M4S muxer frame stats"
+ );
+ }
+ }
+ self.drops_in_window = 0;
+ self.frames_in_window = 0;
+ self.last_check = std::time::Instant::now();
+ }
+ }
+}
+
+type VideoFrameItem = Option<(cidre::arc::R<cidre::cm::SampleBuf>, Duration)>;
+
+struct EncoderState {
+ video_tx: std::sync::mpsc::SyncSender<VideoFrameItem>,
+ encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,
+}
+
+pub struct OutOfProcessFragmentedM4SMuxerConfig {
+ pub segment_duration: Duration,
+ pub preset: H264Preset,
+ pub bpp: f32,
+ pub output_size: Option<(u32, u32)>,
+ pub shared_pause_state: Option<SharedPauseState>,
+ pub disk_space_callback: Option<DiskSpaceCallback>,
+ pub segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
+ pub max_respawns: u32,
+}
+
+impl Default for OutOfProcessFragmentedM4SMuxerConfig {
+ fn default() -> Self {
+ Self {
+ segment_duration: Duration::from_secs(2),
+ preset: H264Preset::Ultrafast,
+ bpp: H264EncoderBuilder::QUALITY_BPP,
+ output_size: None,
+ shared_pause_state: None,
+ disk_space_callback: None,
+ segment_tx: None,
+ max_respawns: DEFAULT_MAX_RESPAWNS,
+ }
+ }
+}
+
+pub struct OutOfProcessFragmentedM4SMuxer {
+ base_path: PathBuf,
+ video_config: VideoInfo,
+ segment_duration: Duration,
+ preset: H264Preset,
+ bpp: f32,
+ output_size: Option<(u32, u32)>,
+ state: Option<EncoderState>,
+ pause: SharedPauseState,
+ frame_drops: FrameDropTracker,
+ started: bool,
+ disk_space_callback: Option<DiskSpaceCallback>,
+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
+ health_tx: SharedHealthSender,
+ max_respawns: u32,
+}
+
+impl Muxer for OutOfProcessFragmentedM4SMuxer {
+ type Config = OutOfProcessFragmentedM4SMuxerConfig;
+
+ async fn setup(
+ config: Self::Config,
+ output_path: PathBuf,
+ video_config: Option<VideoInfo>,
+ _audio_config: Option<AudioInfo>,
+ pause_flag: Arc<AtomicBool>,
+ _tasks: &mut TaskPool,
+ ) -> anyhow::Result<Self>
+ where
+ Self: Sized,
+ {
+ let video_config = video_config
+ .ok_or_else(|| anyhow!("invariant: video config expected for OOP muxer"))?;
+
+ std::fs::create_dir_all(&output_path)
+ .with_context(|| format!("Failed to create OOP segments directory: {output_path:?}"))?;
+
+ let pause = config
+ .shared_pause_state
+ .unwrap_or_else(|| SharedPauseState::new(pause_flag));
+
+ Ok(Self {
+ base_path: output_path,
+ video_config,
+ segment_duration: config.segment_duration,
+ preset: config.preset,
+ bpp: config.bpp,
+ output_size: config.output_size,
+ state: None,
+ pause,
+ frame_drops: FrameDropTracker::new(SharedHealthSender::new(), "muxer:macos-oop"),
+ started: false,
+ disk_space_callback: config.disk_space_callback,
+ segment_tx: config.segment_tx,
+ health_tx: SharedHealthSender::new(),
+ max_respawns: config.max_respawns,
+ })
+ }
+
+ fn stop(&mut self) {
+ if let Some(state) = &self.state {
+ if state.video_tx.try_send(None).is_ok() {
+ return;
+ }
+ for _ in 0..5 {
+ std::thread::sleep(Duration::from_millis(50));
+ match state.video_tx.try_send(None) {
+ Ok(()) => return,
+ Err(std::sync::mpsc::TrySendError::Disconnected(_)) => {
+ trace!("OOP M4S encoder channel closed during stop retry");
+ return;
+ }
+ Err(std::sync::mpsc::TrySendError::Full(_)) => {}
+ }
+ }
+ warn!(
+ "OOP M4S encoder channel still full after retries, finish() will deliver sentinel"
+ );
+ }
+ }
+
+ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
+ if let Some(state) = self.state.take()
+ && let Err(error) = finish_oop_encoder(state, timestamp)
+ {
+ return Ok(Err(error));
+ }
+ Ok(Ok(()))
+ }
+
+ fn set_health_sender(&mut self, tx: HealthSender) {
+ self.health_tx.set(tx);
+ self.frame_drops.health_tx = self.health_tx.clone();
+ }
+}
+
+fn finish_oop_encoder(mut state: EncoderState, _timestamp: Duration) -> anyhow::Result<()> {
+ if let Err(error) = state.video_tx.send(None) {
+ trace!("OOP encoder channel already closed during finish: {error}");
+ }
+
+ let thread_result = state
+ .encoder_handle
+ .take()
+ .map(|handle| {
+ wait_for_blocking_thread_finish(handle, Duration::from_secs(10), "OOP encoder")
+ })
+ .unwrap_or(BlockingThreadFinish::Clean);
+
+ match thread_result {
+ BlockingThreadFinish::Clean => Ok(()),
+ BlockingThreadFinish::Failed(error) => Err(error),
+ BlockingThreadFinish::TimedOut(error) => Err(error),
+ }
+}
+
+impl OutOfProcessFragmentedM4SMuxer {
+ fn start_encoder(&mut self) -> anyhow::Result<()> {
+ let buffer_size = get_muxer_buffer_size();
+ debug!(
+ buffer_size = buffer_size,
+ "OOP M4S muxer encoder channel buffer size"
+ );
+
+ let bin_path =
+ resolve_muxer_binary().with_context(|| "cap-muxer binary not found for OOP muxer")?;
+
+ let (video_tx, video_rx) = std::sync::mpsc::sync_channel::<VideoFrameItem>(buffer_size);
+ let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel::<anyhow::Result<()>>(1);
+
+ let base_path = self.base_path.clone();
+ let video_config = self.video_config;
+ let segment_duration = self.segment_duration;
+ let preset = self.preset;
+ let bpp = self.bpp;
+ let output_size = self.output_size;
+ let disk_space_callback = self.disk_space_callback.clone();
+ let segment_tx = self.segment_tx.clone();
+ let health_tx = self.health_tx.clone();
+ let max_respawns = self.max_respawns;
+
+ let encoder_handle = std::thread::Builder::new()
+ .name("oop-m4s-segment-encoder".to_string())
+ .spawn(move || {
+ let mut last_timestamp: Option<Duration> = None;
+ let mut builder = H264EncoderBuilder::new(video_config)
+ .with_preset(preset)
+ .with_bpp(bpp);
+
+ if let Some((width, height)) = output_size {
+ match builder.with_output_size(width, height) {
+ Ok(b) => builder = b,
+ Err(e) => {
+ let err = anyhow!("Invalid output size: {e:?}");
+ let _ = ready_tx.send(Err(anyhow!("{err:#}")));
+ return Err(err);
+ }
+ }
+ }
+
+ let rebuild_builder = builder.clone();
+ let encoder = match builder.build_standalone() {
+ Ok(e) => e,
+ Err(e) => {
+ let err = anyhow!("Failed to open standalone H264 encoder: {e:?}");
+ let _ = ready_tx.send(Err(anyhow!("{err:#}")));
+ return Err(err);
+ }
+ };
+
+ let codec_name = encoder.codec_name().to_string();
+ let extradata = encoder.extradata();
+
+ debug!(
+ codec = %codec_name,
+ extradata_bytes = extradata.len(),
+ "OOP standalone H264 encoder opened"
+ );
+
+ let video_init = VideoStreamInit {
+ codec: wire_codec_for(&codec_name),
+ width: encoder.output_width(),
+ height: encoder.output_height(),
+ frame_rate: (
+ encoder.frame_rate().numerator(),
+ encoder.frame_rate().denominator(),
+ ),
+ time_base: (
+ encoder.time_base().numerator(),
+ encoder.time_base().denominator(),
+ ),
+ extradata: extradata.clone(),
+ segment_duration_ms: segment_duration.as_millis().min(u32::MAX as u128) as u32,
+ };
+
+ let mut tracker = FragmentManifestTracker::new(
+ base_path.clone(),
+ &video_config,
+ segment_duration,
+ );
+ if let Some(tx) = segment_tx.clone() {
+ tracker.set_segment_callback(tx);
+ }
+ tracker.write_initial_manifest();
+
+ let config = MuxerSubprocessConfig {
+ output_directory: base_path.clone(),
+ init_segment_name: FragmentManifestTracker::init_segment_name().to_string(),
+ media_segment_pattern: FragmentManifestTracker::media_segment_pattern()
+ .to_string(),
+ video_init: Some(video_init),
+ audio_init: None,
+ };
+
+ let subprocess = match RespawningMuxerSubprocess::new(
+ bin_path,
+ config,
+ health_tx.get(),
+ max_respawns,
+ ) {
+ Ok(s) => s,
+ Err(e) => {
+ let err = anyhow!("Failed to spawn cap-muxer subprocess: {e:#}");
+ let _ = ready_tx.send(Err(anyhow!("{err:#}")));
+ return Err(err);
+ }
+ };
+
+ let mut disk_monitor = DiskSpaceMonitor::new();
+ let _ = disk_space_callback;
+ disk_monitor.poll(&base_path, &health_tx);
+
+ if ready_tx.send(Ok(())).is_err() {
+ let err = anyhow!("OOP encoder ready signal receiver dropped");
+ return Err(err);
+ }
+
+ let pixel_format = ffmpeg_pixel_format_for_cap(video_config.pixel_format);
+ let mut frame_pool =
+ FramePool::new(pixel_format, video_config.width, video_config.height);
+
+ let mut encoder = encoder;
+ let mut subprocess = subprocess;
+
+ let mut slow_convert_count = 0u32;
+ let mut slow_encode_count = 0u32;
+ let mut total_frames = 0u64;
+ let mut subprocess_fatal = false;
+ let mut disk_exhausted = false;
+ let mut keyframe_emitted = false;
+ let mut encoder_rebuild_attempts: u32 = 0;
+ const MAX_ENCODER_REBUILD_ATTEMPTS: u32 = 1;
+ const SLOW_THRESHOLD_MS: u128 = 5;
+
+ while let Ok(Some((sample_buf, timestamp))) = video_rx.recv() {
+ last_timestamp = Some(timestamp);
+
+ match disk_monitor.poll(&base_path, &health_tx) {
+ super::core::DiskSpacePollResult::Exhausted { .. } => {
+ disk_exhausted = true;
+ }
+ super::core::DiskSpacePollResult::Stopped => {
+ disk_exhausted = true;
+ }
+ _ => {}
+ }
+
+ if disk_exhausted {
+ continue;
+ }
+
+ if subprocess_fatal || subprocess.is_exhausted() {
+ continue;
+ }
+
+ let convert_start = std::time::Instant::now();
+ let frame = frame_pool.get_frame();
+ let fill_result = fill_frame_from_sample_buf(&sample_buf, frame);
+ let convert_elapsed_ms = convert_start.elapsed().as_millis();
+
+ if convert_elapsed_ms > SLOW_THRESHOLD_MS {
+ slow_convert_count += 1;
+ if slow_convert_count <= 5 || slow_convert_count.is_multiple_of(100) {
+ debug!(
+ elapsed_ms = convert_elapsed_ms,
+ count = slow_convert_count,
+ "OOP fill_frame_from_sample_buf exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+
+ match fill_result {
+ Ok(()) => {
+ let owned_frame = frame_pool.take_frame();
+ let encode_start = std::time::Instant::now();
+ let subprocess_ref = &mut subprocess;
+ let keyframe_emitted_ref = &mut keyframe_emitted;
+ let encode_result = encoder.encode_frame(
+ owned_frame,
+ timestamp,
+ |pkt| {
+ if pkt.is_keyframe {
+ *keyframe_emitted_ref = true;
+ }
+ dispatch_packet(subprocess_ref, pkt)
+ },
+ );
+ let encode_elapsed_ms = encode_start.elapsed().as_millis();
+ if encode_elapsed_ms > SLOW_THRESHOLD_MS {
+ slow_encode_count += 1;
+ if slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) {
+ debug!(
+ elapsed_ms = encode_elapsed_ms,
+ count = slow_encode_count,
+ "OOP encode_frame exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+
+ match encode_result {
+ Ok(()) => {
+ tracker.on_frame(timestamp);
+ }
+ Err(EncodePacketError::Converter(e)) => {
+ warn!("OOP encoder converter failure: {e}");
+ }
+ Err(EncodePacketError::Encode(e)) => {
+ if subprocess.is_exhausted() {
+ error!(
+ respawn_attempts = subprocess.respawn_attempts(),
+ max_consecutive_fast_failures =
+ subprocess.max_consecutive_fast_failures(),
+ "OOP subprocess respawn budget exhausted; draining further frames to disk-only fragments"
+ );
+ subprocess_fatal = true;
+ } else if keyframe_emitted
+ && encoder_rebuild_attempts
+ < MAX_ENCODER_REBUILD_ATTEMPTS
+ {
+ encoder_rebuild_attempts += 1;
+ warn!(
+ attempt = encoder_rebuild_attempts,
+ error = ?e,
+ "OOP encoder mid-stream error; attempting same-codec rebuild"
+ );
+ let _ = encoder.flush(|pkt| {
+ if pkt.is_keyframe {
+ keyframe_emitted = true;
+ }
+ dispatch_packet(&mut subprocess, pkt)
+ });
+ match rebuild_builder.clone().build_standalone() {
+ Ok(new_enc) => {
+ let old_name = encoder.codec_name().to_string();
+ let new_name = new_enc.codec_name().to_string();
+ info!(
+ old_codec = %old_name,
+ new_codec = %new_name,
+ attempt = encoder_rebuild_attempts,
+ "OOP encoder rebuilt mid-stream"
+ );
+ encoder = new_enc;
+ health_tx.emit(
+ super::core::PipelineHealthEvent::EncoderRebuilt {
+ backend: new_name,
+ attempt: encoder_rebuild_attempts,
+ },
+ );
+ }
+ Err(rebuild_err) => {
+ error!(
+ error = ?rebuild_err,
+ "OOP encoder rebuild failed"
+ );
+ }
+ }
+ } else {
+ warn!(
+ "OOP encoder transient ffmpeg error (subprocess still active)"
+ );
+ }
+ }
+ }
+ }
+ Err(e) => {
+ warn!("OOP failed to convert frame: {e:?}");
+ }
+ }
+
+ total_frames += 1;
+ }
+
+ let final_ts = last_timestamp.unwrap_or(Duration::ZERO);
+
+ if !subprocess_fatal && !subprocess.is_exhausted() {
+ let subprocess_ref_flush = &mut subprocess;
+ let flush_result =
+ encoder.flush(|pkt| dispatch_packet(subprocess_ref_flush, pkt));
+ if let Err(e) = flush_result {
+ warn!("OOP encoder flush error: {e:?}");
+ }
+ }
+
+ let subprocess_report = match subprocess.finish() {
+ Ok(report) => Some(report),
+ Err(e) => {
+ warn!("OOP subprocess finish error: {e:#}");
+ None
+ }
+ };
+
+ tracker.flush_pending_segments();
+ tracker.finalize(final_ts);
+
+ if total_frames > 0 {
+ debug!(
+ total_frames = total_frames,
+ slow_converts = slow_convert_count,
+ slow_encodes = slow_encode_count,
+ slow_convert_pct = format!(
+ "{:.1}%",
+ 100.0 * slow_convert_count as f64 / total_frames as f64
+ ),
+ slow_encode_pct = format!(
+ "{:.1}%",
+ 100.0 * slow_encode_count as f64 / total_frames as f64
+ ),
+ subprocess_packets = subprocess_report
+ .as_ref()
+ .map(|r| r.packets_written)
+ .unwrap_or(0),
+ "OOP M4S encoder timing summary"
+ );
+ }
+
+ Ok(())
+ })?;
+
+ ready_rx
+ .recv()
+ .map_err(|_| anyhow!("OOP M4S encoder thread ended unexpectedly"))??;
+
+ self.state = Some(EncoderState {
+ video_tx,
+ encoder_handle: Some(encoder_handle),
+ });
+ self.started = true;
+
+ info!(
+ path = %self.base_path.display(),
+ "Started OOP M4S fragmented video encoder subprocess"
+ );
+
+ Ok(())
+ }
+}
+
+fn wire_codec_for(codec: &str) -> String {
+ match codec {
+ "h264_videotoolbox" | "h264_nvenc" | "h264_qsv" | "h264_amf" | "h264_mf" | "libx264" => {
+ "libx264".to_string()
+ }
+ other => other.to_string(),
+ }
+}
+
+fn dispatch_packet(
+ subprocess: &mut RespawningMuxerSubprocess,
+ pkt: cap_enc_ffmpeg::h264_packet::EncodedPacket,
+) -> Result<(), EncodePacketError> {
+ match subprocess.write_video_packet(
+ pkt.pts,
+ pkt.dts,
+ pkt.duration.max(0) as u64,
+ pkt.is_keyframe,
+ &pkt.data,
+ ) {
+ Ok(()) => Ok(()),
+ Err(MuxerSubprocessError::Crashed(reason)) => {
+ warn!(reason, "OOP subprocess crash reported to encoder loop");
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ Err(MuxerSubprocessError::RespawnExhausted { .. }) => {
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ Err(MuxerSubprocessError::DiskFull(reason)) => {
+ warn!(reason, "OOP subprocess exited with disk full");
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ Err(other) => {
+ warn!(error = ?other, "OOP subprocess transient error");
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ }
+}
+
+impl VideoMuxer for OutOfProcessFragmentedM4SMuxer {
+ type VideoFrame = screen_capture::VideoFrame;
+
+ fn send_video_frame(
+ &mut self,
+ frame: Self::VideoFrame,
+ timestamp: Duration,
+ ) -> anyhow::Result<()> {
+ let Some(adjusted_timestamp) = self.pause.adjust(timestamp)? else {
+ return Ok(());
+ };
+
+ if !self.started {
+ self.start_encoder()?;
+ }
+
+ if let Some(state) = &self.state {
+ match state
+ .video_tx
+ .try_send(Some((frame.sample_buf, adjusted_timestamp)))
+ {
+ Ok(()) => {
+ self.frame_drops.record_frame();
+ }
+ Err(e) => match e {
+ std::sync::mpsc::TrySendError::Full(_) => {
+ self.frame_drops.record_drop();
+ }
+ std::sync::mpsc::TrySendError::Disconnected(_) => {
+ return Err(anyhow!("OOP M4S encoder channel disconnected"));
+ }
+ },
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl AudioMuxer for OutOfProcessFragmentedM4SMuxer {
+ fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
diff --git a/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs b/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
new file mode 100644
index 000000000..94630e206
--- /dev/null
+++ b/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
@@ -0,0 +1,718 @@
+use super::core::{
+ BlockingThreadFinish, DiskSpaceMonitor, HealthSender, SharedHealthSender,
+ wait_for_blocking_thread_finish,
+};
+use super::oop_muxer::{
+ MuxerSubprocessConfig, MuxerSubprocessError, RespawningMuxerSubprocess, VideoStreamInit,
+ resolve_muxer_binary,
+};
+use crate::{
+ AudioFrame, AudioMuxer, Muxer, SharedPauseState, TaskPool, VideoMuxer, screen_capture,
+};
+use anyhow::{Context, anyhow};
+use cap_enc_ffmpeg::fragment_manifest::FragmentManifestTracker;
+use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset};
+use cap_enc_ffmpeg::h264_packet::EncodePacketError;
+use cap_enc_ffmpeg::segmented_stream::{DiskSpaceCallback, SegmentCompletedEvent};
+use cap_media_info::{AudioInfo, VideoInfo};
+use std::{
+ path::PathBuf,
+ sync::{
+ Arc,
+ atomic::AtomicBool,
+ mpsc::{RecvTimeoutError, SyncSender, sync_channel},
+ },
+ thread::JoinHandle,
+ time::Duration,
+};
+use tracing::*;
+
+const DEFAULT_MAX_RESPAWNS: u32 = 3;
+const DEFAULT_MUXER_BUFFER_SIZE: usize = 240;
+
+fn get_muxer_buffer_size() -> usize {
+ std::env::var("CAP_MUXER_BUFFER_SIZE")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(DEFAULT_MUXER_BUFFER_SIZE)
+}
+
+struct FrameDropTracker {
+ drops_in_window: u32,
+ frames_in_window: u32,
+ total_drops: u64,
+ total_frames: u64,
+ last_check: std::time::Instant,
+ health_tx: SharedHealthSender,
+ source: &'static str,
+}
+
+impl FrameDropTracker {
+ fn new(health_tx: SharedHealthSender, source: &'static str) -> Self {
+ Self {
+ drops_in_window: 0,
+ frames_in_window: 0,
+ total_drops: 0,
+ total_frames: 0,
+ last_check: std::time::Instant::now(),
+ health_tx,
+ source,
+ }
+ }
+
+ fn record_frame(&mut self) {
+ self.frames_in_window += 1;
+ self.total_frames += 1;
+ self.check_drop_rate();
+ }
+
+ #[allow(dead_code)]
+ fn record_drop(&mut self) {
+ self.drops_in_window += 1;
+ self.total_drops += 1;
+ self.check_drop_rate();
+ }
+
+ fn check_drop_rate(&mut self) {
+ if self.last_check.elapsed() >= Duration::from_secs(5) {
+ let total_in_window = self.frames_in_window + self.drops_in_window;
+ if total_in_window > 0 {
+ let drop_rate = 100.0 * self.drops_in_window as f64 / total_in_window as f64;
+ if drop_rate > 5.0 {
+ warn!(
+ frames = self.frames_in_window,
+ drops = self.drops_in_window,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ total_frames = self.total_frames,
+ total_drops = self.total_drops,
+ "Windows OOP M4S muxer frame drop rate exceeds 5% threshold"
+ );
+ self.health_tx.emit(PipelineHealthEvent::FrameDropRateHigh {
+ source: self.source.to_string(),
+ rate_pct: drop_rate,
+ });
+ } else if self.drops_in_window > 0 {
+ debug!(
+ frames = self.frames_in_window,
+ drops = self.drops_in_window,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ "Windows OOP M4S muxer frame stats"
+ );
+ }
+ }
+ self.drops_in_window = 0;
+ self.frames_in_window = 0;
+ self.last_check = std::time::Instant::now();
+ }
+ }
+}
+
+type ScreenFrameItem = Option<(screen_capture::ScreenFrame, Duration)>;
+
+struct EncoderState {
+ video_tx: SyncSender<ScreenFrameItem>,
+ encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,
+}
+
+pub struct WindowsOOPFragmentedM4SMuxerConfig {
+ pub segment_duration: Duration,
+ pub preset: H264Preset,
+ pub bpp: f32,
+ pub output_size: Option<(u32, u32)>,
+ pub shared_pause_state: Option<SharedPauseState>,
+ pub disk_space_callback: Option<DiskSpaceCallback>,
+ pub segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
+ pub max_respawns: u32,
+}
+
+impl Default for WindowsOOPFragmentedM4SMuxerConfig {
+ fn default() -> Self {
+ Self {
+ segment_duration: Duration::from_secs(2),
+ preset: H264Preset::Ultrafast,
+ bpp: H264EncoderBuilder::QUALITY_BPP,
+ output_size: None,
+ shared_pause_state: None,
+ disk_space_callback: None,
+ segment_tx: None,
+ max_respawns: DEFAULT_MAX_RESPAWNS,
+ }
+ }
+}
+
+pub struct WindowsOOPFragmentedM4SMuxer {
+ base_path: PathBuf,
+ video_config: VideoInfo,
+ segment_duration: Duration,
+ preset: H264Preset,
+ bpp: f32,
+ output_size: Option<(u32, u32)>,
+ state: Option<EncoderState>,
+ pause: SharedPauseState,
+ frame_drops: FrameDropTracker,
+ disk_space_callback: Option<DiskSpaceCallback>,
+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,
+ health_tx: SharedHealthSender,
+ max_respawns: u32,
+}
+
+impl Muxer for WindowsOOPFragmentedM4SMuxer {
+ type Config = WindowsOOPFragmentedM4SMuxerConfig;
+
+ async fn setup(
+ config: Self::Config,
+ output_path: PathBuf,
+ video_config: Option<VideoInfo>,
+ _audio_config: Option<AudioInfo>,
+ pause_flag: Arc<AtomicBool>,
+ _tasks: &mut TaskPool,
+ ) -> anyhow::Result<Self>
+ where
+ Self: Sized,
+ {
+ let video_config = video_config
+ .ok_or_else(|| anyhow!("invariant: video config expected for OOP muxer"))?;
+
+ std::fs::create_dir_all(&output_path).with_context(|| {
+ format!("Failed to create Windows OOP segments directory: {output_path:?}")
+ })?;
+
+ let pause = config
+ .shared_pause_state
+ .unwrap_or_else(|| SharedPauseState::new(pause_flag));
+
+ let mut muxer = Self {
+ base_path: output_path,
+ video_config,
+ segment_duration: config.segment_duration,
+ preset: config.preset,
+ bpp: config.bpp,
+ output_size: config.output_size,
+ state: None,
+ pause,
+ frame_drops: FrameDropTracker::new(SharedHealthSender::new(), "muxer:windows-oop"),
+ disk_space_callback: config.disk_space_callback,
+ segment_tx: config.segment_tx,
+ health_tx: SharedHealthSender::new(),
+ max_respawns: config.max_respawns,
+ };
+
+ muxer.start_encoder()?;
+ Ok(muxer)
+ }
+
+ fn stop(&mut self) {
+ if let Some(state) = &self.state
+ && let Err(e) = state.video_tx.send(None)
+ {
+ trace!("Windows OOP M4S encoder channel already closed during stop: {e}");
+ }
+ }
+
+ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
+ if let Some(state) = self.state.take()
+ && let Err(error) = finish_oop_encoder(state, timestamp)
+ {
+ return Ok(Err(error));
+ }
+ Ok(Ok(()))
+ }
+
+ fn set_health_sender(&mut self, tx: HealthSender) {
+ self.health_tx.set(tx);
+ self.frame_drops.health_tx = self.health_tx.clone();
+ }
+}
+
+fn finish_oop_encoder(mut state: EncoderState, _timestamp: Duration) -> anyhow::Result<()> {
+ if let Err(error) = state.video_tx.send(None) {
+ trace!("Windows OOP encoder channel already closed during finish: {error}");
+ }
+
+ let thread_result = state
+ .encoder_handle
+ .take()
+ .map(|handle| {
+ wait_for_blocking_thread_finish(handle, Duration::from_secs(10), "Windows OOP encoder")
+ })
+ .unwrap_or(BlockingThreadFinish::Clean);
+
+ match thread_result {
+ BlockingThreadFinish::Clean => Ok(()),
+ BlockingThreadFinish::Failed(error) => Err(error),
+ BlockingThreadFinish::TimedOut(error) => Err(error),
+ }
+}
+
+impl WindowsOOPFragmentedM4SMuxer {
+ fn start_encoder(&mut self) -> anyhow::Result<()> {
+ let buffer_size = get_muxer_buffer_size();
+ debug!(
+ buffer_size = buffer_size,
+ "Windows OOP M4S muxer encoder channel buffer size"
+ );
+
+ let bin_path = resolve_muxer_binary()
+ .with_context(|| "cap-muxer binary not found for Windows OOP muxer")?;
+
+ let (video_tx, video_rx) = sync_channel::<ScreenFrameItem>(buffer_size);
+ let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);
+
+ let base_path = self.base_path.clone();
+ let video_config = self.video_config;
+ let segment_duration = self.segment_duration;
+ let preset = self.preset;
+ let bpp = self.bpp;
+ let output_size = self.output_size;
+ let disk_space_callback = self.disk_space_callback.clone();
+ let segment_tx = self.segment_tx.clone();
+ let health_tx = self.health_tx.clone();
+ let max_respawns = self.max_respawns;
+
+ let encoder_handle = std::thread::Builder::new()
+ .name("win-oop-m4s-segment-encoder".to_string())
+ .spawn(move || {
+ cap_mediafoundation_utils::thread_init();
+
+ let mut builder = H264EncoderBuilder::new(video_config)
+ .with_preset(preset)
+ .with_bpp(bpp);
+
+ if let Some((width, height)) = output_size {
+ match builder.with_output_size(width, height) {
+ Ok(b) => builder = b,
+ Err(e) => {
+ let err = anyhow!("Invalid output size: {e:?}");
+ let _ = ready_tx.send(Err(anyhow!("{err:#}")));
+ return Err(err);
+ }
+ }
+ }
+
+ let mut encoder = match builder.build_standalone() {
+ Ok(e) => e,
+ Err(e) => {
+ let err = anyhow!("Failed to open standalone H264 encoder: {e:?}");
+ let _ = ready_tx.send(Err(anyhow!("{err:#}")));
+ return Err(err);
+ }
+ };
+
+ let codec_name = encoder.codec_name().to_string();
+ let extradata = encoder.extradata();
+
+ debug!(
+ codec = %codec_name,
+ extradata_bytes = extradata.len(),
+ "Windows OOP standalone H264 encoder opened"
+ );
+
+ let video_init = VideoStreamInit {
+ codec: wire_codec_for(&codec_name),
+ width: encoder.output_width(),
+ height: encoder.output_height(),
+ frame_rate: (
+ encoder.frame_rate().numerator(),
+ encoder.frame_rate().denominator(),
+ ),
+ time_base: (
+ encoder.time_base().numerator(),
+ encoder.time_base().denominator(),
+ ),
+ extradata: extradata.clone(),
+ segment_duration_ms: segment_duration.as_millis().min(u32::MAX as u128) as u32,
+ };
+
+ let mut tracker = FragmentManifestTracker::new(
+ base_path.clone(),
+ &video_config,
+ segment_duration,
+ );
+ if let Some(tx) = segment_tx.clone() {
+ tracker.set_segment_callback(tx);
+ }
+ tracker.write_initial_manifest();
+
+ let config = MuxerSubprocessConfig {
+ output_directory: base_path.clone(),
+ init_segment_name: FragmentManifestTracker::init_segment_name().to_string(),
+ media_segment_pattern: FragmentManifestTracker::media_segment_pattern()
+ .to_string(),
+ video_init: Some(video_init),
+ audio_init: None,
+ };
+
+ let mut subprocess = match RespawningMuxerSubprocess::new(
+ bin_path,
+ config,
+ health_tx.get(),
+ max_respawns,
+ ) {
+ Ok(s) => s,
+ Err(e) => {
+ let err = anyhow!("Failed to spawn cap-muxer subprocess: {e:#}");
+ let _ = ready_tx.send(Err(anyhow!("{err:#}")));
+ return Err(err);
+ }
+ };
+
+ let mut disk_monitor = DiskSpaceMonitor::new();
+ let _ = disk_space_callback;
+ disk_monitor.poll(&base_path, &health_tx);
+
+ if ready_tx.send(Ok(())).is_err() {
+ let err = anyhow!("Windows OOP encoder ready signal receiver dropped");
+ return Err(err);
+ }
+
+ let frame_interval = Duration::from_secs_f64(1.0 / video_config.fps() as f64);
+ let mut last_ffmpeg_frame: Option<ffmpeg::frame::Video> = None;
+ let mut last_timestamp: Option<Duration> = None;
+ let mut first_timestamp: Option<Duration> = None;
+ let mut total_frames = 0u64;
+ let mut duplicated_frames = 0u64;
+ let mut slow_convert_count = 0u32;
+ let mut slow_encode_count = 0u32;
+ const SLOW_THRESHOLD_MS: u128 = 5;
+
+ let normalize_timestamp =
+ |ts: Duration, first: &mut Option<Duration>| -> Duration {
+ if let Some(first_ts) = *first {
+ ts.checked_sub(first_ts).unwrap_or(Duration::ZERO)
+ } else {
+ *first = Some(ts);
+ Duration::ZERO
+ }
+ };
+
+ let mut encode_one =
+ |encoder: &mut cap_enc_ffmpeg::h264_packet::H264PacketEncoder,
+ subprocess: &mut RespawningMuxerSubprocess,
+ tracker: &mut FragmentManifestTracker,
+ ffmpeg_frame: ffmpeg::frame::Video,
+ normalized_ts: Duration,
+ slow_encode_count: &mut u32,
+ total_frames: &mut u64|
+ -> anyhow::Result<()> {
+ let encode_start = std::time::Instant::now();
+ let subprocess_ref = &mut *subprocess;
+ let encode_result = encoder.encode_frame(
+ ffmpeg_frame,
+ normalized_ts,
+ |pkt| dispatch_packet(subprocess_ref, pkt),
+ );
+ let encode_elapsed_ms = encode_start.elapsed().as_millis();
+ if encode_elapsed_ms > SLOW_THRESHOLD_MS {
+ *slow_encode_count += 1;
+ if *slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) {
+ debug!(
+ elapsed_ms = encode_elapsed_ms,
+ count = *slow_encode_count,
+ "Windows OOP encode_frame exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+
+ match encode_result {
+ Ok(()) => {
+ tracker.on_frame(normalized_ts);
+ *total_frames += 1;
+ Ok(())
+ }
+ Err(EncodePacketError::Converter(e)) => {
+ warn!("Windows OOP encoder converter failure: {e}");
+ Ok(())
+ }
+ Err(EncodePacketError::Encode(e)) => {
+ let err_str = format!("{e:?}");
+ if err_str.contains("Crashed")
+ || err_str.contains("RespawnExhausted")
+ {
+ error!(
+ reason = %err_str,
+ "Windows OOP subprocess crash propagated from encoder loop; aborting"
+ );
+ tracker.flush_pending_segments();
+ tracker.finalize(normalized_ts);
+ return Err(anyhow!(
+ "Windows OOP subprocess crashed: {err_str}"
+ ));
+ }
+ warn!("Windows OOP encoder ffmpeg error: {err_str}");
+ Ok(())
+ }
+ }
+ };
+
+ loop {
+ match disk_monitor.poll(&base_path, &health_tx) {
+ super::core::DiskSpacePollResult::Exhausted { .. }
+ | super::core::DiskSpacePollResult::Stopped => {
+ tracker.flush_pending_segments();
+ tracker.finalize(
+ last_timestamp
+ .map(|t| normalize_timestamp(t, &mut first_timestamp))
+ .unwrap_or(Duration::ZERO),
+ );
+ break;
+ }
+ _ => {}
+ }
+
+ let convert_start = std::time::Instant::now();
+
+ let (ffmpeg_frame, timestamp) = match video_rx.recv_timeout(frame_interval) {
+ Ok(Some((frame, ts))) => match frame.as_ffmpeg() {
+ Ok(f) => {
+ last_ffmpeg_frame = Some(f.clone());
+ last_timestamp = Some(ts);
+ (Some(f), ts)
+ }
+ Err(e) => {
+ warn!("Windows OOP failed to convert D3D11 frame: {e:?}");
+ match (&last_ffmpeg_frame, last_timestamp) {
+ (Some(f), Some(last_ts)) => {
+ let new_ts = last_ts.saturating_add(frame_interval);
+ last_timestamp = Some(new_ts);
+ duplicated_frames += 1;
+ (Some(f.clone()), new_ts)
+ }
+ _ => (None, Duration::ZERO),
+ }
+ }
+ },
+ Ok(None) | Err(RecvTimeoutError::Disconnected) => {
+ let drain_start = std::time::Instant::now();
+ let drain_timeout = Duration::from_millis(500);
+ loop {
+ match video_rx.recv_timeout(Duration::from_millis(10)) {
+ Ok(Some((frame, ts))) => {
+ if let Ok(f) = frame.as_ffmpeg() {
+ let normalized_ts = normalize_timestamp(
+ ts,
+ &mut first_timestamp,
+ );
+ if let Err(e) = encode_one(
+ &mut encoder,
+ &mut subprocess,
+ &mut tracker,
+ f,
+ normalized_ts,
+ &mut slow_encode_count,
+ &mut total_frames,
+ ) {
+ warn!("Failed to encode drained frame: {e}");
+ break;
+ }
+ }
+ }
+ Ok(None) => break,
+ Err(RecvTimeoutError::Timeout) => {
+ if drain_start.elapsed() > drain_timeout {
+ break;
+ }
+ }
+ Err(RecvTimeoutError::Disconnected) => break,
+ }
+ }
+ break;
+ }
+ Err(RecvTimeoutError::Timeout) => {
+ match (&last_ffmpeg_frame, last_timestamp) {
+ (Some(f), Some(last_ts)) => {
+ let new_ts = last_ts.saturating_add(frame_interval);
+ last_timestamp = Some(new_ts);
+ duplicated_frames += 1;
+ (Some(f.clone()), new_ts)
+ }
+ _ => continue,
+ }
+ }
+ };
+
+ let convert_elapsed_ms = convert_start.elapsed().as_millis();
+ if convert_elapsed_ms > SLOW_THRESHOLD_MS {
+ slow_convert_count += 1;
+ if slow_convert_count <= 5 || slow_convert_count.is_multiple_of(100) {
+ debug!(
+ elapsed_ms = convert_elapsed_ms,
+ count = slow_convert_count,
+ "Windows OOP D3D11 frame conversion exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+
+ let Some(ffmpeg_frame) = ffmpeg_frame else {
+ match video_rx.recv() {
+ Ok(Some((frame, ts))) => {
+ if let Ok(f) = frame.as_ffmpeg() {
+ last_ffmpeg_frame = Some(f);
+ last_timestamp = Some(ts);
+ }
+ }
+ Ok(None) | Err(_) => break,
+ }
+ continue;
+ };
+
+ let normalized_ts = normalize_timestamp(timestamp, &mut first_timestamp);
+ if let Err(e) = encode_one(
+ &mut encoder,
+ &mut subprocess,
+ &mut tracker,
+ ffmpeg_frame,
+ normalized_ts,
+ &mut slow_encode_count,
+ &mut total_frames,
+ ) {
+ return Err(e);
+ }
+ }
+
+ let final_ts = last_timestamp
+ .map(|t| normalize_timestamp(t, &mut first_timestamp))
+ .unwrap_or(Duration::ZERO);
+
+ let subprocess_ref_flush = &mut subprocess;
+ if let Err(e) = encoder.flush(|pkt| dispatch_packet(subprocess_ref_flush, pkt)) {
+ warn!("Windows OOP encoder flush error: {e:?}");
+ }
+
+ let subprocess_report = match subprocess.finish() {
+ Ok(report) => Some(report),
+ Err(e) => {
+ warn!("Windows OOP subprocess finish error: {e:#}");
+ None
+ }
+ };
+
+ tracker.flush_pending_segments();
+ tracker.finalize(final_ts);
+
+ if total_frames > 0 {
+ debug!(
+ total_frames = total_frames,
+ duplicated_frames = duplicated_frames,
+ slow_converts = slow_convert_count,
+ slow_encodes = slow_encode_count,
+ slow_convert_pct = format!(
+ "{:.1}%",
+ 100.0 * slow_convert_count as f64 / total_frames as f64
+ ),
+ slow_encode_pct = format!(
+ "{:.1}%",
+ 100.0 * slow_encode_count as f64 / total_frames as f64
+ ),
+ subprocess_packets = subprocess_report
+ .as_ref()
+ .map(|r| r.packets_written)
+ .unwrap_or(0),
+ "Windows OOP M4S encoder timing summary"
+ );
+ }
+
+ Ok(())
+ })?;
+
+ ready_rx
+ .recv()
+ .map_err(|_| anyhow!("Windows OOP M4S encoder thread ended unexpectedly"))??;
+
+ self.state = Some(EncoderState {
+ video_tx,
+ encoder_handle: Some(encoder_handle),
+ });
+
+ info!(
+ path = %self.base_path.display(),
+ "Started Windows OOP M4S fragmented video encoder subprocess"
+ );
+ Ok(())
+ }
+}
+
+fn wire_codec_for(codec: &str) -> String {
+ match codec {
+ "h264_videotoolbox" | "h264_nvenc" | "h264_qsv" | "h264_amf" | "h264_mf" | "libx264" => {
+ "libx264".to_string()
+ }
+ other => other.to_string(),
+ }
+}
+
+fn dispatch_packet(
+ subprocess: &mut RespawningMuxerSubprocess,
+ pkt: cap_enc_ffmpeg::h264_packet::EncodedPacket,
+) -> Result<(), EncodePacketError> {
+ match subprocess.write_video_packet(
+ pkt.pts,
+ pkt.dts,
+ pkt.duration.max(0) as u64,
+ pkt.is_keyframe,
+ &pkt.data,
+ ) {
+ Ok(()) => Ok(()),
+ Err(MuxerSubprocessError::Crashed(reason)) => {
+ warn!(
+ reason,
+ "Windows OOP subprocess crash reported to encoder loop"
+ );
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ Err(MuxerSubprocessError::RespawnExhausted { attempts }) => {
+ error!(attempts, "Windows OOP subprocess respawn budget exhausted");
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ Err(MuxerSubprocessError::DiskFull(reason)) => {
+ warn!(reason, "Windows OOP subprocess exited with disk full");
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ Err(other) => {
+ warn!(error = ?other, "Windows OOP subprocess transient error");
+ Err(EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ }))
+ }
+ }
+}
+
+impl VideoMuxer for WindowsOOPFragmentedM4SMuxer {
+ type VideoFrame = screen_capture::VideoFrame;
+
+ fn send_video_frame(
+ &mut self,
+ frame: Self::VideoFrame,
+ timestamp: Duration,
+ ) -> anyhow::Result<()> {
+ let Some(adjusted_timestamp) = self.pause.adjust(timestamp)? else {
+ return Ok(());
+ };
+
+ if let Some(state) = &self.state {
+ match state.video_tx.send(Some((frame.frame, adjusted_timestamp))) {
+ Ok(()) => {
+ self.frame_drops.record_frame();
+ }
+ Err(_) => {
+ return Err(anyhow!("Windows OOP M4S encoder channel disconnected"));
+ }
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl AudioMuxer for WindowsOOPFragmentedM4SMuxer {
+ fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
diff --git a/crates/recording/src/output_pipeline/oop_muxer.rs b/crates/recording/src/output_pipeline/oop_muxer.rs
new file mode 100644
index 000000000..919a531f4
--- /dev/null
+++ b/crates/recording/src/output_pipeline/oop_muxer.rs
@@ -0,0 +1,744 @@
+use crate::output_pipeline::core::{HealthSender, PipelineHealthEvent, emit_health};
+use anyhow::{Context, Result, anyhow};
+use cap_muxer_protocol::{
+ Frame, InitAudio, InitVideo, PACKET_FLAG_KEYFRAME, Packet, STREAM_INDEX_AUDIO,
+ STREAM_INDEX_VIDEO, StartParams, write_frame,
+};
+use std::{
+ io::{BufWriter, Write},
+ path::{Path, PathBuf},
+ process::{Child, ChildStderr, ChildStdin, Command, ExitStatus, Stdio},
+ sync::{
+ Arc,
+ atomic::{AtomicBool, AtomicU64, Ordering},
+ },
+ thread::JoinHandle,
+ time::{Duration, Instant},
+};
+use tracing::{debug, error, info, warn};
+
+pub const ENV_BIN_PATH: &str = "CAP_MUXER_BIN";
+const STDERR_RING_LIMIT: usize = 128;
+const RESPAWN_COOLDOWN: Duration = Duration::from_millis(500);
+const RESPAWN_STABILITY_WINDOW: Duration = Duration::from_secs(5);
+pub const EXIT_DISK_FULL: u8 = 60;
+
+pub fn resolve_muxer_binary() -> Result<PathBuf> {
+ if let Ok(override_path) = std::env::var(ENV_BIN_PATH) {
+ let path = PathBuf::from(override_path);
+ if path.exists() {
+ return Ok(path);
+ }
+ return Err(anyhow!(
+ "{ENV_BIN_PATH} points to missing path: {}",
+ path.display()
+ ));
+ }
+
+ let exe = std::env::current_exe().context("current_exe")?;
+ if let Some(dir) = exe.parent() {
+ let candidate = dir.join(bin_name());
+ if candidate.exists() {
+ return Ok(candidate);
+ }
+
+ let alt_dir = dir.join("..").join("MacOS");
+ let candidate = alt_dir.join(bin_name());
+ if candidate.exists() {
+ return Ok(candidate);
+ }
+ }
+
+ if let Ok(cwd) = std::env::current_dir() {
+ let target_debug = cwd.join("target/debug").join(bin_name());
+ if target_debug.exists() {
+ return Ok(target_debug);
+ }
+ let target_release = cwd.join("target/release").join(bin_name());
+ if target_release.exists() {
+ return Ok(target_release);
+ }
+ }
+
+ Err(anyhow!(
+ "cap-muxer binary not found; set {ENV_BIN_PATH} or place it next to the main executable"
+ ))
+}
+
+fn bin_name() -> &'static str {
+ if cfg!(windows) {
+ "cap-muxer.exe"
+ } else {
+ "cap-muxer"
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct VideoStreamInit {
+ pub codec: String,
+ pub width: u32,
+ pub height: u32,
+ pub frame_rate: (i32, i32),
+ pub time_base: (i32, i32),
+ pub extradata: Vec<u8>,
+ pub segment_duration_ms: u32,
+}
+
+#[derive(Debug, Clone)]
+pub struct AudioStreamInit {
+ pub codec: String,
+ pub sample_rate: u32,
+ pub channels: u16,
+ pub sample_format: String,
+ pub time_base: (i32, i32),
+ pub extradata: Vec<u8>,
+}
+
+#[derive(Debug, Clone)]
+pub struct MuxerSubprocessConfig {
+ pub output_directory: PathBuf,
+ pub init_segment_name: String,
+ pub media_segment_pattern: String,
+ pub video_init: Option<VideoStreamInit>,
+ pub audio_init: Option<AudioStreamInit>,
+}
+
+impl MuxerSubprocessConfig {
+ pub fn with_video(mut self, video: VideoStreamInit) -> Self {
+ self.video_init = Some(video);
+ self
+ }
+
+ pub fn with_audio(mut self, audio: AudioStreamInit) -> Self {
+ self.audio_init = Some(audio);
+ self
+ }
+}
+
+pub struct MuxerSubprocess {
+ child: Option<Child>,
+ stdin: Option<BufWriter<ChildStdin>>,
+ stderr_thread: Option<JoinHandle<Vec<String>>>,
+ stderr_lines: Arc<parking_lot::Mutex<Vec<String>>>,
+ bin_path: PathBuf,
+ config: MuxerSubprocessConfig,
+ health_tx: Option<HealthSender>,
+ packets_written: Arc<AtomicU64>,
+ started_at: Instant,
+ crash_reported: Arc<AtomicBool>,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum MuxerSubprocessError {
+ #[error("spawn: {0:#}")]
+ Spawn(anyhow::Error),
+ #[error("subprocess exited during init: {0}")]
+ ExitDuringInit(String),
+ #[error("write: {0:#}")]
+ Write(anyhow::Error),
+ #[error("subprocess crashed: {0}")]
+ Crashed(String),
+ #[error("respawn exhausted after {attempts} attempts")]
+ RespawnExhausted { attempts: u32 },
+ #[error("disk full: {0}")]
+ DiskFull(String),
+}
+
+impl MuxerSubprocess {
+ pub fn spawn(
+ bin_path: PathBuf,
+ config: MuxerSubprocessConfig,
+ health_tx: Option<HealthSender>,
+ ) -> Result<Self, MuxerSubprocessError> {
+ let mut child = Command::new(&bin_path)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .env(
+ "CAP_MUXER_LOG",
+ std::env::var("CAP_MUXER_LOG").unwrap_or_else(|_| "info".to_string()),
+ )
+ .spawn()
+ .map_err(|e| {
+ MuxerSubprocessError::Spawn(anyhow!("failed to spawn {}: {e}", bin_path.display()))
+ })?;
+
+ let stdin = child
+ .stdin
+ .take()
+ .ok_or_else(|| MuxerSubprocessError::Spawn(anyhow!("subprocess stdin missing")))?;
+ let stderr = child
+ .stderr
+ .take()
+ .ok_or_else(|| MuxerSubprocessError::Spawn(anyhow!("subprocess stderr missing")))?;
+
+ let stderr_lines = Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
+ let stderr_thread = Some(spawn_stderr_reader(stderr, stderr_lines.clone()));
+
+ let mut subprocess = Self {
+ child: Some(child),
+ stdin: Some(BufWriter::with_capacity(1024 * 1024, stdin)),
+ stderr_thread,
+ stderr_lines,
+ bin_path,
+ config: config.clone(),
+ health_tx,
+ packets_written: Arc::new(AtomicU64::new(0)),
+ started_at: Instant::now(),
+ crash_reported: Arc::new(AtomicBool::new(false)),
+ };
+
+ subprocess.send_init_frames()?;
+
+ info!(
+ bin_path = %subprocess.bin_path.display(),
+ output_dir = %config.output_directory.display(),
+ "cap-muxer subprocess spawned"
+ );
+
+ Ok(subprocess)
+ }
+
+ fn send_init_frames(&mut self) -> Result<(), MuxerSubprocessError> {
+ let stdin = self
+ .stdin
+ .as_mut()
+ .ok_or_else(|| MuxerSubprocessError::Write(anyhow!("stdin closed")))?;
+
+ if let Some(video) = &self.config.video_init {
+ let frame = Frame::InitVideo(InitVideo {
+ codec: video.codec.clone(),
+ width: video.width,
+ height: video.height,
+ frame_rate_num: video.frame_rate.0,
+ frame_rate_den: video.frame_rate.1,
+ time_base_num: video.time_base.0,
+ time_base_den: video.time_base.1,
+ extradata: video.extradata.clone(),
+ segment_duration_ms: video.segment_duration_ms,
+ });
+ write_frame(stdin, &frame)
+ .map_err(|e| MuxerSubprocessError::Write(anyhow!("init_video: {e}")))?;
+ }
+
+ if let Some(audio) = &self.config.audio_init {
+ let frame = Frame::InitAudio(InitAudio {
+ codec: audio.codec.clone(),
+ sample_rate: audio.sample_rate,
+ channels: audio.channels,
+ sample_format: audio.sample_format.clone(),
+ time_base_num: audio.time_base.0,
+ time_base_den: audio.time_base.1,
+ extradata: audio.extradata.clone(),
+ });
+ write_frame(stdin, &frame)
+ .map_err(|e| MuxerSubprocessError::Write(anyhow!("init_audio: {e}")))?;
+ }
+
+ let start = Frame::Start(StartParams {
+ output_directory: self.config.output_directory.to_string_lossy().to_string(),
+ init_segment_name: self.config.init_segment_name.clone(),
+ media_segment_pattern: self.config.media_segment_pattern.clone(),
+ });
+ write_frame(stdin, &start)
+ .map_err(|e| MuxerSubprocessError::Write(anyhow!("start: {e}")))?;
+
+ stdin
+ .flush()
+ .map_err(|e| MuxerSubprocessError::Write(anyhow!("flush after start: {e}")))?;
+
+ std::thread::sleep(Duration::from_millis(100));
+ if let Some(child) = self.child.as_mut()
+ && let Ok(Some(status)) = child.try_wait()
+ {
+ let reason = self.drain_stderr_reason(status);
+ return Err(MuxerSubprocessError::ExitDuringInit(reason));
+ }
+
+ Ok(())
+ }
+
+ pub fn write_video_packet(
+ &mut self,
+ pts_time_base_units: i64,
+ dts_time_base_units: i64,
+ duration_time_base_units: u64,
+ is_keyframe: bool,
+ data: &[u8],
+ ) -> Result<(), MuxerSubprocessError> {
+ let mut flags = 0u8;
+ if is_keyframe {
+ flags |= PACKET_FLAG_KEYFRAME;
+ }
+ self.write_packet(
+ STREAM_INDEX_VIDEO,
+ pts_time_base_units,
+ dts_time_base_units,
+ duration_time_base_units,
+ flags,
+ data,
+ )
+ }
+
+ pub fn write_audio_packet(
+ &mut self,
+ pts_time_base_units: i64,
+ dts_time_base_units: i64,
+ duration_time_base_units: u64,
+ data: &[u8],
+ ) -> Result<(), MuxerSubprocessError> {
+ self.write_packet(
+ STREAM_INDEX_AUDIO,
+ pts_time_base_units,
+ dts_time_base_units,
+ duration_time_base_units,
+ 0,
+ data,
+ )
+ }
+
+ fn write_packet(
+ &mut self,
+ stream_index: u8,
+ pts: i64,
+ dts: i64,
+ duration: u64,
+ flags: u8,
+ data: &[u8],
+ ) -> Result<(), MuxerSubprocessError> {
+ let stdin = self
+ .stdin
+ .as_mut()
+ .ok_or_else(|| MuxerSubprocessError::Write(anyhow!("stdin closed")))?;
+
+ let frame = Frame::Packet(Packet {
+ stream_index,
+ pts,
+ dts,
+ duration,
+ flags,
+ data: data.to_vec(),
+ });
+
+ match write_frame(stdin, &frame) {
+ Ok(()) => {
+ self.packets_written.fetch_add(1, Ordering::Relaxed);
+ Ok(())
+ }
+ Err(e) => {
+ let reason = self.on_write_failure(&format!("packet write: {e}"));
+ if self.exit_code_if_exited() == Some(EXIT_DISK_FULL as i32) {
+ Err(MuxerSubprocessError::DiskFull(reason))
+ } else {
+ Err(MuxerSubprocessError::Crashed(reason))
+ }
+ }
+ }
+ }
+
+ fn on_write_failure(&mut self, context: &str) -> String {
+ let stderr_tail = self.snapshot_stderr();
+ let exit_code = self.exit_code_if_exited();
+ let status_str = exit_code
+ .map(|c| format!("exit_code={c}"))
+ .unwrap_or_else(|| self.reap_if_exited());
+ let reason = format!(
+ "{context}; exit={status_str}; stderr_tail={:?}",
+ stderr_tail.last()
+ );
+ if exit_code == Some(EXIT_DISK_FULL as i32) {
+ self.report_disk_full(&reason);
+ } else {
+ self.report_crashed(&reason);
+ }
+ reason
+ }
+
+ fn exit_code_if_exited(&mut self) -> Option<i32> {
+ if let Some(child) = self.child.as_mut()
+ && let Ok(Some(status)) = child.try_wait()
+ {
+ return status.code();
+ }
+ None
+ }
+
+ pub fn disk_full_observed(&mut self) -> bool {
+ self.exit_code_if_exited() == Some(EXIT_DISK_FULL as i32)
+ }
+
+ fn reap_if_exited(&mut self) -> String {
+ match self.child.as_mut() {
+ Some(child) => match child.try_wait() {
+ Ok(Some(status)) => format!("{status:?}"),
+ Ok(None) => "still_alive".to_string(),
+ Err(e) => format!("wait_err({e})"),
+ },
+ None => "already_reaped".to_string(),
+ }
+ }
+
+ fn drain_stderr_reason(&mut self, status: ExitStatus) -> String {
+ let tail = self.snapshot_stderr();
+ let code = status
+ .code()
+ .map(|c| c.to_string())
+ .unwrap_or_else(|| "signal".to_string());
+ format!(
+ "exit_code={code} stderr={:?}",
+ tail.iter().rev().take(3).rev().cloned().collect::<Vec<_>>()
+ )
+ }
+
+ fn snapshot_stderr(&self) -> Vec<String> {
+ self.stderr_lines.lock().clone()
+ }
+
+ fn report_crashed(&self, reason: &str) {
+ if self
+ .crash_reported
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .is_err()
+ {
+ return;
+ }
+ error!(reason, "cap-muxer subprocess crashed");
+ if let Some(tx) = &self.health_tx {
+ emit_health(
+ tx,
+ PipelineHealthEvent::MuxerCrashed {
+ reason: reason.to_string(),
+ },
+ );
+ }
+ }
+
+ fn report_disk_full(&self, reason: &str) {
+ if self
+ .crash_reported
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .is_err()
+ {
+ return;
+ }
+ error!(reason, "cap-muxer subprocess exited with disk full");
+ if let Some(tx) = &self.health_tx {
+ emit_health(
+ tx,
+ PipelineHealthEvent::DiskSpaceExhausted { bytes_remaining: 0 },
+ );
+ }
+ }
+
+ pub fn packets_written(&self) -> u64 {
+ self.packets_written.load(Ordering::Acquire)
+ }
+
+ pub fn uptime(&self) -> Duration {
+ self.started_at.elapsed()
+ }
+
+ #[doc(hidden)]
+ pub fn kill_for_testing(&mut self) -> std::io::Result<()> {
+ if let Some(child) = self.child.as_mut() {
+ child.kill()?;
+ let _ = child.wait();
+ }
+ Ok(())
+ }
+
+ pub fn finish(mut self) -> Result<MuxerSubprocessReport, MuxerSubprocessError> {
+ if let Some(mut stdin) = self.stdin.take() {
+ let _ = write_frame(&mut stdin, &Frame::Finish);
+ let _ = stdin.flush();
+ drop(stdin);
+ }
+
+ let packets = self.packets_written.load(Ordering::Acquire);
+ let mut status = None;
+ if let Some(mut child) = self.child.take() {
+ match child.wait() {
+ Ok(s) => status = Some(s),
+ Err(e) => {
+ warn!("cap-muxer wait failed: {e}");
+ }
+ }
+ }
+
+ let stderr_tail = if let Some(handle) = self.stderr_thread.take() {
+ handle.join().unwrap_or_default()
+ } else {
+ self.snapshot_stderr()
+ };
+
+ let exit_code = status.as_ref().and_then(|s| s.code());
+ let success = matches!(exit_code, Some(0));
+ if !success {
+ let reason = format!(
+ "non-zero exit {:?}: {:?}",
+ exit_code,
+ stderr_tail.iter().rev().take(3).collect::<Vec<_>>()
+ );
+ if exit_code == Some(EXIT_DISK_FULL as i32) {
+ self.report_disk_full(&reason);
+ } else {
+ self.report_crashed(&reason);
+ }
+ return Err(MuxerSubprocessError::Crashed(reason));
+ }
+
+ info!(
+ packets,
+ uptime_secs = self.started_at.elapsed().as_secs_f64(),
+ "cap-muxer subprocess finished cleanly"
+ );
+
+ Ok(MuxerSubprocessReport {
+ packets_written: packets,
+ uptime: self.started_at.elapsed(),
+ stderr_tail,
+ exit_code,
+ })
+ }
+}
+
+impl Drop for MuxerSubprocess {
+ fn drop(&mut self) {
+ if let Some(mut child) = self.child.take()
+ && let Ok(None) = child.try_wait()
+ {
+ warn!("cap-muxer subprocess being dropped while still running; killing");
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct MuxerSubprocessReport {
+ pub packets_written: u64,
+ pub uptime: Duration,
+ pub stderr_tail: Vec<String>,
+ pub exit_code: Option<i32>,
+}
+
+fn spawn_stderr_reader(
+ stderr: ChildStderr,
+ lines: Arc<parking_lot::Mutex<Vec<String>>>,
+) -> JoinHandle<Vec<String>> {
+ std::thread::Builder::new()
+ .name("cap-muxer-stderr".into())
+ .spawn(move || {
+ use std::io::{BufRead, BufReader};
+ let reader = BufReader::new(stderr);
+ let mut final_lines = Vec::new();
+ for line_res in reader.lines() {
+ match line_res {
+ Ok(line) => {
+ debug!(target: "cap_muxer_stderr", "{line}");
+ let mut guard = lines.lock();
+ guard.push(line.clone());
+ if guard.len() > STDERR_RING_LIMIT {
+ guard.remove(0);
+ }
+ drop(guard);
+ final_lines.push(line);
+ if final_lines.len() > STDERR_RING_LIMIT * 4 {
+ final_lines.drain(0..STDERR_RING_LIMIT);
+ }
+ }
+ Err(e) => {
+ debug!(target: "cap_muxer_stderr", "read err: {e}");
+ break;
+ }
+ }
+ }
+ final_lines
+ })
+ .expect("failed to spawn cap-muxer-stderr thread")
+}
+
+pub struct RespawningMuxerSubprocess {
+ current: Option<MuxerSubprocess>,
+ bin_path: PathBuf,
+ config: MuxerSubprocessConfig,
+ health_tx: Option<HealthSender>,
+ respawn_attempts: u32,
+ consecutive_fast_failures: u32,
+ max_consecutive_fast_failures: u32,
+ last_crash_at: Option<Instant>,
+ current_spawned_at: Instant,
+}
+
+impl RespawningMuxerSubprocess {
+ pub fn new(
+ bin_path: PathBuf,
+ config: MuxerSubprocessConfig,
+ health_tx: Option<HealthSender>,
+ max_consecutive_fast_failures: u32,
+ ) -> Result<Self, MuxerSubprocessError> {
+ let current = Some(MuxerSubprocess::spawn(
+ bin_path.clone(),
+ config.clone(),
+ health_tx.clone(),
+ )?);
+ Ok(Self {
+ current,
+ bin_path,
+ config,
+ health_tx,
+ respawn_attempts: 0,
+ consecutive_fast_failures: 0,
+ max_consecutive_fast_failures,
+ last_crash_at: None,
+ current_spawned_at: Instant::now(),
+ })
+ }
+
+ pub fn write_video_packet(
+ &mut self,
+ pts: i64,
+ dts: i64,
+ duration: u64,
+ is_keyframe: bool,
+ data: &[u8],
+ ) -> Result<(), MuxerSubprocessError> {
+ self.run_with_respawn(|child| {
+ child.write_video_packet(pts, dts, duration, is_keyframe, data)
+ })
+ }
+
+ pub fn write_audio_packet(
+ &mut self,
+ pts: i64,
+ dts: i64,
+ duration: u64,
+ data: &[u8],
+ ) -> Result<(), MuxerSubprocessError> {
+ self.run_with_respawn(|child| child.write_audio_packet(pts, dts, duration, data))
+ }
+
+ fn run_with_respawn<F>(&mut self, mut op: F) -> Result<(), MuxerSubprocessError>
+ where
+ F: FnMut(&mut MuxerSubprocess) -> Result<(), MuxerSubprocessError>,
+ {
+ loop {
+ let Some(current) = self.current.as_mut() else {
+ if self.consecutive_fast_failures > self.max_consecutive_fast_failures {
+ return Err(MuxerSubprocessError::RespawnExhausted {
+ attempts: self.respawn_attempts,
+ });
+ }
+ self.spawn_new()?;
+ continue;
+ };
+
+ match op(current) {
+ Ok(()) => return Ok(()),
+ Err(MuxerSubprocessError::DiskFull(reason)) => {
+ self.current = None;
+ return Err(MuxerSubprocessError::DiskFull(reason));
+ }
+ Err(MuxerSubprocessError::Crashed(reason)) => {
+ let uptime = self.current_spawned_at.elapsed();
+ if uptime > RESPAWN_STABILITY_WINDOW {
+ if self.consecutive_fast_failures > 0 {
+ info!(
+ stable_uptime_secs = uptime.as_secs_f64(),
+ previous_fast_failures = self.consecutive_fast_failures,
+ "subprocess proved stable; resetting fast-failure counter"
+ );
+ }
+ self.consecutive_fast_failures = 0;
+ } else {
+ self.consecutive_fast_failures += 1;
+ }
+ warn!(
+ reason,
+ uptime_secs = uptime.as_secs_f64(),
+ consecutive_fast_failures = self.consecutive_fast_failures,
+ max_consecutive_fast_failures = self.max_consecutive_fast_failures,
+ "subprocess write failed; evaluating respawn"
+ );
+ self.current = None;
+ if self.consecutive_fast_failures > self.max_consecutive_fast_failures {
+ return Err(MuxerSubprocessError::RespawnExhausted {
+ attempts: self.respawn_attempts,
+ });
+ }
+ if let Some(last) = self.last_crash_at {
+ let since = last.elapsed();
+ if since < RESPAWN_COOLDOWN {
+ std::thread::sleep(RESPAWN_COOLDOWN.saturating_sub(since));
+ }
+ }
+ self.last_crash_at = Some(Instant::now());
+ }
+ Err(other) => return Err(other),
+ }
+ }
+ }
+
+ fn spawn_new(&mut self) -> Result<(), MuxerSubprocessError> {
+ self.respawn_attempts += 1;
+ let mut respawned_config = self.config.clone();
+ let respawn_dir_name = format!("respawn-{}", self.respawn_attempts);
+ respawned_config.output_directory = self.config.output_directory.join(respawn_dir_name);
+
+ info!(
+ attempt = self.respawn_attempts,
+ output_dir = %respawned_config.output_directory.display(),
+ "respawning cap-muxer subprocess into isolated directory"
+ );
+
+ let new = MuxerSubprocess::spawn(
+ self.bin_path.clone(),
+ respawned_config,
+ self.health_tx.clone(),
+ )?;
+ self.current = Some(new);
+ self.current_spawned_at = Instant::now();
+ Ok(())
+ }
+
+ pub fn finish(mut self) -> Result<MuxerSubprocessReport, MuxerSubprocessError> {
+ if let Some(current) = self.current.take() {
+ current.finish()
+ } else {
+ Err(MuxerSubprocessError::Crashed(
+ "no active subprocess at finish".to_string(),
+ ))
+ }
+ }
+
+ pub fn respawn_attempts(&self) -> u32 {
+ self.respawn_attempts
+ }
+
+ pub fn is_exhausted(&self) -> bool {
+ self.current.is_none()
+ && self.consecutive_fast_failures > self.max_consecutive_fast_failures
+ }
+
+ pub fn max_consecutive_fast_failures(&self) -> u32 {
+ self.max_consecutive_fast_failures
+ }
+
+ #[deprecated(
+ note = "Misleading name — returns max_consecutive_fast_failures, not a total respawn cap. Use max_consecutive_fast_failures() instead."
+ )]
+ pub fn max_respawns(&self) -> u32 {
+ self.max_consecutive_fast_failures
+ }
+}
+
+pub fn feature_enabled() -> bool {
+ std::env::var("CAP_OUT_OF_PROCESS_MUXER")
+ .ok()
+ .filter(|v| v == "1" || v.eq_ignore_ascii_case("true"))
+ .is_some()
+}
+
+pub fn output_path_from_dir(dir: &Path) -> PathBuf {
+ dir.to_path_buf()
+}
diff --git a/crates/recording/tests/oop_muxer.rs b/crates/recording/tests/oop_muxer.rs
new file mode 100644
index 000000000..0c3302df9
--- /dev/null
+++ b/crates/recording/tests/oop_muxer.rs
@@ -0,0 +1,317 @@
+use cap_recording::oop_muxer::{
+ MuxerSubprocess, MuxerSubprocessConfig, RespawningMuxerSubprocess, VideoStreamInit,
+ resolve_muxer_binary,
+};
+use std::path::PathBuf;
+use std::sync::Once;
+use tempfile::TempDir;
+
+const TEST_WIDTH: u32 = 640;
+const TEST_HEIGHT: u32 = 360;
+const TEST_FPS: u32 = 30;
+
+static MUXER_BINARY: Once = Once::new();
+
+fn setup_muxer_binary() -> PathBuf {
+ let workspace = env!("CARGO_MANIFEST_DIR");
+ let target_debug = PathBuf::from(workspace).join("../../target/debug/cap-muxer");
+ let target_release = PathBuf::from(workspace).join("../../target/release/cap-muxer");
+
+ for candidate in [target_debug, target_release] {
+ if candidate.exists() {
+ MUXER_BINARY.call_once(|| unsafe {
+ std::env::set_var(cap_recording::oop_muxer::ENV_BIN_PATH, &candidate);
+ });
+ return candidate;
+ }
+ }
+
+ panic!("cap-muxer binary not found; run `cargo build -p cap-muxer` before the OOP muxer tests");
+}
+
+fn minimal_video_config(output_dir: &std::path::Path, extradata: Vec<u8>) -> MuxerSubprocessConfig {
+ MuxerSubprocessConfig {
+ output_directory: output_dir.to_path_buf(),
+ init_segment_name: "init.mp4".to_string(),
+ media_segment_pattern: "segment_$Number%03d$.m4s".to_string(),
+ video_init: Some(VideoStreamInit {
+ codec: "libx264".to_string(),
+ width: TEST_WIDTH,
+ height: TEST_HEIGHT,
+ frame_rate: (TEST_FPS as i32, 1),
+ time_base: (1, 90_000),
+ extradata,
+ segment_duration_ms: 2000,
+ }),
+ audio_init: None,
+ }
+}
+
+#[test]
+fn subprocess_spawns_and_finishes_cleanly_without_packets() {
+ let bin = setup_muxer_binary();
+ let temp_dir = TempDir::new().unwrap();
+ let output_dir = temp_dir.path().join("video");
+
+ let config = minimal_video_config(&output_dir, Vec::new());
+ let subprocess = MuxerSubprocess::spawn(bin, config, None)
+ .expect("spawn cap-muxer subprocess with no packets");
+
+ let report = subprocess
+ .finish()
+ .expect("subprocess finishes cleanly with no packets");
+ assert_eq!(report.exit_code, Some(0));
+ assert_eq!(report.packets_written, 0);
+}
+
+#[test]
+fn subprocess_survives_kill_and_parent_reports_crashed() {
+ let bin = setup_muxer_binary();
+ let temp_dir = TempDir::new().unwrap();
+ let output_dir = temp_dir.path().join("video");
+
+ let fake_extradata = vec![0x01, 0x64, 0x00, 0x33, 0xFF, 0xE1, 0x00, 0x17];
+ let config = minimal_video_config(&output_dir, fake_extradata);
+
+ use cap_recording::PipelineHealthEvent;
+ let (health_tx, mut health_rx) = tokio::sync::mpsc::channel::<PipelineHealthEvent>(16);
+
+ let mut subprocess =
+ MuxerSubprocess::spawn(bin, config, Some(health_tx)).expect("spawn cap-muxer subprocess");
+
+ subprocess
+ .kill_for_testing()
+ .expect("kill subprocess for testing");
+
+ std::thread::sleep(std::time::Duration::from_millis(100));
+
+ let write_result = subprocess.write_video_packet(0, 0, 0, false, &[0u8; 256]);
+ assert!(
+ write_result.is_err() || {
+ let _ = subprocess.finish();
+ true
+ }
+ );
+
+ let mut saw_crashed = false;
+ for _ in 0..10 {
+ match health_rx.try_recv() {
+ Ok(PipelineHealthEvent::MuxerCrashed { .. }) => {
+ saw_crashed = true;
+ break;
+ }
+ Ok(_) => {}
+ Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
+ std::thread::sleep(std::time::Duration::from_millis(25));
+ }
+ Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => break,
+ }
+ }
+
+ assert!(
+ saw_crashed,
+ "parent should emit PipelineHealthEvent::MuxerCrashed after kill"
+ );
+}
+
+#[test]
+fn resolve_muxer_binary_respects_env_override() {
+ let temp = TempDir::new().unwrap();
+ let fake = temp.path().join("fake-muxer");
+ std::fs::write(&fake, b"").unwrap();
+ unsafe {
+ std::env::set_var(cap_recording::oop_muxer::ENV_BIN_PATH, &fake);
+ }
+ let resolved = resolve_muxer_binary().expect("resolve with override");
+ assert_eq!(resolved, fake);
+ unsafe {
+ std::env::remove_var(cap_recording::oop_muxer::ENV_BIN_PATH);
+ }
+}
+
+#[test]
+fn resolve_muxer_binary_fails_with_invalid_env() {
+ unsafe {
+ std::env::set_var(
+ cap_recording::oop_muxer::ENV_BIN_PATH,
+ "/nonexistent/path/definitely-not-here-12345",
+ );
+ }
+ let err = resolve_muxer_binary().unwrap_err();
+ assert!(err.to_string().contains("missing path"));
+ unsafe {
+ std::env::remove_var(cap_recording::oop_muxer::ENV_BIN_PATH);
+ }
+}
+
+#[test]
+fn respawning_subprocess_reports_clean_exit_when_no_crash() {
+ let bin = setup_muxer_binary();
+ let temp_dir = TempDir::new().unwrap();
+ let output_dir = temp_dir.path().join("video");
+
+ let config = minimal_video_config(&output_dir, Vec::new());
+ let respawn =
+ RespawningMuxerSubprocess::new(bin, config, None, 2).expect("spawn respawn subprocess");
+
+ assert_eq!(respawn.respawn_attempts(), 0);
+
+ let report = respawn.finish().expect("clean finish");
+ assert_eq!(report.exit_code, Some(0));
+}
+
+#[test]
+fn subprocess_survives_finish_after_init_only() {
+ let bin = setup_muxer_binary();
+ let temp_dir = TempDir::new().unwrap();
+ let output_dir = temp_dir.path().join("video");
+
+ let fake_extradata = vec![0x01, 0x64, 0x00, 0x33, 0xFF, 0xE1, 0x00, 0x17];
+ let config = minimal_video_config(&output_dir, fake_extradata.clone());
+
+ let subprocess = MuxerSubprocess::spawn(bin, config, None)
+ .expect("spawn cap-muxer with non-empty extradata");
+ let report = subprocess.finish().expect("finish cleanly");
+ assert_eq!(report.exit_code, Some(0));
+
+ let init_path = output_dir.join("init.mp4");
+ assert!(
+ init_path.exists(),
+ "init.mp4 should be written when extradata is supplied"
+ );
+}
+
+#[test]
+fn encoder_to_subprocess_end_to_end_produces_playable_init_and_segments() {
+ use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset};
+ use cap_enc_ffmpeg::h264_packet::EncodePacketError;
+ use cap_media_info::{Pixel, VideoInfo};
+
+ ffmpeg::init().ok();
+
+ let bin = setup_muxer_binary();
+ let temp_dir = TempDir::new().unwrap();
+ let output_dir = temp_dir.path().join("video");
+ std::fs::create_dir_all(&output_dir).unwrap();
+
+ let video_info = VideoInfo {
+ pixel_format: Pixel::NV12,
+ width: 320,
+ height: 240,
+ time_base: ffmpeg::Rational(1, 1_000_000),
+ frame_rate: ffmpeg::Rational(30, 1),
+ };
+
+ let mut encoder = H264EncoderBuilder::new(video_info)
+ .with_preset(H264Preset::Ultrafast)
+ .build_standalone()
+ .expect("standalone encoder");
+
+ let extradata = encoder.extradata();
+ assert!(
+ !extradata.is_empty(),
+ "expected non-empty extradata from standalone libx264 encoder"
+ );
+
+ let config = MuxerSubprocessConfig {
+ output_directory: output_dir.clone(),
+ init_segment_name: "init.mp4".to_string(),
+ media_segment_pattern: "segment_$Number%03d$.m4s".to_string(),
+ video_init: Some(VideoStreamInit {
+ codec: "libx264".to_string(),
+ width: encoder.output_width(),
+ height: encoder.output_height(),
+ frame_rate: (
+ encoder.frame_rate().numerator(),
+ encoder.frame_rate().denominator(),
+ ),
+ time_base: (
+ encoder.time_base().numerator(),
+ encoder.time_base().denominator(),
+ ),
+ extradata,
+ segment_duration_ms: 500,
+ }),
+ audio_init: None,
+ };
+
+ let mut subprocess =
+ MuxerSubprocess::spawn(bin, config, None).expect("spawn cap-muxer subprocess");
+
+ fn ship_packet(
+ subprocess: &mut MuxerSubprocess,
+ pkt: cap_enc_ffmpeg::h264_packet::EncodedPacket,
+ ) -> Result<(), EncodePacketError> {
+ subprocess
+ .write_video_packet(
+ pkt.pts,
+ pkt.dts,
+ pkt.duration.max(0) as u64,
+ pkt.is_keyframe,
+ &pkt.data,
+ )
+ .map_err(|_| {
+ EncodePacketError::Encode(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::AVERROR_EXTERNAL,
+ })
+ })
+ }
+
+ for i in 0..60u64 {
+ let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, 320, 240);
+ for plane_idx in 0..frame.planes() {
+ let data = frame.data_mut(plane_idx);
+ for (idx, byte) in data.iter_mut().enumerate() {
+ *byte = ((i * 13 + idx as u64 * 7) & 0xFF) as u8;
+ }
+ }
+ let timestamp = std::time::Duration::from_millis(i * 33);
+ let sub_ref = &mut subprocess;
+ encoder
+ .encode_frame(frame, timestamp, |pkt| ship_packet(sub_ref, pkt))
+ .expect("encode_frame succeeds");
+ }
+
+ let sub_ref_flush = &mut subprocess;
+ encoder
+ .flush(|pkt| ship_packet(sub_ref_flush, pkt))
+ .expect("flush succeeds");
+
+ let report = subprocess.finish().expect("subprocess finish cleanly");
+ assert_eq!(report.exit_code, Some(0));
+ assert!(
+ report.packets_written > 0,
+ "expected subprocess to have written at least one packet, got {}",
+ report.packets_written
+ );
+
+ let init_path = output_dir.join("init.mp4");
+ assert!(
+ init_path.exists(),
+ "init.mp4 must exist after end-to-end encode"
+ );
+ let init_meta = std::fs::metadata(&init_path).unwrap();
+ assert!(
+ init_meta.len() > 100,
+ "init.mp4 should be non-trivially sized, got {} bytes",
+ init_meta.len()
+ );
+
+ let mut segment_count = 0u32;
+ for entry in std::fs::read_dir(&output_dir).unwrap().flatten() {
+ let name = entry.file_name();
+ let name_str = name.to_string_lossy();
+ if name_str.starts_with("segment_") && name_str.ends_with(".m4s") {
+ let meta = entry.metadata().unwrap();
+ assert!(
+ meta.len() > 0,
+ "segment file {name_str} should be non-empty"
+ );
+ segment_count += 1;
+ }
+ }
+ assert!(
+ segment_count > 0,
+ "expected at least one segment_*.m4s file, got {segment_count}"
+ );
+}