Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(recording): implement non-blocking MP4 muxer with dedicated threads

Richie McIlroy9405e9a9c05f
diff --git a/crates/recording/src/output_pipeline/macos.rs b/crates/recording/src/output_pipeline/macos.rs
index f1d12fa91..e66fbfa83 100644
--- a/crates/recording/src/output_pipeline/macos.rs
+++ b/crates/recording/src/output_pipeline/macos.rs
@@ -9,9 +9,83 @@ use cap_timestamp::Timestamp;
use cidre::arc;
use std::{
path::PathBuf,
- sync::{Arc, Mutex, atomic::AtomicBool},
+ sync::{
+ Arc, Mutex,
+ atomic::AtomicBool,
+ mpsc::{SyncSender, sync_channel},
+ },
+ thread::JoinHandle,
time::Duration,
};
+use tracing::*;
+
+fn get_mp4_muxer_buffer_size() -> usize {
+ std::env::var("CAP_MP4_MUXER_BUFFER_SIZE")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(60)
+}
+
+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,
+ "MP4 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),
+ "MP4 muxer frame stats"
+ );
+ }
+ }
+ self.drops_in_window = 0;
+ self.frames_in_window = 0;
+ self.last_check = std::time::Instant::now();
+ }
+ }
+}
#[derive(Clone)]
pub struct NativeCameraFrame {
@@ -28,14 +102,29 @@ impl VideoFrame for NativeCameraFrame {
}
}
-#[derive(Clone)]
-pub struct AVFoundationMp4Muxer(
- Arc<Mutex<cap_enc_avfoundation::MP4Encoder>>,
- Arc<AtomicBool>,
-);
+enum VideoFrameMessage {
+ Frame(arc::R<cidre::cm::SampleBuf>, Duration),
+ Pause,
+ Resume,
+}
+
+enum AudioFrameMessage {
+ Frame(ffmpeg::frame::Audio, Duration),
+}
-impl AVFoundationMp4Muxer {
- const MAX_QUEUE_RETRIES: u32 = 1500;
+struct Mp4EncoderState {
+ video_tx: SyncSender<Option<VideoFrameMessage>>,
+ audio_tx: Option<SyncSender<Option<AudioFrameMessage>>>,
+ encoder: Arc<Mutex<cap_enc_avfoundation::MP4Encoder>>,
+ encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,
+ audio_handle: Option<JoinHandle<anyhow::Result<()>>>,
+}
+
+pub struct AVFoundationMp4Muxer {
+ state: Option<Mp4EncoderState>,
+ pause_flag: Arc<AtomicBool>,
+ frame_drops: FrameDropTracker,
+ was_paused: bool,
}
#[derive(Default)]
@@ -57,27 +146,269 @@ impl Muxer for AVFoundationMp4Muxer {
let video_config =
video_config.ok_or_else(|| anyhow!("Invariant: No video source provided"))?;
- Ok(Self(
- Arc::new(Mutex::new(
- cap_enc_avfoundation::MP4Encoder::init(
- output_path,
- video_config,
- audio_config,
- config.output_height,
- )
- .map_err(|e| anyhow!("{e}"))?,
- )),
+ let buffer_size = get_mp4_muxer_buffer_size();
+ debug!(buffer_size, "MP4 muxer encoder channel buffer size");
+
+ let (video_tx, video_rx) = sync_channel::<Option<VideoFrameMessage>>(buffer_size);
+ let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);
+
+ let encoder = cap_enc_avfoundation::MP4Encoder::init(
+ output_path.clone(),
+ video_config,
+ audio_config,
+ config.output_height,
+ )
+ .map_err(|e| anyhow!("{e}"))?;
+
+ let encoder = Arc::new(Mutex::new(encoder));
+ let encoder_clone = encoder.clone();
+
+ let encoder_handle = std::thread::Builder::new()
+ .name("mp4-video-encoder".to_string())
+ .spawn(move || {
+ if ready_tx.send(Ok(())).is_err() {
+ return Err(anyhow!("Failed to send ready signal - receiver dropped"));
+ }
+
+ let mut total_frames = 0u64;
+ let mut encoder_busy_count = 0u64;
+
+ while let Ok(Some(msg)) = video_rx.recv() {
+ match msg {
+ VideoFrameMessage::Frame(sample_buf, timestamp) => {
+ let mut encoder = match encoder_clone.lock() {
+ Ok(e) => e,
+ Err(_) => {
+ error!("MP4 encoder mutex poisoned");
+ return Err(anyhow!("MP4 encoder mutex poisoned"));
+ }
+ };
+
+ let mut retry_count = 0;
+ const MAX_RETRIES: u32 = 100;
+
+ loop {
+ match encoder.queue_video_frame(sample_buf.clone(), timestamp) {
+ Ok(()) => break,
+ Err(QueueFrameError::NotReadyForMore) => {
+ retry_count += 1;
+ if retry_count >= MAX_RETRIES {
+ encoder_busy_count += 1;
+ if encoder_busy_count <= 5 || encoder_busy_count.is_multiple_of(100) {
+ debug!(
+ encoder_busy_count,
+ "MP4 encoder busy, frame queued after max retries"
+ );
+ }
+ break;
+ }
+ std::thread::sleep(Duration::from_micros(500));
+ }
+ Err(e) => {
+ warn!("Failed to encode video frame: {e}");
+ break;
+ }
+ }
+ }
+
+ total_frames += 1;
+ }
+ VideoFrameMessage::Pause => {
+ if let Ok(mut encoder) = encoder_clone.lock() {
+ encoder.pause();
+ }
+ }
+ VideoFrameMessage::Resume => {
+ if let Ok(mut encoder) = encoder_clone.lock() {
+ encoder.resume();
+ }
+ }
+ }
+ }
+
+ if total_frames > 0 {
+ debug!(
+ total_frames,
+ encoder_busy_count,
+ busy_pct = format!("{:.1}%", 100.0 * encoder_busy_count as f64 / total_frames as f64),
+ "MP4 video encoder timing summary"
+ );
+ }
+
+ Ok(())
+ })?;
+
+ ready_rx
+ .recv()
+ .map_err(|_| anyhow!("MP4 encoder thread ended unexpectedly"))??;
+
+ let (audio_tx, audio_handle) = if audio_config.is_some() {
+ let (audio_tx, audio_rx) = sync_channel::<Option<AudioFrameMessage>>(buffer_size);
+ let encoder_clone = encoder.clone();
+ let (audio_ready_tx, audio_ready_rx) = sync_channel::<anyhow::Result<()>>(1);
+
+ let audio_handle = std::thread::Builder::new()
+ .name("mp4-audio-encoder".to_string())
+ .spawn(move || {
+ if audio_ready_tx.send(Ok(())).is_err() {
+ return Err(anyhow!("Failed to send audio ready signal"));
+ }
+
+ let mut total_frames = 0u64;
+ let mut encoder_busy_count = 0u64;
+
+ while let Ok(Some(msg)) = audio_rx.recv() {
+ match msg {
+ AudioFrameMessage::Frame(frame, timestamp) => {
+ let mut encoder = match encoder_clone.lock() {
+ Ok(e) => e,
+ Err(_) => {
+ error!("MP4 audio encoder mutex poisoned");
+ return Err(anyhow!("MP4 audio encoder mutex poisoned"));
+ }
+ };
+
+ let mut retry_count = 0;
+ const MAX_RETRIES: u32 = 50;
+
+ loop {
+ match encoder.queue_audio_frame(&frame, timestamp) {
+ Ok(()) => break,
+ Err(QueueFrameError::NotReadyForMore) => {
+ retry_count += 1;
+ if retry_count >= MAX_RETRIES {
+ encoder_busy_count += 1;
+ break;
+ }
+ std::thread::sleep(Duration::from_micros(500));
+ }
+ Err(e) => {
+ warn!("Failed to encode audio frame: {e}");
+ break;
+ }
+ }
+ }
+
+ total_frames += 1;
+ }
+ }
+ }
+
+ if total_frames > 0 {
+ debug!(
+ total_frames,
+ encoder_busy_count, "MP4 audio encoder summary"
+ );
+ }
+
+ Ok(())
+ })?;
+
+ audio_ready_rx
+ .recv()
+ .map_err(|_| anyhow!("MP4 audio encoder thread ended unexpectedly"))??;
+
+ (Some(audio_tx), Some(audio_handle))
+ } else {
+ (None, None)
+ };
+
+ info!(
+ path = %output_path.display(),
+ "Started non-blocking MP4 encoder"
+ );
+
+ Ok(Self {
+ state: Some(Mp4EncoderState {
+ video_tx,
+ audio_tx,
+ encoder,
+ encoder_handle: Some(encoder_handle),
+ audio_handle,
+ }),
pause_flag,
- ))
+ frame_drops: FrameDropTracker::new(),
+ was_paused: false,
+ })
+ }
+
+ fn stop(&mut self) {
+ if let Some(state) = &self.state {
+ if let Err(e) = state.video_tx.send(None) {
+ trace!("MP4 encoder video channel already closed during stop: {e}");
+ }
+ if let Some(audio_tx) = &state.audio_tx {
+ if let Err(e) = audio_tx.send(None) {
+ trace!("MP4 encoder audio channel already closed during stop: {e}");
+ }
+ }
+ }
}
fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
- Ok(self
- .0
- .lock()
- .map_err(|e| anyhow!("{e}"))?
- .finish(Some(timestamp))
- .map(Ok)?)
+ if let Some(mut state) = self.state.take() {
+ if let Err(e) = state.video_tx.send(None) {
+ trace!("MP4 encoder video channel already closed during finish: {e}");
+ }
+ if let Some(audio_tx) = &state.audio_tx {
+ if let Err(e) = audio_tx.send(None) {
+ trace!("MP4 encoder audio 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() {
+ match handle.join() {
+ Err(panic_payload) => {
+ warn!("MP4 encoder thread panicked: {:?}", panic_payload);
+ }
+ Ok(Err(e)) => {
+ warn!("MP4 encoder thread returned error: {e}");
+ }
+ Ok(Ok(())) => {}
+ }
+ break;
+ }
+ if start.elapsed() > timeout {
+ warn!("MP4 encoder thread did not finish within {:?}", timeout);
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ }
+
+ if let Some(handle) = state.audio_handle.take() {
+ let timeout = Duration::from_secs(2);
+ let start = std::time::Instant::now();
+ loop {
+ if handle.is_finished() {
+ let _ = handle.join();
+ break;
+ }
+ if start.elapsed() > timeout {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ }
+
+ match state.encoder.lock() {
+ Ok(mut encoder) => {
+ if let Err(e) = encoder.finish(Some(timestamp)) {
+ warn!("Failed to finish MP4 encoder: {e}");
+ }
+ }
+ Err(_) => {
+ error!("MP4 encoder mutex poisoned during finish");
+ return Ok(Err(anyhow!("MP4 encoder mutex poisoned")));
+ }
+ }
+ }
+
+ Ok(Ok(()))
}
}
@@ -89,30 +420,35 @@ impl VideoMuxer for AVFoundationMp4Muxer {
frame: Self::VideoFrame,
timestamp: Duration,
) -> anyhow::Result<()> {
- let mut mp4 = self.0.lock().map_err(|e| anyhow!("MuxerLock/{e}"))?;
+ let is_paused = self.pause_flag.load(std::sync::atomic::Ordering::Relaxed);
+
+ if let Some(state) = &self.state {
+ if is_paused && !self.was_paused {
+ let _ = state.video_tx.try_send(Some(VideoFrameMessage::Pause));
+ self.was_paused = true;
+ return Ok(());
+ } else if !is_paused && self.was_paused {
+ let _ = state.video_tx.try_send(Some(VideoFrameMessage::Resume));
+ self.was_paused = false;
+ }
- if self.1.load(std::sync::atomic::Ordering::Relaxed) {
- mp4.pause();
- } else {
- mp4.resume();
- }
+ if is_paused {
+ return Ok(());
+ }
- let mut retry_count = 0;
- loop {
- match mp4.queue_video_frame(frame.sample_buf.clone(), timestamp) {
- Ok(()) => break,
- Err(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;
+ match state
+ .video_tx
+ .try_send(Some(VideoFrameMessage::Frame(frame.sample_buf, timestamp)))
+ {
+ Ok(()) => {
+ self.frame_drops.record_frame();
+ }
+ Err(std::sync::mpsc::TrySendError::Full(_)) => {
+ self.frame_drops.record_drop();
+ }
+ Err(std::sync::mpsc::TrySendError::Disconnected(_)) => {
+ trace!("MP4 encoder video channel disconnected");
}
- Err(e) => return Err(anyhow!("send_video_frame/{e}")),
}
}
@@ -122,16 +458,27 @@ impl VideoMuxer for AVFoundationMp4Muxer {
impl AudioMuxer for AVFoundationMp4Muxer {
fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {
- let mut mp4 = self.0.lock().map_err(|e| anyhow!("{e}"))?;
-
- loop {
- match mp4.queue_audio_frame(&frame.inner, timestamp) {
- Ok(()) => break,
- Err(QueueFrameError::NotReadyForMore) => {
- std::thread::sleep(Duration::from_millis(2));
- continue;
+ if let Some(state) = &self.state {
+ if let Some(audio_tx) = &state.audio_tx {
+ let owned_frame = {
+ let mut new_frame = ffmpeg::frame::Audio::new(
+ frame.inner.format(),
+ frame.inner.samples(),
+ frame.inner.channel_layout(),
+ );
+ new_frame.clone_from(&frame.inner);
+ new_frame
+ };
+
+ match audio_tx.try_send(Some(AudioFrameMessage::Frame(owned_frame, timestamp))) {
+ Ok(()) => {}
+ Err(std::sync::mpsc::TrySendError::Full(_)) => {
+ trace!("MP4 audio encoder buffer full, dropping frame");
+ }
+ Err(std::sync::mpsc::TrySendError::Disconnected(_)) => {
+ trace!("MP4 audio encoder channel disconnected");
+ }
}
- Err(e) => return Err(anyhow!("send_audio_frame/{e}")),
}
}
@@ -139,14 +486,23 @@ impl AudioMuxer for AVFoundationMp4Muxer {
}
}
-#[derive(Clone)]
-pub struct AVFoundationCameraMuxer(
- Arc<Mutex<cap_enc_avfoundation::MP4Encoder>>,
- Arc<AtomicBool>,
-);
+enum CameraFrameMessage {
+ Frame(arc::R<cidre::cm::SampleBuf>, Duration),
+ Pause,
+ Resume,
+}
+
+struct CameraEncoderState {
+ video_tx: SyncSender<Option<CameraFrameMessage>>,
+ encoder: Arc<Mutex<cap_enc_avfoundation::MP4Encoder>>,
+ encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,
+}
-impl AVFoundationCameraMuxer {
- const MAX_QUEUE_RETRIES: u32 = 1500;
+pub struct AVFoundationCameraMuxer {
+ state: Option<CameraEncoderState>,
+ pause_flag: Arc<AtomicBool>,
+ frame_drops: FrameDropTracker,
+ was_paused: bool,
}
#[derive(Default)]
@@ -161,34 +517,181 @@ impl Muxer for AVFoundationCameraMuxer {
config: Self::Config,
output_path: PathBuf,
video_config: Option<VideoInfo>,
- audio_config: Option<AudioInfo>,
+ _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(
- Arc::new(Mutex::new(
- cap_enc_avfoundation::MP4Encoder::init(
- output_path,
- video_config,
- audio_config,
- config.output_height,
- )
- .map_err(|e| anyhow!("{e}"))?,
- )),
+ let buffer_size = get_mp4_muxer_buffer_size();
+ debug!(buffer_size, "Camera MP4 muxer encoder channel buffer size");
+
+ let (video_tx, video_rx) = sync_channel::<Option<CameraFrameMessage>>(buffer_size);
+ let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);
+
+ let encoder = cap_enc_avfoundation::MP4Encoder::init(
+ output_path.clone(),
+ video_config,
+ None,
+ config.output_height,
+ )
+ .map_err(|e| anyhow!("{e}"))?;
+
+ let encoder = Arc::new(Mutex::new(encoder));
+ let encoder_clone = encoder.clone();
+
+ let encoder_handle = std::thread::Builder::new()
+ .name("mp4-camera-encoder".to_string())
+ .spawn(move || {
+ if ready_tx.send(Ok(())).is_err() {
+ return Err(anyhow!("Failed to send ready signal - receiver dropped"));
+ }
+
+ let mut total_frames = 0u64;
+ let mut encoder_busy_count = 0u64;
+
+ while let Ok(Some(msg)) = video_rx.recv() {
+ match msg {
+ CameraFrameMessage::Frame(sample_buf, timestamp) => {
+ let mut encoder = match encoder_clone.lock() {
+ Ok(e) => e,
+ Err(_) => {
+ error!("Camera MP4 encoder mutex poisoned");
+ return Err(anyhow!("Camera MP4 encoder mutex poisoned"));
+ }
+ };
+
+ let mut retry_count = 0;
+ const MAX_RETRIES: u32 = 100;
+
+ loop {
+ match encoder.queue_video_frame(sample_buf.clone(), timestamp) {
+ Ok(()) => break,
+ Err(QueueFrameError::NotReadyForMore) => {
+ retry_count += 1;
+ if retry_count >= MAX_RETRIES {
+ encoder_busy_count += 1;
+ if encoder_busy_count <= 5 || encoder_busy_count.is_multiple_of(100) {
+ debug!(
+ encoder_busy_count,
+ "Camera MP4 encoder busy, frame queued after max retries"
+ );
+ }
+ break;
+ }
+ std::thread::sleep(Duration::from_micros(500));
+ }
+ Err(e) => {
+ warn!("Failed to encode camera frame: {e}");
+ break;
+ }
+ }
+ }
+
+ total_frames += 1;
+ }
+ CameraFrameMessage::Pause => {
+ if let Ok(mut encoder) = encoder_clone.lock() {
+ encoder.pause();
+ }
+ }
+ CameraFrameMessage::Resume => {
+ if let Ok(mut encoder) = encoder_clone.lock() {
+ encoder.resume();
+ }
+ }
+ }
+ }
+
+ if total_frames > 0 {
+ debug!(
+ total_frames,
+ encoder_busy_count,
+ busy_pct = format!("{:.1}%", 100.0 * encoder_busy_count as f64 / total_frames as f64),
+ "Camera MP4 encoder timing summary"
+ );
+ }
+
+ Ok(())
+ })?;
+
+ ready_rx
+ .recv()
+ .map_err(|_| anyhow!("Camera MP4 encoder thread ended unexpectedly"))??;
+
+ info!(
+ path = %output_path.display(),
+ "Started non-blocking camera MP4 encoder"
+ );
+
+ Ok(Self {
+ state: Some(CameraEncoderState {
+ video_tx,
+ encoder,
+ encoder_handle: Some(encoder_handle),
+ }),
pause_flag,
- ))
+ frame_drops: FrameDropTracker::new(),
+ was_paused: false,
+ })
+ }
+
+ fn stop(&mut self) {
+ if let Some(state) = &self.state {
+ if let Err(e) = state.video_tx.send(None) {
+ trace!("Camera MP4 encoder channel already closed during stop: {e}");
+ }
+ }
}
fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
- Ok(self
- .0
- .lock()
- .map_err(|e| anyhow!("{e}"))?
- .finish(Some(timestamp))
- .map(Ok)?)
+ if let Some(mut state) = self.state.take() {
+ if let Err(e) = state.video_tx.send(None) {
+ trace!("Camera MP4 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() {
+ match handle.join() {
+ Err(panic_payload) => {
+ warn!("Camera MP4 encoder thread panicked: {:?}", panic_payload);
+ }
+ Ok(Err(e)) => {
+ warn!("Camera MP4 encoder thread returned error: {e}");
+ }
+ Ok(Ok(())) => {}
+ }
+ break;
+ }
+ if start.elapsed() > timeout {
+ warn!(
+ "Camera MP4 encoder thread did not finish within {:?}",
+ timeout
+ );
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ }
+
+ match state.encoder.lock() {
+ Ok(mut encoder) => {
+ if let Err(e) = encoder.finish(Some(timestamp)) {
+ warn!("Failed to finish camera MP4 encoder: {e}");
+ }
+ }
+ Err(_) => {
+ error!("Camera MP4 encoder mutex poisoned during finish");
+ return Ok(Err(anyhow!("Camera MP4 encoder mutex poisoned")));
+ }
+ }
+ }
+
+ Ok(Ok(()))
}
}
@@ -200,30 +703,35 @@ impl VideoMuxer for AVFoundationCameraMuxer {
frame: Self::VideoFrame,
timestamp: Duration,
) -> anyhow::Result<()> {
- let mut mp4 = self.0.lock().map_err(|e| anyhow!("MuxerLock/{e}"))?;
+ let is_paused = self.pause_flag.load(std::sync::atomic::Ordering::Relaxed);
+
+ if let Some(state) = &self.state {
+ if is_paused && !self.was_paused {
+ let _ = state.video_tx.try_send(Some(CameraFrameMessage::Pause));
+ self.was_paused = true;
+ return Ok(());
+ } else if !is_paused && self.was_paused {
+ let _ = state.video_tx.try_send(Some(CameraFrameMessage::Resume));
+ self.was_paused = false;
+ }
- if self.1.load(std::sync::atomic::Ordering::Relaxed) {
- mp4.pause();
- } else {
- mp4.resume();
- }
+ if is_paused {
+ return Ok(());
+ }
- let mut retry_count = 0;
- loop {
- match mp4.queue_video_frame(frame.sample_buf.clone(), timestamp) {
- Ok(()) => break,
- Err(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;
+ match state
+ .video_tx
+ .try_send(Some(CameraFrameMessage::Frame(frame.sample_buf, timestamp)))
+ {
+ Ok(()) => {
+ self.frame_drops.record_frame();
+ }
+ Err(std::sync::mpsc::TrySendError::Full(_)) => {
+ self.frame_drops.record_drop();
+ }
+ Err(std::sync::mpsc::TrySendError::Disconnected(_)) => {
+ trace!("Camera MP4 encoder channel disconnected");
}
- Err(e) => return Err(anyhow!("send_video_frame/{e}")),
}
}
@@ -232,20 +740,7 @@ impl VideoMuxer for AVFoundationCameraMuxer {
}
impl AudioMuxer for AVFoundationCameraMuxer {
- fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {
- let mut mp4 = self.0.lock().map_err(|e| anyhow!("{e}"))?;
-
- loop {
- match mp4.queue_audio_frame(&frame.inner, timestamp) {
- Ok(()) => break,
- Err(QueueFrameError::NotReadyForMore) => {
- std::thread::sleep(Duration::from_millis(2));
- continue;
- }
- Err(e) => return Err(anyhow!("send_audio_frame/{e}")),
- }
- }
-
+ fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {
Ok(())
}
}