Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Replace segmented muxers with M4S muxer on macOS

Richie McIlroy84cba3cf7676
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index 1caa3afe8..d5575bc84 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -6,7 +6,7 @@ use crate::{
};
#[cfg(target_os = "macos")]
-use crate::output_pipeline::{MacOSSegmentedMuxer, MacOSSegmentedMuxerConfig};
+use crate::output_pipeline::{MacOSFragmentedM4SMuxer, MacOSFragmentedM4SMuxerConfig};
use anyhow::anyhow;
use cap_timestamp::Timestamps;
use std::{path::PathBuf, sync::Arc};
@@ -86,7 +86,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {
OutputPipeline::builder(fragments_dir)
.with_video::<screen_capture::VideoSource>(screen_capture)
.with_timestamps(start_time)
- .build::<MacOSSegmentedMuxer>(MacOSSegmentedMuxerConfig::default())
+ .build::<MacOSFragmentedM4SMuxer>(MacOSFragmentedM4SMuxerConfig::default())
.await
} else {
OutputPipeline::builder(output_path.clone())
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index a3701dfea..405c97bf5 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -100,9 +100,10 @@ pub fn spawn_cursor_recorder(
let mut last_flush = Instant::now();
let flush_interval = Duration::from_secs(CURSOR_FLUSH_INTERVAL_SECS);
+ let mut last_cursor_id = "default".to_string();
loop {
- let sleep = tokio::time::sleep(Duration::from_millis(10));
+ let sleep = tokio::time::sleep(Duration::from_millis(16));
let Either::Right(_) =
futures::future::select(pin!(stop_token_child.cancelled()), pin!(sleep)).await
else {
@@ -112,68 +113,70 @@ pub fn spawn_cursor_recorder(
let elapsed = start_time.instant().elapsed().as_secs_f64() * 1000.0;
let mouse_state = device_state.get_mouse();
- let cursor_data = get_cursor_data();
- let cursor_id = if let Some(data) = cursor_data {
- let mut hasher = DefaultHasher::default();
- data.image.hash(&mut hasher);
- let id = hasher.finish();
+ let position = cap_cursor_capture::RawCursorPosition::get();
+ let position_changed = position != last_position;
- if let Some(existing_id) = response.cursors.get(&id) {
- existing_id.id.to_string()
- } else {
- let cursor_id = response.next_cursor_id.to_string();
- let file_name = format!("cursor_{cursor_id}.png");
- let cursor_path = cursors_dir.join(&file_name);
-
- if let Ok(image) = image::load_from_memory(&data.image) {
- let rgba_image = image.into_rgba8();
-
- if let Err(e) = rgba_image.save(&cursor_path) {
- error!("Failed to save cursor image: {}", e);
- } else {
- info!("Saved cursor {cursor_id} image to: {:?}", file_name);
- response.cursors.insert(
- id,
- Cursor {
- file_name,
- id: response.next_cursor_id,
- hotspot: data.hotspot,
- shape: data.shape,
- },
- );
- response.next_cursor_id += 1;
+ let cursor_id = if position_changed {
+ last_position = position;
+ if let Some(data) = get_cursor_data() {
+ let mut hasher = DefaultHasher::default();
+ data.image.hash(&mut hasher);
+ let id = hasher.finish();
+
+ let cursor_id = if let Some(existing_id) = response.cursors.get(&id) {
+ existing_id.id.to_string()
+ } else {
+ let cursor_id = response.next_cursor_id.to_string();
+ let file_name = format!("cursor_{cursor_id}.png");
+ let cursor_path = cursors_dir.join(&file_name);
+
+ if let Ok(image) = image::load_from_memory(&data.image) {
+ let rgba_image = image.into_rgba8();
+
+ if let Err(e) = rgba_image.save(&cursor_path) {
+ error!("Failed to save cursor image: {}", e);
+ } else {
+ info!("Saved cursor {cursor_id} image to: {:?}", file_name);
+ response.cursors.insert(
+ id,
+ Cursor {
+ file_name,
+ id: response.next_cursor_id,
+ hotspot: data.hotspot,
+ shape: data.shape,
+ },
+ );
+ response.next_cursor_id += 1;
+ }
}
- }
+ cursor_id
+ };
+ last_cursor_id = cursor_id.clone();
cursor_id
+ } else {
+ last_cursor_id.clone()
}
} else {
- "default".to_string()
+ last_cursor_id.clone()
};
- let position = cap_cursor_capture::RawCursorPosition::get();
-
- let position = (position != last_position).then(|| {
- last_position = position;
-
+ if position_changed {
let cropped_norm_pos = position
- .relative_to_display(display)?
- .normalize()?
- .with_crop(crop_bounds);
-
- Some((cropped_norm_pos.x(), cropped_norm_pos.y()))
- });
-
- if let Some((x, y)) = position.flatten() {
- let mouse_event = CursorMoveEvent {
- active_modifiers: vec![],
- cursor_id: cursor_id.clone(),
- time_ms: elapsed,
- x,
- y,
- };
-
- response.moves.push(mouse_event);
+ .relative_to_display(display)
+ .and_then(|p| p.normalize())
+ .map(|p| p.with_crop(crop_bounds));
+
+ if let Some(pos) = cropped_norm_pos {
+ let mouse_event = CursorMoveEvent {
+ active_modifiers: vec![],
+ cursor_id: cursor_id.clone(),
+ time_ms: elapsed,
+ x: pos.x(),
+ y: pos.y(),
+ };
+ response.moves.push(mouse_event);
+ }
}
for (num, &pressed) in mouse_state.button_pressed.iter().enumerate() {
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 44148ec89..0946b8b1b 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -455,7 +455,6 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
let mut first_tx = Some(first_tx);
let mut frame_count = 0u64;
-
let res = stop_token
.run_until_cancelled(async {
while let Some(frame) = video_rx.next().await {
@@ -487,9 +486,20 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
if was_cancelled {
info!("mux-video cancelled, draining remaining frames from channel");
+ let drain_start = std::time::Instant::now();
+ let drain_timeout = Duration::from_secs(2);
+ let max_drain_frames = 30u64;
let mut drained = 0u64;
+ let mut skipped = 0u64;
+
while let Some(frame) = video_rx.next().await {
frame_count += 1;
+
+ if drain_start.elapsed() > drain_timeout || drained >= max_drain_frames {
+ skipped += 1;
+ continue;
+ }
+
drained += 1;
let timestamp = frame.timestamp();
@@ -506,14 +516,16 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
Ok(()) => {}
Err(e) => {
warn!("Error processing drained frame: {e}");
- break;
+ skipped += 1;
}
}
}
- if drained > 0 {
+ if drained > 0 || skipped > 0 {
info!(
- "mux-video drained {} additional frames after cancellation",
- drained
+ "mux-video drain complete: {} frames processed, {} skipped in {:?}",
+ drained,
+ skipped,
+ drain_start.elapsed()
);
}
}
diff --git a/crates/recording/src/output_pipeline/fragmented.rs b/crates/recording/src/output_pipeline/fragmented.rs
deleted file mode 100644
index a5dd3d933..000000000
--- a/crates/recording/src/output_pipeline/fragmented.rs
+++ /dev/null
@@ -1,294 +0,0 @@
-#[cfg(target_os = "macos")]
-use crate::{
- VideoFrame,
- output_pipeline::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer},
- sources::screen_capture,
-};
-
-#[cfg(target_os = "macos")]
-use anyhow::anyhow;
-#[cfg(target_os = "macos")]
-use cap_enc_avfoundation::SegmentedMP4Encoder;
-#[cfg(target_os = "macos")]
-use cap_media_info::{AudioInfo, VideoInfo};
-#[cfg(target_os = "macos")]
-use cap_timestamp::Timestamp;
-#[cfg(target_os = "macos")]
-use std::{
- path::PathBuf,
- sync::{Arc, atomic::AtomicBool},
- time::Duration,
-};
-
-#[cfg(target_os = "macos")]
-pub struct FragmentedAVFoundationMp4Muxer {
- inner: SegmentedMP4Encoder,
- pause_flag: Arc<AtomicBool>,
-}
-
-#[cfg(target_os = "macos")]
-pub struct FragmentedAVFoundationMp4MuxerConfig {
- pub output_height: Option<u32>,
- pub segment_duration: Duration,
-}
-
-#[cfg(target_os = "macos")]
-impl Default for FragmentedAVFoundationMp4MuxerConfig {
- fn default() -> Self {
- Self {
- output_height: None,
- segment_duration: Duration::from_secs(3),
- }
- }
-}
-
-#[cfg(target_os = "macos")]
-impl FragmentedAVFoundationMp4Muxer {
- const MAX_QUEUE_RETRIES: u32 = 1500;
-}
-
-#[cfg(target_os = "macos")]
-#[derive(Clone)]
-pub struct FragmentedNativeCameraFrame {
- pub sample_buf: cidre::arc::R<cidre::cm::SampleBuf>,
- pub timestamp: Timestamp,
-}
-
-#[cfg(target_os = "macos")]
-unsafe impl Send for FragmentedNativeCameraFrame {}
-#[cfg(target_os = "macos")]
-unsafe impl Sync for FragmentedNativeCameraFrame {}
-
-#[cfg(target_os = "macos")]
-impl VideoFrame for FragmentedNativeCameraFrame {
- fn timestamp(&self) -> Timestamp {
- self.timestamp
- }
-}
-
-#[cfg(target_os = "macos")]
-impl Muxer for FragmentedAVFoundationMp4Muxer {
- type Config = FragmentedAVFoundationMp4MuxerConfig;
-
- 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> {
- let video_config =
- video_config.ok_or_else(|| anyhow!("Invariant: No video source provided"))?;
-
- Ok(Self {
- inner: SegmentedMP4Encoder::init(
- output_path,
- video_config,
- audio_config,
- config.output_height,
- config.segment_duration,
- )
- .map_err(|e| anyhow!("{e}"))?,
- pause_flag,
- })
- }
-
- fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
- Ok(self.inner.finish(Some(timestamp)).map(Ok)?)
- }
-}
-
-#[cfg(target_os = "macos")]
-impl VideoMuxer for FragmentedAVFoundationMp4Muxer {
- type VideoFrame = screen_capture::VideoFrame;
-
- fn send_video_frame(
- &mut self,
- frame: Self::VideoFrame,
- timestamp: Duration,
- ) -> anyhow::Result<()> {
- if self.pause_flag.load(std::sync::atomic::Ordering::Relaxed) {
- self.inner.pause();
- } else {
- self.inner.resume();
- }
-
- let mut retry_count = 0;
- loop {
- match self
- .inner
- .queue_video_frame(frame.sample_buf.clone(), timestamp)
- {
- Ok(()) => break,
- Err(cap_enc_avfoundation::QueueFrameError::NotReadyForMore) => {
- retry_count += 1;
- if retry_count >= Self::MAX_QUEUE_RETRIES {
- return Err(anyhow!(
- "send_video_frame/timeout after {} retries",
- Self::MAX_QUEUE_RETRIES
- ));
- }
- std::thread::sleep(Duration::from_millis(2));
- continue;
- }
- Err(e) => return Err(anyhow!("send_video_frame/{e}")),
- }
- }
-
- Ok(())
- }
-}
-
-#[cfg(target_os = "macos")]
-impl AudioMuxer for FragmentedAVFoundationMp4Muxer {
- fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {
- let mut retry_count = 0;
- loop {
- match self.inner.queue_audio_frame(&frame.inner, timestamp) {
- Ok(()) => break,
- Err(cap_enc_avfoundation::QueueFrameError::NotReadyForMore) => {
- retry_count += 1;
- if retry_count >= Self::MAX_QUEUE_RETRIES {
- return Err(anyhow!(
- "send_audio_frame/retries_exceeded after {} retries",
- Self::MAX_QUEUE_RETRIES
- ));
- }
- std::thread::sleep(Duration::from_millis(2));
- continue;
- }
- Err(e) => return Err(anyhow!("send_audio_frame/{e}")),
- }
- }
-
- Ok(())
- }
-}
-
-#[cfg(target_os = "macos")]
-pub struct FragmentedAVFoundationCameraMuxer {
- inner: SegmentedMP4Encoder,
- pause_flag: Arc<AtomicBool>,
-}
-
-#[cfg(target_os = "macos")]
-pub struct FragmentedAVFoundationCameraMuxerConfig {
- pub output_height: Option<u32>,
- pub segment_duration: Duration,
-}
-
-#[cfg(target_os = "macos")]
-impl Default for FragmentedAVFoundationCameraMuxerConfig {
- fn default() -> Self {
- Self {
- output_height: None,
- segment_duration: Duration::from_secs(3),
- }
- }
-}
-
-#[cfg(target_os = "macos")]
-impl FragmentedAVFoundationCameraMuxer {
- const MAX_QUEUE_RETRIES: u32 = 1500;
-}
-
-#[cfg(target_os = "macos")]
-impl Muxer for FragmentedAVFoundationCameraMuxer {
- type Config = FragmentedAVFoundationCameraMuxerConfig;
-
- 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> {
- let video_config =
- video_config.ok_or_else(|| anyhow!("Invariant: No video source provided"))?;
-
- Ok(Self {
- inner: SegmentedMP4Encoder::init(
- output_path,
- video_config,
- audio_config,
- config.output_height,
- config.segment_duration,
- )
- .map_err(|e| anyhow!("{e}"))?,
- pause_flag,
- })
- }
-
- fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
- Ok(self.inner.finish(Some(timestamp)).map(Ok)?)
- }
-}
-
-#[cfg(target_os = "macos")]
-impl VideoMuxer for FragmentedAVFoundationCameraMuxer {
- type VideoFrame = crate::output_pipeline::NativeCameraFrame;
-
- fn send_video_frame(
- &mut self,
- frame: Self::VideoFrame,
- timestamp: Duration,
- ) -> anyhow::Result<()> {
- if self.pause_flag.load(std::sync::atomic::Ordering::Relaxed) {
- self.inner.pause();
- } else {
- self.inner.resume();
- }
-
- let mut retry_count = 0;
- loop {
- match self
- .inner
- .queue_video_frame(frame.sample_buf.clone(), timestamp)
- {
- Ok(()) => break,
- Err(cap_enc_avfoundation::QueueFrameError::NotReadyForMore) => {
- retry_count += 1;
- if retry_count >= Self::MAX_QUEUE_RETRIES {
- return Err(anyhow!(
- "send_video_frame/timeout after {} retries",
- Self::MAX_QUEUE_RETRIES
- ));
- }
- std::thread::sleep(Duration::from_millis(2));
- continue;
- }
- Err(e) => return Err(anyhow!("send_video_frame/{e}")),
- }
- }
-
- Ok(())
- }
-}
-
-#[cfg(target_os = "macos")]
-impl AudioMuxer for FragmentedAVFoundationCameraMuxer {
- fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {
- let mut retry_count = 0;
- loop {
- match self.inner.queue_audio_frame(&frame.inner, timestamp) {
- Ok(()) => break,
- Err(cap_enc_avfoundation::QueueFrameError::NotReadyForMore) => {
- retry_count += 1;
- if retry_count >= Self::MAX_QUEUE_RETRIES {
- return Err(anyhow!(
- "send_audio_frame/retries_exceeded after {} retries",
- Self::MAX_QUEUE_RETRIES
- ));
- }
- std::thread::sleep(Duration::from_millis(2));
- continue;
- }
- Err(e) => return Err(anyhow!("send_audio_frame/{e}")),
- }
- }
-
- Ok(())
- }
-}
diff --git a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs
new file mode 100644
index 000000000..484171588
--- /dev/null
+++ b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs
@@ -0,0 +1,891 @@
+use crate::{
+ AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, output_pipeline::NativeCameraFrame,
+ screen_capture,
+};
+use anyhow::{Context, anyhow};
+use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset};
+use cap_enc_ffmpeg::segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig};
+use cap_media_info::{AudioInfo, VideoInfo};
+use std::{
+ path::PathBuf,
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
+ mpsc::{SyncSender, sync_channel},
+ },
+ 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(3)
+}
+
+struct PauseTracker {
+ flag: Arc<AtomicBool>,
+ paused_at: Option<Duration>,
+ offset: Duration,
+}
+
+impl PauseTracker {
+ fn new(flag: Arc<AtomicBool>) -> Self {
+ Self {
+ flag,
+ paused_at: None,
+ offset: Duration::ZERO,
+ }
+ }
+
+ fn adjust(&mut self, timestamp: Duration) -> anyhow::Result<Option<Duration>> {
+ if self.flag.load(Ordering::Relaxed) {
+ if self.paused_at.is_none() {
+ self.paused_at = Some(timestamp);
+ }
+ return Ok(None);
+ }
+
+ if let Some(start) = self.paused_at.take() {
+ let delta = timestamp.checked_sub(start).ok_or_else(|| {
+ anyhow!(
+ "Frame timestamp went backward during unpause (resume={start:?}, current={timestamp:?})"
+ )
+ })?;
+
+ self.offset = self.offset.checked_add(delta).ok_or_else(|| {
+ anyhow!(
+ "Pause offset overflow (offset={:?}, delta={delta:?})",
+ self.offset
+ )
+ })?;
+ }
+
+ let adjusted = timestamp.checked_sub(self.offset).ok_or_else(|| {
+ anyhow!(
+ "Adjusted timestamp underflow (timestamp={timestamp:?}, offset={:?})",
+ self.offset
+ )
+ })?;
+
+ Ok(Some(adjusted))
+ }
+}
+
+struct FrameDropTracker {
+ drops_in_window: u32,
+ frames_in_window: u32,
+ total_drops: u64,
+ total_frames: u64,
+ last_check: std::time::Instant,
+}
+
+impl FrameDropTracker {
+ fn new() -> Self {
+ Self {
+ drops_in_window: 0,
+ frames_in_window: 0,
+ total_drops: 0,
+ total_frames: 0,
+ last_check: std::time::Instant::now(),
+ }
+ }
+
+ 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,
+ "M4S muxer frame drop rate exceeds 5% threshold"
+ );
+ } 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),
+ "M4S muxer frame stats"
+ );
+ }
+ }
+ self.drops_in_window = 0;
+ self.frames_in_window = 0;
+ self.last_check = std::time::Instant::now();
+ }
+ }
+}
+
+struct EncoderState {
+ video_tx: SyncSender<Option<(cidre::arc::R<cidre::cm::SampleBuf>, Duration)>>,
+ encoder: Arc<Mutex<SegmentedVideoEncoder>>,
+ encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,
+}
+
+pub struct MacOSFragmentedM4SMuxer {
+ base_path: PathBuf,
+ video_config: VideoInfo,
+ segment_duration: Duration,
+ state: Option<EncoderState>,
+ pause: PauseTracker,
+ frame_drops: FrameDropTracker,
+ started: bool,
+}
+
+pub struct MacOSFragmentedM4SMuxerConfig {
+ pub segment_duration: Duration,
+ pub preset: H264Preset,
+ pub output_size: Option<(u32, u32)>,
+}
+
+impl Default for MacOSFragmentedM4SMuxerConfig {
+ fn default() -> Self {
+ Self {
+ segment_duration: Duration::from_secs(3),
+ preset: H264Preset::Ultrafast,
+ output_size: None,
+ }
+ }
+}
+
+impl Muxer for MacOSFragmentedM4SMuxer {
+ type Config = MacOSFragmentedM4SMuxerConfig;
+
+ 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"))?;
+
+ std::fs::create_dir_all(&output_path)
+ .with_context(|| format!("Failed to create segments directory: {output_path:?}"))?;
+
+ Ok(Self {
+ base_path: output_path,
+ video_config,
+ segment_duration: config.segment_duration,
+ state: None,
+ pause: PauseTracker::new(pause_flag),
+ frame_drops: FrameDropTracker::new(),
+ started: false,
+ })
+ }
+
+ fn stop(&mut self) {
+ if let Some(state) = &self.state
+ && let Err(e) = state.video_tx.send(None)
+ {
+ trace!("M4S encoder channel already closed during stop: {e}");
+ }
+ }
+
+ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
+ if let Some(mut state) = self.state.take() {
+ if let Err(e) = state.video_tx.send(None) {
+ trace!("M4S encoder channel already closed during finish: {e}");
+ }
+
+ if let Some(handle) = state.encoder_handle.take() {
+ let timeout = Duration::from_secs(5);
+ let start = std::time::Instant::now();
+ loop {
+ if handle.is_finished() {
+ if let Err(panic_payload) = handle.join() {
+ warn!(
+ "M4S encoder thread panicked during finish: {:?}",
+ panic_payload
+ );
+ }
+ break;
+ }
+ if start.elapsed() > timeout {
+ warn!(
+ "M4S encoder thread did not finish within {:?}, abandoning",
+ timeout
+ );
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ }
+
+ if let Ok(mut encoder) = state.encoder.lock() {
+ if let Err(e) = encoder.finish_with_timestamp(timestamp) {
+ warn!("Failed to finish segmented encoder: {e}");
+ }
+ }
+ }
+
+ Ok(Ok(()))
+ }
+}
+
+impl MacOSFragmentedM4SMuxer {
+ fn start_encoder(&mut self) -> anyhow::Result<()> {
+ let buffer_size = get_muxer_buffer_size();
+ debug!(
+ buffer_size = buffer_size,
+ "M4S muxer encoder channel buffer size"
+ );
+
+ let (video_tx, video_rx) =
+ sync_channel::<Option<(cidre::arc::R<cidre::cm::SampleBuf>, Duration)>>(buffer_size);
+ let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);
+
+ let encoder_config = SegmentedVideoEncoderConfig {
+ segment_duration: self.segment_duration,
+ preset: H264Preset::Ultrafast,
+ bpp: H264EncoderBuilder::QUALITY_BPP,
+ output_size: None,
+ };
+
+ let encoder =
+ SegmentedVideoEncoder::init(self.base_path.clone(), self.video_config, encoder_config)?;
+ let encoder = Arc::new(Mutex::new(encoder));
+ let encoder_clone = encoder.clone();
+ let video_config = self.video_config;
+
+ let encoder_handle = std::thread::Builder::new()
+ .name("m4s-segment-encoder".to_string())
+ .spawn(move || {
+ let pixel_format = match video_config.pixel_format {
+ 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,
+ };
+
+ let mut frame_pool =
+ FramePool::new(pixel_format, video_config.width, video_config.height);
+
+ if ready_tx.send(Ok(())).is_err() {
+ return Err(anyhow!("Failed to send ready signal - receiver dropped"));
+ }
+
+ let mut slow_convert_count = 0u32;
+ let mut slow_encode_count = 0u32;
+ let mut total_frames = 0u64;
+ const SLOW_THRESHOLD_MS: u128 = 5;
+
+ while let Ok(Some((sample_buf, timestamp))) = video_rx.recv() {
+ 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 % 100 == 0 {
+ debug!(
+ elapsed_ms = convert_elapsed_ms,
+ count = slow_convert_count,
+ "fill_frame_from_sample_buf exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+
+ match fill_result {
+ Ok(()) => {
+ let encode_start = std::time::Instant::now();
+ let owned_frame = frame_pool.take_frame();
+
+ if let Ok(mut encoder) = encoder_clone.lock() {
+ if let Err(e) = encoder.queue_frame(owned_frame, timestamp) {
+ warn!("Failed to encode frame: {e}");
+ }
+ }
+
+ 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 % 100 == 0 {
+ debug!(
+ elapsed_ms = encode_elapsed_ms,
+ count = slow_encode_count,
+ "encoder.queue_frame exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+ }
+ Err(e) => {
+ warn!("Failed to convert frame: {e:?}");
+ }
+ }
+
+ total_frames += 1;
+ }
+
+ 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
+ ),
+ "M4S encoder timing summary (using SegmentedVideoEncoder)"
+ );
+ }
+
+ Ok(())
+ })?;
+
+ ready_rx
+ .recv()
+ .map_err(|_| anyhow!("M4S encoder thread ended unexpectedly"))??;
+
+ self.state = Some(EncoderState {
+ video_tx,
+ encoder,
+ encoder_handle: Some(encoder_handle),
+ });
+
+ self.started = true;
+
+ info!(
+ path = %self.base_path.display(),
+ "Started M4S fragmented video encoder"
+ );
+
+ Ok(())
+ }
+}
+
+impl VideoMuxer for MacOSFragmentedM4SMuxer {
+ 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(_) => {
+ trace!("M4S encoder channel disconnected");
+ }
+ },
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl AudioMuxer for MacOSFragmentedM4SMuxer {
+ fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+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);
+ }
+ }
+}
+
+struct FramePool {
+ frame: Option<ffmpeg::frame::Video>,
+ pixel_format: ffmpeg::format::Pixel,
+ width: u32,
+ height: u32,
+}
+
+impl FramePool {
+ 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,
+ }
+ }
+
+ 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().unwrap()
+ }
+
+ 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)
+ })
+ }
+}
+
+fn fill_frame_from_sample_buf(
+ sample_buf: &cidre::cm::SampleBuf,
+ frame: &mut ffmpeg::frame::Video,
+) -> Result<(), SampleBufConversionError> {
+ use cidre::cv::{self, pixel_buffer::LockFlags};
+
+ 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(())
+}
+
+#[derive(Debug)]
+#[allow(dead_code)]
+enum SampleBufConversionError {
+ UnsupportedFormat(cidre::cv::PixelFormat),
+ BaseAddrLock(cidre::os::Error),
+ NoImageBuffer,
+}
+
+struct BaseAddrLockGuard<'a>(
+ &'a mut cidre::cv::ImageBuf,
+ cidre::cv::pixel_buffer::LockFlags,
+);
+
+impl<'a> BaseAddrLockGuard<'a> {
+ fn lock(
+ image_buf: &'a mut cidre::cv::ImageBuf,
+ flags: cidre::cv::pixel_buffer::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) {
+ let _ = unsafe { self.0.unlock_lock_base_addr(self.1) };
+ }
+}
+
+pub struct MacOSFragmentedM4SCameraMuxer {
+ base_path: PathBuf,
+ video_config: VideoInfo,
+ segment_duration: Duration,
+ state: Option<EncoderState>,
+ pause: PauseTracker,
+ frame_drops: FrameDropTracker,
+ started: bool,
+}
+
+pub struct MacOSFragmentedM4SCameraMuxerConfig {
+ pub segment_duration: Duration,
+ pub preset: H264Preset,
+ pub output_size: Option<(u32, u32)>,
+}
+
+impl Default for MacOSFragmentedM4SCameraMuxerConfig {
+ fn default() -> Self {
+ Self {
+ segment_duration: Duration::from_secs(3),
+ preset: H264Preset::Ultrafast,
+ output_size: None,
+ }
+ }
+}
+
+impl Muxer for MacOSFragmentedM4SCameraMuxer {
+ type Config = MacOSFragmentedM4SCameraMuxerConfig;
+
+ 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 camera"))?;
+
+ std::fs::create_dir_all(&output_path).with_context(|| {
+ format!("Failed to create camera segments directory: {output_path:?}")
+ })?;
+
+ Ok(Self {
+ base_path: output_path,
+ video_config,
+ segment_duration: config.segment_duration,
+ state: None,
+ pause: PauseTracker::new(pause_flag),
+ frame_drops: FrameDropTracker::new(),
+ started: false,
+ })
+ }
+
+ fn stop(&mut self) {
+ if let Some(state) = &self.state
+ && let Err(e) = state.video_tx.send(None)
+ {
+ trace!("M4S camera encoder channel already closed during stop: {e}");
+ }
+ }
+
+ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
+ if let Some(mut state) = self.state.take() {
+ if let Err(e) = state.video_tx.send(None) {
+ trace!("M4S camera encoder channel already closed during finish: {e}");
+ }
+
+ if let Some(handle) = state.encoder_handle.take() {
+ let timeout = Duration::from_secs(5);
+ let start = std::time::Instant::now();
+ loop {
+ if handle.is_finished() {
+ if let Err(panic_payload) = handle.join() {
+ warn!(
+ "M4S camera encoder thread panicked during finish: {:?}",
+ panic_payload
+ );
+ }
+ break;
+ }
+ if start.elapsed() > timeout {
+ warn!(
+ "M4S camera encoder thread did not finish within {:?}, abandoning",
+ timeout
+ );
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ }
+
+ if let Ok(mut encoder) = state.encoder.lock() {
+ if let Err(e) = encoder.finish_with_timestamp(timestamp) {
+ warn!("Failed to finish camera segmented encoder: {e}");
+ }
+ }
+ }
+
+ Ok(Ok(()))
+ }
+}
+
+impl MacOSFragmentedM4SCameraMuxer {
+ fn start_encoder(&mut self) -> anyhow::Result<()> {
+ let buffer_size = get_muxer_buffer_size();
+ debug!(
+ buffer_size = buffer_size,
+ "M4S camera muxer encoder channel buffer size"
+ );
+
+ let (video_tx, video_rx) =
+ sync_channel::<Option<(cidre::arc::R<cidre::cm::SampleBuf>, Duration)>>(buffer_size);
+ let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);
+
+ let encoder_config = SegmentedVideoEncoderConfig {
+ segment_duration: self.segment_duration,
+ preset: H264Preset::Ultrafast,
+ bpp: H264EncoderBuilder::QUALITY_BPP,
+ output_size: None,
+ };
+
+ let encoder =
+ SegmentedVideoEncoder::init(self.base_path.clone(), self.video_config, encoder_config)?;
+ let encoder = Arc::new(Mutex::new(encoder));
+ let encoder_clone = encoder.clone();
+ let video_config = self.video_config;
+
+ let encoder_handle = std::thread::Builder::new()
+ .name("m4s-camera-segment-encoder".to_string())
+ .spawn(move || {
+ let pixel_format = match video_config.pixel_format {
+ 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,
+ };
+
+ let mut frame_pool =
+ FramePool::new(pixel_format, video_config.width, video_config.height);
+
+ if ready_tx.send(Ok(())).is_err() {
+ return Err(anyhow!(
+ "Failed to send ready signal - camera receiver dropped"
+ ));
+ }
+
+ let mut slow_convert_count = 0u32;
+ let mut slow_encode_count = 0u32;
+ let mut total_frames = 0u64;
+ const SLOW_THRESHOLD_MS: u128 = 5;
+
+ while let Ok(Some((sample_buf, timestamp))) = video_rx.recv() {
+ 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 % 100 == 0 {
+ debug!(
+ elapsed_ms = convert_elapsed_ms,
+ count = slow_convert_count,
+ "Camera fill_frame_from_sample_buf exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+
+ match fill_result {
+ Ok(()) => {
+ let encode_start = std::time::Instant::now();
+ let owned_frame = frame_pool.take_frame();
+
+ if let Ok(mut encoder) = encoder_clone.lock() {
+ if let Err(e) = encoder.queue_frame(owned_frame, timestamp) {
+ warn!("Failed to encode camera frame: {e}");
+ }
+ }
+
+ 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 % 100 == 0 {
+ debug!(
+ elapsed_ms = encode_elapsed_ms,
+ count = slow_encode_count,
+ "Camera encoder.queue_frame exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
+ }
+ }
+ Err(e) => {
+ warn!("Failed to convert camera frame: {e:?}");
+ }
+ }
+
+ total_frames += 1;
+ }
+
+ 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
+ ),
+ "M4S camera encoder timing summary"
+ );
+ }
+
+ Ok(())
+ })?;
+
+ ready_rx
+ .recv()
+ .map_err(|_| anyhow!("M4S camera encoder thread ended unexpectedly"))??;
+
+ self.state = Some(EncoderState {
+ video_tx,
+ encoder,
+ encoder_handle: Some(encoder_handle),
+ });
+
+ self.started = true;
+
+ info!(
+ path = %self.base_path.display(),
+ "Started M4S fragmented camera encoder"
+ );
+
+ Ok(())
+ }
+}
+
+impl VideoMuxer for MacOSFragmentedM4SCameraMuxer {
+ type VideoFrame = NativeCameraFrame;
+
+ 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(_) => {
+ trace!("M4S camera encoder channel disconnected");
+ }
+ },
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl AudioMuxer for MacOSFragmentedM4SCameraMuxer {
+ fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
diff --git a/crates/recording/src/output_pipeline/macos_segmented_ffmpeg.rs b/crates/recording/src/output_pipeline/macos_segmented_ffmpeg.rs
deleted file mode 100644
index ad128644d..000000000
--- a/crates/recording/src/output_pipeline/macos_segmented_ffmpeg.rs
+++ /dev/null
@@ -1,746 +0,0 @@
-use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, fragmentation, screen_capture};
-use anyhow::{Context, anyhow};
-use cap_media_info::{AudioInfo, VideoInfo};
-use serde::Serialize;
-use std::{
- path::PathBuf,
- sync::{
- Arc, Mutex,
- atomic::{AtomicBool, Ordering},
- mpsc::{SyncSender, sync_channel},
- },
- thread::JoinHandle,
- time::Duration,
-};
-use tracing::*;
-
-#[derive(Debug, Clone)]
-pub struct SegmentInfo {
- pub path: PathBuf,
- pub index: u32,
- pub duration: Duration,
- pub file_size: Option<u64>,
-}
-
-#[derive(Serialize)]
-struct FragmentEntry {
- path: String,
- index: u32,
- duration: f64,
- is_complete: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- file_size: Option<u64>,
-}
-
-const MANIFEST_VERSION: u32 = 2;
-
-#[derive(Serialize)]
-struct Manifest {
- version: u32,
- fragments: Vec<FragmentEntry>,
- #[serde(skip_serializing_if = "Option::is_none")]
- total_duration: Option<f64>,
- is_complete: bool,
-}
-
-struct SegmentState {
- video_tx: SyncSender<Option<(cidre::arc::R<cidre::cm::SampleBuf>, Duration)>>,
- output: Arc<Mutex<ffmpeg::format::context::Output>>,
- encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,
-}
-
-struct PauseTracker {
- flag: Arc<AtomicBool>,
- paused_at: Option<Duration>,
- offset: Duration,
-}
-
-struct FrameDropTracker {
- count: u32,
- last_warning: std::time::Instant,
-}
-
-impl FrameDropTracker {
- fn new() -> Self {
- Self {
- count: 0,
- last_warning: std::time::Instant::now(),
- }
- }
-
- fn record_drop(&mut self) {
- self.count += 1;
- if self.count >= 30 && self.last_warning.elapsed() > Duration::from_secs(5) {
- warn!(
- "Dropped {} screen frames due to encoder backpressure",
- self.count
- );
- self.count = 0;
- self.last_warning = std::time::Instant::now();
- }
- }
-
- fn reset(&mut self) {
- if self.count > 0 {
- trace!("Frame drop count at segment boundary: {}", self.count);
- }
- self.count = 0;
- }
-}
-
-impl PauseTracker {
- fn new(flag: Arc<AtomicBool>) -> Self {
- Self {
- flag,
- paused_at: None,
- offset: Duration::ZERO,
- }
- }
-
- fn adjust(&mut self, timestamp: Duration) -> anyhow::Result<Option<Duration>> {
- if self.flag.load(Ordering::Relaxed) {
- if self.paused_at.is_none() {
- self.paused_at = Some(timestamp);
- }
- return Ok(None);
- }
-
- if let Some(start) = self.paused_at.take() {
- let delta = timestamp.checked_sub(start).ok_or_else(|| {
- anyhow!(
- "Frame timestamp went backward during unpause (resume={start:?}, current={timestamp:?})"
- )
- })?;
-
- self.offset = self.offset.checked_add(delta).ok_or_else(|| {
- anyhow!(
- "Pause offset overflow (offset={:?}, delta={delta:?})",
- self.offset
- )
- })?;
- }
-
- let adjusted = timestamp.checked_sub(self.offset).ok_or_else(|| {
- anyhow!(
- "Adjusted timestamp underflow (timestamp={timestamp:?}, offset={:?})",
- self.offset
- )
- })?;
-
- Ok(Some(adjusted))
- }
-}
-
-pub struct MacOSSegmentedMuxer {
- base_path: PathBuf,
- segment_duration: Duration,
- current_index: u32,
- segment_start_time: Option<Duration>,
- completed_segments: Vec<SegmentInfo>,
- pending_segments: Arc<Mutex<Vec<SegmentInfo>>>,
-
- current_state: Option<SegmentState>,
-
- video_config: VideoInfo,
-
- pause: PauseTracker,
- frame_drops: FrameDropTracker,
-}
-
-pub struct MacOSSegmentedMuxerConfig {
- pub segment_duration: Duration,
-}
-
-impl Default for MacOSSegmentedMuxerConfig {
- fn default() -> Self {
- Self {
- segment_duration: Duration::from_secs(3),
- }
- }
-}
-
-impl Muxer for MacOSSegmentedMuxer {
- type Config = MacOSSegmentedMuxerConfig;
-
- 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"))?;
-
- std::fs::create_dir_all(&output_path)
- .with_context(|| format!("Failed to create segments directory: {output_path:?}"))?;
-
- Ok(Self {
- base_path: output_path,
- segment_duration: config.segment_duration,
- current_index: 0,
- segment_start_time: None,
- completed_segments: Vec::new(),
- pending_segments: Arc::new(Mutex::new(Vec::new())),
- current_state: None,
- video_config,
- pause: PauseTracker::new(pause_flag),
- frame_drops: FrameDropTracker::new(),
- })
- }
-
- fn stop(&mut self) {
- if let Some(state) = &self.current_state
- && let Err(e) = state.video_tx.send(None)
- {
- trace!("Screen encoder channel already closed during stop: {e}");
- }
- }
-
- fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
- self.collect_pending_segments();
-
- let segment_path = self.current_segment_path();
- let segment_start = self.segment_start_time;
- let current_index = self.current_index;
-
- if let Some(mut state) = self.current_state.take() {
- if let Err(e) = state.video_tx.send(None) {
- trace!("Screen encoder channel already closed during finish: {e}");
- }
-
- if let Some(handle) = state.encoder_handle.take() {
- let timeout = Duration::from_secs(5);
- let start = std::time::Instant::now();
- loop {
- if handle.is_finished() {
- if let Err(panic_payload) = handle.join() {
- warn!(
- "Screen encoder thread panicked during finish: {:?}",
- panic_payload
- );
- }
- break;
- }
- if start.elapsed() > timeout {
- warn!(
- "Screen encoder thread did not finish within {:?}, abandoning",
- timeout
- );
- break;
- }
- std::thread::sleep(Duration::from_millis(50));
- }
- }
-
- if let Ok(mut output) = state.output.lock()
- && let Err(e) = output.write_trailer()
- {
- warn!("Failed to write trailer for segment {current_index}: {e}");
- }
-
- fragmentation::sync_file(&segment_path);
-
- if let Some(start) = segment_start {
- let final_duration = timestamp.saturating_sub(start);
- let file_size = std::fs::metadata(&segment_path).ok().map(|m| m.len());
-
- self.completed_segments.push(SegmentInfo {
- path: segment_path,
- index: current_index,
- duration: final_duration,
- file_size,
- });
- }
- }
-
- self.finalize_manifest();
-
- Ok(Ok(()))
- }
-}
-
-impl MacOSSegmentedMuxer {
- fn current_segment_path(&self) -> PathBuf {
- self.base_path
- .join(format!("fragment_{:03}.mp4", self.current_index))
- }
-
- fn write_manifest(&self) {
- let manifest = Manifest {
- version: MANIFEST_VERSION,
- fragments: self
- .completed_segments
- .iter()
- .map(|s| FragmentEntry {
- path: s
- .path
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .into_owned(),
- index: s.index,
- duration: s.duration.as_secs_f64(),
- is_complete: true,
- 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) = fragmentation::atomic_write_json(&manifest_path, &manifest) {
- warn!(
- "Failed to write manifest to {}: {e}",
- manifest_path.display()
- );
- }
- }
-
- fn finalize_manifest(&self) {
- let total_duration: Duration = self.completed_segments.iter().map(|s| s.duration).sum();
-
- let manifest = Manifest {
- version: MANIFEST_VERSION,
- fragments: self
- .completed_segments
- .iter()
- .map(|s| FragmentEntry {
- path: s
- .path
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .into_owned(),
- index: s.index,
- duration: s.duration.as_secs_f64(),
- is_complete: true,
- 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) = fragmentation::atomic_write_json(&manifest_path, &manifest) {
- warn!(
- "Failed to write final manifest to {}: {e}",
- manifest_path.display()
- );
- }
- }
-
- fn collect_pending_segments(&mut self) {
- if let Ok(mut pending) = self.pending_segments.lock() {
- for segment in pending.drain(..) {
- self.completed_segments.push(segment);
- }
- self.completed_segments.sort_by_key(|s| s.index);
- }
- }
-
- fn create_segment(&mut self) -> anyhow::Result<()> {
- let segment_path = self.current_segment_path();
-
- let (video_tx, video_rx) =
- sync_channel::<Option<(cidre::arc::R<cidre::cm::SampleBuf>, Duration)>>(8);
- let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);
- let output = ffmpeg::format::output(&segment_path)?;
- let output = Arc::new(Mutex::new(output));
-
- let video_config = self.video_config;
- let output_clone = output.clone();
-
- let encoder_handle = std::thread::Builder::new()
- .name(format!("segment-encoder-{}", self.current_index))
- .spawn(move || {
- let encoder = (|| {
- let mut output_guard = match output_clone.lock() {
- Ok(guard) => guard,
- Err(poisoned) => {
- return Err(anyhow!(
- "MacOSSegmentedEncoder: failed to lock output mutex: {}",
- poisoned
- ));
- }
- };
-
- cap_enc_ffmpeg::h264::H264Encoder::builder(video_config)
- .build(&mut output_guard)
- .map_err(|e| anyhow!("MacOSSegmentedEncoder/{e}"))
- })();
-
- let mut encoder = match encoder {
- Ok(encoder) => {
- if ready_tx.send(Ok(())).is_err() {
- error!("Failed to send ready signal - receiver dropped");
- return Ok(());
- }
- encoder
- }
- Err(e) => {
- error!("Encoder setup failed: {:#}", e);
- if let Err(send_err) = ready_tx.send(Err(anyhow!("{e}"))) {
- error!("failed to send ready_tx error: {send_err}");
- }
- return Err(anyhow!("{e}"));
- }
- };
-
- let mut first_timestamp: Option<Duration> = None;
-
- while let Ok(Some((sample_buf, timestamp))) = video_rx.recv() {
- let Ok(mut output) = output_clone.lock() else {
- continue;
- };
-
- let relative = if let Some(first) = first_timestamp {
- timestamp.checked_sub(first).unwrap_or(Duration::ZERO)
- } else {
- first_timestamp = Some(timestamp);
- Duration::ZERO
- };
-
- let frame = sample_buf_to_ffmpeg_frame(&sample_buf);
-
- match frame {
- Ok(frame) => {
- if let Err(e) = encoder.queue_frame(frame, relative, &mut output) {
- warn!("Failed to encode frame: {e}");
- }
- }
- Err(e) => {
- warn!("Failed to convert frame: {e:?}");
- }
- }
- }
-
- if let Ok(mut output) = output_clone.lock()
- && let Err(e) = encoder.flush(&mut output)
- {
- warn!("Failed to flush encoder: {e}");
- }
-
- drop(encoder);
-
- Ok(())
- })?;
-
- ready_rx
- .recv()
- .map_err(|_| anyhow!("Encoder thread ended unexpectedly"))??;
-
- output
- .lock()
- .map_err(|_| anyhow!("output mutex poisoned when writing header"))?
- .write_header()?;
-
- self.current_state = Some(SegmentState {
- video_tx,
- output,
- encoder_handle: Some(encoder_handle),
- });
-
- Ok(())
- }
-
- fn rotate_segment(&mut self, timestamp: Duration) -> anyhow::Result<()> {
- self.collect_pending_segments();
-
- let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);
- let segment_duration = timestamp.saturating_sub(segment_start);
- let completed_segment_path = self.current_segment_path();
- let current_index = self.current_index;
-
- if let Some(mut state) = self.current_state.take() {
- if let Err(e) = state.video_tx.send(None) {
- trace!("Screen encoder channel already closed during rotation: {e}");
- }
-
- let output = state.output.clone();
- let encoder_handle = state.encoder_handle.take();
- let path_for_sync = completed_segment_path.clone();
- let pending_segments = self.pending_segments.clone();
-
- std::thread::spawn(move || {
- if let Some(handle) = encoder_handle {
- let timeout = Duration::from_secs(5);
- let start = std::time::Instant::now();
- loop {
- if handle.is_finished() {
- if let Err(panic_payload) = handle.join() {
- warn!(
- "Screen encoder thread panicked during rotation: {:?}",
- panic_payload
- );
- }
- break;
- }
- if start.elapsed() > timeout {
- warn!(
- "Screen encoder thread did not finish within {:?} during rotation, abandoning",
- timeout
- );
- break;
- }
- std::thread::sleep(Duration::from_millis(50));
- }
- }
-
- if let Ok(mut output) = output.lock()
- && let Err(e) = output.write_trailer()
- {
- warn!("Failed to write trailer for segment {current_index}: {e}");
- }
-
- fragmentation::sync_file(&path_for_sync);
-
- let file_size = std::fs::metadata(&path_for_sync).ok().map(|m| m.len());
-
- if let Ok(mut pending) = pending_segments.lock() {
- pending.push(SegmentInfo {
- path: path_for_sync,
- index: current_index,
- duration: segment_duration,
- file_size,
- });
- }
- });
-
- self.write_manifest();
- }
-
- self.frame_drops.reset();
- self.current_index += 1;
- self.segment_start_time = Some(timestamp);
-
- self.create_segment()?;
- self.write_in_progress_manifest();
-
- info!(
- "Rotated to segment {} at {:?}",
- self.current_index, timestamp
- );
-
- Ok(())
- }
-
- fn write_in_progress_manifest(&self) {
- let mut fragments: Vec<FragmentEntry> = self
- .completed_segments
- .iter()
- .map(|s| FragmentEntry {
- path: s
- .path
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .into_owned(),
- index: s.index,
- duration: s.duration.as_secs_f64(),
- is_complete: true,
- file_size: s.file_size,
- })
- .collect();
-
- fragments.push(FragmentEntry {
- path: self
- .current_segment_path()
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .into_owned(),
- index: self.current_index,
- duration: 0.0,
- is_complete: false,
- file_size: None,
- });
-
- let manifest = Manifest {
- version: MANIFEST_VERSION,
- fragments,
- total_duration: None,
- is_complete: false,
- };
-
- let manifest_path = self.base_path.join("manifest.json");
- if let Err(e) = fragmentation::atomic_write_json(&manifest_path, &manifest) {
- warn!(
- "Failed to write in-progress manifest to {}: {e}",
- manifest_path.display()
- );
- }
- }
-}
-
-impl VideoMuxer for MacOSSegmentedMuxer {
- 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.current_state.is_none() {
- self.segment_start_time = Some(adjusted_timestamp);
- self.create_segment()?;
- self.write_in_progress_manifest();
- }
-
- if self.segment_start_time.is_none() {
- self.segment_start_time = Some(adjusted_timestamp);
- }
-
- let segment_elapsed =
- adjusted_timestamp.saturating_sub(self.segment_start_time.unwrap_or(Duration::ZERO));
-
- if segment_elapsed >= self.segment_duration {
- self.rotate_segment(adjusted_timestamp)?;
- }
-
- if let Some(state) = &self.current_state
- && let Err(e) = state
- .video_tx
- .try_send(Some((frame.sample_buf, adjusted_timestamp)))
- {
- match e {
- std::sync::mpsc::TrySendError::Full(_) => {
- self.frame_drops.record_drop();
- }
- std::sync::mpsc::TrySendError::Disconnected(_) => {
- trace!("Screen encoder channel disconnected");
- }
- }
- }
-
- Ok(())
- }
-}
-
-impl AudioMuxer for MacOSSegmentedMuxer {
- fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {
- Ok(())
- }
-}
-
-fn sample_buf_to_ffmpeg_frame(
- sample_buf: &cidre::cm::SampleBuf,
-) -> Result<ffmpeg::frame::Video, SampleBufConversionError> {
- use cidre::cv::{self, pixel_buffer::LockFlags};
-
- 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)?;
-
- Ok(match pixel_format {
- cv::PixelFormat::_420V => {
- let mut ff_frame =
- ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, width as u32, height as u32);
-
- let src_stride = plane0_stride;
- let dest_stride = ff_frame.stride(0);
-
- let src_bytes = bytes_lock.plane_data(0);
- let dest_bytes = &mut ff_frame.data_mut(0);
-
- for y in 0..height {
- let row_width = width;
- let src_row = &src_bytes[y * src_stride..y * src_stride + row_width];
- let dest_row = &mut dest_bytes[y * dest_stride..y * dest_stride + row_width];
-
- dest_row.copy_from_slice(src_row);
- }
-
- let src_stride = plane1_stride;
- let dest_stride = ff_frame.stride(1);
-
- let src_bytes = bytes_lock.plane_data(1);
- let dest_bytes = &mut ff_frame.data_mut(1);
-
- for y in 0..height / 2 {
- let row_width = width;
- let src_row = &src_bytes[y * src_stride..y * src_stride + row_width];
- let dest_row = &mut dest_bytes[y * dest_stride..y * dest_stride + row_width];
-
- dest_row.copy_from_slice(src_row);
- }
-
- ff_frame
- }
- cv::PixelFormat::_32_BGRA => {
- let mut ff_frame =
- ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, width as u32, height as u32);
-
- let src_stride = plane0_stride;
- let dest_stride = ff_frame.stride(0);
-
- let src_bytes = bytes_lock.plane_data(0);
- let dest_bytes = &mut ff_frame.data_mut(0);
-
- for y in 0..height {
- let row_width = width * 4;
- let src_row = &src_bytes[y * src_stride..y * src_stride + row_width];
- let dest_row = &mut dest_bytes[y * dest_stride..y * dest_stride + row_width];
-
- dest_row.copy_from_slice(src_row);
- }
-
- ff_frame
- }
- format => return Err(SampleBufConversionError::UnsupportedFormat(format)),
- })
-}
-
-#[derive(Debug)]
-pub enum SampleBufConversionError {
- UnsupportedFormat(cidre::cv::PixelFormat),
- BaseAddrLock(cidre::os::Error),
- NoImageBuffer,
-}
-
-struct BaseAddrLockGuard<'a>(
- &'a mut cidre::cv::ImageBuf,
- cidre::cv::pixel_buffer::LockFlags,
-);
-
-impl<'a> BaseAddrLockGuard<'a> {
- fn lock(
- image_buf: &'a mut cidre::cv::ImageBuf,
- flags: cidre::cv::pixel_buffer::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) {
- let _ = unsafe { self.0.unlock_lock_base_addr(self.1) };
- }
-}
diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rs
index bf1df859e..2f2bf6d2f 100644
--- a/crates/recording/src/output_pipeline/mod.rs
+++ b/crates/recording/src/output_pipeline/mod.rs
@@ -2,17 +2,13 @@ mod async_camera;
mod core;
pub mod ffmpeg;
#[cfg(target_os = "macos")]
-mod fragmented;
-#[cfg(target_os = "macos")]
-mod macos_segmented_ffmpeg;
+mod macos_fragmented_m4s;
pub use async_camera::*;
pub use core::*;
pub use ffmpeg::*;
#[cfg(target_os = "macos")]
-pub use fragmented::*;
-#[cfg(target_os = "macos")]
-pub use macos_segmented_ffmpeg::*;
+pub use macos_fragmented_m4s::*;
#[cfg(target_os = "macos")]
mod macos;
diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rs
index 4490ac1c5..96f24578b 100644
--- a/crates/recording/src/recovery.rs
+++ b/crates/recording/src/recovery.rs
@@ -4,8 +4,9 @@ use std::{
};
use cap_enc_ffmpeg::remux::{
- concatenate_audio_to_ogg, concatenate_video_fragments, get_media_duration, get_video_fps,
- probe_media_valid, probe_video_can_decode,
+ concatenate_audio_to_ogg, concatenate_m4s_segments_with_init, concatenate_video_fragments,
+ get_media_duration, get_video_fps, probe_m4s_can_decode_with_init, probe_media_valid,
+ probe_video_can_decode,
};
use cap_project::{
AudioMeta, Cursors, MultipleSegment, MultipleSegments, ProjectConfiguration, RecordingMeta,
@@ -27,7 +28,9 @@ pub struct IncompleteRecording {
pub struct RecoverableSegment {
pub index: u32,
pub display_fragments: Vec<PathBuf>,
+ pub display_init_segment: Option<PathBuf>,
pub camera_fragments: Option<Vec<PathBuf>>,
+ pub camera_init_segment: Option<PathBuf>,
pub mic_fragments: Option<Vec<PathBuf>>,
pub system_audio_fragments: Option<Vec<PathBuf>>,
pub cursor_path: Option<PathBuf>,
@@ -39,6 +42,12 @@ pub struct RecoveredRecording {
pub meta: StudioRecordingMeta,
}
+#[derive(Debug, Clone)]
+struct FragmentsInfo {
+ fragments: Vec<PathBuf>,
+ init_segment: Option<PathBuf>,
+}
+
#[derive(Debug, thiserror::Error)]
pub enum RecoveryError {
#[error("IO error: {0}")]
@@ -133,13 +142,16 @@ impl RecoveryManager {
let segment_path = segment_entry.path();
let display_dir = segment_path.join("display");
- let mut display_fragments = Self::find_complete_fragments(&display_dir);
+ let display_info = Self::find_complete_fragments_with_init(&display_dir);
+ let mut display_fragments = display_info.fragments;
+ let mut display_init_segment = display_info.init_segment;
if display_fragments.is_empty()
&& let Some(display_mp4) =
Self::probe_single_file(&segment_path.join("display.mp4"))
{
display_fragments = vec![display_mp4];
+ display_init_segment = None;
}
if display_fragments.is_empty() {
@@ -151,12 +163,15 @@ impl RecoveryManager {
}
let camera_dir = segment_path.join("camera");
- let camera_fragments = {
- let frags = Self::find_complete_fragments(&camera_dir);
- if frags.is_empty() {
- Self::probe_single_file(&segment_path.join("camera.mp4")).map(|p| vec![p])
+ let (camera_fragments, camera_init_segment) = {
+ let camera_info = Self::find_complete_fragments_with_init(&camera_dir);
+ if camera_info.fragments.is_empty() {
+ (
+ Self::probe_single_file(&segment_path.join("camera.mp4")).map(|p| vec![p]),
+ None,
+ )
} else {
- Some(frags)
+ (Some(camera_info.fragments), camera_info.init_segment)
}
};
@@ -173,7 +188,9 @@ impl RecoveryManager {
recoverable_segments.push(RecoverableSegment {
index: index as u32,
display_fragments,
+ display_init_segment,
camera_fragments,
+ camera_init_segment,
mic_fragments,
system_audio_fragments,
cursor_path,
@@ -201,6 +218,10 @@ impl RecoveryManager {
}
fn find_complete_fragments(dir: &Path) -> Vec<PathBuf> {
+ Self::find_complete_fragments_with_init(dir).fragments
+ }
+
+ fn find_complete_fragments_with_init(dir: &Path) -> FragmentsInfo {
use crate::fragmentation::CURRENT_MANIFEST_VERSION;
let manifest_path = dir.join("manifest.json");
@@ -208,82 +229,141 @@ impl RecoveryManager {
if manifest_path.exists()
&& let Ok(content) = std::fs::read_to_string(&manifest_path)
&& let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&content)
- && let Some(fragments) = manifest.get("fragments").and_then(|f| f.as_array())
{
let manifest_version = manifest
.get("version")
.and_then(|v| v.as_u64())
.unwrap_or(1) as u32;
- if manifest_version > CURRENT_MANIFEST_VERSION {
+
+ let manifest_type = manifest
+ .get("type")
+ .and_then(|t| t.as_str())
+ .unwrap_or("fragments");
+
+ let max_supported_version = if manifest_type == "m4s_segments" {
+ 4
+ } else {
+ CURRENT_MANIFEST_VERSION
+ };
+
+ if manifest_version > max_supported_version {
warn!(
- "Manifest version {} is newer than supported {}",
- manifest_version, CURRENT_MANIFEST_VERSION
+ "Manifest version {} is newer than supported {} for type {}",
+ manifest_version, max_supported_version, manifest_type
);
}
- let expected_file_size = |f: &serde_json::Value| -> Option<u64> {
- f.get("file_size").and_then(|s| s.as_u64())
+ let init_segment = manifest
+ .get("init_segment")
+ .and_then(|i| i.as_str())
+ .map(|name| dir.join(name))
+ .filter(|p| p.exists());
+
+ let entries = if manifest_type == "m4s_segments" {
+ manifest.get("segments").and_then(|s| s.as_array())
+ } else {
+ manifest.get("fragments").and_then(|f| f.as_array())
};
- let result: Vec<PathBuf> = fragments
- .iter()
- .filter(|f| {
- f.get("is_complete")
- .and_then(|c| c.as_bool())
- .unwrap_or(false)
- })
- .filter_map(|f| {
- let path_str = f.get("path").and_then(|p| p.as_str())?;
- let path = dir.join(path_str);
- if !path.exists() {
- return None;
- }
+ if let Some(entries) = entries {
+ let expected_file_size = |f: &serde_json::Value| -> Option<u64> {
+ f.get("file_size").and_then(|s| s.as_u64())
+ };
+
+ let result: Vec<PathBuf> = entries
+ .iter()
+ .filter(|f| {
+ f.get("is_complete")
+ .and_then(|c| c.as_bool())
+ .unwrap_or(false)
+ })
+ .filter_map(|f| {
+ let path_str = f.get("path").and_then(|p| p.as_str())?;
+ let path = dir.join(path_str);
+ if !path.exists() {
+ return None;
+ }
- if let Some(expected_size) = expected_file_size(f)
- && let Ok(metadata) = std::fs::metadata(&path)
- && metadata.len() != expected_size
- {
- warn!(
- "Fragment {} size mismatch: expected {}, got {}",
- path.display(),
- expected_size,
- metadata.len()
- );
- return None;
- }
+ if let Some(expected_size) = expected_file_size(f)
+ && let Ok(metadata) = std::fs::metadata(&path)
+ && metadata.len() != expected_size
+ {
+ warn!(
+ "Fragment {} size mismatch: expected {}, got {}",
+ path.display(),
+ expected_size,
+ metadata.len()
+ );
+ return None;
+ }
- if Self::is_video_file(&path) {
- match probe_video_can_decode(&path) {
- Ok(true) => Some(path),
- Ok(false) => {
- warn!("Fragment {} has no decodable frames", path.display());
- None
- }
- Err(e) => {
- warn!("Fragment {} validation failed: {}", path.display(), e);
- None
+ if Self::is_video_file(&path) {
+ if let Some(init_path) = &init_segment {
+ match probe_m4s_can_decode_with_init(init_path, &path) {
+ Ok(true) => Some(path),
+ Ok(false) => {
+ warn!(
+ "M4S segment {} has no decodable frames (with init)",
+ path.display()
+ );
+ None
+ }
+ Err(e) => {
+ warn!(
+ "M4S segment {} validation failed: {}",
+ path.display(),
+ e
+ );
+ None
+ }
+ }
+ } else {
+ match probe_video_can_decode(&path) {
+ Ok(true) => Some(path),
+ Ok(false) => {
+ warn!(
+ "Fragment {} has no decodable frames",
+ path.display()
+ );
+ None
+ }
+ Err(e) => {
+ warn!(
+ "Fragment {} validation failed: {}",
+ path.display(),
+ e
+ );
+ None
+ }
+ }
}
+ } else if probe_media_valid(&path) {
+ Some(path)
+ } else {
+ warn!("Fragment {} is not valid media", path.display());
+ None
}
- } else if probe_media_valid(&path) {
- Some(path)
- } else {
- warn!("Fragment {} is not valid media", path.display());
- None
- }
- })
- .collect();
-
- if !result.is_empty() {
- return result;
+ })
+ .collect();
+
+ if !result.is_empty() {
+ return FragmentsInfo {
+ fragments: result,
+ init_segment,
+ };
+ }
}
}
- Self::probe_fragments_in_dir(dir)
+ FragmentsInfo {
+ fragments: Self::probe_fragments_in_dir(dir),
+ init_segment: None,
+ }
}
fn is_video_file(path: &Path) -> bool {
path.extension()
- .map(|e| e.eq_ignore_ascii_case("mp4"))
+ .map(|e| e.eq_ignore_ascii_case("mp4") || e.eq_ignore_ascii_case("m4s"))
.unwrap_or(false)
}
@@ -301,7 +381,7 @@ impl RecoveryManager {
.and_then(|e| e.to_str())
.map(|e| e.to_lowercase());
match ext.as_deref() {
- Some("mp4") => match probe_video_can_decode(p) {
+ Some("mp4") | Some("m4s") => match probe_video_can_decode(p) {
Ok(true) => true,
Ok(false) => {
debug!("Skipping {} - no decodable frames", p.display());
@@ -398,7 +478,7 @@ impl RecoveryManager {
.join(format!("segment-{}", segment.index));
let display_output = segment_dir.join("display.mp4");
- if segment.display_fragments.len() == 1 {
+ if segment.display_fragments.len() == 1 && segment.display_init_segment.is_none() {
let source = &segment.display_fragments[0];
if source != &display_output {
info!("Moving single display fragment to {:?}", display_output);
@@ -410,20 +490,39 @@ impl RecoveryManager {
debug!("Failed to clean up display dir {:?}: {e}", display_dir);
}
}
- } else if segment.display_fragments.len() > 1 {
- info!(
- "Concatenating {} display fragments to {:?}",
- segment.display_fragments.len(),
- display_output
- );
- concatenate_video_fragments(&segment.display_fragments, &display_output)
+ } else if !segment.display_fragments.is_empty() {
+ if let Some(init_path) = &segment.display_init_segment {
+ info!(
+ "Concatenating {} M4S display segments with init to {:?}",
+ segment.display_fragments.len(),
+ display_output
+ );
+ concatenate_m4s_segments_with_init(
+ init_path,
+ &segment.display_fragments,
+ &display_output,
+ )
.map_err(RecoveryError::VideoConcat)?;
+ } else {
+ info!(
+ "Concatenating {} display fragments to {:?}",
+ segment.display_fragments.len(),
+ display_output
+ );
+ concatenate_video_fragments(&segment.display_fragments, &display_output)
+ .map_err(RecoveryError::VideoConcat)?;
+ }
for fragment in &segment.display_fragments {
if let Err(e) = std::fs::remove_file(fragment) {
debug!("Failed to remove display fragment {:?}: {e}", fragment);
}
}
+ if let Some(init_path) = &segment.display_init_segment {
+ if let Err(e) = std::fs::remove_file(init_path) {
+ debug!("Failed to remove display init segment {:?}: {e}", init_path);
+ }
+ }
let display_dir = segment_dir.join("display");
if display_dir.exists()
&& let Err(e) = std::fs::remove_dir_all(&display_dir)
@@ -434,7 +533,7 @@ impl RecoveryManager {
if let Some(camera_frags) = &segment.camera_fragments {
let camera_output = segment_dir.join("camera.mp4");
- if camera_frags.len() == 1 {
+ if camera_frags.len() == 1 && segment.camera_init_segment.is_none() {
let source = &camera_frags[0];
if source != &camera_output {
info!("Moving single camera fragment to {:?}", camera_output);
@@ -446,20 +545,35 @@ impl RecoveryManager {
debug!("Failed to clean up camera dir {:?}: {e}", camera_dir);
}
}
- } else if camera_frags.len() > 1 {
- info!(
- "Concatenating {} camera fragments to {:?}",
- camera_frags.len(),
- camera_output
- );
- concatenate_video_fragments(camera_frags, &camera_output)
- .map_err(RecoveryError::VideoConcat)?;
+ } else if !camera_frags.is_empty() {
+ if let Some(init_path) = &segment.camera_init_segment {
+ info!(
+ "Concatenating {} M4S camera segments with init to {:?}",
+ camera_frags.len(),
+ camera_output
+ );
+ concatenate_m4s_segments_with_init(init_path, camera_frags, &camera_output)
+ .map_err(RecoveryError::VideoConcat)?;
+ } else {
+ info!(
+ "Concatenating {} camera fragments to {:?}",
+ camera_frags.len(),
+ camera_output
+ );
+ concatenate_video_fragments(camera_frags, &camera_output)
+ .map_err(RecoveryError::VideoConcat)?;
+ }
for fragment in camera_frags {
if let Err(e) = std::fs::remove_file(fragment) {
debug!("Failed to remove camera fragment {:?}: {e}", fragment);
}
}
+ if let Some(init_path) = &segment.camera_init_segment {
+ if let Err(e) = std::fs::remove_file(init_path) {
+ debug!("Failed to remove camera init segment {:?}: {e}", init_path);
+ }
+ }
let camera_dir = segment_dir.join("camera");
if camera_dir.exists()
&& let Err(e) = std::fs::remove_dir_all(&camera_dir)
diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs
index 51916b5e2..a5322af97 100644
--- a/crates/recording/src/sources/screen_capture/macos.rs
+++ b/crates/recording/src/sources/screen_capture/macos.rs
@@ -13,7 +13,7 @@ use futures::{FutureExt as _, channel::mpsc, future::BoxFuture};
use std::{
sync::{
Arc,
- atomic::{self, AtomicBool, AtomicU32},
+ atomic::{self, AtomicBool, AtomicU32, AtomicU64},
},
time::Duration,
};
@@ -24,6 +24,20 @@ use tokio_util::{
};
use tracing::{debug, warn};
+fn get_screen_buffer_size() -> usize {
+ std::env::var("CAP_SCREEN_BUFFER_SIZE")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(4)
+}
+
+fn get_max_queue_depth() -> isize {
+ std::env::var("CAP_MAX_QUEUE_DEPTH")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(4)
+}
+
#[derive(Debug)]
pub struct CMSampleBufferCapture;
@@ -31,7 +45,7 @@ impl ScreenCaptureFormat for CMSampleBufferCapture {
type VideoFormat = cidre::arc::R<cidre::cm::SampleBuf>;
fn pixel_format() -> ffmpeg::format::Pixel {
- ffmpeg::format::Pixel::BGRA
+ ffmpeg::format::Pixel::NV12
}
fn audio_info() -> AudioInfo {
@@ -68,8 +82,10 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
&self,
) -> anyhow::Result<(VideoSourceConfig, Option<SystemAudioSourceConfig>)> {
let (error_tx, error_rx) = broadcast::channel(1);
- // Increased from 4 to 12 to provide more buffer tolerance for frame processing delays
- let (video_tx, video_rx) = flume::bounded(12);
+ let buffer_size = get_screen_buffer_size();
+ debug!(buffer_size = buffer_size, "Screen capture buffer size");
+ let (video_tx, video_rx) = flume::bounded(buffer_size);
+ let drop_counter: Arc<AtomicU64> = Arc::new(AtomicU64::new(0));
let (mut audio_tx, audio_rx) = if self.system_audio {
let (tx, rx) = mpsc::channel(32);
(Some(tx), Some(rx))
@@ -129,8 +145,14 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
debug!("size: {:?}", size);
- let queue_depth = ((self.config.fps as f32 / 30.0 * 5.0).ceil() as isize).clamp(3, 8);
- debug!("Using queue depth: {}", queue_depth);
+ let max_queue_depth = get_max_queue_depth();
+ let queue_depth =
+ ((self.config.fps as f32 / 30.0 * 5.0).ceil() as isize).clamp(3, max_queue_depth);
+ debug!(
+ queue_depth = queue_depth,
+ max_queue_depth = max_queue_depth,
+ "Screen capture queue depth"
+ );
let mut settings = scap_screencapturekit::StreamCfgBuilder::default()
.with_width(size.width() as usize)
@@ -141,7 +163,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
.with_queue_depth(queue_depth)
.build();
- settings.set_pixel_format(cv::PixelFormat::_32_BGRA);
+ settings.set_pixel_format(cv::PixelFormat::_420V);
settings.set_color_space_name(cg::color_space::names::srgb());
if let Some(crop_bounds) = self.config.crop_bounds {
@@ -163,6 +185,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
let builder = scap_screencapturekit::Capturer::builder(content_filter, settings)
.with_output_sample_buf_cb({
let video_frame_count = video_frame_counter.clone();
+ let drop_counter = drop_counter.clone();
move |frame| {
let sample_buffer = frame.sample_buf();
@@ -185,10 +208,15 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
video_frame_count.fetch_add(1, atomic::Ordering::Relaxed);
- let _ = video_tx.try_send(VideoFrame {
- sample_buf: sample_buffer.retained(),
- timestamp,
- });
+ if video_tx
+ .try_send(VideoFrame {
+ sample_buf: sample_buffer.retained(),
+ timestamp,
+ })
+ .is_err()
+ {
+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ }
}
scap_screencapturekit::Frame::Audio(_) => {
use ffmpeg::ChannelLayout;
@@ -243,6 +271,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
capturer: capturer.clone(),
error_rx: error_rx.resubscribe(),
video_frame_counter: video_frame_counter.clone(),
+ drop_counter,
cancel_token: cancel_token.clone(),
drop_guard: cancel_token.drop_guard(),
},
@@ -341,12 +370,14 @@ pub struct VideoSourceConfig {
cancel_token: CancellationToken,
drop_guard: DropGuard,
video_frame_counter: Arc<AtomicU32>,
+ drop_counter: Arc<AtomicU64>,
}
pub struct VideoSource {
inner: ChannelVideoSource<VideoFrame>,
capturer: Capturer,
cancel_token: CancellationToken,
video_frame_counter: Arc<AtomicU32>,
+ drop_counter: Arc<AtomicU64>,
_drop_guard: DropGuard,
}
@@ -369,6 +400,7 @@ impl output_pipeline::VideoSource for VideoSource {
cancel_token,
drop_guard,
video_frame_counter,
+ drop_counter,
} = config;
let monitor_capturer = capturer.clone();
@@ -415,6 +447,7 @@ impl output_pipeline::VideoSource for VideoSource {
cancel_token,
_drop_guard: drop_guard,
video_frame_counter,
+ drop_counter,
})
}
@@ -424,13 +457,43 @@ impl output_pipeline::VideoSource for VideoSource {
tokio::spawn({
let video_frame_count = self.video_frame_counter.clone();
+ let drop_counter = self.drop_counter.clone();
async move {
+ let mut prev_frames = 0u32;
+ let mut prev_drops = 0u64;
loop {
tokio::time::sleep(Duration::from_secs(5)).await;
- debug!(
- "Captured {} frames",
- video_frame_count.load(atomic::Ordering::Relaxed)
- );
+ let current_frames = video_frame_count.load(atomic::Ordering::Relaxed);
+ let current_drops = drop_counter.load(atomic::Ordering::Relaxed);
+
+ let frame_delta = current_frames.saturating_sub(prev_frames);
+ let drop_delta = current_drops.saturating_sub(prev_drops);
+
+ if frame_delta > 0 {
+ let drop_rate = 100.0 * drop_delta as f64
+ / (frame_delta as f64 + drop_delta as f64);
+ if drop_rate > 5.0 {
+ warn!(
+ frames = frame_delta,
+ drops = drop_delta,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ total_frames = current_frames,
+ total_drops = current_drops,
+ "Screen capture frame drop rate exceeds 5% threshold"
+ );
+ } else {
+ debug!(
+ frames = frame_delta,
+ drops = drop_delta,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ total_frames = current_frames,
+ "Screen capture stats"
+ );
+ }
+ }
+
+ prev_frames = current_frames;
+ prev_drops = current_drops;
}
}
.with_cancellation_token_owned(self.cancel_token.clone())